diff --git a/dprint.json b/dprint.json index 5dfe4336fc2..1391f55535d 100644 --- a/dprint.json +++ b/dprint.json @@ -1,11 +1,21 @@ { "$schema": "https://dprint.dev/schemas/v0.json", - "incremental": false, + "incremental": true, "includes": ["**/*.{ts,tsx,js,jsx,json,md}"], "indentWidth": 2, "lineWidth": 120, "newLineKind": "lf", + "exec": { + "cwd": "${configDir}", + "associations": ["**/examples/ui/**/*.{ts,tsx}", "!**/*.test.{ts,tsx}"], + "commands": [{ + "command": "node scripts/stack-chains.mjs {{ext}}", + "associations": ["**/examples/ui/**/*.{ts,tsx}"], + "cacheKeyFiles": ["scripts/stack-chains.mjs"] + }] + }, "typescript": { + "associations": ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"], "semiColons": "asi", "quoteStyle": "alwaysDouble", "trailingCommas": "never", @@ -38,6 +48,7 @@ "!.vscode/**/*" ], "plugins": [ + "https://plugins.dprint.dev/exec-0.9.0.json@939c28cce4022e2676ac9596585448c16abee12b8ccb0320a9eb9596ade1c219", "https://plugins.dprint.dev/typescript-0.93.4.wasm", "https://plugins.dprint.dev/markdown-0.20.0.wasm", "https://plugins.dprint.dev/json-0.21.1.wasm" diff --git a/examples/ui/README.md b/examples/ui/README.md index 37950d750d1..21baad2d59b 100644 --- a/examples/ui/README.md +++ b/examples/ui/README.md @@ -54,4 +54,4 @@ pnpm vitest run --project examples/ui examples/ui/routing/ ## Formatting -The examples follow the repository's dprint configuration. `launch` has its own `dprint.json` with a 70-column line width, so the code it shows in the article fits its code windows. +The examples follow the repository's dprint configuration. dprint also runs `scripts/stack-chains.mjs` over their TypeScript, except `*.test.ts(x)` files: when two or more method calls follow the start of a chain (such as `h.div`), each goes on its own line, so a view reads as a tree. `launch` has its own `dprint.json` with a 70-column line width, so the code it shows in the article fits its code windows. diff --git a/examples/ui/auth/src/App.ts b/examples/ui/auth/src/App.ts index 69f9c3470d1..8d96789d8fe 100644 --- a/examples/ui/auth/src/App.ts +++ b/examples/ui/auth/src/App.ts @@ -130,13 +130,17 @@ export const AppNoDeps = Html.component({ $.set(AppModel.LoggedIn({ route: LoggedInRoute.Dashboard(), session })) .run( SaveSession.make({ session }), - AppNavigation.Dashboard.replace().pipe(Command.asNoop) + AppNavigation.Dashboard + .replace() + .pipe(Command.asNoop) ), SignedOut: ($) => $.set(AppModel.LoggedOut({ route: LoggedOutRoute.Home() })).run( ClearSession.make(), - AppNavigation.Home.replace().pipe(Command.asNoop) + AppNavigation.Home + .replace() + .pipe(Command.asNoop) ), FailedSaveSession: ($, { error }) => $.run(LogError.make({ entries: ["Failed to save session:", error] })), @@ -161,22 +165,24 @@ export const AppNoDeps = Html.component({ ], view: (h, model) => - h.div.class("min-h-screen bg-gray-100").children( - AppModel.match(model, { - LoggedOut: ({ route }) => - LoggedOut(h, { - props: { route }, - onEmit: { - SignedIn: ({ session }) => AppMessage.SignedIn({ session }) - } - }), - LoggedIn: ({ route, session }) => - LoggedIn(h, { - props: { route, session }, - onEmit: { SignedOut: () => AppMessage.SignedOut() } - }) - }) - ) + h.div + .class("min-h-screen bg-gray-100") + .children( + AppModel.match(model, { + LoggedOut: ({ route }) => + LoggedOut(h, { + props: { route }, + onEmit: { + SignedIn: ({ session }) => AppMessage.SignedIn({ session }) + } + }), + LoggedIn: ({ route, session }) => + LoggedIn(h, { + props: { route, session }, + onEmit: { SignedOut: () => AppMessage.SignedOut() } + }) + }) + ) }) export const App = AppNoDeps.pipe( diff --git a/examples/ui/auth/src/LoggedIn.ts b/examples/ui/auth/src/LoggedIn.ts index 0b00b3016ed..581c30aba0e 100644 --- a/examples/ui/auth/src/LoggedIn.ts +++ b/examples/ui/auth/src/LoggedIn.ts @@ -23,12 +23,10 @@ const NavLink = LoggedInDef.fragment( (h, tag: "Dashboard" | "Settings") => { const active = tag === h.props.route._tag return h.li.children( - h.a.attr("href", LoggedInRoute[tag].href()) + h.a + .attr("href", LoggedInRoute[tag].href()) .attr("aria-current", active ? "page" : undefined) - .class( - "hover:bg-blue-600 font-medium px-3 py-1 rounded transition", - active && "bg-blue-700/50" - ) + .class("hover:bg-blue-600 font-medium px-3 py-1 rounded transition", active && "bg-blue-700/50") .children(tag) ) } @@ -41,33 +39,41 @@ export const LoggedIn = LoggedInDef.make({ view: (h) => { const { route, session } = h.props - return h.div.class("min-h-screen").children( - h.nav.class("bg-blue-500 text-white p-4").children( - h.div.class("max-w-4xl mx-auto flex justify-between items-center") + return h.div + .class("min-h-screen") + .children( + h.nav + .class("bg-blue-500 text-white p-4") .children( - h.ul.class("flex gap-6 list-none").children( - NavLink(h, "Dashboard"), - NavLink(h, "Settings") - ), - h.div.class("text-sm").children(`Signed in as ${session.email}`) - ) - ), - h.main.class("py-8").children( - LoggedInRoute.match(route, { - Dashboard: () => DashboardPage(h, session), - Settings: () => - SettingsPage(h, { - session, - onSignOut: LoggedInMessage.ClickedSignOut() - }), - NotFound: (route) => - NotFound(h, { - path: route.params["*"], - backHref: LoggedInRoute.Dashboard.href(), - backText: "Go to Dashboard" + h.div + .class("max-w-4xl mx-auto flex justify-between items-center") + .children( + h.ul + .class("flex gap-6 list-none") + .children(NavLink(h, "Dashboard"), NavLink(h, "Settings")), + h.div + .class("text-sm") + .children(`Signed in as ${session.email}`) + ) + ), + h.main + .class("py-8") + .children( + LoggedInRoute.match(route, { + Dashboard: () => DashboardPage(h, session), + Settings: () => + SettingsPage(h, { + session, + onSignOut: LoggedInMessage.ClickedSignOut() + }), + NotFound: (route) => + NotFound(h, { + path: route.params["*"], + backHref: LoggedInRoute.Dashboard.href(), + backText: "Go to Dashboard" + }) }) - }) + ) ) - ) } }) diff --git a/examples/ui/auth/src/LoggedOut.ts b/examples/ui/auth/src/LoggedOut.ts index 569b60cd4c6..1700f602483 100644 --- a/examples/ui/auth/src/LoggedOut.ts +++ b/examples/ui/auth/src/LoggedOut.ts @@ -27,21 +27,23 @@ export const LoggedOut = Html.component({ update: ($, { session }) => $.emit(LoggedOutEvents.SignedIn({ session })), view: (h) => - h.div.class("py-8").children( - LoggedOutRoute.match(h.props.route, { - Home: () => HomePage(h), - Login: () => - LoginPage(h, { - onEmit: { - SignedIn: ({ session }) => LoggedOutMessage.SignedInLogin({ session }) - } - }), - NotFound: (route) => - NotFound(h, { - path: route.params["*"], - backHref: LoggedOutRoute.Home.href(), - backText: "Go Home" - }) - }) - ) + h.div + .class("py-8") + .children( + LoggedOutRoute.match(h.props.route, { + Home: () => HomePage(h), + Login: () => + LoginPage(h, { + onEmit: { + SignedIn: ({ session }) => LoggedOutMessage.SignedInLogin({ session }) + } + }), + NotFound: (route) => + NotFound(h, { + path: route.params["*"], + backHref: LoggedOutRoute.Home.href(), + backText: "Go Home" + }) + }) + ) }) diff --git a/examples/ui/auth/src/pages/HomePage.ts b/examples/ui/auth/src/pages/HomePage.ts index cf7d631c592..d43689247ca 100644 --- a/examples/ui/auth/src/pages/HomePage.ts +++ b/examples/ui/auth/src/pages/HomePage.ts @@ -2,41 +2,52 @@ import type { Html } from "effect/ui/html" import { LoggedOutRoute } from "../routes.ts" const FeatureCard = (h: Html.H, title: string, description: string) => - h.div.class("bg-white rounded-lg shadow-md p-6").children( - h.h2.class("text-xl font-semibold text-gray-800 mb-3").children(title), - h.p.class("text-gray-600").children(description) - ) + h.div + .class("bg-white rounded-lg shadow-md p-6") + .children( + h.h2 + .class("text-xl font-semibold text-gray-800 mb-3") + .children(title), + h.p + .class("text-gray-600") + .children(description) + ) export const HomePage = (h: Html.H) => - h.div.class("max-w-4xl mx-auto px-4").children( - h.div.class("text-center py-16").children( - h.h1.class("text-5xl font-bold text-gray-800 mb-6").children( - "Welcome to Auth Example" - ), - h.p.class("text-xl text-gray-600 mb-8").children( - "A demonstration of authentication with a Model union and route guards in Effect UI." - ), - h.a.attr("href", LoggedOutRoute.Login.href()) - .class( - "inline-block px-8 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 transition" + h.div + .class("max-w-4xl mx-auto px-4") + .children( + h.div + .class("text-center py-16") + .children( + h.h1 + .class("text-5xl font-bold text-gray-800 mb-6") + .children("Welcome to Auth Example"), + h.p + .class("text-xl text-gray-600 mb-8") + .children("A demonstration of authentication with a Model union and route guards in Effect UI."), + h.a + .attr("href", LoggedOutRoute.Login.href()) + .class("inline-block px-8 py-3 bg-blue-500 text-white font-medium rounded-lg hover:bg-blue-600 transition") + .children("Sign In") + ), + h.div + .class("grid grid-cols-1 md:grid-cols-3 gap-8 mt-16") + .children( + FeatureCard( + h, + "Model as Union", + "App state is fundamentally LoggedOut | LoggedIn, not a flat struct with optional session." + ), + FeatureCard( + h, + "Route Guards", + "Protected routes redirect to login. Auth routes redirect to dashboard when logged in." + ), + FeatureCard( + h, + "Session Persistence", + "Session survives page refresh via localStorage, read into the root's props before it mounts." + ) ) - .children("Sign In") - ), - h.div.class("grid grid-cols-1 md:grid-cols-3 gap-8 mt-16").children( - FeatureCard( - h, - "Model as Union", - "App state is fundamentally LoggedOut | LoggedIn, not a flat struct with optional session." - ), - FeatureCard( - h, - "Route Guards", - "Protected routes redirect to login. Auth routes redirect to dashboard when logged in." - ), - FeatureCard( - h, - "Session Persistence", - "Session survives page refresh via localStorage, read into the root's props before it mounts." - ) ) - ) diff --git a/examples/ui/auth/src/pages/NotFound.ts b/examples/ui/auth/src/pages/NotFound.ts index 887cc2eac25..f533f60d915 100644 --- a/examples/ui/auth/src/pages/NotFound.ts +++ b/examples/ui/auth/src/pages/NotFound.ts @@ -5,13 +5,17 @@ export const NotFound = (h: Html.H, options: { readonly backHref: string readonly backText: string }) => - h.div.class("max-w-4xl mx-auto px-4 text-center").children( - h.h1.class("text-4xl font-bold text-red-600 mb-6").children( - "404 - Page Not Found" - ), - h.p.class("text-lg text-gray-600 mb-4").children( - `The path "${options.path}" was not found.` - ), - h.a.attr("href", options.backHref).class("text-blue-500 hover:underline") - .children(options.backText) - ) + h.div + .class("max-w-4xl mx-auto px-4 text-center") + .children( + h.h1 + .class("text-4xl font-bold text-red-600 mb-6") + .children("404 - Page Not Found"), + h.p + .class("text-lg text-gray-600 mb-4") + .children(`The path "${options.path}" was not found.`), + h.a + .attr("href", options.backHref) + .class("text-blue-500 hover:underline") + .children(options.backText) + ) diff --git a/examples/ui/auth/src/pages/dashboard/DashboardPage.ts b/examples/ui/auth/src/pages/dashboard/DashboardPage.ts index 4c724d32020..0a11bd03ba0 100644 --- a/examples/ui/auth/src/pages/dashboard/DashboardPage.ts +++ b/examples/ui/auth/src/pages/dashboard/DashboardPage.ts @@ -2,22 +2,32 @@ import type { Session } from "#domain/Session" import type { Html } from "effect/ui/html" const StatCard = (h: Html.H, title: string, value: string) => - h.div.class("bg-white rounded-lg shadow-md p-6").children( - h.h2.class("text-sm font-medium text-gray-500 uppercase mb-1").children( - title - ), - h.p.class("text-3xl font-bold text-gray-800").children(value) - ) + h.div + .class("bg-white rounded-lg shadow-md p-6") + .children( + h.h2 + .class("text-sm font-medium text-gray-500 uppercase mb-1") + .children(title), + h.p + .class("text-3xl font-bold text-gray-800") + .children(value) + ) export const DashboardPage = (h: Html.H, session: Session) => - h.div.class("max-w-4xl mx-auto px-4").children( - h.h1.class("text-4xl font-bold text-gray-800 mb-6").children( - `Welcome back, ${session.name}!` - ), - h.p.class("text-lg text-gray-600 mb-8").children("Here is your dashboard."), - h.div.class("grid grid-cols-1 md:grid-cols-3 gap-6").children( - StatCard(h, "Total Sessions", "42"), - StatCard(h, "Active Projects", "7"), - StatCard(h, "Tasks Completed", "128") + h.div + .class("max-w-4xl mx-auto px-4") + .children( + h.h1 + .class("text-4xl font-bold text-gray-800 mb-6") + .children(`Welcome back, ${session.name}!`), + h.p + .class("text-lg text-gray-600 mb-8") + .children("Here is your dashboard."), + h.div + .class("grid grid-cols-1 md:grid-cols-3 gap-6") + .children( + StatCard(h, "Total Sessions", "42"), + StatCard(h, "Active Projects", "7"), + StatCard(h, "Tasks Completed", "128") + ) ) - ) diff --git a/examples/ui/auth/src/pages/login/LoginPage.ts b/examples/ui/auth/src/pages/login/LoginPage.ts index 4cb6134e597..3ddbefad532 100644 --- a/examples/ui/auth/src/pages/login/LoginPage.ts +++ b/examples/ui/auth/src/pages/login/LoginPage.ts @@ -72,12 +72,17 @@ const FormField = (h: Html.H, options: { props: { ...fieldValidationProps(state), disabled: options.disabled }, view: (field) => field.root(h.div).children( - h.div.class("flex items-center gap-2 mb-1").children( - field.label(h.label).class("block text-sm font-medium text-gray-700") - .children(options.label), - state._tag === "Valid" && - h.span.class("text-green-600 text-sm").children("✓") - ), + h.div + .class("flex items-center gap-2 mb-1") + .children( + field.label(h.label) + .class("block text-sm font-medium text-gray-700") + .children(options.label), + state._tag === "Valid" && + h.span + .class("text-green-600 text-sm") + .children("✓") + ), Input(h, { element: field.control(h.input), props: { value: options.value }, @@ -90,9 +95,9 @@ const FormField = (h: Html.H, options: { "disabled:bg-gray-100 data-valid:border-green-500 data-invalid:border-red-500" ), state._tag === "Invalid" && - field.error(h.div)?.class("text-red-600 text-sm mt-1").children( - state.errors[0] - ) + field.error(h.div) + ?.class("text-red-600 text-sm mt-1") + .children(state.errors[0]) ) }) } @@ -149,65 +154,75 @@ export const LoginPageNoDeps = Html.component({ view: (h, model) => { const validated = LoginValidation.validate(model.form) const canSubmit = Option.isSome(validated.value) && !model.submitting - return h.div.class("max-w-md mx-auto px-4").children( - h.div.class("bg-white rounded-xl shadow-lg p-8").children( - h.h1.class("text-3xl font-bold text-gray-800 text-center mb-8") - .children("Sign In"), - h.div.class("mb-6 p-3 bg-blue-50 border border-blue-200 rounded-lg") + return h.div + .class("max-w-md mx-auto px-4") + .children( + h.div + .class("bg-white rounded-xl shadow-lg p-8") .children( - h.p.class("text-sm text-blue-700").children( - "Hint: Use any email with password \"password\"" - ) - ), - Form(h, { - onEmit: () => LoginPageMessage.SubmittedForm(), - view: (form) => - form.root( - h.form.ref(LoginForm).attr("aria-label", "Sign in").class( - "space-y-6" - ) - ).children( - FormField(h, { - key: "email", - label: "Email", - type: "email", - placeholder: "you@example.com", - state: validated.fields.email, - value: validated.fields.email.value, - disabled: model.submitting, - onUpdate: (value) => LoginPageMessage.ChangedEmail({ value }) - }), - FormField(h, { - key: "password", - label: "Password", - type: "password", - placeholder: "Enter your password", - state: validated.fields.password, - value: Redacted.value(validated.fields.password.value), - disabled: model.submitting, - onUpdate: (value) => - LoginPageMessage.ChangedPassword({ - value: Redacted.make(value) - }) - }), - Button(h, { props: { type: "submit", disabled: !canSubmit } }) - .class( - "w-full py-3 font-medium rounded-lg transition bg-blue-500 text-white cursor-pointer", - "enabled:hover:bg-blue-600 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed" + h.h1 + .class("text-3xl font-bold text-gray-800 text-center mb-8") + .children("Sign In"), + h.div + .class("mb-6 p-3 bg-blue-50 border border-blue-200 rounded-lg") + .children( + h.p + .class("text-sm text-blue-700") + .children("Hint: Use any email with password \"password\"") + ), + Form(h, { + onEmit: () => LoginPageMessage.SubmittedForm(), + view: (form) => + form.root( + h.form + .ref(LoginForm) + .attr("aria-label", "Sign in") + .class("space-y-6") + ).children( + FormField(h, { + key: "email", + label: "Email", + type: "email", + placeholder: "you@example.com", + state: validated.fields.email, + value: validated.fields.email.value, + disabled: model.submitting, + onUpdate: (value) => LoginPageMessage.ChangedEmail({ value }) + }), + FormField(h, { + key: "password", + label: "Password", + type: "password", + placeholder: "Enter your password", + state: validated.fields.password, + value: Redacted.value(validated.fields.password.value), + disabled: model.submitting, + onUpdate: (value) => + LoginPageMessage.ChangedPassword({ + value: Redacted.make(value) + }) + }), + Button(h, { props: { type: "submit", disabled: !canSubmit } }) + .class( + "w-full py-3 font-medium rounded-lg transition bg-blue-500 text-white cursor-pointer", + "enabled:hover:bg-blue-600 disabled:bg-gray-300 disabled:text-gray-500 disabled:cursor-not-allowed" + ) + .children(model.submitting ? "Signing in..." : "Sign In") ) - .children(model.submitting ? "Signing in..." : "Sign In") - ) - }), - h.div.class("mt-6 text-center").children( - h.span.class("text-gray-600").children("Back to "), - h.a.attr("href", LoggedOutRoute.Home.href()).class( - "text-blue-500 hover:underline" - ).children( - "Home" + }), + h.div + .class("mt-6 text-center") + .children( + h.span + .class("text-gray-600") + .children("Back to "), + h.a + .attr("href", LoggedOutRoute.Home.href()) + .class("text-blue-500 hover:underline") + .children("Home") + ) ) - ) ) - ) } }) diff --git a/examples/ui/auth/src/pages/settings/SettingsPage.ts b/examples/ui/auth/src/pages/settings/SettingsPage.ts index c79d6adb256..59c4e5b88df 100644 --- a/examples/ui/auth/src/pages/settings/SettingsPage.ts +++ b/examples/ui/auth/src/pages/settings/SettingsPage.ts @@ -3,36 +3,49 @@ import type { Html } from "effect/ui/html" import { Button } from "effect/ui/kit" const InfoRow = (h: Html.H, label: string, value: string) => - h.div.class("flex justify-between items-center py-2 border-b border-gray-100") + h.div + .class("flex justify-between items-center py-2 border-b border-gray-100") .children( - h.p.class("text-gray-600").children(label), - h.p.class("font-medium text-gray-800").children(value) + h.p + .class("text-gray-600") + .children(label), + h.p + .class("font-medium text-gray-800") + .children(value) ) export const SettingsPage = (h: Html.H, options: { readonly session: Session readonly onSignOut: M }) => - h.div.class("max-w-4xl mx-auto px-4").children( - h.h1.class("text-4xl font-bold text-gray-800 mb-6").children("Settings"), - h.div.class("bg-white rounded-lg shadow-md p-6 mb-6").children( - h.h2.class("text-xl font-semibold text-gray-800 mb-4").children( - "Account Information" - ), - h.div.class("space-y-4").children( - InfoRow(h, "User ID", options.session.userId), - InfoRow(h, "Email", options.session.email), - InfoRow(h, "Name", options.session.name) - ) - ), - h.div.class("bg-white rounded-lg shadow-md p-6").children( - h.h2.class("text-xl font-semibold text-gray-800 mb-4").children( - "Actions" - ), - Button(h, { onPress: options.onSignOut }) - .class( - "px-6 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 transition cursor-pointer" + h.div + .class("max-w-4xl mx-auto px-4") + .children( + h.h1 + .class("text-4xl font-bold text-gray-800 mb-6") + .children("Settings"), + h.div + .class("bg-white rounded-lg shadow-md p-6 mb-6") + .children( + h.h2 + .class("text-xl font-semibold text-gray-800 mb-4") + .children("Account Information"), + h.div + .class("space-y-4") + .children( + InfoRow(h, "User ID", options.session.userId), + InfoRow(h, "Email", options.session.email), + InfoRow(h, "Name", options.session.name) + ) + ), + h.div + .class("bg-white rounded-lg shadow-md p-6") + .children( + h.h2 + .class("text-xl font-semibold text-gray-800 mb-4") + .children("Actions"), + Button(h, { onPress: options.onSignOut }) + .class("px-6 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 transition cursor-pointer") + .children("Sign Out") ) - .children("Sign Out") ) - ) diff --git a/examples/ui/canvas-art/src/CanvasArt.ts b/examples/ui/canvas-art/src/CanvasArt.ts index eb80b1b736d..8a61d441c49 100644 --- a/examples/ui/canvas-art/src/CanvasArt.ts +++ b/examples/ui/canvas-art/src/CanvasArt.ts @@ -132,33 +132,36 @@ export const CanvasArt = Html.component({ ], head: ({ model }) => [Head.title(`Canvas Art (${model.balls.length} balls)`)], view: (h, model) => - h.div.class( - "flex flex-col items-center justify-center min-h-screen bg-black text-white p-8" - ).children( - h.h1.class("text-4xl font-bold mb-2").children("Canvas Art"), - h.p.class("text-zinc-400 mb-6").children( - "Click the canvas to spawn a ball." - ), - Canvas.view(h, { - width: CANVAS_WIDTH, - height: CANVAS_HEIGHT, - pixelRatio: "auto", - shapes: sceneOf(model), - onPointerDown: ({ x, y }) => CanvasArtMessage.ClickedCanvas({ x, y }) - }).class("rounded-lg shadow-2xl cursor-crosshair").attr( - "aria-label", - "Canvas art" - ), - h.div.class("flex gap-3 mt-4").children( - Button(h, { onPress: CanvasArtMessage.ClickedTogglePlay() }) - .class(BUTTON_CLASS, "bg-indigo-600 hover:bg-indigo-500") - .children(model.running ? "Pause" : "Play"), - Button(h, { onPress: CanvasArtMessage.ClickedClear() }) - .class(BUTTON_CLASS, "bg-zinc-700 hover:bg-zinc-600") - .children("Clear"), - h.p.class("px-4 py-2 text-zinc-400 text-sm self-center").children( - `${model.balls.length} balls` - ) + h.div + .class("flex flex-col items-center justify-center min-h-screen bg-black text-white p-8") + .children( + h.h1 + .class("text-4xl font-bold mb-2") + .children("Canvas Art"), + h.p + .class("text-zinc-400 mb-6") + .children("Click the canvas to spawn a ball."), + Canvas.view(h, { + width: CANVAS_WIDTH, + height: CANVAS_HEIGHT, + pixelRatio: "auto", + shapes: sceneOf(model), + onPointerDown: ({ x, y }) => CanvasArtMessage.ClickedCanvas({ x, y }) + }) + .class("rounded-lg shadow-2xl cursor-crosshair") + .attr("aria-label", "Canvas art"), + h.div + .class("flex gap-3 mt-4") + .children( + Button(h, { onPress: CanvasArtMessage.ClickedTogglePlay() }) + .class(BUTTON_CLASS, "bg-indigo-600 hover:bg-indigo-500") + .children(model.running ? "Pause" : "Play"), + Button(h, { onPress: CanvasArtMessage.ClickedClear() }) + .class(BUTTON_CLASS, "bg-zinc-700 hover:bg-zinc-600") + .children("Clear"), + h.p + .class("px-4 py-2 text-zinc-400 text-sm self-center") + .children(`${model.balls.length} balls`) + ) ) - ) }) diff --git a/examples/ui/counter/src/Counter.ts b/examples/ui/counter/src/Counter.ts index 0824163d120..88d0e809e5c 100644 --- a/examples/ui/counter/src/Counter.ts +++ b/examples/ui/counter/src/Counter.ts @@ -28,22 +28,24 @@ export const Counter = Html.component({ }, head: ({ model }) => [Head.title(`Counter: ${model.count}`)], view: (h, model) => - h.div.class( - "min-h-screen bg-white flex flex-col items-center justify-center gap-6 p-6" - ).children( - h.p.class("text-6xl font-bold text-gray-800").children( - String(model.count) - ), - h.div.class("flex flex-wrap justify-center gap-4").children( - Button(h, { onPress: CounterMessage.ClickedDecrement() }).class( - BUTTON_CLASS - ).children("-"), - Button(h, { onPress: CounterMessage.ClickedReset() }).class( - BUTTON_CLASS - ).children("Reset"), - Button(h, { onPress: CounterMessage.ClickedIncrement() }).class( - BUTTON_CLASS - ).children("+") + h.div + .class("min-h-screen bg-white flex flex-col items-center justify-center gap-6 p-6") + .children( + h.p + .class("text-6xl font-bold text-gray-800") + .children(String(model.count)), + h.div + .class("flex flex-wrap justify-center gap-4") + .children( + Button(h, { onPress: CounterMessage.ClickedDecrement() }) + .class(BUTTON_CLASS) + .children("-"), + Button(h, { onPress: CounterMessage.ClickedReset() }) + .class(BUTTON_CLASS) + .children("Reset"), + Button(h, { onPress: CounterMessage.ClickedIncrement() }) + .class(BUTTON_CLASS) + .children("+") + ) ) - ) }) diff --git a/examples/ui/counters/src/Counter.ts b/examples/ui/counters/src/Counter.ts index f56845217b7..20e9eff1113 100644 --- a/examples/ui/counters/src/Counter.ts +++ b/examples/ui/counters/src/Counter.ts @@ -26,20 +26,19 @@ export const Counter = Html.component({ ClickedIncrement: ($) => $.evolve({ count: (count) => count + 1 }) }, view: (h, model) => - h.div.class( - "flex items-center gap-3 rounded-lg border border-gray-200 px-4 py-3" - ).children( - Button(h, { onPress: CounterMessage.ClickedDecrement() }).attr( - "aria-label", - "Decrement" - ).class(BUTTON_CLASS) - .children("-"), - h.output.class("w-12 text-center text-2xl font-mono tabular-nums") - .children(String(model.count)), - Button(h, { onPress: CounterMessage.ClickedIncrement() }).attr( - "aria-label", - "Increment" - ).class(BUTTON_CLASS) - .children("+") - ) + h.div + .class("flex items-center gap-3 rounded-lg border border-gray-200 px-4 py-3") + .children( + Button(h, { onPress: CounterMessage.ClickedDecrement() }) + .attr("aria-label", "Decrement") + .class(BUTTON_CLASS) + .children("-"), + h.output + .class("w-12 text-center text-2xl font-mono tabular-nums") + .children(String(model.count)), + Button(h, { onPress: CounterMessage.ClickedIncrement() }) + .attr("aria-label", "Increment") + .class(BUTTON_CLASS) + .children("+") + ) }) diff --git a/examples/ui/counters/src/Counters.ts b/examples/ui/counters/src/Counters.ts index 83119eb6b37..ee3d7e395c2 100644 --- a/examples/ui/counters/src/Counters.ts +++ b/examples/ui/counters/src/Counters.ts @@ -30,39 +30,49 @@ export const Counters = Html.component({ }, head: ({ model }) => [Head.title(`Counters (${model.counterIds.length})`)], view: (h, model) => - h.div.class( - "min-h-screen bg-white flex flex-col items-center py-12 px-6 gap-6" - ).children( - h.h1.class("text-2xl font-semibold text-gray-900").children("Counters"), - h.p.class("text-sm text-gray-500 max-w-md text-center").children( - "Each row is a Counter child keyed by its id. The parent holds only the list of ids, and each Counter keeps its own count, so adding, updating or removing one leaves the others as they were." - ), - h.div.class("flex flex-col gap-3 w-full max-w-md").children( - model.counterIds.map((id) => { - const labelId = h.id("label", id) - return h.div.key(String(id)).attr("role", "group").attr( - "aria-labelledby", - labelId - ) - .class("flex items-center gap-2").children( - h.span.id(labelId).class("w-20 text-sm text-gray-500").children( - `Counter ${id}` - ), - h.div.class("flex-1").children(Counter(h, { key: String(id) })), - Button(h, { - onPress: CountersMessage.ClickedRemoveCounter({ id }) - }) - .class( - "rounded border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:border-red-300 hover:text-red-600 transition cursor-pointer" + h.div + .class("min-h-screen bg-white flex flex-col items-center py-12 px-6 gap-6") + .children( + h.h1 + .class("text-2xl font-semibold text-gray-900") + .children("Counters"), + h.p + .class("text-sm text-gray-500 max-w-md text-center") + .children( + "Each row is a Counter child keyed by its id. The parent holds only the list of ids, and each Counter keeps its own count, so adding, updating or removing one leaves the others as they were." + ), + h.div + .class("flex flex-col gap-3 w-full max-w-md") + .children( + model.counterIds.map((id) => { + const labelId = h.id("label", id) + return h.div + .key(String(id)) + .attr("role", "group") + .attr("aria-labelledby", labelId) + .class("flex items-center gap-2") + .children( + h.span + .id(labelId) + .class("w-20 text-sm text-gray-500") + .children(`Counter ${id}`), + h.div + .class("flex-1") + .children(Counter(h, { key: String(id) })), + Button(h, { + onPress: CountersMessage.ClickedRemoveCounter({ id }) + }) + .class( + "rounded border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:border-red-300 hover:text-red-600 transition cursor-pointer" + ) + .children("Remove") ) - .children("Remove") - ) - }) - ), - Button(h, { onPress: CountersMessage.ClickedAddCounter() }) - .class( - "rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700 transition cursor-pointer" - ) - .children("+ Add Counter") - ) + }) + ), + Button(h, { onPress: CountersMessage.ClickedAddCounter() }) + .class( + "rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-700 transition cursor-pointer" + ) + .children("+ Add Counter") + ) }) diff --git a/examples/ui/domains/src/App.ts b/examples/ui/domains/src/App.ts index 48dcfbbab2a..a35461f4675 100644 --- a/examples/ui/domains/src/App.ts +++ b/examples/ui/domains/src/App.ts @@ -180,8 +180,14 @@ const tldFilters: ReadonlyArray = [ ] const visibleTldFilters = (search: string): ReadonlyArray => { - const needle = search.trim().toLowerCase().replace(/^\./, "") - return tldFilters.filter((value) => tldFilterLabel(value).toLowerCase().includes(needle)) + const needle = search.trim() + .toLowerCase() + .replace(/^\./, "") + return tldFilters.filter((value) => + tldFilterLabel(value) + .toLowerCase() + .includes(needle) + ) } const itemsOf = ( @@ -233,42 +239,48 @@ const AppDef = Html.component({ const SearchForm = AppDef.fragment((h, model: AppModel) => { const invalid = queryOf(model.route) !== "" && labelOfRoute(model.route) === undefined - return h.form.class("search").attr("role", "search").on( - "submit", - AppMessage.SubmittedSearch() - ).children( - Icon(h, "search"), - h.input.ref(SearchInput).attrs({ - id: bootstrapConfig.inputId, - type: "search", - name: "q", - "aria-label": "Search domains", - "aria-invalid": `${invalid}`, - placeholder: "Search for a domain", - autocomplete: "off", - autocapitalize: "none", - enterkeyhint: "search", - spellcheck: "false" - }) - .attr("aria-describedby", invalid ? "search-error" : undefined) - .value(model.query) - .on("input", ({ value }) => AppMessage.UpdatedSearch({ value })) - .on("keydown", ({ composing, key }) => - key === "Escape" && !composing - ? AppMessage.PressedEscape() - : undefined, { preventDefault: true }), - h.button.attrs({ - type: "button", - "aria-label": "Clear search, Esc", - "aria-keyshortcuts": "Escape" - }) - .class("clear-search") - .on("click", AppMessage.ClickedClearSearch()) - .children( - h.kbd.attr("aria-hidden", "true").children("Esc"), - Icon(h, "close") - ) - ) + return h.form + .class("search") + .attr("role", "search") + .on("submit", AppMessage.SubmittedSearch()) + .children( + Icon(h, "search"), + h.input + .ref(SearchInput) + .attrs({ + id: bootstrapConfig.inputId, + type: "search", + name: "q", + "aria-label": "Search domains", + "aria-invalid": `${invalid}`, + placeholder: "Search for a domain", + autocomplete: "off", + autocapitalize: "none", + enterkeyhint: "search", + spellcheck: "false" + }) + .attr("aria-describedby", invalid ? "search-error" : undefined) + .value(model.query) + .on("input", ({ value }) => AppMessage.UpdatedSearch({ value })) + .on("keydown", ({ composing, key }) => + key === "Escape" && !composing + ? AppMessage.PressedEscape() + : undefined, { preventDefault: true }), + h.button + .attrs({ + type: "button", + "aria-label": "Clear search, Esc", + "aria-keyshortcuts": "Escape" + }) + .class("clear-search") + .on("click", AppMessage.ClickedClearSearch()) + .children( + h.kbd + .attr("aria-hidden", "true") + .children("Esc"), + Icon(h, "close") + ) + ) }) const CartDialog = AppDef.fragment((h, model: AppModel) => { @@ -282,67 +294,80 @@ const CartDialog = AppDef.fragment((h, model: AppModel) => { Settled: () => undefined }, view: (dialog) => - h.div.class("ml-auto flex items-center gap-2 max-[700px]:gap-1.5") + h.div + .class("ml-auto flex items-center gap-2 max-[700px]:gap-1.5") .children( dialog.trigger( - h.button.attrs({ - id: "cart-button", - "aria-label": "Cart, " + model.cart.length + " domains" - }) + h.button + .attrs({ + id: "cart-button", + "aria-label": "Cart, " + model.cart.length + " domains" + }) .class("button cart-button") ).children( Icon(h, "cart"), h.span("Cart"), model.cart.length > 0 && - h.span.class("cart-count").children(String(model.cart.length)) + h.span + .class("cart-count") + .children(String(model.cart.length)) ), dialog.portal(h.div.class("dialog-overlay"))?.children( dialog.backdrop(h.div.class("dialog-backdrop")), dialog.popup(h.div.class("cart-panel")).children( - h.div.class("cart-heading").children( - dialog.title(h.h2).children("Your cart"), - dialog.close( - dialog.initialFocus( - h.button.ref(CartCloseButton).attrs({ - id: "cart-close-button", - "aria-label": "Close cart panel" - }) - .class("icon-button") - ) - ).children(Icon(h, "close")) - ), - model.cart.length === 0 - ? h.p.class("empty-cart").children( - "Your next idea starts with a name. Search for a domain to add it here." - ) - : h.ul.class("cart-items").children( - model.cart.map((domain) => - h.li.key(domain.name).children( - h.div( - h.strong(domain.name), - h.span(formatRegistrationPrice(domain)), - h.span.class("mt-1 block text-xs text-gray-400") - .children(formatRenewalPrice(domain)) - ), - h.button.attrs({ - type: "button", - "aria-label": "Remove " + domain.name - }) + h.div + .class("cart-heading") + .children( + dialog.title(h.h2).children("Your cart"), + dialog.close( + dialog.initialFocus( + h.button + .ref(CartCloseButton) + .attrs({ + id: "cart-close-button", + "aria-label": "Close cart panel" + }) .class("icon-button") - .on( - "click", - AppMessage.ClickedRemoveCartDomain({ - name: domain.name - }) - ) - .children(Icon(h, "close")) ) - ) + ).children(Icon(h, "close")) ), - h.div.class("cart-total").children( - h.span("Registration total"), - h.strong(formatPrice(total)) - ), + model.cart.length === 0 + ? h.p + .class("empty-cart") + .children("Your next idea starts with a name. Search for a domain to add it here.") + : h.ul + .class("cart-items") + .children( + model.cart.map((domain) => + h.li + .key(domain.name) + .children( + h.div( + h.strong(domain.name), + h.span(formatRegistrationPrice(domain)), + h.span + .class("mt-1 block text-xs text-gray-400") + .children(formatRenewalPrice(domain)) + ), + h.button + .attrs({ + type: "button", + "aria-label": "Remove " + domain.name + }) + .class("icon-button") + .on( + "click", + AppMessage.ClickedRemoveCartDomain({ + name: domain.name + }) + ) + .children(Icon(h, "close")) + ) + ) + ), + h.div + .class("cart-total") + .children(h.span("Registration total"), h.strong(formatPrice(total))), dialog.description(h.p.class("demo-note")).children( "Demo cart with sample prices and availability. No domains are reserved. No purchases are made." ) @@ -353,90 +378,109 @@ const CartDialog = AppDef.fragment((h, model: AppModel) => { }) const Header = AppDef.fragment((h, model: AppModel) => - h.header.class("header").children( - h.a.attrs({ href: AppRoute.Search.href(), "aria-label": "Domains home" }) - .class("brand") - .on("click", AppMessage.ClickedDomainsHome()) - .children( - Logo(h), - h.span.class("brand-divider").children("/"), - h.span("Domains") - ), - h.span.class("demo-label").children("Unofficial demo"), - CartDialog(h, model), - h.p.attrs({ - id: "cart-announcement", - "aria-live": "polite", - "aria-atomic": "true" - }).class("sr-only").children( - model.cart.length === 0 - ? "Your cart is empty." - : model.cart.length + " " + - (model.cart.length === 1 ? "domain" : "domains") + " in your cart." + h.header + .class("header") + .children( + h.a + .attrs({ href: AppRoute.Search.href(), "aria-label": "Domains home" }) + .class("brand") + .on("click", AppMessage.ClickedDomainsHome()) + .children( + Logo(h), + h.span + .class("brand-divider") + .children("/"), + h.span("Domains") + ), + h.span + .class("demo-label") + .children("Unofficial demo"), + CartDialog(h, model), + h.p + .attrs({ + id: "cart-announcement", + "aria-live": "polite", + "aria-atomic": "true" + }) + .class("sr-only") + .children( + model.cart.length === 0 + ? "Your cart is empty." + : model.cart.length + " " + + (model.cart.length === 1 ? "domain" : "domains") + " in your cart." + ) ) - ) ) const Hero = AppDef.fragment((h, model: AppModel) => - h.section.class("hero").attr("aria-label", "Find your domain").children( - h.h1("Find a domain for", h.br, h.span("the next viral idea.")), - h.p( - "Sample data. ", - h.a.attr("href", "https://vercel.com/domains/pricing").children( - "Vercel pricing" - ) - ), - SearchForm(h, model), - h.div.class("hero-search-space") - ) + h.section + .class("hero") + .attr("aria-label", "Find your domain") + .children( + h.h1("Find a domain for", h.br, h.span("the next viral idea.")), + h.p( + "Sample data. ", + h.a + .attr("href", "https://vercel.com/domains/pricing") + .children("Vercel pricing") + ), + SearchForm(h, model), + h.div.class("hero-search-space") + ) ) const DomainNameText = AppDef.fragment((h, domain: DomainName) => [ - h.span.attr("data-domain-label", "").children( - domain.name.slice(0, -(domain.tld.length + 1)) - ), + h.span + .attr("data-domain-label", "") + .children(domain.name.slice(0, -(domain.tld.length + 1))), "." + domain.tld ]) const DomainAction = AppDef.fragment( (h, model: AppModel, domain: Domain | undefined) => { if (domain === undefined) { - return h.div.class("domain-action").attr("aria-hidden", "true").children( - h.span.class("skeleton skeleton-price"), - h.span.class("skeleton skeleton-action") - ) + return h.div + .class("domain-action") + .attr("aria-hidden", "true") + .children(h.span.class("skeleton skeleton-price"), h.span.class("skeleton skeleton-action")) } if (domain._tag === "Unavailable") { - return h.div.class("domain-action").children( - h.span.class("unavailable").attr( - "title", - "This sample domain is marked unavailable in the demo data." + return h.div + .class("domain-action") + .children( + h.span + .class("unavailable") + .attr("title", "This sample domain is marked unavailable in the demo data.") + .children("Not available") ) - .children("Not available") - ) } const inCart = model.cart.some((item) => item.name === domain.name) const premium = domain.isPremium ? "Premium domain. " : "" - return h.div.class("domain-action").children( - h.span.class("price").attr("title", premium + formatRenewalPrice(domain)) - .children(formatRegistrationPrice(domain)), - h.button.attrs({ - type: "button", - "aria-label": inCart - ? "Remove " + domain.name + " from cart" - : "Add " + domain.name + " to cart", - "aria-description": formatRegistrationPrice(domain) + ". " + premium + - formatRenewalPrice(domain) - }) - .class("icon-button", inCart && "is-added") - .on( - "click", - inCart - ? AppMessage.ClickedRemoveDomain({ name: domain.name }) - : AppMessage.ClickedAddDomain({ domain }) - ) - .children(Icon(h, inCart ? "check" : "cart")) - ) + return h.div + .class("domain-action") + .children( + h.span + .class("price") + .attr("title", premium + formatRenewalPrice(domain)) + .children(formatRegistrationPrice(domain)), + h.button + .attrs({ + type: "button", + "aria-label": inCart + ? "Remove " + domain.name + " from cart" + : "Add " + domain.name + " to cart", + "aria-description": formatRegistrationPrice(domain) + ". " + premium + + formatRenewalPrice(domain) + }) + .class("icon-button", inCart && "is-added") + .on( + "click", + inCart + ? AppMessage.ClickedRemoveDomain({ name: domain.name }) + : AppMessage.ClickedAddDomain({ domain }) + ) + .children(Icon(h, inCart ? "check" : "cart")) + ) } ) @@ -470,38 +514,43 @@ const FilterSelect = AppDef.fragment( Settled: () => undefined }, view: (select) => - h.div.class("filter-listbox").children( - select.trigger( - h.button.class("filter-trigger").attr( - "aria-label", - options.label + ": " + - (options.items.find((item) => item.value === options.value) - ?.label ?? "") - ) - ).children( - h.span.class("filter-trigger-content").children( - select.value(h.span.class("filter-trigger-label")), - Icon(h, "chevron-down") - ) - ), - select.positioner(h.div.class("filter-positioner")).children( - select.popup(h.div.class("filter-options")).children( - open && options.items.map((item) => - select.item({ - element: h.div.class("filter-option"), - value: item.value - }).children( - h.div.class("filter-option-content").children( - h.span.class("filter-option-check").children( - Icon(h, "check") - ), - select.itemText(h.div).children(item.label) + h.div + .class("filter-listbox") + .children( + select.trigger( + h.button + .class("filter-trigger") + .attr( + "aria-label", + options.label + ": " + + (options.items.find((item) => item.value === options.value) + ?.label ?? "") + ) + ).children( + h.span + .class("filter-trigger-content") + .children(select.value(h.span.class("filter-trigger-label")), Icon(h, "chevron-down")) + ), + select.positioner(h.div.class("filter-positioner")).children( + select.popup(h.div.class("filter-options")).children( + open && options.items.map((item) => + select.item({ + element: h.div.class("filter-option"), + value: item.value + }).children( + h.div + .class("filter-option-content") + .children( + h.span + .class("filter-option-check") + .children(Icon(h, "check")), + select.itemText(h.div).children(item.label) + ) ) ) ) ) ) - ) }) } ) @@ -515,17 +564,20 @@ const FilterChoice = AppDef.fragment(( selected: boolean, message: AppMessage ) => - h.button.key(label).attrs({ - type: "button", - "aria-pressed": `${selected}` - }) + h.button + .key(label) + .attrs({ + type: "button", + "aria-pressed": `${selected}` + }) .class("filter-choice") .on("click", message) .children( h.span(label), - h.span.class("filter-choice-check").attr("aria-hidden", "true").children( - Icon(h, "check") - ) + h.span + .class("filter-choice-check") + .attr("aria-hidden", "true") + .children(Icon(h, "check")) ) ) @@ -540,63 +592,72 @@ const TldDialog = AppDef.fragment((h, model: AppModel) => }, view: (dialog) => { const values = visibleTldFilters(model.tldSearch) - return h.div.class("contents").children( - dialog.trigger( - h.button.attrs({ - id: "mobile-tld-filter", - "aria-label": "Filter by TLD: " + tldFilterLabel(model.tldFilter) - }).class("filter-trigger mobile-tld-filter") - ).children( - h.span.class("filter-trigger-content").children( - h.span.class("filter-trigger-label").children( - tldFilterLabel(model.tldFilter) - ), - Icon(h, "chevron-down") - ) - ), - dialog.portal(h.div.class("dialog-overlay"))?.children( - dialog.backdrop(h.div.class("dialog-backdrop filters-backdrop")), - dialog.popup(h.div.class("filters-panel tld-panel")).children( - dialog.title(h.h2.class("sr-only")).children("Filter by TLD"), - h.div.class("tld-search").children( - Icon(h, "search"), - dialog.initialFocus( - h.input.attrs({ - type: "search", - "aria-label": "Search TLDs", - placeholder: "Search TLDs...", - autocomplete: "off" - }) - ).value(model.tldSearch).on( - "input", - ({ value }) => AppMessage.UpdatedTldSearch({ value }) + return h.div + .class("contents") + .children( + dialog.trigger( + h.button + .attrs({ + id: "mobile-tld-filter", + "aria-label": "Filter by TLD: " + tldFilterLabel(model.tldFilter) + }) + .class("filter-trigger mobile-tld-filter") + ).children( + h.span + .class("filter-trigger-content") + .children( + h.span + .class("filter-trigger-label") + .children(tldFilterLabel(model.tldFilter)), + Icon(h, "chevron-down") ) - ), - h.div.class("tld-options").children( - values.length === 0 - ? h.p.class("tld-no-results").attr("role", "status").children( - "No TLDs found." - ) - : values.map((value) => - FilterChoice( - h, - tldFilterLabel(value), - value === model.tldFilter, - AppMessage.PickedTldFilter({ value }) + ), + dialog.portal(h.div.class("dialog-overlay"))?.children( + dialog.backdrop(h.div.class("dialog-backdrop filters-backdrop")), + dialog.popup(h.div.class("filters-panel tld-panel")).children( + dialog.title(h.h2.class("sr-only")).children("Filter by TLD"), + h.div + .class("tld-search") + .children( + Icon(h, "search"), + dialog.initialFocus( + h.input.attrs({ + type: "search", + "aria-label": "Search TLDs", + placeholder: "Search TLDs...", + autocomplete: "off" + }) ) - ) - ), - dialog.close( - h.button.class("filters-close").attr( - "aria-label", - "Close TLD filter" + .value(model.tldSearch) + .on("input", ({ value }) => AppMessage.UpdatedTldSearch({ value })) + ), + h.div + .class("tld-options") + .children( + values.length === 0 + ? h.p + .class("tld-no-results") + .attr("role", "status") + .children("No TLDs found.") + : values.map((value) => + FilterChoice( + h, + tldFilterLabel(value), + value === model.tldFilter, + AppMessage.PickedTldFilter({ value }) + ) + ) + ), + dialog.close( + h.button + .class("filters-close") + .attr("aria-label", "Close TLD filter") + ).children( + Icon(h, "close") ) - ).children( - Icon(h, "close") ) ) ) - ) } }) ) @@ -611,106 +672,121 @@ const FiltersDialog = AppDef.fragment((h, model: AppModel) => Settled: () => undefined }, view: (dialog) => - h.div.class("contents").children( - dialog.trigger( - h.button.attrs({ - id: "filters-button", - "aria-label": "Filters and sort" - }) - .class( - "filters-button", - (model.availability !== "All" || model.sort !== "Relevance") && - "has-active-filters" - ) - ).children(Icon(h, "filter")), - dialog.portal(h.div.class("dialog-overlay"))?.children( - dialog.backdrop(h.div.class("dialog-backdrop filters-backdrop")), - dialog.popup(h.div.class("filters-panel")).children( - dialog.title(h.h2.class("sr-only")).children("Filters and sort"), - h.div.attrs({ - role: "group", - "aria-labelledby": "availability-filter-heading" - }).children( - h.h3.attr("id", "availability-filter-heading").class( - "filter-group-label" - ).children("Filter by"), - AvailabilityFilter.literals.map((value) => { - const choice = FilterChoice( - h, - availabilityLabels[value], - value === model.availability, - AppMessage.PickedAvailabilityFilter({ value }) - ) - return value === model.availability - ? dialog.initialFocus(choice) - : choice + h.div + .class("contents") + .children( + dialog.trigger( + h.button + .attrs({ + id: "filters-button", + "aria-label": "Filters and sort" }) - ), - h.hr.class("filter-group-divider"), - h.div.attrs({ - role: "group", - "aria-labelledby": "sort-order-heading" - }).children( - h.h3.attr("id", "sort-order-heading").class("filter-group-label") - .children("Sort by"), - mobileSortOrders.map((value) => - FilterChoice( - h, - value === "PriceAscending" ? "Price" : sortLabels[value], - value === model.sort || - (value === "PriceAscending" && - model.sort === "PriceDescending"), - AppMessage.PickedSortOrder({ value }) - ) + .class( + "filters-button", + (model.availability !== "All" || model.sort !== "Relevance") && + "has-active-filters" ) - ), - dialog.close( - h.button.class("filters-close").attr( - "aria-label", - "Close filters and sort" + ).children(Icon(h, "filter")), + dialog.portal(h.div.class("dialog-overlay"))?.children( + dialog.backdrop(h.div.class("dialog-backdrop filters-backdrop")), + dialog.popup(h.div.class("filters-panel")).children( + dialog.title(h.h2.class("sr-only")).children("Filters and sort"), + h.div + .attrs({ + role: "group", + "aria-labelledby": "availability-filter-heading" + }) + .children( + h.h3 + .attr("id", "availability-filter-heading") + .class("filter-group-label") + .children("Filter by"), + AvailabilityFilter.literals.map((value) => { + const choice = FilterChoice( + h, + availabilityLabels[value], + value === model.availability, + AppMessage.PickedAvailabilityFilter({ value }) + ) + return value === model.availability + ? dialog.initialFocus(choice) + : choice + }) + ), + h.hr.class("filter-group-divider"), + h.div + .attrs({ + role: "group", + "aria-labelledby": "sort-order-heading" + }) + .children( + h.h3 + .attr("id", "sort-order-heading") + .class("filter-group-label") + .children("Sort by"), + mobileSortOrders.map((value) => + FilterChoice( + h, + value === "PriceAscending" ? "Price" : sortLabels[value], + value === model.sort || + (value === "PriceAscending" && + model.sort === "PriceDescending"), + AppMessage.PickedSortOrder({ value }) + ) + ) + ), + dialog.close( + h.button + .class("filters-close") + .attr("aria-label", "Close filters and sort") + ).children( + Icon(h, "close") ) - ).children( - Icon(h, "close") ) ) ) - ) }) ) const Filters = AppDef.fragment((h, model: AppModel) => - h.div.class("filters").children( - h.div.class("desktop-tld-filter").children( - FilterSelect(h, model, { - popup: "TldListbox", - label: "Filter by TLD", - value: model.tldFilter, - items: tldItems, - picked: (value) => AppMessage.PickedTldFilter({ value }) - }) - ), - TldDialog(h, model), - h.div.class("desktop-filters").children( - FilterSelect(h, model, { - popup: "AvailabilityListbox", - label: "Filter availability", - value: model.availability, - items: availabilityItems, - picked: (value) => - isAvailabilityFilter(value) - ? AppMessage.PickedAvailabilityFilter({ value }) - : undefined - }), - FilterSelect(h, model, { - popup: "SortListbox", - label: "Sort results", - value: model.sort, - items: sortItems, - picked: (value) => isSortOrder(value) ? AppMessage.PickedSortOrder({ value }) : undefined - }) - ), - FiltersDialog(h, model) - ) + h.div + .class("filters") + .children( + h.div + .class("desktop-tld-filter") + .children( + FilterSelect(h, model, { + popup: "TldListbox", + label: "Filter by TLD", + value: model.tldFilter, + items: tldItems, + picked: (value) => AppMessage.PickedTldFilter({ value }) + }) + ), + TldDialog(h, model), + h.div + .class("desktop-filters") + .children( + FilterSelect(h, model, { + popup: "AvailabilityListbox", + label: "Filter availability", + value: model.availability, + items: availabilityItems, + picked: (value) => + isAvailabilityFilter(value) + ? AppMessage.PickedAvailabilityFilter({ value }) + : undefined + }), + FilterSelect(h, model, { + popup: "SortListbox", + label: "Sort results", + value: model.sort, + items: sortItems, + picked: (value) => isSortOrder(value) ? AppMessage.PickedSortOrder({ value }) : undefined + }) + ), + FiltersDialog(h, model) + ) ) const ResultsList = AppDef.fragment(( @@ -718,75 +794,93 @@ const ResultsList = AppDef.fragment(( model: AppModel, results: ReadonlyArray ) => - h.div.class("all-results").children( - queryOf(model.route) !== "" && VirtualList(h, { - props: { - itemSize: 57, - keys: results.map((listing) => listing.name), - overscan: 2, - initialCount: PREVIEW_RESULT_COUNT, - dataset: labelOfRoute(model.route) ?? "" - }, - onEmit: { - Scrolled: ({ first, last }) => AppMessage.ScrolledResults({ first, last }) - }, - view: (virtualList) => - virtualList.list( - h.ul.attrs({ - id: "domain-results", - "aria-label": "All domain results", - "aria-description": results.length + - " domains. Use arrow keys, Page Up, Page Down, Home, and End to scroll the page.", - tabindex: "0" - }).class( - "results-viewport", - results.length === 1 && "is-single-result" + h.div + .class("all-results") + .children( + queryOf(model.route) !== "" && VirtualList(h, { + props: { + itemSize: 57, + keys: results.map((listing) => listing.name), + overscan: 2, + initialCount: PREVIEW_RESULT_COUNT, + dataset: labelOfRoute(model.route) ?? "" + }, + onEmit: { + Scrolled: ({ first, last }) => AppMessage.ScrolledResults({ first, last }) + }, + view: (virtualList) => + virtualList.list( + h.ul + .attrs({ + id: "domain-results", + "aria-label": "All domain results", + "aria-description": results.length + + " domains. Use arrow keys, Page Up, Page Down, Home, and End to scroll the page.", + tabindex: "0" + }) + .class("results-viewport", results.length === 1 && "is-single-result") + ).children( + virtualList.items.map((index) => { + const listing = results[index]! + return virtualList.item({ + element: h.li + .key(listing.name) + .class("domain-row", listing.domain?._tag === "Unavailable" && "is-unavailable"), + index + }).children( + h.span + .class("domain-name") + .children(DomainNameText(h, listing)), + DomainAction(h, model, listing.domain) + ) + }) + ) + }), + h.ul + .class("results-preview") + .attr("aria-hidden", "true") + .children( + results.slice(0, PREVIEW_RESULT_COUNT).map((listing) => + h.li + .key(listing.name) + .class("domain-row") + .children( + h.span + .class("domain-name") + .children(DomainNameText(h, listing)), + DomainAction(h, model, undefined) + ) ) - ).children( - virtualList.items.map((index) => { - const listing = results[index]! - return virtualList.item({ - element: h.li.key(listing.name).class( - "domain-row", - listing.domain?._tag === "Unavailable" && "is-unavailable" - ), - index - }).children( - h.span.class("domain-name").children(DomainNameText(h, listing)), - DomainAction(h, model, listing.domain) - ) - }) - ) - }), - h.ul.class("results-preview").attr("aria-hidden", "true").children( - results.slice(0, PREVIEW_RESULT_COUNT).map((listing) => - h.li.key(listing.name).class("domain-row").children( - h.span.class("domain-name").children(DomainNameText(h, listing)), - DomainAction(h, model, undefined) ) - ) ) - ) ) const Results = AppDef.fragment((h, model: AppModel) => { const query = queryOf(model.route) const search = searchState(query, h.queries.top, h.queries.ranges) if (search._tag === "Invalid" || search._tag === "Failed") { - return h.section.class("results").attr("aria-label", "Domain results") + return h.section + .class("results") + .attr("aria-label", "Domain results") .children( - h.div.class("search-error").attr("role", "alert").children( - h.h2("Let’s try that again"), - h.p.attr("id", "search-error").children( - search._tag === "Invalid" - ? invalidQueryMessage - : failedSearchMessage - ), - h.button.attr("type", "button").class("button").on( - "click", - AppMessage.ClickedRetrySearch() - ).children("Try again") - ) + h.div + .class("search-error") + .attr("role", "alert") + .children( + h.h2("Let’s try that again"), + h.p + .attr("id", "search-error") + .children( + search._tag === "Invalid" + ? invalidQueryMessage + : failedSearchMessage + ), + h.button + .attr("type", "button") + .class("button") + .on("click", AppMessage.ClickedRetrySearch()) + .children("Try again") + ) ) } const allListings = queryToListings( @@ -801,104 +895,129 @@ const Results = AppDef.fragment((h, model: AppModel) => { ) const loading = search._tag === "Loading" || (search._tag === "Ready" && search.loading) - return h.section.class("results").attr("aria-label", "Domain results") + return h.section + .class("results") + .attr("aria-label", "Domain results") .children( - h.div.class("results-content").attr("aria-busy", `${loading}`) + h.div + .class("results-content") + .attr("aria-busy", `${loading}`) .children( - h.div.class("top-results-heading").children( - h.h2("Top Results"), - h.span.class("sample-data-label").children("Sample data") - ), - h.div.class("top-results").children( - allListings.slice(0, TOP_RESULT_COUNT).map((listing) => - h.article.key(listing.name).class( - "domain-card", - listing.domain?._tag === "Unavailable" && "is-unavailable" - ).children( - h.h3(...DomainNameText(h, listing)), - DomainAction(h, model, listing.domain) + h.div + .class("top-results-heading") + .children( + h.h2("Top Results"), + h.span + .class("sample-data-label") + .children("Sample data") + ), + h.div + .class("top-results") + .children( + allListings.slice(0, TOP_RESULT_COUNT).map((listing) => + h.article + .key(listing.name) + .class("domain-card", listing.domain?._tag === "Unavailable" && "is-unavailable") + .children(h.h3(...DomainNameText(h, listing)), DomainAction(h, model, listing.domain)) ) - ) - ), - h.div.class("results-heading").children( - h.h2("All Results"), - Filters(h, model) - ), + ), + h.div + .class("results-heading") + .children(h.h2("All Results"), Filters(h, model)), listings.length === 0 - ? h.p.class("empty-results").attr("role", "status").children( - "No domains match your filters. Try another extension or show all domains." - ) + ? h.p + .class("empty-results") + .attr("role", "status") + .children("No domains match your filters. Try another extension or show all domains.") : ResultsList(h, model, listings) ), search._tag === "Ready" && search.failed && !search.loading && - h.div.attr("role", "alert").class( - "sticky bottom-4 z-10 mt-4 flex items-center justify-between gap-4 rounded-md border border-gray-800 bg-gray-950 p-4 text-sm text-gray-300" - ).children( - h.p(failedSearchMessage), - h.button.attr("type", "button").class("button").on( - "click", - AppMessage.ClickedRetrySearch() - ).children("Try again") - ), + h.div + .attr("role", "alert") + .class( + "sticky bottom-4 z-10 mt-4 flex items-center justify-between gap-4 rounded-md border border-gray-800 bg-gray-950 p-4 text-sm text-gray-300" + ) + .children( + h.p(failedSearchMessage), + h.button + .attr("type", "button") + .class("button") + .on("click", AppMessage.ClickedRetrySearch()) + .children("Try again") + ), search._tag === "Ready" - ? h.p.attrs({ role: "status", "aria-atomic": "true" }).class( - "result-count" - ).children( - search.domains.size < domainTlds.length - ? search.domains.size + " of " + domainTlds.length + - " domains checked · Registration prices in USD" - : listings.length + " domains · Registration prices in USD" - ) - : h.p.attrs({ - role: "status", - "aria-atomic": "true", - "aria-label": "Searching domains" - }).class("result-count") + ? h.p + .attrs({ role: "status", "aria-atomic": "true" }) + .class("result-count") + .children( + search.domains.size < domainTlds.length + ? search.domains.size + " of " + domainTlds.length + + " domains checked · Registration prices in USD" + : listings.length + " domains · Registration prices in USD" + ) + : h.p + .attrs({ + role: "status", + "aria-atomic": "true", + "aria-label": "Searching domains" + }) + .class("result-count") .children("Checking availability and prices…") ) }) const SearchPage = AppDef.fragment((h, model: AppModel) => - h.div.attrs({ - id: bootstrapConfig.appId, - "data-search-layout": model.layout, - "data-search": queryOf(model.route) === "" ? "idle" : "active" - }).class("app").children( - h.a.attr("href", "#main").class("skip-link").children( - "Skip to main content" - ), - Header(h, model), - h.main.attrs({ id: "main", tabindex: "-1" }).class( - "flex-1 scroll-mt-20 focus:outline-none" - ).children( - h.h1.class("search-page-heading").children("Domain search"), - Hero(h, model), - h.section.class("begin-search").attr("aria-label", "Begin your search") + h.div + .attrs({ + id: bootstrapConfig.appId, + "data-search-layout": model.layout, + "data-search": queryOf(model.route) === "" ? "idle" : "active" + }) + .class("app") + .children( + h.a + .attr("href", "#main") + .class("skip-link") + .children("Skip to main content"), + Header(h, model), + h.main + .attrs({ id: "main", tabindex: "-1" }) + .class("flex-1 scroll-mt-20 focus:outline-none") .children( - h.div.class("begin-search-copy").children( - h.div.class("begin-search-icon").children(Icon(h, "search")), - h.h2("Begin your search"), - h.p( - "Enter a domain name to explore sample prices and availability." - ) - ) + h.h1 + .class("search-page-heading") + .children("Domain search"), + Hero(h, model), + h.section + .class("begin-search") + .attr("aria-label", "Begin your search") + .children( + h.div + .class("begin-search-copy") + .children( + h.div + .class("begin-search-icon") + .children(Icon(h, "search")), + h.h2("Begin your search"), + h.p( + "Enter a domain name to explore sample prices and availability." + ) + ) + ), + Results(h, model) ), - Results(h, model) - ), - h.footer.class("footer").children( - h.span( - "A Foldkit Domains port to Effect UI · Not affiliated with Vercel" - ), - h.span("Sample data · Demo cart"), - h.a.attr( - "href", - "https://github.com/Effect-TS/effect/tree/main/examples/ui/domains" - ).children( - "View source", - Icon(h, "arrow-up-right") - ) + h.footer + .class("footer") + .children( + h.span( + "A Foldkit Domains port to Effect UI · Not affiliated with Vercel" + ), + h.span("Sample data · Demo cart"), + h.a + .attr("href", "https://github.com/Effect-TS/effect/tree/main/examples/ui/domains") + .children("View source", Icon(h, "arrow-up-right")) + ) ) - ) ) const focusSearchInput = HtmlCommand.focus(SearchInput, () => Component.noop, { diff --git a/examples/ui/domains/src/components/Icon.ts b/examples/ui/domains/src/components/Icon.ts index bff805c1600..52fb88736c5 100644 --- a/examples/ui/domains/src/components/Icon.ts +++ b/examples/ui/domains/src/components/Icon.ts @@ -43,9 +43,9 @@ const Svg = ( attributes: Readonly>, shapes: ReadonlyArray ) => - h.el("svg").attrs({ "aria-hidden": "true", ...attributes }).children( - shapes.map(([tag, shape]) => h.el(tag).attrs(shape)) - ) + h.el("svg") + .attrs({ "aria-hidden": "true", ...attributes }) + .children(shapes.map(([tag, shape]) => h.el(tag).attrs(shape))) export const Logo = (h: Html.H) => Svg(h, { diff --git a/examples/ui/domains/src/domain/Domain.ts b/examples/ui/domains/src/domain/Domain.ts index 49936dfb5a6..dbb586dedaf 100644 --- a/examples/ui/domains/src/domain/Domain.ts +++ b/examples/ui/domains/src/domain/Domain.ts @@ -63,7 +63,10 @@ export const DomainLabel = Schema.String.check( ) export const normalizeLabel = (query: string): string => - query.trim().toLowerCase().replace(/^https?:\/\//, "").split(/[./]/)[0] ?? "" + query.trim() + .toLowerCase() + .replace(/^https?:\/\//, "") + .split(/[./]/)[0] ?? "" export const labelOf = (query: string): string | undefined => { const label = normalizeLabel(query) @@ -100,18 +103,20 @@ export type DomainSearch = typeof DomainSearch.Type export const searchSample = ( { label, limit, offset }: DomainSearch ): ReadonlyArray => - domainCandidates(label).slice(offset, offset + limit).map((domain) => { - if (takenLabels.includes(label) && takenTlds.includes(domain.tld)) { - return Domain.cases.Unavailable.make(domain) - } - const price = samplePrices[domain.tld] ?? 19.99 - return Domain.cases.Available.make({ - ...domain, - price, - renewalPrice: price, - years: 1, - isPremium: false + domainCandidates(label) + .slice(offset, offset + limit) + .map((domain) => { + if (takenLabels.includes(label) && takenTlds.includes(domain.tld)) { + return Domain.cases.Unavailable.make(domain) + } + const price = samplePrices[domain.tld] ?? 19.99 + return Domain.cases.Available.make({ + ...domain, + price, + renewalPrice: price, + years: 1, + isPremium: false + }) }) - }) export class SearchUnavailable extends Schema.TaggedError()("SearchUnavailable", {}) {} diff --git a/examples/ui/domains/src/pages/NotFoundPage.ts b/examples/ui/domains/src/pages/NotFoundPage.ts index 2031388508f..02c8ce2dcf9 100644 --- a/examples/ui/domains/src/pages/NotFoundPage.ts +++ b/examples/ui/domains/src/pages/NotFoundPage.ts @@ -2,15 +2,17 @@ import type { Html } from "effect/ui/html" import { AppRoute } from "../routes.ts" export const NotFoundPage = (h: Html.H, path: string) => - h.main.class( - "mx-auto flex min-h-svh max-w-xl flex-col justify-center gap-6 px-6" - ).children( - h.h1.class("text-4xl font-semibold tracking-tight").children( - "404 — Page Not Found" - ), - h.p.class("text-gray-300").children(`The path "${path}" was not found.`), - h.a.attr("href", AppRoute.Search.href()).class( - "w-fit underline underline-offset-4" + h.main + .class("mx-auto flex min-h-svh max-w-xl flex-col justify-center gap-6 px-6") + .children( + h.h1 + .class("text-4xl font-semibold tracking-tight") + .children("404 — Page Not Found"), + h.p + .class("text-gray-300") + .children(`The path "${path}" was not found.`), + h.a + .attr("href", AppRoute.Search.href()) + .class("w-fit underline underline-offset-4") + .children("← Back to Domains") ) - .children("← Back to Domains") - ) diff --git a/examples/ui/file-preview/src/FilePreview.ts b/examples/ui/file-preview/src/FilePreview.ts index 6cbefef1437..f1eccb084e3 100644 --- a/examples/ui/file-preview/src/FilePreview.ts +++ b/examples/ui/file-preview/src/FilePreview.ts @@ -54,34 +54,40 @@ const FilePreviewDef = Html.component({ const Status = FilePreviewDef.fragment((h, preview: Preview) => Preview.match(preview, { NoFile: () => - h.p.class("text-center text-gray-500").children( - "Choose a text file to preview it." - ), + h.p + .class("text-center text-gray-500") + .children("Choose a text file to preview it."), Reading: ({ name }) => - h.div.class( - "flex items-center justify-between gap-3 p-4 bg-white rounded-lg shadow" - ).children( - h.span.class("text-gray-700").children(`Reading ${name}…`), - h.button.on("click", PreviewMessage.ClickedCancel()) - .class( - BUTTON_CLASS, - "border border-red-300 text-red-600 hover:bg-red-50" - ) - .children("Cancel") - ), + h.div + .class("flex items-center justify-between gap-3 p-4 bg-white rounded-lg shadow") + .children( + h.span + .class("text-gray-700") + .children(`Reading ${name}…`), + h.button + .on("click", PreviewMessage.ClickedCancel()) + .class(BUTTON_CLASS, "border border-red-300 text-red-600 hover:bg-red-50") + .children("Cancel") + ), Read: ({ head, lines, name }) => - h.section.class("flex flex-col gap-2 p-4 bg-white rounded-lg shadow") + h.section + .class("flex flex-col gap-2 p-4 bg-white rounded-lg shadow") .children( - h.h2.class("font-medium text-gray-800").children( - `${name}: ${lines} lines` - ), - h.pre.class("text-sm text-gray-600 overflow-x-auto").children(head) + h.h2 + .class("font-medium text-gray-800") + .children(`${name}: ${lines} lines`), + h.pre + .class("text-sm text-gray-600 overflow-x-auto") + .children(head) ), Cancelled: ({ name }) => - h.p.class("text-center text-gray-500").children( - `Cancelled reading ${name}.` - ), - Failed: ({ name }) => h.p.class("text-center text-red-600").children(`Couldn't read ${name}.`) + h.p + .class("text-center text-gray-500") + .children(`Cancelled reading ${name}.`), + Failed: ({ name }) => + h.p + .class("text-center text-red-600") + .children(`Couldn't read ${name}.`) }) ) @@ -105,20 +111,26 @@ export const FilePreview = FilePreviewDef.make({ }, head: () => [Head.title("Effect UI File Preview Example")], view: (h, preview) => - h.div.class("min-h-screen bg-gray-100 py-8").children( - h.div.class("max-w-lg mx-auto flex flex-col gap-6 px-4").children( - h.h1.class("text-3xl font-bold text-gray-800 text-center").children( - "File Preview" - ), - h.label.class( - BUTTON_CLASS, - "self-center bg-blue-500 text-white hover:bg-blue-600" - ).children( - "Choose a file", - h.input.attr("type", "file").class("sr-only").value("") - .on("change", ({ files }) => PreviewMessage.ChoseFiles({ files })) - ), - Status(h, preview) + h.div + .class("min-h-screen bg-gray-100 py-8") + .children( + h.div + .class("max-w-lg mx-auto flex flex-col gap-6 px-4") + .children( + h.h1 + .class("text-3xl font-bold text-gray-800 text-center") + .children("File Preview"), + h.label + .class(BUTTON_CLASS, "self-center bg-blue-500 text-white hover:bg-blue-600") + .children( + "Choose a file", + h.input + .attr("type", "file") + .class("sr-only") + .value("") + .on("change", ({ files }) => PreviewMessage.ChoseFiles({ files })) + ), + Status(h, preview) + ) ) - ) }) diff --git a/examples/ui/interrupting-commands/src/Uploads.ts b/examples/ui/interrupting-commands/src/Uploads.ts index c6e438cbe71..8280126d9fd 100644 --- a/examples/ui/interrupting-commands/src/Uploads.ts +++ b/examples/ui/interrupting-commands/src/Uploads.ts @@ -83,26 +83,16 @@ const UploadsDef = Html.component({ const UploadAction = UploadsDef.fragment((h, upload: Upload) => { switch (upload.status) { case "Uploading": - return h.button.on( - "click", - UploadsMessage.ClickedCancelUpload({ uploadId: upload.id }) - ) + return h.button + .on("click", UploadsMessage.ClickedCancelUpload({ uploadId: upload.id })) .attr("aria-label", `Cancel upload ${upload.id}`) - .class( - ACTION_BUTTON_CLASS, - "border-red-300 text-red-600 hover:bg-red-50" - ) + .class(ACTION_BUTTON_CLASS, "border-red-300 text-red-600 hover:bg-red-50") .children("Cancel") case "Cancelled": - return h.button.on( - "click", - UploadsMessage.ClickedRestartUpload({ uploadId: upload.id }) - ) + return h.button + .on("click", UploadsMessage.ClickedRestartUpload({ uploadId: upload.id })) .attr("aria-label", `Restart upload ${upload.id}`) - .class( - ACTION_BUTTON_CLASS, - "border-blue-300 text-blue-600 hover:bg-blue-50" - ) + .class(ACTION_BUTTON_CLASS, "border-blue-300 text-blue-600 hover:bg-blue-50") .children("Restart") case "Done": return null @@ -110,30 +100,35 @@ const UploadAction = UploadsDef.fragment((h, upload: Upload) => { }) const UploadRow = UploadsDef.fragment((h, upload: Upload) => - h.li.key(String(upload.id)).class( - "p-4 bg-white rounded-lg shadow flex flex-col gap-2" - ).children( - h.div.class("flex items-center justify-between gap-3").children( - h.div.class("flex items-baseline gap-2 min-w-0").children( - h.span.class("font-medium text-gray-800 truncate").children( - upload.fileName + h.li + .key(String(upload.id)) + .class("p-4 bg-white rounded-lg shadow flex flex-col gap-2") + .children( + h.div + .class("flex items-center justify-between gap-3") + .children( + h.div + .class("flex items-baseline gap-2 min-w-0") + .children( + h.span + .class("font-medium text-gray-800 truncate") + .children(upload.fileName), + h.span + .class("text-sm text-gray-500 shrink-0") + .children(`${upload.sizeMegabytes} MB`) + ), + h.div + .class("flex items-center gap-3 shrink-0") + .children( + h.span + .class("px-2 py-0.5 text-xs font-semibold rounded-full", BADGE_CLASS[upload.status]) + .children(upload.status), + UploadAction(h, upload) + ) ), - h.span.class("text-sm text-gray-500 shrink-0").children( - `${upload.sizeMegabytes} MB` - ) - ), - h.div.class("flex items-center gap-3 shrink-0").children( - h.span.class( - "px-2 py-0.5 text-xs font-semibold rounded-full", - BADGE_CLASS[upload.status] - ) - .children(upload.status), - UploadAction(h, upload) - ) - ), - isUploading(upload) && - h.div.class("h-1.5 rounded-full bg-blue-400 animate-pulse") - ) + isUploading(upload) && + h.div.class("h-1.5 rounded-full bg-blue-400 animate-pulse") + ) ) export const UploadsNoDeps = UploadsDef.make({ @@ -188,33 +183,39 @@ export const UploadsNoDeps = UploadsDef.make({ }, head: () => [Head.title("Effect UI Interrupting Commands Example")], view: (h, model) => - h.div.class("min-h-screen bg-gray-100 py-8").children( - h.div.class("max-w-lg mx-auto flex flex-col gap-6 px-4").children( - h.h1.class("text-3xl font-bold text-gray-800 text-center").children( - "File Uploads" - ), - h.div.class("flex justify-center gap-3").children( - h.button.on("click", UploadsMessage.ClickedStartUpload()) - .class( - "px-4 py-2 rounded-md bg-blue-500 text-white font-medium hover:bg-blue-600 transition" - ) - .children("Upload a file"), - model.uploads.some(isUploading) && - h.button.on("click", UploadsMessage.ClickedCancelAllUploads()) - .class( - "px-4 py-2 rounded-md border border-red-300 text-red-600 font-medium hover:bg-red-50 transition" - ) - .children("Cancel all") - ), - model.uploads.length === 0 - ? h.p.class("text-center text-gray-500").children( - "Nothing here yet. Start an upload." - ) - : h.ul.class("flex flex-col gap-3").children( - model.uploads.map((upload) => UploadRow(h, upload)) + h.div + .class("min-h-screen bg-gray-100 py-8") + .children( + h.div + .class("max-w-lg mx-auto flex flex-col gap-6 px-4") + .children( + h.h1 + .class("text-3xl font-bold text-gray-800 text-center") + .children("File Uploads"), + h.div + .class("flex justify-center gap-3") + .children( + h.button + .on("click", UploadsMessage.ClickedStartUpload()) + .class("px-4 py-2 rounded-md bg-blue-500 text-white font-medium hover:bg-blue-600 transition") + .children("Upload a file"), + model.uploads.some(isUploading) && + h.button + .on("click", UploadsMessage.ClickedCancelAllUploads()) + .class( + "px-4 py-2 rounded-md border border-red-300 text-red-600 font-medium hover:bg-red-50 transition" + ) + .children("Cancel all") + ), + model.uploads.length === 0 + ? h.p + .class("text-center text-gray-500") + .children("Nothing here yet. Start an upload.") + : h.ul + .class("flex flex-col gap-3") + .children(model.uploads.map((upload) => UploadRow(h, upload))) ) ) - ) }) export const Uploads = UploadsNoDeps.pipe(Component.provide(UploadFile.layer)) diff --git a/examples/ui/launch/dprint.json b/examples/ui/launch/dprint.json index b35381b14b8..b64fe64a14b 100644 --- a/examples/ui/launch/dprint.json +++ b/examples/ui/launch/dprint.json @@ -1,10 +1,20 @@ { "$schema": "https://dprint.dev/schemas/v0.json", - "incremental": false, + "incremental": true, "indentWidth": 2, "lineWidth": 70, "newLineKind": "lf", + "exec": { + "cwd": "${configDir}/../../..", + "associations": ["**/*.{ts,tsx}", "!**/*.test.{ts,tsx}"], + "commands": [{ + "command": "node scripts/stack-chains.mjs {{ext}}", + "associations": ["**/*.{ts,tsx}"], + "cacheKeyFiles": ["scripts/stack-chains.mjs"] + }] + }, "typescript": { + "associations": ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"], "semiColons": "asi", "quoteStyle": "alwaysDouble", "trailingCommas": "never", @@ -13,6 +23,7 @@ }, "excludes": ["**/dist", "**/*.tsbuildinfo"], "plugins": [ + "https://plugins.dprint.dev/exec-0.9.0.json@939c28cce4022e2676ac9596585448c16abee12b8ccb0320a9eb9596ade1c219", "https://plugins.dprint.dev/typescript-0.93.4.wasm", "https://plugins.dprint.dev/markdown-0.20.0.wasm", "https://plugins.dprint.dev/json-0.21.1.wasm" diff --git a/examples/ui/launch/src/LaunchPage.ts b/examples/ui/launch/src/LaunchPage.ts index d428410f217..6922655efd8 100644 --- a/examples/ui/launch/src/LaunchPage.ts +++ b/examples/ui/launch/src/LaunchPage.ts @@ -48,25 +48,34 @@ const Caption = ( content: Markdown.InlineContent ) => content.length > 0 && - h.figcaption.class(caption).children(content) + h.figcaption + .class(caption) + .children(content) const inline: Pick< Markdown.Views, "InlineCode" | "Link" | "Strong" > = { InlineCode: (h, { value }) => - h.code.class( - "rounded-sm bg-muted px-[0.35em] py-[0.1em] text-[0.86em]", - "wrap-anywhere [font-variant-ligatures:none]" - ).children(value), + h.code + .class( + "rounded-sm bg-muted px-[0.35em] py-[0.1em] text-[0.86em]", + "wrap-anywhere [font-variant-ligatures:none]" + ) + .children(value), Link: (h, { title, url }, content) => - h.a.class( - "underline decoration-border-strong underline-offset-3", - "hover:decoration-accent-text" - ).attr("href", url).attr("title", Option.getOrUndefined(title)) + h.a + .class( + "underline decoration-border-strong underline-offset-3", + "hover:decoration-accent-text" + ) + .attr("href", url) + .attr("title", Option.getOrUndefined(title)) .children(content), Strong: (h, _strong, content) => - h.strong.class("font-semibold").children(content) + h.strong + .class("font-semibold") + .children(content) } const layouts = { @@ -77,15 +86,21 @@ const layouts = { // A bullet with an icon: a row with the icon in a column of its // own, so the label and the description under it share a left edge. const Card = (h: Html.H, feature: Feature) => - h.li.class("grid grid-cols-[2.25rem_minmax(0,1fr)] gap-x-4") + h.li + .class("grid grid-cols-[2.25rem_minmax(0,1fr)] gap-x-4") .children( - h.span.class( - "grid size-9 place-items-center rounded-lg text-accent-text", - "bg-[color-mix(in_oklab,var(--color-accent)_10%,var(--color-background))]" - ).children(Icon(h, feature.icon, { class: "size-[1.125rem]" })), + h.span + .class( + "grid size-9 place-items-center rounded-lg text-accent-text", + "bg-[color-mix(in_oklab,var(--color-accent)_10%,var(--color-background))]" + ) + .children( + Icon(h, feature.icon, { class: "size-[1.125rem]" }) + ), h.div.children( // Level with the middle of the icon. - h.p.class("pt-[0.4375rem] text-base/[1.4] font-semibold") + h.p + .class("pt-[0.4375rem] text-base/[1.4] font-semibold") .children(feature.title), Markdown.viewBlocks( h, @@ -99,10 +114,12 @@ const Card = (h: Html.H, feature: Feature) => views: { ...inline, Paragraph: (h, _paragraph, content) => - h.p.class( - "mt-1 text-[0.9375rem]/[1.6] text-pretty", - "text-prose-foreground" - ).children(content) + h.p + .class( + "mt-1 text-[0.9375rem]/[1.6] text-pretty", + "text-prose-foreground" + ) + .children(content) } } ) @@ -162,278 +179,370 @@ export const LaunchPage = Html.component({ head: () => [Head.title(meta.title)], view: (h) => { const { articleUrl, snippets } = h.props - return h.div.class( - "[--nav-bar:3rem]", - "[--nav-inset:max(clamp(20px,5vw,48px),calc((100%-68ch)/2))]", - "rail:grid rail:[--nav-bar:0px] rail:[--nav-rail:12rem]", - "rail:[--nav-gutter:48px]", - "rail:[--nav-article:calc(1180px+2*var(--nav-gutter))]", - // The rail and the article are centered together, so the - // margins beside them are equal. - "rail:grid-cols-[var(--nav-rail)_minmax(0,var(--nav-article))]", - "rail:justify-center" - ).children( - h.a.class("skip-link").attr("href", "#content").children( - "Skip to content" - ), - Nav(h, { props: { sections } }), - // Focusable from script only, so the skip link moves focus here. - h.main.id("content").attr("tabindex", "-1").class( - "focus:outline-none", - "article-main px-[clamp(20px,5vw,48px)] pt-10 pb-24", - "[--column:68ch] [--wide:1180px] rail:px-(--nav-gutter)" - ).children( - h.div.class("article-masthead").children( - h.a.class("article-brand").attr( - "href", - "https://effect.website/" - ) - .children( - // The logo comes in black and in white, so the browser - // picks the file that suits the color scheme. - h.picture.children( - h.source.attr("srcset", "/effect-ui-white.svg").attr( - "media", - "(prefers-color-scheme: dark)" - ), - h.img.attr("src", "/effect-ui-black.svg").attr( - "alt", - "Effect UI" - ).attr("width", "123").attr("height", "28") - ) - ), - h.div.class("article-links").children( - h.a.attr("href", "https://effect.website/docs/v4") - .children("Effect docs"), - h.a.attr("href", "https://github.com/Effect-TS/effect") - .class("inline-flex items-center gap-0.5").children( - "GitHub", - Icon(h, "external", { class: "size-3.5" }) - ) - ) - ), - h.header.class("article-header").children( - h.div.class("mx-auto max-w-(--column)").children( - h.p.class("article-eyebrow").children( - "// PUBLIC PREVIEW" - ), - h.h1.class( - "text-[clamp(2.2rem,5.2vw,3.6rem)]/[1.08] font-bold", - "tracking-[-0.035em] text-balance" - ).children(meta.title), - h.p.class( - "mt-4 flex flex-wrap items-center gap-x-2.5 gap-y-1", - "font-mono text-[11px] tracking-[0.04em]", - "text-muted-foreground font-features-[normal]" - ).children( - dates.flatMap(({ iso, label, text }, index) => [ - index > 0 && - h.span.attr("aria-hidden", "true").children("·"), - h.span.children( - label, - " ", - h.time.attr("datetime", iso).children(text) - ) - ]) - ) + return h.div + .class( + "[--nav-bar:3rem]", + "[--nav-inset:max(clamp(20px,5vw,48px),calc((100%-68ch)/2))]", + "rail:grid rail:[--nav-bar:0px] rail:[--nav-rail:12rem]", + "rail:[--nav-gutter:48px]", + "rail:[--nav-article:calc(1180px+2*var(--nav-gutter))]", + // The rail and the article are centered together, so the + // margins beside them are equal. + "rail:grid-cols-[var(--nav-rail)_minmax(0,var(--nav-article))]", + "rail:justify-center" + ) + .children( + h.a + .class("skip-link") + .attr("href", "#content") + .children("Skip to content"), + Nav(h, { props: { sections } }), + // Focusable from script only, so the skip link moves focus here. + h.main + .id("content") + .attr("tabindex", "-1") + .class( + "focus:outline-none", + "article-main px-[clamp(20px,5vw,48px)] pt-10 pb-24", + "[--column:68ch] [--wide:1180px] rail:px-(--nav-gutter)" ) - ), - Markdown.viewBlocks(h, article, { - views: { - Heading: (h, node, content) => { - const { id, isNested, label } = fromHeading(node) - // The link is beside the heading, not inside it, so the - // heading's name stays its own text. - return h.div.class( - block, - "group relative flex items-baseline font-[620]", - isNested - ? "mt-12 text-lg/[1.35] tracking-[-0.01em]" - : "mt-18 text-[1.5rem]/[1.3] tracking-[-0.02em]" - ).children( - Permalink(h, { key: id, props: { id, label } }), - isNested - ? h.h3.id(id).class(heading).children(content) - : h.h2.id(id).class(heading).children(content) - ) - }, - Paragraph: (h, _paragraph, content) => - h.p.class( - "[main>&]:mx-auto [main>&]:max-w-(--column)", - "mt-[1.1em] text-pretty first:mt-0", - // The lede: the first paragraph, set larger and closed - // off from the article by a rule. - "[header+&]:mt-8 [header+&]:mb-8 [header+&]:border-b", - "[header+&]:border-border [header+&]:pb-8", - "[header+&]:text-[1.3125rem]/[1.5]", - "[header+&]:tracking-[-0.011em] [header+&]:text-balance", - "compact:[header+&]:text-[1.1875rem]/[1.5]" - ).children(content), - List: (h, list, items) => - list.isOrdered - ? Markdown.defaultViews.List(h, list, items) - : list.items.every((item) => - fromItem(item) !== undefined + .children( + h.div + .class("article-masthead") + .children( + h.a + .class("article-brand") + .attr("href", "https://effect.website/") + .children( + // The logo comes in black and in white, so the browser + // picks the file that suits the color scheme. + h.picture.children( + h.source + .attr("srcset", "/effect-ui-white.svg") + .attr( + "media", + "(prefers-color-scheme: dark)" + ), + h.img + .attr("src", "/effect-ui-black.svg") + .attr("alt", "Effect UI") + .attr("width", "123") + .attr("height", "28") + ) + ), + h.div + .class("article-links") + .children( + h.a + .attr("href", "https://effect.website/docs/v4") + .children("Effect docs"), + h.a + .attr( + "href", + "https://github.com/Effect-TS/effect" + ) + .class("inline-flex items-center gap-0.5") + .children( + "GitHub", + Icon(h, "external", { class: "size-3.5" }) + ) ) - ? h.ul.class( - block, - layouts[ - list.items.flatMap((item) => - fromItem(item)?.layout ?? [] - )[0] ?? "rows" - ] - ).children(items) - : h.ul.class( - block, - "mt-[1.1em] grid list-disc gap-[0.5em] pl-[1.25em]", - "text-pretty" - ).children(items), - ListItem: (h, item, blocks) => { - const feature = fromItem(item) - return feature === undefined - ? Markdown.defaultViews.ListItem(h, item, blocks) - : Card(h, feature) - }, - Table: (h, _table, headerRow, bodyRows) => - h.div.class(block, "mt-[1.4em] overflow-x-auto") - .children( - h.table.class( - "w-full border-collapse text-[0.9375rem]/[1.5]", - "compact:text-[0.875rem]/[1.5]" - ).children( - h.thead.children(headerRow), - h.tbody.children(bodyRows) - ) - ), - TableCell: (h, _cell, content, _alignment, isHeader) => - isHeader - ? h.th.attr("scope", "col").class( - "border-b border-border-strong pe-5 pb-2 text-start", - "font-mono text-[0.6875rem] font-medium", - "tracking-[0.08em] uppercase text-muted-foreground", - "font-features-[normal] last:pe-0 compact:pe-3" - ).children(content) - : h.td.class( - "border-b border-border py-3 pe-5 align-top", - "text-prose-foreground last:pe-0 compact:pe-3", - // A name in code stays in one piece. - "[&_code]:whitespace-nowrap", - "min-[521px]:last:whitespace-nowrap", - "[tr:last-child>&]:border-b-0" - ).children(content), - CodeBlock: (h, { value }) => - h.pre.class( - block, - "mt-[1.1em] rounded-lg border border-border px-3.5 py-3", - "text-code wrap-anywhere whitespace-pre-wrap", - "[font-variant-ligatures:none]" - ).children(h.code.children(value)), - ...inline - }, - islands: Markdown.islandsFor(Islands, { - AgentPrompts: (h) => - AgentPrompts(h, { - props: { - prompts: prompts.map((prompt) => ({ - ...prompt, - prompt: prompt.prompt.replace("$URL", articleUrl) - })) - } - }), - // AgentPrompts reads these from the document and draws - // them itself, so what this returns is never shown. - AgentPrompt: (h) => h.span, - Chips: (h, { items, label }) => - h.div.class(block, "mt-6").children( - h.p.class( - "font-mono text-[0.6875rem] tracking-[0.08em]", - "uppercase text-muted-foreground", - "font-features-[normal]" - ).children(label), - h.ul.class("mt-2.5 flex flex-wrap gap-2").children( - items.split(",").map((item) => - h.li.key(item.trim()).class( - "rounded-full border border-border bg-muted", - "px-3 py-1 text-[0.8125rem]/[1.4]", - "text-prose-foreground first-letter:uppercase" - ).children(item.trim()) - ) - ) ), - PageOnly: (h, _attributes, content) => - h.div.class("mx-auto mt-[1.1em] max-w-(--column)") - .children(content), - Architecture: (h) => Architecture(h), - Diagram: (h, { scenario }) => - Diagram(h, { key: scenario, props: { scenario } }), - Counter: (h, { code, label }, caption, occurrence) => - h.figure.class(listing).children( - snippets[code].map((snippet, index) => - h.div.key(snippet.name).children( - Code(h, snippet, { - preview: previewOf(snippet), - // The Counter's grid tracks are sized by the - // panel, never by a label, so a changing label - // or count can't move them. - demo: index === 0 && - h.div.class( - "live-demo @container border-b border-border", - "bg-background px-3.5 py-4", - "[&>div]:grid [&>div]:grid-cols-2", - "[&>div]:items-center", - // The two add buttons share the width - // one of the others takes. - "[&>div>:not(.counter-add)]:col-span-2", - "@min-[312px]:[&>div]:grid-cols-4", - "@min-[560px]:[&>div]:grid-cols-[minmax(0,2fr)_repeat(2,minmax(0,1.5fr))_repeat(2,minmax(0,3fr))]", - "@min-[560px]:[&>div>:not(.counter-add)]:col-span-1", - "[&_output]:text-center", - "[&_output]:text-[2rem]/[normal]", - "[&_output]:font-features-[normal]", - "[&_button]:font-features-[normal]", - "[&_button]:whitespace-nowrap" - ).attr("role", "group") - .attr("aria-label", label).children( - Counter(h, { - key: `counter-${occurrence}` - }) + h.header + .class("article-header") + .children( + h.div + .class("mx-auto max-w-(--column)") + .children( + h.p + .class("article-eyebrow") + .children("// PUBLIC PREVIEW"), + h.h1 + .class( + "text-[clamp(2.2rem,5.2vw,3.6rem)]/[1.08] font-bold", + "tracking-[-0.035em] text-balance" + ) + .children(meta.title), + h.p + .class( + "mt-4 flex flex-wrap items-center gap-x-2.5 gap-y-1", + "font-mono text-[11px] tracking-[0.04em]", + "text-muted-foreground font-features-[normal]" + ) + .children( + dates.flatMap(( + { iso, label, text }, + index + ) => [ + index > 0 && + h.span + .attr("aria-hidden", "true") + .children("·"), + h.span.children( + label, + " ", + h.time + .attr("datetime", iso) + .children(text) ) - }) + ]) + ) ) - ), - Caption(h, caption) ), - Listing: (h, { code, example, whole }, caption) => - Listing(h, { - files: snippets[code], - example: example === "counter" && - Page(h, { key: "example" }), - whole: whole === "true", - caption - }), - PlayTest: (h) => - PlayTest(h, { - props: { - tests: [ - { id: "counter", snippet: snippets.play[0] }, - { id: "signIn", snippet: snippets.playSignIn[0] }, - { id: "snake", snippet: snippets.playSnake[0] } - ] - } - }), - PerformanceChart: (h) => PerformanceChart(h), - AllResults: (h) => AllResults(h, {}), - Kit: (h) => Kit(h, {}), - LauncherPointer: (h, _attributes, content) => - LauncherPointer(h, content), - Footer: (h, _attributes, content) => - h.footer.class( - "mx-auto mt-24 max-w-[68ch] border-t border-border pt-6", - "text-sm text-muted-foreground" - ).children(content) - }) - }) + Markdown.viewBlocks(h, article, { + views: { + Heading: (h, node, content) => { + const { id, isNested, label } = fromHeading(node) + // The link is beside the heading, not inside it, so the + // heading's name stays its own text. + return h.div + .class( + block, + "group relative flex items-baseline font-[620]", + isNested + ? "mt-12 text-lg/[1.35] tracking-[-0.01em]" + : "mt-18 text-[1.5rem]/[1.3] tracking-[-0.02em]" + ) + .children( + Permalink(h, { key: id, props: { id, label } }), + isNested + ? h.h3 + .id(id) + .class(heading) + .children(content) + : h.h2 + .id(id) + .class(heading) + .children(content) + ) + }, + Paragraph: (h, _paragraph, content) => + h.p + .class( + "[main>&]:mx-auto [main>&]:max-w-(--column)", + "mt-[1.1em] text-pretty first:mt-0", + // The lede: the first paragraph, set larger and closed + // off from the article by a rule. + "[header+&]:mt-8 [header+&]:mb-8 [header+&]:border-b", + "[header+&]:border-border [header+&]:pb-8", + "[header+&]:text-[1.3125rem]/[1.5]", + "[header+&]:tracking-[-0.011em] [header+&]:text-balance", + "compact:[header+&]:text-[1.1875rem]/[1.5]" + ) + .children(content), + List: (h, list, items) => + list.isOrdered + ? Markdown.defaultViews.List(h, list, items) + : list.items.every((item) => + fromItem(item) !== undefined + ) + ? h.ul + .class( + block, + layouts[ + list.items.flatMap((item) => + fromItem(item)?.layout ?? [] + )[0] ?? "rows" + ] + ) + .children(items) + : h.ul + .class( + block, + "mt-[1.1em] grid list-disc gap-[0.5em] pl-[1.25em]", + "text-pretty" + ) + .children(items), + ListItem: (h, item, blocks) => { + const feature = fromItem(item) + return feature === undefined + ? Markdown.defaultViews.ListItem(h, item, blocks) + : Card(h, feature) + }, + Table: (h, _table, headerRow, bodyRows) => + h.div + .class(block, "mt-[1.4em] overflow-x-auto") + .children( + h.table + .class( + "w-full border-collapse text-[0.9375rem]/[1.5]", + "compact:text-[0.875rem]/[1.5]" + ) + .children( + h.thead.children(headerRow), + h.tbody.children(bodyRows) + ) + ), + TableCell: ( + h, + _cell, + content, + _alignment, + isHeader + ) => + isHeader + ? h.th + .attr("scope", "col") + .class( + "border-b border-border-strong pe-5 pb-2 text-start", + "font-mono text-[0.6875rem] font-medium", + "tracking-[0.08em] uppercase text-muted-foreground", + "font-features-[normal] last:pe-0 compact:pe-3" + ) + .children(content) + : h.td + .class( + "border-b border-border py-3 pe-5 align-top", + "text-prose-foreground last:pe-0 compact:pe-3", + // A name in code stays in one piece. + "[&_code]:whitespace-nowrap", + "min-[521px]:last:whitespace-nowrap", + "[tr:last-child>&]:border-b-0" + ) + .children(content), + CodeBlock: (h, { value }) => + h.pre + .class( + block, + "mt-[1.1em] rounded-lg border border-border px-3.5 py-3", + "text-code wrap-anywhere whitespace-pre-wrap", + "[font-variant-ligatures:none]" + ) + .children(h.code.children(value)), + ...inline + }, + islands: Markdown.islandsFor(Islands, { + AgentPrompts: (h) => + AgentPrompts(h, { + props: { + prompts: prompts.map((prompt) => ({ + ...prompt, + prompt: prompt.prompt.replace( + "$URL", + articleUrl + ) + })) + } + }), + // AgentPrompts reads these from the document and draws + // them itself, so what this returns is never shown. + AgentPrompt: (h) => h.span, + Chips: (h, { items, label }) => + h.div + .class(block, "mt-6") + .children( + h.p + .class( + "font-mono text-[0.6875rem] tracking-[0.08em]", + "uppercase text-muted-foreground", + "font-features-[normal]" + ) + .children(label), + h.ul + .class("mt-2.5 flex flex-wrap gap-2") + .children( + items.split(",").map((item) => + h.li + .key(item.trim()) + .class( + "rounded-full border border-border bg-muted", + "px-3 py-1 text-[0.8125rem]/[1.4]", + "text-prose-foreground first-letter:uppercase" + ) + .children(item.trim()) + ) + ) + ), + PageOnly: (h, _attributes, content) => + h.div + .class("mx-auto mt-[1.1em] max-w-(--column)") + .children(content), + Architecture: (h) => Architecture(h), + Diagram: (h, { scenario }) => + Diagram(h, { key: scenario, props: { scenario } }), + Counter: (h, { code, label }, caption, occurrence) => + h.figure + .class(listing) + .children( + snippets[code].map((snippet, index) => + h.div + .key(snippet.name) + .children( + Code(h, snippet, { + preview: previewOf(snippet), + // The Counter's grid tracks are sized by the + // panel, never by a label, so a changing label + // or count can't move them. + demo: index === 0 && + h.div + .class( + "live-demo @container border-b border-border", + "bg-background px-3.5 py-4", + "[&>div]:grid [&>div]:grid-cols-2", + "[&>div]:items-center", + // The two add buttons share the width + // one of the others takes. + "[&>div>:not(.counter-add)]:col-span-2", + "@min-[312px]:[&>div]:grid-cols-4", + "@min-[560px]:[&>div]:grid-cols-[minmax(0,2fr)_repeat(2,minmax(0,1.5fr))_repeat(2,minmax(0,3fr))]", + "@min-[560px]:[&>div>:not(.counter-add)]:col-span-1", + "[&_output]:text-center", + "[&_output]:text-[2rem]/[normal]", + "[&_output]:font-features-[normal]", + "[&_button]:font-features-[normal]", + "[&_button]:whitespace-nowrap" + ) + .attr("role", "group") + .attr("aria-label", label) + .children( + Counter(h, { + key: `counter-${occurrence}` + }) + ) + }) + ) + ), + Caption(h, caption) + ), + Listing: (h, { code, example, whole }, caption) => + Listing(h, { + files: snippets[code], + example: example === "counter" && + Page(h, { key: "example" }), + whole: whole === "true", + caption + }), + PlayTest: (h) => + PlayTest(h, { + props: { + tests: [ + { id: "counter", snippet: snippets.play[0] }, + { + id: "signIn", + snippet: snippets.playSignIn[0] + }, + { + id: "snake", + snippet: snippets.playSnake[0] + } + ] + } + }), + PerformanceChart: (h) => PerformanceChart(h), + AllResults: (h) => AllResults(h, {}), + Kit: (h) => Kit(h, {}), + LauncherPointer: (h, _attributes, content) => + LauncherPointer(h, content), + Footer: (h, _attributes, content) => + h.footer + .class( + "mx-auto mt-24 max-w-[68ch] border-t border-border pt-6", + "text-sm text-muted-foreground" + ) + .children(content) + }) + }) + ) ) - ) } }) diff --git a/examples/ui/launch/src/autocounter/Counter.ts b/examples/ui/launch/src/autocounter/Counter.ts index 54264ad3e9f..273640c818e 100644 --- a/examples/ui/launch/src/autocounter/Counter.ts +++ b/examples/ui/launch/src/autocounter/Counter.ts @@ -68,35 +68,48 @@ export const Counter = Html.component({ ) ], view: (h, model) => - h.div.class("counter").children( - h.output.class("counter-value").children(String(model.count)), - // Button is a view function from the UI kit, not a Component. - // It returns a