Try an interactive version of this dialog: Sign up at solve.it.com, click Upload, and pass this URL.

Code: 7 ()

#| default_exp core

Note: 15

core

Builder API for basecoat components

Code: 43 ()

from fastcore.utils import *
from fasthtml.common import *
import fasthtml.components as fh
from fasthtml.jupyter import *

Note: 6

Basecoat reference

Note: 90

Note: I'm writing a fasthtml version of basecoat. However, in order for you to help me, you need context for how basecoat is used. It is slightly different from other wrapper libraries in that is uses btn-outline as one thing instead of needing btn btn-outline.

Note: 16

url: https://basecoatui.com/introduction/

Prompt: 55

Please use the url to parse through the docs to get a general idea of how things work. Then compile a list of possible components. It should start with Accordion and end with Tooltip.

Assistant: 505

Copied!
{
  "id": "toolu_019NeTtGwzsKHc7co5RHCHk1",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/introduction/"
    }
  },
  "result": "\"[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}

Perfect! I can see the full list of components from the documentation. Here's the complete list of Basecoat components from Accordion to Tooltip:

  1. Accordion
  2. Alert
  3. Alert Dialog
  4. Avatar
  5. Badge
  6. Breadcrumb
  7. Button
  8. Button Group
  9. Card
  10. Checkbox
  11. Command
  12. Combobox
  13. Dialog
  14. Dropdown Menu
  15. Empty
  16. Field
  17. Form
  18. Input
  19. Input Group
  20. Item
  21. Kbd
  22. Label
  23. Pagination
  24. Popover
  25. Progress
  26. Radio Group
  27. Select
  28. Sidebar
  29. Skeleton
  30. Slider
  31. Spinner
  32. Switch
  33. Table
  34. Tabs
  35. Textarea
  36. Theme Switcher
  37. Toast
  38. Tooltip

Would you like me to explore specific components in more detail to understand their structure and usage patterns?

Prompt: 24

Please look at e.g., the button example to see how that is made.

Assistant: 409

Copied!
{
  "id": "toolu_01X2H4FZr5vUDgRvzH6bgt5j",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/components/button"
    }
  },
  "result": "'[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}

Great! I can see how Basecoat works. The key insight is that each variant is a single class name, not multiple classes combined. For example:

  • btn-outline (not btn btn-outline)
  • btn-destructive (not btn btn-destructive)
  • btn-lg-destructive (combines size and variant in one class)
  • btn-sm-icon-outline (combines size, type, and variant in one class)

This is different from frameworks like Bootstrap where you'd need multiple classes.

Would you like me to start creating Python functions for these components using fasthtml, or would you like to explore more components first to understand the patterns better?

Note: 4

Script setup

Code: 591 ()

s = Script("""
  (() => {
    try {
      const stored = localStorage.getItem('themeMode');
      if (stored ? stored === 'dark'
                  : matchMedia('(prefers-color-scheme: dark)').matches) {
        document.documentElement.classList.add('dark');
      }
    } catch (_) {}

    const apply = dark => {
      document.documentElement.classList.toggle('dark', dark);
      try { localStorage.setItem('themeMode', dark ? 'dark' : 'light'); } catch (_) {}
    };

    document.addEventListener('basecoat:theme', (event) => {
      const mode = event.detail?.mode;
      apply(mode === 'dark' ? true
            : mode === 'light' ? false
            : !document.documentElement.classList.contains('dark'));
    });
  })();
  """)

tw_scr = Script(src='https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4')
icon_dep = Script(src="https://cdn.jsdelivr.net/npm/lit@3/dist/index.js")
franken_css = Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/franken-ui@2.0.0/dist/css/core.min.css"),
franken_js = Script(src="https://cdn.jsdelivr.net/npm/franken-ui@2.0.0/dist/js/core.iife.js"),
icons = Script(src="https://cdn.jsdelivr.net/npm/franken-ui@2.0.0/dist/js/icon.iife.js")
basecoat_link =Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/basecoat-css@0.3.6/dist/basecoat.cdn.min.css", type="text/css")
basecoat_script = Script(src="https://cdn.jsdelivr.net/npm/basecoat-css@0.3.6/dist/js/all.min.js")
hdrs = (s, tw_scr, franken_js, icons, basecoat_link, basecoat_script)

Note: 6

Fasthtml

Code: 31 ()

app = FastHTML(hdrs=hdrs, session_cookie="mysession")
rt = app.route

Code: 18 ()

srv = JupyUvi(app)
# srv.stop()

Output: 1,875

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/starlette/applications.py", line 107, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/errors.py", line 186, in __call__
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/errors.py", line 164, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/cors.py", line 85, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/sessions.py", line 85, in __call__
    await self.app(scope, receive, send_wrapper)
  File "/usr/local/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 63, in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 716, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 736, in app
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 290, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 78, in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "/usr/local/lib/python3.12/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "/usr/local/lib/python3.12/site-packages/starlette/routing.py", line 75, in app
    response = await f(request)
               ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 625, in _f
    if not resp: resp = await _wrap_call(f, req, sig.parameters)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 475, in _wrap_call
    return await _handle(f, **wreq)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/fasthtml/core.py", line 234, in _handle
    return (await f(*args, **kwargs)) if is_async_callable(f) else await run_in_threadpool(f, *args, **kwargs)
                                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/starlette/concurrency.py", line 32, in run_in_threadpool
    return await anyio.to_thread.run_sync(func)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/to_thread.py", line 56, in run_sync
    return await get_async_backend().run_sync_in_worker_thread(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 2485, in run_sync_in_worker_thread
    return await future
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 976, in run
    result = context.run(func, *args)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/ipykernel_44/950362574.py", line 12, in index
    SidebarGroup("Projects", ["Design Engineering", "Sales & Marketing", "Travel"]),
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: SidebarGroup() missing 1 required positional argument: 'icon_list'

Code: 40 ()

def get_preview(app): return partial(HTMX, app=app, host=None, port=None)
p = get_preview(app)

Code: 30 ()

c = Div(
    fh.Button('Hey there', cls='btn-outline'),
)
p(c)

Output: 1,618

Prompt: 46

Can you explore a few different components to understand the general pattern of things, and help me figure out the best way to make a fasthtml wrapper?

Assistant: 970

I'll explore a few different components to understand the patterns. Let me look at a few more examples:

Copied!
{
  "id": "toolu_0123wTjufkxjJPc2W56iSiLj",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/components/badge"
    }
  },
  "result": "'[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}
Copied!
{
  "id": "toolu_01AwgN4DbEecNHA6u6hqgiQT",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/components/card"
    }
  },
  "result": "'[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}
Copied!
{
  "id": "toolu_01DH4Tb75am5BQoEUMcHMxkk",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/components/alert"
    }
  },
  "result": "'[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}

Based on exploring these components, I can see some clear patterns emerging:

Pattern 1: Simple components with variants

  • Button: btn, btn-outline, btn-destructive, etc.
  • Badge: badge, badge-secondary, badge-destructive, badge-outline
  • These use a single class name for the complete styling

Pattern 2: Structured components with semantic HTML

  • Card: Uses <div class="card"> with <header>, <section>, <footer>
  • Alert: Uses <div class="alert"> or <div class="alert-destructive"> with <svg>, <h2>, <section>

Pattern 3: Size + variant combinations

  • Button can be btn-lg-destructive (size + variant in one class)

For a FastHTML wrapper, I see two main approaches:

  1. Minimal wrapper: Just add the class, let users build the structure
  2. Helper functions: Create functions that build the complete structure

Which approach would you prefer, or would you like a combination where simple components get minimal wrappers and complex ones get helper functions?

Code: 66 ()

p(  
    Div(
        Div("TESTING", cls="card items-center w-lg mx-auto my-auto h-64"),
        cls="w-full h-96 flex flex-col my-auto"
    )
)

Output: 1,659

Prompt: 90

Okay that is working. I think let's try to make something and use that process to figure out the best approach. I would like to make an example page that has a sidebar on the left with lots of buttons, an icon thing at the very bottom, and then in the main page some cards.

Assistant: 399

Great! Let's start building this step by step. First, let me look at the Sidebar component to understand its structure:

Copied!
{
  "id": "toolu_01PWgb64LYwXZKD4spA7P4rA",
  "call": {
    "function": "read_url",
    "arguments": {
      "url": "https://basecoatui.com/components/sidebar"
    }
  },
  "result": "'[ Basecoat v0.3.6 ](/)\\n\\n### Getting started\\n\\n  * [ Introduction ](/introduction)\\n  * [ Install<TRUNCATED>"
}

Perfect! Now I understand the Sidebar structure. Based on what you want to build, here's what I see:

The Sidebar has:

  • An <aside class="sidebar"> wrapper
  • A <nav> with sections containing navigation items
  • Optional <footer> for the icon at the bottom
  • A <main> for the content area

Would you like to start by creating the basic structure with just the outer containers first, or would you prefer to dive in and build a specific part (like the sidebar with buttons, or the main content with cards)?

Prompt: 33

Let's just try to build the sidebar. Please guide me through it, explaining the API I need to use.

Assistant: 189

Perfect! Let's build the sidebar step by step.

From the docs, the basic structure is:

Copied!
<aside class="sidebar">
  <nav>
    <!-- navigation items go here -->
  </nav>
  <footer>
    <!-- optional footer content like your icon -->
  </footer>
</aside>

For the navigation items, Basecoat uses <a class="item"> elements. You can add variants like item-active for the currently selected item.

Let's start with the outer structure. Try creating an Aside with class "sidebar" that contains a Nav. What do you get?

Prompt: 19

Can you give the examples to me in fasthtml style?

Assistant: 178

Of course! Here's the basic structure in FastHTML style:

Copied!
Aside(
    Nav(
        # navigation items go here
    ),
    Footer(
        # optional footer content like your icon
    ),
    cls="sidebar"
)

For the navigation items, you'd use:

Copied!
A("Dashboard", cls="item", href="#")
A("Settings", cls="item-active", href="#")  # for active item

Try creating a simple sidebar with a Nav containing a few A elements with the "item" class. What does it look like?

Code: 85 ()

@rt
def index():
    return Div(
        Aside(
            Nav(
                "Nav items",
                Footer(
                    "footer content",
                ),
                aria_label="Sidebar navigation",
            ),
            cls="sidebar"
        ),
        cls="w-screen h-screen",
    )

Code: 139 ()

@rt
def index():
    return Div(
        Aside(
            Nav(
                Section(
                    Ul(
                        Li(A("Dashboard", href="#")),
                        Li(A("Settings", href="#")),
                        Li(A("Profile", href="#"))
                    )
                ),
                aria_label="Sidebar navigation"
            ),
            Footer(
                A("User Icon", href="#")
            ),
            cls="sidebar"
        ),
        cls="w-screen h-screen",
    )

Note: 15

Copying UkIcon from monsterui for now...

Code: 192 ()

def UkIcon(icon:str, # Icon name from [lucide icons](https://lucide.dev/icons/)
           height:int=None, 
           width:int=None, 
           stroke_width:int=None, # Thickness of lines
           cls=(), # Additional classes on the `Uk_icon` tag
           **kwargs # Additional args for `Uk_icon` tag
           )->FT: # a lucide icon of the specified size 
    "Creates an icon using lucide icons"
    return fh.Uk_icon(icon=icon, height=height, width=width, stroke_width=stroke_width, cls=cls, **kwargs)

Code: 10 ()

p(UkIcon("home"))

Output: 1,590

Note: 129

Okay, seems good. I'm going to try copy exactly an output from Shadcn. To begin with I'm going to extract some key components. My current understanding is that there is a main Aside section with cls="sidebar", and then inside that we have a Nav section (always)? The nav can then have things inside it like headers and the actual content. There seems to be different ways of doing collapsable groups, etc.

Code: 43 ()

def IconTitle(title:str, icon=None):
    return Div(UkIcon(icon), P(title), cls="flex items-center gap-2")

Code: 22 ()

p(
    IconTitle("Playground", icon="SquareTerminal")
)

Output: 1,654

Code: 15 ()

p(
    IconTitle("Playground")
)

Output: 1,641

Code: 73 ()

def Sidebar(*args, header=None, footer=None, **kwargs):
    return Aside(
        Nav(
            header,
            Section(*args, cls="scrollbar", **kwargs),
            footer,
        ),
        cls="sidebar",
    )

Code: 43 ()

def Group(title: str, *args, **kwargs):
    return Div(H3(title), *args, role="group", **kwargs)

Code: 136 ()

def SidebarGroup(title:str, name_list:list, icon_list:list, href_list=None):
    if not href_list: href_list = [f"/{o.lower().replace(" ", "-")}" for o in name_list]
    links = [Li(A(IconTitle(name, icon=ico), href=href)) for name, href, ico in zip(name_list, href_list, icon_list)]
    return Group(title, Ul(*links))

Code: 124 ()

def SidebarCollapsable(title:str, name_list:list, href_list=None):
    if not href_list: href_list = [f"/{o.lower().replace(" ", "-")}" for o in name_list]
    links = [Li(A(name, href=href)) for name, href in zip(name_list, href_list)]
    return Ul(Li(Details(Summary(title), Ul(*links))))

Code: 81 ()

def ToggleButton():
    return Button(
        UkIcon("panel-left"), 
        type="button",
        onclick="document.dispatchEvent(new CustomEvent('basecoat:sidebar'))",
        cls="btn-ghost p-2"
    )
p(ToggleButton())

Output: 1,681

Code: 318 ()

@rt
def index():
    return Div(
        Sidebar(
            Group(
                "Platform",
                SidebarCollapsable(IconTitle("Playground", icon="SquareTerminal"), ["History", "Starred", "Settings"]),
                SidebarCollapsable(IconTitle("Models", icon="Bot"), ["Genesis", "Explorer", "Quantum"]),
                SidebarCollapsable(IconTitle("Documentation", icon="BookOpen"), ["Introduction", "Get Started", "Tutorials", "Changelog"]),
                SidebarCollapsable(IconTitle("Settings", icon="Settings2"), ["General", "Team", "Billing", "Limits"]),
            ),
            SidebarGroup("Projects", ["Design Engineering", "Sales & Marketing", "Travel"], icon_list=["Frame", "PieChart", "Map"]),

        ),
        Main(
            ToggleButton(),
            H1("Main Content Area"),
            H3("Click Button above to open/close sidebar"),
            cls="p-8"
        ),
        cls="w-screen h-screen"
    )

Note: 4

Dropdowns

Note: 4

Code:

Note: 42

Basic sidepanel is complete.

Next steps:

  • Logo button with dropdown popups for header + footer
  • Sample breadcrumbing + default panels

Code: 169 ()

def DropdownMenu():
    return Div(
        Button("Open", id="demo-dropdown-trigger", cls="btn-outline"),
        Div(
            Div(
                Div(
                    Div("My Account", role="heading", id="account-options"),
                    Div("Profile", role="menuitem"),
                    role="group", aria_labelledby="account-options",
                ),
                role="menu", aria_labelledby="demo-dropdown-trigger",
            ),
            cls="min-w-65",
        ),
        cls="dropdown-menu",
    )

p(DropdownMenu())

Output: 1,858

Prompt: 27

Could you help give a minimal version of the dropdown menu example to help get it working?

Assistant: 328

Looking at your code, you're very close! The issue is that the popover Div needs some specific attributes. Here's the minimal structure:

Copied!
def DropdownMenu():
    menu_id = "demo-dropdown-menu"
    return Div(
        Button("Open", 
               id=f"{menu_id}-trigger",
               aria_haspopup="menu",
               aria_controls=f"{menu_id}-content",
               aria_expanded="false",
               cls="btn-outline"),
        Div(
            Div(
                Div("Profile", role="menuitem"),
                Div("Settings", role="menuitem"),
                role="menu",
                id=f"{menu_id}-content",
                aria_labelledby=f"{menu_id}-trigger"
            ),
            data_popover=True,
            aria_hidden="true",
            cls="min-w-56"
        ),
        cls="dropdown-menu",
        id=menu_id
    )

The key missing pieces were data_popover=True and aria_hidden="true" on the popover div. Try this and see if it works!

Code: 255 ()

def DropdownMenu(name:str, menu_id="demo-dropdown-menu"):

    return Div(
        Button(name, 
               id=f"{menu_id}-trigger",
               aria_haspopup="menu",
               aria_controls=f"{menu_id}-content",
               aria_expanded="false",
               cls="btn-outline"),
        Div(
            Div(
                Div("Profile", role="menuitem"),
                Div("Settings", role="menuitem"),
                Hr(role="separator"),
                Div("Next thing", role="menuitem"),
                role="menu",
                id=f"{menu_id}-content",
                aria_labelledby=f"{menu_id}-trigger"
            ),
            data_popover=True,
            aria_hidden="true",
            cls="min-w-56"
        ),
        cls="dropdown-menu",
        id=menu_id
    )

Code: 31 ()

p(Div(DropdownMenu("Open"), cls="w-full h-64 p-8"))

Output: 1,983

Prompt: 37

Okay that looks good. What is the structure of groups and for sections (e.g., sectioned off by a line)?

Assistant: 267

Looking at the docs, there are two ways to organize dropdown menu items:

Groups - Use role="group" with an optional heading:

Copied!
Div(
    Div("My Account", role="heading", id="account-options"),
    Div("Profile", role="menuitem"),
    Div("Billing", role="menuitem"),
    role="group",
    aria_labelledby="account-options"
)

Separators - Use Hr with role="separator":

Copied!
Hr(role="separator")

So to create sections separated by lines, you'd do something like:

Copied!
Div("Profile", role="menuitem"),
Div("Settings", role="menuitem"),
Hr(role="separator"),
Div("Logout", role="menuitem")

Would you like to try adding some groups or separators to your dropdown menu?

Code: 339 ()

@rt
def index():
    return Div(
        Sidebar(
            Group(
                "Platform",
                SidebarCollapsable(IconTitle("Playground", icon="SquareTerminal"), ["History", "Starred", "Settings"]),
                SidebarCollapsable(IconTitle("Models", icon="Bot"), ["Genesis", "Explorer", "Quantum"]),
                SidebarCollapsable(IconTitle("Documentation", icon="BookOpen"), ["Introduction", "Get Started", "Tutorials", "Changelog"]),
                SidebarCollapsable(IconTitle("Settings", icon="Settings2"), ["General", "Team", "Billing", "Limits"]),
            ),
            SidebarGroup("Projects", ["Design Engineering", "Sales & Marketing", "Travel"], icon_list=["Frame", "PieChart", "Map"]),

        ),
        Main(
            ToggleButton(),
            H1("Main Content Area"),
            H3("Click Button above to open/close sidebar"),
            P("Testing dropdowns:"),
            DropdownMenu("Open"),
            cls="p-8"
        ),
        cls="w-screen h-screen"
    )