示例
实用示例,实时演示。
挑一个示例全屏打开,运行效果和源码并排呈现。
挑一个示例全屏打开,运行效果和源码并排呈现。
一个没有尽头的信息流:快速的模拟 fetch() 把每一页即时生成,放进同一个普通数组。只有视口附近的行留在 DOM 里:list() 在两个占位元素之间渲染 posts.slice(start, end),所以就算翻到十万条帖子,页面也依然轻快。真正的末尾处有个哨兵,在它进入视野之前就会去请求下一页。
// app.ts: the feed. Every page lands in the same plain array with push(), but // only the rows near the viewport are in the DOM: the list() renders // posts.slice(start, end), and two spacers stand in for everything above and // below. Rows have one fixed height, so start and end are arithmetic on the // scroll position. A row that scrolls away is dropped; its post object keeps // its likes, and the same object gets a fresh row when it comes back. // The sentinel at the real end asks for the next page before it comes into view. import "nuclo"; import { fetchPage, type Post } from "./api.ts"; import { s } from "./styles.ts"; const ROW = 120; // px: every row is this tall, margin included const OVERSCAN = 4; // rows rendered beyond each edge of the viewport let posts: Post[] = []; let next = 0; // the cursor of the next page let loading = false; let error: string | null = null; let scrollTop = 0; let viewport = 0; // the feed's visible height let lookAgain: (() => void) | null = null; // set by the mounted sentinel: checks again whether it is in view const start = () => Math.max(0, Math.floor(scrollTop / ROW) - OVERSCAN); const end = () => Math.min(posts.length, Math.ceil((scrollTop + viewport) / ROW) + OVERSCAN); async function loadMore() { if (loading || error !== null) return; loading = true; update(); try { const page = await fetchPage(next); posts.push(...page.items); next = page.next; } catch (e) { error = (e as Error).message; } loading = false; update(); lookAgain?.(); // a short page can leave the sentinel in view: then load the next one too } function retry() { error = null; loadMore(); } function startOver() { posts = []; next = 0; error = null; scrollTop = 0; update(); lookAgain?.(); } const ago = (m: number) => (m < 60 ? `${m}m ago` : m < 1440 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`); function PostView(post: Post) { return article( s.post, div(s.avatar, { style: { backgroundColor: `hsl(${(post.id * 47) % 360} 55% 48%)` } }, post.author[0]), div( s.body, div(s.meta, strong(post.author), span(ago(post.minutesAgo)), span(s.id, `#${post.id + 1}`)), p(post.text), button( s.like, { class: () => cx(s.like, post.liked ? s.liked : null).className, "aria-pressed": () => String(post.liked) }, "♥ ", () => String(post.likes), { onClick: () => { post.liked = !post.liked; post.likes += post.liked ? 1 : -1; update(); } }, ), ), ); } const Skeleton = () => div(s.skeleton, div(s.bone, s.boneAvatar), div(s.boneLines, div(s.bone), div(s.bone, s.boneShort))); function Sentinel() { return div( s.sentinel, on("mount", (el) => { const observer = new IntersectionObserver( ([entry]) => { if (entry.isIntersecting) loadMore(); }, { root: el.parentElement, rootMargin: "800px" }, // start the next page well before the end is reached ); observer.observe(el); lookAgain = () => { observer.unobserve(el); observer.observe(el); }; return () => { observer.disconnect(); lookAgain = null; }; // left set, it would keep this element alive }), when(() => loading, Skeleton(), Skeleton(), Skeleton()) .when(() => error !== null, div(s.error, span(() => error ?? ""), button(s.btn, "Retry", { onClick: retry }))), ); } export function InfiniteFeed() { return div( s.app, header( s.head, strong(() => `${posts.length} posts`), span(s.state, () => `${end() - start()} rows in the DOM · ${loading ? "loading…" : error !== null ? "failed" : "scroll, it never ends"}`), button(s.btn, "Start over", { disabled: () => loading, onClick: startOver }), ), div( s.feed, on("mount", (el) => { // The state outlives the element: a feed built again (the page was left // and reopened) resumes where it was, instead of windowing for a scroll // position its new element does not have. el.scrollTop = scrollTop; scrollTop = el.scrollTop; const sizes = new ResizeObserver(() => { viewport = el.clientHeight; update(); }); sizes.observe(el); return () => sizes.disconnect(); }), { onScroll: (e) => { scrollTop = e.currentTarget.scrollTop; update(); } }, div({ style: () => ({ height: `${start() * ROW}px` }) }), list(() => posts.slice(start(), end()), PostView), div({ style: () => ({ height: `${(posts.length - end()) * ROW}px` }) }), Sentinel(), ), ); }
// api.ts: a fake backend with no end. fetchPage() behaves like a real request: // it takes a moment and answers with one page and the cursor of the next. // Rows are generated on the fly from their id, so // the same cursor always returns the same page. Nothing here knows about the UI. export interface Post { id: number; author: string; text: string; likes: number; liked: boolean; minutesAgo: number; } export interface Page { items: Post[]; next: number; // the cursor of the next page } const PAGE_SIZE = 20; const AUTHORS = ["Ada", "Grace", "Linus", "Margaret", "Dennis", "Barbara", "Ken", "Radia", "Edsger", "Frances", "Tony", "Yukihiro"]; const OPENERS = ["Shipped", "Fixed", "Rewrote", "Profiled", "Deleted half of", "Paired on", "Reviewed", "Benchmarked", "Documented", "Simplified"]; const SUBJECTS = ["the list diff", "the kanban demo", "the router", "the fake fetch", "the docs build", "the three.js inspector", "the form validation", "the SSR hydration", "the style engine", "the undo stack"]; const OUTCOMES = ["and it is faster now.", "with half the code.", "before lunch.", "and nothing re-rendered.", "and found the slow part.", "in one update() call.", "without a store.", "by mutating the array in place.", "and the mount count stayed put.", "while this feed kept loading."]; const EXTRAS = ["Breakpoint at update() showed every change.", "Rows already on screen were never rebuilt.", "The sentinel loaded the next page early.", "Plain objects, plain arrays, one update()."]; // A small integer hash: every field of a post is a deterministic 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[], id: number, salt: number) => list[hash(id * 31 + salt) % list.length]; function post(id: number): Post { let text = `${pick(OPENERS, id, 1)} ${pick(SUBJECTS, id, 2)} ${pick(OUTCOMES, id, 3)}`; if (hash(id) % 3 === 0) text += ` ${pick(EXTRAS, id, 4)}`; return { id, author: pick(AUTHORS, id, 5), text, likes: hash(id + 7) % 900, liked: false, minutesAgo: id * 3 + 1 }; } export function fetchPage(cursor: number): Promise<Page> { return new Promise((resolve) => { setTimeout(() => { const items = Array.from({ length: PAGE_SIZE }, (_, i) => post(cursor + i)); resolve({ items, next: cursor + PAGE_SIZE }); }, 60 + Math.random() * 140); }); }
import "nuclo"; const mono = "ui-monospace, monospace"; const pulse = keyframes({ from: { opacity: "0.35" }, to: { opacity: "1" } }); // A row is 112px plus an 8px margin: the 120px the app's ROW constant counts with. const card = { display: "flex", gap: "12px", height: "112px", marginBottom: "8px", padding: "10px 14px", borderRadius: "12px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg)" }; export const s = { app: css("feed-app", { display: "flex", flexDirection: "column", gap: "10px", width: "100%", maxWidth: "640px", height: "100%", margin: "0 auto" }), head: css("feed-head", { display: "flex", alignItems: "center", gap: "10px", fontSize: "0.875rem", "& strong": { fontVariantNumeric: "tabular-nums" } }), state: css("feed-state", { flex: "1", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-muted)" }), btn: css("feed-btn", { height: "32px", padding: "0 12px", borderRadius: "8px", border: "1px solid var(--c-border-light)", fontSize: "0.8125rem", fontWeight: "600", color: "var(--c-text)", whiteSpace: "nowrap", hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:disabled": { opacity: "0.45", cursor: "default" } }), feed: css("feed-feed", { flex: "1", minHeight: "0", overflowY: "auto", paddingRight: "4px" }), post: css("feed-post", card), avatar: css("feed-avatar", { display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, width: "36px", height: "36px", borderRadius: "10px", color: "#fff", fontWeight: "600" }), // The text is cut at two lines by height: a -webkit-box clamp would give the row the width of the unwrapped text. body: css("feed-body", { display: "flex", flexDirection: "column", alignItems: "flex-start", flex: "1", minWidth: "0", "& > div": { alignSelf: "stretch" }, "& p": { maxHeight: "2.9em", overflow: "hidden", margin: "2px 0 4px", fontSize: "0.875rem", lineHeight: "1.45" } }), meta: css("feed-meta", { display: "flex", alignItems: "baseline", gap: "8px", fontSize: "0.8125rem", color: "var(--c-text-muted)", "& strong": { color: "var(--c-text)" } }), id: css("feed-id", { marginLeft: "auto", fontFamily: mono, fontSize: "0.6875rem" }), like: css("feed-like", { display: "inline-flex", alignItems: "center", height: "24px", marginTop: "auto", padding: "0 10px", borderRadius: "999px", border: "1px solid var(--c-border)", fontSize: "0.75rem", color: "var(--c-text-dim)", fontVariantNumeric: "tabular-nums", hover: { borderColor: "var(--c-primary)", color: "var(--c-primary-ink)" } }), liked: css("feed-liked", { borderColor: "var(--c-primary)", color: "var(--c-primary-ink)", backgroundColor: "var(--c-primary-alpha-08)" }), sentinel: css("feed-sentinel", { minHeight: "1px" }), skeleton: css("feed-skeleton", { ...card, animation: `${pulse} 0.7s ease-in-out infinite alternate` }), bone: css("feed-bone", { height: "12px", borderRadius: "6px", backgroundColor: "var(--c-bg-light)" }), boneAvatar: css("feed-boneAvatar", { flexShrink: 0, width: "36px", height: "36px", borderRadius: "10px" }), boneLines: css("feed-boneLines", { display: "flex", flexDirection: "column", gap: "10px", flex: "1", paddingTop: "4px" }), boneShort: css("feed-boneShort", { width: "60%" }), error: css("feed-error", { display: "flex", alignItems: "center", gap: "10px", padding: "12px 14px", borderRadius: "12px", border: "1px solid #ef4444", fontSize: "0.875rem", "& span": { flex: "1" } }), };