Examples
Practical examples। Live demos।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
एक भाषा वाले app की तरह हर label एक static value है, इसलिए update() उसे दोबारा नहीं पढ़ता। cart पर click करने से सिर्फ़ quantity और total update होते हैं। भाषा बदलने पर इस tree का forceUpdate() चलता है, जो components दोबारा चलाकर उन्हीं elements को patch करता है, lang और dir समेत। currency, plurals, dates और lists Intl से format होते हैं। भाषा बदलने पर cart और टाइप किया हुआ coupon बने रहते हैं।
Good things for your kitchen.
// app.ts: the shop. Every label is a static value, written exactly as in an // app with one language: h1(t.title), button(t.add). update() never reads // them again, so a click costs nothing for them. Only the cart is dynamic. // Switching the language is rare and changes everything at once: it sets // `locale` and calls forceUpdate(), which runs Shop() again and patches the // same elements. The cart, and a code typed in the coupon field, stay. import "nuclo"; import { LOCALES, PRODUCTS, localize, type Code, type Localized, type Product } from "./messages.ts"; import { s } from "./styles.ts"; interface Line { product: Product; qty: number } const SHIPPING = 6; // USD, free from FREE_OVER const FREE_OVER = 50; let locale: Code = "en-US"; const cart: Line[] = []; let coupon = ""; let ordered = false; let builds = 0; // Shop() calls: one per build, none per update() let switchMs: number | null = null; let host: HTMLDivElement | undefined; // the element Shop() is rendered into const subtotal = () => cart.reduce((sum, line) => sum + line.product.usd * line.qty, 0); const discount = () => (coupon.trim().toUpperCase() === "NUCLO" ? subtotal() / 10 : 0); const shipping = () => (cart.length === 0 || subtotal() >= FREE_OVER ? 0 : SHIPPING); function add(product: Product) { const line = cart.find((l) => l.product === product); if (line) line.qty++; else cart.push({ product, qty: 1 }); ordered = false; update(); } function change(line: Line, by: number) { line.qty += by; if (line.qty === 0) cart.splice(cart.indexOf(line), 1); update(); } function checkout() { cart.length = 0; ordered = true; update(); } function switchTo(code: Code) { if (!host || code === locale) return; locale = code; const start = performance.now(); // The explicit form rebuilds this one tree. A bare forceUpdate() would call // every root rendered with render(App) or hydrate(App) again: here, that is // the whole docs site around this demo. forceUpdate(Shop(), host); switchMs = performance.now() - start; update(); // the diagnostics strip is outside the rebuilt tree } function ProductCard(product: Product, { t, price }: Localized) { const [name, description] = t.products[product.id]; return li( s.card, span(s.emoji, { "aria-hidden": "true" }, product.emoji), strong(name), span(s.muted, description), div(s.buy, span(s.price, price(product.usd)), button(s.btn, s.add, t.add, { onClick: () => add(product) })), ); } // The split: labels are static, read once per build. Quantities and money // change on clicks, so they are functions that update() reads again, with // the formatters of the locale this build was made for. function Cart({ t, price, number, items, delivery }: Localized) { const row = (label: string, value: () => string) => div(dt(label), dd(value)); return aside( s.cart, header(s.cartHead, h2(t.cart), span(s.muted, () => items(cart.reduce((n, line) => n + line.qty, 0)))), when(() => cart.length === 0, p(s.muted, () => (ordered ? t.thanks : t.empty))).else( ul(s.lines, list(() => cart, (line) => li( s.line, span(s.name, `${line.product.emoji} ${t.products[line.product.id][0]}`), button(s.icon, { title: t.less, "aria-label": t.less, onClick: () => change(line, -1) }, "−"), span(s.qty, () => number(line.qty)), button(s.icon, { title: t.more, "aria-label": t.more, onClick: () => change(line, 1) }, "+"), span(s.amount, () => price(line.product.usd * line.qty)), ))), ), dl( s.totals, row(t.subtotal, () => price(subtotal())), row(t.shipping, () => (shipping() === 0 ? t.free : price(shipping()))), when(() => discount() > 0, row(t.discount, () => price(-discount()))), div(s.total, dt(t.total), dd(() => price(subtotal() + shipping() - discount()))), ), p(s.muted, t.freeOver(price(FREE_OVER))), label( s.field, t.coupon, // No value binding: the typed text lives in the element, and // forceUpdate() reuses the element. Only the placeholder is replaced. input({ placeholder: t.couponHint, onInput: (e) => { coupon = e.currentTarget.value; update(); } }), ), div(s.delivery, span(s.muted, t.delivery), strong(delivery)), button(s.btn, s.primary, t.checkout, { disabled: () => cart.length === 0, onClick: checkout }), ); } function Shop() { builds++; const l = localize(locale); const { t } = l; return div( s.shop, { lang: locale, dir: l.dir }, // static as well: forceUpdate() patches them header( s.head, div(h1(t.title), p(s.muted, t.tagline)), nav( s.langs, { "aria-label": t.language }, ...(Object.keys(LOCALES) as Code[]).map((code) => button( cx(s.lang, code === locale ? s.on : null), // static: only a switch changes it { lang: code, "aria-pressed": String(code === locale), onClick: () => switchTo(code) }, LOCALES[code].name, ), ), ), ), div(s.body, ul(s.grid, ...PRODUCTS.map((product) => ProductCard(product, l))), Cart(l)), footer(s.foot, span(s.muted, t.shipsTo(l.shipsTo)), span(s.muted, t.rates)), ); } export function LocaleShop() { builds = 0; // a new tree: its builds count from here, coupon = ""; // and its coupon field starts empty return div( s.app, div(s.host, { onMount: (el) => { host = el; return () => { host = undefined; }; } }, Shop()), div( s.diag, span(s.diagLabel, "Diagnostics"), span("Shop() built ", strong(() => `${builds}×`)), span("last switch ", strong(() => (switchMs === null ? "none yet" : `${switchMs.toFixed(1)} ms`))), span("cart clicks: update() · language: forceUpdate()"), ), ); }
// messages.ts: the translations. Each language is a plain object typed from // the English one, so a missing key is a type error. Messages that embed a // value are functions: each language puts the value where its grammar wants. // Money, numbers, plurals, dates, country names and lists are formatted by // the browser's Intl, per locale. Nothing here knows about the UI. /** Plural forms, picked by Intl.PluralRules. "#" is replaced by the count. */ type Plural = Partial<Record<Intl.LDMLPluralRule, string>> & { other: string }; export interface Product { id: keyof Messages["products"]; emoji: string; usd: number; // prices are stored in one currency, converted for display } export const PRODUCTS: Product[] = [ { id: "coffee", emoji: "☕", usd: 18 }, { id: "matcha", emoji: "🍵", usd: 24 }, { id: "chocolate", emoji: "🍫", usd: 7.5 }, { id: "honey", emoji: "🍯", usd: 12 }, { id: "cookies", emoji: "🍪", usd: 6 }, { id: "teapot", emoji: "🫖", usd: 39 }, ]; const en = { title: "Corner Store", tagline: "Good things for your kitchen.", language: "Language", add: "Add to cart", cart: "Your cart", items: { one: "# item", other: "# items" } as Plural, empty: "Your cart is empty.", thanks: "Thank you! Your order is on its way.", less: "Remove one", more: "Add one", subtotal: "Subtotal", shipping: "Shipping", free: "Free", discount: "Discount", total: "Total", freeOver: (amount: string) => `Free shipping on orders of ${amount} or more.`, coupon: "Coupon code", couponHint: "Try NUCLO", delivery: "Delivery", checkout: "Check out", shipsTo: (countries: string) => `Ships to: ${countries}.`, rates: "Prices converted from US dollars at fixed demo rates.", products: { // [name, description] coffee: ["Coffee beans", "Medium roast, 500 g"], matcha: ["Matcha", "Ceremonial grade, 30 g"], chocolate: ["Dark chocolate", "70% cacao bar"], honey: ["Wildflower honey", "Raw, 350 g jar"], cookies: ["Butter cookies", "Baked this morning"], teapot: ["Cast-iron teapot", "Holds 0.8 liters"], }, }; type Messages = typeof en; const pt: Messages = { title: "Mercadinho da Esquina", tagline: "Coisas boas para a sua cozinha.", language: "Idioma", add: "Adicionar ao carrinho", cart: "Seu carrinho", items: { one: "# item", other: "# itens" }, empty: "Seu carrinho está vazio.", thanks: "Obrigado! Seu pedido está a caminho.", less: "Remover um", more: "Adicionar um", subtotal: "Subtotal", shipping: "Frete", free: "Grátis", discount: "Desconto", total: "Total", freeOver: (amount) => `Frete grátis a partir de ${amount}.`, coupon: "Cupom de desconto", couponHint: "Experimente NUCLO", delivery: "Entrega", checkout: "Finalizar compra", shipsTo: (countries) => `Países de entrega: ${countries}.`, rates: "Preços convertidos de dólares americanos com taxas de câmbio fixas para esta demonstração.", products: { coffee: ["Café em grãos", "Torra média, 500 g"], matcha: ["Matcha", "Grau cerimonial, 30 g"], chocolate: ["Chocolate amargo", "Barra 70% cacau"], honey: ["Mel silvestre", "Não pasteurizado, pote de 350 g"], cookies: ["Biscoitos amanteigados", "Assados hoje de manhã"], teapot: ["Bule de ferro fundido", "Capacidade de 0,8 litro"], }, }; const de: Messages = { title: "Laden an der Ecke", tagline: "Gute Dinge für deine Küche.", language: "Sprache", add: "In den Warenkorb", cart: "Dein Warenkorb", items: { one: "# Artikel", other: "# Artikel" }, empty: "Dein Warenkorb ist leer.", thanks: "Danke! Deine Bestellung ist unterwegs.", less: "Einen entfernen", more: "Einen hinzufügen", subtotal: "Zwischensumme", shipping: "Versand", free: "Kostenlos", discount: "Rabatt", total: "Gesamt", freeOver: (amount) => `Kostenloser Versand ab ${amount}.`, coupon: "Gutscheincode", couponHint: "Probier NUCLO", delivery: "Lieferung", checkout: "Zur Kasse", shipsTo: (countries) => `Lieferländer: ${countries}.`, rates: "Preise zu festen Demo-Kursen aus US-Dollar umgerechnet.", products: { coffee: ["Kaffeebohnen", "Mittlere Röstung, 500 g"], matcha: ["Matcha", "Zeremonienqualität, 30 g"], chocolate: ["Zartbitterschokolade", "Tafel mit 70 % Kakao"], honey: ["Wildblütenhonig", "Naturbelassen, 350-g-Glas"], cookies: ["Butterkekse", "Heute Morgen gebacken"], teapot: ["Teekanne aus Gusseisen", "Fasst 0,8 Liter"], }, }; const ja: Messages = { title: "街角ストア", tagline: "キッチンに、いいものを。", language: "言語", add: "カートに追加", cart: "カート", items: { other: "#点" }, empty: "カートは空です。", thanks: "ありがとうございます!ご注文の商品は配送中です。", less: "1つ減らす", more: "1つ増やす", subtotal: "小計", shipping: "送料", free: "無料", discount: "割引", total: "合計", freeOver: (amount) => `${amount}以上で送料無料。`, coupon: "クーポンコード", couponHint: "例: NUCLO", delivery: "お届け予定", checkout: "レジに進む", shipsTo: (countries) => `配送先:${countries}`, rates: "価格はデモ用の固定レートで米ドルから換算しています。", products: { coffee: ["コーヒー豆", "中煎り・500 g"], matcha: ["抹茶", "茶道用・30 g"], chocolate: ["ダークチョコレート", "カカオ70%の板チョコレート"], honey: ["百花蜜", "非加熱・350 g入りの瓶"], cookies: ["バタークッキー", "今朝焼きました"], teapot: ["鋳鉄製の急須", "容量0.8 L"], }, }; // Arabic has six plural forms: 0, 1, 2, a few (3–10), many (11–99), and the rest. const ar: Messages = { title: "متجر الحي", tagline: "أشياء جميلة لمطبخك.", language: "اللغة", add: "أضف إلى السلة", cart: "سلة التسوق", items: { zero: "لا منتجات", one: "منتج واحد", two: "منتجان", few: "# منتجات", many: "# منتجًا", other: "# منتج" }, empty: "سلتك فارغة.", thanks: "شكرًا لك! طلبك في الطريق.", less: "تقليل الكمية", more: "زيادة الكمية", subtotal: "المجموع الفرعي", shipping: "الشحن", free: "مجاني", discount: "الخصم", total: "الإجمالي", freeOver: (amount) => `شحن مجاني للطلبات بقيمة ${amount} أو أكثر`, // no period: the currency ends with one coupon: "رمز القسيمة", couponHint: "جرّب NUCLO", delivery: "موعد التوصيل", checkout: "إتمام الشراء", shipsTo: (countries) => `نشحن إلى: ${countries}.`, rates: "الأسعار محوّلة من الدولار الأمريكي بأسعار صرف ثابتة للعرض.", products: { coffee: ["حبوب القهوة", "تحميص متوسط، ٥٠٠ غرام"], matcha: ["ماتشا", "درجة احتفالية، ٣٠ غرامًا"], chocolate: ["شوكولاتة داكنة", "لوح شوكولاتة بنسبة كاكاو ٧٠٪"], honey: ["عسل الزهور البرية", "خام، برطمان ٣٥٠ غرامًا"], cookies: ["بسكويت بالزبدة", "مخبوز هذا الصباح"], teapot: ["إبريق شاي من الحديد الزهر", "سعة ٠٫٨ لتر"], }, }; // rate: one US dollar in the display currency. export const LOCALES = { "en-US": { name: "English", currency: "USD", rate: 1, dir: "ltr", t: en }, "pt-BR": { name: "Português", currency: "BRL", rate: 5.4, dir: "ltr", t: pt }, "de-DE": { name: "Deutsch", currency: "EUR", rate: 0.92, dir: "ltr", t: de }, "ja-JP": { name: "日本語", currency: "JPY", rate: 150, dir: "ltr", t: ja }, "ar-EG": { name: "العربية", currency: "EGP", rate: 48.5, dir: "rtl", t: ar }, }; export type Code = keyof typeof LOCALES; // Fixed, not new Date(): the server and the browser must print the same text. const DELIVERY = new Date(Date.UTC(2026, 10, 3, 12)); const SHIPS_TO = ["US", "BR", "DE", "JP", "EG"]; // region codes: Intl.DisplayNames names them /** One locale's messages and formatters. Built once per build of the shop. */ export function localize(code: Code) { const { currency, rate, dir, t } = LOCALES[code]; const money = new Intl.NumberFormat(code, { style: "currency", currency }); const num = new Intl.NumberFormat(code); const plural = new Intl.PluralRules(code); const region = new Intl.DisplayNames(code, { type: "region" }); return { t, dir, price: (usd: number) => money.format(usd * rate), number: num.format, // Intl's format is bound: it can be passed around items: (n: number) => (t.items[plural.select(n)] ?? t.items.other).replace("#", num.format(n)), delivery: new Intl.DateTimeFormat(code, { weekday: "long", month: "long", day: "numeric", timeZone: "UTC" }).format(DELIVERY), shipsTo: new Intl.ListFormat(code).format(SHIPS_TO.map((r) => region.of(r)!)), }; } export type Localized = ReturnType<typeof localize>;
// styles.ts: the look. Nothing here says left or right: text aligns to start // or end, spacing is symmetric, and flex and grid follow the text direction. // With dir="rtl" the whole shop mirrors by itself. import "nuclo"; const mono = "ui-monospace, monospace"; const wide = "@media (min-width: 900px)"; const control = { height: "30px", padding: "0 10px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.75rem", fontWeight: "600", whiteSpace: "nowrap" }; const panel = { borderRadius: "12px", border: "1px solid var(--c-border)" }; export const s = { app: css("i18n-app", { display: "flex", flexDirection: "column", gap: "10px", width: "100%", height: "100%" }), host: css("i18n-host", { flex: "1", minHeight: "0" }), shop: css("i18n-shop", { display: "flex", flexDirection: "column", gap: "14px", height: "100%", overflowY: "auto", textAlign: "start", color: "var(--c-text)" }), head: css("i18n-head", { display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "10px", "& h1": { fontSize: "1.25rem", fontWeight: "700", lineHeight: "1.2" } }), muted: css("i18n-muted", { fontSize: "0.75rem", color: "var(--c-text-muted)", lineHeight: "1.4" }), langs: css("i18n-langs", { display: "flex", flexWrap: "wrap", gap: "2px", padding: "3px", borderRadius: "10px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-secondary)" }), lang: css("i18n-lang", { height: "28px", padding: "0 10px", borderRadius: "7px", fontSize: "0.8125rem", fontWeight: "600", color: "var(--c-text-dim)", hover: { color: "var(--c-text)" } }), on: css("i18n-on", { backgroundColor: "var(--c-bg-card)", color: "var(--c-primary-ink)", boxShadow: "0 1px 3px var(--c-shadow)" }), body: css("i18n-body", { display: "flex", flexDirection: "column", gap: "14px", [wide]: { flexDirection: "row", flex: "1", minHeight: "0" } }), grid: css("i18n-grid", { display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", alignContent: "start", gap: "10px", listStyle: "none", "@media (min-width: 640px)": { gridTemplateColumns: "repeat(3, minmax(0, 1fr))" }, [wide]: { flex: "1", overflowY: "auto" } }), card: css("i18n-card", { ...panel, display: "flex", flexDirection: "column", gap: "2px", padding: "10px", backgroundColor: "var(--c-bg-card)", "& strong": { fontSize: "0.875rem", fontWeight: "600" } }), emoji: css("i18n-emoji", { display: "flex", alignItems: "center", justifyContent: "center", height: "64px", marginBottom: "6px", borderRadius: "8px", backgroundColor: "var(--c-bg-secondary)", fontSize: "2.25rem" }), buy: css("i18n-buy", { display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "6px", marginTop: "auto", paddingTop: "8px" }), price: css("i18n-price", { fontSize: "0.875rem", fontWeight: "600", fontVariantNumeric: "tabular-nums" }), btn: css("i18n-btn", { ...control, hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:disabled": { opacity: "0.45", cursor: "default" } }), add: css("i18n-add", { borderColor: "transparent", backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-primary-ink)", hover: { backgroundColor: "var(--c-primary-alpha-19)" } }), primary: css("i18n-primary", { height: "36px", borderColor: "transparent", backgroundColor: "var(--c-primary-dark)", color: "#fff", fontSize: "0.875rem", hover: { backgroundColor: "var(--c-primary-dark)", filter: "brightness(0.92)" } }), cart: css("i18n-cart", { ...panel, display: "flex", flexDirection: "column", gap: "12px", padding: "14px", backgroundColor: "var(--c-bg-secondary)", [wide]: { width: "320px", flexShrink: 0, overflowY: "auto" } }), cartHead: css("i18n-cartHead", { display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: "8px", "& h2": { fontSize: "1rem", fontWeight: "700" } }), lines: css("i18n-lines", { display: "flex", flexDirection: "column", gap: "6px", listStyle: "none" }), line: css("i18n-line", { display: "flex", alignItems: "center", gap: "4px", fontSize: "0.8125rem" }), name: css("i18n-name", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), icon: css("i18n-icon", { ...control, width: "24px", height: "24px", padding: "0", borderRadius: "6px", fontSize: "0.875rem", color: "var(--c-text-dim)", hover: { color: "var(--c-text)" } }), qty: css("i18n-qty", { minWidth: "22px", textAlign: "center", fontVariantNumeric: "tabular-nums" }), amount: css("i18n-amount", { minWidth: "76px", textAlign: "end", fontWeight: "500", fontVariantNumeric: "tabular-nums" }), totals: css("i18n-totals", { display: "flex", flexDirection: "column", gap: "4px", paddingTop: "10px", borderTop: "1px solid var(--c-border)", fontSize: "0.8125rem", "& div": { display: "flex", justifyContent: "space-between", gap: "8px" }, "& dt": { color: "var(--c-text-dim)" }, "& dd": { fontVariantNumeric: "tabular-nums" } }), total: css("i18n-total", { paddingTop: "4px", fontSize: "0.9375rem", fontWeight: "700", "& dt": { color: "var(--c-text)" } }), field: css("i18n-field", { display: "flex", flexDirection: "column", gap: "4px", fontSize: "0.75rem", color: "var(--c-text-dim)", "& input": { ...control, fontWeight: "400", fontSize: "0.8125rem" } }), delivery: css("i18n-delivery", { display: "flex", flexDirection: "column", gap: "2px", fontSize: "0.8125rem" }), foot: css("i18n-foot", { display: "flex", flexWrap: "wrap", justifyContent: "space-between", gap: "4px 16px", paddingTop: "10px", borderTop: "1px solid var(--c-border)" }), diag: css("i18n-diag", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "4px 16px", padding: "8px 12px", borderRadius: "10px", backgroundColor: "var(--c-bg-secondary)", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-muted)", "& strong": { color: "var(--c-primary-ink)", fontVariantNumeric: "tabular-nums" } }), diagLabel: css("i18n-diagLabel", { fontWeight: "600", textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--c-text-dim)" }), };