Du concret. Des démos en direct.
Choisissez un exemple pour l'ouvrir en plein écran : l'aperçu en direct et son code source, côte à côte.
Choisissez un exemple pour l'ouvrir en plein écran : l'aperçu en direct et son code source, côte à côte.
Un chat à trois canaux, et chaque canal est un simple objet : historique, curseur, indicateur de saisie, brouillon et position de défilement. Changer de canal retrouve donc chacun exactement dans l'état où on l'a laissé, et update("chat-sidebar") ne rafraîchit que les badges de messages non lus. En remontant, l'historique se charge sans fin : unshift() insère les anciens messages et scrollTop augmente d'autant, sans à-coup. Votre message s'affiche avant que le serveur ne l'ait reçu, send() retouche le même objet, et Retry, Edit, Delete et les réactions ne reconstruisent jamais sa ligne. Les messages gèrent le code, le gras, les liens et les @mentions.
Loading older messages…
// app.ts: the chat. Async is plain async/await: change the state, update(), // await, change it again, update(). History loads upward forever: a sentinel // above the oldest message asks for the page before it, the page goes in with // unshift(), and scrollTop grows by the height it added, so nothing on screen // moves. Your message shows before the server has it; when send() settles, // the same object becomes sent, or failed with a Retry, and its row stays. // Everything a channel is lives in one plain object, so switching channels // swaps which object the same log, head and composer read — and the sidebar // refreshes its badges with update("chat-sidebar") while the rest sleeps. import "nuclo"; import { CHANNELS, connect, fetchHistory, ME, send, type ChannelEvent, type ChannelInfo, type Message } from "./server.ts"; import { s } from "./styles.ts"; const GROUP = 5 * 60_000; // ms: one author's messages this close together share a header const NEAR = 60; // px from the bottom that still counts as "at the bottom" const EMOJIS = ["👍", "👏", "🚀", "❤️", "😂", "🎉", "💡", "🔥"]; interface Reaction { emoji: string; count: number; mine: boolean; } // A message on screen: the server's fields, how far it got, and how it joins the one above. interface Msg extends Message { status: "sent" | "sending" | "failed"; first: boolean; // starts a group: shows the avatar and the name day: string; // the day line above it, or "" fresh: boolean; // arrived live: the pop animation plays once edited: boolean; editing: boolean; // the inline editor is open copied: boolean; reactions: Reaction[]; } interface Channel { info: ChannelInfo; messages: Msg[]; before: number | undefined; // the id of the oldest message loaded: the next page ends there loading: boolean; error: string | null; atStart: boolean; // the channel has nothing older online: number; typing: Set<string>; unseen: number; // messages that arrived while the reader was scrolled up firstUnseen: Msg | null; // where the "New messages" divider sits unread: number; // messages that arrived while another channel was open draft: string; atBottom: boolean; // where the reader was when they left scrollTop: number; } const channels: Channel[] = CHANNELS.map((info) => ({ info, messages: [], before: undefined, loading: false, error: null, atStart: false, online: 0, typing: new Set(), unseen: 0, firstUnseen: null, unread: 0, draft: "", atBottom: true, scrollTop: 0, })); let active = channels[0]; let scroller: HTMLElement | null = null; let composerEl: HTMLTextAreaElement | null = null; let composerFocused = false; let menu = false; // the phone drawer let picker: Msg | null = null; // the message whose reaction picker is open let composerPicker = false; let lookAgain: (() => void) | null = null; // set by the mounted sentinel: checks again whether it is in view const toMsg = (m: Message, fresh = false): Msg => { const msg: Msg = { ...m, status: "sent", first: true, day: "", fresh, edited: false, editing: false, copied: false, reactions: [] }; if (fresh) setTimeout(() => { msg.fresh = false; }, 1200); return msg; }; const clock = (t: number) => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); const fullTime = (t: number) => new Date(t).toLocaleString([], { dateStyle: "long", timeStyle: "medium" }); const dayOf = (t: number) => { const d = new Date(t); const today = new Date(); const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); if (d.toDateString() === today.toDateString()) return "Today"; if (d.toDateString() === yesterday.toDateString()) return "Yesterday"; return d.toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" }); }; const hue = (name: string) => [...name].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 360, 0); // What messages[i] shows depends on the message above it: a day line when the // day changes, the author's header when a new group starts. function link(ch: Channel, i: number) { const m = ch.messages[i]; const prev = ch.messages[i - 1]; const day = dayOf(m.at); m.day = prev && dayOf(prev.at) === day ? "" : day; m.first = m.day !== "" || prev.author !== m.author || m.at - prev.at > GROUP; } function push(ch: Channel, m: Msg) { ch.messages.push(m); link(ch, ch.messages.length - 1); } const nearBottom = () => !scroller || scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < NEAR; const toBottom = (behavior: ScrollBehavior = "auto") => scroller?.scrollTo({ top: scroller.scrollHeight, behavior }); async function loadOlder() { const ch = active; if (ch.loading || ch.error !== null || ch.atStart) return; ch.loading = true; update(); try { const page = await fetchHistory(ch.info.id, ch.before); if (page.length === 0) ch.atStart = true; else { ch.before = page[0].id; ch.messages.unshift(...page.map((m) => toMsg(m))); for (let i = 0; i <= page.length && i < ch.messages.length; i++) link(ch, i); // the old top message may join the page's last group } } catch (e) { ch.error = (e as Error).message; } ch.loading = false; // The page lands above what the reader is looking at: measure, update(), and // scroll down by the height it added. On the first page, that is the bottom. // A channel left mid-flight keeps its page, but the visible log is untouched. const height = ch === active ? scroller?.scrollHeight ?? 0 : 0; update(); if (ch === active && scroller) { scroller.scrollTop += scroller.scrollHeight - height; lookAgain?.(); // a short page can leave the sentinel in view: then load the next one too } } // The row of a message, for the scroll arithmetic that keeps the view stable. const rowOf = (m: Msg) => scroller?.querySelector(`[data-msg="${m.id}"]`) as HTMLElement | null | undefined; // A row grew or shrank (picker, editor, a reaction): keep the view stable the // same way loadOlder() does — except a reader stuck to the bottom follows it. function relayoutUnder(el: HTMLElement | null | undefined) { if (!el || !scroller) { update("chat-pane"); return; } const stick = nearBottom(); const top = el.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop; const height = scroller.scrollHeight; update("chat-pane"); if (stick) toBottom(); else if (top + el.offsetHeight <= scroller.scrollTop) scroller.scrollTop += scroller.scrollHeight - height; } function receive(e: ChannelEvent) { const ch = channels.find((c) => c.info.id === e.channel); if (!ch) return; if (e.type === "online") { ch.online = e.count; if (ch === active) update(); else update("chat-sidebar"); return; } if (e.type === "typing") { ch.typing.add(e.author); if (ch === active) { const stick = nearBottom(); update("chat-pane"); if (stick) toBottom(); // the typing row appears at the bottom: stay on it } return; } if (e.type === "reaction") { const m = ch.messages.find((x) => x.id === e.messageId); if (!m) return; react(m, e.emoji, false); if (ch === active) relayoutUnder(rowOf(m)); return; } ch.typing.delete(e.message.author); const m = toMsg(e.message, true); push(ch, m); if (ch === active) { const stick = nearBottom(); // read before anything changes if (!stick) { ch.unseen++; ch.firstUnseen ??= m; } update(); if (stick) toBottom(); // a reader at the bottom follows the conversation; the others get the pill } else { ch.unread++; ch.firstUnseen ??= m; update("chat-sidebar"); // only the badge needs to know } } // Optimistic: the message is on screen before the server has it. send() only // changes fields on the same object, so its row is never rebuilt. async function deliver(m: Msg) { const ch = active; m.status = "sending"; update(); try { Object.assign(m, await send(ch.info.id, m.text)); m.status = "sent"; } catch { m.status = "failed"; } update(); } function submit() { const ch = active; const text = ch.draft.trim(); if (!text) return; ch.draft = ""; ch.unseen = 0; ch.firstUnseen = null; const m = toMsg({ id: -1, author: ME, text, at: Date.now() }, true); push(ch, m); deliver(m); toBottom(); // your own message always takes you down } function remove(m: Msg) { const ch = active; const i = ch.messages.indexOf(m); ch.messages.splice(i, 1); if (i < ch.messages.length) link(ch, i); // the next message may now start a group update(); } const typingText = () => { const names = [...active.typing]; return names.length === 0 ? "" : `${names.join(" and ")} ${names.length === 1 ? "is" : "are"} typing…`; }; function markRead() { active.unseen = 0; active.firstUnseen = null; update("chat-pane"); } // ── Reactions: a plain array on each message, rebuilt on every change ── function react(m: Msg, emoji: string, mine: boolean) { const r = m.reactions.find((x) => x.emoji === emoji); if (!r) m.reactions = [...m.reactions, { emoji, count: 1, mine }]; else if (r.mine) { if (mine) return; m.reactions = r.count === 1 ? m.reactions.filter((x) => x !== r) : m.reactions.map((x) => (x === r ? { emoji, count: x.count - 1, mine: false } : x)); } else if (mine) m.reactions = m.reactions.map((x) => (x === r ? { emoji, count: x.count + 1, mine: true } : x)); else m.reactions = m.reactions.map((x) => (x === r ? { emoji, count: x.count + 1, mine: false } : x)); } function toggleReaction(m: Msg, emoji: string) { react(m, emoji, true); picker = null; relayoutUnder(rowOf(m)); } // ── The composer: a scope, so a keystroke only refreshes the composer ── function insertEmoji(emoji: string) { active.draft += emoji; composerPicker = false; update("chat-composer"); composerEl?.focus(); } const lastOwn = () => [...active.messages].reverse().find((m) => m.author === ME && m.status === "sent"); // ── Editing: swap the text for a textarea on the same row, patch on save ── function startEdit(m: Msg) { m.editing = true; relayoutUnder(rowOf(m)); } function cancelEdit(m: Msg) { m.editing = false; relayoutUnder(rowOf(m)); composerEl?.focus(); } function saveEdit(m: Msg, value: string) { const text = value.trim(); if (text && text !== m.text) { m.text = text; m.edited = true; } m.editing = false; relayoutUnder(rowOf(m)); composerEl?.focus(); } async function copy(m: Msg) { try { await navigator.clipboard.writeText(m.text); } catch { // The Clipboard API can be missing in sandboxed frames: fall back to a selection. const ta = document.createElement("textarea"); ta.value = m.text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); } m.copied = true; update("chat-pane"); setTimeout(() => { m.copied = false; update("chat-pane"); }, 1200); } // ── Markdown-lite: bold, italic, inline code, links and @mentions. The text // is parsed once per message, and the segments are a nested list(), so an edit // replaces them without touching the row. type Seg = | { k: "text"; text: string } | { k: "bold"; text: string } | { k: "ital"; text: string } | { k: "code"; text: string } | { k: "link"; text: string; href: string } | { k: "mention"; text: string; me: boolean }; const TOKEN = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(\*[^*\n]+\*)|(@[a-z-]+)|(https?:\/\/\S+)/gi; function parseSegments(text: string): Seg[] { const out: Seg[] = []; let last = 0; for (const match of text.matchAll(TOKEN)) { const i = match.index ?? 0; if (i > last) out.push({ k: "text", text: text.slice(last, i) }); const [full, code, bold, ital, mention, link] = match; if (code) out.push({ k: "code", text: code.slice(1, -1) }); else if (bold) out.push({ k: "bold", text: bold.slice(2, -2) }); else if (ital) out.push({ k: "ital", text: ital.slice(1, -1) }); else if (mention) out.push({ k: "mention", text: full, me: full === "@you" }); else if (link) { const href = link.replace(/[.,;:!?]+$/, ""); out.push({ k: "link", text: href, href }); } last = i + full.length; } if (last < text.length) out.push({ k: "text", text: text.slice(last) }); return out; } const segCache = new WeakMap<Msg, { text: string; segs: Seg[] }>(); function segs(m: Msg): Seg[] { const hit = segCache.get(m); if (hit && hit.text === m.text) return hit.segs; const next = { text: m.text, segs: parseSegments(m.text) }; segCache.set(m, next); return next.segs; } function SegView(g: Seg) { if (g.k === "code") return span(s.code, g.text); if (g.k === "bold") return span({ style: { fontWeight: "700" } }, g.text); if (g.k === "ital") return span({ style: { fontStyle: "italic" } }, g.text); if (g.k === "link") return a({ href: g.href, target: "_blank", rel: "noopener" }, s.link, g.text); if (g.k === "mention") return span(g.me ? s.mentionMe : s.mention, g.text); return span(g.text); } // ── The pieces ── function ReactionChip(m: Msg, r: Reaction) { return button( { type: "button", class: () => cx(s.reaction, r.mine ? s.reactionMine : null).className, title: () => `${r.emoji} — ${r.count}`, "aria-label": `${r.emoji}: ${r.count} reaction${r.count === 1 ? "" : "s"}${r.mine ? ", yours" : ""}`, onClick: () => { react(m, r.emoji, !r.mine); // yours leaves, theirs joins relayoutUnder(rowOf(m)); }, }, span(r.emoji), span(s.reactionCount, () => String(r.count)), ); } function MessageRow(m: Msg) { return article( s.msg, { "data-msg": () => String(m.id), // reactive: the optimistic -1 becomes the server id when send() settles class: () => cx(s.msg, m.first ? s.first : null, m.status === "sent" ? null : m.status === "sending" ? s.sending : s.failed, m.fresh ? s.live : null, m.text.includes("@you") ? s.mentionRow : null).className, }, when(() => m.day !== "", div(s.day, () => m.day)), when(() => active.firstUnseen === m, div(s.divider, span("New messages"), button(s.dividerBtn, { type: "button", onClick: markRead }, "Mark as read"))), when( () => m.first, div(s.avatar, { style: { backgroundColor: `hsl(${hue(m.author)} 55% 48%)` }, title: m.author }, m.author[0].toUpperCase()), div(s.meta, strong(m.author), time({ title: fullTime(m.at) }, clock(m.at)), when(() => m.edited, span(s.edited, "(edited)"))), ), when( () => m.editing, textarea(s.edit, { "aria-label": "Edit message", value: m.text }, { onKeyDown: (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); saveEdit(m, e.currentTarget.value); } else if (e.key === "Escape") cancelEdit(m); }, }, on("mount", (el) => { el.focus(); el.setSelectionRange(el.value.length, el.value.length); })), ), when(() => !m.editing, p(s.text, list(() => segs(m), SegView))), when(() => m.reactions.length > 0, div(s.reactions, list(() => m.reactions, (r) => ReactionChip(m, r)))), when( () => picker === m, div(s.picker, ...EMOJIS.map((emoji) => button(s.pick, { type: "button", title: emoji, "aria-label": `React with ${emoji}`, onClick: () => toggleReaction(m, emoji) }, emoji))), ), when( () => m.status === "sent" && !m.editing, div(s.actions, { "data-chat-actions": "" }, button(s.action, { type: "button", title: "Add a reaction", "aria-label": "Add a reaction", onClick: () => { picker = picker === m ? null : m; relayoutUnder(rowOf(m)); } }, "😊"), button(s.action, { type: "button", "aria-label": "Copy message", onClick: () => copy(m) }, () => (m.copied ? "✓ Copied" : "Copy")), when( () => m.author === ME, button(s.action, { type: "button", "aria-label": "Edit message", onClick: () => startEdit(m) }, "Edit"), button(s.action, { type: "button", "aria-label": "Delete message", onClick: () => remove(m) }, "Delete"), ), ), ), when( () => m.status === "failed", div(s.retry, "Not sent.", button(s.small, { type: "button", onClick: () => deliver(m) }, "Retry"), button(s.small, { type: "button", onClick: () => remove(m) }, "Delete")), ), ); } // The row above the oldest message: it asks for the page before it while it // is still well out of view, and says how that went. function Sentinel() { return div( s.top, on("mount", (el) => { const observer = new IntersectionObserver( ([entry]) => { if (entry.isIntersecting) loadOlder(); }, { root: el.parentElement, rootMargin: "800px" }, ); observer.observe(el); lookAgain = () => { observer.unobserve(el); observer.observe(el); }; return () => { observer.disconnect(); lookAgain = null; }; // left set, it would keep this element alive }), when(() => active.error !== null, div(s.error, span(() => active.error ?? ""), button(s.btn, { type: "button", onClick: () => { active.error = null; loadOlder(); } }, "Retry"))) .when(() => active.atStart, p(s.beginning, () => `This is the beginning of ${active.info.name}.`)) .else(p(s.loading, "Loading older messages…")), ); } // A channel row: the badge is the only thing an inactive channel updates. function Sidebar() { return nav( s.sidebar, scope("chat-sidebar"), { "data-chat-sidebar": "", class: () => cx(s.sidebar, menu ? null : s.sidebarClosed).className }, div(s.brand, div(s.logo, "◆"), "nuclo chat"), div(s.sideLabel, "Channels"), list(() => channels, (ch) => button( { type: "button", class: () => cx(s.channel, ch === active ? s.channelOn : null).className, "aria-current": () => String(ch === active), title: ch.info.topic, onClick: () => openChannel(ch), }, span(s.hash, "#"), span(s.channelName, () => ch.info.name.slice(2)), when(() => ch.unread > 0, span(s.badge, () => (ch.unread > 99 ? "99+" : String(ch.unread)))), )), div(s.sideFoot, div(s.you, div(s.youAvatar, "y"), div(s.youMeta, span(s.youName, "you"), span(s.youSub, () => `${channels.length} channels · ${channels.reduce((n, c) => n + c.online, 0)} people online`), ), ), ), ); } // Switching channels keeps the one you leave, exactly as it was. function openChannel(ch: Channel) { if (ch === active) { menu = false; update(); return; } active.atBottom = nearBottom(); active.scrollTop = scroller?.scrollTop ?? 0; active = ch; menu = false; picker = null; composerPicker = false; const away = ch.unread; // what arrived while this channel was closed ch.unread = 0; // Clicking the channel button blurs the composer: on a pointer-fine device, // put the cursor back so the reader can keep typing. On touch, leave it — // focusing would pop the keyboard over the conversation. const focusComposer = composerFocused || (document.activeElement instanceof HTMLElement && document.activeElement.getAttribute("aria-current") !== null); const pointerFine = matchMedia("(hover: hover)").matches; update(); if (scroller) { if (ch.atBottom) { toBottom(); ch.unseen = 0; ch.firstUnseen = null; } else { scroller.scrollTop = ch.scrollTop; ch.unseen += away; // what arrived while away joins what was already unread if (nearBottom()) { ch.unseen = 0; ch.firstUnseen = null; } } } if (focusComposer && pointerFine) composerEl?.focus(); lookAgain?.(); // the sentinel may be in view again: load the next page } export function ChatApp() { return div( s.app, on("mount", () => { const disconnect = connect(receive); loadOlder(); return () => { disconnect(); channels.forEach((ch) => { ch.typing.clear(); ch.unseen = 0; ch.firstUnseen = null; }); }; }), Sidebar(), when(() => menu, div(s.backdrop, { onClick: () => { menu = false; update(); } })), div( s.main, header( s.head, button(s.menuBtn, { type: "button", "aria-label": "Channels", "aria-expanded": () => String(menu), onClick: () => { menu = !menu; update(); } }, "☰"), div(s.headMain, strong(() => active.info.name), span(s.topic, () => active.info.topic)), span(s.online, () => (active.online ? `${active.online} online` : "connecting…")), span(s.state, () => `${active.messages.length} messages in the DOM · ${active.loading ? "loading history…" : active.atStart ? "all of it" : "scroll up for more"}`), ), div( s.pane, scope("chat-pane"), div( s.log, on("mount", (el) => { scroller = el; toBottom(); // opened again: the messages are still here, show the newest return () => { scroller = null; }; }), { onScroll: () => { if (active.unseen > 0 && nearBottom()) { active.unseen = 0; active.firstUnseen = null; update("chat-pane"); } } }, Sentinel(), list(() => active.messages, MessageRow), when(() => active.typing.size > 0, div(s.typingRow, { "aria-live": "polite" }, span(s.dots, i(), i(), i()), span(() => typingText()))), ), when( () => active.unseen > 0, button(s.pill, () => `${active.unseen} new message${active.unseen === 1 ? "" : "s"} ↓`, { onClick: () => { markRead(); toBottom("smooth"); } }), ), ), div( s.composerArea, scope("chat-composer"), // one scope for the picker and the form: a keystroke or an emoji click refreshes only this when( () => composerPicker, div(s.composerPicker, ...EMOJIS.map((emoji) => button(s.pick, { type: "button", title: emoji, "aria-label": `Add ${emoji}`, onClick: () => insertEmoji(emoji) }, emoji))), ), form( s.composer, { onSubmit: (e) => { e.preventDefault(); submit(); } }, textarea(s.input, { rows: 1, placeholder: () => `Message ${active.info.name}`, "aria-label": "Message", value: () => active.draft }, { onInput: (e) => { active.draft = e.currentTarget.value; update("chat-composer"); }, // a keystroke only refreshes the composer onKeyDown: (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); submit(); } else if (e.key === "ArrowUp" && active.draft === "" && e.currentTarget.selectionStart === 0) { const last = lastOwn(); if (last) { e.preventDefault(); startEdit(last); } // ↑ edits your last message } }, onFocus: () => { composerFocused = true; }, onBlur: () => { composerFocused = false; }, }, on("mount", (el) => { composerEl = el; el.focus(); return () => { composerEl = null; }; })), button(s.emojiBtn, { type: "button", title: "Add an emoji", "aria-label": "Add an emoji", onClick: () => { composerPicker = !composerPicker; update("chat-composer"); } }, "😊"), button(s.send, { type: "submit", disabled: () => !active.draft.trim() }, "Send"), ), ), ), ); }
// server.ts: a fake multi-channel chat backend and its socket. Each channel's // history is generated from its message ids, so the same cursor always returns // the same page. Requests take a moment, and sending sometimes fails. The // socket brings what other people post — per channel — after showing that they // are typing; a bot answers what you send, and once in a while someone reacts // to a message. Nothing here knows about the UI. export interface Message { id: number; author: string; text: string; at: number; // ms since the epoch } export interface ChannelInfo { id: string; name: string; // "# general" topic: string; } export type ChannelEvent = | { type: "typing"; channel: string; author: string } | { type: "message"; channel: string; message: Message } | { type: "reaction"; channel: string; messageId: number; emoji: string } | { type: "online"; channel: string; count: number }; export const ME = "you"; const BOT = "nuclo-bot"; const PAGE = 30; const GAP = 4 * 60_000; // ms between two history messages, on average // Each channel: how much history it has, and a salt so its archive differs. export const CHANNELS: ChannelInfo[] = [ { id: "general", name: "# general", topic: "The build, the demos and everything in between" }, { id: "random", name: "# random", topic: "Off-topic: lunch, keyboards, compilers" }, { id: "nuclo", name: "# nuclo", topic: "One update() call at a time" }, ]; const SIZE: Record<string, number> = { general: 5000, random: 3000, nuclo: 2000 }; const SALT: Record<string, number> = { general: 1, random: 2, nuclo: 3 }; const AUTHORS = ["Ada", "Grace", "Linus", "Margaret", "Dennis", "Barbara", "Ken", "Radia"]; const SHORT = ["+1", "lgtm", "nice!", "on it", "ha, same", "thanks!", "which branch?", "merged", "brb, coffee", "can't reproduce"]; const OPENERS = ["Pushed a fix for", "Reviewed", "Reverted", "Finally fixed", "Still debugging", "Benchmarked", "Rewrote", "Deleted half of", "Paired on", "Wrote tests for"]; const SUBJECTS = ["the list diff", "the router", "the docs build", "hydration", "the style engine", "the flaky test", "the update loop", "the scroll anchoring", "the composer", "the fake socket"]; const ENDINGS = ["today.", "before lunch.", "on main.", "with half the code.", "in one update() call.", "without a store.", "if anyone wants to look.", "for the next release.", "with Ada.", "this morning."]; const REPLIES = ["Noted.", "Agreed.", "Tell me more.", "Filed under #general.", "Everyone saw that after one update()."]; // #nuclo posts are markdown-heavy, so the demo shows code spans, bold, links // and @mentions; #random is short and loud. const MD = [ "**merged** the router after `list()` matched every row by identity.", "`update()` twice, no store: the message showed before the server had it, and Retry just calls `send()` again.", "Pushed a fix for the **hydration** edge case: `scope()` ids are cleaned up now.", "see https://nuclo.dev/en/docs#api-list for how a `list()` reconciles.", "@you have you tried **Shift+Enter** in the composer? `field-sizing` grows it for you.", "Benchmarked the style engine: `css()` compiles once, `cx()` just compares class strings.", "Rewrote the update loop with `queueMicrotask`: every `update()` in one tick coalesces.", "`unshift()` the older page, grow `scrollTop` by the height it added: nothing on screen moves.", "The typing line is `when(() => typing.size > 0, …)`: one update() and it is there.", ]; const RANDOM = [ "lunch was **tacos** 🌮", "brb, coffee ☕", "anyone tried `nuclo@next` yet?", "ship it 🚀", "**weekend** plans: rewrite the router in 300 lines", "🎉 it passed on main", "the demo ate my `localStorage`, nice", "keyboard arrived, typing **+11%** faster", ]; // A small integer hash: every field of a history message is a function of its id. function hash(n: number) { n = Math.imul(n ^ (n >>> 16), 0x45d9f3b); n = Math.imul(n ^ (n >>> 16), 0x45d9f3b); return (n ^ (n >>> 16)) >>> 0; } const pick = <T,>(list: T[], n: number, salt: number) => list[hash(n * 31 + salt) % list.length]; const random = <T,>(list: T[]) => list[Math.floor(Math.random() * list.length)]; const sentence = (ch: ChannelInfo, n: number) => `${pick(OPENERS, n, SALT[ch.id] + 2)} ${pick(SUBJECTS, n, SALT[ch.id] + 3)} ${pick(ENDINGS, n, SALT[ch.id] + 4)}`; // Any number makes a message: a short reply, or one to three sentences. function say(ch: ChannelInfo, n: number) { const h = hash(n * 31 + SALT[ch.id]); if (ch.id === "nuclo") return h % 4 === 0 ? pick(SHORT, n, SALT[ch.id]) : pick(MD, n, SALT[ch.id] + 7); if (ch.id === "random") return h % 3 === 0 ? pick(SHORT, n, SALT[ch.id]) : pick(RANDOM, n, SALT[ch.id] + 7); if (h % 4 === 0) return pick(SHORT, n, SALT[ch.id]); return Array.from({ length: 1 + ((h % 7) % 3) }, (_, i) => sentence(ch, n * 3 + i)).join(" "); } const opened = Date.now(); // the history ends when this module loads; everything after arrives live function archived(ch: ChannelInfo, id: number): Message { // Messages come in bursts: most of a block of four share an author. const author = pick(AUTHORS, hash(id * 7 + SALT[ch.id]) % 5 === 0 ? id : id >> 2, 5); // Each message gets a slot GAP wide and a random spot in it, so time only moves forward. return { id, author, text: say(ch, id), at: opened - (SIZE[ch.id] - id) * GAP + (hash(id + SALT[ch.id]) % GAP) }; } /** The messages before `before` (the id of the oldest one you have), oldest first. Empty at the beginning of the channel. */ export function fetchHistory(channelId: string, before = SIZE[channelId]): Promise<Message[]> { const ch = CHANNELS.find((c) => c.id === channelId) ?? CHANNELS[0]; return new Promise((resolve) => { setTimeout(() => { const from = Math.max(0, before - PAGE); resolve(Array.from({ length: before - from }, (_, i) => archived(ch, from + i))); }, 300 + Math.random() * 400); }); } const EMOJIS = ["👍", "🚀", "😂", "❤️", "🔥"]; const nextId: Record<string, number> = { general: 5000, random: 3000, nuclo: 2000 }; const online: Record<string, number> = { general: 9, random: 5, nuclo: 4 }; let listener: ((e: ChannelEvent) => void) | null = null; const timers = new Set<ReturnType<typeof setTimeout>>(); const emit = (e: ChannelEvent) => listener?.(e); const stamp = (channelId: string, author: string, text: string): Message => ({ id: nextId[channelId]++, author, text, at: Date.now() }); // A timer the socket owns: disconnecting clears every one still pending. function later(ms: number, fn: () => void) { const timer = setTimeout(() => { timers.delete(timer); fn(); }, ms); timers.add(timer); } function typeThenPost(ch: ChannelInfo, author: string, text: string, ms: number) { emit({ type: "typing", channel: ch.id, author }); later(ms, () => { const message = stamp(ch.id, author, text); emit({ type: "message", channel: ch.id, message }); if (Math.random() < 0.3) { later(900 + Math.random() * 1500, () => emit({ type: "reaction", channel: ch.id, messageId: message.id, emoji: random(EMOJIS) })); } }); } // Other people, now and then: someone types and posts, someone comes or goes. function chatter(ch: ChannelInfo) { if (Math.random() < 0.3) { online[ch.id] = Math.max(2, online[ch.id] + (Math.random() < 0.5 ? -1 : 1)); emit({ type: "online", channel: ch.id, count: online[ch.id] }); } typeThenPost(ch, random(AUTHORS), say(ch, Math.floor(Math.random() * 1e9)), 1500 + Math.random() * 2500); later(5000 + Math.random() * 7000, () => chatter(ch)); } /** Stores your message. It takes a moment and fails about one time in seven; then the bot answers and someone may react. */ export function send(channelId: string, text: string): Promise<Message> { return new Promise((resolve, reject) => { setTimeout(() => { if (Math.random() < 0.15) return reject(new Error("Not delivered.")); const message = stamp(channelId, ME, text); resolve(message); const quote = text.length > 48 ? `${text.slice(0, 48)}…` : text; later(600, () => typeThenPost(CHANNELS.find((c) => c.id === channelId) ?? CHANNELS[0], BOT, `“${quote}”: ${random(REPLIES)}`, 1200)); if (Math.random() < 0.7) { later(1500 + Math.random() * 1800, () => emit({ type: "reaction", channel: channelId, messageId: message.id, emoji: random(EMOJIS) })); } }, 400 + Math.random() * 600); }); } /** Opens the socket: `onEvent` hears typing, messages, reactions and the online count of every channel. Returns the disconnect. */ export function connect(onEvent: (e: ChannelEvent) => void) { listener = onEvent; for (const ch of CHANNELS) { emit({ type: "online", channel: ch.id, count: online[ch.id] }); later(1500 + Math.random() * 2500, () => chatter(ch)); } return () => { listener = null; timers.forEach(clearTimeout); timers.clear(); }; }
import "nuclo"; const mono = "ui-monospace, monospace"; const pop = keyframes({ from: { opacity: "0", transform: "translateY(6px)" }, to: { opacity: "1", transform: "none" } }); const pulse = keyframes({ from: { opacity: "0.35" }, to: { opacity: "1" } }); const bounce = keyframes({ "0%, 60%, 100%": { transform: "none" }, "30%": { transform: "translateY(-3px)" } }); const rule = { content: '""', flex: "1", height: "1px", backgroundColor: "var(--c-border)" }; export const s = { app: css("chat-app", { position: "relative", display: "flex", width: "100%", maxWidth: "1060px", height: "100%", margin: "0 auto", borderRadius: "12px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg)", overflow: "hidden" }), // ── The sidebar: channels on the left, an overlay drawer on phones. The // off-screen transform lives on the *closed* class inside the media query, // so opening (which drops the class) always wins the cascade. sidebar: css("chat-sidebar", { display: "flex", flexDirection: "column", width: "224px", flexShrink: 0, padding: "14px 10px", borderRight: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", "@media (max-width: 760px)": { position: "absolute", inset: "0 auto 0 0", zIndex: 30, width: "min(80%, 280px)", transition: "transform 0.22s ease", boxShadow: "0 0 60px var(--c-shadow)" } }), sidebarClosed: css("chat-sidebar-closed", { "@media (max-width: 760px)": { transform: "translateX(-100%)" } }), backdrop: css("chat-backdrop", { display: "none", "@media (max-width: 760px)": { display: "block", position: "absolute", inset: "0", zIndex: 20, backgroundColor: "rgba(0,0,0,0.45)" } }), brand: css("chat-brand", { display: "flex", alignItems: "center", gap: "8px", padding: "2px 8px 12px", fontWeight: "700", fontSize: "0.9375rem" }), logo: css("chat-logo", { display: "flex", alignItems: "center", justifyContent: "center", width: "26px", height: "26px", borderRadius: "8px", backgroundColor: "var(--c-primary-dark)", color: "#fff", fontSize: "0.75rem" }), sideLabel: css("chat-side-label", { padding: "0 8px 6px", fontSize: "0.6875rem", fontWeight: "700", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--c-text-muted)" }), channel: css("chat-channel", { display: "flex", alignItems: "center", gap: "8px", width: "100%", height: "34px", padding: "0 8px", borderRadius: "8px", fontSize: "0.875rem", color: "var(--c-text-dim)", hover: { backgroundColor: "var(--c-bg-secondary)", color: "var(--c-text)" } }), channelOn: css("chat-channel-on", { backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-text)" }), hash: css("chat-hash", { color: "var(--c-text-muted)", fontWeight: "600" }), channelName: css("chat-channel-name", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", textAlign: "left" }), badge: css("chat-badge", { minWidth: "20px", height: "20px", padding: "0 6px", borderRadius: "999px", backgroundColor: "var(--c-primary-dark)", color: "#fff", fontSize: "0.6875rem", fontWeight: "700", lineHeight: "20px", textAlign: "center", animation: `${pop} 0.18s ease-out both` }), sideFoot: css("chat-side-foot", { marginTop: "auto", padding: "12px 8px 2px", borderTop: "1px solid var(--c-border)" }), you: css("chat-you", { display: "flex", alignItems: "center", gap: "10px" }), youAvatar: css("chat-you-avatar", { display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, width: "32px", height: "32px", borderRadius: "9px", backgroundColor: "hsl(24 70% 48%)", color: "#fff", fontWeight: "700", fontSize: "0.8125rem" }), youMeta: css("chat-you-meta", { display: "flex", flexDirection: "column", minWidth: "0" }), youName: css("chat-you-name", { fontSize: "0.875rem", fontWeight: "600", lineHeight: "1.3" }), youSub: css("chat-you-sub", { fontSize: "0.75rem", color: "var(--c-text-muted)", lineHeight: "1.3" }), // ── The main column: header, log, composer ── main: css("chat-main", { display: "flex", flexDirection: "column", flex: "1", minWidth: "0" }), head: css("chat-head", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "4px 12px", padding: "10px 14px", borderBottom: "1px solid var(--c-border)" }), menuBtn: css("chat-menu-btn", { display: "none", alignItems: "center", justifyContent: "center", width: "34px", height: "34px", borderRadius: "8px", color: "var(--c-text-dim)", fontSize: "1rem", hover: { backgroundColor: "var(--c-bg-secondary)", color: "var(--c-text)" }, "@media (max-width: 760px)": { display: "flex" } }), headMain: css("chat-head-main", { display: "flex", flexDirection: "column", minWidth: "0", fontSize: "0.9375rem" }), topic: css("chat-topic", { fontSize: "0.75rem", color: "var(--c-text-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), online: css("chat-online", { display: "inline-flex", alignItems: "center", gap: "6px", fontSize: "0.8125rem", color: "var(--c-text-dim)", before: { content: '""', width: "7px", height: "7px", borderRadius: "50%", backgroundColor: "#22c55e" } }), state: css("chat-state", { marginLeft: "auto", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-muted)", fontVariantNumeric: "tabular-nums" }), pane: css("chat-pane", { position: "relative", display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), // The browser's own scroll anchoring is off: the app anchors by hand, the same in every browser. log: css("chat-log", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0", overflowY: "auto", padding: "8px 6px", raw: { "overflow-anchor": "none" } }), // The auto margin pushes a short history down to the composer, like a chat; once it overflows, it is 0. top: css("chat-top", { marginTop: "auto", padding: "12px 10px", fontSize: "0.8125rem" }), loading: css("chat-loading", { color: "var(--c-text-muted)", textAlign: "center", animation: `${pulse} 0.7s ease-in-out infinite alternate` }), beginning: css("chat-beginning", { fontWeight: "600", color: "var(--c-text-dim)", textAlign: "center" }), error: css("chat-error", { display: "flex", alignItems: "center", gap: "10px", padding: "8px 12px", borderRadius: "10px", border: "1px solid #ef4444", "& span": { flex: "1" } }), btn: css("chat-btn", { height: "30px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", fontSize: "0.8125rem", fontWeight: "600", color: "var(--c-text)", hover: { backgroundColor: "var(--c-bg-secondary)" } }), // ── A message: grid rows for day, divider, avatar+meta, text, reactions ── msg: css("chat-msg", { position: "relative", display: "grid", gridTemplateColumns: "36px minmax(0, 1fr)", columnGap: "10px", padding: "1px 10px", borderRadius: "8px", hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:hover [data-chat-actions], &:focus-within [data-chat-actions]": { opacity: "1", pointerEvents: "auto" } }), first: css("chat-first", { marginTop: "10px" }), sending: css("chat-sending", { opacity: "0.5" }), failed: css("chat-failed", { "& p": { color: "#ef4444" } }), live: css("chat-live", { animation: `${pop} 0.22s ease-out both` }), mentionRow: css("chat-mention-row", { backgroundColor: "var(--c-primary-alpha-08)", boxShadow: "inset 2px 0 0 var(--c-primary)", hover: { backgroundColor: "var(--c-primary-alpha-13)" } }), day: css("chat-day", { gridColumn: "1 / -1", display: "flex", alignItems: "center", gap: "10px", margin: "10px 0 4px", fontSize: "0.75rem", fontWeight: "600", color: "var(--c-text-muted)", before: rule, after: rule }), divider: css("chat-divider", { gridColumn: "1 / -1", display: "flex", alignItems: "center", gap: "10px", margin: "12px 0 4px", fontSize: "0.75rem", fontWeight: "700", color: "var(--c-primary-ink)", whiteSpace: "nowrap", before: rule, after: rule }), dividerBtn: css("chat-divider-btn", { height: "22px", padding: "0 8px", borderRadius: "6px", fontSize: "0.75rem", fontWeight: "600", color: "var(--c-text-dim)", hover: { color: "var(--c-text)", backgroundColor: "var(--c-bg-light)" } }), avatar: css("chat-avatar", { gridRow: "span 2", display: "flex", alignItems: "center", justifyContent: "center", width: "36px", height: "36px", marginTop: "2px", borderRadius: "10px", color: "#fff", fontWeight: "600" }), meta: css("chat-meta", { display: "flex", alignItems: "baseline", gap: "8px", fontSize: "0.8125rem", "& time": { fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-muted)" } }), edited: css("chat-edited", { fontSize: "0.6875rem", color: "var(--c-text-muted)", fontStyle: "italic" }), // ── Text: markdown-lite segments, rendered by a nested list ── text: css("chat-text", { gridColumn: "2", fontSize: "0.875rem", lineHeight: "1.5", whiteSpace: "pre-wrap", overflowWrap: "anywhere" }), code: css("chat-code", { fontFamily: mono, fontSize: "0.8125em", padding: "1px 5px", borderRadius: "5px", backgroundColor: "var(--c-bg-secondary)", border: "1px solid var(--c-border)", color: "var(--c-text)", whiteSpace: "pre-wrap" }), link: css("chat-link", { color: "var(--c-primary-ink)", textDecoration: "none", fontWeight: "500", hover: { textDecoration: "underline" } }), mention: css("chat-mention", { color: "var(--c-primary-ink)", fontWeight: "600" }), mentionMe: css("chat-mention-me", { padding: "0 4px", borderRadius: "5px", backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-primary-ink)", fontWeight: "600" }), edit: css("chat-edit", { gridColumn: "2", display: "block", width: "100%", minHeight: "38px", margin: "0", padding: "6px 8px", borderRadius: "8px", border: "1px solid var(--c-primary)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem", lineHeight: "1.5", resize: "vertical", whiteSpace: "pre-wrap", overflowWrap: "anywhere", raw: { "field-sizing": "content" }, focus: { outline: "none" } }), // ── Reactions, the picker and the hover actions ── reactions: css("chat-reactions", { gridColumn: "2", display: "flex", flexWrap: "wrap", gap: "4px", marginTop: "4px" }), reaction: css("chat-reaction", { display: "inline-flex", alignItems: "center", gap: "5px", height: "24px", padding: "0 8px 0 6px", borderRadius: "999px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg-secondary)", fontSize: "0.8125rem", hover: { borderColor: "var(--c-primary)" } }), reactionMine: css("chat-reaction-mine", { borderColor: "var(--c-primary)", backgroundColor: "var(--c-primary-alpha-13)" }), reactionCount: css("chat-reaction-count", { fontSize: "0.75rem", fontWeight: "600", color: "var(--c-text-dim)", fontVariantNumeric: "tabular-nums" }), picker: css("chat-picker", { gridColumn: "2", display: "flex", flexWrap: "wrap", gap: "2px", width: "fit-content", marginTop: "6px", padding: "4px", borderRadius: "10px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", boxShadow: "0 10px 30px var(--c-shadow)", animation: `${pop} 0.15s ease-out both` }), pick: css("chat-pick", { display: "flex", alignItems: "center", justifyContent: "center", width: "32px", height: "32px", borderRadius: "8px", fontSize: "1.0625rem", transition: "transform 0.12s ease", hover: { backgroundColor: "var(--c-bg-secondary)", transform: "scale(1.15)" } }), actions: css("chat-actions", { position: "absolute", top: "4px", right: "8px", zIndex: 5, display: "flex", alignItems: "center", gap: "2px", padding: "2px", borderRadius: "8px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", boxShadow: "0 6px 20px var(--c-shadow)", opacity: "0", pointerEvents: "none", transition: "opacity 0.12s ease", "@media (hover: none)": { opacity: "1", pointerEvents: "auto" } }), action: css("chat-action", { display: "flex", alignItems: "center", gap: "4px", height: "26px", padding: "0 7px", borderRadius: "6px", fontSize: "0.75rem", fontWeight: "600", color: "var(--c-text-dim)", whiteSpace: "nowrap", hover: { color: "var(--c-text)", backgroundColor: "var(--c-bg-secondary)" } }), retry: css("chat-retry", { gridColumn: "2", display: "flex", alignItems: "center", gap: "4px", fontSize: "0.75rem", color: "#ef4444" }), small: css("chat-small", { height: "22px", padding: "0 6px", borderRadius: "6px", fontSize: "0.75rem", fontWeight: "600", color: "var(--c-text-dim)", hover: { color: "var(--c-text)", backgroundColor: "var(--c-bg-light)" } }), // ── The new-message pill and the typing row ── pill: css("chat-pill", { position: "absolute", bottom: "10px", left: "50%", transform: "translateX(-50%)", height: "30px", padding: "0 14px", borderRadius: "999px", backgroundColor: "var(--c-primary-dark)", color: "#fff", fontSize: "0.8125rem", fontWeight: "600", whiteSpace: "nowrap", boxShadow: "0 4px 14px var(--c-shadow)", animation: `${pop} 0.18s ease-out both` }), typingRow: css("chat-typing-row", { display: "flex", alignItems: "center", gap: "10px", padding: "6px 10px 2px", fontSize: "0.8125rem", fontStyle: "italic", color: "var(--c-text-muted)" }), dots: css("chat-dots", { display: "inline-flex", gap: "3px", "& i": { width: "6px", height: "6px", borderRadius: "50%", backgroundColor: "var(--c-text-muted)", animation: `${bounce} 1s ease-in-out infinite`, "&:nth-child(2)": { raw: { "animation-delay": "0.15s" } }, "&:nth-child(3)": { raw: { "animation-delay": "0.3s" } } } }), // ── The composer ── composerArea: css("chat-composer-area", { position: "relative", flexShrink: 0 }), composer: css("chat-composer", { display: "flex", alignItems: "flex-end", gap: "8px", padding: "0 12px 12px" }), // field-sizing grows the box with Shift+Enter lines where it is supported. 16px on phones: iOS zooms into smaller inputs. input: css("chat-input", { flex: "1", minWidth: "0", minHeight: "38px", maxHeight: "120px", padding: "8px 12px", borderRadius: "10px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg-secondary)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.875rem", lineHeight: "1.4", resize: "none", raw: { "field-sizing": "content" }, focus: { outline: "none", borderColor: "var(--c-primary)" }, "@media (max-width: 600px)": { fontSize: "16px" } }), emojiBtn: css("chat-emoji-btn", { display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, width: "38px", height: "38px", borderRadius: "10px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg-secondary)", fontSize: "1.0625rem", hover: { backgroundColor: "var(--c-bg-light)" } }), composerPicker: css("chat-composer-picker", { position: "absolute", right: "12px", bottom: "calc(100% - 8px)", zIndex: 10, display: "flex", gap: "2px", padding: "4px", borderRadius: "10px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)", boxShadow: "0 10px 30px var(--c-shadow)", animation: `${pop} 0.15s ease-out both` }), send: css("chat-send", { height: "38px", padding: "0 16px", borderRadius: "10px", backgroundColor: "var(--c-primary-dark)", color: "#fff", fontSize: "0.875rem", fontWeight: "600", "&:disabled": { opacity: "0.45", cursor: "default" } }), };