diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a45e181..2381a76 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ Get it running first, so you know the environment is sound: ```bash npm install -npm test # 125 of them, ~4s, no network +npm test # 199 of them, ~1.5s, no network npm run dev # demo mode; no keys needed ``` @@ -51,6 +51,14 @@ The `description` field is **the rubric Jev chooses from**. Write what kind of b `LANGUAGES` in `lib/plan.ts` (the rubric Jev judges from) and `LANGUAGE_RULE` / `LENGTH_RULE` in `lib/content-parallel.ts` (the instructions the LLM writes under). Length hints are written for Chinese, so a new language needs a conversion note. +## Adding a component source + +`lib/sources.ts` only. A source is one row: name, url, role, a factual one-line summary, licence, the exact install command an agent should run (or `null` when the browser is the only way in), the machine-readable endpoints that answered, the slots it can improve, and the caveat that bites whoever pastes it in without reading. + +Fetch before you write. Every url, endpoint and command in that table was checked rather than recalled, and checking is what produced most of the caveats — `/r/index.json` is a 404 on beui.dev, `/registry.json` is a 404 on ui.shadcn.com, and Beautiful UI publishes no machine-readable surface at all. `npm run sources` re-runs those checks and exits non-zero if a declared endpoint stops answering; it needs the network, so it stays a script and never becomes a test. + +`role` carries more weight than `blocks`. None of the five sources ships a marketing page section, so a source improves a block loom already renders rather than replacing one, and a `summary` written like a block catalogue sends an agent looking for a hero that does not exist. Check the licence in the same pass: one of the five forbids redistributing a substantial part of its collection, which is fine for a site built with it and not fine for anything vendored here. + ## On what to ask a model This is the one place the project has an opinion. Please follow it when changing things: diff --git a/README.md b/README.md index 6766656..1d9c704 100644 --- a/README.md +++ b/README.md @@ -177,13 +177,15 @@ The editor UI is a separate matter: eight languages, picked from `navigator.lang ## Export -Three formats, all derived from **the same rendered result**. There is no second copy of the layout code. +Five formats, all derived from **the same rendered result**. There is no second copy of the layout code. | Export | Size | For | |---|---|---| | `site.html` | 36 KB | Put it online, or just double-click it | | `Site.tsx` | 34 KB | Keep developing; compiles under `tsc --strict` | | `spec.json` | a few KB | Archive it, or feed another renderer | +| `site.registry.json` | `Site.tsx`, wrapped | Install the page into a project that already uses shadcn/ui | +| `AGENTS.md` | a page | Hand the page to a coding agent: tokens, blocks, and where components come from | ### Site.tsx @@ -209,6 +211,44 @@ Filtering tests each selector with `root.matches()` / `root.querySelector()`, st Size-wise it only saves 16% (Tailwind was never the problem). The real gain is that the exported site no longer carries the editor's own styling. See `lib/export.ts`; there is **no second renderer**, block layout exists only in `app/registry.tsx`. +### site.registry.json + +A [shadcn registry](https://ui.shadcn.com/docs/registry) item, so the page installs the way any shadcn component does: + +```bash +npx shadcn@latest add ./site.registry.json +``` + +One command writes the component into whatever directory the project's `components.json` calls components, and merges the theme's 17 tokens into its stylesheet. The dependency list is empty on purpose: `Site.tsx` imports one type from React and nothing else, and padding the list would make the CLI install packages the file never uses. The CLI accepts a local path, so nothing has to be hosted first — the file the browser just downloaded works where it landed. + +The item carries the same `Site.tsx` source; it is not a second rendering of the page. The tokens travel with it as `cssVars` because a component dropped into a project that defines its own variables renders in that project's colours, which is not the page anyone exported. They are keyed without the leading `--`, since the CLI adds that itself: written `--accent`, the token reaches the Tailwind bridge as `var(----accent)`, resolves to nothing, and the install still reports success. + +### AGENTS.md + +A short brief for the coding agent that picks the export up: `spec.json` is the authoritative description of the page, here are the 17 theme tokens with their values, here are the blocks this page actually has, and here are the component sources relevant to those blocks. It is written to be read once before work starts, not as documentation for a person. + +## Components worth stealing + +The workflow is the lazy one — point a coding agent at a good library and let it pick, adapt and paste. `lib/sources.ts` is the table it reads: five libraries, each with its role, licence, install command, the machine-readable endpoints that answered when they were checked, the slots it can improve, and the caveat that bites. + +| Source | What it is | Way in | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 accessible React primitives over Radix, plus the registry spec the other four target | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 animated components as a shadcn-compatible registry, with an MCP endpoint | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | About 20 single-file animated widgets — gooey nav, proximity sidebar, odometer counter | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | About 44 named motion snippets as plain CSS, namespaced `.t-*` | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 primitives for AI application interfaces | Copy-paste from the browser; no CLI, no registry | + +**None of the five ships a marketing page section.** No hero, no testimonials, no team grid and no footer anywhere in the set — they are primitives, motion and app-shaped widgets. So a source improves a block loom already renders; it never replaces one, and `role` is the field that says which kind of improvement to expect. An agent that reads the table as a block catalogue goes looking for a hero in shadcn/ui and finds `/blocks/login`. + +The licences are not uniform either. Four are MIT; Transitions is a custom licence that forbids redistributing a substantial part of the collection, so its snippets can be used on a site but must not be vendored into this repo. + +Every url and endpoint in that table was fetched and checked rather than recalled, and all of them will rot eventually: + +```bash +npm run sources # re-checks each endpoint and reports how many components it still lists +``` + ## Themes are data

@@ -261,7 +301,7 @@ The audit needs a running server and `npx playwright install chromium`, so it st ```bash -npm test # 125 of them, ~4s, no network +npm test # 199 of them, ~1.5s, no network ``` They cover **the three rules taken back from the model** — selling-point count decides grid vs list, tier count decides single vs comparison, whether there is a UI screenshot decides the hero layout. If any of these drift, the decision quietly goes back to a model that cannot make it, so they are the ones that must not move. @@ -295,7 +335,10 @@ lib/ edit.ts edit intent recognition (speculative fan-out) export.ts self-contained HTML, only the CSS in use export-tsx.ts React source export, DOM → JSX + export-registry.ts the same source as a shadcn registry item, tokens included + export-agents.ts AGENTS.md: spec, tokens, blocks, and where components come from i18n.ts UI language, reads locales/*.json + sources.ts five component libraries an agent can pull from, with roles and caveats *.test.ts pure-logic tests, no network locales/ en|zh|ja|ko|es|fr|de|pt.json UI translations, zh is the reference @@ -316,7 +359,7 @@ app/ ## Contributing -See [CONTRIBUTING.md](CONTRIBUTING.md). Adding a block, a theme or a UI language each has a short, established path. +See [CONTRIBUTING.md](CONTRIBUTING.md). Adding a block, a theme, a UI language or a component source each has a short, established path. ## Star History diff --git a/app/page.tsx b/app/page.tsx index e560a54..136517a 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -8,6 +8,8 @@ import { THEMES } from "@/lib/themes"; import { elementsFor, type SiteContent } from "@/lib/content"; import { buildStandaloneHtml } from "@/lib/export"; import { buildReactSource } from "@/lib/export-tsx"; +import { buildRegistryItem } from "@/lib/export-registry"; +import { buildAgentsMd } from "@/lib/export-agents"; import { detectLocale, dict, @@ -278,6 +280,50 @@ export default function Page() { URL.revokeObjectURL(url); }, [spec, theme]); + /** + * Export the page as a shadcn registry item. + * + * This is the only interchange format the libraries in lib/sources.ts agree on: four of the five publish one, and `npx shadcn add ` is how a component gets pulled into a project in the first place. Emitting the same shape sends the generated page back down that pipe, so an agent handles it with the machinery it already has rather than being handed a novel file it has to be taught about. + */ + const exportRegistry = useCallback(() => { + const node = previewRef.current?.firstElementChild; + if (!node) return; + const item = buildRegistryItem(node, prompt, theme); + const blob = new Blob([item], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "site.registry.json"; + a.click(); + URL.revokeObjectURL(url); + setEditLog((log) => [ + ...log, + `${t.exportRegistry} · ${(item.length / 1024).toFixed(0)} KB`, + ]); + }, [prompt, theme, t]); + + /** + * Export a brief for a coding agent rather than an artefact for a build. + * + * The other four exports assume whoever receives them already knows what loom rendered. An agent asked to improve the result does not: it needs the slots that are actually on the page and the honest account of what each source can and cannot do for them — none of the five ships a marketing section, so the instruction is always to improve a block that exists, never to go find a replacement for it. Left to guess, an agent looks for a hero in shadcn/ui, finds a login block, and invents something. + */ + const exportAgents = useCallback(() => { + const node = previewRef.current?.firstElementChild; + if (!node) return; + const brief = buildAgentsMd(node, prompt, theme, slots); + const blob = new Blob([brief], { type: "text/markdown;charset=utf-8" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "AGENTS.md"; + a.click(); + URL.revokeObjectURL(url); + setEditLog((log) => [ + ...log, + `${t.exportAgents} · ${(brief.length / 1024).toFixed(0)} KB · ${slots.join(" ")}`, + ]); + }, [prompt, theme, slots, t]); + const totalTokens = steps.reduce((sum, step) => sum + (step.inputTokens ?? 0), 0); // Appearance lives entirely in one prop, so re-theming costs nothing: no @@ -445,6 +491,20 @@ export default function Page() { > {t.exportSpec} + + )} diff --git a/docs/README.de.md b/docs/README.de.md index c903e5d..0218299 100644 --- a/docs/README.de.md +++ b/docs/README.de.md @@ -175,13 +175,15 @@ Die Editor-Oberfläche ist eine andere Sache: acht Sprachen, gewählt anhand von ## Export -Drei Formate, alle aus **demselben gerenderten Ergebnis**. Es gibt keine zweite Kopie des Layout-Codes. +Fünf Formate, alle aus **demselben gerenderten Ergebnis**. Es gibt keine zweite Kopie des Layout-Codes. | Export | Größe | Für | |---|---|---| | `site.html` | 36 KB | Online stellen oder einfach doppelklicken | | `Site.tsx` | 34 KB | Weiterentwickeln; kompiliert unter `tsc --strict` | | `spec.json` | ein paar KB | Archivieren oder einem anderen Renderer geben | +| `site.registry.json` | `Site.tsx`, verpackt | Die Seite in ein Projekt installieren, das schon shadcn/ui nutzt | +| `AGENTS.md` | eine Seite | Die Seite einem Coding-Agent übergeben: Tokens, Blöcke, Herkunft der Komponenten | ### Site.tsx @@ -207,6 +209,44 @@ Gefiltert wird, indem jeder Selektor mit `root.matches()` / `root.querySelector( An Größe spart das nur 16 % (Tailwind war nie das Problem). Der eigentliche Gewinn ist, dass die exportierte Seite nicht mehr das Styling des Editors mitschleppt. Siehe `lib/export.ts`; es gibt **keinen zweiten Renderer**, das Blocklayout existiert nur in `app/registry.tsx`. +### site.registry.json + +Ein [shadcn-Registry](https://ui.shadcn.com/docs/registry)-Item, die Seite installiert sich also wie jede andere shadcn-Komponente: + +```bash +npx shadcn@latest add ./site.registry.json +``` + +Ein Befehl schreibt die Komponente in das Verzeichnis, das die `components.json` des Projekts als Komponentenordner ausweist, und führt die 17 Tokens des Themes mit dessen Stylesheet zusammen. Die Abhängigkeitsliste ist mit Absicht leer: `Site.tsx` importiert einen Typ aus React und sonst nichts, und sie zu füllen hieße, die CLI Pakete installieren zu lassen, die die Datei nie benutzt. Die CLI nimmt einen lokalen Pfad an, es muss also vorher nichts gehostet werden — die Datei, die der Browser gerade heruntergeladen hat, funktioniert dort, wo sie gelandet ist. + +Das Item trägt denselben `Site.tsx`-Quelltext; es ist kein zweites Rendern der Seite. Die Tokens reisen als `cssVars` mit, denn eine Komponente, die in einem Projekt mit eigenen Variablen landet, wird in dessen Farben gezeichnet — und das ist nicht die Seite, die jemand exportiert hat. Ihre Schlüssel stehen ohne führendes `--`, weil die CLI das selbst ergänzt: als `--accent` geschrieben, kommt der Token in der Tailwind-Brücke als `var(----accent)` an, löst sich zu nichts auf, und die Installation meldet trotzdem Erfolg. + +### AGENTS.md + +Eine kurze Einweisung für den Coding-Agent, der den Export aufnimmt: `spec.json` ist die maßgebliche Beschreibung der Seite, hier sind die 17 Theme-Tokens mit ihren Werten, hier sind die Blöcke, die diese Seite tatsächlich hat, und hier sind die Komponentenquellen, die zu diesen Blöcken passen. Geschrieben, um vor der Arbeit einmal gelesen zu werden, nicht als Dokumentation für einen Menschen. + +## Komponenten, die das Stehlen wert sind + +Der Weg ist der bequeme: einem Coding-Agent eine gute Bibliothek zeigen und ihn auswählen, anpassen und einfügen lassen. `lib/sources.ts` ist die Tabelle, die er dabei liest: fünf Bibliotheken, jede mit ihrer Rolle, ihrer Lizenz, ihrem Installationsbefehl, den maschinenlesbaren Endpunkten, die bei der Prüfung geantwortet haben, den Slots, die sie verbessern kann, und dem Haken, der beißt. + +| Quelle | Was es ist | Weg hinein | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 zugängliche React-Primitive auf Radix, dazu die Registry-Spezifikation, auf die die anderen vier zielen | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 animierte Komponenten als shadcn-kompatible Registry, mit MCP-Endpunkt | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | Rund 20 animierte Einzeldatei-Widgets — zähflüssige Navigation, Näherungs-Sidebar, Kilometerzähler | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | Rund 44 benannte Bewegungsschnipsel in reinem CSS, im Namensraum `.t-*` | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 Primitive für Oberflächen von KI-Anwendungen | Nur Kopieren und Einfügen im Browser; keine CLI, keine Registry | + +**Keine der fünf liefert einen Abschnitt einer Marketingseite.** Kein Kopfbereich, keine Kundenstimmen, kein Teamraster, keine Fußzeile in der ganzen Auswahl — es sind Primitive, Bewegung und Widgets in App-Form. Eine Quelle verbessert also einen Block, den loom ohnehin rendert; sie ersetzt ihn nie, und `role` ist das Feld, das sagt, welche Art von Verbesserung zu erwarten ist. Ein Agent, der die Tabelle als Blockkatalog liest, sucht in shadcn/ui nach einem Kopfbereich und findet `/blocks/login`. + +Auch die Lizenzen sind nicht einheitlich. Vier sind MIT; Transitions hat eine eigene Lizenz, die das Weiterverbreiten eines wesentlichen Teils der Sammlung untersagt, seine Schnipsel dürfen also auf einer Seite verwendet, aber nicht in dieses Repository übernommen werden. + +Jede url und jeder Endpunkt in dieser Tabelle wurde abgerufen und geprüft statt aus dem Gedächtnis notiert, und verrotten werden sie trotzdem: + +```bash +npm run sources # ruft jeden Endpunkt erneut ab und meldet, wie viele Komponenten er noch listet +``` + ## Themes sind Daten

@@ -258,7 +298,7 @@ Die Prüfung braucht einen laufenden Server und `npx playwright install chromium ```bash -npm test # 125 Stück, rund 4 s, ohne Netz +npm test # 199 Stück, rund 1,5 s, ohne Netz ``` Sie decken **die drei dem Modell abgenommenen Regeln** ab: Die Anzahl der Verkaufsargumente entscheidet Raster oder Liste, die Anzahl der Preisstufen entscheidet Einzelkarte oder Vergleich, und ob es einen Oberflächen-Screenshot gibt, entscheidet das Layout des Kopfbereichs. Driftet eine davon, geht die Entscheidung still an ein Modell zurück, das sie nicht treffen kann — sie dürfen sich also nicht bewegen. @@ -292,8 +332,11 @@ lib/ edit.ts Erkennung der Änderungsabsicht (spekulatives Fan-out) export.ts eigenständiges HTML, nur das genutzte CSS export-tsx.ts React-Quellexport, DOM → JSX + export-registry.ts derselbe Quelltext als shadcn-Registry-Item, Tokens inklusive + export-agents.ts AGENTS.md: Spec, Tokens, Blöcke und Herkunft der Komponenten i18n.ts Oberflächensprache, liest locales/*.json demo.ts spielt fixtures/ ab, wenn keine Schlüssel gesetzt sind + sources.ts fünf Komponentenquellen, aus denen ein Agent schöpfen kann, mit Rollen und Haken *.test.ts Tests reiner Logik, ohne Netz locales/ en|zh|ja|ko|es|fr|de|pt.json Oberflächenübersetzungen, zh ist die Referenz @@ -316,7 +359,7 @@ app/ ## Mitmachen -Siehe [CONTRIBUTING.md](../CONTRIBUTING.md). Für einen neuen Block, ein Theme oder eine Oberflächensprache gibt es jeweils einen kurzen, festgelegten Weg. +Siehe [CONTRIBUTING.md](../CONTRIBUTING.md). Für einen neuen Block, ein Theme, eine Oberflächensprache oder eine Komponentenquelle gibt es jeweils einen kurzen, festgelegten Weg. ## Star History diff --git a/docs/README.es.md b/docs/README.es.md index f5a4c3b..99a0ed1 100644 --- a/docs/README.es.md +++ b/docs/README.es.md @@ -174,13 +174,15 @@ La interfaz del editor es otra cosa: ocho idiomas, elegidos a partir de `navigat ## Exportación -Tres formatos, todos derivados **del mismo resultado renderizado**. No hay una segunda copia del código de composición. +Cinco formatos, todos derivados **del mismo resultado renderizado**. No hay una segunda copia del código de composición. | Exportación | Tamaño | Para | |---|---|---| | `site.html` | 36 KB | Súbelo, o simplemente ábrelo con doble clic | | `Site.tsx` | 34 KB | Seguir desarrollando; compila con `tsc --strict` | | `spec.json` | unos pocos KB | Archivarlo, o alimentar otro renderizador | +| `site.registry.json` | `Site.tsx`, envuelto | Instalar la página en un proyecto que ya use shadcn/ui | +| `AGENTS.md` | una página | Entregarle la página a un agente de código: tokens, bloques y de dónde salen los componentes | ### Site.tsx @@ -206,6 +208,44 @@ El filtrado prueba cada selector con `root.matches()` / `root.querySelector()`, En tamaño solo ahorra un 16 % (Tailwind nunca fue el problema). La ganancia real es que el sitio exportado ya no arrastra el estilo del propio editor. Ver `lib/export.ts`; **no hay un segundo renderizador**, la composición de bloques existe únicamente en `app/registry.tsx`. +### site.registry.json + +Un elemento de [registro shadcn](https://ui.shadcn.com/docs/registry), así que la página se instala igual que cualquier componente de shadcn: + +```bash +npx shadcn@latest add ./site.registry.json +``` + +Un solo comando escribe el componente en el directorio que el `components.json` del proyecto llame de componentes y fusiona los 17 tokens del tema con su hoja de estilos. La lista de dependencias está vacía a propósito: `Site.tsx` importa un tipo de React y nada más, y rellenarla haría que la CLI instalase paquetes que el archivo no usa. La CLI acepta una ruta local, así que no hay que alojar nada primero: el archivo que acaba de descargar el navegador sirve donde cayó. + +El elemento lleva el mismo código de `Site.tsx`; no es un segundo renderizado de la página. Los tokens viajan con él como `cssVars` porque un componente soltado en un proyecto que define sus propias variables se dibuja con los colores de ese proyecto, que no son los de la página que alguien exportó. Van sin el `--` inicial, porque esos guiones los pone la CLI: escrito `--accent`, el token llega al puente de Tailwind como `var(----accent)`, no resuelve nada, y la instalación informa igualmente de éxito. + +### AGENTS.md + +Un informe breve para el agente de código que recoge la exportación: `spec.json` es la descripción autorizada de la página, estos son los 17 tokens del tema con sus valores, estos son los bloques que la página tiene de verdad, y estas son las fuentes de componentes relevantes para esos bloques. Está escrito para leerse una vez antes de empezar, no como documentación para una persona. + +## Componentes que vale la pena robar + +El método es el perezoso: señalarle una buena biblioteca a un agente de código y dejar que elija, adapte y pegue. `lib/sources.ts` es la tabla que lee: cinco bibliotecas, cada una con su papel, su licencia, su comando de instalación, los endpoints legibles por máquina que respondieron cuando se comprobaron, los slots que puede mejorar y la advertencia que muerde. + +| Fuente | Qué es | Cómo se coge | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 primitivas React accesibles sobre Radix, más la especificación de registro a la que apuntan las otras cuatro | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 componentes animados como registro compatible con shadcn, con endpoint MCP | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | Unos 20 widgets animados de un solo archivo: navegación gelatinosa, barra lateral por proximidad, contador de odómetro | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | Unos 44 fragmentos de movimiento con nombre, en CSS puro y con el espacio de nombres `.t-*` | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 primitivas para interfaces de aplicaciones de IA | Copiar y pegar desde el navegador; ni CLI ni registro | + +**Ninguna de las cinco trae una sección de página de marketing.** No hay portada, ni testimonios, ni rejilla de equipo, ni pie de página en todo el conjunto: son primitivas, movimiento y widgets con forma de aplicación. Así que una fuente mejora un bloque que loom ya dibuja; nunca lo sustituye, y `role` es el campo que dice qué clase de mejora cabe esperar. Un agente que lea la tabla como un catálogo de bloques se irá a buscar una portada a shadcn/ui y encontrará `/blocks/login`. + +Las licencias tampoco son uniformes. Cuatro son MIT; Transitions usa una licencia propia que prohíbe redistribuir una parte sustancial de la colección, así que sus fragmentos se pueden usar en un sitio pero no incorporarse a este repositorio. + +Cada url y cada endpoint de esa tabla se obtuvieron y comprobaron en vez de recordarse, y aun así acabarán pudriéndose: + +```bash +npm run sources # vuelve a pedir cada endpoint e informa de cuántos componentes sigue listando +``` + ## Los temas son datos

@@ -257,7 +297,7 @@ La auditoría necesita el servidor en marcha y `npx playwright install chromium` ```bash -npm test # 125, unos 4 s, sin red +npm test # 199, unos 1,5 s, sin red ``` Cubren **las tres reglas recuperadas del modelo**: el número de argumentos decide rejilla o lista, el número de planes decide tarjeta única o comparativa, y la existencia de una captura de interfaz decide la composición de la portada. Si alguna se desvía, la decisión vuelve en silencio a un modelo que no puede tomarla, así que son las que no deben moverse. @@ -291,8 +331,11 @@ lib/ edit.ts reconocimiento de intención de edición (abanico especulativo) export.ts HTML autocontenido, solo con el CSS en uso export-tsx.ts exportación de fuente React, DOM → JSX + export-registry.ts el mismo código como elemento de registro shadcn, con los tokens + export-agents.ts AGENTS.md: spec, tokens, bloques y de dónde salen los componentes i18n.ts idioma de la interfaz, lee locales/*.json demo.ts reproduce fixtures/ cuando no hay claves + sources.ts cinco bibliotecas de componentes de las que puede tirar un agente, con papeles y advertencias *.test.ts pruebas de lógica pura, sin red locales/ en|zh|ja|ko|es|fr|de|pt.json traducciones de la interfaz, zh es la referencia @@ -315,7 +358,7 @@ app/ ## Contribuir -Ver [CONTRIBUTING.md](../CONTRIBUTING.md). Añadir un bloque, un tema o un idioma de interfaz tiene cada uno un camino corto y establecido. +Ver [CONTRIBUTING.md](../CONTRIBUTING.md). Añadir un bloque, un tema, un idioma de interfaz o una fuente de componentes tiene cada uno un camino corto y establecido. ## Star History diff --git a/docs/README.fr.md b/docs/README.fr.md index 6aa72ee..95b8017 100644 --- a/docs/README.fr.md +++ b/docs/README.fr.md @@ -175,13 +175,15 @@ L'interface de l'éditeur est une autre affaire : huit langues, choisies d'aprè ## Export -Trois formats, tous issus **du même rendu**. Il n'existe pas de seconde copie du code de mise en page. +Cinq formats, tous issus **du même rendu**. Il n'existe pas de seconde copie du code de mise en page. | Export | Taille | Pour | |---|---|---| | `site.html` | 36 Ko | Le mettre en ligne, ou simplement double-cliquer | | `Site.tsx` | 34 Ko | Continuer à développer ; compile sous `tsc --strict` | | `spec.json` | quelques Ko | L'archiver, ou alimenter un autre moteur de rendu | +| `site.registry.json` | `Site.tsx`, emballé | Installer la page dans un projet qui utilise déjà shadcn/ui | +| `AGENTS.md` | une page | Confier la page à un agent de code : tokens, blocs, et d'où viennent les composants | ### Site.tsx @@ -207,6 +209,44 @@ Le filtrage teste chaque sélecteur avec `root.matches()` / `root.querySelector( En taille, cela ne fait gagner que 16 % (Tailwind n'a jamais été le problème). Le vrai gain, c'est que le site exporté ne traîne plus le style de l'éditeur. Voir `lib/export.ts` ; **il n'y a pas de second moteur de rendu**, la mise en page des blocs n'existe que dans `app/registry.tsx`. +### site.registry.json + +Un élément de [registre shadcn](https://ui.shadcn.com/docs/registry) : la page s'installe donc comme n'importe quel composant shadcn. + +```bash +npx shadcn@latest add ./site.registry.json +``` + +Une seule commande écrit le composant dans le répertoire que le `components.json` du projet appelle composants, et fusionne les 17 tokens du thème dans sa feuille de style. La liste de dépendances est vide exprès : `Site.tsx` importe un type de React et rien d'autre, et la remplir ferait installer à la CLI des paquets que le fichier n'utilise pas. La CLI accepte un chemin local, donc rien n'a besoin d'être hébergé au préalable : le fichier que le navigateur vient de télécharger fonctionne là où il a atterri. + +L'élément embarque le même source `Site.tsx` ; ce n'est pas un second rendu de la page. Les tokens voyagent avec lui sous forme de `cssVars`, parce qu'un composant déposé dans un projet qui définit ses propres variables s'affiche aux couleurs de ce projet — et ce n'est pas la page que quelqu'un a exportée. Ils sont écrits sans le `--` initial, que la CLI ajoute elle-même : noté `--accent`, le token arrive côté Tailwind sous la forme `var(----accent)`, ne résout rien, et l'installation annonce quand même une réussite. + +### AGENTS.md + +Une note brève pour l'agent de code qui récupère l'export : `spec.json` fait foi pour décrire la page, voici les 17 tokens du thème avec leurs valeurs, voici les blocs réellement présents sur cette page, et voici les sources de composants pertinentes pour ces blocs. C'est écrit pour être lu une fois avant de commencer, pas comme une documentation destinée à une personne. + +## Des composants à voler + +La méthode est la paresseuse : indiquer une bonne bibliothèque à un agent de code et le laisser choisir, adapter et coller. `lib/sources.ts` est le tableau qu'il lit : cinq bibliothèques, chacune avec son rôle, sa licence, sa commande d'installation, les endpoints lisibles par une machine qui ont répondu lors de la vérification, les slots qu'elle peut améliorer, et la mise en garde qui mord. + +| Source | Ce que c'est | Comment l'obtenir | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 primitives React accessibles au-dessus de Radix, plus la spécification de registre que visent les quatre autres | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 composants animés servis comme registre compatible shadcn, avec un endpoint MCP | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | Environ 20 widgets animés en un seul fichier — nav gluante, barre latérale de proximité, compteur à odomètre | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | Environ 44 extraits de mouvement nommés, en CSS pur, dans l'espace de noms `.t-*` | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 primitives pour interfaces d'applications d'IA | Copier-coller depuis le navigateur ; ni CLI ni registre | + +**Aucune des cinq ne fournit de section de page marketing.** Pas d'en-tête, pas de témoignages, pas de grille d'équipe, pas de pied de page dans tout l'ensemble : ce sont des primitives, du mouvement et des widgets en forme d'application. Une source améliore donc un bloc que loom affiche déjà ; elle ne le remplace jamais, et `role` est le champ qui dit de quelle sorte d'amélioration il s'agit. Un agent qui lit ce tableau comme un catalogue de blocs ira chercher un en-tête dans shadcn/ui et trouvera `/blocks/login`. + +Les licences ne sont pas uniformes non plus. Quatre sont MIT ; Transitions est une licence propre qui interdit de redistribuer une partie substantielle de la collection, donc ses extraits peuvent servir sur un site mais ne doivent pas être embarqués dans ce dépôt. + +Chaque url et chaque endpoint de ce tableau ont été récupérés et vérifiés plutôt que retrouvés de mémoire, et ils finiront quand même par pourrir : + +```bash +npm run sources # redemande chaque endpoint et indique combien de composants il liste encore +``` + ## Les thèmes sont des données

@@ -258,7 +298,7 @@ L'audit a besoin d'un serveur lancé et de `npx playwright install chromium`, il ```bash -npm test # 125, environ 4 s, sans réseau +npm test # 199, environ 1,5 s, sans réseau ``` Ils couvrent **les trois règles reprises au modèle** : le nombre d'arguments décide grille ou liste, le nombre de paliers décide carte unique ou comparatif, et la présence d'une capture d'interface décide la mise en page de l'en-tête. Si l'une dérive, la décision retourne en silence à un modèle incapable de la prendre : ce sont celles qui ne doivent pas bouger. @@ -292,8 +332,11 @@ lib/ edit.ts reconnaissance de l'intention de modification (éventail spéculatif) export.ts HTML autonome, seulement le CSS utilisé export-tsx.ts export de source React, DOM → JSX + export-registry.ts le même source en élément de registre shadcn, tokens compris + export-agents.ts AGENTS.md : spec, tokens, blocs, et d'où viennent les composants i18n.ts langue de l'interface, lit locales/*.json demo.ts rejoue fixtures/ en l'absence de clés + sources.ts cinq bibliothèques de composants où un agent peut puiser, avec rôles et mises en garde *.test.ts tests de logique pure, sans réseau locales/ en|zh|ja|ko|es|fr|de|pt.json traductions de l'interface, zh fait référence @@ -316,7 +359,7 @@ app/ ## Contribuer -Voir [CONTRIBUTING.md](../CONTRIBUTING.md). Ajouter un bloc, un thème ou une langue d'interface suit à chaque fois un chemin court et balisé. +Voir [CONTRIBUTING.md](../CONTRIBUTING.md). Ajouter un bloc, un thème, une langue d'interface ou une source de composants suit à chaque fois un chemin court et balisé. ## Star History diff --git a/docs/README.ja.md b/docs/README.ja.md index 0025d32..12c6640 100644 --- a/docs/README.ja.md +++ b/docs/README.ja.md @@ -176,13 +176,15 @@ A small bakery in Brooklyn → en locale ## 書き出し -三種類、すべて**同じ描画結果**から作られます。レイアウトのコードが二重に存在することはありません。 +五種類、すべて**同じ描画結果**から作られます。レイアウトのコードが二重に存在することはありません。 | 書き出し | サイズ | 用途 | |---|---|---| | `site.html` | 36 KB | そのまま公開、ダブルクリックでも開く | | `Site.tsx` | 34 KB | 開発を続ける用。`tsc --strict` を通る | | `spec.json` | 数 KB | 保管、あるいは別のレンダラへ | +| `site.registry.json` | `Site.tsx` を包んだもの | すでに shadcn/ui を使っているプロジェクトへ導入する | +| `AGENTS.md` | 1 ページ | コーディングエージェントに渡す用。トークン、ブロック、コンポーネントの出どころ | ### Site.tsx @@ -208,6 +210,44 @@ A small bakery in Brooklyn → en locale サイズ削減は 16% ほど(Tailwind はもともと大きくない)。本当の収穫は、書き出したサイトにエディタ自身の見た目が混ざらなくなったことです。実装は `lib/export.ts`。**第二のレンダラは存在せず**、ブロックのレイアウトは `app/registry.tsx` の一箇所だけです。 +### site.registry.json + +[shadcn registry](https://ui.shadcn.com/docs/registry) の item です。つまりこのページは、shadcn のコンポーネントと同じ手順で導入できます。 + +```bash +npx shadcn@latest add ./site.registry.json +``` + +一つのコマンドが、プロジェクトの `components.json` がコンポーネント置き場と呼んでいるディレクトリへコンポーネントを書き込み、テーマの 17 個のトークンをそのスタイルシートへ統合します。依存関係の一覧は意図的に空です。`Site.tsx` が読み込むのは React の型ひとつだけで、そこに何かを足せば、ファイルが使いもしないパッケージを CLI に入れさせることになります。CLI はローカルパスを受け取るので、先にどこかへ置く必要はありません——ブラウザがダウンロードしたそのファイルを、その場所のまま使えます。 + +item が抱えているのは同じ `Site.tsx` のソースであって、ページの二度目の描画ではありません。トークンは `cssVars` として一緒に運ばれます。自前の変数を定義しているプロジェクトに落とされたコンポーネントは、そのプロジェクトの色で描画されてしまい、それは誰かが書き出したページではないからです。キーは先頭の `--` を付けずに書きます。そこは CLI が足す部分で、`--accent` と書くとトークンは Tailwind 側で `var(----accent)` になり、何にも解決しないまま、インストールは成功したと報告します。 + +### AGENTS.md + +書き出しを受け取るコーディングエージェント向けの短い説明書です。`spec.json` がこのページの正本であること、テーマの 17 個のトークンとその値、このページに実際にあるブロック、そしてそれらのブロックに関係するコンポーネントの供給元。作業を始める前に一度読ませるためのもので、人間向けのドキュメントではありません。 + +## 盗む価値のあるコンポーネント + +やり方は横着なものです——良いライブラリをコーディングエージェントに教え、選ぶのも直すのも貼るのも任せる。`lib/sources.ts` はそのとき読ませる表です。五つのライブラリについて、役割、ライセンス、インストールコマンド、確認した時点で実際に応答した機械可読なエンドポイント、改善できるスロット、そして噛みつく注意点が載っています。 + +| 供給元 | 中身 | 入手手段 | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | Radix の上に載った 63 個のアクセシブルな React プリミティブと、他の四つが揃えにいく registry 仕様 | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 個のアニメーション付きコンポーネント。shadcn 互換の registry と MCP エンドポイント付き | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | 単一ファイルのアニメーション部品が約 20 個——ぬるりと動くナビ、近接反応サイドバー、オドメーター | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | 名前の付いたモーションが約 44 種。素の CSS で、`.t-*` の名前空間 | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | AI アプリケーションの画面向けプリミティブが 21 個 | ブラウザからのコピー&ペーストのみ。CLI も registry も無い | + +**五つのどれ一つとして、マーケティングページのセクションを持っていません。** ファーストビューも、お客様の声も、チーム紹介も、フッターも、この五つのどこにもありません——あるのはプリミティブ、モーション、そしてアプリ寄りの部品です。つまりある供給元は loom がすでに描いているブロックを良くするのであって、置き換えるのではありません。どちらの改善なのかを言っているのが `role` です。この表をブロックのカタログとして読むエージェントは、shadcn/ui にファーストビューを探しに行き、`/blocks/login` を見つけることになります。 + +ライセンスも揃っていません。四つは MIT ですが、Transitions は独自ライセンスで、コレクションの実質的な部分の再配布を禁じています。サイトで使うのは構いませんが、このリポジトリに同梱してはいけません。 + +表にある url とエンドポイントはすべて、記憶ではなく実際に取得して確認したものです。それでもいずれ腐ります。 + +```bash +npm run sources # 各エンドポイントを取り直し、いま何個のコンポーネントを列挙しているかを報告する +``` + ## テーマはデータ

@@ -260,7 +300,7 @@ npm run audit:a11y # 生成結果に axe-core、6 テーマすべて ```bash -npm test # 125 件、約 4 秒、ネットワーク不使用 +npm test # 199 件、約 1.5 秒、ネットワーク不使用 ``` 中心は**モデルから取り戻した三つの規則**です——売りの個数がグリッドかリストかを決め、料金段階数が単一か比較かを決め、画面写真の有無がファーストビューの版を決める。ここが戻ると、判断は答えられないモデルに黙って返されてしまうので、最も動いてはいけない部分です。 @@ -294,7 +334,10 @@ lib/ edit.ts 修正意図の識別(投機的ファンアウト) export.ts 自己完結 HTML、使っている CSS だけ export-tsx.ts React ソース書き出し、DOM → JSX + export-registry.ts 同じソースを shadcn registry item に。テーマトークン込み + export-agents.ts AGENTS.md:spec、トークン、ブロック、コンポーネントの出どころ i18n.ts UI 言語、locales/*.json を読む + sources.ts エージェントが取りに行ける五つのコンポーネント供給元、役割と注意点つき *.test.ts 純粋ロジックのテスト、ネットワーク不使用 locales/ en|zh|ja|ko|es|fr|de|pt.json UI 翻訳、zh が基準 @@ -315,7 +358,7 @@ app/ ## 参加する -[CONTRIBUTING.md](../CONTRIBUTING.md) を参照してください。ブロック・テーマ・UI 言語の追加には、それぞれ短い定石があります。 +[CONTRIBUTING.md](../CONTRIBUTING.md) を参照してください。ブロック・テーマ・UI 言語・コンポーネント供給元の追加には、それぞれ短い定石があります。 ## Star History diff --git a/docs/README.ko.md b/docs/README.ko.md index d495a94..eb417e7 100644 --- a/docs/README.ko.md +++ b/docs/README.ko.md @@ -176,13 +176,15 @@ A small bakery in Brooklyn → en locale ## 내보내기 -세 가지, 모두 **같은 렌더링 결과**에서 나옵니다. 레이아웃 코드가 두 벌 존재하지 않습니다. +다섯 가지, 모두 **같은 렌더링 결과**에서 나옵니다. 레이아웃 코드가 두 벌 존재하지 않습니다. | 내보내기 | 크기 | 용도 | |---|---|---| | `site.html` | 36 KB | 그대로 올리거나 더블클릭으로 열기 | | `Site.tsx` | 34 KB | 이어서 개발. `tsc --strict` 통과 | | `spec.json` | 수 KB | 보관하거나 다른 렌더러에 투입 | +| `site.registry.json` | `Site.tsx` 를 감싼 것 | 이미 shadcn/ui 를 쓰는 프로젝트에 설치 | +| `AGENTS.md` | 한 쪽 | 코딩 에이전트에게 넘기기: 토큰, 블록, 컴포넌트 출처 | ### Site.tsx @@ -208,6 +210,44 @@ A small bakery in Brooklyn → en locale 크기로는 16% 정도만 줄어듭니다 (Tailwind는 원래 크지 않았습니다). 진짜 수확은 내보낸 사이트에 에디터 자신의 스타일이 섞이지 않게 된 것입니다. 구현은 `lib/export.ts`. **두 번째 렌더러는 없고**, 블록 레이아웃은 `app/registry.tsx` 한 곳뿐입니다. +### site.registry.json + +[shadcn registry](https://ui.shadcn.com/docs/registry) 항목입니다. 그래서 이 페이지는 여느 shadcn 컴포넌트와 똑같은 방식으로 설치됩니다. + +```bash +npx shadcn@latest add ./site.registry.json +``` + +명령 하나가 프로젝트의 `components.json` 이 컴포넌트 폴더라고 부르는 곳에 컴포넌트를 쓰고, 테마의 토큰 17개를 그 스타일시트에 합칩니다. 의존성 목록은 일부러 비워 두었습니다. `Site.tsx` 는 React 에서 타입 하나만 가져올 뿐이고, 목록을 채우면 파일이 쓰지도 않는 패키지를 CLI 가 설치하게 됩니다. CLI 가 로컬 경로를 받으므로 어딘가에 먼저 올릴 필요가 없습니다 — 브라우저가 방금 내려받은 그 파일을, 내려받은 자리에서 그대로 씁니다. + +항목이 품고 있는 것은 같은 `Site.tsx` 소스이지 페이지를 두 번째로 렌더링한 결과가 아닙니다. 토큰은 `cssVars` 로 함께 따라갑니다. 자기 변수를 정의해 둔 프로젝트에 떨어진 컴포넌트는 그 프로젝트의 색으로 그려지고, 그건 누구도 내보낸 적 없는 페이지이기 때문입니다. 키는 앞의 `--` 없이 씁니다. 그 두 글자는 CLI 가 붙이는 몫이라, `--accent` 라고 쓰면 토큰은 Tailwind 쪽에서 `var(----accent)` 가 되어 아무것도 가리키지 못하는데, 설치는 그래도 성공했다고 보고합니다. + +### AGENTS.md + +내보낸 결과를 집어 드는 코딩 에이전트를 위한 짧은 브리핑입니다. `spec.json` 이 이 페이지의 정본이라는 것, 테마의 토큰 17개와 그 값, 이 페이지에 실제로 있는 블록, 그리고 그 블록들과 관련된 컴포넌트 출처. 작업을 시작하기 전에 한 번 읽히려고 쓴 것이지, 사람을 위한 문서가 아닙니다. + +## 훔칠 만한 컴포넌트 + +방식은 게으른 쪽입니다 — 괜찮은 라이브러리를 코딩 에이전트에게 알려 주고, 고르고 고치고 붙여 넣는 일을 맡깁니다. `lib/sources.ts` 가 에이전트가 읽는 표입니다. 라이브러리 다섯 곳 각각의 역할, 라이선스, 설치 명령, 확인 당시 실제로 응답한 기계 판독용 엔드포인트, 개선할 수 있는 슬롯, 그리고 무는 주의사항이 들어 있습니다. + +| 출처 | 무엇인가 | 가져오는 법 | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | Radix 위에 올린 접근성 React 프리미티브 63개, 그리고 나머지 넷이 맞추는 registry 명세 | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 애니메이션 컴포넌트 85개. shadcn 호환 registry 와 MCP 엔드포인트까지 | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | 단일 파일 애니메이션 위젯 약 20개 — 끈적이는 내비, 근접 반응 사이드바, 오도미터 카운터 | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | 이름 붙은 모션 스니펫 약 44개. 순수 CSS, `.t-*` 네임스페이스 | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | AI 애플리케이션 화면용 프리미티브 21개 | 브라우저에서 복사·붙여넣기만. CLI 도 registry 도 없음 | + +**다섯 곳 중 어디도 마케팅 페이지 섹션을 제공하지 않습니다.** 첫 화면도, 고객 후기도, 팀 소개도, 푸터도 이 다섯 곳 어디에도 없습니다 — 있는 것은 프리미티브와 모션, 그리고 앱 모양의 위젯입니다. 그래서 어떤 출처는 loom 이 이미 그리고 있는 블록을 개선할 뿐, 대체하지 않습니다. 어느 쪽 개선인지를 말해 주는 필드가 `role` 입니다. 이 표를 블록 카탈로그로 읽는 에이전트는 shadcn/ui 에서 첫 화면을 찾다가 `/blocks/login` 을 만나게 됩니다. + +라이선스도 균일하지 않습니다. 넷은 MIT 이고, Transitions 는 컬렉션의 실질적인 부분을 재배포하는 것을 금지하는 자체 라이선스입니다. 사이트에 쓰는 것은 되지만 이 저장소에 담아 함께 배포해서는 안 됩니다. + +표에 있는 url 과 엔드포인트는 기억이 아니라 실제로 가져와 확인한 것입니다. 그래도 언젠가는 썩습니다. + +```bash +npm run sources # 각 엔드포인트를 다시 불러, 지금 몇 개의 컴포넌트를 나열하는지 보고 +``` + ## 테마는 데이터

@@ -260,7 +300,7 @@ npm run audit:a11y # 생성 결과에 axe-core, 여섯 테마 전부 ```bash -npm test # 125개, 약 4초, 네트워크 미사용 +npm test # 199개, 약 1.5초, 네트워크 미사용 ``` 핵심은 **모델에게서 되찾아온 세 규칙**입니다 — 강점 개수가 그리드냐 리스트냐를, 요금 단계 수가 단일이냐 비교냐를, 화면 스크린샷 유무가 첫 화면 판을 정합니다. 여기가 되돌아가면 결정이 답할 수 없는 모델에게 조용히 넘어가므로, 가장 흔들리면 안 되는 부분입니다. @@ -294,7 +334,10 @@ lib/ edit.ts 수정 의도 식별 (투기적 팬아웃) export.ts 자기완결 HTML, 쓰이는 CSS만 export-tsx.ts React 소스 내보내기, DOM → JSX + export-registry.ts 같은 소스를 shadcn registry 항목으로, 테마 토큰 포함 + export-agents.ts AGENTS.md: spec, 토큰, 블록, 컴포넌트 출처 i18n.ts UI 언어, locales/*.json 을 읽음 + sources.ts 에이전트가 가져다 쓸 수 있는 컴포넌트 출처 다섯 곳, 역할과 주의사항 포함 *.test.ts 순수 로직 테스트, 네트워크 미사용 locales/ en|zh|ja|ko|es|fr|de|pt.json UI 번역, zh 가 기준 @@ -315,7 +358,7 @@ app/ ## 기여 -[CONTRIBUTING.md](../CONTRIBUTING.md) 를 참고하세요. 블록·테마·UI 언어 추가에는 각각 짧고 정해진 경로가 있습니다. +[CONTRIBUTING.md](../CONTRIBUTING.md) 를 참고하세요. 블록·테마·UI 언어·컴포넌트 출처 추가에는 각각 짧고 정해진 경로가 있습니다. ## Star History diff --git a/docs/README.pt.md b/docs/README.pt.md index 1456f7a..28b1ff3 100644 --- a/docs/README.pt.md +++ b/docs/README.pt.md @@ -174,13 +174,15 @@ A interface do editor é outra história: oito idiomas, escolhidos a partir de ` ## Exportação -Três formatos, todos derivados **do mesmo resultado renderizado**. Não existe uma segunda cópia do código de layout. +Cinco formatos, todos derivados **do mesmo resultado renderizado**. Não existe uma segunda cópia do código de layout. | Exportação | Tamanho | Para | |---|---|---| | `site.html` | 36 KB | Subir para a web, ou só dar dois cliques | | `Site.tsx` | 34 KB | Continuar desenvolvendo; compila com `tsc --strict` | | `spec.json` | alguns KB | Arquivar, ou alimentar outro renderizador | +| `site.registry.json` | `Site.tsx`, embrulhado | Instalar a página num projeto que já usa shadcn/ui | +| `AGENTS.md` | uma página | Entregar a página a um agente de código: tokens, blocos e de onde vêm os componentes | ### Site.tsx @@ -206,6 +208,44 @@ O filtro testa cada seletor com `root.matches()` / `root.querySelector()`, remov Em tamanho economiza só 16 % (o Tailwind nunca foi o problema). O ganho real é que o site exportado não carrega mais o estilo do próprio editor. Veja `lib/export.ts`; **não há um segundo renderizador**, o layout dos blocos existe apenas em `app/registry.tsx`. +### site.registry.json + +Um item de [registro shadcn](https://ui.shadcn.com/docs/registry), então a página se instala como qualquer componente shadcn: + +```bash +npx shadcn@latest add ./site.registry.json +``` + +Um único comando escreve o componente no diretório que o `components.json` do projeto chama de componentes e funde os 17 tokens do tema com a folha de estilo dele. A lista de dependências está vazia de propósito: o `Site.tsx` importa um tipo do React e mais nada, e enchê-la faria a CLI instalar pacotes que o arquivo não usa. A CLI aceita um caminho local, então nada precisa ser hospedado antes — o arquivo que o navegador acabou de baixar serve de onde caiu. + +O item carrega o mesmo código de `Site.tsx`; não é uma segunda renderização da página. Os tokens viajam junto como `cssVars` porque um componente largado num projeto que define as próprias variáveis é desenhado com as cores daquele projeto, e essa não é a página que alguém exportou. As chaves vão sem o `--` inicial, que é justamente o que a CLI acrescenta: escrito `--accent`, o token chega à ponte do Tailwind como `var(----accent)`, não resolve nada, e a instalação ainda assim relata sucesso. + +### AGENTS.md + +Um informe curto para o agente de código que pega a exportação: `spec.json` é a descrição autoritativa da página, aqui estão os 17 tokens do tema com seus valores, aqui estão os blocos que esta página realmente tem, e aqui estão as fontes de componentes relevantes para esses blocos. Foi escrito para ser lido uma vez antes de começar, não como documentação para uma pessoa. + +## Componentes que vale a pena roubar + +O método é o preguiçoso: apontar uma boa biblioteca para um agente de código e deixar que ele escolha, adapte e cole. `lib/sources.ts` é a tabela que ele lê: cinco bibliotecas, cada uma com seu papel, sua licença, seu comando de instalação, os endpoints legíveis por máquina que responderam quando foram conferidos, os slots que ela pode melhorar e a ressalva que morde. + +| Fonte | O que é | Como se pega | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 primitivos React acessíveis sobre o Radix, mais a especificação de registro que as outras quatro seguem | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 componentes animados como registro compatível com shadcn, com endpoint MCP | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | Cerca de 20 widgets animados de arquivo único — navegação gosmenta, barra lateral por proximidade, contador de odômetro | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | Cerca de 44 trechos de movimento nomeados, em CSS puro, no espaço de nomes `.t-*` | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 primitivos para interfaces de aplicações de IA | Copiar e colar pelo navegador; sem CLI, sem registro | + +**Nenhuma das cinco traz uma seção de página de marketing.** Não há topo, nem depoimentos, nem grade de equipe, nem rodapé em todo o conjunto — são primitivos, movimento e widgets em formato de aplicativo. Então uma fonte melhora um bloco que o loom já desenha; ela nunca o substitui, e `role` é o campo que diz que tipo de melhoria esperar. Um agente que leia a tabela como um catálogo de blocos vai procurar um topo no shadcn/ui e encontrar `/blocks/login`. + +As licenças também não são uniformes. Quatro são MIT; a Transitions tem licença própria, que proíbe redistribuir parte substancial da coleção, então seus trechos podem ser usados num site mas não embutidos neste repositório. + +Cada url e cada endpoint dessa tabela foram buscados e conferidos em vez de lembrados, e ainda assim vão apodrecer: + +```bash +npm run sources # busca cada endpoint de novo e informa quantos componentes ele ainda lista +``` + ## Temas são dados

@@ -257,7 +297,7 @@ A auditoria precisa do servidor no ar e de `npx playwright install chromium`, po ```bash -npm test # 125 deles, cerca de 4 s, sem rede +npm test # 199 deles, cerca de 1,5 s, sem rede ``` Eles cobrem **as três regras retomadas do modelo**: a quantidade de diferenciais decide grade ou lista, a quantidade de planos decide cartão único ou comparativo, e a existência de uma captura de interface decide o layout do topo. Se alguma delas escorregar, a decisão volta em silêncio para um modelo que não consegue tomá-la — são as que não podem se mexer. @@ -291,8 +331,11 @@ lib/ edit.ts reconhecimento da intenção de edição (fan-out especulativo) export.ts HTML autocontido, só com o CSS em uso export-tsx.ts exportação de fonte React, DOM → JSX + export-registry.ts o mesmo código como item de registro shadcn, com os tokens + export-agents.ts AGENTS.md: spec, tokens, blocos e de onde vêm os componentes i18n.ts idioma da interface, lê locales/*.json demo.ts reproduz fixtures/ quando não há chaves + sources.ts cinco bibliotecas de componentes de onde um agente pode puxar, com papéis e ressalvas *.test.ts testes de lógica pura, sem rede locales/ en|zh|ja|ko|es|fr|de|pt.json traduções da interface, zh é a referência @@ -315,7 +358,7 @@ app/ ## Contribuir -Veja [CONTRIBUTING.md](../CONTRIBUTING.md). Acrescentar um bloco, um tema ou um idioma de interface tem, cada um, um caminho curto e já definido. +Veja [CONTRIBUTING.md](../CONTRIBUTING.md). Acrescentar um bloco, um tema, um idioma de interface ou uma fonte de componentes tem, cada um, um caminho curto e já definido. ## Star History diff --git a/docs/README.zh.md b/docs/README.zh.md index 7809082..177067c 100644 --- a/docs/README.zh.md +++ b/docs/README.zh.md @@ -176,13 +176,15 @@ A small bakery in Brooklyn → en locale ## 导出 -三种,都从**同一份渲染结果**生成,不存在第二套布局代码。 +五种,都从**同一份渲染结果**生成,不存在第二套布局代码。 | 导出 | 大小 | 给谁 | |---|---|---| | `site.html` | 36 KB | 直接挂上去,双击就开 | | `Site.tsx` | 34 KB | 拿去继续开发,`tsc --strict` 编译通过 | | `spec.json` | 几 KB | 存起来或喂给别的渲染器 | +| `site.registry.json` | `Site.tsx` 包一层 | 装进已经在用 shadcn/ui 的项目 | +| `AGENTS.md` | 一页 | 把页面交给 coding agent:token、区块、组件从哪来 | ### Site.tsx @@ -208,6 +210,44 @@ A small bakery in Brooklyn → en locale 体积上只省 16%(Tailwind 本来就不大),真正的收获是导出的网站里不再混进编辑器自己的样式。实现见 `lib/export.ts`,**没有第二套渲染器**,区块布局只有 `app/registry.tsx` 一份。 +### site.registry.json + +一个 [shadcn registry](https://ui.shadcn.com/docs/registry) item,所以这个页面按任何 shadcn 组件的方式安装: + +```bash +npx shadcn@latest add ./site.registry.json +``` + +一条命令把组件写进项目 `components.json` 指定的组件目录,并把主题的 17 个 token 合进它的样式表。依赖列表是故意留空的:`Site.tsx` 只从 React 引入一个类型,别的什么都不引,往列表里塞东西只会让 CLI 装上这个文件根本不用的包。CLI 接受本地路径,所以不用先找地方托管——浏览器刚下载下来的那个文件,落在哪就能从哪装。 + +item 里带的就是同一份 `Site.tsx` 源码,不是页面的第二次渲染。token 以 `cssVars` 一起走,因为组件丢进一个自己定义了变量的项目,会按那个项目的颜色渲染,那就不是任何人导出的那个页面了。key 不带前面的 `--`,那两个短横由 CLI 自己补:写成 `--accent`,token 到了 Tailwind 那一层就成了 `var(----accent)`,解析不出任何东西,而安装照样报成功。 + +### AGENTS.md + +给接手这份导出的 coding agent 的一页简报:`spec.json` 是这个页面的权威描述,主题的 17 个 token 连同取值,这个页面实际有哪些区块,以及和这些区块相关的组件来源。它是写给动手之前读一遍的,不是给人看的文档。 + +## 值得抄的组件 + +懒人玩法:把 coding agent 指到一个好库上,让它自己挑、自己改、自己贴进来。`lib/sources.ts` 就是它读的那张表:五个库,每个都带角色、许可证、安装命令、核对时确实有响应的机器可读端点、能改进哪些槽位,以及会咬人的那条注意事项。 + +| 来源 | 是什么 | 怎么拿 | +|---|---|---| +| [shadcn/ui](https://ui.shadcn.com) | 63 个基于 Radix 的无障碍 React 基础组件,外加另外四家都在对齐的 registry 规范 | `npx shadcn@latest add ` | +| [beUI](https://beui.dev) | 85 个带动效的组件,shadcn 兼容的 registry,还有 MCP 端点 | `npx shadcn@latest add https://beui.dev/r/.json` | +| [Rare UI](https://rareui.com) | 约 20 个单文件动效小部件——粘液态导航、临近感应侧栏、里程表计数 | `npx shadcn@latest add swamimalode07/rare-ui/` | +| [Transitions](https://transitions.dev) | 约 44 段有名字的动效,纯 CSS,`.t-*` 命名空间 | `npx transitions-dev add ` | +| [Beautiful UI](https://beautifului.dev) | 21 个面向 AI 应用界面的基础组件 | 只能从浏览器里复制粘贴,没有 CLI,没有 registry | + +**五个里没有一个提供落地页区块。** 整套里找不到首屏、客户评价、团队墙和页脚——它们是基础组件、动效和应用形态的小部件。所以一个来源改进的是 loom 已经在渲染的区块,而不是替换它,`role` 这个字段说的正是该期待哪一种改进。把这张表当区块目录读的 agent,会跑去 shadcn/ui 找首屏,然后找到 `/blocks/login`。 + +许可证也不齐。四个是 MIT;Transitions 是自定义许可证,禁止再分发这套集合的实质部分,所以它的片段可以用在站点上,但不能内嵌进这个仓库。 + +表里每个 url 和端点都是真去取过、核对过的,不是凭印象写的,而且它们早晚会失效: + +```bash +npm run sources # 逐个重新请求端点,报出各家现在还列着多少组件 +``` + ## 主题即数据

@@ -260,7 +300,7 @@ npm run audit:a11y # axe-core 扫生成结果,六套主题全过一遍 ```bash -npm test # 125 个,约 4 秒,不碰网络 +npm test # 199 个,约 1.5 秒,不碰网络 ``` 测的是**三条被从模型手里拿回来的规则**——卖点条数决定网格还是列表、价格档数决定单档还是对比、有没有界面截图决定首屏版式。这几条一旦回归,决策就悄悄还给了一个答不了的模型,所以它们最不该漂。 @@ -294,8 +334,11 @@ lib/ edit.ts 修改意图识别(投机扇出) export.ts 自包含 HTML 导出,只带用到的 CSS export-tsx.ts React 源码导出,DOM → JSX + export-registry.ts 同一份源码打成 shadcn registry item,带上主题 token + export-agents.ts AGENTS.md:spec、token、区块、组件从哪来 i18n.ts 界面语言,读 locales/*.json demo.ts 无 key 时回放 fixtures/ 里的真实录制 + sources.ts 五个可供 agent 取用的组件库,带角色和注意事项 *.test.ts 纯逻辑的测试,不碰网络 locales/ en|zh|ja|ko|es|fr|de|pt.json 界面翻译,zh 为基准 @@ -318,7 +361,7 @@ app/ ## 参与 -改动请看 [CONTRIBUTING.md](../CONTRIBUTING.md)。加区块、加主题、加界面语言各有一条既定路径,都不长。 +改动请看 [CONTRIBUTING.md](../CONTRIBUTING.md)。加区块、加主题、加界面语言、加组件来源各有一条既定路径,都不长。 ## Star History diff --git a/lib/export-agents.test.ts b/lib/export-agents.test.ts new file mode 100644 index 0000000..1e1d0df --- /dev/null +++ b/lib/export-agents.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from "vitest"; +import { SLOT_ORDER, type SlotKey } from "@/lib/plan"; +import { COMPONENT_SOURCES, sourcesFor } from "@/lib/sources"; +import { themeVars } from "@/lib/themes"; +import { buildAgentsMd } from "./export-agents"; + +/** + * The brief is only worth its lines if every line is load-bearing, so these check the four facts an agent acts on: which file it may edit, which variables it must write against, which blocks it has, and which sources are real. A wrong value here is worse than no file at all — it sends the agent off confidently in the wrong direction. + */ +function page(): Element { + const host = document.createElement("div"); + host.innerHTML = `

hero
`; + return host.firstElementChild!; +} + +/** `team` is in here deliberately: it is the one slot no source in the table covers. */ +const SLOTS = ["nav", "hero", "features", "team", "faq", "footer"]; + +const build = (theme = "forest", slots = SLOTS) => + buildAgentsMd(page(), "我开了家咖啡店", theme, slots); + +/** Table rows only, with the header and the separator dropped. */ +function rows(markdown: string): string[][] { + return markdown + .split("\n") + .filter((line) => line.startsWith("|")) + .map((line) => line.split("|").slice(1, -1).map((c) => c.trim())) + .filter((cells) => cells[0] !== "Source" && cells[0] !== "---"); +} + +describe("buildAgentsMd", () => { + it("names every block it was handed, so the agent's page and the brief's page are the same page", () => { + const markdown = build(); + for (const slot of SLOTS) expect(markdown, `${slot} is missing from the brief`).toContain(`\`${slot}\``); + }); + + it("lists the blocks in render order rather than the order it was handed them, because the brief claims they read top to bottom", () => { + // The caller passes the planning order, which is not the rendering order: `footer` is planned early in an edit session and always renders last. The first version printed the caller's order under the words "in that order". + const markdown = build("forest", ["footer", "hero", "nav", "faq"]); + const line = markdown.split("\n").find((l) => l.includes("top to bottom"))!; + expect(line).toContain("`nav`, `hero`, `faq`, `footer`"); + + const listed = [...line.matchAll(/`([a-z]+)`/g)].map((m) => m[1] as SlotKey); + const ranks = listed.map((slot) => SLOT_ORDER.indexOf(slot)); + expect(ranks, "a slot was printed out of SLOT_ORDER").toEqual([...ranks].sort((a, b) => a - b)); + }); + + it("keeps a slot it does not recognise, rather than silently dropping a block from the brief", () => { + // The unknown slot goes first on the way in, so only sorting can put it last on the way out. + const markdown = build("forest", ["not_a_slot", "footer", "nav"]); + const line = markdown.split("\n").find((l) => l.includes("top to bottom"))!; + expect(line).toContain("`not_a_slot`"); + expect(line.indexOf("`footer`")).toBeLessThan(line.indexOf("`not_a_slot`")); + }); + + it("keeps a block no source covers out of the table, so no row arrives with an empty cell", () => { + const markdown = build(); + expect(sourcesFor("team")).toHaveLength(0); + for (const cells of rows(markdown)) { + expect(cells).toHaveLength(5); + for (const cell of cells) expect(cell, `empty cell in row ${cells[0]}`).not.toBe(""); + expect(cells[2], "team reached the table despite having no source").not.toContain("`team`"); + } + expect(markdown).toContain("Nothing in the table below covers `team`"); + }); + + it("prints all seventeen tokens at the values the theme declares, so nothing has to be guessed", () => { + const markdown = build("forest"); + const vars = themeVars("forest"); + expect(Object.keys(vars)).toHaveLength(17); + for (const [name, value] of Object.entries(vars)) { + expect(markdown, `${name} is missing or wrong`).toContain(`${name}: ${value};`); + } + }); + + it("follows the theme it was given, so a retheme cannot leave the brief quoting the old palette", () => { + const terminal = build("terminal"); + expect(terminal).toContain(`--accent: ${themeVars("terminal")["--accent"]};`); + expect(terminal).not.toContain(`--accent: ${themeVars("forest")["--accent"]};`); + expect(terminal).toContain("`terminal` theme"); + }); + + it("offers no command for a source that has none, so nothing in the table fails when pasted", () => { + const markdown = build(); + const byName = new Map(Object.values(COMPONENT_SOURCES).map((s) => [s.name, s])); + for (const cells of rows(markdown)) { + const name = cells[0]!.replace(/^\[|\].*$/g, ""); + const source = byName.get(name)!; + const install = cells[3]!; + if (source.install) expect(install).toBe(`\`${source.install}\``); + else { + expect(install).not.toContain("npx"); + expect(install).not.toContain("`"); + expect(install).toContain("Browser only"); + } + } + }); + + it("carries the Transitions licence constraint through, because that one is a legal limit and not a caveat", () => { + const markdown = build(); + expect(markdown).toContain(COMPONENT_SOURCES.transitions!.license); + expect(markdown).toContain("vendoring the collection into anything you redistribute is not"); + }); + + it("says once that the TSX is generated, so the agent does not spend an afternoon on a file the next export overwrites", () => { + const markdown = build(); + expect(markdown).toContain("`spec.json` — the page as data"); + expect(markdown).toMatch(/`Site\.tsx`[^\n]*generated/); + expect(markdown).toContain("overwrites the file"); + }); + + it("states that the sources improve a block rather than replace one, so no time goes into hunting for a hero", () => { + const markdown = build(); + expect(markdown).toContain("None of them replaces one"); + expect(markdown).toMatch(/no hero, no testimonial block, no team grid and no footer section/); + }); + + it("never hard-wraps a paragraph, so the prose survives any editor's own wrapping", () => { + // A wrapped paragraph shows up as two adjacent prose lines. Tables, list items, headings and the token block all legitimately run line after line, so only plain prose is examined. + const lines = build().split("\n"); + let inCode = false; + let previousWasProse = false; + for (const line of lines) { + if (line.startsWith("```")) { + inCode = !inCode; + previousWasProse = false; + continue; + } + const prose = !inCode && line.trim() !== "" && !/^[|#\-]/.test(line); + expect(previousWasProse && prose, `hard-wrapped paragraph at: ${line.slice(0, 60)}`).toBe(false); + previousWasProse = prose; + } + }); + + it("builds a table with several rows from the fixture, so the checks above cannot pass on an empty document", () => { + const markdown = build(); + const table = rows(markdown); + expect(table.length).toBeGreaterThanOrEqual(3); + // The fixture has to contain all three shapes the checks depend on, or they each assert nothing. + expect(table.some((cells) => cells[3] === "Browser only — nothing to run")).toBe(true); + expect(table.some((cells) => cells[0]!.includes("Transitions"))).toBe(true); + expect(SLOTS.some((slot) => sourcesFor(slot as SlotKey).length === 0)).toBe(true); + expect(markdown.split("\n").length).toBeLessThanOrEqual(70); + }); +}); diff --git a/lib/export-agents.ts b/lib/export-agents.ts new file mode 100644 index 0000000..98f8f27 --- /dev/null +++ b/lib/export-agents.ts @@ -0,0 +1,139 @@ +import { SLOT_ORDER, type SlotKey } from "./plan"; +import { sourcesFor, type ComponentSource } from "./sources"; +import { THEMES, themeVars } from "./themes"; + +/** + * The brief that ships beside the other exports. + * + * The other three hand over a page; this hands over the context needed to keep working on it. AGENTS.md is a real convention that specifies almost nothing beyond the filename, which is an open invitation to emit Setup Commands / Testing / PR Guidelines headings — ceremony that costs the receiving agent context and says nothing true here, because what loom exports is three files in a folder, not a repo with a test suite and a PR process. + * + * So every section below exists to head off one mistake an agent predictably makes: hand-editing the generated TSX and losing the work on the next export, pasting a component that carries its own palette, or going looking for a hero section in libraries that have never shipped one. Nothing else earns the space. + * + * The theme tokens are printed in full for that reason rather than described. An agent holding the seventeen values does not have to guess them, and rewriting a pasted component onto those variables is the whole difference between the lazy workflow working and a page wearing two colour schemes at once. + */ + +/** A source shown in the table, with the page's own blocks it applies to. */ +type Shown = { source: ComponentSource; slots: string[] }; + +/** Pipes would end the cell early, so the one character that can break a row is escaped rather than trusted not to appear. */ +function cell(text: string): string { + return text.replace(/\|/g, "\\|"); +} + +function code(text: string): string { + return `\`${text}\``; +} + +function list(items: string[]): string { + return items.map(code).join(", "); +} + +/** + * The sources worth showing, each carrying the blocks on this page it can improve. + * + * Grouping by source rather than printing one table per block keeps the brief short: five rows at most, and the blocks column tells the agent where each one applies. Order follows first appearance in page order, so the table reads top-down like the page does. + */ +function shownSources(slots: string[]): Shown[] { + const shown = new Map(); + for (const slot of slots) { + // `slots` arrives as the page's own strings; one loom does not recognise simply matches no source. + for (const source of sourcesFor(slot as SlotKey)) { + const entry = shown.get(source.name); + if (entry) entry.slots.push(slot); + else shown.set(source.name, { source, slots: [slot] }); + } + } + return [...shown.values()]; +} + +function sourceTable(shown: Shown[]): string { + const rows = shown.map(({ source, slots }) => + [ + `[${source.name}](${source.url})`, + source.role, + list(slots), + source.install + ? code(source.install) + : "Browser only — nothing to run", + cell(source.caveat), + ].join(" | "), + ); + return [ + "Source | Gives you | Blocks here it can improve | Install | What bites you", + "--- | --- | --- | --- | ---", + ...rows, + ] + .map((row) => `| ${row} |`) + .join("\n"); +} + +function tokenBlock(theme: string): string { + const declarations = Object.entries(themeVars(theme)).map(([name, value]) => `${name}: ${value};`); + return ["```css", ...declarations, "```"].join("\n"); +} + +/** + * The page's blocks in the order they are rendered. + * + * The caller's `slots` arrives in the order the blocks were planned and edited, which is not the order they appear on screen — code owns rendering order and keeps it in SLOT_ORDER. Telling an agent "in that order" while printing the planning order is a small lie that costs it a scroll to catch. A slot loom does not recognise sorts last rather than being dropped, because a brief that quietly omits a block is worse than one that lists it out of place. + */ +function inPageOrder(slots: string[]): string[] { + const rank = (slot: string) => { + const index = SLOT_ORDER.indexOf(slot as SlotKey); + return index === -1 ? SLOT_ORDER.length : index; + }; + return [...new Set(slots)].sort((a, b) => rank(a) - rank(b)); +} + +export function buildAgentsMd(root: Element, prompt: string, theme: string, slots: string[]): string { + const present = inPageOrder(slots); + const shown = shownSources(present); + const uncovered = present.filter((slot) => sourcesFor(slot as SlotKey).length === 0); + // themeVars falls back to forest for a name it does not know, so the prose names the theme actually printed. The HTML file is named after the string the export was given, whatever it was. + const printed = theme in THEMES ? theme : "forest"; + const wrapper = root.tagName.toLowerCase(); + + const licences = shown + .filter(({ source }) => source.name !== "Transitions") + .map(({ source }) => `${source.name} — ${source.license}`) + .join(" · "); + const transitions = shown.find(({ source }) => source.name === "Transitions"); + + const sections = [ + `# AGENTS.md`, + `This folder is one marketing page that loom generated from a single sentence: "${prompt.replace(/\s+/g, " ").trim()}". The notes below are the parts an agent cannot see by reading the markup. Not every agent picks this file up on its own — Claude Code looks for CLAUDE.md — so point yours at it if it has not been read.`, + + `## The files, and which one is authoritative`, + [ + `- ${code("spec.json")} — the page as data, and the only file loom itself reads. Everything else here is generated from it.`, + `- ${code("Site.tsx")} — one flat React component, generated. Editing it by hand works right up until the next export, which overwrites the file and takes the edits with it. If the page will be regenerated, change ${code("spec.json")} instead; if this folder is where the page ends its life, edit away.`, + `- ${code(`site-${theme}.html`)} — the same page standalone, with the CSS rules it actually uses inlined. Also generated.`, + ].join("\n"), + + `## The theme contract`, + `Nothing in the markup names a colour, a radius or a typeface directly — every one of them reads a CSS custom property. These seventeen are the ${code(printed)} theme, set as an inline style on the outermost ${code(`<${wrapper}>`)}, and every block on the page sits inside that element.`, + tokenBlock(printed), + `A component pasted in from anywhere else arrives with a palette of its own: hex literals, or another design system's token names such as ${code("text-foreground")} that resolve to nothing here. It will ignore the theme until it is rewritten onto the variables above. That rewrite is the step this workflow skips most often, and skipping it puts two colour schemes on one page.`, + + `## The blocks on this page`, + `${list(present)} — top to bottom, one block each.`, + ...(uncovered.length > 0 + ? [ + `Nothing in the table below covers ${list(uncovered)}. ${uncovered.length === 1 ? "That block stays" : "Those blocks stay"} as loom rendered ${uncovered.length === 1 ? "it" : "them"} unless you write the replacement yourself.`, + ] + : []), + + `## Where to get better components`, + `${code("primitives")} are unstyled, accessible building blocks; ${code("motion")} is animation applied to a block you already have; ${code("widgets")} are finished single-purpose components. Rows are filtered to the blocks this page actually has.`, + sourceTable(shown), + `These improve a block that is already here. None of them replaces one: there is no hero, no testimonial block, no team grid and no footer section anywhere in the set — they are primitives, motion and app-shaped widgets. An agent sent to find a landing page section in them will spend a long time and come back empty, so take the animation, the primitive or the widget and keep loom's layout around it.`, + ...(licences ? [`Licences: ${licences}.`] : []), + ...(transitions + ? [ + `Transitions is the one to read twice — its licence: ${transitions.source.license}. A snippet used in a page you ship is fine; vendoring the collection into anything you redistribute is not.`, + ] + : []), + ]; + + return `${sections.join("\n\n")}\n`; +} diff --git a/lib/export-registry.test.ts b/lib/export-registry.test.ts new file mode 100644 index 0000000..a81fa44 --- /dev/null +++ b/lib/export-registry.test.ts @@ -0,0 +1,177 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { buildRegistryItem } from "./export-registry"; +import { buildReactSource } from "@/lib/export-tsx"; +import { THEMES, themeVars } from "@/lib/themes"; + +// jsdom throws on getComputedStyle(el, pseudo), which buildReactSource calls for every element. Nothing here is about generated content, so this stands in the empty answer a browser would give and keeps the suite output free of jsdom stack traces that would hide a real failure. +const realGetComputedStyle = globalThis.getComputedStyle; +beforeAll(() => { + globalThis.getComputedStyle = ((el: Element, pseudo?: string | null) => + pseudo + ? ({ content: "none", quotes: "auto" } as CSSStyleDeclaration) + : realGetComputedStyle(el)) as typeof globalThis.getComputedStyle; +}); +afterAll(() => { + globalThis.getComputedStyle = realGetComputedStyle; +}); + +function element(html: string): Element { + const host = document.createElement("div"); + host.innerHTML = html.trim(); + return host.firstElementChild!; +} + +const SITE = element(`

咖啡

a {b} c

`); + +function parse(root: Element, prompt: string, theme: string) { + return JSON.parse(buildRegistryItem(root, prompt, theme)); +} + +describe("buildRegistryItem", () => { + it("emits the fields the published schema marks required, so the CLI accepts the file instead of rejecting it", () => { + // registry-item.json requires ["name", "type"] at the top level, and each files entry requires ["path", "type"] unless it is registry:file or registry:page, which also need "target". + const item = parse(SITE, "我开了家咖啡店", "forest"); + expect(typeof item.name).toBe("string"); + expect(item.name.length).toBeGreaterThan(0); + expect(item.type).toBe("registry:block"); + expect(item.files).toHaveLength(1); + expect(item.files[0].path).toBe("components/site.tsx"); + expect(item.files[0].type).toBe("registry:component"); + expect(item.$schema).toBe("https://ui.shadcn.com/schema/registry-item.json"); + }); + + it("uses type values from the schema's enum, so a plausible-looking invention cannot ship", () => { + const TOP_LEVEL = [ + "registry:lib", "registry:block", "registry:component", "registry:ui", "registry:hook", + "registry:theme", "registry:page", "registry:file", "registry:style", "registry:base", + "registry:font", "registry:item", + ]; + // The files enum is the same list minus registry:font, which only exists at the top level. + const FILE_LEVEL = TOP_LEVEL.filter((type) => type !== "registry:font"); + const item = parse(SITE, "咖啡店", "ink"); + expect(TOP_LEVEL).toContain(item.type); + expect(FILE_LEVEL).toContain(item.files[0].type); + }); + + it("omits the top-level theme key, which the schema forbids for every type except registry:base", () => { + // The schema's allOf sets `theme`, `style`, `iconLibrary` and `baseColor` to `false` unless type is registry:base, so parking the theme name there would fail validation outright. + const item = parse(SITE, "咖啡店", "terminal"); + expect(item).not.toHaveProperty("theme"); + expect(item).not.toHaveProperty("style"); + expect(item).not.toHaveProperty("baseColor"); + expect(item).not.toHaveProperty("iconLibrary"); + }); + + it("carries all 17 theme tokens with the values THEMES holds, so the installed page looks like the previewed one", () => { + for (const theme of Object.keys(THEMES)) { + const vars = parse(SITE, "咖啡店", theme).cssVars.light; + const expected = themeVars(theme); + expect(Object.keys(vars)).toHaveLength(17); + expect(Object.keys(expected)).toHaveLength(17); + for (const [token, value] of Object.entries(expected)) { + expect(vars[token.replace(/^--/, "")]).toBe(value); + } + } + }); + + it("keys cssVars without the leading --, the spelling the published docs use", () => { + // Docs example: "light": { "brand": "oklch(0.205 0.015 18)" }, referenced from the tailwind block above it as hsl(var(--brand)). The CLI is what adds the dashes. + const vars = parse(SITE, "咖啡店", "forest").cssVars.light; + expect(Object.keys(vars)).toContain("accent"); + expect(Object.keys(vars)).toContain("accent-text"); + expect(Object.keys(vars)).toContain("radius"); + expect(Object.keys(vars).some((key) => key.startsWith("--"))).toBe(false); + }); + + it("emits keys the CLI's @theme bridge can dereference, which a leading -- would break without any error", () => { + // shadcn 4.21.0's update-theme plugin writes the Tailwind v4 bridge with the property stripped and the value not: property `--color-${key.replace(/^--/, "")}`, value `var(--${key})`. A key of "--accent" therefore produces `var(----accent)`, which resolves to nothing while the install still reports success. Reproducing the value expression here is the only way this asymmetry fails loudly. + const vars = parse(SITE, "咖啡店", "coral").cssVars.light; + const bridged = Object.keys(vars).map((key) => `var(--${key})`); + expect(bridged).toContain("var(--accent)"); + expect(bridged).toContain("var(--hero-from)"); + expect(bridged.filter((value) => value.startsWith("var(---"))).toEqual([]); + }); + + it("spells radius the way the CLI's radius-scale expansion matches, or the whole --radius-sm..4xl scale is skipped", () => { + // That expansion keys off the literal string "radius"; "--radius" misses it silently. + const vars = parse(SITE, "咖啡店", "warm").cssVars.light; + expect(vars.radius).toBe(THEMES.warm!.tokens.radius); + }); + + it("puts the tokens in the light bucket, the only one the CLI maps to :root", () => { + // Its selector rule is `bucket === "light" ? ":root" : `.${bucket}``. A loom theme is one closed palette, dark ones included, so a `dark` bucket would leave :root empty. + const item = parse(SITE, "咖啡店", "terminal"); + expect(Object.keys(item.cssVars)).toEqual(["light"]); + expect(item.cssVars.light.bg).toBe(THEMES.terminal!.tokens.bg); + }); + + it("names the theme the tokens actually came from, so an unknown key cannot be reported as installed", () => { + // themes.ts resolves an unknown key to a default; this pins the name in the description to that same default. + const item = parse(SITE, "咖啡店", "no-such-theme"); + const named = item.description.match(/loom's "([^"]+)" theme tokens/)![1]; + expect(THEMES[named]).toBeDefined(); + for (const [token, value] of Object.entries(themeVars("no-such-theme"))) { + expect(item.cssVars.light[token.replace(/^--/, "")]).toBe(value); + } + expect(themeVars(named)).toEqual(themeVars("no-such-theme")); + }); + + it("takes its file content byte-for-byte from buildReactSource, proving there is no second renderer", () => { + const prompt = "我开了家咖啡店,主打手冲"; + const item = parse(SITE, prompt, "forest"); + expect(item.files[0].content).toBe(buildReactSource(SITE, prompt)); + }); + + it("reports no npm dependencies, because Site.tsx imports nothing the CLI would have to install", () => { + // Padding this makes `add` install packages the file never imports. + expect(parse(SITE, "咖啡店", "forest").dependencies).toEqual([]); + }); + + it("pretty-prints with a 2-space indent, so the file is reviewable where it lands", () => { + const json = buildRegistryItem(SITE, "咖啡店", "forest"); + expect(json).toContain('\n "name": '); + expect(json).toBe(JSON.stringify(JSON.parse(json), null, 2)); + }); +}); + +describe("registry name derivation", () => { + it("collapses punctuation into single hyphens and trims the ends, so the name stays a usable URL segment", () => { + const item = parse(SITE, " Ada's Coffee & Tea -- Now Open!! ", "forest"); + expect(item.name).toBe("ada-s-coffee-tea-now-open"); + }); + + it("falls back rather than emitting an empty name, for a prompt with no ASCII in it at all", () => { + for (const prompt of ["我开了家咖啡店", "", " ", "!?。、", "\n\t"]) { + const item = parse(SITE, prompt, "forest"); + expect(item.name).toBe("loom-site"); + } + }); + + it("never emits a name the CLI cannot use, whatever the prompt throws at it", () => { + const prompts = [ + "我开了家咖啡店", + "Ada's Coffee & Tea!!", + "", + "---", + "Café ☕ ouvert", + "a".repeat(200), + "A very long sentence about a bakery that would otherwise become an unusable filename", + ]; + for (const prompt of prompts) { + const { name } = parse(SITE, prompt, "forest"); + expect(name).toMatch(/^[a-z0-9]+(-[a-z0-9]+)*$/); + expect(name.length).toBeLessThanOrEqual(40); + } + }); + + it("keeps a title even when the prompt slugs away to nothing, since an empty title reads as a broken item", () => { + expect(parse(SITE, "", "forest").title.length).toBeGreaterThan(0); + expect(parse(SITE, "我开了家咖啡店", "forest").title).toBe("我开了家咖啡店"); + }); + + it("folds a multi-line request onto one line, which both title and description sit on", () => { + const item = parse(SITE, "咖啡店\n\n手冲 单品", "forest"); + expect(item.title).toBe("咖啡店 手冲 单品"); + expect(item.description).toContain("咖啡店 手冲 单品"); + }); +}); diff --git a/lib/export-registry.ts b/lib/export-registry.ts new file mode 100644 index 0000000..e71259c --- /dev/null +++ b/lib/export-registry.ts @@ -0,0 +1,87 @@ +/** + * shadcn registry item export. + * + * The other three exports hand over an artefact and leave the recipient to work out the rest: site.html is a page you cannot edit, Site.tsx is a file that references seventeen CSS custom properties nothing in the target project defines, spec.json is data. This one hands over a verb. `npx shadcn@latest add ./site.registry.json` writes the component into whatever directory the project's components.json calls components, merges the theme tokens into its stylesheet, and installs dependencies — and it is a command the agents people point at this thing already know. The CLI documents the `add` argument as "name, url or local path to component", so a file on disk works with nothing hosted behind it. + * + * The component text comes from buildReactSource. There is no second renderer here and there must not be one: every exporter reads back the DOM the app already rendered, which is the only reason the thirteen block layouts exist in exactly one place. + * + * The one genuinely dangerous detail is the cssVars key spelling, and it is dangerous precisely because getting it wrong is silent — see the comment on themeCssVars below. + */ + +import { buildReactSource } from "./export-tsx"; +import { THEMES, themeVars } from "./themes"; + +/** Emitted when the request yields no ASCII the CLI can use as a name. Registry names travel through URLs and filenames, so an empty or CJK one is not an option. */ +const FALLBACK_NAME = "loom-site"; + +/** A name is a URL segment and a CLI argument before it is a label; a whole sentence makes both unusable. */ +const NAME_LIMIT = 40; + +/** The schema asks for a title that is "short and descriptive"; the untruncated request lives in `description`. */ +const TITLE_LIMIT = 60; + +/** themes.ts resolves an unknown key to this one. Duplicated rather than exported because themeVars() gives back tokens, not the name it settled on — and a description that names a theme the tokens did not come from is worse than no description. A test pins the two together. */ +const FALLBACK_THEME = "forest"; + +function oneLine(text: string): string { + return text.replace(/\s+/g, " ").trim(); +} + +function slugify(prompt: string): string { + const slug = prompt + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, NAME_LIMIT) + .replace(/-+$/, ""); + return slug || FALLBACK_NAME; +} + +/** + * loom's theme tokens, keyed the way the shadcn CLI expects: WITHOUT the leading `--` that themeVars() returns. + * + * Verified against shadcn 4.21.0 and the published docs rather than recalled, because the failure mode is an install that reports success and themes nothing. + * + * The docs example at /docs/registry/registry-item-json writes `"light": { "brand": "oklch(0.205 0.015 18)" }` and the `tailwind` example immediately above it refers to the same token as `hsl(var(--brand))` — the CLI is what puts the dashes on. In the CLI's postcss pass the declaration itself is forgiving: `update-css-vars-v4` emits `--${key.replace(/^--/, "")}`, which normalises either spelling. The `update-theme` plugin that runs straight after it is not. It builds the Tailwind v4 `@theme inline` bridge with the property stripped but the value not: property `--color-${key.replace(/^--/, "")}`, value `var(--${key})`. A key of `"--accent"` therefore emits `--color-accent: var(----accent)` — four dashes, resolves to nothing, no error anywhere. That same plugin also expands the radius scale (`--radius-sm` through `--radius-4xl`) by matching the literal key `radius`, so `"--radius"` would skip the expansion without saying so. + * + * `light` is the bucket because it is the one the CLI maps to `:root` (`const selector = bucket === "light" ? ":root" : `.${bucket}``). There is no `dark` counterpart: a loom theme is a single closed palette, and some of them — terminal — are dark palettes. Writing those into `.dark` would leave `:root` empty and the page unthemed in the default colour scheme. + */ +function themeCssVars(theme: string): Record { + return Object.fromEntries( + Object.entries(themeVars(theme)).map(([token, value]) => [token.replace(/^--/, ""), value]), + ); +} + +/** + * The generated site as a shadcn registry item, pretty-printed. + * + * Note what is deliberately absent: a top-level `theme` key. The schema's `allOf` turns `theme`, `style`, `iconLibrary` and `baseColor` into `false` for every type except `registry:base`, so putting the theme name there would make the file fail validation outright. It goes in the description instead. + */ +export function buildRegistryItem(root: Element, prompt: string, theme: string): string { + const request = oneLine(prompt); + const themeName = THEMES[theme] ? theme : FALLBACK_THEME; + + const item = { + $schema: "https://ui.shadcn.com/schema/registry-item.json", + name: slugify(request), + // `registry:block` is what shadcn's own multi-part items use at the top level, with the files inside typed by what each one is. A single flat component is still a block: `registry:component` and `registry:block` both resolve a file to the project's components directory, and `block` is the honest label for a whole page section. + type: "registry:block", + title: request.slice(0, TITLE_LIMIT).trim() || FALLBACK_NAME, + description: request + ? `Landing page generated by loom from the request: ${request}. Carries loom's "${themeName}" theme tokens, merged into the project stylesheet on install.` + : `Landing page generated by loom. Carries loom's "${themeName}" theme tokens, merged into the project stylesheet on install.`, + // Empty on purpose, and stated rather than omitted. Site.tsx imports one type from react, which every project the CLI can target already has — shadcn's own items never list react either. Padding this with tailwindcss or clsx would make the CLI install packages the file does not import. + dependencies: [] as string[], + files: [ + { + // The CLI strips the leading segment that matches the resolved components directory, so this lands at `/site.tsx` rather than nesting a second `components/`. + path: "components/site.tsx", + type: "registry:component", + content: buildReactSource(root, prompt), + }, + ], + cssVars: { light: themeCssVars(themeName) }, + }; + + return JSON.stringify(item, null, 2); +} diff --git a/lib/sources.test.ts b/lib/sources.test.ts new file mode 100644 index 0000000..ca28e20 --- /dev/null +++ b/lib/sources.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; +import { COMPONENT_SOURCES, sourcesFor } from "./sources"; +import { SLOTS, SLOT_ORDER, type SlotKey } from "@/lib/plan"; + +/** + * A hand-curated table rots without making a sound. Nothing in the app breaks when a `blocks` entry names a slot that was renamed two months ago, when two rows drift onto the same url, or when a source loses the one caveat that stopped an agent pasting licensed CSS into a redistributed build — the page still renders, and the wrong row just gets handed to whoever asked where to find components. These tests are the only thing that notices. + * + * `npm run sources` covers the other half, the half that needs the network: whether the endpoints still answer. Everything checkable offline is checked here. + */ + +const KNOWN_SLOTS = new Set(Object.keys(SLOTS)); + +/** The slot no source in the table covers today. Asserted by name below so that adding coverage forces the prose to be updated with it. */ +const UNCOVERED_SLOT: SlotKey = "team"; + +describe("the source table", () => { + it("lists exactly the five sources it was researched from, so a dropped row cannot pass as a deliberate prune", () => { + expect(Object.keys(COMPONENT_SOURCES).sort()).toEqual(["beautifului", "beui", "rareui", "shadcn", "transitions"]); + }); + + it("names only real slots in `blocks`, so renaming a slot fails here instead of shipping a dead row to an agent", () => { + for (const [key, source] of Object.entries(COMPONENT_SOURCES)) { + for (const slot of source.blocks) { + expect(KNOWN_SLOTS.has(slot), `${key} claims unknown slot ${slot}`).toBe(true); + } + expect(source.blocks.length, `${key} improves no slot, so nothing would ever point at it`).toBeGreaterThan(0); + expect(new Set(source.blocks).size, `${key} lists the same slot twice`).toBe(source.blocks.length); + } + }); + + it("gives every source its own url, because two rows for one site means one of them is stale", () => { + const urls = Object.values(COMPONENT_SOURCES).map((source) => source.url); + expect(new Set(urls).size).toBe(urls.length); + + const endpoints = Object.values(COMPONENT_SOURCES).flatMap((source) => source.endpoints); + expect(new Set(endpoints).size, "the same endpoint is checked twice").toBe(endpoints.length); + }); + + it("leaves no field blank, since a half-filled row reads as researched when it is not", () => { + for (const [key, source] of Object.entries(COMPONENT_SOURCES)) { + for (const field of ["name", "url", "role", "summary", "license"] as const) { + expect(source[field].trim(), `${key}.${field} is empty`).not.toBe(""); + } + // `install` is legitimately null when the browser is the only way in, but an empty string would mean "run nothing" and silently succeed. + expect(source.install === null || source.install.trim() !== "", `${key}.install is an empty command`).toBe(true); + for (const endpoint of source.endpoints) { + expect(endpoint.trim(), `${key} has a blank endpoint`).not.toBe(""); + } + } + }); + + it("states a caveat for every source, which is the field that keeps the table honest rather than promotional", () => { + for (const [key, source] of Object.entries(COMPONENT_SOURCES)) { + expect(source.caveat.trim(), `${key} has no caveat, which is worse than having no entry`).not.toBe(""); + } + }); + + it("reaches every url and endpoint over https, because an agent fetches these unattended", () => { + for (const [key, source] of Object.entries(COMPONENT_SOURCES)) { + expect(source.url.startsWith("https://"), `${key}.url is not https`).toBe(true); + for (const endpoint of source.endpoints) { + expect(endpoint.startsWith("https://"), `${key} endpoint ${endpoint} is not https`).toBe(true); + } + } + }); + + it("declares no endpoints for a source with no install command, so browser-only really means no machine surface", () => { + const browserOnly = Object.entries(COMPONENT_SOURCES).filter(([, source]) => source.install === null); + expect(browserOnly.length, "nothing is browser-only any more, so the implication no longer has anything to protect").toBeGreaterThan(0); + for (const [key, source] of browserOnly) { + expect(source.endpoints, `${key} has no install command yet lists endpoints; one of the two is wrong`).toEqual([]); + } + }); +}); + +describe("sourcesFor", () => { + it("returns only sources that actually list the slot, so a recommendation is never invented", () => { + for (const slot of SLOT_ORDER) { + for (const source of sourcesFor(slot)) { + expect(source.blocks, `${source.name} was returned for ${slot} without listing it`).toContain(slot); + } + } + }); + + it("puts the most machine-readable source first, because an agent can install from it unattended", () => { + for (const slot of SLOT_ORDER) { + const counts = sourcesFor(slot).map((source) => source.endpoints.length); + expect(counts, `${slot} is ordered so an agent meets a browser-only source first`).toEqual([...counts].sort((a, b) => b - a)); + } + }); + + it("returns nothing for the team slot, the one kind of section none of the five ships", () => { + expect(sourcesFor(UNCOVERED_SLOT), "a source now covers team: say so in lib/sources.ts and in the docs before changing this test").toEqual([]); + }); + + it("covers every other slot, so the table is worth consulting at all", () => { + const uncovered = SLOT_ORDER.filter((slot) => sourcesFor(slot).length === 0); + expect(uncovered).toEqual([UNCOVERED_SLOT]); + }); +}); diff --git a/lib/sources.ts b/lib/sources.ts new file mode 100644 index 0000000..9b58906 --- /dev/null +++ b/lib/sources.ts @@ -0,0 +1,129 @@ +import type { SlotKey } from "./plan"; + +/** + * Where to find components worth stealing. + * + * The workflow this exists for is the lazy one: point a coding agent at a good + * library, let it pick, adapt and paste. That only works if the agent is told + * the truth about each library, and the truth here is uncomfortable — none of + * these five ships a marketing page section. There is no hero, no testimonial + * block, no team grid and no footer anywhere in the set. They are primitives, + * motion, and app-shaped widgets. + * + * So `role` is the most important field in this table, not `blocks`. A source + * improves a block loom already renders; it never replaces one. An agent that + * reads this as a block catalogue will go looking for a hero in shadcn/ui, + * find /blocks/login instead, and either give up or invent something. + * + * Every url, endpoint and install command below was fetched and checked rather + * than recalled. They will still rot — `npm run sources` re-checks them. + */ + +/** What a source actually gives you, which decides how an agent should use it. */ +export type SourceRole = + /** Unstyled, accessible building blocks: menus, dialogs, tables, form controls. */ + | "primitives" + /** Animation only. Applies to a block loom already renders; contains no layout. */ + | "motion" + /** Finished single-purpose widgets — a nav, a counter, an orb — not page sections. */ + | "widgets"; + +export type ComponentSource = { + name: string; + url: string; + role: SourceRole; + /** One factual line: what it is, not what it advertises. */ + summary: string; + license: string; + /** The exact command an agent should run, or null when the browser is the only way in. */ + install: string | null; + /** Machine-readable surfaces that answered, for an agent that wants to enumerate before it picks. */ + endpoints: string[]; + /** loom slots this source can plausibly improve. Improve, not replace — see `role`. */ + blocks: SlotKey[]; + /** The thing that bites whoever pastes this in without reading first. */ + caveat: string; +}; + +export const COMPONENT_SOURCES: Record = { + shadcn: { + name: "shadcn/ui", + url: "https://ui.shadcn.com", + role: "primitives", + summary: + "63 accessible React primitives over Radix, plus the registry JSON spec and CLI that the other registries here target. The reference implementation, and the reason `npx shadcn add ` works at all.", + license: "MIT", + install: "npx shadcn@latest add ", + endpoints: ["https://ui.shadcn.com/llms.txt", "https://ui.shadcn.com/r/index.json"], + blocks: ["nav", "features", "comparison", "pricing", "contact", "faq", "footer"], + caveat: + "The first-party block catalogue is app-shaped — login, sidebar, signup, dashboard. There is no landing page in it. Primitives are also `registry:ui` only: /r/index.json does not list blocks, and /registry.json is a 404.", + }, + beui: { + name: "beUI", + url: "https://beui.dev", + role: "motion", + summary: + "85 animated React components — transitions, reveals, animated numbers, form controls with motion states — served as a shadcn-compatible registry with the most complete agent surface of the five.", + license: "MIT for the public registry; pro.beui.dev is a separate paid tier", + install: "npx shadcn@latest add https://beui.dev/r/.json", + endpoints: ["https://beui.dev/llms.txt", "https://beui.dev/r", "https://mcp.beui.dev/mcp"], + blocks: ["nav", "hero", "social", "features", "gallery", "steps", "faq", "cta"], + caveat: + "Every component pulls `motion` plus clsx and tailwind-merge, and the source imports `@/lib/utils` for a `cn()` helper and shadcn token classes such as `text-foreground`. loom ships none of that. Also: /r/index.json is a 404 — the index is /r.", + }, + rareui: { + name: "Rare UI", + url: "https://rareui.com", + role: "widgets", + summary: + "About 20 single-file animated widgets — gooey nav, proximity sidebar, odometer counter, stepped player — published as an open shadcn registry.", + license: "MIT", + install: "npx shadcn@latest add swamimalode07/rare-ui/", + endpoints: ["https://www.rareui.com/llms.txt", "https://www.rareui.com/r/registry.json"], + blocks: ["nav", "hero", "social", "gallery", "steps"], + caveat: + "Hostile to themed colour: no registry item declares `cssVars`, and the sources hardcode hex literals. Anything pasted in has to be rewritten onto loom's CSS custom properties or it will ignore the theme entirely.", + }, + transitions: { + name: "Transitions", + url: "https://transitions.dev", + role: "motion", + summary: + "About 44 named motion snippets as plain CSS with namespaced `.t-*` classes and a shared token block. Not components — the animation for a block you already have.", + license: "Custom, not OSI. Redistribution of a substantial part of the collection is forbidden", + install: "npx transitions-dev add ", + endpoints: ["https://transitions.dev/cli/free-manifest.json"], + blocks: ["hero", "features", "gallery", "steps", "faq", "cta"], + caveat: + "The licence is the constraint, not the code: these snippets may be used in a site but must not be vendored into anything loom redistributes. The free CLI payload is also CSS and vanilla JS only — React variants are a paid tier.", + }, + beautifului: { + name: "Beautiful UI", + url: "https://beautifului.dev", + role: "primitives", + summary: + "21 primitives for AI application interfaces — chat composer, thinking state, approval card, tool chips, dense data tables. Careful work, and the furthest of the five from a marketing page.", + license: "MIT", + install: null, + endpoints: [], + blocks: ["features", "comparison", "steps"], + caveat: + "Copy-paste from the browser is the only way in: no CLI, no registry, no repo, no llms.txt. What you copy also does not compile alone — the sources import project-local paths such as `@/components/atoms/Button` that the site never publishes.", + }, +}; + +export type SourceKey = keyof typeof COMPONENT_SOURCES; + +/** + * The sources worth pointing an agent at for one slot, best-documented first. + * + * Ordering is by how much of the work is already machine-readable: a source an + * agent can enumerate and install unattended beats a prettier one it has to be + * driven through a browser to reach. + */ +export function sourcesFor(slot: SlotKey): ComponentSource[] { + return Object.values(COMPONENT_SOURCES) + .filter((source) => source.blocks.includes(slot)) + .sort((a, b) => b.endpoints.length - a.endpoints.length); +} diff --git a/locales/de.json b/locales/de.json index 999ba63..a2c1b4f 100644 --- a/locales/de.json +++ b/locales/de.json @@ -9,6 +9,8 @@ "exportHtml": "Als HTML exportieren", "exportTsx": "Site.tsx exportieren", "exportSpec": "spec.json exportieren", + "exportRegistry": "site.registry.json exportieren", + "exportAgents": "AGENTS.md exportieren", "editPlaceholder": "Ändere etwas — „Preise weglassen“, „lebendiger machen“", "edit": "Anwenden", "empty": "Wähle oben ein Beispiel oder beschreibe deins", diff --git a/locales/en.json b/locales/en.json index 1c9c0e2..72a4c88 100644 --- a/locales/en.json +++ b/locales/en.json @@ -9,6 +9,8 @@ "exportHtml": "Export HTML", "exportTsx": "Export Site.tsx", "exportSpec": "Export spec.json", + "exportRegistry": "Export site.registry.json", + "exportAgents": "Export AGENTS.md", "editPlaceholder": "Change something — \"drop the pricing\", \"make it more playful\"", "edit": "Apply", "empty": "Pick an example above, or describe your own", diff --git a/locales/es.json b/locales/es.json index d9feff3..1662c0e 100644 --- a/locales/es.json +++ b/locales/es.json @@ -9,6 +9,8 @@ "exportHtml": "Exportar HTML", "exportTsx": "Exportar Site.tsx", "exportSpec": "Exportar spec.json", + "exportRegistry": "Exportar site.registry.json", + "exportAgents": "Exportar AGENTS.md", "editPlaceholder": "Cambia algo — «quita los precios», «que sea más desenfadado»", "edit": "Aplicar", "empty": "Elige un ejemplo de arriba, o describe el tuyo", diff --git a/locales/fr.json b/locales/fr.json index 197db07..bf2e5e6 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -9,6 +9,8 @@ "exportHtml": "Exporter en HTML", "exportTsx": "Exporter Site.tsx", "exportSpec": "Exporter spec.json", + "exportRegistry": "Exporter site.registry.json", + "exportAgents": "Exporter AGENTS.md", "editPlaceholder": "Changez quelque chose — « enlève les tarifs », « rends-le plus enjoué »", "edit": "Appliquer", "empty": "Choisissez un exemple ci-dessus, ou décrivez le vôtre", diff --git a/locales/ja.json b/locales/ja.json index eef7176..0e34f48 100644 --- a/locales/ja.json +++ b/locales/ja.json @@ -9,6 +9,8 @@ "exportHtml": "HTML を書き出す", "exportTsx": "Site.tsx を書き出す", "exportSpec": "spec.json を書き出す", + "exportRegistry": "site.registry.json を書き出す", + "exportAgents": "AGENTS.md を書き出す", "editPlaceholder": "どこを直しますか?「料金は不要」「もっと明るく」など", "edit": "適用", "empty": "上の例を選ぶか、ご自分で説明してください", diff --git a/locales/ko.json b/locales/ko.json index 3b5d3bd..ef4412b 100644 --- a/locales/ko.json +++ b/locales/ko.json @@ -9,6 +9,8 @@ "exportHtml": "HTML 내보내기", "exportTsx": "Site.tsx 내보내기", "exportSpec": "spec.json 내보내기", + "exportRegistry": "site.registry.json 내보내기", + "exportAgents": "AGENTS.md 내보내기", "editPlaceholder": "무엇을 바꿀까요? 예: \"가격표 빼줘\", \"더 발랄하게\"", "edit": "적용", "empty": "위 예시를 고르거나 직접 설명해 주세요", diff --git a/locales/pt.json b/locales/pt.json index 32a6318..a3f59bb 100644 --- a/locales/pt.json +++ b/locales/pt.json @@ -9,6 +9,8 @@ "exportHtml": "Exportar HTML", "exportTsx": "Exportar Site.tsx", "exportSpec": "Exportar spec.json", + "exportRegistry": "Exportar site.registry.json", + "exportAgents": "Exportar AGENTS.md", "editPlaceholder": "Mude algo — “tire os preços”, “deixe mais animado”", "edit": "Aplicar", "empty": "Escolha um exemplo acima, ou descreva o seu", diff --git a/locales/zh.json b/locales/zh.json index cfa28ec..1ee4fe7 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -9,6 +9,8 @@ "exportHtml": "导出 HTML", "exportTsx": "导出 Site.tsx", "exportSpec": "导出 spec.json", + "exportRegistry": "导出 site.registry.json", + "exportAgents": "导出 AGENTS.md", "editPlaceholder": "改点什么?比如「不要定价了」「换个更活泼的配色」", "edit": "修改", "empty": "点上面一个例子,或者自己描述一个网站", diff --git a/package.json b/package.json index 664d30d..2867cc4 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "test": "vitest run", "test:watch": "vitest", "audit:a11y": "node scripts/audit-a11y.mjs", + "sources": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/sources.mjs", "record": "node scripts/record-fixture.mjs", "capture": "node scripts/capture-docs.mjs" }, diff --git a/scripts/sources.mjs b/scripts/sources.mjs new file mode 100644 index 0000000..1fdcac3 --- /dev/null +++ b/scripts/sources.mjs @@ -0,0 +1,147 @@ +#!/usr/bin/env node +/** + * Reachability check for the component sources in lib/sources.ts. + * + * The unit tests check everything about that table that can be known offline — that the slots exist, that nothing is blank, that the ordering holds. They cannot check the part that actually rots: whether the registries still answer, and with how much. That needs the network, so it stays a script you invoke rather than part of `npm test`. + * + * This is the inbound half of the feature. Before an agent goes shopping it says which of the five can still be enumerated without a browser, and how many components each one is offering today. The count is the point: a 200 from a registry that has quietly emptied itself looks exactly like a healthy one. + * + * npm run sources + * + * Exit code is the verdict: non-zero if any declared endpoint failed to answer. + */ + +/** + * lib/sources.ts is imported directly rather than parsed. Node strips the types itself (built in since 22.18), the file is erasable-syntax only, and its single import is `import type`, which is erased — so nothing else in lib/ is pulled in at runtime. The alternative, regexing the table out of the TypeScript source, is exactly the kind of reader that keeps working while going wrong: the day a field is added or a string moves onto one line it silently reports a table that is not the one shipping. Importing the module cannot disagree with the module. tsx/ts-node would also work and are not dependencies here, which is the third reason. + */ +const { COMPONENT_SOURCES } = await import("../lib/sources.ts").catch((error) => { + if (String(error).includes("Unknown file extension")) { + console.error(`This script reads lib/sources.ts with Node's own type stripping, which needs Node 22.18 or newer. Running ${process.version}.`); + process.exit(1); + } + throw error; +}); + +const TIMEOUT_MS = 10_000; +const UA = "loom-sources-check"; + +/** Where a registry index keeps its list, most specific first — beUI's payload also has a `categories` array, and the longest-array heuristic would pick the wrong one. */ +const LIST_KEYS = ["components", "items", "registry", "entries"]; + +/** Counts entries under the `## Components` heading of an llms.txt. shadcn and beUI list them as markdown links, Rare UI as `###` sub-headings, and every file also links docs and guides that are not components — so the section has to be isolated before anything is counted. */ +function countLlms(text) { + const lines = text.split("\n"); + const start = lines.findIndex((line) => /^##\s+components\b/i.test(line)); + if (start === -1) return null; + const rest = lines.slice(start + 1); + const end = rest.findIndex((line) => /^##\s/.test(line)); + const section = end === -1 ? rest : rest.slice(0, end); + + const links = section.filter((line) => /^\s*-\s*\[[^\]]+\]\(/.test(line)).length; + if (links > 0) return links; + const headings = section.filter((line) => /^###\s+/.test(line)).length; + return headings > 0 ? headings : null; +} + +function countJson(payload) { + if (Array.isArray(payload)) return payload.length; + if (payload === null || typeof payload !== "object") return null; + for (const key of LIST_KEYS) { + if (Array.isArray(payload[key])) return payload[key].length; + } + return null; +} + +/** + * An MCP endpoint is not a document, and a plain GET is the wrong question to ask it: beUI's answers 406 to one, which would be reported as broken when the server is perfectly healthy. Speak the protocol instead — initialize, then tools/list — and report the number of tools, which is the same kind of number as a component count. + */ +async function probeMcp(url) { + const headers = { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + "User-Agent": UA, + }; + const call = (body, extra = {}) => + fetch(url, { + method: "POST", + headers: { ...headers, ...extra }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + + const handshake = await call({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: UA, version: "0" } }, + }); + await handshake.text(); + if (!handshake.ok) return { status: handshake.status, ok: false, note: "initialize refused" }; + + const session = handshake.headers.get("mcp-session-id"); + const listed = await call( + { jsonrpc: "2.0", id: 2, method: "tools/list" }, + session ? { "mcp-session-id": session, "mcp-protocol-version": "2025-06-18" } : {}, + ); + const body = await listed.text(); + if (!listed.ok) return { status: listed.status, ok: false, note: "tools/list refused" }; + + // Streamable HTTP wraps the reply in server-sent events; the JSON-RPC message is the `data:` line. + const line = body.split("\n").find((l) => l.startsWith("data:")); + const tools = line ? JSON.parse(line.slice(5)).result?.tools : undefined; + return { status: listed.status, ok: true, note: Array.isArray(tools) ? `${tools.length} tools` : "no tool list" }; +} + +async function probe(url) { + try { + if (/\/mcp\/?$/.test(url)) return await probeMcp(url); + + const response = await fetch(url, { + headers: { "User-Agent": UA, Accept: "application/json, text/plain, */*" }, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + const body = await response.text(); + if (!response.ok) return { status: response.status, ok: false, note: response.statusText.toLowerCase() || "not ok" }; + + const type = response.headers.get("content-type") ?? ""; + const count = type.includes("json") || url.endsWith(".json") ? countJson(JSON.parse(body)) : countLlms(body); + return { + status: response.status, + ok: true, + note: count === null ? `${body.length} bytes, nothing countable` : `${count} components`, + }; + } catch (error) { + if (error.name === "TimeoutError") return { status: null, ok: false, note: `no answer in ${TIMEOUT_MS / 1000}s` }; + if (error instanceof SyntaxError) return { status: 200, ok: false, note: "answered with unparseable JSON" }; + // Node wraps DNS and TLS failures in a bare "fetch failed"; the cause carries the only useful part. + return { status: null, ok: false, note: error.cause?.code ?? error.cause?.message ?? error.message }; + } +} + +// Every endpoint goes out at once, but the results are printed back in table order so two runs diff cleanly. +const sources = Object.values(COMPONENT_SOURCES); +const results = await Promise.all(sources.map((source) => Promise.all(source.endpoints.map((url) => probe(url))))); + +let checked = 0; +let failed = 0; +let browserOnly = 0; +let enumerable = 0; + +for (const [index, source] of sources.entries()) { + console.log(`${source.name} — ${source.role}`); + if (source.endpoints.length === 0) { + browserOnly += 1; + console.log(" · browser only, no machine-readable surface to check"); + continue; + } + if (results[index].every((result) => result.ok)) enumerable += 1; + for (const [i, url] of source.endpoints.entries()) { + const result = results[index][i]; + checked += 1; + if (!result.ok) failed += 1; + console.log(` ${result.ok ? "✓" : "✗"} ${String(result.status ?? "—").padEnd(3)} ${url.padEnd(46)} ${result.note}`); + } +} + +console.log(`\n${checked - failed}/${checked} endpoints answered; ${enumerable} of ${sources.length} sources enumerable without a browser, ${browserOnly} browser only.`); +process.exit(failed === 0 ? 0 : 1);