### Run Example API Server Source: https://prefab.prefect.io/docs/running/api Start the development server for the Hitchhiker's Guide example application. ```bash uvicorn examples.hitchhikers_guide.api_server:app --reload ``` -------------------------------- ### Hitchhiker's Guide Dashboard Example Source: https://prefab.prefect.io/docs This example demonstrates the Prefab UI framework by showcasing the 'Hitchhiker's Guide' dashboard. It includes imports for various Prefab UI components, actions, and reactive programming utilities. To run this example, use the 'prefab serve' or 'prefab export' commands. ```python """The Hitchhiker's Guide dashboard from the Prefab welcome page. Run with: prefab serve examples/hitchhikers-guide/dashboard.py prefab export examples/hitchhikers-guide/dashboard.py """ from prefab_ui import PrefabApp from prefab_ui.actions import SetInterval, SetState, ShowToast from prefab_ui.components import ( Alert, AlertDescription, AlertTitle, Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Carousel, Checkbox, Column, Combobox, ComboboxOption, DataTable, DataTableColumn, DatePicker, Dialog, Grid, GridItem, HoverCard, Loader, Metric, Muted, P, Progress, Radio, RadioGroup, Ring, Row, Separator, Slider, Switch, Text, Tooltip, ) from prefab_ui.components.charts import ( BarChart, ChartSeries, RadarChart, Sparkline, ) from prefab_ui.components.control_flow import Else, If from prefab_ui.rx import Rx ctx_tick = Rx("ctx_tick") ``` -------------------------------- ### Run Hitchhiker's Guide MCP Server Source: https://prefab.prefect.io/docs/running/fastmcp Execute the Hitchhiker's Guide MCP server example using `uv`. This example demonstrates a complete working MCP server with search, dialog-based entry creation, inline deletion, and error handling. ```bash uv run examples/hitchhikers-guide/mcp_server.py ``` -------------------------------- ### Prefab UI Hitchhiker's Guide Dashboard Example Source: https://prefab.prefect.io/docs/welcome This Python script demonstrates the creation of the Hitchhiker's Guide dashboard using Prefab UI components. It includes setup instructions and examples of various components like Grid, Card, Combobox, and Rx for state management. ```python """The Hitchhiker's Guide dashboard from the Prefab welcome page. Run with: prefab serve examples/hitchhikers-guide/dashboard.py prefab export examples/hitchhikers-guide/dashboard.py """ from prefab_ui import PrefabApp from prefab_ui.actions import SetInterval, SetState, ShowToast from prefab_ui.components import ( Alert, AlertDescription, AlertTitle, Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Carousel, Checkbox, Column, Combobox, ComboboxOption, DataTable, DataTableColumn, DatePicker, Dialog, Grid, GridItem, HoverCard, Loader, Metric, Muted, P, Progress, Radio, RadioGroup, Ring, Row, Separator, Slider, Switch, Text, Tooltip, ) from prefab_ui.components.charts import ( BarChart, ChartSeries, RadarChart, Sparkline, ) from prefab_ui.components.control_flow import Else, If from prefab_ui.rx import Rx ctx_tick = Rx("ctx_tick") # Context window: climbs from 24% to ~78%, then resets ctx_pct = (ctx_tick % 20) * 3 + 20 ctx_variant = (ctx_pct > 70).then( "destructive", (ctx_pct <= 33).then("success", "default") ) with PrefabApp( title="Prefab Showcase", state={"ctx_tick": 0, "improbability": 42}, on_mount=SetInterval( 400, on_tick=SetState("ctx_tick", ctx_tick + 1), ), ) as app: with Grid(columns={"default": 1, "md": 2, "lg": 4}, gap=4): # ── Col 1 ───────────────────────────────────────────────────────── with Column(gap=4): with Card(): with CardHeader(): CardTitle("Register Towel") CardDescription("The most important item in the galaxy") with CardContent(): with Column(gap=3): with Combobox( placeholder="Type...", search_placeholder="Search types...", ): ComboboxOption("Bath", value="bath") ComboboxOption("Beach", value="beach") ComboboxOption("Interstellar", value="interstellar") ComboboxOption("Microfiber", value="micro") ``` -------------------------------- ### Run Actions on App Mount Source: https://prefab.prefect.io/docs/reference/app Use `on_mount` to perform setup actions like fetching data or starting intervals when the application loads. It can be used with `PrefabApp` and other components, firing when they enter the DOM. ```python from prefab_ui.actions import SetState from prefab_ui.actions.mcp import CallTool from prefab_ui.actions.timing import SetInterval from prefab_ui.rx import RESULT with PrefabApp( state={\"stats\": {}}, on_mount=SetInterval( duration=3000, on_tick=CallTool( "get_stats", on_success=SetState("stats", RESULT), ), ), ) as app: Metric(label="CPU", value=STATE.stats.cpu + "%" ) ``` -------------------------------- ### Instant Tooltips Example Source: https://prefab.prefect.io/docs/components/tooltip Example demonstrating how to use the `delay=0` parameter for instant tooltips. ```APIDOC ## Instant Tooltips Example ### Description Demonstrates how to use the `delay=0` parameter for instant tooltips, useful in dashboards or status displays where users are scanning quickly. ### Code Example (Python) ```python from prefab_ui.components import Badge, Row, Tooltip with Row(gap=4): with Tooltip("Deployed 2h ago", delay=0): Badge("In Orbit") with Tooltip("64% — ETA 12 min", delay=0): Badge("Deploying", variant="secondary") with Tooltip("Position 3 of 8", delay=0): Badge("Queued", variant="outline") ``` ### Code Example (JSON Protocol) ```json { "view": { "cssClass": "gap-4", "type": "Row", "children": [ { "type": "Tooltip", "content": "Deployed 2h ago", "delay": 0, "children": [{"type": "Badge", "label": "In Orbit", "variant": "default"}] }, { "type": "Tooltip", "content": "64% — ETA 12 min", "delay": 0, "children": [{"type": "Badge", "label": "Deploying", "variant": "secondary"}] }, { "type": "Tooltip", "content": "Position 3 of 8", "delay": 0, "children": [{"type": "Badge", "label": "Queued", "variant": "outline"}] } ] } } ``` ``` -------------------------------- ### Tabs with State Example Source: https://prefab.prefect.io/docs/components/tabs Example demonstrating how to use the `name` parameter to sync the active tab with client state and control it with buttons. ```APIDOC ## State Tracking Give Tabs a `name` to sync the active tab with client state. Other components can then read or change which tab is active — useful for building wizard flows or linking navigation between different parts of the UI. ### Request Example ```python from prefab_ui.components import Button, Column, Row, Tab, Tabs, Text from prefab_ui.actions import SetState with Column(gap=4): with Tabs(name="activeTab", value="general"): with Tab("General", value="general"): Text("General settings here.") with Tab("Advanced", value="advanced"): Text("Advanced settings here.") with Row(gap=2): Button("Go to General", on_click=SetState("activeTab", "general")) Button("Go to Advanced", on_click=SetState("activeTab", "advanced")) ``` ``` -------------------------------- ### Install Prefab UI Source: https://prefab.prefect.io/docs Use this command to install the Prefab UI package. Prefab requires Python 3.10+. ```bash pip install prefab-ui ``` -------------------------------- ### Install Prefab UI with pip Source: https://prefab.prefect.io/docs/getting-started/installation Use this command to install the prefab-ui package using pip. This is an alternative to using uv. Prefab requires Python 3.10+. ```bash pip install prefab-ui ``` -------------------------------- ### Verify Prefab Installation Source: https://prefab.prefect.io/docs/getting-started/installation Run this command after installation to check the installed Prefab version. This helps confirm that the installation was successful and that the CLI is accessible. ```bash prefab version ``` -------------------------------- ### Initialize Prefab UI Dashboard Source: https://prefab.prefect.io/docs/welcome Demonstrates the setup of a PrefabApp with reactive state and an interval-based update mechanism. ```python """The Hitchhiker's Guide dashboard from the Prefab welcome page. Run with: prefab serve examples/hitchhikers-guide/dashboard.py prefab export examples/hitchhikers-guide/dashboard.py """ from prefab_ui import PrefabApp from prefab_ui.actions import SetInterval, SetState, ShowToast from prefab_ui.components import ( Alert, AlertDescription, AlertTitle, Badge, Button, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Carousel, Checkbox, Column, Combobox, ComboboxOption, DataTable, DataTableColumn, DatePicker, Dialog, Grid, GridItem, HoverCard, Loader, Metric, Muted, P, Progress, Radio, RadioGroup, Ring, Row, Separator, Slider, Switch, Text, Tooltip, ) from prefab_ui.components.charts import ( BarChart, ChartSeries, RadarChart, Sparkline, ) from prefab_ui.components.control_flow import Else, If from prefab_ui.rx import Rx ctx_tick = Rx("ctx_tick") # Context window: climbs from 24% to ~78%, then resets ctx_pct = (ctx_tick % 20) * 3 + 20 ctx_variant = (ctx_pct > 70).then( "destructive", (ctx_pct <= 33).then("success", "default") ) with PrefabApp( title="Prefab Showcase", state={"ctx_tick": 0, "improbability": 42}, on_mount=SetInterval( 400, on_tick=SetState("ctx_tick", ctx_tick + 1), ), ) as app: with Grid(columns={"default": 1, "md": 2, "lg": 4}, gap=4): # ── Col 1 ───────────────────────────────────────────────────────── with Column(gap=4): with Card(): with CardHeader(): CardTitle("Register Towel") CardDescription("The most important item in the galaxy") with CardContent(): with Column(gap=3): with Combobox( placeholder="Type...", search_placeholder="Search types...", ): ComboboxOption("Bath", value="bath") ``` -------------------------------- ### Minimal Prefect UI Theme Example Source: https://prefab.prefect.io/docs/styling/themes Applies a minimal theme to Prefect UI components, removing default padding and gaps for full control over layout. This example demonstrates how to use the `Minimal` theme and displays system status with progress bars and badges. ```python from prefab_ui.app import PrefabApp from prefab_ui.themes import Minimal from prefab_ui.components import Column, Row, H2, Muted, Progress, Badge with Column(gap=4) as view: H2("System Status") Muted("Last checked 2 minutes ago") with Column(gap=2): Progress(value=92, variant="success", label="API") Progress(value=67, label="Workers") Progress(value=34, variant="warning", label="Queue") with Row(gap=2): Badge("3 healthy", variant="success") Badge("1 degraded", variant="warning") PrefabApp(view=view, theme=Minimal()) ``` -------------------------------- ### GET Request with Query Parameters Source: https://prefab.prefect.io/docs/actions/fetch Use the `Fetch.get` classmethod for GET requests. It accepts a URL and an optional `params` dictionary for query parameters. Ensure `prefab_ui.rx` is imported. ```python from prefab_ui.rx import Rx query = Rx("query") Fetch.get("/api/search", params={"q": query, "page": "1"}) ``` -------------------------------- ### Create a Dashboard with Prefab Source: https://prefab.prefect.io/docs/examples/cross-filter Example of creating a dashboard using Prefab, including layout and data display. ```python with PrefabApp(state=state, css_class="max-w-none p-0"): with Dashboard( columns=12, row_height="auto", gap=4, let={ "m": pick("metrics"), "chart": pick("monthly"), "cat": pick("categories"), "t": pick("trend"), }, ): # Row 1: Region filter with DashboardItem(col=1, row=1, col_span=12): with Card(): with CardContent(): with Row(align="center", gap=4): Muted("Region") with Select(name="region", css_class="w-48"): SelectOption(value="all", label="All Regions") SelectOption(value="north", label="North") SelectOption(value="south", label="South") SelectOption(value="east", label="East") SelectOption(value="west", label="West") # Row 2: Metrics driven by `m` from the let binding m = R("m") with DashboardItem(col=1, row=2, col_span=3): Metric(label="Revenue", value=m.revenue.currency()) with DashboardItem(col=4, row=2, col_span=3): Metric(label="Units Sold", value=m.units.number()) with DashboardItem(col=7, row=2, col_span=3): Metric(label="Avg. Price", value=m.avg_price.currency()) with DashboardItem(col=10, row=2, col_span=3): Metric(label="Stores", value=m.stores) ``` -------------------------------- ### Define UI Components with Number Formatting Source: https://prefab.prefect.io/docs/concepts/expressions Examples showing how to structure a dashboard card with formatted revenue and growth metrics. ```python from prefab_ui.components import ( STATE as state, Badge, Card, CardContent, CardDescription, CardHeader, CardTitle, Column, Progress, Row, Text, ) with Card(): with CardHeader(): CardTitle("Q4 Revenue") CardDescription(state.revenue.currency()) with CardContent(): with Column(gap=2): Progress(value=(state.revenue / state.target * 100), max=100) with Row(gap=2, align="center"): Text(f"{(state.revenue / state.target).percent(1)} of target") Badge(f"{state.growth.percent(1)} YoY", variant="secondary") ``` ```json { "view": { "type": "Card", "children": [ { "type": "CardHeader", "children": [ {"type": "CardTitle", "content": "Q4 Revenue"}, {"type": "CardDescription", "content": "{{ revenue | currency }}"} ] }, { "type": "CardContent", "children": [ { "cssClass": "gap-2", "type": "Column", "children": [ { "type": "Progress", "value": "{{ revenue / target * 100 }}", "max": 100.0, "variant": "default", "size": "default" }, { "cssClass": "gap-2 items-center", "type": "Row", "children": [ {"content": "{{ revenue / target | percent:1 }} of target", "type": "Text"}, { "type": "Badge", "label": "{{ growth | percent:1 }} YoY", "variant": "secondary" } ] } ] } ] } ] } } ``` -------------------------------- ### Create Dashboard Card with Python Source: https://prefab.prefect.io/docs/styling/themes Example of using Prefab UI Python components to render a service health dashboard. ```python from prefab_ui.app import PrefabApp from prefab_ui.themes import Presentation from prefab_ui.components import Card, CardHeader, CardContent, Muted, Badge, DataTable, DataTableColumn, Progress, H2 rows = [ {"name": "API Requests", "current": "2,531/s", "target": "3,900/s", "gauge": Progress(value=65), "status": Badge("65%")}, {"name": "Latency P99", "current": "38ms", "target": "52ms", "gauge": Progress(value=73, variant="success"), "status": Badge("73%", variant="success")}, {"name": "Error Rate", "current": "0.4%", "target": "0.5%", "gauge": Progress(value=80, variant="success"), "status": Badge("80%", variant="success")}, {"name": "Cache Hit", "current": "91%", "target": "95%", "gauge": Progress(value=96, variant="warning"), "status": Badge("96%", variant="warning")}, ] with Card() as view: with CardHeader(): Muted("Week of Mar 9, 2026") H2("Service Health vs Target", bold=True) with CardContent(): DataTable( columns=[ DataTableColumn(key="name", header="Metric"), ``` -------------------------------- ### Create a minimal Prefab and FastAPI application Source: https://prefab.prefect.io/docs/running/api Demonstrates a basic setup with a data route for filtering items and a page route that renders a search input with live updates. ```python from fastapi import FastAPI from fastapi.responses import HTMLResponse from prefab_ui.actions import Fetch, SetState from prefab_ui.app import PrefabApp from prefab_ui.components import Column, Input, Text from prefab_ui.components.control_flow import ForEach from prefab_ui.rx import RESULT app = FastAPI() @app.get("/api/items") def list_items(q: str = ""): items = [{"name": "Widget"}, {"name": "Gadget"}, {"name": "Gizmo"}] if q: items = [i for i in items if q.lower() in i["name"].lower()] return items @app.get("/", response_class=HTMLResponse) def page(): with Column(gap=4) as view: Input( name="q", placeholder="Search...", on_change=[ SetState("q", "{{ $event }}"), Fetch.get( "/api/items", params={"q": "{{ $event }}"}, on_success=SetState("items", RESULT), ), ], ) with ForEach("items"): Text("{{ name }}") return HTMLResponse( PrefabApp( title="My App", view=view, state={"q": "", "items": []}, ).html() ) ``` -------------------------------- ### Serve a PrefabApp Locally Source: https://prefab.prefect.io/docs/serve Use the `prefab serve` command followed by the Python file path to start a local server for previewing your PrefabApp. This command opens your browser to a local URL. ```bash prefab serve app.py ``` -------------------------------- ### Define a PrefabApp for Local Preview Source: https://prefab.prefect.io/docs/serve Create a Python file defining a PrefabApp with initial state and CSS classes. This is the entry point for `prefab serve`. ```python from prefab_ui.app import PrefabApp from prefab_ui.components import Heading, Text with PrefabApp(state={"greeting": "Hello"}, css_class="p-6") as app: Heading("Hello Prefab") Text("This is a local preview.") ``` -------------------------------- ### Create a Prefab UI Application Source: https://prefab.prefect.io/docs/getting-started/quickstart A basic example demonstrating reactive state with Rx and layout components like Card, Column, and Input. ```python from prefab_ui.app import PrefabApp from prefab_ui.components import Badge, Card, CardContent, CardFooter, Column, H3, Input, Muted, Row from prefab_ui.rx import Rx name = Rx("name").default("world") with PrefabApp(css_class="max-w-md mx-auto") as app: with Card(): with CardContent(): with Column(gap=3): H3(f"Hello, {name}!") Muted("Type below and watch this update in real time.") Input(name="name", placeholder="Your name...") with CardFooter(): with Row(gap=2): Badge(f"Name: {name}", variant="default") Badge("Prefab", variant="success") ``` -------------------------------- ### Conditional Rendering Chain Example Source: https://prefab.prefect.io/docs/components/conditional This example illustrates a chain of If, Elif, and Else statements within a Column. It also shows how a non-conditional sibling breaks the chain, starting a new independent chain. ```python from prefab_ui.rx import Rx status = Rx("status") showDetails = Rx("showDetails") showFooter = Rx("showFooter") with Column(): # Chain 1: If / Elif / Else → one Condition node with If(status == "error"): Badge("Error", variant="destructive") with Elif(status == "warning"): Badge("Warning", variant="secondary") with Else(): Badge("OK") Text("---") # breaks the chain # Chain 2: standalone If → separate Condition node with If(showDetails): Text("Details here...") # Chain 3: another If starts a new chain (not an Elif!) with If(showFooter): Text("Footer content") ``` -------------------------------- ### Prefab UI Initialization and Data Setup Source: https://prefab.prefect.io/docs/examples/cross-filter Initializes the PrefabApp and sets up sample data for metrics and monthly trends. Includes REGIONS for filtering. This forms the basis for the dashboard components. ```python from prefab_ui import PrefabApp from prefab_ui.components import ( Card, CardContent, CardHeader, CardTitle, Dashboard, DashboardItem, Muted, Row, Select, SelectOption, ) from prefab_ui.components.charts import BarChart, ChartSeries, LineChart, RadarChart from prefab_ui.components.metric import Metric from prefab_ui.rx import Rx # Pre-segmented data for each region. The Select writes to `region` in state, # and a `let` binding picks the right dataset via a ternary chain. REGIONS = ["all", "north", "south", "east", "west"] metrics = { "all": {"revenue": 284750, "units": 12450, "avg_price": 22.87, "stores": 48}, "north": {"revenue": 142800, "units": 4200, "avg_price": 34.00, "stores": 8}, "south": {"revenue": 38900, "units": 3850, "avg_price": 10.10, "stores": 18}, "east": {"revenue": 67200, "units": 1680, "avg_price": 40.00, "stores": 6}, "west": {"revenue": 35850, "units": 2720, "avg_price": 13.18, "stores": 16}, } monthly = { "all": [ {"month": "Jan", "sales": 42000, "returns": 3200}, {"month": "Feb", "sales": 48500, "returns": 3800}, {"month": "Mar", "sales": 45200, "returns": 3400}, {"month": "Apr", "sales": 51800, "returns": 4100}, {"month": "May", "sales": 47600, "returns": 3600}, {"month": "Jun", "sales": 53200, "returns": 4200}, ], "north": [ {"month": "Jan", "sales": 22000, "returns": 800}, {"month": "Feb", "sales": 25500, "returns": 900}, {"month": "Mar", "sales": 24200, "returns": 850}, {"month": "Apr", "sales": 27800, "returns": 1000}, {"month": "May", "sales": 23100, "returns": 750}, {"month": "Jun", "sales": 29200, "returns": 1100}, ], "south": [ {"month": "Jan", "sales": 5800, "returns": 1200}, {"month": "Feb", "sales": 6400, "returns": 1400}, {"month": "Mar", "sales": 5600, "returns": 1100}, {"month": "Apr", "sales": 7200, "returns": 1600}, {"month": "May", "sales": 6100, "returns": 1300}, {"month": "Jun", "sales": 7800, "returns": 1700}, ], } # The following code is not present in the input text, so it is omitted. ``` -------------------------------- ### Expression Syntax Examples Source: https://prefab.prefect.io/docs/expressions/context Examples of using operators and string literals within expressions. ```text {{ status == 'active' }} ``` -------------------------------- ### Counter Button Example Source: https://prefab.prefect.io/docs/concepts/expressions This example demonstrates a counter with increment and decrement buttons. It uses template expressions for state updates and conditional badge variants. ```Python from prefab_ui.components import Button, Row, Badge from prefab_ui.actions import SetState with Row(gap=3, align="center"): Button("-", variant="outline", on_click=SetState("count", "{{ count - 1 }}")) Badge("{{ count }}", variant="{{ count > 0 ? 'success' : 'destructive' }}") Button("+", variant="outline", on_click=SetState("count", "{{ count + 1 }}")) ``` ```json { "view": { "cssClass": "gap-3 items-center", "type": "Row", "children": [ { "type": "Button", "label": "-", "variant": "outline", "size": "default", "disabled": false, "onClick": {"action": "setState", "key": "count", "value": "{{ count - 1 }}"} }, { "type": "Badge", "label": "{{ count }}", "variant": "{{ count > 0 ? 'success' : 'destructive' }}" }, { "type": "Button", "label": "+", "variant": "outline", "size": "default", "disabled": false, "onClick": {"action": "setState", "key": "count", "value": "{{ count + 1 }}"} } ] } } ``` -------------------------------- ### Run Prefab Server Source: https://prefab.prefect.io/docs/getting-started/quickstart Use this command to start the Prefab development server. The `--reload` flag enables live updates in the browser when `app.py` is saved. ```bash prefab serve app.py --reload ``` -------------------------------- ### Conditional Rendering Example Source: https://prefab.prefect.io/docs/components/conditional This example demonstrates how to use If, Elif, and Else for conditional rendering. Ensure that the conditions evaluate correctly to render the desired components. ```jsx function ExampleComponent({ condition1, condition2, children }) { return ( {/* Render this if condition1 is true */}

Condition 1 is met.

{/* Render this if condition1 is false and condition2 is true */}

Condition 2 is met.

{/* Render this if both condition1 and condition2 are false */}

Neither condition is met.

); } ``` -------------------------------- ### Create a Dashboard with Cards and Metrics Source: https://prefab.prefect.io/docs/examples/sales-dashboard Demonstrates how to create a dashboard layout using `Dashboard` and `DashboardItem`. It shows how to embed `Card` components, each containing a `Metric` for displaying key performance indicators with trend information. ```python from prefab_ui.components import ( Card, CardContent, CardHeader, CardTitle, Dashboard, DashboardItem, DataTable, DataTableColumn, Muted, Row, ) from prefab_ui.components.charts import AreaChart, ChartSeries, PieChart from prefab_ui.components.metric import Metric monthly = [ {"month": "Sep", "revenue": 38200, "costs": 22100}, {"month": "Oct", "revenue": 41500, "costs": 23400}, {"month": "Nov", "revenue": 45800, "costs": 24800}, {"month": "Dec", "revenue": 52100, "costs": 27200}, {"month": "Jan", "revenue": 48900, "costs": 25600}, {"month": "Feb", "revenue": 58250, "costs": 28900}, ] categories = [ {"category": "Electronics", "revenue": 98600}, {"category": "Clothing", "revenue": 67200}, {"category": "Home", "revenue": 54300}, {"category": "Books", "revenue": 38400}, {"category": "Sports", "revenue": 26250}, ] orders = [ {"id": "ORD-7842", "customer": "Acme Corp", "product": "Laptop Pro", "total": "$1,249.99", "status": "Shipped", "date": "Feb 18"}, {"id": "ORD-7841", "customer": "Globex Inc", "product": "Wireless Mouse", "total": "$42.00", "status": "Delivered", "date": "Feb 17"}, {"id": "ORD-7840", "customer": "Initech", "product": "Standing Desk", "total": "$599.00", "status": "Processing", "date": "Feb 17"}, {"id": "ORD-7839", "customer": "Umbrella LLC", "product": "Monitor 27\"", "total": "$389.99", "status": "Shipped", "date": "Feb 16"}, {"id": "ORD-7838", "customer": "Stark Industries", "product": "Keyboard MX", "total": "$179.00", "status": "Delivered", "date": "Feb 16"}, {"id": "ORD-7837", "customer": "Wayne Enterprises", "product": "Webcam HD", "total": "$89.99", "status": "Delivered", "date": "Feb 15"}, {"id": "ORD-7836", "customer": "Cyberdyne", "product": "USB Hub", "total": "$34.99", "status": "Shipped", "date": "Feb 15"}, {"id": "ORD-7835", "customer": "Oscorp", "product": "Headphones Pro", "total": "$299.00", "status": "Processing", "date": "Feb 14"}, ] with Dashboard(columns=12, row_height="auto", gap=4): # Row 1: KPI metrics in cards with DashboardItem(col=1, row=1, col_span=3): with Card(): with CardContent(): Metric(label="Revenue", value="$284,750", delta="+12.5%", trend="up", trend_sentiment="positive") with DashboardItem(col=4, row=1, col_span=3): with Card(): with CardContent(): Metric(label="Orders", value="1,842", delta="+8.2%", trend="up", trend_sentiment="positive") with DashboardItem(col=7, row=1, col_span=3): with Card(): with CardContent(): Metric(label="Avg Order", value="$154.59", delta="-3.1%", trend="down", trend_sentiment="negative") with DashboardItem(col=10, row=1, col_span=3): with Card(): with CardContent(): Metric(label="Growth", value="12.5%", delta="+2.4pp", trend="up", trend_sentiment="positive") # Row 2: Revenue trend + category breakdown with DashboardItem(col=1, row=2, col_span=8): with Card(css_class="h-full"): with CardHeader(): CardTitle("Revenue Over Time") with CardContent(): AreaChart( data=monthly, series=[ ``` -------------------------------- ### Perform HTTP GET Request with Button Source: https://prefab.prefect.io/docs/actions/fetch Demonstrates triggering a GET request upon a button click, updating state and showing a toast notification on success. ```python from prefab_ui.components import Button from prefab_ui.actions import Fetch, SetState, ShowToast from prefab_ui.rx import RESULT Button( "Load Users", on_click=Fetch.get( "/api/users", on_success=[ SetState("users", RESULT), ShowToast("Users loaded!", variant="success"), ], ), ) ``` ```json { "view": { "type": "Button", "label": "Load Users", "variant": "default", "size": "default", "disabled": false, "onClick": { "onSuccess": [ {"action": "setState", "key": "users", "value": "{{ $result }}"}, {"action": "showToast", "message": "Users loaded!", "variant": "success"} ], "action": "fetch", "url": "/api/users", "method": "GET" } } } ``` -------------------------------- ### Nested Grid Layout Source: https://prefab.prefect.io/docs/components/grid Demonstrates how to nest Column components within a Grid. The Python example uses a context manager, while the JSON example defines the structure declaratively. ```python from prefab_ui.components import ( Column, Grid, H3, P, ) with Grid(columns=2, gap=6, css_class="p-3 border-3 border-dashed"): with Column(css_class="p-3 border-3 border-dashed"): H3("Left Panel") P("Primary content goes here.") with Column(css_class="p-3 border-3 border-dashed"): H3("Right Panel") P("Secondary content goes here.") ``` ```json { "view": { "cssClass": "gap-6 grid-cols-2 p-3 border-3 border-dashed", "type": "Grid", "children": [ { "cssClass": "p-3 border-3 border-dashed", "type": "Column", "children": [ {"content": "Left Panel", "type": "H3"}, {"content": "Primary content goes here.", "type": "P"} ] }, { "cssClass": "p-3 border-3 border-dashed", "type": "Column", "children": [ {"content": "Right Panel", "type": "H3"}, {"content": "Secondary content goes here.", "type": "P"} ] } ] } } ``` -------------------------------- ### Component Preview with State Management Source: https://prefab.prefect.io/docs/components/pages This example demonstrates a multi-step form using Prefabs components. It manages the current step using the `state` object and `setState` action for navigation between pages. ```javascript { "type": "ComponentPreview", "content": [ { "type": "Page", "title": "Setup", "value": "setup", "children": [ {"content": "Welcome to Prefabs!", "type": "Text"}, { "type": "Button", "label": "Next", "variant": "default", "size": "default", "disabled": false, "onClick": {"action": "setState", "key": "pages_1", "value": "review"} } ] }, { "type": "Page", "title": "Review", "value": "review", "children": [ { "cssClass": "gap-4", "type": "Column", "children": [ {"content": "Review your choices.", "type": "Text"}, { "cssClass": "gap-2", "type": "Row", "children": [ { "type": "Button", "label": "Back", "variant": "outline", "size": "default", "disabled": false, "onClick": {"action": "setState", "key": "pages_1", "value": "setup"} }, { "type": "Button", "label": "Next", "variant": "default", "size": "default", "disabled": false, "onClick": {"action": "setState", "key": "pages_1", "value": "complete"} } ] } ] } ] }, { "type": "Page", "title": "Complete", "value": "complete", "children": [{"content": "All done!", "type": "Text"}] } ], "state": {"pages_1": "setup"} } ``` -------------------------------- ### Create an interactive Hello World card Source: https://prefab.prefect.io/docs/welcome Uses the Rx class to bind input state to UI elements. Requires importing components and the reactive module from prefab_ui. ```python from prefab_ui.components import * from prefab_ui.rx import Rx name = Rx("name").default("world") with Card(): with CardContent(): with Column(gap=3): H3(f"Hello, {name}!") Muted("Type below and watch this update in real time.") Input(name="name", placeholder="Your name...") with CardFooter(): with Row(gap=2): Badge(f"Name: {name}", variant="default") Badge("Prefab", variant="success") ``` ```json { "view": { "type": "Card", "children": [ { "type": "CardContent", "children": [ { "cssClass": "gap-3", "type": "Column", "children": [ {"content": "Hello, {{ name | default:world }}!", "type": "H3"}, {"content": "Type below and watch this update in real time.", "type": "Muted"}, { "name": "name", "type": "Input", "inputType": "text", "placeholder": "Your name...", "disabled": false, "readOnly": false, "required": false } ] } ] }, { "type": "CardFooter", "children": [ { "cssClass": "gap-2", "type": "Row", "children": [ { "type": "Badge", "label": "Name: {{ name | default:world }}", "variant": "default" }, {"type": "Badge", "label": "Prefab", "variant": "success"} ] } ] } ] } } ``` -------------------------------- ### DropZone with Chained Actions for File Upload Feedback Source: https://prefab.prefect.io/docs/components/drop-zone This example demonstrates chaining multiple actions for a DropZone. It shows a loading state, calls a tool to upload the file, and then clears the loading state, providing UI feedback during the upload process. ```python from prefab_ui.components import DropZone from prefab_ui.actions import SetState from prefab_ui.actions.mcp import CallTool DropZone( label="Upload data file", on_change=[ SetState("uploading", True), CallTool("upload_file", arguments={"file": "{{ $event }}"}), SetState("uploading", False), ], ) ``` -------------------------------- ### Hitchhiker's Guide Dashboard Structure Source: https://prefab.prefect.io/docs/welcome This JSON structure defines the layout and state for the Hitchhiker's Guide dashboard, including data for crew members and pagination settings. ```json { "crew": [ { "crew": "Arthur Dent", "species": "Human", "towel": "Yes", "status": "Presidential" }, { "crew": "Trillian", "species": "Human", "towel": "Yes", "status": "Navigating" }, { "crew": "Marvin", "species": "Android", "towel": "No point", "status": "Depressed" }, { "crew": "Slartibartfast", "species": "Magrathean", "towel": "Somewhere", "status": "Designing" } ], "search": true, "paginated": false, "pageSize": 10 } ``` -------------------------------- ### Conditional Rendering Example Source: https://prefab.prefect.io/docs/components/conditional This example demonstrates conditional rendering based on the 'status' variable. It shows how different badges are displayed for 'error', 'warning', and 'active' statuses, with a fallback for unknown statuses. ```python { "when": "{{ status == 'error' }}", "children": [ {"type": "Badge", "label": "Error — system down", "variant": "destructive"} ] }, { "when": "{{ status == 'warning' }}", "children": [{"type": "Badge", "label": "Warning — degraded", "variant": "warning"}] }, { "when": "{{ status == 'active' }}", "children": [ {"type": "Badge", "label": "Active — all systems go", "variant": "success"} ] } ], "else": [ { "type": "Badge", "label": "Unknown status: {{ status }}", "variant": "secondary" } ] ``` -------------------------------- ### Actions Demo Implementation Source: https://prefab.prefect.io/docs/examples/actions This example shows how to use Prefab UI components and reactive state to handle button clicks that trigger multiple actions. ```python from prefab_ui import PrefabApp from prefab_ui.actions import SetState, ShowToast, ToggleState from prefab_ui.components import ( Badge, Button, Card, CardContent, CardHeader, CardTitle, Column, Muted, Progress, Row, Text, ) from prefab_ui.components.control_flow import Else, If from prefab_ui.rx import Rx count = Rx("count") saved = Rx("saved") with PrefabApp(state={"count": 0, "saved": False}, css_class="max-w-none p-0"): with Card(css_class="w-full"): with CardHeader(): CardTitle("Actions Demo") ``` -------------------------------- ### Hitchhiker's Guide Dashboard State Source: https://prefab.prefect.io/docs/welcome This JSON object defines the state properties for the Hitchhiker's Guide dashboard, including improbability, autoscale, and various UI control states. ```json { "state": { "improbability": 42, "autoscale": true, "code_mode": true, "cache": false, "radio_16": false, "radio_17": false, "radio_18": true, "checkbox_12": true, "checkbox_13": true, "checkbox_14": false, "ctx_tick": 0 } } ``` -------------------------------- ### GET /api/users Source: https://prefab.prefect.io/docs/actions/fetch Fetches a list of users from the server. ```APIDOC ## GET /api/users ### Description Retrieves user data from the API. ### Method GET ### Endpoint /api/users ``` -------------------------------- ### Video Component Usage Source: https://prefab.prefect.io/docs/components/video Example of how to use the Video component with a poster image. ```APIDOC ## Poster Image Show a thumbnail before the video plays: ```python Poster thumbnail theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}} from prefab_ui.components import Video Video( src="https://example.com/presentation.mp4", poster="https://example.com/thumbnail.jpg", width="640px", ) ``` ``` -------------------------------- ### PieChart with Labels Source: https://prefab.prefect.io/docs/components/pie-chart Example of how to display labels on each slice of the PieChart for better readability. ```APIDOC ## PieChart with Labels Set `show_label=True` to display a label on each slice, making values readable without tooltips. ### Method Not applicable (Component Configuration) ### Endpoint Not applicable (Component Configuration) ### Request Body Example ```json { "view": { "type": "PieChart", "data": [ {"browser": "Chrome", "visitors": 275}, {"browser": "Safari", "visitors": 200}, {"browser": "Firefox", "visitors": 187}, {"browser": "Edge", "visitors": 173}, {"browser": "Other", "visitors": 90} ], "dataKey": "visitors", "nameKey": "browser", "height": 300, "innerRadius": 0, "showLabel": true, "paddingAngle": 0, "showLegend": true, "showTooltip": true, "animate": true } } ``` ### Python Code Example ```python PieChart( data=data, data_key="visitors", name_key="browser", show_label=True, show_legend=True, ) ``` ```