text
stringlengths
27
54.3k
url
stringlengths
31
137
page_name
stringlengths
7
59
# MonsterUI Documentation > MonsterUI is a python library which brings styling to python for FastHTML apps. ## API Reference - [API List](https://raw.githubusercontent.com/AnswerDotAI/MonsterUI/refs/heads/main/docs/apilist.txt): Complete API Reference ## Examples - [Ticket](https://monsterui.answer.ai/ticket/md): MonsterUI Help Desk Example - Professional Dashboard with DaisyUI components - [Scrollspy](https://monsterui.answer.ai/scrollspy/md): MonsterUI Scrollspy Example application - [Dashboard](https://monsterui.answer.ai/dashboard/md): FrankenUI Dashboard Example built with MonsterUI (original design by ShadCN) - [Mail](https://monsterui.answer.ai/mail/md): FrankenUI Mail Example built with MonsterUI (original design by ShadCN) - [Cards](https://monsterui.answer.ai/cards/md): FrankenUI Cards Example built with MonsterUI (original design by ShadCN) - [Playground](https://monsterui.answer.ai/playground/md): FrankenUI Playground Example built with MonsterUI (original design by ShadCN) - [Tasks](https://monsterui.answer.ai/tasks/md): FrankenUI Tasks Example built with MonsterUI (original design by ShadCN) - [Music](https://monsterui.answer.ai/music/md): FrankenUI Music Example build with MonsterUI (Original design by ShadCN) - [Forms](https://monsterui.answer.ai/forms/md): FrankenUI Forms Example built with MonsterUI (original design by ShadCN) - [Auth](https://monsterui.answer.ai/auth/md): FrankenUI Auth Example built with MonsterUI (original design by ShadCN) ## Optional - [Button | Link](https://monsterui.answer.ai/api_ref/docs_button_link/md): Buttons & Links API Reference - [Cards](https://monsterui.answer.ai/api_ref/docs_cards/md): Cards API Reference - [Containers](https://monsterui.answer.ai/api_ref/docs_containers/md): Articles, Containers & Sections API Reference - [Dividers](https://monsterui.answer.ai/api_ref/docs_dividers/md): Dividers API Reference - [Forms](https://monsterui.answer.ai/api_ref/docs_forms/md): Forms and User Inputs API Reference - [Icons | Images](https://monsterui.answer.ai/api_ref/docs_icons_images/md): Icons & Images API Reference - [Layout](https://monsterui.answer.ai/api_ref/docs_layout/md): Layout (Flex and Grid) API Reference - [Lists](https://monsterui.answer.ai/api_ref/docs_lists/md): Lists API Reference - [Loading](https://monsterui.answer.ai/api_ref/docs_loading/md): Loading IndicatorsAPI Reference - [Markdown | Htmlstyling](https://monsterui.answer.ai/api_ref/docs_markdown_HTMLstyling/md): <!doctype html> - [Modals](https://monsterui.answer.ai/api_ref/docs_modals/md): Modals API Reference - [Navigation](https://monsterui.answer.ai/api_ref/docs_navigation/md): Navigation (Nav, NavBar, Tabs, etc.) API Reference - [Notifications](https://monsterui.answer.ai/api_ref/docs_notifications/md): Alerts & Toasts API Reference - [Sliders](https://monsterui.answer.ai/api_ref/docs_sliders/md): Carousel Sliders API Reference - [Steps](https://monsterui.answer.ai/api_ref/docs_steps/md): Steps API Reference - [Tables](https://monsterui.answer.ai/api_ref/docs_tables/md): Tables API Reference - [Theme | Headers](https://monsterui.answer.ai/api_ref/docs_theme_headers/md): Theme and Headers API Reference - [Typography](https://monsterui.answer.ai/api_ref/docs_typography/md): Typography API Reference - [Layout](https://monsterui.answer.ai/tutorial_layout/md): MonsterUI Page Layout Guide - [Spacing](https://monsterui.answer.ai/tutorial_spacing/md): Padding & Margin & Spacing, Oh my! (MonsterUI Spacing Guide)
https://monsterui.answer.ai/llms.txt
monsterui.answer.ai_llms.txt
# monsterui Module Documentation ## monsterui.core - `class Theme(Enum)` Selector to choose theme and get all headers needed for app. Includes frankenui + tailwind + daisyui + highlight.js options Members: slate, stone, gray, neutral, red, rose, orange, green, blue, yellow, violet, zinc - `headers(self, mode, daisy, highlightjs, katex)` Create frankenui and tailwind cdns - `local_headers(self, mode, static_dir, daisy, highlightjs, katex)` Create headers using local files downloaded from CDNs ## monsterui.daisy - `class AlertT(Enum)` Alert styles from DaisyUI Members: info, success, warning, error - `def Alert(*c, **kwargs)` Alert informs users about important events. - `class StepsT(Enum)` Options for Steps Members: vertical, horizonal - `class StepT(Enum)` Step styles for LiStep Members: primary, secondary, accent, info, success, warning, error, neutral - `def Steps(*li, **kwargs)` Creates a steps container - `def LiStep(*c, **kwargs)` Creates a step list item - `class LoadingT(Enum)` Members: spinner, dots, ring, ball, bars, infinity, xs, sm, md, lg - `def Loading(cls, htmx_indicator, **kwargs)` Creates a loading animation component - `class ToastHT(Enum)` Horizontal position for Toast Members: start, center, end - `class ToastVT(Enum)` Vertical position for Toast Members: top, middle, bottom - `def Toast(*c, **kwargs)` Toasts are stacked announcements, positioned on the corner of page. ## monsterui.foundations > Data Structures and Utilties - `def stringify(o)` Converts input types into strings that can be passed to FT components - `class VEnum(Enum)` Members: - `__str__(self)` - `__add__(self, other)` - `__radd__(self, other)` ## monsterui.franken - `class TextT(Enum)` Text Styles from https://franken-ui.dev/docs/text Members: paragraph, lead, meta, gray, italic, xs, sm, lg, xl, light, normal, medium, bold, extrabold, muted, primary, secondary, success, warning, error, info, left, right, center, justify, start, end, top, middle, bottom, truncate, break_, nowrap, underline, highlight - `class TextPresets(Enum)` Common Typography Presets Members: muted_sm, muted_lg, bold_sm, bold_lg, md_weight_sm, md_weight_muted - `def CodeSpan(*c, **kwargs)` A CodeSpan with Styling - `def CodeBlock(*c, **kwargs)` CodeBlock with Styling - `def H1(*c, **kwargs)` H1 with styling and appropriate size - `def H2(*c, **kwargs)` H2 with styling and appropriate size - `def H3(*c, **kwargs)` H3 with styling and appropriate size - `def H4(*c, **kwargs)` H4 with styling and appropriate size - `def H5(*c, **kwargs)` H5 with styling and appropriate size - `def H6(*c, **kwargs)` H6 with styling and appropriate size - `def Subtitle(*c, **kwargs)` Styled muted_sm text designed to go under Headings and Titles - `def Q(*c, **kwargs)` Styled quotation mark - `def Em(*c, **kwargs)` Styled emphasis text - `def Strong(*c, **kwargs)` Styled strong text - `def I(*c, **kwargs)` Styled italic text - `def Small(*c, **kwargs)` Styled small text - `def Mark(*c, **kwargs)` Styled highlighted text - `def Del(*c, **kwargs)` Styled deleted text - `def Ins(*c, **kwargs)` Styled inserted text - `def Sub(*c, **kwargs)` Styled subscript text - `def Sup(*c, **kwargs)` Styled superscript text - `def Blockquote(*c, **kwargs)` Blockquote with Styling - `def Caption(*c, **kwargs)` Styled caption text - `def Cite(*c, **kwargs)` Styled citation text - `def Time(*c, **kwargs)` Styled time element - `def Address(*c, **kwargs)` Styled address element - `def Abbr(*c, **kwargs)` Styled abbreviation with dotted underline - `def Dfn(*c, **kwargs)` Styled definition term with italic and medium weight - `def Kbd(*c, **kwargs)` Styled keyboard input with subtle background - `def Samp(*c, **kwargs)` Styled sample output with subtle background - `def Var(*c, **kwargs)` Styled variable with italic monospace - `def Figure(*c, **kwargs)` Styled figure container with card-like appearance - `def Details(*c, **kwargs)` Styled details element - `def Summary(*c, **kwargs)` Styled summary element - `def Data(*c, **kwargs)` Styled data element - `def Meter(*c, **kwargs)` Styled meter element - `def S(*c, **kwargs)` Styled strikethrough text (different semantic meaning from Del) - `def U(*c, **kwargs)` Styled underline (for proper names in Chinese, proper spelling etc) - `def Output(*c, **kwargs)` Styled output element for form results - `def PicSumImg(h, w, id, grayscale, blur, **kwargs)` Creates a placeholder image using https://picsum.photos/ - `class ButtonT(Enum)` Options for styling Buttons Members: default, ghost, primary, secondary, destructive, text, link, xs, sm, lg, xl, icon - `def Button(*c, **kwargs)` Button with Styling (defaults to `submit` for form submission) - `class ContainerT(Enum)` Max width container sizes from https://franken-ui.dev/docs/container Members: xs, sm, lg, xl, expand - `class BackgroundT(Enum)` Members: muted, primary, secondary, default - `def Container(*c, **kwargs)` Div to be used as a container that often wraps large sections or a page of content - `def Titled(title, *c, **kwargs)` Creates a standard page structure for titled page. Main(Container(title, content)) - `class DividerT(Enum)` Divider Styles from https://franken-ui.dev/docs/divider Members: icon, sm, vertical - `def Divider(*c, **kwargs)` Divider with default styling and margin - `def DividerSplit(*c)` Creates a simple horizontal line divider with configurable thickness and vertical spacing - `def Article(*c, **kwargs)` A styled article container for blog posts or similar content - `def ArticleTitle(*c, **kwargs)` A title component for use within an Article - `def ArticleMeta(*c, **kwargs)` A metadata component for use within an Article showing things like date, author etc - `class SectionT(Enum)` Section styles from https://franken-ui.dev/docs/section Members: default, muted, primary, secondary, xs, sm, lg, xl, remove_vertical - `def Section(*c, **kwargs)` Section with styling and margins - `def Form(*c, **kwargs)` A Form with default spacing between form elements - `def Fieldset(*c, **kwargs)` A Fieldset with default styling - `def Legend(*c, **kwargs)` A Legend with default styling - `def Input(*c, **kwargs)` An Input with default styling - `def Radio(*c, **kwargs)` A Radio with default styling - `def CheckboxX(*c, **kwargs)` A Checkbox with default styling - `def Range(*c, **kwargs)` A Range with default styling - `def TextArea(*c, **kwargs)` A Textarea with default styling - `def Switch(*c, **kwargs)` A Switch with default styling - `def Upload(*c, **kwargs)` A file upload component with default styling - `def UploadZone(*c, **kwargs)` A file drop zone component with default styling - `def FormLabel(*c, **kwargs)` A Label with default styling - `class LabelT(Enum)` Members: primary, secondary, danger - `def Label(*c, **kwargs)` FrankenUI labels, which look like pills - `def UkFormSection(title, description, *c)` A form section with a title, description and optional button - `def GenericLabelInput(label, lbl_cls, input_cls, container, cls, id, input_fn, **kwargs)` `Div(Label,Input)` component with Uk styling injected appropriately. Generally you should higher level API, such as `LabelInput` which is created for you in this library - `def LabelInput(label, lbl_cls, input_cls, cls, id, **kwargs)` A `FormLabel` and `Input` pair that provides default spacing and links/names them based on id - `def LabelRadio(label, lbl_cls, input_cls, container, cls, id, **kwargs)` A FormLabel and Radio pair that provides default spacing and links/names them based on id - `def LabelCheckboxX(label, lbl_cls, input_cls, container, cls, id, **kwargs)` A FormLabel and CheckboxX pair that provides default spacing and links/names them based on id - `def LabelSelect(*option, **kwargs)` A FormLabel and Select pair that provides default spacing and links/names them based on id (usually UkLabelSelect is a better choice) - `def Options(*c)` Helper function to wrap things into `Option`s for use in `Select` - `def Select(*option, **kwargs)` Creates a select dropdown with uk styling and option for adding a search box - `@delegates(GenericLabelInput, but=['input_fn', 'cls']) def LabelRange(label, lbl_cls, input_cls, cls, id, value, min, max, step, label_range, **kwargs)` A FormLabel and Range pair that provides default spacing and links/names them based on id - `class AT(Enum)` Link styles from https://franken-ui.dev/docs/link Members: muted, text, reset, primary, classic - `class ListT(Enum)` List styles using Tailwind CSS Members: disc, circle, square, decimal, hyphen, bullet, divider, striped - `def ModalContainer(*c, **kwargs)` Creates a modal container that components go in - `def ModalDialog(*c, **kwargs)` Creates a modal dialog - `def ModalHeader(*c, **kwargs)` Creates a modal header - `def ModalBody(*c, **kwargs)` Creates a modal body - `def ModalFooter(*c, **kwargs)` Creates a modal footer - `def ModalTitle(*c, **kwargs)` Creates a modal title - `def ModalCloseButton(*c, **kwargs)` Creates a button that closes a modal with js - `def Modal(*c, **kwargs)` Creates a modal with the appropriate classes to put the boilerplate in the appropriate places for you - `def Placeholder(*c, **kwargs)` Creates a placeholder - `def Progress(*c, **kwargs)` Creates a progress bar - `def UkIcon(icon, height, width, stroke_width, cls, **kwargs)` Creates an icon using lucide icons - `def UkIconLink(icon, height, width, stroke_width, cls, button, **kwargs)` Creates an icon link using lucide icons - `def DiceBearAvatar(seed_name, h, w)` Creates an Avatar using https://dicebear.com/ - `def Center(*c, **kwargs)` Centers contents both vertically and horizontally by default - `class FlexT(Enum)` Flexbox modifiers using Tailwind CSS Members: block, inline, left, center, right, between, around, stretch, top, middle, bottom, row, row_reverse, column, column_reverse, nowrap, wrap, wrap_reverse - `def Grid(*div, **kwargs)` Creates a responsive grid layout with smart defaults based on content - `def DivFullySpaced(*c, **kwargs)` Creates a flex div with it's components having as much space between them as possible - `def DivCentered(*c, **kwargs)` Creates a flex div with it's components centered in it - `def DivLAligned(*c, **kwargs)` Creates a flex div with it's components aligned to the left - `def DivRAligned(*c, **kwargs)` Creates a flex div with it's components aligned to the right - `def DivVStacked(*c, **kwargs)` Creates a flex div with it's components stacked vertically - `def DivHStacked(*c, **kwargs)` Creates a flex div with it's components stacked horizontally - `class NavT(Enum)` Members: default, primary, secondary - `def NavContainer(*li, **kwargs)` Creates a navigation container (useful for creating a sidebar navigation). A Nav is a list (NavBar is something different) - `def NavParentLi(*nav_container, **kwargs)` Creates a navigation list item with a parent nav for nesting - `def NavDividerLi(*c, **kwargs)` Creates a navigation list item with a divider - `def NavHeaderLi(*c, **kwargs)` Creates a navigation list item with a header - `def NavSubtitle(*c, **kwargs)` Creates a navigation subtitle - `def NavCloseLi(*c, **kwargs)` Creates a navigation list item with a close button - `class ScrollspyT(Enum)` Members: underline, bold - `def NavBar(*c)` Creates a responsive navigation bar with mobile menu support - `def SliderContainer(*c, **kwargs)` Creates a slider container - `def SliderItems(*c, **kwargs)` Creates a slider items container - `def SliderNav(cls, prev_cls, next_cls, **kwargs)` Navigation arrows for Slider component - `def Slider(*c, **kwargs)` Creates a slider with optional navigation arrows - `def DropDownNavContainer(*li, **kwargs)` A Nav that is part of a DropDown - `def TabContainer(*li, **kwargs)` A TabContainer where children will be different tabs - `class CardT(Enum)` Card styles from UIkit Members: default, primary, secondary, destructive, hover - `def CardTitle(*c, **kwargs)` Creates a card title - `def CardHeader(*c, **kwargs)` Creates a card header - `def CardBody(*c, **kwargs)` Creates a card body - `def CardFooter(*c, **kwargs)` Creates a card footer - `def CardContainer(*c, **kwargs)` Creates a card container - `def Card(*c, **kwargs)` Creates a Card with a header, body, and footer - `class TableT(Enum)` Members: divider, striped, hover, sm, lg, justify, middle, responsive - `def Table(*c, **kwargs)` Creates a table - `def TableFromLists(header_data, body_data, footer_data, header_cell_render, body_cell_render, footer_cell_render, cls, sortable, **kwargs)` Creates a Table from a list of header data and a list of lists of body data - `def TableFromDicts(header_data, body_data, footer_data, header_cell_render, body_cell_render, footer_cell_render, cls, sortable, **kwargs)` Creates a Table from a list of header data and a list of dicts of body data - `def apply_classes(html_str, class_map, class_map_mods)` Apply classes to html string - `def render_md(md_content, class_map, class_map_mods)` Renders markdown using mistletoe and lxml - `def get_franken_renderer(img_dir)` Create a renderer class with the specified img_dir - `def ThemePicker(color, radii, shadows, font, mode, cls)` Theme picker component with configurable sections
https://raw.githubusercontent.com/AnswerDotAI/MonsterUI/refs/heads/main/docs/apilist.txt
docs_apilist.txt
"""MonsterUI Help Desk Example - Professional Dashboard with DaisyUI components""" from fasthtml.common import * from monsterui.all import * from datetime import datetime app, rt = fast_app(hdrs=Theme.blue.headers(daisy=True)) def TicketSteps(step): return Steps( LiStep("Submitted", data_content="πŸ“", cls=StepT.success if step > 0 else StepT.primary if step == 0 else StepT.neutral), LiStep("In Review", data_content="πŸ”Ž", cls=StepT.success if step > 1 else StepT.primary if step == 1 else StepT.neutral), LiStep("Processing", data_content="βš™οΈ", cls=StepT.success if step > 2 else StepT.primary if step == 2 else StepT.neutral), LiStep("Resolved", data_content="βœ…", cls=StepT.success if step > 3 else StepT.primary if step == 3 else StepT.neutral), cls="w-full") def StatusBadge(status): styles = {'high': AlertT.error, 'medium': AlertT.warning,'low': AlertT.info} alert_type = styles.get(status, AlertT.info) return Alert(f"{status.title()} Priority", cls=(alert_type,"w-32 shadow-sm")) def TicketCard(id, title, description, status, step, department): return Card( CardHeader( DivFullySpaced( Div(H3(f"#{id}", cls=TextT.muted), H4(title), cls='space-y-2'), StatusBadge(status))), CardBody( P(description, cls=(TextT.muted, "mb-6")), DividerSplit(cls="my-6"), TicketSteps(step), DividerSplit(cls="my-6"), DivFullySpaced( Div(Strong("Department"), P(department), cls=('space-y-3', TextPresets.muted_sm)), Div(Strong("Last Updated"), P(Time(datetime.now().strftime('%b %d, %H:%M'))), cls=('space-y-3', TextPresets.muted_sm)), Button("View Details", cls=ButtonT.primary), cls='mt-6')), cls=CardT.hover) def NewTicketModal(): return Modal( ModalHeader(H3("Create New Support Ticket")), ModalBody( Alert( DivLAligned(UkIcon("info"), Span("Please provide as much detail as possible to help us assist you quickly.")), cls=(AlertT.info,"mb-4")), Form( Grid(LabelInput("Title", id="title", placeholder="Brief description of your issue"), LabelSelect(Options("IT Support", "HR", "Facilities", "Finance"), label="Department", id="department")), LabelSelect(Options("Low", "Medium", "High"), label="Priority Level", id="priority"), LabelTextArea("Description", id="description", placeholder="Please provide detailed information about your issue"), DivRAligned( Button("Cancel", cls=ButtonT.ghost, data_uk_toggle="target: #new-ticket"), Button(Loading(cls=LoadingT.spinner), "Submit Ticket", cls=ButtonT.primary, data_uk_toggle="target: #success-toast; target: #new-ticket")), cls='space-y-8')), id="new-ticket") @rt def index(): tickets = [ {'id': "TK-1001", 'title': "Cloud Storage Access Error", 'description': "Unable to access cloud storage with persistent authorization errors. Multiple users affected across marketing department.", 'status': 'high', 'step': 2, 'department': 'IT Support'}, {'id': "TK-1002", 'title': "Email Integration Issue", 'description': "Exchange server not syncing with mobile devices. Affecting external client communications.", 'status': 'medium', 'step': 1, 'department': 'IT Support'}, {'id': "TK-1003", 'title': "Office Equipment Setup", 'description': "New department printer needs configuration and network integration. Required for upcoming client presentation.", 'status': 'low', 'step': 0, 'department': 'Facilities'} ] return Title("Help Desk Dashboard"), Container( Section( DivFullySpaced( H2("Active Tickets"), Button(UkIcon("plus-circle", cls="mr-2"), "New Ticket", cls=ButtonT.primary, data_uk_toggle="target: #new-ticket"), cls='mb-8'), Grid(*[TicketCard(**ticket) for ticket in tickets], cols=1), cls="my-6"), NewTicketModal(), Toast(DivLAligned(UkIcon('check-circle', cls='mr-2'), "Ticket submitted successfully! Our team will review it shortly."), id="success-toast", alert_cls=AlertT.success, cls=(ToastHT.end, ToastVT.bottom)), Loading(htmx_indicator=True, type=LoadingT.dots, cls="fixed top-0 right-0 m-4"), cls="mx-auto max-w-7xl" ) serve()
https://monsterui.answer.ai/ticket/md
ticket_md
"MonsterUI Scrollspy Example application" from fasthtml.common import * from monsterui.all import * import random # Using the "slate" theme with Highlight.js enabled hdrs = Theme.slate.headers(highlightjs=True) app, rt = fast_app(hdrs=hdrs) ################################ ### Example Data and Content ### ################################ products = [ {"name": "Laptop", "price": "$999"}, {"name": "Smartphone", "price": "$599"} ] code_example = """ # Python Code Example def greet(name): return f"Hello, {name}!" print(greet("World")) """ testimonials = [ {"name": "Alice", "feedback": "Great products and excellent customer service!"}, {"name": "Bob", "feedback": "Fast shipping and amazing quality!"}, {"name": "Charlie", "feedback": "Amazing experience! Will definitely buy again."}, {"name": "Diana", "feedback": "Affordable prices and great variety!"}, {"name": "Edward", "feedback": "Customer support was very helpful."}, {"name": "Fiona", "feedback": "Loved the design and quality!"} ] # Team members team = [ {"name": "Isaac Flath", "role": "CEO"}, {"name": "Benjamin ClaviΓ©", "role": "AI Researcher"}, {"name": "Alexis Gallagher", "role": "ML Engineer"}, {"name": "Hamel Husain", "role": "Data Scientist"}, {"name": "Austin Huang", "role": "Software Engineer"}, {"name": "Benjamin Warner", "role": "Product Manager"}, {"name": "Jonathan Whitaker", "role": "UX Designer"}, {"name": "Kerem Turgutlu", "role": "DevOps Engineer"}, {"name": "Curtis Allan", "role": "DevOps Engineer"}, {"name": "Audrey Roy Greenfeld", "role": "Security Analyst"}, {"name": "Nathan Cooper", "role": "Full Stack Developer"}, {"name": "Jeremy Howard", "role": "CTO"}, {"name": "Wayde Gilliam", "role": "Cloud Architect"}, {"name": "Daniel Roy Greenfeld", "role": "Blockchain Expert"}, {"name": "Tommy Collins", "role": "AI Ethics Researcher"} ] def ProductCard(p,img_id=1): return Card( PicSumImg(w=500, height=100, id=img_id), DivFullySpaced(H4(p["name"]), P(Strong(p["price"], cls=TextT.sm))), Button("Details", cls=(ButtonT.primary, "w-full"))) def TestimonialCard(t,img_id=1): return Card( DivLAligned(PicSumImg(w=50, h=50, cls='rounded-full', id=img_id), H4(t["name"])), P(Q((t["feedback"])))) def TeamCard(m,img_id=1): return Card( DivLAligned( PicSumImg(w=50, h=50, cls='rounded-full', id=img_id), Div(H4(m["name"]), P(m["role"]))), DivRAligned( UkIcon('twitter', cls='w-5 h-5'), UkIcon('linkedin', cls='w-5 h-5'), UkIcon('github', cls='w-5 h-5'), cls=TextT.gray+'space-x-2' ), cls='p-3') ################################ ### Navigation and Scrollspy ### ################################ scrollspy_links = ( A("Welcome", href="#welcome-section"), A("Products", href="#products-section"), A("Testimonials", href="#testimonials-section"), A("Team", href="#team-section"), A("Code Example", href="#code-section")) @rt def index(): def _Section(*c, **kwargs): return Section(*c, cls='space-y-3 my-48',**kwargs) return Container( NavBar( *scrollspy_links, brand=DivLAligned(H3("Scrollspy Demo!"),UkIcon('rocket',height=30,width=30)), sticky=True, uk_scrollspy_nav=True, scrollspy_cls=ScrollspyT.bold), NavContainer( *map(Li, scrollspy_links), uk_scrollspy_nav=True, sticky=True, cls=(NavT.primary,'pt-20 px-5 pr-10')), Container( # Notice the ID of each section corresponds to the `scrollspy_links` dictionary # So in scollspy `NavContainer` the `href` of each `Li` is the ID of the section DivCentered( H1("Welcome to the Store!"), Subtitle("Explore our products and enjoy dynamic code examples."), id="welcome-section"), _Section(H2("Products"), Grid(*[ProductCard(p,img_id=i) for i,p in enumerate(products)], cols_lg=2), id="products-section"), _Section(H2("Testimonials"), Slider(*[TestimonialCard(t,img_id=i) for i,t in enumerate(testimonials)]), id="testimonials-section"), _Section(H2("Our Team"), Grid(*[TeamCard(m,img_id=i) for i,m in enumerate(team)], cols_lg=2, cols_max=3), id="team-section"), _Section(H2("Code Example"), CodeBlock(code_example, lang="python"), id="code-section")), cls=(ContainerT.xl,'uk-container-expand')) serve()
https://monsterui.answer.ai/scrollspy/md
scrollspy_md
"""FrankenUI Dashboard Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * # Bring in all of fasthtml import fasthtml.common as fh # Used to get unstyled components from monsterui.all import * # Bring in all of monsterui, including shadowing fasthtml components with styled components from fasthtml.svg import * import numpy as np import plotly.express as px import pandas as pd import numpy as np app, rt = fast_app(hdrs=Theme.blue.headers()) def generate_chart(num_points=30): df = pd.DataFrame({ 'Date': pd.date_range('2024-01-01', periods=num_points), 'Revenue': np.random.normal(100, 10, num_points).cumsum(), 'Users': np.random.normal(80, 8, num_points).cumsum(), 'Growth': np.random.normal(60, 6, num_points).cumsum()}) fig = px.line(df, x='Date', y=['Revenue', 'Users', 'Growth'], template='plotly_white', line_shape='spline') fig.update_traces(mode='lines+markers') fig.update_layout( margin=dict(l=20, r=20, t=20, b=20), hovermode='x unified', showlegend=True, legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='right', x=1), plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', xaxis=dict(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)'), yaxis=dict(showgrid=True, gridwidth=1, gridcolor='rgba(0,0,0,0.1)')) return fig.to_html(include_plotlyjs=True, full_html=False, config={'displayModeBar': False}) def InfoCard(title, value, change): return Card(H3(value),P(change, cls=TextPresets.muted_sm), header = H4(title)) rev = InfoCard("Total Revenue", "$45,231.89", "+20.1% from last month") sub = InfoCard("Subscriptions", "+2350", "+180.1% from last month") sal = InfoCard("Sales", "+12,234", "+19% from last month") act = InfoCard("Active Now", "+573", "+201 since last hour") info_card_data = [("Total Revenue", "$45,231.89", "+20.1% from last month"), ("Subscriptions", "+2350", "+180.1% from last month"), ("Sales", "+12,234", "+19% from last month"), ("Active Now", "+573", "+201 since last hour")] top_info_row = Grid(*[InfoCard(*row) for row in info_card_data]) def AvatarItem(name, email, amount): return DivFullySpaced( DivLAligned( DiceBearAvatar(name, 9,9), Div(Strong(name, cls=TextT.sm), Address(A(email,href=f'mailto:{email}')))), fh.Data(amount, cls="ml-auto font-medium", value=amount[2:])) recent_sales = Card( Div(cls="space-y-8")( *[AvatarItem(n,e,d) for (n,e,d) in ( ("Olivia Martin", "[email protected]", "+$1,999.00"), ("Jackson Lee", "[email protected]", "+$39.00"), ("Isabella Nguyen", "[email protected]", "+$299.00"), ("William Kim", "[email protected]", "+$99.00"), ("Sofia Davis", "[email protected]", "+$39.00"))]), header=Div(H3("Recent Sales"),Subtitle("You made 265 sales this month.")), cls='col-span-3') teams = [["Alicia Koch"],['Acme Inc', 'Monster Inc.'],['Create a Team']] opt_hdrs = ["Personal", "Team", ""] team_dropdown = Select( Optgroup(Option(A("Alicia Koch")), label="Personal Account"), Optgroup(Option(A("Acme Inc")), Option(A("Monster Inc.")), label="Teams"), Option(A("Create a Team")), cls='flex items-center') hotkeys = [('Profile','β‡§βŒ˜P'),('Billing','⌘B'),('Settings','⌘S'),('New Team', ''), ('Logout', '')] def NavSpacedLi(t,s): return NavCloseLi(A(DivFullySpaced(P(t),P(s,cls=TextPresets.muted_sm)))) avatar_dropdown = Div( DiceBearAvatar('Alicia Koch',8,8), DropDownNavContainer( NavHeaderLi('sveltecult',NavSubtitle("[email protected]")), *[NavSpacedLi(*hk) for hk in hotkeys],)) top_nav = NavBar( team_dropdown, *map(A, ["Overview", "Customers", "Products", "Settings"]), brand=DivLAligned(avatar_dropdown, Input(placeholder='Search'))) @rt def index(): return Title("Dashboard Example"), Container( top_nav, H2('Dashboard'), TabContainer( Li(A("Overview"),cls='uk-active'), *map(lambda x: Li(A(x)), ["Analytics", "Reports", "Notifications"]), alt=True), top_info_row, Grid( Card(Safe(generate_chart(100)), cls='col-span-4'), recent_sales, gap=4,cols_xl=7,cols_lg=7,cols_md=1,cols_sm=1,cols_xs=1), cls=('space-y-4', ContainerT.xl)) serve()
https://monsterui.answer.ai/dashboard/md
dashboard_md
"""FrankenUI Mail Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * from fasthtml.svg import * import pathlib, json from datetime import datetime app, rt = fast_app(hdrs=Theme.blue.headers()) sidebar_group1 = (('home', 'Inbox', '128'), ('file-text', 'Drafts', '9'), (' arrow-up-right', 'Sent', ''), ('ban', 'Junk', '23'), ('trash', 'Trash', ''), ('folder', 'Archive', '')) sidebar_group2 = (('globe','Social','972'),('info','Updates','342'),('messages-square','Forums','128'), ('shopping-cart','Shopping','8'),('shopping-bag','Promotions','21'),) def MailSbLi(icon, title, cnt): return Li(A(DivLAligned(Span(UkIcon(icon)),Span(title),P(cnt, cls=TextPresets.muted_sm)),href='#', cls='hover:bg-secondary p-4')) sidebar = NavContainer( NavHeaderLi(H3("Email"), cls='p-3'), Li(Select(map(Option, ('[email protected]','[email protected]', '[email protected]')))), *[MailSbLi(i, t, c) for i, t, c in sidebar_group1], Li(Hr()), *[MailSbLi(i, t, c) for i, t, c in sidebar_group2], cls='mt-3') mail_data = json.load(open(pathlib.Path('data/mail.json'))) def format_date(date_str): date_obj = datetime.fromisoformat(date_str) return date_obj.strftime("%Y-%m-%d %I:%M %p") def MailItem(mail): cls_base = 'relative rounded-lg border border-border p-3 text-sm hover:bg-secondary space-y-2' cls = f"{cls_base} {'bg-muted' if mail == mail_data[0] else ''} {'tag-unread' if not mail['read'] else 'tag-mail'}" return Li( DivFullySpaced( DivLAligned( Strong(mail['name']), Span(cls='flex h-2 w-2 rounded-full bg-blue-600') if not mail['read'] else ''), Time(format_date(mail['date']), cls='text-xs')), Small(mail['subject'], href=f"#mail-{mail['id']}"), Div(mail['text'][:100] + '...', cls=TextPresets.muted_sm), DivLAligned( *[Label(A(label, href='#'), cls='uk-label-primary' if label == 'work' else '') for label in mail['labels']]), cls=cls) def MailList(mails): return Ul(cls='js-filter space-y-2 p-4 pt-0')(*[MailItem(mail) for mail in mails]) def MailContent(): return Div(cls='flex flex-col',uk_filter="target: .js-filter")( Div(cls='flex px-4 py-2 ')( H3('Inbox'), TabContainer(Li(A("All Mail",href='#', role='button'),cls='uk-active', uk_filter_control="filter: .tag-mail"), Li(A("Unread",href='#', role='button'), uk_filter_control="filter: .tag-unread"), alt=True, cls='ml-auto max-w-40', )), Div(cls='flex flex-1 flex-col')( Div(cls='p-4')( Div(cls='uk-inline w-full')( Span(cls='uk-form-icon text-muted-foreground')(UkIcon('search')), Input(placeholder='Search'))), Div(cls='flex-1 overflow-y-auto max-h-[600px]')(MailList(mail_data)))) def IconNavItem(*d): return [Li(A(UkIcon(o[0],uk_tooltip=o[1]))) for o in d] def IconNav(*c,cls=''): return Ul(cls=f'uk-iconnav {cls}')(*c) def MailDetailView(mail): top_icons = [('folder','Archive'), ('ban','Move to junk'), ('trash','Move to trash')] reply_icons = [('reply','Reply'), ('reply','Reply all'), ('forward','Forward')] dropdown_items = ['Mark as unread', 'Star read', 'Add Label', 'Mute Thread'] return Container( DivFullySpaced( DivLAligned( DivLAligned(*[UkIcon(o[0],uk_tooltip=o[1]) for o in top_icons]), Div(UkIcon('clock', uk_tooltip='Snooze'), cls='pl-2'), cls='space-x-2 divide-x divide-border'), DivLAligned( *[UkIcon(o[0],uk_tooltip=o[1]) for o in reply_icons], Div(UkIcon('ellipsis-vertical',button=True)), DropDownNavContainer(*map(lambda x: Li(A(x)), dropdown_items)))), DivLAligned( Span(mail['name'][:2], cls='flex h-10 w-10 items-center justify-center rounded-full bg-muted'), Div(Strong(mail['name']), Div(mail['subject']), DivLAligned(P('Reply-To:'), A(mail['email'], href=f"mailto:{mail['email']}"), cls='space-x-1'), P(Time(format_date(mail['date']))), cls='space-y-1'+TextT.sm), cls='m-4 space-x-4'), DividerLine(), P(mail['text'], cls=TextT.sm +'p-4'), DividerLine(), Div(TextArea(id='message', placeholder=f"Reply {mail['name']}"), DivFullySpaced( LabelSwitch('Mute this thread',id='mute'), Button('Send', cls=ButtonT.primary)), cls='space-y-4')) @rt def index(): return Title("Mail Example"),Container( Grid(Div(sidebar, cls='col-span-1'), Div(MailContent(), cls='col-span-2'), Div(MailDetailView(mail_data[0]), cls='col-span-2'), cols_sm=1, cols_md=1, cols_lg=5, cols_xl=5, gap=0, cls='flex-1'), cls=('flex', ContainerT.xl)) serve()
https://monsterui.answer.ai/mail/md
mail_md
"""FrankenUI Cards Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from fasthtml.components import Uk_input_tag from fasthtml.svg import * from monsterui.all import * import calendar from datetime import datetime app, rt = fast_app(hdrs=Theme.blue.headers()) CreateAccount = Card( Grid(Button(DivLAligned(UkIcon('github'),Div('Github'))),Button('Google')), DividerSplit("OR CONTINUE WITH", text_cls=TextPresets.muted_sm), LabelInput('Email', id='email', placeholder='[email protected]'), LabelInput('Password', id='password',placeholder='Password', type='Password'), header=(H3('Create an Account'),Subtitle('Enter your email below to create your account')), footer=Button('Create Account',cls=(ButtonT.primary,'w-full'))) PaypalSVG_data = "M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.565-5.946.36-1.847.174-3.388-.777-4.471z" AppleSVG_data = "M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701" Card1Svg = Svg(viewBox="0 0 24 24", fill="none", stroke="currentColor", stroke_linecap="round", stroke_linejoin="round", stroke_width="2", cls="h-6 w-6 mr-1")(Rect(width="20", height="14", x="2", y="5", rx="2"),Path(d="M2 10h20")) PaypalSvg = Svg(role="img", viewBox="0 0 24 24", cls="h-6 w-6 mr-1")(Path(d=PaypalSVG_data, fill="currentColor")), AppleSvg = Svg(role="img", viewBox="0 0 24 24", cls="h-6 w-6 mr-1")(Path(d=AppleSVG_data, fill="currentColor")) PaymentMethod = Card( Grid(Button(DivCentered(Card1Svg, "Card"), cls='h-20 border-2 border-primary'), Button(DivCentered(PaypalSvg, "PayPal"), cls='h-20'), Button(DivCentered(AppleSvg, "Apple"), cls='h-20')), Form(LabelInput('Name', id='name', placeholder='John Doe'), LabelInput('Card Number', id='card_number', placeholder='[email protected]'), Grid(LabelSelect(*Options(*calendar.month_name[1:],selected_idx=0),label='Expires',id='expire_month'), LabelSelect(*Options(*range(2024,2030),selected_idx=0), label='Year', id='expire_year'), LabelInput('CVV', id='cvv',placeholder='CVV', cls='mt-0'))), header=(H3('Payment Method'),Subtitle('Add a new payment method to your account.'))) area_opts = ('Team','Billing','Account','Deployment','Support') severity_opts = ('Severity 1 (Highest)', 'Severity 2', 'Severity 3', 'Severity 4 (Lowest)') ReportIssue = Card( Grid(Div(LabelSelect(*Options(*area_opts), label='Area', id='area')), Div(LabelSelect(*Options(*severity_opts),label='Severity',id='area'))), LabelInput( label='Subject', id='subject', placeholder='I need help with'), LabelTextArea( label='Description', id='description',placeholder='Please include all information relevant to your issue'), Div(FormLabel('Tags', fr='#tags'), Uk_input_tag(name="Tags",state="danger", value="Spam,Invalid", uk_cloak=True, id='tags')), header=(H3('Report Issue'),Subtitle('What area are you having problems with?')), footer = DivFullySpaced(Button('Cancel'), Button(cls=ButtonT.primary)('Submit'))) monster_desc ="Python-first beautifully designed components because you deserve to focus on features that matter and your app deserves to be beautiful from day one." MonsterUI = Card(H4("Monster UI"), Subtitle(monster_desc), DivLAligned( Div("Python"), DivLAligned(UkIcon('star'),Div("20k"), cls='space-x-1'), Div(datetime.now().strftime("%B %d, %Y")), cls=('space-x-4',TextPresets.muted_sm))) def CookieTableRow(heading, description, active=False): return Tr(Td(H5(heading)), Td(P(description, cls=TextPresets.muted_sm)), Td(Switch(checked=active))) CookieSettings = Card( Table(Tbody( CookieTableRow('Strictly Necessary', 'These cookies are essential in order to use the website and use its features.', True), CookieTableRow('Functional Cookies', 'These cookies allow the website to provide personalized functionality.'), CookieTableRow('Performance Cookies', 'These cookies help to improve the performance of the website.'))), header=(H4('Cookie Settings'),Subtitle('Manage your cookie settings here.')), footer=Button('Save Preferences', cls=(ButtonT.primary, 'w-full'))) team_members = [("Sofia Davis", "[email protected]", "Owner"),("Jackson Lee", "[email protected]", "Member"),] def TeamMemberRow(name, email, role): return DivFullySpaced( DivLAligned( DiceBearAvatar(name, 10,10), Div(P(name, cls=(TextT.sm, TextT.medium)), P(email, cls=TextPresets.muted_sm))), Button(role, UkIcon('chevron-down', cls='ml-4')), DropDownNavContainer(map(NavCloseLi, [ A(Div('Viewer', NavSubtitle('Can view and comment.'))), A(Div('Developer', NavSubtitle('Can view, comment and edit.'))), A(Div('Billing', NavSubtitle('Can view, comment and manage billing.'))), A(Div('Owner', NavSubtitle('Admin-level access to all resources.')))]))) TeamMembers = Card(*[TeamMemberRow(*member) for member in team_members], header = (H4('Team Members'),Subtitle('Invite your team members to collaborate.'))) access_roles = ("Read and write access", "Read-only access") team_members = [("Olivia Martin", "[email protected]", "Read and write access"), ("Isabella Nguyen", "[email protected]", "Read-only access"), ("Sofia Davis", "[email protected]", "Read-only access")] def TeamMemberRow(name, email, role): return DivFullySpaced( DivLAligned(DiceBearAvatar(name, 10,10), Div(P(name, cls=(TextT.sm, TextT.medium)), P(email, cls=TextPresets.muted_sm))), Select(*Options(*access_roles, selected_idx=access_roles.index(role)))) ShareDocument = Card( DivLAligned(Input(value='http://example.com/link/to/document'),Button('Copy link', cls='whitespace-nowrap')), Divider(), H4('People with access', cls=TextPresets.bold_sm), *[TeamMemberRow(*member) for member in team_members], header = (H4('Share this document'),Subtitle('Anyone with the link can view this document.'))) DateCard = Card(Button('Jan 20, 2024 - Feb 09, 2024')) section_content =(('bell','Everything',"Email digest, mentions & all activity."), ('user',"Available","Only mentions and comments"), ('ban', "Ignoring","Turn of all notifications")) def NotificationRow(icon, name, desc): return Li(cls='-mx-1')(A(DivLAligned(UkIcon(icon),Div(P(name),P(desc, cls=TextPresets.muted_sm))))) Notifications = Card( NavContainer( *[NotificationRow(*row) for row in section_content], cls=NavT.secondary), header = (H4('Notification'),Subtitle('Choose what you want to be notified about.')), body_cls='pt-0') TeamCard = Card( DivLAligned( DiceBearAvatar("Isaac Flath", h=24, w=24), Div(H3("Isaac Flath"), P("Library Creator"))), footer=DivFullySpaced( DivHStacked(UkIcon("map-pin", height=16), P("Alexandria, VA")), DivHStacked(*(UkIconLink(icon, height=16) for icon in ("mail", "linkedin", "github")))), cls=CardT.hover) @rt def index(): return Title("Cards Example"),Container(Grid( *map(Div,( Div(PaymentMethod,CreateAccount, TeamCard, cls='space-y-4'), Div(TeamMembers, ShareDocument,DateCard,Notifications, cls='space-y-4'), Div(ReportIssue,MonsterUI,CookieSettings, cls='space-y-4'))), cols_md=1, cols_lg=2, cols_xl=3)) serve()
https://monsterui.answer.ai/cards/md
cards_md
"""FrankenUI Playground Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * from fasthtml.svg import * app, rt = fast_app(hdrs=Theme.blue.headers()) preset_options = ["Grammatical Standard English", "Summarize for a 2nd grader", "Text to command","Q&A","English to other languages","Parse unstructured data", "Classification","Natural language to Python","Explain code","Chat","More examples"] def playground_navbar(): save_modal = Modal( ModalTitle("Save preset"), P("This will save the current playground state as a preset which you can access later or share with others.",cls=("mt-1.5", TextPresets.muted_sm)), LabelInput("Name", id="name"), LabelInput("Description", id="description"), ModalCloseButton("Save", cls=ButtonT.primary), id="save") share_dd = Div(cls="space-y-6 p-4")( H3("Share preset"), P("Anyone who has this link and an OpenAI account will be able to view this.", cls=TextPresets.muted_sm), Div(Input(value="https://platform.openai.com/playground/p/7bbKYQvsVkNmVb8NGcdUOLae?model=text-davinci-003", readonly=True), Button(UkIcon('copy'), cls=(ButtonT.primary, "uk-drop-close",'mt-4')))) rnav = ( Select(*Options(*preset_options), name='preset', optgroup_label="Examples", placeholder='Load a preset', searchable=True, cls='h-9 w-[200px] lg:w-[300px]'), Button("Save", cls=ButtonT.secondary, data_uk_toggle="#save"),save_modal, Button("View Code", cls=ButtonT.secondary), Button("Share", cls=ButtonT.secondary),DropDownNavContainer(share_dd), Button(UkIcon(icon="ellipsis"), cls=ButtonT.secondary), DropDownNavContainer( Li(A("Content filter preferences")), NavDividerLi(), Li(A("Delete preset", cls="text-destructive")), uk_dropdown="mode: click")) return NavBar(*rnav, brand=H4('Playground')) rsidebar = NavContainer( Select( Optgroup(map(Option,("text-davinci-003", "text-curie-001", "text-babbage-001", "text-ada-001")),label='GPT-3'), Optgroup(map(Option,("code-davinci-002", "code-cushman-001")),label='Codex'), label="Model", searchable=True), LabelRange(label='Temperature', value='12'), LabelRange(label='Maximum Length', value='80'), LabelRange(label='Top P', value='40'), cls='space-y-6 mt-8') @rt def index(): navbar = playground_navbar() main_content = Div( Div(cls="flex-1")( Textarea(cls="uk-textarea h-full p-4", placeholder="Write a tagline for an ice cream shop")), cls="flex h-[700px] p-8 w-4/5") bottom_buttons = Div( Button("Submit", cls=ButtonT.primary), Button(UkIcon(icon="history"), cls=ButtonT.secondary), cls="flex gap-x-2") return Title("Playground Example"),Div(navbar, Div(cls="flex w-full")(main_content, rsidebar), bottom_buttons) serve()
https://monsterui.answer.ai/playground/md
playground_md
"""FrankenUI Tasks Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * from fasthtml.svg import * import json app, rt = fast_app(hdrs=Theme.blue.headers()) def LAlignedCheckTxt(txt): return DivLAligned(UkIcon(icon='check'), P(txt, cls=TextPresets.muted_sm)) with open('data/status_list.json', 'r') as f: data = json.load(f) with open('data/statuses.json', 'r') as f: statuses = json.load(f) def _create_tbl_data(d): return {'Done': d['selected'], 'Task': d['id'], 'Title': d['title'], 'Status' : d['status'], 'Priority': d['priority'] } data = [_create_tbl_data(d) for d in data] page_size = 15 current_page = 0 paginated_data = data[current_page*page_size:(current_page+1)*page_size] priority_dd = [{'priority': "low", 'count': 36 }, {'priority': "medium", 'count': 33 }, {'priority': "high", 'count': 31 }] status_dd = [{'status': "backlog", 'count': 21 },{'status': "todo", 'count': 21 },{'status': "progress", 'count': 20 },{'status': "done",'count': 19 },{'status': "cancelled", 'count': 19 }] def create_hotkey_li(hotkey): return NavCloseLi(A(DivFullySpaced(hotkey[0], Span(hotkey[1], cls=TextPresets.muted_sm)))) hotkeys_a = (('Profile','β‡§βŒ˜P'),('Billing','⌘B'),('Settings','⌘S'),('New Team','')) hotkeys_b = (('Logout',''), ) avatar_opts = DropDownNavContainer( NavHeaderLi(P('sveltecult'),NavSubtitle('[email protected]')), NavDividerLi(), *map(create_hotkey_li, hotkeys_a), NavDividerLi(), *map(create_hotkey_li, hotkeys_b),) def CreateTaskModal(): return Modal( Div(cls='p-6')( ModalTitle('Create Task'), P('Fill out the information below to create a new task', cls=TextPresets.muted_sm), Br(), Form(cls='space-y-6')( Grid(Div(Select(*map(Option,('Documentation', 'Bug', 'Feature')), label='Task Type', id='task_type')), Div(Select(*map(Option,('In Progress', 'Backlog', 'Todo', 'Cancelled', 'Done')), label='Status', id='task_status')), Div(Select(*map(Option, ('Low', 'Medium', 'High')), label='Priority', id='task_priority'))), TextArea(label='Title', placeholder='Please describe the task that needs to be completed'), DivRAligned( ModalCloseButton('Cancel', cls=ButtonT.ghost), ModalCloseButton('Submit', cls=ButtonT.primary), cls='space-x-5'))), id='TaskForm') page_heading = DivFullySpaced(cls='space-y-2')( Div(cls='space-y-2')( H2('Welcome back!'),P("Here's a list of your tasks for this month!", cls=TextPresets.muted_sm)), Div(DiceBearAvatar("sveltcult",8,8),avatar_opts)) table_controls =(Input(cls='w-[250px]',placeholder='Filter task'), Button("Status"), DropDownNavContainer(map(NavCloseLi,[A(DivFullySpaced(P(a['status']), P(a['count'])),cls='capitalize') for a in status_dd])), Button("Priority"), DropDownNavContainer(map(NavCloseLi,[A(DivFullySpaced(LAlignedCheckTxt(a['priority']), a['count']),cls='capitalize') for a in priority_dd])), Button("View"), DropDownNavContainer(map(NavCloseLi,[A(LAlignedCheckTxt(o)) for o in ['Title','Status','Priority']])), Button('Create Task',cls=(ButtonT.primary, TextPresets.bold_sm), data_uk_toggle="target: #TaskForm")) def task_dropdown(): return Div(Button(UkIcon('ellipsis')), DropDownNavContainer( map(NavCloseLi,[ *map(A,('Edit', 'Make a copy', 'Favorite')), A(DivFullySpaced(*[P(o, cls=TextPresets.muted_sm) for o in ('Delete', '⌘⌫')]))]))) def header_render(col): match col: case "Done": return Th(CheckboxX(), shrink=True) case 'Actions': return Th("", shrink=True) case _: return Th(col, expand=True) def cell_render(col, val): def _Td(*args,cls='', **kwargs): return Td(*args, cls=f'p-2 {cls}',**kwargs) match col: case "Done": return _Td(shrink=True)(CheckboxX(selected=val)) case "Task": return _Td(val, cls='uk-visible@s') # Hide on small screens case "Title": return _Td(val, cls='font-medium', expand=True) case "Status" | "Priority": return _Td(cls='uk-visible@m uk-text-nowrap capitalize')(Span(val)) case "Actions": return _Td(task_dropdown(), shrink=True) case _: raise ValueError(f"Unknown column: {col}") task_columns = ["Done", 'Task', 'Title', 'Status', 'Priority', 'Actions'] tasks_table = Div(cls='mt-4')( TableFromDicts( header_data=task_columns, body_data=paginated_data, body_cell_render=cell_render, header_cell_render=header_render, sortable=True, cls=(TableT.responsive, TableT.sm, TableT.divider))) def footer(): total_pages = (len(data) + page_size - 1) // page_size return DivFullySpaced( Div('1 of 100 row(s) selected.', cls=TextPresets.muted_sm), DivLAligned( DivCentered(f'Page {current_page + 1} of {total_pages}', cls=TextT.sm), DivLAligned(*[UkIconLink(icon=i, button=True) for i in ('chevrons-left', 'chevron-left', 'chevron-right', 'chevrons-right')]))) tasks_ui = Div(DivFullySpaced(DivLAligned(table_controls), cls='mt-8'), tasks_table, footer()) @rt def index(): return Container(page_heading, tasks_ui, CreateTaskModal()) serve()
https://monsterui.answer.ai/tasks/md
tasks_md
"""FrankenUI Music Example build with MonsterUI (Original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * app, rt = fast_app(hdrs=Theme.blue.headers()) def MusicLi(t,hk=''): return Li(A(DivFullySpaced(t,P(hk,cls=TextPresets.muted_sm)))) music_items = [("About Music", "" ), ("Preferences", "⌘" ), ("Hide Music" , "⌘H" ), ("Hide Others", "β‡§βŒ˜H"), ("Quit Music" , "⌘Q" )] file_dd_items = [("New", ""), ("Open Stream URL", "⌘U"), ("Close Window", "⌘W"), ("Library", ""), ("Import", "⌘O"), ("Burn Playlist to Disc", ""), ("Show in Finder", "β‡§βŒ˜R"), ("Convert", ""), ("Page Setup", "Print")] edit_actions = [("Undo", "⌘Z"), ("Redo", "β‡§βŒ˜Z"), ("Cut", "⌘X"), ("Copy", "⌘C"), ("Paste", "⌘V"), ("Select All", "⌘A"), ("Deselect All", "β‡§βŒ˜A")] view_dd_data = ["Show Playing Next", "Show Lyrics", "Show Status Bar", "Hide Sidebar", "Enter Full Screen"] music_headers = NavBar( Button("Music", cls=ButtonT.ghost+TextT.gray),DropDownNavContainer(Li(A("Music"),NavContainer(map(lambda x: MusicLi(*x), music_items)))), Button("File", cls=ButtonT.ghost+TextT.gray), DropDownNavContainer(Li(A("File"), NavContainer(map(lambda x: MusicLi(*x), file_dd_items)))), Button("Edit", cls=ButtonT.ghost+TextT.gray), DropDownNavContainer(Li(A("Edit")),NavContainer( *map(lambda x: MusicLi(*x), edit_actions), Li(A(DivFullySpaced("Smart Dictation",UkIcon("mic")))), Li(A(DivFullySpaced("Emojis & Symbols",UkIcon("globe")))))), Button("View", cls=ButtonT.ghost+TextT.gray),DropDownNavContainer(Li(A("View"),NavContainer(map(lambda x: MusicLi(x), view_dd_data)))), ) # music_headers = NavBarContainer( # NavBarLSide( # NavBarNav( # Li(A("Music"),NavBarNavContainer(map(lambda x: MusicLi(*x), music_items))), # Li(A("File"), NavBarNavContainer(map(lambda x: MusicLi(*x), file_dd_items))), # Li(A("Edit")), # NavBarNavContainer( # *map(lambda x: MusicLi(*x), edit_actions), # Li(A(DivFullySpaced("Smart Dictation",UkIcon("mic")))), # Li(A(DivFullySpaced("Emojis & Symbols",UkIcon("globe"))))), # Li(A("View"), # NavBarNavContainer(map(lambda x: MusicLi(x), view_dd_data))), # Li(A("Account"), # NavBarNavContainer( # NavHeaderLi("Switch Account"), # *map(MusicLi, ("Andy", "Benoit", "Luis", "Manage Family", "Add Account"))))))) def Album(title,artist): img_url = 'https://ucarecdn.com/e5607eaf-2b2a-43b9-ada9-330824b6afd7/music1.webp' return Div( Div(cls="overflow-hidden rounded-md")(Img(cls="transition-transform duration-200 hover:scale-105", src=img_url)), Div(cls='space-y-1')(Strong(title),P(artist,cls=TextT.muted))) listen_now_albums = (("Roar", "Catty Perry"), ("Feline on a Prayer", "Cat Jovi"),("Fur Elise", "Ludwig van Beethovpurr"),("Purrple Rain", "Prince's Cat")) made_for_you_albums = [("Like a Feline", "Catdonna"), ("Livin' La Vida Purrda", "Ricky Catin"), ("Meow Meow Rocket", "Elton Cat"), ("Rolling in the Purr", "Catdelle"), ("Purrs of Silence", "Cat Garfunkel"), ("Meow Me Maybe", "Carly Rae Purrsen"),] music_content = (Div(H3("Listen Now"), cls="mt-6 space-y-1"), Subtitle("Top picks for you. Updated daily."), DividerLine(), Grid(*[Album(t,a) for t,a in listen_now_albums], cls='gap-8'), Div(H3("Made for You"), cls="mt-6 space-y-1"), Subtitle("Your personal playlists. Updated daily."), DividerLine(), Grid(*[Album(t,a) for t,a in made_for_you_albums], cols_xl=6)) tabs = TabContainer( Li(A('Music', href='#'), cls='uk-active'), Li(A('Podcasts', href='#')), Li(A('Live', cls='opacity-50'), cls='uk-disabled'), uk_switcher='connect: #component-nav; animation: uk-animation-fade', alt=True) def podcast_tab(): return Div( Div(cls='space-y-3 mt-6')( H3("New Episodes"), Subtitle("Your favorite podcasts. Updated daily.")), Div(cls="uk-placeholder flex h-[450px] items-center justify-center rounded-md mt-4",uk_placeholder=True)( DivVStacked(cls="space-y-6")( UkIcon("microphone", 3), H4("No episodes added"), Subtitle("You have not added any podcasts. Add one below."), Button("Add Podcast", cls=ButtonT.primary)))) discoved_data = [("play-circle","Listen Now"), ("binoculars", "Browse"), ("rss","Radio")] library_data = [("play-circle", "Playlists"), ("music", "Songs"), ("user", "Made for You"), ("users", "Artists"), ("bookmark", "Albums")] playlists_data = [("library","Recently Added"), ("library","Recently Played")] def MusicSidebarLi(icon, text): return Li(A(DivLAligned(UkIcon(icon), P(text)))) sidebar = NavContainer( NavHeaderLi(H3("Discover")), *[MusicSidebarLi(*o) for o in discoved_data], NavHeaderLi(H3("Library")), *[MusicSidebarLi(*o) for o in library_data], NavHeaderLi(H3("Playlists")),*[MusicSidebarLi(*o) for o in playlists_data], cls=(NavT.primary,'space-y-3','pl-8')) @rt def index(): return Title("Music Example"),Container(music_headers, DividerSplit(), Grid(sidebar, Div(cls="col-span-4 border-l border-border")( Div(cls="px-8 py-6")( DivFullySpaced( Div(cls="max-w-80")(tabs), Button(cls=ButtonT.primary)(DivLAligned(UkIcon('circle-plus')),Div("Add music"))), Ul(id="component-nav", cls="uk-switcher")( Li(*music_content), Li(podcast_tab())))), cols_sm=1, cols_md=1, cols_lg=5, cols_xl=5)) serve()
https://monsterui.answer.ai/music/md
music_md
"""FrankenUI Forms Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * from fasthtml.svg import * app, rt = fast_app(hdrs=Theme.blue.headers()) def HelpText(c): return P(c,cls=TextPresets.muted_sm) def heading(): return Div(cls="space-y-5")( H2("Settings"), Subtitle("Manage your account settings and set e-mail preferences."), DividerSplit()) sidebar = NavContainer( *map(lambda x: Li(A(x)), ("Profile", "Account", "Appearance", "Notifications", "Display")), uk_switcher="connect: #component-nav; animation: uk-animation-fade", cls=(NavT.secondary,"space-y-4 p-4 w-1/5")) def FormSectionDiv(*c, cls='space-y-2', **kwargs): return Div(*c, cls=cls, **kwargs) def FormLayout(title, subtitle, *content, cls='space-y-3 mt-4'): return Container(Div(H3(title), Subtitle(subtitle), DividerLine(), Form(*content, cls=cls))) def profile_form(): content = (FormSectionDiv( LabelInput("Username", placeholder='sveltecult', id='username'), HelpText("This is your public display name. It can be your real name or a pseudonym. You can only change this once every 30 days.")), FormSectionDiv( LabelSelect( Option("Select a verified email to display", value="", selected=True, disabled=True), *[Option(o, value=o) for o in ('[email protected]', '[email protected]', '[email protected]')], label="Email", id="email"), HelpText("You can manage verified email addresses in your email settings.")), FormSectionDiv( LabelTextArea("Bio", id="bio", placeholder="Tell us a little bit about yourself"), HelpText("You can @mention other users and organizations to link to them."), P("String must contain at least 4 character(s)", cls="text-destructive")), FormSectionDiv( FormLabel("URLs"), HelpText("Add links to your website, blog, or social media profiles."), Input(value="https://www.franken-ui.dev"), Input(value="https://github.com/sveltecult/franken-ui"), Button("Add URL")), Button('Update profile', cls=ButtonT.primary)) return FormLayout('Profile', 'This is how others will see you on the site.', *content) def account_form(): content = ( FormSectionDiv( LabelInput("Name", placeholder="Your name", id="name"), HelpText("This is the name that will be displayed on your profile and in emails.")), FormSectionDiv( LabelInput("Date of Birth", type="date", placeholder="Pick a date", id="date_of_birth"), HelpText("Your date of birth is used to calculate your age.")), FormSectionDiv( LabelSelect(*Options("Select a language", "English", "French", "German", "Spanish", "Portuguese", selected_idx=1, disabled_idxs={0}), label='Language', id="language"), HelpText("This is the language that will be used in the dashboard.")), Button('Update profile', cls=ButtonT.primary)) return FormLayout('Account', 'Update your account settings. Set your preferred language and timezone.', *content) def appearance_form(): def theme_item(bg_color, content_bg, text_bg): common_content = f"space-y-2 rounded-md {content_bg} p-2 shadow-sm" item_row = lambda: Div(cls=f"flex items-center space-x-2 {common_content}")( Div(cls=f"h-4 w-4 rounded-full {text_bg}"), Div(cls=f"h-2 w-[100px] rounded-lg {text_bg}")) return Div(cls=f"space-y-2 rounded-sm {bg_color} p-2")( Div(cls=common_content)( Div(cls=f"h-2 w-[80px] rounded-lg {text_bg}"), Div(cls=f"h-2 w-[100px] rounded-lg {text_bg}")), item_row(), item_row()) common_toggle_cls = "block cursor-pointer items-center rounded-md border-2 border-muted p-1 ring-ring" content = ( FormSectionDiv( LabelSelect(*Options('Select a font family', 'Inter', 'Geist', 'Open Sans', selected_idx=2, disabled_idxs={0}), label='Font Family', id='font_family'), HelpText("Set the font you want to use in the dashboard.")), FormSectionDiv( FormLabel("Theme"), HelpText("Select the theme for the dashboard."), Grid( A(id="theme-toggle-light", cls=common_toggle_cls)(theme_item("bg-[#ecedef]", "bg-white", "bg-[#ecedef]")), A(id="theme-toggle-dark", cls=f"{common_toggle_cls} bg-popover")(theme_item("bg-slate-950", "bg-slate-800", "bg-slate-400")), cols_max=2,cls=('max-w-md','gap-8'))), Button('Update preferences', cls=ButtonT.primary)) return FormLayout('Appearance', 'Customize the appearance of the app. Automatically switch between day and night themes.', *content) notification_items = [ {"title": "Communication emails", "description": "Receive emails about your account activity.", "checked": False, "disabled": False}, {"title": "Marketing emails", "description": "Receive emails about new products, features, and more.", "checked": False, "disabled": False}, {"title": "Social emails", "description": "Receive emails for friend requests, follows, and more.", "checked": True, "disabled": False}, {"title": "Security emails", "description": "Receive emails about your account activity and security.", "checked": True, "disabled": True}] def notifications_form(): def RadioLabel(label): return DivLAligned(Radio(name="notification", checked=(label=="Nothing")), FormLabel(label)) def NotificationCard(item): return Card( Div(cls="space-y-0.5")( FormLabel(Strong(item['title'], cls=TextT.sm), HelpText(item['description'])))) content = Div( FormSectionDiv( FormLabel("Notify me about"), *map(RadioLabel, ["All new messages", "Direct messages and mentions", "Nothing"])), Div( H4("Email Notifications", cls="mb-4"), Grid(*map(NotificationCard, notification_items), cols=1)), LabelCheckboxX("Use different settings for my mobile devices", id="notification_mobile"), HelpText("You can manage your mobile notifications in the mobile settings page."), Button('Update notifications', cls=ButtonT.primary)) return FormLayout('Notifications', 'Configure how you receive notifications.', *content) def display_form(): content = ( Div(cls="space-y-2")( Div(cls="mb-4")( H5("Sidebar"), Subtitle("Select the items you want to display in the sidebar.")), *[Div(CheckboxX(id=f"display_{i}", checked=i in [0, 1, 2]),FormLabel(label)) for i, label in enumerate(["Recents", "Home", "Applications", "Desktop", "Downloads", "Documents"])]), Button('Update display', cls=ButtonT.primary)) return FormLayout('Display', 'Turn items on or off to control what\'s displayed in the app.', *content) @rt def index(): return Title("Forms Example"),Container( heading(), Div(cls="flex gap-x-12")( sidebar, Ul(id="component-nav", cls="uk-switcher max-w-2xl")( Li(cls="uk-active")(profile_form(), *map(Li, [account_form(), appearance_form(), notifications_form(), display_form()]))))) serve()
https://monsterui.answer.ai/forms/md
forms_md
"""FrankenUI Auth Example built with MonsterUI (original design by ShadCN)""" from fasthtml.common import * from monsterui.all import * from fasthtml.svg import * app, rt = fast_app(hdrs=Theme.blue.headers()) @rt def index(): left = Div(cls="col-span-1 hidden flex-col justify-between bg-zinc-900 p-8 text-white lg:flex")( Div(cls=(TextT.bold))("Acme Inc"), Blockquote(cls="space-y-2")( P(cls=TextT.lg)('"This library has saved me countless hours of work and helped me deliver stunning designs to my clients faster than ever before."'), Footer(cls=TextT.sm)("Sofia Davis"))) right = Div(cls="col-span-2 flex flex-col p-8 lg:col-span-1")( DivRAligned(Button("Login", cls=ButtonT.ghost)), DivCentered(cls='flex-1')( Container( DivVStacked( H3("Create an account"), Small("Enter your email below to create your account", cls=TextT.muted)), Form( Input(placeholder="[email protected]"), Button(Span(cls="mr-2", uk_spinner="ratio: 0.54"), "Sign in with Email", cls=(ButtonT.primary, "w-full"), disabled=True), DividerSplit(Small("Or continue with"),cls=TextT.muted), Button(UkIcon('github',cls='mr-2'), "Github", cls=(ButtonT.default, "w-full")), cls='space-y-6'), DivVStacked(Small( "By clicking continue, you agree to our ", A(cls=AT.muted, href="#demo")("Terms of Service")," and ", A(cls=AT.muted, href="#demo")("Privacy Policy"),".", cls=(TextT.muted,"text-center"))), cls="space-y-6"))) return Title("Auth Example"),Grid(left,right,cols=2, gap=0,cls='h-screen') serve()
https://monsterui.answer.ai/auth/md
auth_md
# Buttons & Links API Reference See Source See Output DefaultPrimarySecondaryDangerTextLinkGhost [code] def ex_buttons(): return Grid( Button("Default"), Button("Primary", cls=ButtonT.primary), Button("Secondary", cls=ButtonT.secondary), Button("Danger", cls=ButtonT.destructive), Button("Text", cls=ButtonT.text), Button("Link", cls=ButtonT.link), Button("Ghost", cls=ButtonT.ghost), ) [/code] See Source See Output Default LinkMuted LinkText LinkReset LinkPrimary LinkClassic Link [code] def ex_links(): return Div(cls='space-x-4')( A('Default Link'), A('Muted Link', cls=AT.muted), A('Text Link', cls=AT.text), A('Reset Link', cls=AT.reset), A('Primary Link', cls=AT.primary), A('Classic Link', cls=AT.classic),) [/code] ### Button Source [code] Button(*c: Union[str, fastcore.xml.FT], cls: Union[str, enum.Enum] = <ButtonT.default: 'uk-btn-default'>, submit=True, **kwargs) -> fastcore.xml.FT [/code] > Button with Styling (defaults to `submit` for form submission) **Params** * `c` Contents of `Button` tag (often text) * `cls` Classes in addition to `Button` styling (use `ButtonT` for built in styles) * `submit` Whether the button should submit a form * `kwargs` **Returns:** Button(..., cls='uk-btn') * * * ### ButtonT _Options for styling Buttons_ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- default | uk-btn-default | ghost | uk-btn-ghost | primary | uk-btn-primary secondary | uk-btn-secondary | destructive | uk-btn-destructive | text | uk-btn-text link | uk-btn-link | xs | uk-btn-xs | sm | uk-btn-sm lg | uk-btn-lg | xl | uk-btn-xl | icon | uk-btn-icon * * * ### AT _Link styles from https://franken-ui.dev/docs/link_ Option | Value | Option | Value ---|---|---|--- muted | uk-link-muted | text | uk-link-text reset | uk-link-reset | primary | uk-link text-primary hover:text-primary-focus underline classic | text-blue-600 hover:text-blue-800 underline | |
https://monsterui.answer.ai/api_ref/docs_button_link/md
docs_button_link_md
# Cards API Reference ### Example Usage See Source See Output Header A card with header and footer Input Range Footer Submit Button [code] def ex_card(): return Card( Form(LabelInput("Input"), LabelRange("Range")), header=Div( CardTitle("Header"), P("A card with header and footer",cls=TextPresets.muted_sm)), footer=DivLAligned(Button("Footer Submit Button"))) [/code] See Source See Output #### Creating Custom FastHTML Tags for Markdown Rendering A step by step tutorial to rendering markdown in FastHTML using zero-md inside of DaisyUI chat bubbles Isaac Flath20-October-2024 FastHTMLHTMXWeb Apps Read [code] def ex_card2_wide(): def Tags(cats): return DivLAligned(map(Label, cats)) return Card( DivLAligned( A(Img(src="https://picsum.photos/200/200?random=12", style="width:200px"),href="#"), Div(cls='space-y-3 uk-width-expand')( H4("Creating Custom FastHTML Tags for Markdown Rendering"), P("A step by step tutorial to rendering markdown in FastHTML using zero-md inside of DaisyUI chat bubbles"), DivFullySpaced(map(Small, ["Isaac Flath", "20-October-2024"]), cls=TextT.muted), DivFullySpaced( Tags(["FastHTML", "HTMX", "Web Apps"]), Button("Read", cls=(ButtonT.primary,'h-6'))))), cls=CardT.hover) [/code] See Source See Output #### Creating Custom FastHTML Tags for Markdown Rendering A step by step tutorial to rendering markdown in FastHTML using zero-md inside of DaisyUI chat bubbles Isaac Flath20-October-2024 FastHTMLHTMXWeb Apps Read [code] def ex_card2_tall(): def Tags(cats): return DivLAligned(map(Label, cats)) return Card( Div( A(Img(src="https://picsum.photos/400/200?random=14"), href="#"), Div(cls='space-y-3 uk-width-expand')( H4("Creating Custom FastHTML Tags for Markdown Rendering"), P("A step by step tutorial to rendering markdown in FastHTML using zero-md inside of DaisyUI chat bubbles"), DivFullySpaced(map(Small, ["Isaac Flath", "20-October-2024"]), cls=TextT.muted), DivFullySpaced( Tags(["FastHTML", "HTMX", "Web Apps"]), Button("Read", cls=(ButtonT.primary,'h-6'))))), cls=CardT.hover) [/code] See Source See Output ### Sarah Chen Engineering Lead San Francisco ### James Wilson Senior Developer New York ### Maria Garcia UX Designer London ### Alex Kumar Product Manager Singapore ### Emma Brown DevOps Engineer Toronto ### Marcus Johnson Frontend Developer Berlin [code] def ex_card3(): def team_member(name, role, location="Remote"): return Card( DivLAligned( DiceBearAvatar(name, h=24, w=24), Div(H3(name), P(role))), footer=DivFullySpaced( DivHStacked(UkIcon("map-pin", height=16), P(location)), DivHStacked(*(UkIconLink(icon, height=16) for icon in ("mail", "linkedin", "github"))))) team = [ team_member("Sarah Chen", "Engineering Lead", "San Francisco"), team_member("James Wilson", "Senior Developer", "New York"), team_member("Maria Garcia", "UX Designer", "London"), team_member("Alex Kumar", "Product Manager", "Singapore"), team_member("Emma Brown", "DevOps Engineer", "Toronto"), team_member("Marcus Johnson", "Frontend Developer", "Berlin") ] return Grid(*team, cols_sm=1, cols_md=1, cols_lg=2, cols_xl=3) [/code] ### API Reference ### Card Source [code] Card(*c, header: Union[fastcore.xml.FT, Iterable[fastcore.xml.FT]] = None, footer: Union[fastcore.xml.FT, Iterable[fastcore.xml.FT]] = None, body_cls='space-y-6', header_cls=(), footer_cls=(), cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a Card with a header, body, and footer **Params** * `c` Components that go in the body (Main content of the card such as a form, and image, a signin form, etc.) * `header` Component(s) that goes in the header (often a `ModalTitle` and a subtitle) * `footer` Component(s) that goes in the footer (often a `ModalCloseButton`) * `body_cls` classes for the body * `header_cls` classes for the header * `footer_cls` classes for the footer * `cls` class for outermost component * `kwargs` **Returns:** Card component ### CardTitle Source [code] CardTitle(*c, cls=(), **kwargs) [/code] > Creates a card title **Params** * `c` Components (often a string) * `cls` Additional classes on the div * `kwargs` * * * ### CardT _Card styles from UIkit_ Option | Value | Option | Value ---|---|---|--- default | uk-card-default | primary | uk-card-primary secondary | uk-card-secondary | destructive | uk-card-destructive hover | uk-card hover:shadow-lg hover:-translate-y-1 transition-all duration-200 | | The remainder of these are only needed if you're doing something really special. They are used in the `Card` function to generate the boilerplate for you. ### CardContainer Source [code] CardContainer(*c, cls=<CardT.default: 'uk-card-default'>, **kwargs) -> fastcore.xml.FT [/code] > Creates a card container **Params** * `c` Components (typically `CardHeader`, `CardBody`, `CardFooter`) * `cls` Additional classes on the div * `kwargs` **Returns:** Container for a card ### CardHeader Source [code] CardHeader(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a card header **Params** * `c` Components that goes in the header (often a `ModalTitle` and description) * `cls` Additional classes on the div * `kwargs` **Returns:** Container for the header of a card ### CardBody Source [code] CardBody(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a card body **Params** * `c` Components that go in the body (Main content of the card such as a form, and image, a signin form, etc.) * `cls` Additional classes on the div * `kwargs` **Returns:** Container for the body of a card ### CardFooter Source [code] CardFooter(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a card footer **Params** * `c` Components that go in the footer (often a `ModalCloseButton`) * `cls` Additional classes on the div * `kwargs` **Returns:** Container for the footer of a card
https://monsterui.answer.ai/api_ref/docs_cards/md
docs_cards_md
# Articles, Containers & Sections API Reference ### ArticleMeta Source [code] ArticleMeta(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A metadata component for use within an Article showing things like date, author etc **Params** * `c` contents of ArticleMeta tag (often other tags) * `cls` Classes in addition to ArticleMeta styling * `kwargs` **Returns:** P(..., cls='uk-article-meta') ### ArticleTitle Source [code] ArticleTitle(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A title component for use within an Article **Params** * `c` contents of ArticleTitle tag (often other tags) * `cls` Classes in addition to ArticleTitle styling * `kwargs` **Returns:** H1(..., cls='uk-article-title') ### Article Source [code] Article(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A styled article container for blog posts or similar content **Params** * `c` contents of Article tag (often other tags) * `cls` Classes in addition to Article styling * `kwargs` **Returns:** Article(..., cls='uk-article') See Source See Output # Sample Article Title By: John Doe lorem ipsum dolor sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. [code] def ex_articles(): return Article( ArticleTitle("Sample Article Title"), Subtitle("By: John Doe"), P('lorem ipsum dolor sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.')) [/code] ### Container Source [code] Container(*c, cls=('mt-5', <ContainerT.xl: 'uk-container-xl'>), **kwargs) -> fastcore.xml.FT [/code] > Div to be used as a container that often wraps large sections or a page of content **Params** * `c` Contents of Container tag (often other FT Components) * `cls` Classes in addition to Container styling * `kwargs` **Returns:** Container(..., cls='uk-container') * * * ### ContainerT _Max width container sizes from https://franken-ui.dev/docs/container_ Option | Value | Option | Value ---|---|---|--- xs | uk-container-xs | sm | uk-container-sm lg | uk-container-lg | xl | uk-container-xl expand | uk-container-expand | | See Source See Output This is a sample container with custom styling. [code] def ex_containers(): return Container( "This is a sample container with custom styling.", cls=ContainerT.xs, style="background-color: #FFA500; color: #000000") [/code] ### Section Source [code] Section(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Section with styling and margins **Params** * `c` contents of Section tag (often other tags) * `cls` Classes in addition to Section styling * `kwargs` **Returns:** Div(..., cls='uk-section') * * * ### SectionT _Section styles from https://franken-ui.dev/docs/section_ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- default | uk-section-default | muted | uk-section-muted | primary | uk-section-primary secondary | uk-section-secondary | xs | uk-section-xsmall | sm | uk-section-small lg | uk-section-large | xl | uk-section-xlarge | remove_vertical | uk-section-remove-vertical
https://monsterui.answer.ai/api_ref/docs_containers/md
docs_containers_md
# Dividers API Reference ### Divider Source [code] Divider(*c, cls=('my-4', <DividerT.icon: 'uk-divider-icon'>), **kwargs) -> fastcore.xml.FT [/code] > Divider with default styling and margin **Params** * `c` contents of Divider tag (often nothing) * `cls` Classes in addition to Divider styling * `kwargs` **Returns:** Hr(..., cls='uk-divider-icon') or Div(..., cls='uk-divider-vertical') * * * ### DividerT _Divider Styles from https://franken-ui.dev/docs/divider_ Option | Value | Option | Value ---|---|---|--- icon | uk-divider-icon | sm | uk-divider-sm vertical | uk-divider-vertical | | See Source See Output Small Divider * * * Vertical Divider Icon Divider * * * [code] def ex_dividers(): return Div( P("Small Divider"), Divider(cls=DividerT.sm), DivCentered( P("Vertical Divider"), Divider(cls=DividerT.vertical)), DivCentered("Icon Divider"), Divider(cls=DividerT.icon)) [/code] ### DividerSplit Source [code] DividerSplit(*c, cls=(), line_cls=(), text_cls=()) [/code] > Creates a simple horizontal line divider with configurable thickness and vertical spacing **Params** * `c` * `cls` * `line_cls` * `text_cls` See Source See Output Or continue with [code] def ex_dividersplit(): return DividerSplit(P("Or continue with", cls=TextPresets.muted_sm)) [/code] ### DividerLine Source [code] DividerLine(lwidth=2, y_space=4) [/code] > **Params** * `lwidth` * `y_space` See Source See Output * * * [code] def ex_dividerline(): return DividerLine() [/code]
https://monsterui.answer.ai/api_ref/docs_dividers/md
docs_dividers_md
# Forms and User Inputs API Reference ### Example Form This form was live coded in a 5 minute video here See Source See Output ### Emergency Contact Form Please fill out the form completely First Name Last Name Email Phone ### Relationship to patient Parent Sibling Friend Spouse Significant Other Relative Child Other Address Address Line 2 City State Zip Submit Form [code] def ex_form(): relationship = ["Parent",'Sibling', "Friend", "Spouse", "Significant Other", "Relative", "Child", "Other"] return Div(cls='space-y-4')( DivCentered( H3("Emergency Contact Form"), P("Please fill out the form completely", cls=TextPresets.muted_sm)), Form(cls='space-y-4')( Grid(LabelInput("First Name",id='fn'), LabelInput("Last Name",id='ln')), Grid(LabelInput("Email", id='em'), LabelInput("Phone", id='ph')), H3("Relationship to patient"), Grid(*[LabelCheckboxX(o) for o in relationship], cols=4, cls='space-y-3'), LabelInput("Address", id='ad'), LabelInput("Address Line 2", id='ad2'), Grid(LabelInput("City", id='ct'), LabelInput("State", id='st')), LabelInput("Zip", id='zp'), DivCentered(Button("Submit Form", cls=ButtonT.primary)))) [/code] See Source See Output Upload Button! Upload Zone [code] def ex_upload(): return Div(Upload("Upload Button!", id='upload1'), UploadZone(DivCentered(Span("Upload Zone"), UkIcon("upload")), id='upload2'), cls='space-y-4') [/code] ### FormLabel Source [code] FormLabel(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Label with default styling **Params** * `c` contents of FormLabel tag (often text) * `cls` Classes in addition to FormLabel styling * `kwargs` **Returns:** Label(..., cls='uk-form-label') See Source See Output Form Label [code] def ex_formlabel(): return FormLabel("Form Label") [/code] ### Input Source [code] Input(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > An Input with default styling **Params** * `c` contents of Input tag (often nothing) * `cls` Classes in addition to Input styling * `kwargs` **Returns:** Input(..., cls='uk-input') See Source See Output Input [code] def ex_input(): return Div( Input(placeholder="Enter text"), LabelInput(label="Input", id='myid')) [/code] ### LabelInput Source [code] LabelInput(label: str | fastcore.xml.FT, lbl_cls='', input_cls='', cls='space-y-2', id='', **kwargs) -> fastcore.xml.FT [/code] > A `FormLabel` and `Input` pair that provides default spacing and links/names them based on id **Params** * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Input` * `cls` Classes on container (default is `'space-y-2'` to prevent scrunched up form elements) * `id` id for `FormLabel` and `Input` (`id`, `name` and `for` attributes are set to this value) * `kwargs` **Returns:** Div(cls='space-y-2')(`FormLabel`, `Input`) ### LabelCheckboxX Source [code] LabelCheckboxX(label: str | fastcore.xml.FT, lbl_cls='', input_cls='', container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False), cls='flex items-center space-x-2', id='', **kwargs) -> fastcore.xml.FT [/code] > A FormLabel and CheckboxX pair that provides default spacing and links/names them based on id **Params** * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `CheckboxX` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is 'flex items-center space-x-2') * `id` id for `FormLabel` and `CheckboxX` (`id`, `name` and `for` attributes are set to this value) * `kwargs` **Returns:** Div(cls='flex items-center space-x-2')(`FormLabel`, `CheckboxX`) ### LabelSwitch Source [code] LabelSwitch(label: str | fastcore.xml.FT, lbl_cls='', input_cls='', cls='space-x-2', id='', *, container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False)) -> fastcore.xml.FT [/code] > **Params** * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Switch` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is `'space-x-2'` to prevent scrunched up form elements) * `id` id for `FormLabel` and `Switch` (`id`, `name` and `for` attributes are set to this value) **Returns:** Div(cls='space-y-2')(`FormLabel`, `Switch`) ### LabelRange Source [code] LabelRange(label: str | fastcore.xml.FT, lbl_cls='', input_cls='', cls='space-y-6', id='', value='', min=None, max=None, step=None, label_range=True, *, container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False)) -> fastcore.xml.FT [/code] > A FormLabel and Range pair that provides default spacing and links/names them based on id **Params** * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Range` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is `'space-y-2'` to prevent scrunched up form elements) * `id` id for `FormLabel` and `Range` (`id`, `name` and `for` attributes are set to this value) * `value` Value for the range input * `min` Minimum value * `max` Maximum value * `step` Step size * `label_range` Whether to show the range value label (label for the `Range` component) **Returns:** Div(cls='space-y-2')(`FormLabel`, `Range`) ### LabelTextArea Source [code] LabelTextArea(label: str | fastcore.xml.FT, value='', lbl_cls='', input_cls='', cls='space-y-2', id='', **kwargs) -> fastcore.xml.FT [/code] > **Params** * `label` FormLabel content (often text) * `value` Value for the textarea * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `TextArea` * `cls` Classes on container (default is `'space-y-2'` to prevent scrunched up form elements) * `id` id for `FormLabel` and `TextArea` (`id`, `name` and `for` attributes are set to this value) * `kwargs` **Returns:** Div(cls='space-y-2')(`FormLabel`, `TextArea`) ### LabelRadio Source [code] LabelRadio(label: str | fastcore.xml.FT, lbl_cls='', input_cls='', container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False), cls='flex items-center space-x-2', id='', **kwargs) -> fastcore.xml.FT [/code] > A FormLabel and Radio pair that provides default spacing and links/names them based on id **Params** * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Radio` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is 'flex items-center space-x-2') * `id` id for `FormLabel` and `Radio` (`id`, `name` and `for` attributes are set to this value) * `kwargs` **Returns:** Div(cls='flex items-center space-x-2')(`FormLabel`, `Radio`) ### LabelSelect Source [code] LabelSelect(*option, label: str | fastcore.xml.FT, lbl_cls='', input_cls='', container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False), cls='space-y-2', id='', **kwargs) [/code] > A FormLabel and Select pair that provides default spacing and links/names them based on id (usually UkLabelSelect is a better choice) **Params** * `option` Options for the select dropdown (can use `Options` helper function to create) * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Select` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is 'space-y-2') * `id` id for `FormLabel` and `Select` (`id`, `name` and `for` attributes are set to this value) * `kwargs` ### LabelSelect Source [code] LabelSelect(*option, label: str | fastcore.xml.FT, lbl_cls='', input_cls='', container=functools.partial(<function ft at 0x7ff1c27a67a0>, 'div', void_=False), cls='space-y-2', id='', **kwargs) [/code] > A FormLabel and Select pair that provides default spacing and links/names them based on id (usually UkLabelSelect is a better choice) **Params** * `option` Options for the select dropdown (can use `Options` helper function to create) * `label` FormLabel content (often text) * `lbl_cls` Additional classes for `FormLabel` * `input_cls` Additional classes for `Select` * `container` Container to wrap label and input in (default is Div) * `cls` Classes on container (default is 'space-y-2') * `id` id for `FormLabel` and `Select` (`id`, `name` and `for` attributes are set to this value) * `kwargs` ### Progress Source [code] Progress(*c, cls=(), value='', max='100', **kwargs) -> fastcore.xml.FT [/code] > Creates a progress bar **Params** * `c` Components to put in the progress bar (often nothing) * `cls` Additional classes on the progress bar * `value` Value of the progress bar * `max` Max value of the progress bar (defaults to 100 for percentage) * `kwargs` **Returns:** Progress(..., cls='uk-progress') See Source See Output [code] def ex_progress(): return Progress(value=20, max=100) [/code] ### Radio Source [code] Radio(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Radio with default styling **Params** * `c` contents of Radio tag (often nothing) * `cls` Classes in addition to Radio styling * `kwargs` **Returns:** Input(..., cls='uk-radio', type='radio') See Source See Output Radio [code] def ex_radio(): return Div( Radio(name="radio-group", id="radio1"), LabelRadio(label="Radio", id='radio1',cls='flex items-center space-x-4')) [/code] ### CheckboxX Source [code] CheckboxX(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Checkbox with default styling **Params** * `c` contents of CheckboxX tag (often nothing) * `cls` Classes in addition to CheckboxX styling * `kwargs` **Returns:** Input(..., cls='uk-checkbox', type='checkbox') See Source See Output Checkbox [code] def ex_checkbox(): return Div( CheckboxX(), LabelCheckboxX(label="Checkbox", id='checkbox1')) [/code] ### Range Source [code] Range(*c, value='', label=True, min=None, max=None, step=None, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Range with default styling **Params** * `c` contents of Range tag (often nothing) * `value` * `label` * `min` * `max` * `step` * `cls` Classes in addition to Range styling * `kwargs` **Returns:** Input(..., cls='uk-range', type='range') See Source See Output Basic Range Range with Label Multiple Values Custom Range [code] def ex_range(): return Div( Range(), Range(label='kg', value="25,75", min=20, max=75), LabelRange('Basic Range', value='50', min=0, max=100, step=1), LabelRange('Range with Label', value='75', min=0, max=100, step=5, label_range=True), LabelRange('Multiple Values', value='25,75', min=0, max=100, step=5, label_range=True), LabelRange('Custom Range', value='500', min=0, max=1000, step=100, label_range=True) ) [/code] ### Switch Source [code] Switch(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Switch with default styling **Params** * `c` contents of Switch tag (often nothing) * `cls` Classes in addition to Switch styling * `kwargs` **Returns:** Input(..., cls='uk-toggle-switch uk-toggle-switch-primary min-w-9', type='checkbox') See Source See Output Switch [code] def ex_switch(): return Div( Switch(id="switch"), LabelSwitch(label="Switch", id='switch')) [/code] ### TextArea Source [code] TextArea(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Textarea with default styling **Params** * `c` contents of TextArea tag (often text) * `cls` Classes in addition to TextArea styling * `kwargs` **Returns:** TextArea(..., cls='uk-textarea') See Source See Output TextArea [code] def ex_textarea(): return Div( TextArea(placeholder="Enter multiple lines of text"), LabelTextArea(label="TextArea", id='myid')) [/code] ### Select Source [code] Select(*option, inp_cls=(), cls=('h-10',), cls_custom='button: uk-input-fake dropdown: w-full', id='', name='', placeholder='', searchable=False, select_kwargs=None, **kwargs) [/code] > Creates a select dropdown with uk styling and option for adding a search box **Params** * `option` Options for the select dropdown (can use `Options` helper function to create) * `inp_cls` Additional classes for the select input * `cls` Classes for the outer div (default h-10 for consistent height) * `cls_custom` Classes for the Uk_Select web component * `id` ID for the select input * `name` Name attribute for the select input * `placeholder` Placeholder text for the select input * `searchable` Whether the select should be searchable * `select_kwargs` Additional Arguments passed to Select * `kwargs` See Source See Output Option 1Option 2Option 3 Select Option 1Option 2Option 3 [code] def ex_select(): return Div( Select(map(Option, ["Option 1", "Option 2", "Option 3"])), LabelSelect(map(Option, ["Option 1", "Option 2", "Option 3"]), label="Select", id='myid')) [/code] ### Select Source [code] Select(*option, inp_cls=(), cls=('h-10',), cls_custom='button: uk-input-fake dropdown: w-full', id='', name='', placeholder='', searchable=False, select_kwargs=None, **kwargs) [/code] > Creates a select dropdown with uk styling and option for adding a search box **Params** * `option` Options for the select dropdown (can use `Options` helper function to create) * `inp_cls` Additional classes for the select input * `cls` Classes for the outer div (default h-10 for consistent height) * `cls_custom` Classes for the Uk_Select web component * `id` ID for the select input * `name` Name attribute for the select input * `placeholder` Placeholder text for the select input * `searchable` Whether the select should be searchable * `select_kwargs` Additional Arguments passed to Select * `kwargs` See Source See Output Option 1Option 2Option 3 Select Option 1Option 2Option 3 [code] def ex_Select(): return Div( Select(map(Option, ["Option 1", "Option 2", "Option 3"])), LabelSelect(map(Option, ["Option 1", "Option 2", "Option 3"]), label="Select", id='myid')) [/code] ### Legend Source [code] Legend(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Legend with default styling **Params** * `c` contents of Legend tag (often other tags) * `cls` Classes in addition to Legend styling * `kwargs` **Returns:** Legend(..., cls='uk-legend') ### Fieldset Source [code] Fieldset(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A Fieldset with default styling **Params** * `c` contents of Fieldset tag (often other tags) * `cls` Classes in addition to Fieldset styling * `kwargs` **Returns:** Fieldset(..., cls='uk-fieldset')
https://monsterui.answer.ai/api_ref/docs_forms/md
docs_forms_md
# Icons & Images API Reference # Avatars See Source See Output [code] def ex_dicebear(): return DivLAligned( DiceBearAvatar('Isaac Flath',10,10), DiceBearAvatar('Aaliyah',10,10), DiceBearAvatar('Alyssa',10,10)) [/code] ### DiceBearAvatar Source [code] DiceBearAvatar(seed_name: str, h: int = 20, w: int = 20) [/code] > Creates an Avatar using https://dicebear.com/ **Params** * `seed_name` Seed name (ie 'Isaac Flath') * `h` Height * `w` Width # PlaceHolder Images See Source See Output [code] def ex_picsum(): return Grid(PicSumImg(100,100), PicSumImg(100,100, blur=6),PicSumImg(100,100, grayscale=True)) [/code] ### PicSumImg Source [code] PicSumImg(h: int = 200, w: int = 200, id: int = None, grayscale: bool = False, blur: int = None, **kwargs) -> fastcore.xml.FT [/code] > Creates a placeholder image using https://picsum.photos/ **Params** * `h` Height in pixels * `w` Width in pixels * `id` Optional specific image ID to use * `grayscale` Whether to return grayscale version * `blur` Optional blur amount (1-10) * `kwargs` **Returns:** Img tag with picsum image # Icons Icons use Lucide icons - you can find a full list of icons in their docs. See Source See Output [code] def ex_icon(): return Grid( UkIcon('chevrons-right', height=15, width=15), UkIcon('bug', height=15, width=15), UkIcon('phone-call', height=15, width=15), UkIcon('maximize-2', height=15, width=15), UkIcon('thumbs-up', height=15, width=15),) [/code] ### UkIcon Source [code] UkIcon(icon: str, height: int = None, width: int = None, stroke_width: int = None, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates an icon using lucide icons **Params** * `icon` Icon name from lucide icons * `height` * `width` * `stroke_width` Thickness of lines * `cls` Additional classes on the `Uk_icon` tag * `kwargs` **Returns:** a lucide icon of the specified size See Source See Output [code] def ex_iconlink(): return DivLAligned( UkIconLink('chevrons-right'), UkIconLink('chevrons-right', button=True, cls=ButtonT.primary)) [/code] ### UkIconLink Source [code] UkIconLink(icon: str, height: int = None, width: int = None, stroke_width: int = None, cls=(), button: bool = False, **kwargs) -> fastcore.xml.FT [/code] > Creates an icon link using lucide icons **Params** * `icon` Icon name from lucide icons * `height` * `width` * `stroke_width` Thickness of lines * `cls` Additional classes on the icon * `button` Whether to use a button (defaults to a link) * `kwargs` **Returns:** a lucide icon button or link of the specified size
https://monsterui.answer.ai/api_ref/docs_icons_images/md
docs_icons_images_md
# Layout (Flex and Grid) API Reference This page covers `Grid`s, which are often used for general structure, `Flex` which is often used for layout of components that are not grid based, padding and positioning that can help you make your layout look good, and dividers that can help break up the page ## Grid See Source See Output Column 1 Item 1 Column 1 Item 2 Column 1 Item 3 Column 2 Item 1 Column 2 Item 2 Column 2 Item 3 Column 3 Item 1 Column 3 Item 2 Column 3 Item 3 [code] def ex_grid(): return Grid( Div( P("Column 1 Item 1"), P("Column 1 Item 2"), P("Column 1 Item 3")), Div( P("Column 2 Item 1"), P("Column 2 Item 2"), P("Column 2 Item 3")), Div( P("Column 3 Item 1"), P("Column 3 Item 2"), P("Column 3 Item 3"))) [/code] ### Grid Source [code] Grid(*div, cols_min: int = 1, cols_max: int = 4, cols_sm: int = None, cols_md: int = None, cols_lg: int = None, cols_xl: int = None, cols: int = None, cls='gap-4', **kwargs) -> fastcore.xml.FT [/code] > Creates a responsive grid layout with smart defaults based on content **Params** * `div` `Div` components to put in the grid * `cols_min` Minimum number of columns at any screen size * `cols_max` Maximum number of columns allowed at any screen size * `cols_sm` Number of columns on small screens * `cols_md` Number of columns on medium screens * `cols_lg` Number of columns on large screens * `cols_xl` Number of columns on extra large screens * `cols` Number of columns on all screens * `cls` Additional classes on the grid (tip: `gap` provides spacing for grids) * `kwargs` **Returns:** Responsive grid component #### Practical Grid Example See Source See Output #### Laptop $999 Add to Cart #### Smartphone $599 Add to Cart #### Headphones $199 Add to Cart #### Smartwatch $299 Add to Cart #### Tablet $449 Add to Cart #### Camera $799 Add to Cart [code] def ex_product_grid(): products = [ {"name": "Laptop", "price": "$999", "img": "https://picsum.photos/200/100?random=1"}, {"name": "Smartphone", "price": "$599", "img": "https://picsum.photos/200/100?random=2"}, {"name": "Headphones", "price": "$199", "img": "https://picsum.photos/200/100?random=3"}, {"name": "Smartwatch", "price": "$299", "img": "https://picsum.photos/200/100?random=4"}, {"name": "Tablet", "price": "$449", "img": "https://picsum.photos/200/100?random=5"}, {"name": "Camera", "price": "$799", "img": "https://picsum.photos/200/100?random=6"}, ] product_cards = [ Card( Img(src=p["img"], alt=p["name"], style="width:100%; height:100px; object-fit:cover;"), H4(p["name"], cls="mt-2"), P(p["price"], cls=TextPresets.bold_sm), Button("Add to Cart", cls=(ButtonT.primary, "mt-2")) ) for p in products ] return Grid(*product_cards, cols_lg=3) [/code] ## Flex Play Flex Box Froggy to get an understanding of flex box. ### DivFullySpaced Source [code] DivFullySpaced(*c, cls='w-full', **kwargs) [/code] > Creates a flex div with it's components having as much space between them as possible **Params** * `c` Components * `cls` Classes for outer div (`w-full` makes it use all available width) * `kwargs` See Source See Output LeftCenterRight [code] def ex_fully_spaced_div(): return DivFullySpaced( Button("Left", cls=ButtonT.primary), Button("Center", cls=ButtonT.secondary), Button("Right", cls=ButtonT.destructive) ) [/code] ### DivCentered Source [code] DivCentered(*c, cls='space-y-4', vstack=True, **kwargs) -> fastcore.xml.FT [/code] > Creates a flex div with it's components centered in it **Params** * `c` Components * `cls` Classes for outer div (`space-y-4` provides spacing between components) * `vstack` Whether to stack the components vertically * `kwargs` **Returns:** Div with components centered in it See Source See Output ### Centered Title This content is centered both horizontally and vertically. [code] def ex_centered_div(): return DivCentered( H3("Centered Title"), P("This content is centered both horizontally and vertically.") ) [/code] ### DivLAligned Source [code] DivLAligned(*c, cls='space-x-4', **kwargs) -> fastcore.xml.FT [/code] > Creates a flex div with it's components aligned to the left **Params** * `c` Components * `cls` Classes for outer div * `kwargs` **Returns:** Div with components aligned to the left See Source See Output #### Left Aligned Title Some text that's left-aligned with the title and image. [code] def ex_l_aligned_div(): return DivLAligned( Img(src="https://picsum.photos/100/100?random=1", style="max-width: 100px;"), H4("Left Aligned Title"), P("Some text that's left-aligned with the title and image.") ) [/code] ### DivRAligned Source [code] DivRAligned(*c, cls='space-x-4', **kwargs) -> fastcore.xml.FT [/code] > Creates a flex div with it's components aligned to the right **Params** * `c` Components * `cls` Classes for outer div * `kwargs` **Returns:** Div with components aligned to the right See Source See Output Action Right-aligned text [code] def ex_r_aligned_div(): return DivRAligned( Button("Action", cls=ButtonT.primary), P("Right-aligned text"), Img(src="https://picsum.photos/100/100?random=3", style="max-width: 100px;") ) [/code] ### DivVStacked Source [code] DivVStacked(*c, cls='space-y-4', **kwargs) -> fastcore.xml.FT [/code] > Creates a flex div with it's components stacked vertically **Params** * `c` Components * `cls` Additional classes on the div (tip: `space-y-4` provides spacing between components) * `kwargs` **Returns:** Div with components stacked vertically See Source See Output ## Vertical Stack First paragraph in the stack Second paragraph in the stack Action Button [code] def ex_v_stacked_div(): return DivVStacked( H2("Vertical Stack"), P("First paragraph in the stack"), P("Second paragraph in the stack"), Button("Action Button", cls=ButtonT.secondary) ) [/code] ### DivHStacked Source [code] DivHStacked(*c, cls='space-x-4', **kwargs) -> fastcore.xml.FT [/code] > Creates a flex div with it's components stacked horizontally **Params** * `c` Components * `cls` Additional classes on the div (`space-x-4` provides spacing between components) * `kwargs` **Returns:** Div with components stacked horizontally See Source See Output #### Column 1 Content for column 1 #### Column 2 Content for column 2 #### Column 3 Content for column 3 [code] def ex_h_stacked_div(): return DivHStacked( Div(H4("Column 1"), P("Content for column 1")), Div(H4("Column 2"), P("Content for column 2")), Div(H4("Column 3"), P("Content for column 3")) ) [/code] * * * ### FlexT _Flexbox modifiers using Tailwind CSS_ Option | Value | Option | Value | Option | Value | Option | Value ---|---|---|---|---|---|---|--- block | flex | inline | inline-flex | left | justify-start | center | justify-center right | justify-end | between | justify-between | around | justify-around | stretch | items-stretch top | items-start | middle | items-center | bottom | items-end | row | flex-row row_reverse | flex-row-reverse | column | flex-col | column_reverse | flex-col-reverse | nowrap | flex-nowrap wrap | flex-wrap | wrap_reverse | flex-wrap-reverse | | | |
https://monsterui.answer.ai/api_ref/docs_layout/md
docs_layout_md
# Lists API Reference See Source See Output #### disc List: * Item 1 * Item 2 #### circle List: * Item 1 * Item 2 #### square List: * Item 1 * Item 2 #### decimal List: * Item 1 * Item 2 #### hyphen List: * Item 1 * Item 2 #### bullet List: * Item 1 * Item 2 #### divider List: * Item 1 * Item 2 #### striped List: * Item 1 * Item 2 [code] def ex_lists(): list_options = [(style,str(cls)) for style,cls in ListT.__members__.items()] lists = [Div(H4(f"{style} List:"), Ul(Li("Item 1"), Li("Item 2"), cls=cls)) for style, cls in list_options] return Grid(*lists) [/code] * * * ### ListT _List styles using Tailwind CSS_ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- disc | list-disc list-inside | circle | list-[circle] list-inside | square | list-[square] list-inside decimal | uk-list uk-list-decimal | hyphen | uk-list uk-list-hyphen | bullet | uk-list uk-list-bullet divider | uk-list uk-list-divider | striped | uk-list uk-list-striped | |
https://monsterui.answer.ai/api_ref/docs_lists/md
docs_lists_md
# Loading IndicatorsAPI Reference See Source See Output [code] def ex_loading1(): return Loading() [/code] See Source See Output [code] def ex_loading2(): types = [LoadingT.spinner, LoadingT.dots, LoadingT.ring, LoadingT.ball, LoadingT.bars, LoadingT.infinity] sizes = [LoadingT.xs, LoadingT.sm, LoadingT.md, LoadingT.lg] rows = [Div(*[Loading((t,s)) for s in sizes], cls='flex gap-4') for t in types] return Div(*rows, cls='flex flex-col gap-4') [/code] ### Loading Source [code] Loading(cls=(<LoadingT.bars: 'loading-bars'>, <LoadingT.lg: 'loading-large'>), htmx_indicator=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a loading animation component **Params** * `cls` Classes for indicator (generally `LoadingT` options) * `htmx_indicator` Add htmx-indicator class * `kwargs` **Returns:** Span(cls=...) * * * ### LoadingT __ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- spinner | loading-spinner | dots | loading-dots | ring | loading-ring ball | loading-ball | bars | loading-bars | infinity | loading-infinity xs | loading-xsmall | sm | loading-small | md | loading-medium lg | loading-large | | | |
https://monsterui.answer.ai/api_ref/docs_loading/md
docs_loading_md
# Markdown + automated HTML styling API Reference See Source See Output # Example Markdown * With **bold** and _italics_ * With a link ### And a subheading > This is a blockquote This supports inline latex: $e^{\pi i} + 1 = 0$ as well as block latex thanks to Katex. $$ \frac{1}{2\pi i} \oint_C \frac{f(z)}{z-z_0} dz $$ And even syntax highlighting thanks to Highlight.js! (Just make sure you set `highlightjs=True` in the headers function) [code] def add(a, b): return a + b [/code] [code] def ex_markdown(): md = '''# Example Markdown + With **bold** and *italics* + With a [link](https://github.com) ### And a subheading > This is a blockquote This supports inline latex: $e^{\\pi i} + 1 = 0$ as well as block latex thanks to Katex. $$ \\frac{1}{2\\pi i} \\oint_C \\frac{f(z)}{z-z_0} dz $$ And even syntax highlighting thanks to Highlight.js! (Just make sure you set `highlightjs=True` in the headers function) ```python def add(a, b): return a + b ``` ''' return render_md(md) [/code] You can overwrite the default styling for markdown rendering with your own css classes with `class_map See Source See Output With custom **bold** style > But no extra quote style because class_map overrides all default styled [code] def ex_markdown2(): md = '''With custom **bold** style\n\n > But no extra quote style because class_map overrides all default styled''' return render_md(md, class_map={'b': 'text-red-500'}) [/code] You can modify the default styling for markdown rendering with your own css classes with `class_map_mods See Source See Output With custom **bold** style > But default quote style because class_map_mods replaces sepecified styles and leaves the rest as default [code] def ex_markdown3(): md = '''With custom **bold** style\n\n > But default quote style because class_map_mods replaces sepecified styles and leaves the rest as default''' return render_md(md, class_map_mods={'b': 'text-red-500'}) [/code] This uses the `apply_classes` function, which can be used to apply classes to html strings. This is useful for applying styles to any html you get from an external source. ### apply_classes Source [code] apply_classes(html_str: str, class_map=None, class_map_mods=None) -> str [/code] > Apply classes to html string **Params** * `html_str` Html string * `class_map` Class map * `class_map_mods` Class map that will modify the class map map (useful for small changes to a base class map) **Returns:** Html string with classes applied See Source See Output <div><h1 class="uk-h1 text-4xl font-bold mt-12 mb-6">Hello, World!</h1><p class="text-lg leading-relaxed mb-6">This is a paragraph</p></div> [code] def ex_applyclasses(): return apply_classes('<h1>Hello, World!</h1><p>This is a paragraph</p>') [/code]
https://monsterui.answer.ai/api_ref/docs_markdown_HTMLstyling/md
docs_markdown_HTMLstyling_md
# Modals API Reference ### Example Modal This is a subtitle See Source See Output Open Modal ## Simple Test Modal With some somewhat brief content to show that it works! Close [code] def ex_modal(): return Div( Button("Open Modal",data_uk_toggle="target: #my-modal" ), Modal(ModalTitle("Simple Test Modal"), P("With some somewhat brief content to show that it works!", cls=TextPresets.muted_sm), footer=ModalCloseButton("Close", cls=ButtonT.primary),id='my-modal')) [/code] ### Modal Source [code] Modal(*c, header=None, footer=None, cls=(), dialog_cls=(), header_cls='p-6', body_cls='space-y-6', footer_cls=(), id='', open=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a modal with the appropriate classes to put the boilerplate in the appropriate places for you **Params** * `c` Components to put in the `ModalBody` (often forms, sign in buttons, images, etc.) * `header` Components that go in the `ModalHeader` (often a `ModalTitle`) * `footer` Components that go in the `ModalFooter` (often a `ModalCloseButton`) * `cls` Additional classes on the outermost `ModalContainer` * `dialog_cls` Additional classes on the `ModalDialog` * `header_cls` Additional classes on the `ModalHeader` * `body_cls` Additional classes on the `ModalBody` * `footer_cls` Additional classes on the `ModalFooter` * `id` id for the outermost container * `open` Whether the modal is open (typically used for HTMX controlled modals) * `kwargs` **Returns:** Fully styled modal FT Component ### ModalCloseButton Source [code] ModalCloseButton(*c, cls=(), htmx=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a button that closes a modal with js **Params** * `c` Components to put in the button (often text and/or an icon) * `cls` Additional classes on the button * `htmx` Whether to use HTMX to close the modal (must add hx_get to a route that closes the modal) * `kwargs` **Returns:** Button(..., cls='uk-modal-close') + `hx_target` and `hx_swap` if htmx is True The remainder of the Modal functions below are used internally by the `Modal` function for you. You shouldn't need to use them unless you're doing something really special. ### ModalTitle Source [code] ModalTitle(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal title **Params** * `c` Components to put in the `ModalTitle` (often text) * `cls` Additional classes on the `ModalTitle` * `kwargs` **Returns:** H2(..., cls='uk-modal-title') ### ModalFooter Source [code] ModalFooter(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal footer **Params** * `c` Components to put in the `ModalFooter` (often buttons) * `cls` Additional classes on the `ModalFooter` * `kwargs` **Returns:** Div(..., cls='uk-modal-footer') ### ModalBody Source [code] ModalBody(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal body **Params** * `c` Components to put in the `ModalBody` (often forms, sign in buttons, images, etc.) * `cls` Additional classes on the `ModalBody` * `kwargs` **Returns:** Div(..., cls='uk-modal-body') ### ModalHeader Source [code] ModalHeader(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal header **Params** * `c` Components to put in the `ModalHeader` * `cls` Additional classes on the `ModalHeader` * `kwargs` **Returns:** Div(..., cls='uk-modal-header') ### ModalDialog Source [code] ModalDialog(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal dialog **Params** * `c` Components to put in the `ModalDialog` (often `ModalBody`, `ModalHeader`, etc) * `cls` Additional classes on the `ModalDialog` * `kwargs` **Returns:** Div(..., cls='uk-modal-dialog') ### ModalContainer Source [code] ModalContainer(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a modal container that components go in **Params** * `c` Components to put in the modal (often `ModalDialog`) * `cls` Additional classes on the `ModalContainer` * `kwargs` **Returns:** Div(..., cls='uk-modal uk-modal-container')
https://monsterui.answer.ai/api_ref/docs_modals/md
docs_modals_md
# Navigation (Nav, NavBar, Tabs, etc.) API Reference # Nav, NavBar, DowDownNav, and Tab examples * * * ## Nav See Source See Output * Option 1 * Option 2 * Option 3 [code] def ex_nav1(): mbrs1 = [Li(A('Option 1'), cls='uk-active'), Li(A('Option 2')), Li(A('Option 3'))] return NavContainer(*mbrs1) [/code] See Source See Output * NavHeaderLi * Option 1 * Option 2 * Option 3 * Subtitle Ex NavSubtitle text to be shown * * Parent Name * Child 1 * Child 2 * Child 3 [code] def ex_nav2(): mbrs1 = [Li(A('Option 1'), cls='uk-active'), Li(A('Option 2')), Li(A('Option 3'))] mbrs2 = [Li(A('Child 1')), Li(A('Child 2')),Li(A('Child 3'))] return NavContainer( NavHeaderLi("NavHeaderLi"), *mbrs1, Li(A(href='')(Div("Subtitle Ex",NavSubtitle("NavSubtitle text to be shown")))), NavDividerLi(), NavParentLi( A('Parent Name'), NavContainer(*mbrs2,parent=False), ), ) [/code] ## Navbars Fully responsive simple navbar using the high level API. This will collapse to a hamburger menu on mobile devices. See the Scrollspy example for a more complex navbar example. See Source See Output ### My Blog Page1Page2Page3 Page1Page2Page3 [code] def ex_navbar1(): return NavBar(A("Page1",href='/rt1'), A("Page2",href='/rt2'), A("Page3",href='/rt3'), brand=H3('My Blog')) [/code] See Source See Output Page1Page2 Page1Page2 [code] def ex_navbar2(): return NavBar( A(Input(placeholder='search')), A(UkIcon("rocket")), A('Page1',href='/rt1'), A("Page2", href='/rt3'), brand=DivLAligned(Img(src='/api_reference/logo.svg'),UkIcon('rocket',height=30,width=30))) [/code] ## Drop Down Navs See Source See Output Open DropDown * Item 1 * Item 2 [code] def ex_navdrop(): return Div( Button("Open DropDown"), DropDownNavContainer(Li(A("Item 1",href=''),Li(A("Item 2",href=''))))) [/code] ## Tabs See Source See Output * Active * Item * Item * Disabled [code] def ex_tabs2(): return Container( TabContainer( Li(A("Active",href='javascript:void(0);', cls='uk-active')), Li(A("Item",href='javascript:void(0);')), Li(A("Item",href='javascript:void(0);')), Li(A("Disabled", cls='uk-disabled')))) [/code] A tabs can use any method of navigation (htmx, or href). However, often these are use in conjunction with switchers do to this client side See Source See Output * Active * Item * Item * Disabled * # Tab 1 * # Tab 2 * # Tab 3 [code] def ex_tabs1(): return Container( TabContainer( Li(A("Active",href='#', cls='uk-active')), Li(A("Item",href='#')), Li(A("Item",href='#')), Li(A("Disabled",href='#', cls='uk-disabled')), uk_switcher='connect: #component-nav; animation: uk-animation-fade', alt=True), Ul(id="component-nav", cls="uk-switcher")( Li(H1("Tab 1")), Li(H1("Tab 2")), Li(H1("Tab 3")))) [/code] # API Docs ### NavBar Source [code] NavBar(*c, brand=h3(('Title',),{'class': 'uk-h3 '}), right_cls='items-center space-x-4', mobile_cls='space-y-4', sticky: bool = False, uk_scrollspy_nav: bool | str = False, cls='p-4', scrollspy_cls=<ScrollspyT.underline: 'navbar-underline'>, menu_id=None) -> fastcore.xml.FT [/code] > Creates a responsive navigation bar with mobile menu support **Params** * `c` Component for right side of navbar (Often A tag links) * `brand` Brand/logo component for left side * `right_cls` Spacing for desktop links * `mobile_cls` Spacing for mobile links * `sticky` Whether to stick to the top of the page while scrolling * `uk_scrollspy_nav` Whether to use scrollspy for navigation * `cls` Classes for navbar * `scrollspy_cls` Scrollspy class (usually ScrollspyT.*) * `menu_id` ID for menu container (used for mobile toggle) **Returns:** Responsive NavBar ### TabContainer Source [code] TabContainer(*li, cls='', alt=False, **kwargs) -> fastcore.xml.FT [/code] > A TabContainer where children will be different tabs **Params** * `li` Components * `cls` Additional classes on the `Ul` * `alt` Whether to use an alternative tab style * `kwargs` **Returns:** Tab container ### NavContainer Source [code] NavContainer(*li, cls=<NavT.primary: 'uk-nav-primary'>, parent=True, uk_nav=False, uk_scrollspy_nav=False, sticky=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation container (useful for creating a sidebar navigation). A Nav is a list (NavBar is something different) **Params** * `li` List items are navigation elements (Special `Li` such as `NavParentLi`, `NavDividerLi`, `NavHeaderLi`, `NavSubtitle`, `NavCloseLi` can also be used) * `cls` Additional classes on the nav * `parent` Whether this nav is a _parent_ or _sub_ nav * `uk_nav` True for default collapsible behavior, see frankenui docs for more advanced options * `uk_scrollspy_nav` Activates scrollspy linking each item `A` tags `href` to content's `id` attribute * `sticky` Whether to stick to the top of the page while scrolling * `kwargs` **Returns:** FT Component that is a list of `Li` styled for a sidebar navigation menu * * * ### NavT __ Option | Value | Option | Value ---|---|---|--- default | uk-nav-default | primary | uk-nav-primary secondary | uk-nav-secondary | | ### NavCloseLi Source [code] NavCloseLi(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation list item with a close button **Params** * `c` Components * `cls` Additional classes on the li * `kwargs` **Returns:** Navigation list item with a close button ### NavSubtitle Source [code] NavSubtitle(*c, cls=<TextPresets.muted_sm: 'text-gray-500 dark:text-gray-200 text-sm'>, **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation subtitle **Params** * `c` Components * `cls` Additional classes on the div * `kwargs` **Returns:** Navigation subtitle ### NavHeaderLi Source [code] NavHeaderLi(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation list item with a header **Params** * `c` Components * `cls` Additional classes on the li * `kwargs` **Returns:** Navigation list item with a header ### NavDividerLi Source [code] NavDividerLi(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation list item with a divider **Params** * `c` Components * `cls` Additional classes on the li * `kwargs` **Returns:** Navigation list item with a divider ### NavParentLi Source [code] NavParentLi(*nav_container, cls=(), **kwargs) -> fastcore.xml.FT [/code] > Creates a navigation list item with a parent nav for nesting **Params** * `nav_container` `NavContainer` container for a nested nav with `parent=False`) * `cls` Additional classes on the li * `kwargs` **Returns:** Navigation list item ### DropDownNavContainer Source [code] DropDownNavContainer(*li, cls=<NavT.primary: 'uk-nav-primary'>, parent=True, uk_nav=False, uk_dropdown=True, **kwargs) -> fastcore.xml.FT [/code] > A Nav that is part of a DropDown **Params** * `li` Components * `cls` Additional classes on the nav * `parent` Whether to use a parent nav * `uk_nav` True for default collapsible behavior, see https://franken-ui.dev/docs/nav#component-options for more advanced options * `uk_dropdown` Whether to use a dropdown * `kwargs` **Returns:** DropDown nav container
https://monsterui.answer.ai/api_ref/docs_navigation/md
docs_navigation_md
# Alerts & Toasts API Reference ### Alerts The simplest alert is a div wrapped with a span: See Source See Output This is a plain alert [code] def ex_alerts1(): return Alert("This is a plain alert") [/code] Alert colors are defined by the alert styles: See Source See Output Your purchase has been confirmed! [code] def ex_alerts2(): return Alert("Your purchase has been confirmed!", cls=AlertT.success) [/code] It often looks nice to use icons in alerts: See Source See Output Please enter a valid email. [code] def ex_alerts3(): return Alert( DivLAligned(UkIcon('triangle-alert'), P("Please enter a valid email.")), cls=AlertT.error) [/code] ### Alert Source [code] Alert(*c, cls='', **kwargs) -> fastcore.xml.FT [/code] > Alert informs users about important events. **Params** * `c` Content for Alert (often text and/or icon) * `cls` Class for the alert (often an `AlertT` option) * `kwargs` **Returns:** Div(Span(...), cls='alert', role='alert') * * * ### AlertT _Alert styles from DaisyUI_ Option | Value | Option | Value ---|---|---|--- info | alert-info | success | alert-success warning | alert-warning | error | alert-error * * * ### Toasts To define a toast with a particular location, add horizontal or vertical toast type classes: See Source See Output First Example Toast [code] def ex_toasts1(): return Toast("First Example Toast", cls=(ToastHT.start, ToastVT.bottom)) [/code] To define toast colors, set the class of the alert wrapped by the toast: See Source See Output Second Example Toast [code] def ex_toasts2(): return Toast("Second Example Toast", alert_cls=AlertT.info) [/code] ### Toast Source [code] Toast(*c, cls='', alert_cls='', **kwargs) -> fastcore.xml.FT [/code] > Toasts are stacked announcements, positioned on the corner of page. **Params** * `c` Content for toast (often test) * `cls` Classes for toast (often `ToastHT` and `ToastVT` options) * `alert_cls` classes for altert (often `AlertT` options) * `kwargs` **Returns:** Div(Alert(...), cls='toast') * * * ### ToastHT _Horizontal position for Toast_ Option | Value | Option | Value ---|---|---|--- start | toast-start | center | toast-center end | toast-end | | * * * ### ToastVT _Vertical position for Toast_ Option | Value | Option | Value ---|---|---|--- top | toast-top | middle | toast-middle bottom | toast-bottom | |
https://monsterui.answer.ai/api_ref/docs_notifications/md
docs_notifications_md
# Carousel Sliders API Reference Here is a simple example of a slider: See Source See Output [code] def ex_sliders_1(): return Slider(*[Img(src=f'https://picsum.photos/200/200?random={i}') for i in range(10)]) [/code] Here is a slider with cards: See Source See Output ### Card 0 Card 0 content ### Card 1 Card 1 content ### Card 2 Card 2 content ### Card 3 Card 3 content ### Card 4 Card 4 content ### Card 5 Card 5 content ### Card 6 Card 6 content ### Card 7 Card 7 content ### Card 8 Card 8 content ### Card 9 Card 9 content [code] def ex_sliders_2(): def _card(i): return Card(H3(f'Card {i}'), P(f'Card {i} content')) return Slider(*[_card(i) for i in range(10)]) [/code] Here is a slider with cards and autoplay: See Source See Output ### Card 0 Card 0 content ### Card 1 Card 1 content ### Card 2 Card 2 content ### Card 3 Card 3 content ### Card 4 Card 4 content ### Card 5 Card 5 content ### Card 6 Card 6 content ### Card 7 Card 7 content ### Card 8 Card 8 content ### Card 9 Card 9 content [code] def ex_sliders_3(): def _card(i): return Card(H3(f'Card {i}'), P(f'Card {i} content')) return Slider(*[_card(i) for i in range(10)], items_cls='gap-10', uk_slider='autoplay: true; autoplay-interval: 1000') [/code] Typically you want to use the `Slider` component, but if you need more control you can use the `SliderContainer`, `SliderItems`, and `SliderNav` components. ### Slider Source [code] Slider(*c, cls='', items_cls='gap-4', nav=True, nav_cls='', **kwargs) -> fastcore.xml.FT [/code] > Creates a slider with optional navigation arrows **Params** * `c` Items to show in slider * `cls` Classes for slider container * `items_cls` Classes for items container * `nav` Whether to show navigation arrows * `nav_cls` Classes for navigation arrows * `kwargs` **Returns:** SliderContainer(SliderItems(..., cls='gap-4'), SliderNav?) ### SliderContainer Source [code] SliderContainer(*c, cls='', uk_slider=True, **kwargs) -> fastcore.xml.FT [/code] > Creates a slider container **Params** * `c` Components * `cls` Additional classes on the container * `uk_slider` See FrankenUI Slider docs for more options * `kwargs` **Returns:** Div(..., cls='relative', uk_slider=True, ...) ### SliderItems Source [code] SliderItems(*c, cls='', **kwargs) -> fastcore.xml.FT [/code] > Creates a slider items container **Params** * `c` Components * `cls` Additional classes for the items * `kwargs` **Returns:** Div(..., cls='uk-slider-items uk-grid', ...) ### SliderNav Source [code] SliderNav(cls='uk-position-small uk-hidden-hover', prev_cls='absolute left-0 top-1/2 -translate-y-1/2', next_cls='absolute right-0 top-1/2 -translate-y-1/2', **kwargs) -> fastcore.xml.FT [/code] > Navigation arrows for Slider component **Params** * `cls` Additional classes for the navigation * `prev_cls` Additional classes for the previous navigation * `next_cls` Additional classes for the next navigation * `kwargs` **Returns:** Left and right navigation arrows for Slider component
https://monsterui.answer.ai/api_ref/docs_sliders/md
docs_sliders_md
# Steps API Reference See Source See Output * Account Created * Profile Setup * Verification [code] def ex_steps2(): return Steps( LiStep("Account Created", cls=StepT.primary), LiStep("Profile Setup", cls=StepT.neutral), LiStep("Verification", cls=StepT.neutral), cls="w-full") [/code] See Source See Output * Project Planning * Design Phase * Development * Testing * Deployment [code] def ex_steps3(): return Steps( LiStep("Project Planning", cls=StepT.success, data_content="πŸ“"), LiStep("Design Phase", cls=StepT.success, data_content="πŸ’‘"), LiStep("Development", cls=StepT.primary, data_content="πŸ› οΈ"), LiStep("Testing", cls=StepT.neutral, data_content="πŸ”Ž"), LiStep("Deployment", cls=StepT.neutral, data_content="πŸš€"), cls=(StepsT.vertical, "min-h-[400px]")) [/code] # API Docs ### Steps Source [code] Steps(*li, cls='', **kwargs) -> fastcore.xml.FT [/code] > Creates a steps container **Params** * `li` Each `Li` represent a step (generally use `LiStep`) * `cls` class for Steps (generally a `StepsT` option) * `kwargs` **Returns:** Ul(..., cls='steps') * * * ### StepsT _Options for Steps_ Option | Value | Option | Value ---|---|---|--- vertical | steps-vertical | horizonal | steps-horizonal ### LiStep Source [code] LiStep(*c, cls='', data_content=None, **kwargs) -> fastcore.xml.FT [/code] > Creates a step list item **Params** * `c` Description for Step that goes next to bubble (often text) * `cls` Additional step classes (generally a `StepT` component) * `data_content` Content for inside bubble (defaults to number, often an emoji) * `kwargs` **Returns:** Li(..., cls='step') * * * ### StepT _Step styles for LiStep_ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- primary | step-primary | secondary | step-secondary | accent | step-accent info | step-info | success | step-success | warning | step-warning error | step-error | neutral | step-neutral | |
https://monsterui.answer.ai/api_ref/docs_steps/md
docs_steps_md
# Tables API Reference See Source See Output Name | Age | City ---|---|--- Alice | 25 | New York Bob | 30 | San Francisco Charlie | 35 | London Total | 90 [code] def ex_tables0(): return Table( Thead(Tr(Th('Name'), Th('Age'), Th('City'))), Tbody(Tr(Td('Alice'), Td('25'), Td('New York')), Tr(Td('Bob'), Td('30'), Td('San Francisco')), Tr(Td('Charlie'), Td('35'), Td('London'))), Tfoot(Tr(Td('Total'), Td('90')))) [/code] See Source See Output Name | Age | City ---|---|--- Alice | 25 | New York Bob | 30 | San Francisco Charlie | 35 | London Total | 90 [code] def ex_tables1(): header = ['Name', 'Age', 'City'] body = [['Alice', '25', 'New York'], ['Bob', '30', 'San Francisco'], ['Charlie', '35', 'London']] footer = ['Total', '90'] return TableFromLists(header, body, footer) [/code] See Source See Output NAME | AGE | CITY ---|---|--- Alice | 30 years | New York Bob | 25 years | London [code] def ex_tables2(): def body_render(k, v): match k.lower(): case 'name': return Td(v, cls='font-bold') case 'age': return Td(f"{v} years") case _: return Td(v) header_data = ['Name', 'Age', 'City'] body_data =[{'Name': 'Alice', 'Age': 30, 'City': 'New York'}, {'Name': 'Bob', 'Age': 25, 'City': 'London'}] return TableFromDicts(header_data, body_data, header_cell_render=lambda v: Th(v.upper()), body_cell_render=body_render) [/code] ### Table Source [code] Table(*c, cls=(<TableT.middle: 'uk-table-middle'>, <TableT.divider: 'uk-table-divider'>, <TableT.hover: 'uk-table-hover'>, <TableT.sm: 'uk-table-sm'>), **kwargs) -> fastcore.xml.FT [/code] > Creates a table **Params** * `c` Components (typically `Thead`, `Tbody`, `Tfoot`) * `cls` Additional classes on the table * `kwargs` **Returns:** Table component ### TableFromLists Source [code] TableFromLists(header_data: Sequence, body_data: Sequence[Sequence], footer_data=None, header_cell_render=<function Th at 0x7ff16c639800>, body_cell_render=<function Td at 0x7ff16c639760>, footer_cell_render=<function Td at 0x7ff16c639760>, cls=(<TableT.middle: 'uk-table-middle'>, <TableT.divider: 'uk-table-divider'>, <TableT.hover: 'uk-table-hover'>, <TableT.sm: 'uk-table-sm'>), sortable=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a Table from a list of header data and a list of lists of body data **Params** * `header_data` List of header data * `body_data` List of lists of body data * `footer_data` List of footer data * `header_cell_render` Function(content) -> FT that renders header cells * `body_cell_render` Function(key, content) -> FT that renders body cells * `footer_cell_render` Function(key, content) -> FT that renders footer cells * `cls` Additional classes on the table * `sortable` Whether to use sortable table * `kwargs` **Returns:** Table from lists ### TableFromDicts Source [code] TableFromDicts(header_data: Sequence, body_data: Sequence[dict], footer_data=None, header_cell_render=<function Th at 0x7ff16c639800>, body_cell_render=<function <lambda> at 0x7ff16c639940>, footer_cell_render=<function <lambda> at 0x7ff16c6399e0>, cls=(<TableT.middle: 'uk-table-middle'>, <TableT.divider: 'uk-table-divider'>, <TableT.hover: 'uk-table-hover'>, <TableT.sm: 'uk-table-sm'>), sortable=False, **kwargs) -> fastcore.xml.FT [/code] > Creates a Table from a list of header data and a list of dicts of body data **Params** * `header_data` List of header data * `body_data` List of dicts of body data * `footer_data` List of footer data * `header_cell_render` Function(content) -> FT that renders header cells * `body_cell_render` Function(key, content) -> FT that renders body cells * `footer_cell_render` Function(key, content) -> FT that renders footer cells * `cls` Additional classes on the table * `sortable` Whether to use sortable table * `kwargs` **Returns:** Styled Table * * * ### TableT __ Option | Value | Option | Value | Option | Value ---|---|---|---|---|--- divider | uk-table-divider | striped | uk-table-striped | hover | uk-table-hover sm | uk-table-sm | lg | uk-table-lg | justify | uk-table-justify middle | uk-table-middle | responsive | uk-table-responsive | | ### Tbody Source [code] Tbody(*rows, cls=(), sortable=False, **kwargs) [/code] > **Params** * `rows` * `cls` * `sortable` * `kwargs` ### Th Source [code] Th(*c, cls=(), shrink=False, expand=False, small=False) [/code] > **Params** * `c` Components that go in the cell * `cls` Additional classes on the cell container * `shrink` Whether to shrink the cell * `expand` Whether to expand the cell * `small` Whether to use a small table **Returns:** Table cell ### Td Source [code] Td(*c, cls=(), shrink=False, expand=False, small=False) [/code] > **Params** * `c` Components that go in the cell * `cls` Additional classes on the cell container * `shrink` Whether to shrink the cell * `expand` Whether to expand the cell * `small` Whether to use a small table **Returns:** Table cell
https://monsterui.answer.ai/api_ref/docs_tables/md
docs_tables_md
# Theme and Headers API Reference To get headers with a default theme use `hdrs=Theme.<color>.headers()`. For example for the blue theme you would use `hdrs=Theme.blue.headers()`. The theme integrated together different frameworks and allows tailwind, FrankenUI, HighlighJS, and DaisyUI components to work well together. Tailwind, FrankenUI and DaisyUI are imported by default. You must use DaisyUI headers to use anything in the `daisy` module, and FrankenUI headers to use anything in the `franken` module. HighlightJS is not added by default, but you can add it by setting `highlightjs=True` in the headers function. The `render_md` function will use HighlightJS for code blocks. Theme options are: Theme.slate Theme.stone Theme.gray Theme.neutral Theme.red Theme.rose Theme.orange Theme.green Theme.blue Theme.yellow Theme.violet Theme.zinc ### Theme Picker See Source See Output ZincSlateStoneGrayNeutralRedRoseOrangeGreenBlueYellowVioletNoneSmallMediumLargeNoneSmallMediumLargeSmallDefaultLightDark [code] def ex_theme_switcher(): return ThemePicker() [/code] ### ThemePicker Source [code] ThemePicker(color=True, radii=True, shadows=True, font=True, mode=True, cls='p-4') [/code] > Theme picker component with configurable sections **Params** * `color` * `radii` * `shadows` * `font` * `mode` * `cls` Themes are controlled with `bg-background text-foreground` classes on the `Body` tag. `fast_app` and `FastHTML` will do this for you automatically so you typically do not have to do anything ### fast_app Source [code] fast_app(*args, pico=False, db_file: Optional[str] = None, render: Optional[<built-in function callable>] = None, hdrs: Optional[tuple] = None, ftrs: Optional[tuple] = None, tbls: Optional[dict] = None, before: Union[tuple, NoneType, fasthtml.core.Beforeware] = None, middleware: Optional[tuple] = None, live: bool = False, debug: bool = False, routes: Optional[tuple] = None, exception_handlers: Optional[dict] = None, on_startup: Optional[<built-in function callable>] = None, on_shutdown: Optional[<built-in function callable>] = None, lifespan: Optional[<built-in function callable>] = None, default_hdrs=True, surreal: Optional[bool] = True, htmx: Optional[bool] = True, exts: Union[list, str, NoneType] = None, secret_key: Optional[str] = None, key_fname: str = '.sesskey', session_cookie: str = 'session_', max_age: int = 31536000, sess_path: str = '/', same_site: str = 'lax', sess_https_only: bool = False, sess_domain: Optional[str] = None, htmlkw: Optional[dict] = None, bodykw: Optional[dict] = None, reload_attempts: Optional[int] = 1, reload_interval: Optional[int] = 1000, static_path: str = '.', body_wrap: <built-in function callable> = <function noop_body at 0x7ff1c1e4db20>, nb_hdrs: bool = False) [/code] > Create a FastHTML or FastHTMLWithLiveReload app with `bg-background text-foreground` to bodykw for frankenui themes **Params** * `db_file` Database file name, if needed * `render` Function used to render default database class * `hdrs` Additional FT elements to add to * `ftrs` Additional FT elements to add to end of * `tbls` Experimental mapping from DB table names to dict table definitions * `before` Functions to call prior to calling handler * `middleware` Standard Starlette middleware * `live` Enable live reloading * `debug` Passed to Starlette, indicating if debug tracebacks should be returned on errors * `routes` Passed to Starlette * `exception_handlers` Passed to Starlette * `on_startup` Passed to Starlette * `on_shutdown` Passed to Starlette * `lifespan` Passed to Starlette * `default_hdrs` Include default FastHTML headers such as HTMX script? * `pico` Include PicoCSS header? * `surreal` Include surreal.js/scope headers? * `htmx` Include HTMX header? * `exts` HTMX extension names to include * `secret_key` Signing key for sessions * `key_fname` Session cookie signing key file name * `session_cookie` Session cookie name * `max_age` Session cookie expiry time * `sess_path` Session cookie path * `same_site` Session cookie same site policy * `sess_https_only` Session cookie HTTPS only? * `sess_domain` Session cookie domain * `htmlkw` Attrs to add to the HTML tag * `bodykw` Attrs to add to the Body tag * `reload_attempts` Number of reload attempts when live reloading * `reload_interval` Time between reload attempts in ms * `static_path` Where the static file route points to, defaults to root dir * `body_wrap` FT wrapper for body contents * `nb_hdrs` If in notebook include headers inject headers in notebook DOM? * `args` ### FastHTML Source [code] FastHTML(*args, pico=False, debug=False, routes=None, middleware=None, title: str = 'FastHTML page', exception_handlers=None, on_startup=None, on_shutdown=None, lifespan=None, hdrs=None, ftrs=None, exts=None, before=None, after=None, surreal=True, htmx=True, default_hdrs=True, sess_cls=<class 'starlette.middleware.sessions.SessionMiddleware'>, secret_key=None, session_cookie='session_', max_age=31536000, sess_path='/', same_site='lax', sess_https_only=False, sess_domain=None, key_fname='.sesskey', body_wrap=<function noop_body at 0x7ff1c1e4db20>, htmlkw=None, nb_hdrs=False) [/code] > Create a FastHTML app and adds `bg-background text-foreground` to bodykw for frankenui themes **Params** * `debug` * `routes` * `middleware` * `title` * `exception_handlers` * `on_startup` * `on_shutdown` * `lifespan` * `hdrs` * `ftrs` * `exts` * `before` * `after` * `surreal` * `htmx` * `default_hdrs` * `sess_cls` * `secret_key` * `session_cookie` * `max_age` * `sess_path` * `same_site` * `sess_https_only` * `sess_domain` * `key_fname` * `body_wrap` * `htmlkw` * `nb_hdrs` * `args` * `pico`
https://monsterui.answer.ai/api_ref/docs_theme_headers/md
docs_theme_headers_md
# Typography API Reference Ready to go semantic options that cover most of what you need based on the HTML spec See Source See Output Titled # Titled # Level 1 Heading (H1) ## Level 2 Heading (H2) ### Level 3 Heading (H3) #### Level 4 Heading (H4) ##### Level 5 Heading (H5) ###### Level 6 Heading (H6) [code] def ex_headings(): return Div( Titled("Titled"), H1("Level 1 Heading (H1)"), H2("Level 2 Heading (H2)"), H3("Level 3 Heading (H3)"), H4("Level 4 Heading (H4)"), H5("Level 5 Heading (H5)"), H6("Level 6 Heading (H6)"), ) [/code] See Source See Output ## Semantic HTML Elements Demo Here's an example of _emphasized (Em)_ and **strong (Strong)** text. Some _italic text (I)_ and smaller text (Small) in a paragraph. You can highlight (Mark) text, show ~~deleted (Del)~~ and inserted (Ins) content. Chemical formulas use subscripts (Sub) and superscripts (Sup) like H2O. > The only way to do great work is to love what you do. > > Steve Jobs (Cite) As Shakespeare wrote, "All the world's a stage (Q)". Posted on 2024-01-29 Mozilla Foundation (Address) 331 E Evelyn Ave (Address) Mountain View, CA 94041 (Address) USA (Address) HTML (Dfn) (HyperText Markup Language (Abbr)) is the standard markup language for documents designed to be displayed in a web browser. Press `Ctrl (Kbd)` \+ `C (Kbd)` to copy. The command returned: Hello, World! (Samp) Let x (Var) be the variable in the equation. Figure 1: An example image with caption (Caption)Click to show more information (Summary) This is the detailed content that is initially hidden (P) 123 (Data) is a number, and here's a Meter showing progress: Temperature: (with low/high/optimum values) €42.00 \- price example with semantic value Form calculation result: The sum is 42 (Output) ### Blog Post Title (H3) By John Doe β€’ 5 min read (Small) Article content here... This text has _proper name annotation (U)_ and this is ~~outdated information (S)~~ that's been superseded. [code] def ex_semantic_elements(): return Div( H2("Semantic HTML Elements Demo"), # Text formatting examples P("Here's an example of ", Em("emphasized (Em)"), " and ", Strong("strong (Strong)"), " text."), P("Some ", I("italic text (I)"), " and ", Small("smaller text (Small)"), " in a paragraph."), P("You can ", Mark("highlight (Mark)"), " text, show ", Del("deleted (Del)"), " and ", Ins("inserted (Ins)"), " content."), P("Chemical formulas use ", Sub("subscripts (Sub)"), " and ", Sup("superscripts (Sup)"), " like H", Sub("2"), "O."), # Quote examples Blockquote( P("The only way to do great work is to love what you do."), Cite("Steve Jobs (Cite)")), P("As Shakespeare wrote, ", Q("All the world's a stage (Q)"), "."), # Time and Address P("Posted on ", Time("2024-01-29", datetime="2024-01-29")), Address( "Mozilla Foundation (Address)", Br(), "331 E Evelyn Ave (Address)", Br(), "Mountain View, CA 94041 (Address)", Br(), "USA (Address)"), # Technical and definition examples P( Dfn("HTML (Dfn)"), " (", Abbr("HyperText Markup Language (Abbr)", title="HyperText Markup Language"), ") is the standard markup language for documents designed to be displayed in a web browser."), P("Press ", Kbd("Ctrl (Kbd)"), " + ", Kbd("C (Kbd)"), " to copy."), P("The command returned: ", Samp("Hello, World! (Samp)")), P("Let ", Var("x (Var)"), " be the variable in the equation."), # Figure with caption Figure( PicSumImg(), Caption("Figure 1: An example image with caption (Caption)")), # Interactive elements Details( Summary("Click to show more information (Summary)"), P("This is the detailed content that is initially hidden (P)")), # Data representation P( Data("123 (Data)", value="123"), " is a number, and here's a Meter showing progress: ", Meter(value=0.6, min=0, max=1)), P( "Temperature: ", Meter(value=-1, min=-10, max=40, low=0, high=30, optimum=21), " (with low/high/optimum values)"), P( Data("€42.00", value="42"), " - price example with semantic value"), # Output example P("Form calculation result: ", Output("The sum is 42 (Output)", form="calc-form", for_="num1 num2")), # Meta information example Section( H3("Blog Post Title (H3)"), Small("By John Doe β€’ 5 min read (Small)"), P("Article content here...")), # Text decoration examples P("This text has ",U("proper name annotation (U)"), " and this is ",S("outdated information (S)"), " that's been superseded."), cls='space-y-4' ) [/code] See Source See Output `This is a CodeSpan element` > This is a blockquote element [code] #This is a CodeBlock element def add(a,b): return a+b [/code] [code] def ex_other(): return Div( CodeSpan("This is a CodeSpan element"), Blockquote("This is a blockquote element"), CodeBlock("#This is a CodeBlock element\n\ndef add(a,b): return a+b")) [/code] Styling text is possibly the most common style thing to do, so we have a couple of helpers for discoverability inside python. `TextPresets` is intended to be combinations are are widely applicable and used often, where `TextT` is intended to be more flexible options for you to combine together yourself. ##### TextPresets.* See Source See Output This is muted_sm text This is muted_lg text This is bold_sm text This is bold_lg text This is md_weight_sm text This is md_weight_muted text [code] def ex_textpresets(): return Grid(*[Div(P(f"This is {preset.name} text", cls=preset.value)) for preset in TextPresets]) [/code] ##### TextT.* See Source See Output This is paragraph text This is lead text This is meta text This is gray text This is italic text This is xs text This is sm text This is lg text This is xl text This is light text This is normal text This is medium text This is bold text This is extrabold text This is primary text This is secondary text This is success text This is warning text This is error text This is info text This is left text This is right text This is center text This is justify text This is start text This is end text This is top text This is middle text This is bottom text This is truncate text This is break_ text This is nowrap text This is underline text This is highlight text [code] def ex_textt(): return Grid(*[Div(P(f"This is {s.name} text", cls=s.value)) for s in TextT]) [/code] ### API Reference * * * ### TextPresets _Common Typography Presets_ Option | Value | Option | Value ---|---|---|--- muted_sm | text-gray-500 dark:text-gray-200 text-sm | muted_lg | text-gray-500 dark:text-gray-200 text-lg bold_sm | font-bold text-sm | bold_lg | font-bold text-lg md_weight_sm | text-sm font-medium | md_weight_muted | font-medium text-gray-500 dark:text-gray-200 * * * ### TextT _Text Styles from https://franken-ui.dev/docs/text_ Option | Value | Option | Value | Option | Value | Option | Value ---|---|---|---|---|---|---|--- paragraph | uk-paragraph | lead | uk-text-lead | meta | uk-text-meta | gray | text-gray-500 dark:text-gray-200 italic | italic | xs | text-xs | sm | text-sm | lg | text-lg xl | text-xl | light | font-normal | normal | font-light | medium | font-medium bold | font-bold | extrabold | font-extrabold | muted | text-gray-500 dark:text-gray-200 | primary | text-primary secondary | text-secondary | success | text-success | warning | text-warning | error | text-error info | text-info | left | text-left | right | text-right | center | text-center justify | text-justify | start | text-start | end | text-end | top | align-top middle | align-middle | bottom | align-bottom | truncate | uk-text-truncate | break_ | uk-text-break nowrap | uk-text-nowrap | underline | underline | highlight | bg-yellow-200 dark:bg-yellow-800 text-black | | ### H1 Source [code] H1(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H1 with styling and appropriate size **Params** * `c` Contents of H1 tag (often text) * `cls` Classes in addition to H1 styling * `kwargs` **Returns:** H1(..., cls='uk-h1') ### H2 Source [code] H2(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H2 with styling and appropriate size **Params** * `c` Contents of H2 tag (often text) * `cls` Classes in addition to H2 styling * `kwargs` **Returns:** H2(..., cls='uk-h2') ### H3 Source [code] H3(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H3 with styling and appropriate size **Params** * `c` Contents of H3 tag (often text) * `cls` Classes in addition to H3 styling * `kwargs` **Returns:** H3(..., cls='uk-h3') ### H4 Source [code] H4(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H4 with styling and appropriate size **Params** * `c` Contents of H4 tag (often text) * `cls` Classes in addition to H4 styling * `kwargs` **Returns:** H4(..., cls='uk-h4') ### H5 Source [code] H5(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H5 with styling and appropriate size **Params** * `c` Contents of H5 tag (often text) * `cls` Classes in addition to H5 styling * `kwargs` **Returns:** H5(..., cls='text-lg font-semibold') ### H6 Source [code] H6(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > H6 with styling and appropriate size **Params** * `c` Contents of H6 tag (often text) * `cls` Classes in addition to H6 styling * `kwargs` **Returns:** H6(..., cls='text-base font-semibold') ### CodeSpan Source [code] CodeSpan(*c, cls=(), **kwargs) -> fastcore.xml.FT [/code] > A CodeSpan with Styling **Params** * `c` Contents of CodeSpan tag (inline text code snippets) * `cls` Classes in addition to CodeSpan styling * `kwargs` **Returns:** Code(..., cls='uk-codespan') ### Blockquote Source [code] Blockquote(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Blockquote with Styling **Params** * `c` Contents of Blockquote tag (often text) * `cls` Classes in addition to Blockquote styling * `kwargs` **Returns:** Blockquote(..., cls='uk-blockquote') ### CodeBlock Source [code] CodeBlock(*c: str, cls: enum.Enum | str | tuple = (), code_cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > CodeBlock with Styling **Params** * `c` Contents of Code tag (often text) * `cls` Classes for the outer container * `code_cls` Classes for the code tag * `kwargs` **Returns:** Div(Pre(Code(..., cls='uk-codeblock), cls='multiple tailwind styles'), cls='uk-block') ### Em Source [code] Em(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled emphasis text **Params** * `c` Contents of Em tag (emphasis) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Em tag ### Strong Source [code] Strong(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled strong text **Params** * `c` Contents of Strong tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Strong tag ### I Source [code] I(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled italic text **Params** * `c` Contents of I tag (italics) * `cls` Additional classes * `kwargs` **Returns:** Additional args for I tag ### Small Source [code] Small(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled small text **Params** * `c` Contents of Small tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Small tag ### Mark Source [code] Mark(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled highlighted text **Params** * `c` Contents of Mark tag (highlighted text) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Mark tag ### Sub Source [code] Sub(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled subscript text **Params** * `c` Contents of Sub tag (subscript) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Sub tag ### Sup Source [code] Sup(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled superscript text **Params** * `c` Contents of Sup tag (superscript) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Sup tag ### Del Source [code] Del(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled deleted text **Params** * `c` Contents of Del tag (deleted text) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Del tag ### Ins Source [code] Ins(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled inserted text **Params** * `c` Contents of Ins tag (inserted text) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Ins tag ### Dfn Source [code] Dfn(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled definition term with italic and medium weight **Params** * `c` Contents of Dfn tag (definition) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Dfn tag ### Abbr Source [code] Abbr(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), title: str = None, **kwargs) -> fastcore.xml.FT [/code] > Styled abbreviation with dotted underline **Params** * `c` Contents of Abbr tag * `cls` Additional classes * `title` Title attribute for abbreviation * `kwargs` **Returns:** Additional args for Abbr tag ### Q Source [code] Q(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled quotation mark **Params** * `c` Contents of Q tag (quote) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Q tag ### Kbd Source [code] Kbd(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled keyboard input with subtle background **Params** * `c` Contents of Kbd tag (keyboard input) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Kbd tag ### Samp Source [code] Samp(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled sample output with subtle background **Params** * `c` Contents of Samp tag (sample output) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Samp tag ### Var Source [code] Var(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled variable with italic monospace **Params** * `c` Contents of Var tag (variable) * `cls` Additional classes * `kwargs` **Returns:** Additional args for Var tag ### Figure Source [code] Figure(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled figure container with card-like appearance **Params** * `c` Contents of Figure tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Figure tag ### Caption Source [code] Caption(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled caption text **Params** * `c` * `cls` * `kwargs` ### Details Source [code] Details(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled details element **Params** * `c` Contents of Details tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Details tag ### Summary Source [code] Summary(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled summary element **Params** * `c` Contents of Summary tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Summary tag ### Meter Source [code] Meter(*c: fastcore.xml.FT | str, value: float = None, min: float = None, max: float = None, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled meter element **Params** * `c` Contents of Meter tag * `value` Current value * `min` Minimum value * `max` Maximum value * `cls` Additional classes * `kwargs` **Returns:** Additional args for Meter tag ### Data Source [code] Data(*c: fastcore.xml.FT | str, value: str = None, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled data element **Params** * `c` Contents of Data tag * `value` Value attribute * `cls` Additional classes * `kwargs` **Returns:** Additional args for Data tag ### Output Source [code] Output(*c: fastcore.xml.FT | str, form: str = None, for_: str = None, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled output element for form results **Params** * `c` Contents of Output tag * `form` ID of form this output belongs to * `for_` IDs of elements this output is for * `cls` Additional classes * `kwargs` **Returns:** Additional args for Output tag ### Address Source [code] Address(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), **kwargs) -> fastcore.xml.FT [/code] > Styled address element **Params** * `c` Contents of Address tag * `cls` Additional classes * `kwargs` **Returns:** Additional args for Address tag ### Time Source [code] Time(*c: fastcore.xml.FT | str, cls: enum.Enum | str | tuple = (), datetime: str = None, **kwargs) -> fastcore.xml.FT [/code] > Styled time element **Params** * `c` Contents of Time tag * `cls` Additional classes * `datetime` datetime attribute * `kwargs` **Returns:** Additional args for Time tag *[HyperText Markup Language (Abbr)]: HyperText Markup Language
https://monsterui.answer.ai/api_ref/docs_typography/md
docs_typography_md
# MonterUI Page Layout Guide This guide will discuss 3 tools for laying out your app pages, Grid, Flexbox, and Columns. This page will discuss the strengths and when to use each individually, and then a section for how to combine them for more complex layouts at the end. > Note: This guide is designed to get you started building layouts quickly, not to teach you all the details needed to build every possible custom layout with pixel-perfect control. To get more detailed and lower-level control, explore the tailwind docs. This guide is for creating flexible layouts you envision, but does not discuss responsiveness to make different layouts that are both mobile and desktop friendly. Stay tunes for a responsiveness guide that will help with that! # Grid Grids are best for regular predictable layouts with lots of the same shape of things that may need to change a lot for different screen sizes. I think the best way to see what it can do is to see a bunch of examples, so here they are! ## Minimal Image Cards This is a minimal example of a grid that just shows image and text. This is the foundation for many more complex layouts so make sure to understand what's going on here first before moving on! A grid lays things out in a...grid. As you can see, we have evenly sized cards by default. See Source See Output Image 0 Image 1 Image 2 Image 3 Image 4 Image 5 [code] def picsum_img(seed): return Img(src=f'https://picsum.photos/300/200?random={seed}') Grid(*[Card(picsum_img(i),P(f"Image {i}")) for i in range(6)]) [/code] ## Dashboard Example However, they don't have to be evenly sized! By providing `row-span-{int}` and `col-span-{int}` we can control how many rows or columns specific grid elements take up. By doing this, we can create a grid that has lots of different shapes and types of elements. Let's look at a dashboard layout at an examples of this. See Source See Output ### SideBar Range For Filters A search Bar Choose Product Line Product Line AProduct Line BProduct Line CProduct Line D Include Inactive Users Include Users without order Include Users without email Total Users ### 1,234 Active Now ### 342 Revenue ### $45,678 Conversion ### 2.4% ### Monthly Revenue Chart Goes Here ### User Growth Chart Goes Here [code] def StatCard(title, value, color='primary'): "A card with a statistics. Since there is no row/col span class it will take up 1 slot" return Card(P(title, cls=TextPresets.muted_sm), H3(value, cls=f'text-{color}'),) stats = [StatCard(*data) for data in [ ("Total Users", "1,234", "blue-600"), ("Active Now", "342", "green-600"), ("Revenue", "$45,678", "purple-600"), ("Conversion", "2.4%", "amber-600")]] def ChartCard(title): "A card for a chart. col-span-2 means it will take up 2 columns" return Div(cls="col-span-2")( Card(H3(title),Div("Chart Goes Here", cls="h-64 uk-background-muted"))) chart_cards = [ChartCard(title) for title in ("Monthly Revenue", "User Growth")] sidebar = Form( H3("SideBar"), LabelRange("Range For Filters", min=0, max=100), LabelInput("A search Bar"), LabelSelect(map(Option, ["Product Line A", "Product Line B", "Product Line C", "Product Line D"]), label="Choose Product Line"), LabelCheckboxX("Include Inactive Users"), LabelCheckboxX("Include Users without order"), LabelCheckboxX("Include Users without email"), # This sidebar will take up 2 rows b/c of row-span-2 cls='row-span-2 space-y-5' ) Container(Grid(sidebar, *stats, *chart_cards, cols=5)) [/code] # Flexbox Using Grid for the overall layout, and flex for the individual elements is a powerful pattern. With `MonsterUI` you can do quite a bit without knowing anything about flexbox, which is what will be taught here. However, flexbox is well worth learning about it in more detail. You will run into situations where you need more flexbox knowledge than is covered here to build your vision. Thankfully you can get that knowledge by playing a fantastic tutorial game called FlexBox Froggy! ## Forms Often you want to stack things horizontally. You can use the `DivHStacked` component to do this. `DivHStacked` is a helper function for flexbox and creates a div with these classes by default `cls=(FlexT.block, FlexT.row, FlexT.middle, 'space-x-4')`. See Source See Output ### Form with Input Groups Search Users Filter Tags Email List SubmitCancel [code] def InputGroup(label, placeholder='', button_text='Submit', cls=''): # Div H Stacked makes the label and input show up on the same row instead of putting the input on a newline return DivHStacked( FormLabel(label, cls='whitespace-nowrap'), Input(placeholder=placeholder)) Container( H3("Form with Input Groups"), Form(cls='space-y-4')( InputGroup("Search Users", "Enter username..."), InputGroup("Filter Tags", "Add tags...", "Add"), InputGroup("Email List", "Enter email...", "Subscribe"), Div(*( Button(UkIcon(icon, cls='mr-2'), text) for icon, text in [("rocket", "Submit"), ("circle-x", "Cancel")]), cls='space-x-4'))) [/code] ## Avatar You can use this same `DivHStacked` to align things like text next to images. And you can use `DivVStacked` to stack things vertically to create design structures you like. `DivVStacked` works by using `cls=(FlexT.block,FlexT.column,FlexT.middle)` See Source See Output John Doe [email protected] +1-123-456-7890 [code] # DivHStacked makes the a single row so text is to on same line as avatar DivHStacked( DiceBearAvatar("user"), # DivVStacked stacks things vertically together and centers it with flex DivVStacked( P("John Doe", cls=TextT.lg), P("[emailΒ protected]", cls=TextT.muted), P("+1-123-456-7890"), cls=TextT.muted)) [/code] ## Pricing Card These can be combined with icons and other styling to create larger components like a pricing card. See Source See Output ## Pro Plan ### $99 per month * Unlimited users * 24/7 priority support * Custom branding options * Advanced analytics dashboard * Full API access * Priority request queue Subscribe Now [code] features = [ "Unlimited users", "24/7 priority support", "Custom branding options", "Advanced analytics dashboard", "Full API access", "Priority request queue" ] def PricingCard(plan, price, features): "Create a polished pricing card with consistent styling" return Card( DivVStacked( # Center and veritcally stack the plan name and price H2(plan), H3(price, cls='text-primary'), P('per month',cls=TextT.muted), cls='space-y-1'), # DivHStacked makes green check and feature Li show up on same row instead of newline Ul(*[DivHStacked(UkIcon('check', cls='text-green-500 mr-2'), Li(feature)) for feature in features], cls='space-y-4'), Button("Subscribe Now", cls=(ButtonT.primary, 'w-full'))) DivVStacked(PricingCard("Pro Plan", "$99", features)) [/code] ## Footer Or you can combine things to make advanced footers that have titles, organized links, and icons! In this example we add another flex helper function, `DivFullySpaced`. `DivFullySpaced` is a flex class that puts as much space between items as possible See Source See Output ### Company Name * * * #### Company AboutBlogCareersPress Kit #### Resources DocumentationHelp CenterStatusContact Sales #### Legal Terms of ServicePrivacy PolicyCookie SettingsAccessibility * * * Β© 2024 Company Name. All rights reserved. [code] def FooterLinkGroup(title, links): # DivVStacked centers and makes title and each link stack vertically return DivVStacked( H4(title), *[A(text, href=f"#{text.lower().replace(' ', '-')}", cls=TextT.muted) for text in links]) company = ["About", "Blog", "Careers", "Press Kit"] resource = ["Documentation", "Help Center", "Status", "Contact Sales"] legal = ["Terms of Service", "Privacy Policy", "Cookie Settings", "Accessibility"] Container(cls='uk-background-muted py-12')(Div( # Company Name and social icons will be on the same row with as much sapce between as possible DivFullySpaced( H3("Company Name"), # DivHStacked makes the icons be on the same row in a group DivHStacked(*[UkIcon(icon, cls=TextT.lead) for icon in ['twitter', 'facebook', 'github', 'linkedin']])), DividerLine(), DivFullySpaced( # Each child will be spread out as much as possible based on number of children FooterLinkGroup("Company", company), FooterLinkGroup("Resources", resource), FooterLinkGroup("Legal", legal)), DividerLine(), P("Β© 2024 Company Name. All rights reserved.", cls=TextT.lead+TextT.sm), cls='space-y-8 p-8')) [/code] ## Dashboard See Source See Output ## Welcome back, Isaac! Here's what's happening with your projects today. Total Projects ### 12 +2.5% from last month Hours Logged ### 164 +12.3% from last month Tasks Complete ### 64% -4.1% from last month Team Velocity ### 23 +8.4% from last month ### Recent Activity Sarah Chen completed Project Alpha deployment 2h ago James Wilson commented on Project Beta 4h ago Maria Garcia uploaded new design files 6h ago Alex Kumar started Sprint Planning 8h ago [code] def StatsCard(label, value, change): color = 'green' if change[0] == '+' else 'red' return Card(DivVStacked( # Stacks vertically and centers all elements P(label, cls=TextPresets.muted_sm), H3(value), P(f"{change}% from last month", cls=f"text-{color}-600 text-sm"))) def RecentActivity(user, action, time): return DivHStacked( # Makes Avatar and text be on same row DiceBearAvatar(user, h=8, w=8), P(f"{user} {action}", cls="flex-1"), P(time, cls=TextPresets.muted_sm)) DivVStacked( # Centers the entire dashboard layout # Page header DivVStacked( # Stacks vertically and centers the title/subtitle H2("Welcome back, Isaac!"), P("Here's what's happening with your projects today.",cls=TextT.muted)), # DivHStacked puts all the stats cards on the same row DivHStacked(*(StatsCard(label, value, change) for label, value, change in [ ("Total Projects", "12", "+2.5"), ("Hours Logged", "164", "+12.3"), ("Tasks Complete", "64%", "-4.1"), ("Team Velocity", "23", "+8.4")] )), # Recent activity Card(*(RecentActivity(user, action, time) for user, action, time in [ ("Sarah Chen", "completed Project Alpha deployment", "2h ago"), ("James Wilson", "commented on Project Beta", "4h ago"), ("Maria Garcia", "uploaded new design files", "6h ago"), ("Alex Kumar", "started Sprint Planning", "8h ago")]), header=H3("Recent Activity"), ), cls="space-y-6" ) [/code] ## Columns Columns are a great for sections that have a lot of text. See Source See Output # Lorem Ipsum Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor. [code] Container( H1("Lorem Ipsum", cls="text-center mb-8"), # Use 2 columns for the main content Div(cls="columns-2 gap-12")( P("""Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."""), DivCentered(cls='mt-8')( P("""Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.""", cls=(TextT.lg, TextT.bold, TextT.center, TextT.italic, "text-primary"))), P("""Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium."""), P("""Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor."""))) [/code]
https://monsterui.answer.ai/tutorial_layout/md
tutorial_layout_md
# Padding & Margin & Spacing, Oh my! (MonsterUI Spacing Guide) This guide will cover some essentials about how to properly space apps and what the differences are between: * Padding * Margin * Spacing * Gap Manipulating the space between components can make a huge difference to the percieved quality of the page. Being able to tweak the spacing can have a big impact! > Tip: I find it works best to get everything on the page without adjusting spacing much, and adjusting spacing at the end. ## Abreviations: First a few abbreviations that are helpful to know with tailwind (and a convention we follow in `MonsterUI`). * `t`, `b`, `l`, `r` = top, bottom, left, right * `p`, `m` = padding, margin * `x`, `y` = horizontal, vertical That means: * `mt` means margin on top of the element * `px` means padding on the x axis (both left and right) * `space-y` means apply spacing on the y axis (both top and bottom) ## Padding vs Margin Margin applies space to the left of the component, and padding applies space on the left inside of the component. Please reference the example with cards below: * `ml-20` applies space to the left of the card (outside the card) * `pl-20` applies space on the left inside of the card (inside the card) This means that if you want to move the whole thing but keep the actual container unchanged, use margin. If you want to change the container by adding space inside of it, use padding. See Source See Output #### A Simple Card with ml-20 #### A Simple Card with pl-20 [code] Grid( Card(H4("A Simple Card with ml-20",style='background-color: red'), cls='ml-20'), Card(H4("A Simple Card with pl-20", style='background-color: red'), cls='pl-20')) [/code] ## Space vs gap Spacing and gap are both about setting the space between components. * Spacing applies margin to every element except for the first element in a group. * Gap creates a gap between every element in flexbox elements and grids. > Rule of thumb: Use Gap when using grids. Let's take a look at some grid examples. #### Grid See Source See Output #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card [code] Grid( Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), cls='') [/code] #### Grid with gap See Source See Output #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card [code] Grid( Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), cls='gap-4') [/code] #### Grid with space See Source See Output #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card #### A Simple Card [code] Grid( Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), Card(H4("A Simple Card")), cls='space-x-4 space-y-4') [/code] ### Grid with no gap or space The first example has no gap or not space applied. As expected this means the cards are flush with each other. Often this is not what you want, because a little space between cards looks much nicer. ### Grid with gap The second example has the same grid but with gap applied. As youc an see, this gives constent space between all elements of the grid looks great! ### Grid with space The third example has the same grid but with space applied. As you can see, it's not really what we want. However it's a really good illustration of how space works so let's notice a few things about it: **X Axis** * The first card is flush with the left side of the page (no margin) * The card below it isn't flush with the left side of the page (has margin) **Y Axis** * The first card is flush with the heading immediately above it (no margin) * The card top it's right isn't flush with the heading above it (has margin) So `space` applies margin to every element except for the first element in a group! > Tip: Use your browser developer tools to inspect the examples Next, let's look at a form example where `gap` isn't a good choice but `space` works beautifully! See Source See Output ### My Form Name Phone Email [code] Form(DivCentered(H3("My Form")), LabelInput("Name"), Grid(LabelInput("Phone"), LabelInput("Email"), cols=2), cls='') [/code] See Source See Output ### My Form with gap Name Phone Email [code] Form(DivCentered(H3("My Form with gap")), LabelInput("Name"), Grid(LabelInput("Phone"), LabelInput("Email"), cols=2), cls='gap-y-5') [/code] See Source See Output ### My Form with Spacing Name Phone Email [code] Form(DivCentered(H3("My Form with Spacing")), LabelInput("Name"), Grid(LabelInput("Phone"), LabelInput("Email"), cols=2), cls='space-y-5') [/code] ### Form with no gap or space The top form looks a bit scrunched with defaults, but it's certainly passable. There is a bit of a space between the label and it's associated input because of the defaults in MonsterUI. ### Form with gap The second form with gap is identical to the first. Because we're not in a flex element or a grid, it doesn't do anything at all! ### Form with space `Space-y-5` adds vertical space between each child which really spreads out the form for a nice aesthetic. If you recall from the grid example, it does not apply this margin to the first element - but in this situation (and many others) we do not want the spacing above the top element (heading) to be the same as the spacing between the form elements. > Tip: Use your browser developer tools to inspect the examples # Further reading For further reading, check out the Tailwind CSS guide, which other users have found to be a useful as an additional guide.
https://monsterui.answer.ai/tutorial_spacing/md
tutorial_spacing_md
# FastHTML > FastHTML is a python library which brings together Starlette, Uvicorn, HTMX, and fastcore's `FT` "FastTags" into a library for creating server-rendered hypermedia applications. The `FastHTML` class itself inherits from `Starlette`, and adds decorator-based routing with many additions, Beforeware, automatic `FT` to HTML rendering, and much more. Things to remember when writing FastHTML apps: - Although parts of its API are inspired by FastAPI, it is *not* compatible with FastAPI syntax and is not targeted at creating API services - FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional - FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte - Use `serve()` for running uvicorn (`if __name__ == "__main__"` is not needed since it's automatic) - When a title is needed with a response, use `Titled`; note that that already wraps children in `Container`, and already includes both the meta title as well as the H1 element. ## Docs - [FastHTML quick start](https://docs.fastht.ml/tutorials/quickstart_for_web_devs.html.md): A brief overview of many FastHTML features - [HTMX reference](https://raw.githubusercontent.com/bigskysoftware/htmx/master/www/content/reference.md): Brief description of all HTMX attributes, CSS classes, headers, events, extensions, js lib methods, and config options - [Surreal](https://raw.githubusercontent.com/AnswerDotAI/surreal/main/README.md): Tiny jQuery alternative for plain Javascript with inline Locality of Behavior, providing `me` and `any` functions - [CSS Scope Inline](https://raw.githubusercontent.com/gnat/css-scope-inline/main/README.md): A JS library which allow `me` to be used in CSS selectors, by using a `MutationObserver` to monitor the DOM - [Starlette quick guide](https://gist.githubusercontent.com/jph00/e91192e9bdc1640f5421ce3c904f2efb/raw/61a2774912414029edaf1a55b506f0e283b93c46/starlette-quick.md): A quick overview of some Starlette features useful to FastHTML devs. ## API - [API List](https://docs.fastht.ml/apilist.txt): A succint list of all functions and methods in fasthtml. ## Examples - [Websockets application](https://raw.githubusercontent.com/AnswerDotAI/fasthtml/main/examples/basic_ws.py): Very brief example of using websockets with HTMX and FastHTML - [Todo list application](https://raw.githubusercontent.com/AnswerDotAI/fasthtml/main/examples/adv_app.py): Detailed walk-thru of a complete CRUD app in FastHTML showing idiomatic use of FastHTML and HTMX patterns. ## Optional - [Starlette full documentation](https://gist.githubusercontent.com/jph00/809e4a4808d4510be0e3dc9565e9cbd3/raw/9b717589ca44cedc8aaf00b2b8cacef922964c0f/starlette-sml.md): A subset of the Starlette documentation useful for FastHTML development. - [JS App Walkthrough](https://docs.fastht.ml/tutorials/e2e.html.md): An end-to-end walkthrough of a complete FastHTML app, including deployment to railway. - [FastHTML by Example](https://docs.fastht.ml/tutorials/by_example.html.md): A collection of 4 FastHTML apps showcasing idiomatic use of FastHTML and HTMX patterns. - [Using Jupyter to write FastHTML](https://docs.fastht.ml/tutorials/jupyter_and_fasthtml.html.md): A guide to developing FastHTML apps inside Jupyter notebooks. - [FT Components](https://docs.fastht.ml/explains/explaining_xt_components.html.md): Explanation of the `FT` components, which are a way to write HTML in a Pythonic way. - [FAQ](https://docs.fastht.ml/explains/faq.html.md): Answers to common questions about FastHTML. - [MiniDataAPI Spec](https://docs.fastht.ml/explains/minidataapi.html.md): Explanation of the MiniDataAPI specification, which allows us to use the same API for many different database engines. - [OAuth](https://docs.fastht.ml/explains/oauth.html.md): Tutorial and explanation of how to use OAuth in FastHTML apps. - [Routes](https://docs.fastht.ml/explains/routes.html.md): Explanation of how routes work in FastHTML. - [WebSockets](https://docs.fastht.ml/explains/websockets.html.md): Explanation of websockets and how they work in FastHTML. - [Custom Components](https://docs.fastht.ml/ref/defining_xt_component.html.md): Explanation of how to create custom components in FastHTML. - [Handling Handlers](https://docs.fastht.ml/ref/handlers.html.md): Explanation of how to request and response handlers work in FastHTML as routes. - [Live Reloading](https://docs.fastht.ml/ref/live_reload.html.md): Explanation of how to use live reloading for FastHTML development.
https://docs.fastht.ml/llms.txt
docs.fastht.ml_llms.txt
# Web Devs Quickstart <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> ## Installation ``` bash pip install python-fasthtml ``` ## A Minimal Application A minimal FastHTML application looks something like this: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) serve() ``` </div> Line 1 We import what we need for rapid development! A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience. Line 3 We instantiate a FastHTML app with the `fast_app()` utility function. This provides a number of really useful defaults that we’ll take advantage of later in the tutorial. Line 5 We use the `rt()` decorator to tell FastHTML what to return when a user visits `/` in their browser. Line 6 We connect this route to HTTP GET requests by defining a view function called `get()`. Line 7 A tree of Python function calls that return all the HTML required to write a properly formed web page. You’ll soon see the power of this approach. Line 9 The [`serve()`](https://docs.fastht.ml/api/core.html#serve) utility configures and runs FastHTML using a library called `uvicorn`. Run the code: ``` bash python main.py ``` The terminal will look like this: ``` bash INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit) INFO: Started reloader process [58058] using WatchFiles INFO: Started server process [58060] INFO: Waiting for application startup. INFO: Application startup complete. ``` Confirm FastHTML is running by opening your web browser to [127.0.0.1:5001](http://127.0.0.1:5001). You should see something like the image below: ![](quickstart-web-dev/quickstart-fasthtml.png) <div> > **Note** > > While some linters and developers will complain about the wildcard > import, it is by design here and perfectly safe. FastHTML is very > deliberate about the objects it exports in `fasthtml.common`. If it > bothers you, you can import the objects you need individually, though > it will make the code more verbose and less readable. > > If you want to learn more about how FastHTML handles imports, we cover > that [here](https://docs.fastht.ml/explains/faq.html#why-use-import). </div> ## A Minimal Charting Application The [`Script`](https://docs.fastht.ml/api/xtend.html#script) function allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this: ``` python import json from fasthtml.common import * app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.32.0.min.js"),)) data = json.dumps({ "data": [{"x": [1, 2, 3, 4],"type": "scatter"}, {"x": [1, 2, 3, 4],"y": [16, 5, 11, 9],"type": "scatter"}], "title": "Plotly chart in FastHTML ", "description": "This is a demo dashboard", "type": "scatter" }) @rt("/") def get(): return Titled("Chart Demo", Div(id="myDiv"), Script(f"var data = {data}; Plotly.newPlot('myDiv', data);")) serve() ``` ## Debug Mode When we can’t figure out a bug in FastHTML, we can run it in `DEBUG` mode. When an error is thrown, the error screen is displayed in the browser. This error setting should never be used in a deployed app. ``` python from fasthtml.common import * app, rt = fast_app(debug=True) @rt("/") def get(): 1/0 return Titled("FastHTML Error!", P("Let's error!")) serve() ``` Line 3 `debug=True` sets debug mode on. Line 7 Python throws an error when it tries to divide an integer by zero. ## Routing FastHTML builds upon FastAPI’s friendly decorator pattern for specifying URLs, with extra features: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) @rt("/hello") def get(): return Titled("Hello, world!") serve() ``` </div> Line 5 The β€œ/” URL on line 5 is the home of a project. This would be accessed at [127.0.0.1:5001](http://127.0.0.1:5001). Line 9 β€œ/hello” URL on line 9 will be found by the project if the user visits [127.0.0.1:5001/hello](http://127.0.0.1:5001/hello). <div> > **Tip** > > It looks like `get()` is being defined twice, but that’s not the case. > Each function decorated with `rt` is totally separate, and is injected > into the router. We’re not calling them in the module’s namespace > (`locals()`). Rather, we’re loading them into the routing mechanism > using the `rt` decorator. </div> You can do more! Read on to learn what we can do to make parts of the URL dynamic. ## Variables in URLs You can add variable sections to a URL by marking them with `{variable_name}`. Your function then receives the `{variable_name}` as a keyword argument, but only if it is the correct type. Here’s an example: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app() @rt("/{name}/{age}") def get(name: str, age: int): return Titled(f"Hello {name.title()}, age {age}") serve() ``` </div> Line 5 We specify two variable names, `name` and `age`. Line 6 We define two function arguments named identically to the variables. You will note that we specify the Python types to be passed. Line 7 We use these functions in our project. Try it out by going to this address: [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5). You should get a page that says, > β€œHello Uma, age 5”. ### What happens if we enter incorrect data? The [127.0.0.1:5001/uma/5](http://127.0.0.1:5001/uma/5) URL works because `5` is an integer. If we enter something that is not, such as [127.0.0.1:5001/uma/five](http://127.0.0.1:5001/uma/five), then FastHTML will return an error instead of a web page. <div> > **FastHTML URL routing supports more complex types** > > The two examples we provide here use Python’s built-in `str` and `int` > types, but you can use your own types, including more complex ones > such as those defined by libraries like > [attrs](https://pypi.org/project/attrs/), > [pydantic](https://pypi.org/project/pydantic/), and even > [sqlmodel](https://pypi.org/project/sqlmodel/). </div> ## HTTP Methods FastHTML matches function names to HTTP methods. So far the URL routes we’ve defined have been for HTTP GET methods, the most common method for web pages. Form submissions often are sent as HTTP POST. When dealing with more dynamic web page designs, also known as Single Page Apps (SPA for short), the need can arise for other methods such as HTTP PUT and HTTP DELETE. The way FastHTML handles this is by changing the function name. <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("HTTP GET", P("Handle GET")) @rt("/") def post(): return Titled("HTTP POST", P("Handle POST")) serve() ``` </div> Line 6 On line 6 because the `get()` function name is used, this will handle HTTP GETs going to the `/` URI. Line 10 On line 10 because the `post()` function name is used, this will handle HTTP POSTs going to the `/` URI. ## CSS Files and Inline Styles Here we modify default headers to demonstrate how to use the [Sakura CSS microframework](https://github.com/oxalorg/sakura) instead of FastHTML’s default of Pico CSS. <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app( pico=False, hdrs=( Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'), Link(rel='stylesheet', href='assets/sakura.css', type='text/css'), Style("p {color: red;}") )) @app.get("/") def home(): return Titled("FastHTML", P("Let's do this!"), ) serve() ``` </div> Line 4 By setting `pico` to `False`, FastHTML will not include `pico.min.css`. Line 7 This will generate an HTML `<link>` tag for sourcing the css for Sakura. Line 8 If you want an inline styles, the [`Style()`](https://docs.fastht.ml/api/xtend.html#style) function will put the result into the HTML. ## Other Static Media File Locations As you saw, [`Script`](https://docs.fastht.ml/api/xtend.html#script) and `Link` are specific to the most common static media use cases in web apps: including JavaScript, CSS, and images. But it also works with videos and other static media files. The default behavior is to look for these files in the root directory - typically we don’t do anything special to include them. We can change the default directory that is looked in for files by adding the `static_path` parameter to the `fast_app` function. ``` python app, rt = fast_app(static_path='public') ``` FastHTML also allows us to define a route that uses `FileResponse` to serve the file at a specified path. This is useful for serving images, videos, and other media files from a different directory without having to change the paths of many files. So if we move the directory containing the media files, we only need to change the path in one place. In the example below, we call images from a directory called `public`. ``` python @rt("/{fname:path}.{ext:static}") async def get(fname:str, ext:str): return FileResponse(f'public/{fname}.{ext}') ``` ## Rendering Markdown ``` python from fasthtml.common import * hdrs = (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), ) app, rt = fast_app(hdrs=hdrs) content = """ Here are some _markdown_ elements. - This is a list item - This is another list item - And this is a third list item **Fenced code blocks work here.** """ @rt('/') def get(req): return Titled("Markdown rendering example", Div(content,cls="marked")) serve() ``` ## Code highlighting Here’s how to highlight code without any markdown configuration. ``` python from fasthtml.common import * # Add the HighlightJS built-in header hdrs = (HighlightJS(langs=['python', 'javascript', 'html', 'css']),) app, rt = fast_app(hdrs=hdrs) code_example = """ import datetime import time for i in range(10): print(f"{datetime.datetime.now()}") time.sleep(1) """ @rt('/') def get(req): return Titled("Markdown rendering example", Div( # The code example needs to be surrounded by # Pre & Code elements Pre(Code(code_example)) )) serve() ``` ## Defining new `ft` components We can build our own `ft` components and combine them with other components. The simplest method is defining them as a function. ``` python from fasthtml.common import * ``` ``` python def hero(title, statement): return Div(H1(title),P(statement), cls="hero") # usage example Main( hero("Hello World", "This is a hero statement") ) ``` ``` html <main> <div class="hero"> <h1>Hello World</h1> <p>This is a hero statement</p> </div> </main> ``` ### Pass through components For when we need to define a new component that allows zero-to-many components to be nested within them, we lean on Python’s `*args` and `**kwargs` mechanism. Useful for creating page layout controls. ``` python def layout(*args, **kwargs): """Dashboard layout for all our dashboard views""" return Main( H1("Dashboard"), Div(*args, **kwargs), cls="dashboard", ) # usage example layout( Ul(*[Li(o) for o in range(3)]), P("Some content", cls="description"), ) ``` ``` html <main class="dashboard"> <h1>Dashboard</h1> <div> <ul> <li>0</li> <li>1</li> <li>2</li> </ul> <p class="description">Some content</p> </div> </main> ``` ### Dataclasses as ft components While functions are easy to read, for more complex components some might find it easier to use a dataclass. ``` python from dataclasses import dataclass @dataclass class Hero: title: str statement: str def __ft__(self): """ The __ft__ method renders the dataclass at runtime.""" return Div(H1(self.title),P(self.statement), cls="hero") #Β usage example Main( Hero("Hello World", "This is a hero statement") ) ``` ``` html <main> <div class="hero"> <h1>Hello World</h1> <p>This is a hero statement</p> </div> </main> ``` ## Testing views in notebooks Because of the ASGI event loop it is currently impossible to run FastHTML inside a notebook. However, we can still test the output of our views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML uses. ``` python # First we instantiate our app, in this case we remove the # default headers to reduce the size of the output. app, rt = fast_app(default_hdrs=False) # Setting up the Starlette test client from starlette.testclient import TestClient client = TestClient(app) # Usage example @rt("/") def get(): return Titled("FastHTML is awesome", P("The fastest way to create web apps in Python")) print(client.get("/").text) ``` <!doctype html> <html> <head> <title>FastHTML is awesome</title> </head> <body> <main class="container"> <h1>FastHTML is awesome</h1> <p>The fastest way to create web apps in Python</p> </main> </body> </html> ## Forms To validate data coming from users, first define a dataclass representing the data you want to check. Here’s an example representing a signup form. ``` python from dataclasses import dataclass @dataclass class Profile: email:str; phone:str; age:int ``` Create an FT component representing an empty version of that form. Don’t pass in any value to fill the form, that gets handled later. ``` python profile_form = Form(method="post", action="/profile")( Fieldset( Label('Email', Input(name="email")), Label("Phone", Input(name="phone")), Label("Age", Input(name="age")), ), Button("Save", type="submit"), ) profile_form ``` ``` html <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email"> </label><label>Phone <input name="phone"> </label><label>Age <input name="age"> </label></fieldset><button type="submit">Save</button></form> ``` Once the dataclass and form function are completed, we can add data to the form. To do that, instantiate the profile dataclass: ``` python profile = Profile(email='[email protected]', phone='123456789', age=5) profile ``` Profile(email='[email protected]', phone='123456789', age=5) Then add that data to the `profile_form` using FastHTML’s [`fill_form`](https://docs.fastht.ml/api/components.html#fill_form) class: ``` python fill_form(profile_form, profile) ``` ``` html <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]"> </label><label>Phone <input name="phone" value="123456789"> </label><label>Age <input name="age" value="5"> </label></fieldset><button type="submit">Save</button></form> ``` ### Forms with views The usefulness of FastHTML forms becomes more apparent when they are combined with FastHTML views. We’ll show how this works by using the test client from above. First, let’s create a SQlite database: ``` python db = database("profiles.db") profiles = db.create(Profile, pk="email") ``` Now we insert a record into the database: ``` python profiles.insert(profile) ``` Profile(email='[email protected]', phone='123456789', age=5) And we can then demonstrate in the code that form is filled and displayed to the user. ``` python @rt("/profile/{email}") def profile(email:str): profile = profiles[email] filled_profile_form = fill_form(profile_form, profile) return Titled(f'Profile for {profile.email}', filled_profile_form) print(client.get(f"/profile/[email protected]").text) ``` Line 3 Fetch the profile using the profile table’s `email` primary key Line 4 Fill the form for display. <!-- --> <!doctype html> <html> <head> <title>Profile for [email protected]</title> </head> <body> <main class="container"> <h1>Profile for [email protected]</h1> <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]"> </label><label>Phone <input name="phone" value="123456789"> </label><label>Age <input name="age" value="5"> </label></fieldset><button type="submit">Save</button></form></main> </body> </html> And now let’s demonstrate making a change to the data. ``` python @rt("/profile") def post(profile: Profile): profiles.update(profile) return RedirectResponse(url=f"/profile/{profile.email}") new_data = dict(email='[email protected]', phone='7654321', age=25) print(client.post("/profile", data=new_data).text) ``` Line 2 We use the `Profile` dataclass definition to set the type for the incoming `profile` content. This validates the field types for the incoming data Line 3 Taking our validated data, we updated the profiles table Line 4 We redirect the user back to their profile view Line 7 The display is of the profile form view showing the changes in data. <!-- --> <!doctype html> <html> <head> <title>Profile for [email protected]</title> </head> <body> <main class="container"> <h1>Profile for [email protected]</h1> <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[email protected]"> </label><label>Phone <input name="phone" value="7654321"> </label><label>Age <input name="age" value="25"> </label></fieldset><button type="submit">Save</button></form></main> </body> </html> ## Strings and conversion order The general rules for rendering are: - `__ft__` method will be called (for default components like `P`, `H2`, etc. or if you define your own components) - If you pass a string, it will be escaped - On other python objects, `str()` will be called As a consequence, if you want to include plain HTML tags directly into e.g.Β a `Div()` they will get escaped by default (as a security measure to avoid code injections). This can be avoided by using `NotStr()`, a convenient way to reuse python code that returns already HTML. If you use pandas, you can use `pandas.DataFrame.to_html()` to get a nice table. To include the output a FastHTML, wrap it in `NotStr()`, like `Div(NotStr(df.to_html()))`. Above we saw how a dataclass behaves with the `__ft__` method defined. On a plain dataclass, `str()` will be called (but not escaped). ``` python from dataclasses import dataclass @dataclass class Hero: title: str statement: str #Β rendering the dataclass with the default method Main( Hero("<h1>Hello World</h1>", "This is a hero statement") ) ``` ``` html <main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main> ``` ``` python # This will display the HTML as text on your page Div("Let's include some HTML here: <div>Some HTML</div>") ``` ``` html <div>Let&#x27;s include some HTML here: &lt;div&gt;Some HTML&lt;/div&gt;</div> ``` ``` python # Keep the string untouched, will be rendered on the page Div(NotStr("<div><h1>Some HTML</h1></div>")) ``` ``` html <div><div><h1>Some HTML</h1></div></div> ``` ## Custom exception handlers FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the `<html>` tags needed to display attractive content. Try it out! ``` python from fasthtml.common import * def not_found(req, exc): return Titled("404: I don't exist!") exception_handlers = {404: not_found} app, rt = fast_app(exception_handlers=exception_handlers) @rt('/') def get(): return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error")))) serve() ``` We can also use lambda to make things more terse: ``` python from fasthtml.common import * exception_handlers={ 404: lambda req, exc: Titled("404: I don't exist!"), 418: lambda req, exc: Titled("418: I'm a teapot!") } app, rt = fast_app(exception_handlers=exception_handlers) @rt('/') def get(): return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error")))) serve() ``` ## Cookies We can set cookies using the [`cookie()`](https://docs.fastht.ml/api/core.html#cookie) function. In our example, we’ll create a `timestamp` cookie. ``` python from datetime import datetime from IPython.display import HTML ``` ``` python @rt("/settimestamp") def get(req): now = datetime.now() return P(f'Set to {now}'), cookie('now', datetime.now()) HTML(client.get('/settimestamp').text) ``` <!doctype html> <html> <head> <title>FastHTML page</title> </head> <body> <p>Set to 2024-09-26 15:33:48.141869</p> </body> </html> Now let’s get it back using the same name for our parameter as the cookie name. ``` python @rt('/gettimestamp') def get(now:parsed_date): return f'Cookie was set at time {now.time()}' client.get('/gettimestamp').text ``` 'Cookie was set at time 15:33:48.141903' ## Sessions For convenience and security, FastHTML has a mechanism for storing small amounts of data in the user’s browser. We can do this by adding a `session` argument to routes. FastHTML sessions are Python dictionaries, and we can leverage to our benefit. The example below shows how to concisely set and get sessions. ``` python @rt('/adder/{num}') def get(session, num: int): session.setdefault('sum', 0) session['sum'] = session.get('sum') + num return Response(f'The sum is {session["sum"]}.') ``` ## Toasts (also known as Messages) Toasts, sometimes called β€œMessages” are small notifications usually in colored boxes used to notify users that something has happened. Toasts can be of four types: - info - success - warning - error Examples toasts might include: - β€œPayment accepted” - β€œData submitted” - β€œRequest approved” Toasts require the use of the `setup_toasts()` function plus every view needs these two features: - The session argument - Must return FT components ``` python setup_toasts(app) @rt('/toasting') def get(session): # Normally one toast is enough, this allows us to see # different toast types in action. add_toast(session, f"Toast is being cooked", "info") add_toast(session, f"Toast is ready", "success") add_toast(session, f"Toast is getting a bit crispy", "warning") add_toast(session, f"Toast is burning!", "error") return Titled("I like toast") ``` Line 1 `setup_toasts` is a helper function that adds toast dependencies. Usually this would be declared right after `fast_app()` Line 4 Toasts require sessions Line 11 Views with Toasts must return FT or FtResponse components. πŸ’‘ `setup_toasts` takes a `duration` input that allows you to specify how long a toast will be visible before disappearing. For example `setup_toasts(duration=5)` sets the toasts duration to 5 seconds. By default toasts disappear after 10 seconds. ## Authentication and authorization In FastHTML the tasks of authentication and authorization are handled with Beforeware. Beforeware are functions that run before the route handler is called. They are useful for global tasks like ensuring users are authenticated or have permissions to access a view. First, we write a function that accepts a request and session arguments: ``` python # Status code 303 is a redirect that can change POST to GET, # so it's appropriate for a login page. login_redir = RedirectResponse('/login', status_code=303) def user_auth_before(req, sess): # The `auth` key in the request scope is automatically provided # to any handler which requests it, and can not be injected # by the user using query params, cookies, etc, so it should # be secure to use. auth = req.scope['auth'] = sess.get('auth', None) # If the session key is not there, it redirects to the login page. if not auth: return login_redir ``` Now we pass our `user_auth_before` function as the first argument into a [`Beforeware`](https://docs.fastht.ml/api/core.html#beforeware) class. We also pass a list of regular expressions to the `skip` argument, designed to allow users to still get to the home and login pages. ``` python beforeware = Beforeware( user_auth_before, skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', r'.*\.js', '/login', '/'] ) app, rt = fast_app(before=beforeware) ``` ## Server-sent events (SSE) With [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), it’s possible for a server to send new data to a web page at any time, by pushing messages to the web page. Unlike WebSockets, SSE can only go in one direction: server to client. SSE is also part of the HTTP specification unlike WebSockets which uses its own specification. FastHTML introduces several tools for working with SSE which are covered in the example below. While concise, there’s a lot going on in this function so we’ve annotated it quite a bit. ``` python import random from asyncio import sleep from fasthtml.common import * hdrs=(Script(src="https://unpkg.com/[email protected]/sse.js"),) app,rt = fast_app(hdrs=hdrs) @rt def index(): return Titled("SSE Random Number Generator", P("Generate pairs of random numbers, as the list grows scroll downwards."), Div(hx_ext="sse", sse_connect="/number-stream", hx_swap="beforeend show:bottom", sse_swap="message")) shutdown_event = signal_shutdown() async def number_generator(): while not shutdown_event.is_set(): data = Article(random.randint(1, 100)) yield sse_message(data) await sleep(1) @rt("/number-stream") async def get(): return EventStream(number_generator()) ``` Line 5 Import the HTMX SSE extension Line 12 Tell HTMX to load the SSE extension Line 13 Look at the `/number-stream` endpoint for SSE content Line 14 When new items come in from the SSE endpoint, add them at the end of the current content within the div. If they go beyond the screen, scroll downwards Line 15 Specify the name of the event. FastHTML’s default event name is β€œmessage”. Only change if you have more than one call to SSE endpoints within a view Line 17 Set up the asyncio event loop Line 19 Don’t forget to make this an `async` function! Line 20 Iterate through the asyncio event loop Line 22 We yield the data. Data ideally should be comprised of FT components as that plugs nicely into HTMX in the browser Line 26 The endpoint view needs to be an async function that returns a [`EventStream`](https://docs.fastht.ml/api/core.html#eventstream) ## Websockets With websockets we can have bi-directional communications between a browser and client. Websockets are useful for things like chat and certain types of games. While websockets can be used for single direction messages from the server (i.e.Β telling users that a process is finished), that task is arguably better suited for SSE. FastHTML provides useful tools for adding websockets to your pages. ``` python from fasthtml.common import * from asyncio import sleep app, rt = fast_app(exts='ws') def mk_inp(): return Input(id='msg', autofocus=True) @rt('/') async def get(request): cts = Div( Div(id='notifications'), Form(mk_inp(), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) async def on_connect(send): print('Connected!') await send(Div('Hello, you have connected', id="notifications")) async def on_disconnect(ws): print('Disconnected!') @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str, send): await send(Div('Hello ' + msg, id="notifications")) await sleep(2) return Div('Goodbye ' + msg, id="notifications"), mk_inp() ``` Line 4 To use websockets in FastHTML, you must instantiate the app with `exts` set to β€˜ws’ Line 6 As we want to use websockets to reset the form, we define the `mk_input` function that can be called from multiple locations Line 12 We create the form and mark it with the `ws_send` attribute, which is documented here in the [HTMX websocket specification](https://v1.htmx.org/extensions/web-sockets/). This tells HTMX to send a message to the nearest websocket based on the trigger for the form element, which for forms is pressing the `enter` key, an action considered to be a form submission Line 13 This is where the HTMX extension is loaded (`hx_ext='ws'`) and the nearest websocket is defined (`ws_connect='/ws'`) Line 16 When a websocket first connects we can optionally have it call a function that accepts a `send` argument. The `send` argument will push a message to the browser. Line 18 Here we use the `send` function that was passed into the `on_connect` function to send a `Div` with an `id` of `notifications` that HTMX assigns to the element in the page that already has an `id` of `notifications` Line 20 When a websocket disconnects we can call a function which takes no arguments. Typically the role of this function is to notify the server to take an action. In this case, we print a simple message to the console Line 23 We use the `app.ws` decorator to mark that `/ws` is the route for our websocket. We also pass in the two optional `conn` and `disconn` parameters to this decorator. As a fun experiment, remove the `conn` and `disconn` arguments and see what happens Line 24 Define the `ws` function as async. This is necessary for ASGI to be able to serve websockets. The function accepts two arguments, a `msg` that is user input from the browser, and a `send` function for pushing data back to the browser Line 25 The `send` function is used here to send HTML back to the page. As the HTML has an `id` of `notifications`, HTMX will overwrite what is already on the page with the same ID Line 27 The websocket function can also be used to return a value. In this case, it is a tuple of two HTML elements. HTMX will take the elements and replace them where appropriate. As both have `id` specified (`notifications` and `msg` respectively), they will replace their predecessor on the page. ## File Uploads A common task in web development is uploading files. The examples below are for uploading files to the hosting server, with information about the uploaded file presented to the user. <div> > **File uploads in production can be dangerous** > > File uploads can be the target of abuse, accidental or intentional. > That means users may attempt to upload files that are too large or > present a security risk. This is especially of concern for public > facing apps. File upload security is outside the scope of this > tutorial, for now we suggest reading the [OWASP File Upload Cheat > Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html). </div> ### Single File Uploads ``` python from fasthtml.common import * from pathlib import Path app, rt = fast_app() upload_dir = Path("filez") upload_dir.mkdir(exist_ok=True) @rt('/') def get(): return Titled("File Upload Demo", Article( Form(hx_post=upload, hx_target="#result-one")( Input(type="file", name="file"), Button("Upload", type="submit", cls='secondary'), ), Div(id="result-one") ) ) def FileMetaDataCard(file): return Article( Header(H3(file.filename)), Ul( Li('Size: ', file.size), Li('Content Type: ', file.content_type), Li('Headers: ', file.headers), ) ) @rt async def upload(file: UploadFile): card = FileMetaDataCard(file) filebuffer = await file.read() (upload_dir / file.filename).write_bytes(filebuffer) return card serve() ``` Line 13 Every form rendered with the [`Form`](https://docs.fastht.ml/api/xtend.html#form) FT component defaults to `enctype="multipart/form-data"` Line 14 Don’t forget to set the `Input` FT Component’s type to `file` Line 32 The upload view should receive a [Starlette UploadFile](https://www.starlette.io/requests/#request-files) type. You can add other form variables Line 33 We can access the metadata of the card (filename, size, content_type, headers), a quick and safe process. We set that to the card variable Line 34 In order to access the contents contained within a file we use the `await` method to read() it. As files may be quite large or contain bad data, this is a seperate step from accessing metadata Line 35 This step shows how to use Python’s built-in `pathlib.Path` library to write the file to disk. ### Multiple File Uploads ``` python from fasthtml.common import * from pathlib import Path app, rt = fast_app() upload_dir = Path("filez") upload_dir.mkdir(exist_ok=True) @rt('/') def get(): return Titled("Multiple File Upload Demo", Article( Form(hx_post=upload_many, hx_target="#result-many")( Input(type="file", name="files", multiple=True), Button("Upload", type="submit", cls='secondary'), ), Div(id="result-many") ) ) def FileMetaDataCard(file): return Article( Header(H3(file.filename)), Ul( Li('Size: ', file.size), Li('Content Type: ', file.content_type), Li('Headers: ', file.headers), ) ) @rt async def upload_many(files: list[UploadFile]): cards = [] for file in files: cards.append(FileMetaDataCard(file)) filebuffer = await file.read() (upload_dir / file.filename).write_bytes(filebuffer) return cards serve() ``` Line 13 Every form rendered with the [`Form`](https://docs.fastht.ml/api/xtend.html#form) FT component defaults to `enctype="multipart/form-data"` Line 14 Don’t forget to set the `Input` FT Component’s type to `file` and assign the multiple attribute to `True` Line 32 The upload view should receive a `list` containing the [Starlette UploadFile](https://www.starlette.io/requests/#request-files) type. You can add other form variables Line 34 Iterate through the files Line 35 We can access the metadata of the card (filename, size, content_type, headers), a quick and safe process. We add that to the cards variable Line 36 In order to access the contents contained within a file we use the `await` method to read() it. As files may be quite large or contain bad data, this is a seperate step from accessing metadata Line 37 This step shows how to use Python’s built-in `pathlib.Path` library to write the file to disk.
https://docs.fastht.ml/tutorials/quickstart_for_web_devs.html.md
tutorials_quickstart_for_web_devs.html.md
+++ title = "Reference" +++ ## Contents * [htmx Core Attributes](#attributes) * [htmx Additional Attributes](#attributes-additional) * [htmx CSS Classes](#classes) * [htmx Request Headers](#request_headers) * [htmx Response Headers](#response_headers) * [htmx Events](#events) * [htmx Extensions](/extensions) * [JavaScript API](#api) * [Configuration Options](#config) ## Core Attribute Reference {#attributes} The most common attributes when using htmx. <div class="info-table"> | Attribute | Description | |--------------------------------------------------|--------------------------------------------------------------------------------------------------------------------| | [`hx-get`](@/attributes/hx-get.md) | issues a `GET` to the specified URL | | [`hx-post`](@/attributes/hx-post.md) | issues a `POST` to the specified URL | | [`hx-on*`](@/attributes/hx-on.md) | handle events with inline scripts on elements | | [`hx-push-url`](@/attributes/hx-push-url.md) | push a URL into the browser location bar to create history | | [`hx-select`](@/attributes/hx-select.md) | select content to swap in from a response | | [`hx-select-oob`](@/attributes/hx-select-oob.md) | select content to swap in from a response, somewhere other than the target (out of band) | | [`hx-swap`](@/attributes/hx-swap.md) | controls how content will swap in (`outerHTML`, `beforeend`, `afterend`, ...) | | [`hx-swap-oob`](@/attributes/hx-swap-oob.md) | mark element to swap in from a response (out of band) | | [`hx-target`](@/attributes/hx-target.md) | specifies the target element to be swapped | | [`hx-trigger`](@/attributes/hx-trigger.md) | specifies the event that triggers the request | | [`hx-vals`](@/attributes/hx-vals.md) | add values to submit with the request (JSON format) | </div> ## Additional Attribute Reference {#attributes-additional} All other attributes available in htmx. <div class="info-table"> | Attribute | Description | |------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| | [`hx-boost`](@/attributes/hx-boost.md) | add [progressive enhancement](https://en.wikipedia.org/wiki/Progressive_enhancement) for links and forms | | [`hx-confirm`](@/attributes/hx-confirm.md) | shows a `confirm()` dialog before issuing a request | | [`hx-delete`](@/attributes/hx-delete.md) | issues a `DELETE` to the specified URL | | [`hx-disable`](@/attributes/hx-disable.md) | disables htmx processing for the given node and any children nodes | | [`hx-disabled-elt`](@/attributes/hx-disabled-elt.md) | adds the `disabled` attribute to the specified elements while a request is in flight | | [`hx-disinherit`](@/attributes/hx-disinherit.md) | control and disable automatic attribute inheritance for child nodes | | [`hx-encoding`](@/attributes/hx-encoding.md) | changes the request encoding type | | [`hx-ext`](@/attributes/hx-ext.md) | extensions to use for this element | | [`hx-headers`](@/attributes/hx-headers.md) | adds to the headers that will be submitted with the request | | [`hx-history`](@/attributes/hx-history.md) | prevent sensitive data being saved to the history cache | | [`hx-history-elt`](@/attributes/hx-history-elt.md) | the element to snapshot and restore during history navigation | | [`hx-include`](@/attributes/hx-include.md) | include additional data in requests | | [`hx-indicator`](@/attributes/hx-indicator.md) | the element to put the `htmx-request` class on during the request | | [`hx-inherit`](@/attributes/hx-inherit.md) | control and enable automatic attribute inheritance for child nodes if it has been disabled by default | | [`hx-params`](@/attributes/hx-params.md) | filters the parameters that will be submitted with a request | | [`hx-patch`](@/attributes/hx-patch.md) | issues a `PATCH` to the specified URL | | [`hx-preserve`](@/attributes/hx-preserve.md) | specifies elements to keep unchanged between requests | | [`hx-prompt`](@/attributes/hx-prompt.md) | shows a `prompt()` before submitting a request | | [`hx-put`](@/attributes/hx-put.md) | issues a `PUT` to the specified URL | | [`hx-replace-url`](@/attributes/hx-replace-url.md) | replace the URL in the browser location bar | | [`hx-request`](@/attributes/hx-request.md) | configures various aspects of the request | | [`hx-sync`](@/attributes/hx-sync.md) | control how requests made by different elements are synchronized | | [`hx-validate`](@/attributes/hx-validate.md) | force elements to validate themselves before a request | | [`hx-vars`](@/attributes/hx-vars.md) | adds values dynamically to the parameters to submit with the request (deprecated, please use [`hx-vals`](@/attributes/hx-vals.md)) | </div> ## CSS Class Reference {#classes} <div class="info-table"> | Class | Description | |-----------|-------------| | `htmx-added` | Applied to a new piece of content before it is swapped, removed after it is settled. | `htmx-indicator` | A dynamically generated class that will toggle visible (opacity:1) when a `htmx-request` class is present | `htmx-request` | Applied to either the element or the element specified with [`hx-indicator`](@/attributes/hx-indicator.md) while a request is ongoing | `htmx-settling` | Applied to a target after content is swapped, removed after it is settled. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md). | `htmx-swapping` | Applied to a target before any content is swapped, removed after it is swapped. The duration can be modified via [`hx-swap`](@/attributes/hx-swap.md). </div> ## HTTP Header Reference {#headers} ### Request Headers Reference {#request_headers} <div class="info-table"> | Header | Description | |--------|-------------| | `HX-Boosted` | indicates that the request is via an element using [hx-boost](@/attributes/hx-boost.md) | `HX-Current-URL` | the current URL of the browser | `HX-History-Restore-Request` | "true" if the request is for history restoration after a miss in the local history cache | `HX-Prompt` | the user response to an [hx-prompt](@/attributes/hx-prompt.md) | `HX-Request` | always "true" | `HX-Target` | the `id` of the target element if it exists | `HX-Trigger-Name` | the `name` of the triggered element if it exists | `HX-Trigger` | the `id` of the triggered element if it exists </div> ### Response Headers Reference {#response_headers} <div class="info-table"> | Header | Description | |------------------------------------------------------|-------------| | [`HX-Location`](@/headers/hx-location.md) | allows you to do a client-side redirect that does not do a full page reload | [`HX-Push-Url`](@/headers/hx-push-url.md) | pushes a new url into the history stack | [`HX-Redirect`](@/headers/hx-redirect.md) | can be used to do a client-side redirect to a new location | `HX-Refresh` | if set to "true" the client-side will do a full refresh of the page | [`HX-Replace-Url`](@/headers/hx-replace-url.md) | replaces the current URL in the location bar | `HX-Reswap` | allows you to specify how the response will be swapped. See [hx-swap](@/attributes/hx-swap.md) for possible values | `HX-Retarget` | a CSS selector that updates the target of the content update to a different element on the page | `HX-Reselect` | a CSS selector that allows you to choose which part of the response is used to be swapped in. Overrides an existing [`hx-select`](@/attributes/hx-select.md) on the triggering element | [`HX-Trigger`](@/headers/hx-trigger.md) | allows you to trigger client-side events | [`HX-Trigger-After-Settle`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the settle step | [`HX-Trigger-After-Swap`](@/headers/hx-trigger.md) | allows you to trigger client-side events after the swap step </div> ## Event Reference {#events} <div class="info-table"> | Event | Description | |-------|-------------| | [`htmx:abort`](@/events.md#htmx:abort) | send this event to an element to abort a request | [`htmx:afterOnLoad`](@/events.md#htmx:afterOnLoad) | triggered after an AJAX request has completed processing a successful response | [`htmx:afterProcessNode`](@/events.md#htmx:afterProcessNode) | triggered after htmx has initialized a node | [`htmx:afterRequest`](@/events.md#htmx:afterRequest) | triggered after an AJAX request has completed | [`htmx:afterSettle`](@/events.md#htmx:afterSettle) | triggered after the DOM has settled | [`htmx:afterSwap`](@/events.md#htmx:afterSwap) | triggered after new content has been swapped in | [`htmx:beforeCleanupElement`](@/events.md#htmx:beforeCleanupElement) | triggered before htmx [disables](@/attributes/hx-disable.md) an element or removes it from the DOM | [`htmx:beforeOnLoad`](@/events.md#htmx:beforeOnLoad) | triggered before any response processing occurs | [`htmx:beforeProcessNode`](@/events.md#htmx:beforeProcessNode) | triggered before htmx initializes a node | [`htmx:beforeRequest`](@/events.md#htmx:beforeRequest) | triggered before an AJAX request is made | [`htmx:beforeSwap`](@/events.md#htmx:beforeSwap) | triggered before a swap is done, allows you to configure the swap | [`htmx:beforeSend`](@/events.md#htmx:beforeSend) | triggered just before an ajax request is sent | [`htmx:beforeTransition`](@/events.md#htmx:beforeTransition) | triggered before the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) wrapped swap occurs | [`htmx:configRequest`](@/events.md#htmx:configRequest) | triggered before the request, allows you to customize parameters, headers | [`htmx:confirm`](@/events.md#htmx:confirm) | triggered after a trigger occurs on an element, allows you to cancel (or delay) issuing the AJAX request | [`htmx:historyCacheError`](@/events.md#htmx:historyCacheError) | triggered on an error during cache writing | [`htmx:historyCacheMiss`](@/events.md#htmx:historyCacheMiss) | triggered on a cache miss in the history subsystem | [`htmx:historyCacheMissError`](@/events.md#htmx:historyCacheMissError) | triggered on a unsuccessful remote retrieval | [`htmx:historyCacheMissLoad`](@/events.md#htmx:historyCacheMissLoad) | triggered on a successful remote retrieval | [`htmx:historyRestore`](@/events.md#htmx:historyRestore) | triggered when htmx handles a history restoration action | [`htmx:beforeHistorySave`](@/events.md#htmx:beforeHistorySave) | triggered before content is saved to the history cache | [`htmx:load`](@/events.md#htmx:load) | triggered when new content is added to the DOM | [`htmx:noSSESourceError`](@/events.md#htmx:noSSESourceError) | triggered when an element refers to a SSE event in its trigger, but no parent SSE source has been defined | [`htmx:onLoadError`](@/events.md#htmx:onLoadError) | triggered when an exception occurs during the onLoad handling in htmx | [`htmx:oobAfterSwap`](@/events.md#htmx:oobAfterSwap) | triggered after an out of band element as been swapped in | [`htmx:oobBeforeSwap`](@/events.md#htmx:oobBeforeSwap) | triggered before an out of band element swap is done, allows you to configure the swap | [`htmx:oobErrorNoTarget`](@/events.md#htmx:oobErrorNoTarget) | triggered when an out of band element does not have a matching ID in the current DOM | [`htmx:prompt`](@/events.md#htmx:prompt) | triggered after a prompt is shown | [`htmx:pushedIntoHistory`](@/events.md#htmx:pushedIntoHistory) | triggered after an url is pushed into history | [`htmx:responseError`](@/events.md#htmx:responseError) | triggered when an HTTP response error (non-`200` or `300` response code) occurs | [`htmx:sendAbort`](@/events.md#htmx:sendAbort) | triggered when a request is aborted | [`htmx:sendError`](@/events.md#htmx:sendError) | triggered when a network error prevents an HTTP request from happening | [`htmx:sseError`](@/events.md#htmx:sseError) | triggered when an error occurs with a SSE source | [`htmx:sseOpen`](/events#htmx:sseOpen) | triggered when a SSE source is opened | [`htmx:swapError`](@/events.md#htmx:swapError) | triggered when an error occurs during the swap phase | [`htmx:targetError`](@/events.md#htmx:targetError) | triggered when an invalid target is specified | [`htmx:timeout`](@/events.md#htmx:timeout) | triggered when a request timeout occurs | [`htmx:validation:validate`](@/events.md#htmx:validation:validate) | triggered before an element is validated | [`htmx:validation:failed`](@/events.md#htmx:validation:failed) | triggered when an element fails validation | [`htmx:validation:halted`](@/events.md#htmx:validation:halted) | triggered when a request is halted due to validation errors | [`htmx:xhr:abort`](@/events.md#htmx:xhr:abort) | triggered when an ajax request aborts | [`htmx:xhr:loadend`](@/events.md#htmx:xhr:loadend) | triggered when an ajax request ends | [`htmx:xhr:loadstart`](@/events.md#htmx:xhr:loadstart) | triggered when an ajax request starts | [`htmx:xhr:progress`](@/events.md#htmx:xhr:progress) | triggered periodically during an ajax request that supports progress events </div> ## JavaScript API Reference {#api} <div class="info-table"> | Method | Description | |-------|-------------| | [`htmx.addClass()`](@/api.md#addClass) | Adds a class to the given element | [`htmx.ajax()`](@/api.md#ajax) | Issues an htmx-style ajax request | [`htmx.closest()`](@/api.md#closest) | Finds the closest parent to the given element matching the selector | [`htmx.config`](@/api.md#config) | A property that holds the current htmx config object | [`htmx.createEventSource`](@/api.md#createEventSource) | A property holding the function to create SSE EventSource objects for htmx | [`htmx.createWebSocket`](@/api.md#createWebSocket) | A property holding the function to create WebSocket objects for htmx | [`htmx.defineExtension()`](@/api.md#defineExtension) | Defines an htmx [extension](https://htmx.org/extensions) | [`htmx.find()`](@/api.md#find) | Finds a single element matching the selector | [`htmx.findAll()` `htmx.findAll(elt, selector)`](@/api.md#find) | Finds all elements matching a given selector | [`htmx.logAll()`](@/api.md#logAll) | Installs a logger that will log all htmx events | [`htmx.logger`](@/api.md#logger) | A property set to the current logger (default is `null`) | [`htmx.off()`](@/api.md#off) | Removes an event listener from the given element | [`htmx.on()`](@/api.md#on) | Creates an event listener on the given element, returning it | [`htmx.onLoad()`](@/api.md#onLoad) | Adds a callback handler for the `htmx:load` event | [`htmx.parseInterval()`](@/api.md#parseInterval) | Parses an interval declaration into a millisecond value | [`htmx.process()`](@/api.md#process) | Processes the given element and its children, hooking up any htmx behavior | [`htmx.remove()`](@/api.md#remove) | Removes the given element | [`htmx.removeClass()`](@/api.md#removeClass) | Removes a class from the given element | [`htmx.removeExtension()`](@/api.md#removeExtension) | Removes an htmx [extension](https://htmx.org/extensions) | [`htmx.swap()`](@/api.md#swap) | Performs swapping (and settling) of HTML content | [`htmx.takeClass()`](@/api.md#takeClass) | Takes a class from other elements for the given element | [`htmx.toggleClass()`](@/api.md#toggleClass) | Toggles a class from the given element | [`htmx.trigger()`](@/api.md#trigger) | Triggers an event on an element | [`htmx.values()`](@/api.md#values) | Returns the input values associated with the given element </div> ## Configuration Reference {#config} Htmx has some configuration options that can be accessed either programmatically or declaratively. They are listed below: <div class="info-table"> | Config Variable | Info | |---------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `htmx.config.historyEnabled` | defaults to `true`, really only useful for testing | | `htmx.config.historyCacheSize` | defaults to 10 | | `htmx.config.refreshOnHistoryMiss` | defaults to `false`, if set to `true` htmx will issue a full page refresh on history misses rather than use an AJAX request | | `htmx.config.defaultSwapStyle` | defaults to `innerHTML` | | `htmx.config.defaultSwapDelay` | defaults to 0 | | `htmx.config.defaultSettleDelay` | defaults to 20 | | `htmx.config.includeIndicatorStyles` | defaults to `true` (determines if the indicator styles are loaded) | | `htmx.config.indicatorClass` | defaults to `htmx-indicator` | | `htmx.config.requestClass` | defaults to `htmx-request` | | `htmx.config.addedClass` | defaults to `htmx-added` | | `htmx.config.settlingClass` | defaults to `htmx-settling` | | `htmx.config.swappingClass` | defaults to `htmx-swapping` | | `htmx.config.allowEval` | defaults to `true`, can be used to disable htmx's use of eval for certain features (e.g. trigger filters) | | `htmx.config.allowScriptTags` | defaults to `true`, determines if htmx will process script tags found in new content | | `htmx.config.inlineScriptNonce` | defaults to `''`, meaning that no nonce will be added to inline scripts | | `htmx.config.inlineStyleNonce` | defaults to `''`, meaning that no nonce will be added to inline styles | | `htmx.config.attributesToSettle` | defaults to `["class", "style", "width", "height"]`, the attributes to settle during the settling phase | | `htmx.config.wsReconnectDelay` | defaults to `full-jitter` | | `htmx.config.wsBinaryType` | defaults to `blob`, the [the type of binary data](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) being received over the WebSocket connection | | `htmx.config.disableSelector` | defaults to `[hx-disable], [data-hx-disable]`, htmx will not process elements with this attribute on it or a parent | | `htmx.config.disableInheritance` | defaults to `false`. If it is set to `true`, the inheritance of attributes is completely disabled and you can explicitly specify the inheritance with the [hx-inherit](@/attributes/hx-inherit.md) attribute. | `htmx.config.withCredentials` | defaults to `false`, allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates | | `htmx.config.timeout` | defaults to 0, the number of milliseconds a request can take before automatically being terminated | | `htmx.config.scrollBehavior` | defaults to 'instant', the scroll behavior when using the [show](@/attributes/hx-swap.md#scrolling-scroll-show) modifier with `hx-swap`. The allowed values are `instant` (scrolling should happen instantly in a single jump), `smooth` (scrolling should animate smoothly) and `auto` (scroll behavior is determined by the computed value of [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)). | | `htmx.config.defaultFocusScroll` | if the focused element should be scrolled into view, defaults to false and can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier. | | `htmx.config.getCacheBusterParam` | defaults to false, if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId` | | `htmx.config.globalViewTransitions` | if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content. | | `htmx.config.methodsThatUseUrlParams` | defaults to `["get", "delete"]`, htmx will format requests with these methods by encoding their parameters in the URL, not the request body | | `htmx.config.selfRequestsOnly` | defaults to `true`, whether to only allow AJAX requests to the same domain as the current document | | `htmx.config.ignoreTitle` | defaults to `false`, if set to `true` htmx will not update the title of the document when a `title` tag is found in new content | | `htmx.config.scrollIntoViewOnBoost` | defaults to `true`, whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top. | | `htmx.config.triggerSpecsCache` | defaults to `null`, the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) | | `htmx.config.responseHandling` | the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error | | `htmx.config.allowNestedOobSwaps` | defaults to `true`, whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps). | </div> You can set them directly in javascript, or you can use a `meta` tag: ```html <meta name="htmx-config" content='{"defaultSwapStyle":"outerHTML"}'> ```
https://raw.githubusercontent.com/bigskysoftware/htmx/master/www/content/reference.md
content_reference.md
# πŸ—Ώ Surreal ### Tiny jQuery alternative for plain Javascript with inline [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour/)! ![cover](https://user-images.githubusercontent.com/24665/171092805-b41286b2-be4a-4aab-9ee6-d604699cc507.png) (Art by [shahabalizadeh](https://www.deviantart.com/shahabalizadeh)) <!-- <a href="https://github.com/gnat/surreal/archive/refs/heads/main.zip"><img src="https://img.shields.io/badge/Download%20.zip-ff9800?style=for-the-badge&color=%234400e5" alt="Download badge" /></a> <a href="https://github.com/gnat/surreal"><img src="https://img.shields.io/github/workflow/status/gnat/surreal/ci?label=ci&style=for-the-badge&color=%237d91ce" alt="CI build badge" /></a> <a href="https://github.com/gnat/surreal/releases"><img src="https://img.shields.io/github/workflow/status/gnat/surreal/release?label=Mini&style=for-the-badge&color=%237d91ce" alt="Mini build badge" /></a> <a href="https://github.com/gnat/surreal/blob/main/LICENSE"><img src="https://img.shields.io/github/license/gnat/surreal?style=for-the-badge&color=%234400e5" alt="License badge" /></a>--> ## Why does this exist? For devs who love ergonomics! You may appreciate Surreal if: * You want to stay as close as possible to Vanilla JS. * Hate typing `document.querySelector` over.. and over.. * Hate typing `addEventListener` over.. and over.. * Really wish `document.querySelectorAll` had Array functions.. * Really wish `this` would work in any inline `<script>` tag * Enjoyed using jQuery selector syntax. * [Animations, timelines, tweens](#-quick-start) with no extra libraries. * Only 320 lines. No build step. No dependencies. * Pairs well with [htmx](https://htmx.org) * Want fewer layers, less complexity. Are aware of the cargo cult. ✈️ ## ✨ What does it add to Javascript? * ⚑️ [Locality of Behavior (LoB)](https://htmx.org/essays/locality-of-behaviour/) Use `me()` inside `<script>` * No **.class** or **#id** needed! Get an element without creating a unique name. * `this` but much more flexible! * Want `me` in your CSS `<style>` tags, too? See our [companion script](https://github.com/gnat/css-scope-inline) * πŸ”— Call chaining, jQuery style. * ♻️ Functions work seamlessly on 1 element or arrays of elements! * All functions can use: `me()`, `any()`, `NodeList`, `HTMLElement` (..or arrays of these!) * Get 1 element: `me()` * ..or many elements: `any()` * `me()` or `any()` can chain with any Surreal function. * `me()` can be used directly as a single element (like `querySelector()` or `$()`) * `any()` can use: `for` / `forEach` / `filter` / `map` (like `querySelectorAll()` or `$()`) * πŸŒ— No forced style. Use: `classAdd` or `class_add` or `addClass` or `add_class` * Use `camelCase` (Javascript) or `snake_case` (Python, Rust, PHP, Ruby, SQL, CSS). ### πŸ€” Why use `me()` / `any()` instead of `$()` * πŸ’‘ Solves the classic jQuery bloat problem: Am I getting 1 element or an array of elements? * `me()` is guaranteed to return 1 element (or first found, or null). * `any()` is guaranteed to return an array (or empty array). * No more checks = write less code. Bonus: Reads more like self-documenting english. ## πŸ‘οΈ How does it look? Do surreal things with [Locality of Behavior](https://htmx.org/essays/locality-of-behaviour/) like: ```html <label for="file-input" > <div class="uploader"></div> <script> me().on("dragover", ev => { halt(ev); me(ev).classAdd('.hover'); console.log("Files in drop zone.") }) me().on("dragleave", ev => { halt(ev); me(ev).classRemove('.hover'); console.log("Files left drop zone.") }) me().on("drop", ev => { halt(ev); me(ev).classRemove('.hover').classAdd('.loading'); me('#file-input').attribute('files', ev.dataTransfer.files); me('#form').send('change') }) </script> </label> ``` See the [Live Example](https://gnat.github.io/surreal/example.html)! Then [view source](https://github.com/gnat/surreal/blob/main/example.html). ## 🎁 Install Surreal is only 320 lines. No build step. No dependencies. [πŸ“₯ Download](https://raw.githubusercontent.com/gnat/surreal/main/surreal.js) into your project, and add `<script src="/surreal.js"></script>` in your `<head>` Or, 🌐 via CDN: `<script src="https://cdnjs.cloudflare.com/ajax/libs/surreal/1.3.2/surreal.js"></script>` ## ⚑ Usage ### <a name="selectors"></a>πŸ”οΈ DOM Selection * Select **one** element: `me(...)` * Can be any of: * CSS selector: `".button"`, `"#header"`, `"h1"`, `"body > .block"` * Variables: `body`, `e`, `some_element` * Events: `event.currentTarget` will be used. * Surreal selectors: `me()`,`any()` * Choose the start location in the DOM with the 2nd arg. (Default: `document`) * πŸ”₯ `any('button', me('#header')).classAdd('red')` * Add `.red` to any `<button>` inside of `#header` * `me()` ⭐ Get parent element of `<script>` without a **.class** or **#id** ! * `me("body")` Gets `<body>` * `me(".button")` Gets the first `<div class="button">...</div>`. To get all of them use `any()` * Select **one or more** elements as an array: `any(...)` * Like `me()` but guaranteed to return an array (or empty array). * `any(".foo")` ⭐ Get all matching elements. * Convert between arrays of elements and single elements: `any(me())`, `me(any(".something"))` ### πŸ”₯ DOM Functions * ♻️ All functions work on single elements or arrays of elements. * πŸ”— Start a chain using `me()` and `any()` * 🟒 Style A `me().classAdd('red')` ⭐ Chain style. Recommended! * 🟠 Style B: `classAdd(me(), 'red')` * 🌐 Global conveniences help you write less code. * `globalsAdd()` will automatically warn you of any clobbering issues! * πŸ’€πŸ©Έ If you want no conveniences, or are a masochist, delete `globalsAdd()` * 🟒 `me().classAdd('red')` becomes `surreal.me().classAdd('red')` * 🟠 `classAdd(me(), 'red')` becomes `surreal.classAdd(surreal.me(), 'red')` See: [Quick Start](#quick-start) and [Reference](#reference) and [No Surreal Needed](#no-surreal) ## <a name="quick-start"></a>⚑ Quick Start * Add a class * `me().classAdd('red')` * `any("button").classAdd('red')` * Events * `me().on("click", ev => me(ev).fadeOut() )` * `any('button').on('click', ev => { me(ev).styles('color: red') })` * Run functions over elements. * `any('button').run(_ => { alert(_) })` * Styles / CSS * `me().styles('color: red')` * `me().styles({ 'color':'red', 'background':'blue' })` * Attributes * `me().attribute('active', true)` <a name="timelines"></a> #### Timeline animations without any libraries. ```html <div>I change color every second. <script> // On click, animate something new every second. me().on("click", async ev => { let el = me(ev) // Save target because async will lose it. me(el).styles({ "transition": "background 1s" }) await sleep(1000) me(el).styles({ "background": "red" }) await sleep(1000) me(el).styles({ "background": "green" }) await sleep(1000) me(el).styles({ "background": "blue" }) await sleep(1000) me(el).styles({ "background": "none" }) await sleep(1000) me(el).remove() }) </script> </div> ``` ```html <div>I fade out and remove myself. <script>me().on("click", ev => { me(ev).fadeOut() })</script> </div> ``` ```html <div>Change color every second. <script> // Run immediately. (async (e = me()) => { me(e).styles({ "transition": "background 1s" }) await sleep(1000) me(e).styles({ "background": "red" }) await sleep(1000) me(e).styles({ "background": "green" }) await sleep(1000) me(e).styles({ "background": "blue" }) await sleep(1000) me(e).styles({ "background": "none" }) await sleep(1000) me(e).remove() })() </script> </div> ``` ```html <script> // Run immediately, for every <button> globally! (async () => { any("button").fadeOut() })() </script> ``` #### Array methods ```js any('button')?.forEach(...) any('button')?.map(...) ``` ## <a name="reference"></a>πŸ‘οΈ Functions Looking for [DOM Selectors](#selectors)? Looking for stuff [we recommend doing in vanilla JS](#no-surreal)? ### 🧭 Legend * πŸ”— Chainable off `me()` and `any()` * 🌐 Global shortcut. * πŸ”₯ Runnable example. * πŸ”Œ Built-in Plugin ### πŸ‘οΈ At a glance * πŸ”— `run` * It's `forEach` but less wordy and works on single elements, too! * πŸ”₯ `me().run(e => { alert(e) })` * πŸ”₯ `any('button').run(e => { alert(e) })` * πŸ”— `remove` * πŸ”₯ `me().remove()` * πŸ”₯ `any('button').remove()` * πŸ”— `classAdd` πŸŒ— `class_add` πŸŒ— `addClass` πŸŒ— `add_class` * πŸ”₯ `me().classAdd('active')` * Leading `.` is **optional** * Same thing: `me().classAdd('active')` πŸŒ— `me().classAdd('.active')` * πŸ”— `classRemove` πŸŒ— `class_remove` πŸŒ— `removeClass` πŸŒ— `remove_class` * πŸ”₯ `me().classRemove('active')` * πŸ”— `classToggle` πŸŒ— `class_toggle` πŸŒ— `toggleClass` πŸŒ— `toggle_class` * πŸ”₯ `me().classToggle('active')` * πŸ”— `styles` * πŸ”₯ `me().styles('color: red')` Add style. * πŸ”₯ `me().styles({ 'color':'red', 'background':'blue' })` Add multiple styles. * πŸ”₯ `me().styles({ 'background':null })` Remove style. * πŸ”— `attribute` πŸŒ— `attributes` πŸŒ— `attr` * Get: πŸ”₯ `me().attribute('data-x')` * For single elements. * For many elements, wrap it in: `any(...).run(...)` or `any(...).forEach(...)` * Set: πŸ”₯`me().attribute('data-x', true)` * Set multiple: πŸ”₯ `me().attribute({ 'data-x':'yes', 'data-y':'no' })` * Remove: πŸ”₯ `me().attribute('data-x', null)` * Remove multiple: πŸ”₯ `me().attribute({ 'data-x': null, 'data-y':null })` * πŸ”— `send` πŸŒ— `trigger` * πŸ”₯ `me().send('change')` * πŸ”₯ `me().send('change', {'data':'thing'})` * Wraps `dispatchEvent` * πŸ”— `on` * πŸ”₯ `me().on('click', ev => { me(ev).styles('background', 'red') })` * Wraps `addEventListener` * πŸ”— `off` * πŸ”₯ `me().off('click', fn)` * Wraps `removeEventListener` * πŸ”— `offAll` * πŸ”₯ `me().offAll()` * πŸ”— `disable` * πŸ”₯ `me().disable()` * Easy alternative to `off()`. Disables click, key, submit events. * πŸ”— `enable` * πŸ”₯ `me().enable()` * Opposite of `disable()` * 🌐 `createElement` πŸŒ— `create_element` * πŸ”₯ `e_new = createElement("div"); me().prepend(e_new)` * Alias of [document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) * 🌐 `sleep` * πŸ”₯ `await sleep(1000, ev => { alert(ev) })` * `async` version of `setTimeout` * Wonderful for animation timelines. * 🌐 `halt` * πŸ”₯ `halt(event)` * When recieving an event, stop propagation, and prevent default actions (such as form submit). * Wrapper for [stopPropagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) and [preventDefault](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) * 🌐 `tick` * πŸ”₯ `await tick()` * `await` version of `rAF` / `requestAnimationFrame`. * Waits for 1 frame (browser paint). * Useful to guarantee CSS properties are applied, and events have propagated. * 🌐 `rAF` * πŸ”₯ `rAF(e => { return e })` * Calls after 1 frame (browser paint). Alias of [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) * Useful to guarantee CSS properties are applied, and events have propagated. * 🌐 `rIC` * πŸ”₯ `rIC(e => { return e })` * Calls when Javascript is idle. Alias of [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) * 🌐 `onloadAdd` πŸŒ— `onload_add` πŸŒ— `addOnload` πŸŒ— `add_onload` * πŸ”₯ `onloadAdd(_ => { alert("loaded!"); })` * πŸ”₯ `<script>let e = me(); onloadAdd(_ => { me(e).on("click", ev => { alert("clicked") }) })</script>` * Execute after the DOM is ready. Similar to jquery `ready()` * Add to `window.onload` while preventing overwrites of `window.onload` and predictable loading! * Alternatives: * Skip missing elements using `?.` example: `me("video")?.requestFullscreen()` * Place `<script>` after the loaded element. * See `me('-')` / `me('prev')` * πŸ”Œ `fadeOut` * See below * πŸ”Œ `fadeIn` * See below ### <a name="plugin-included"></a>πŸ”Œ Built-in Plugins ### Effects Build effects with `me().styles({...})` with timelines using [CSS transitioned `await` or callbacks](#timelines). Common effects included: * πŸ”— `fadeOut` πŸŒ— `fade_out` * Fade out and remove element. * Keep element with `remove=false`. * πŸ”₯ `me().fadeOut()` * πŸ”₯ `me().fadeOut(ev => { alert("Faded out!") }, 3000)` Over 3 seconds then call function. * πŸ”— `fadeIn` πŸŒ— `fade_in` * Fade in existing element which has `opacity: 0` * πŸ”₯ `me().fadeIn()` * πŸ”₯ `me().fadeIn(ev => { alert("Faded in!") }, 3000)` Over 3 seconds then call function. ## <a name="no-surreal"></a>βšͺ No Surreal Needed More often than not, Vanilla JS is the easiest way! Logging * πŸ”₯ `console.log()` `console.warn()` `console.error()` * Event logging: πŸ”₯ `monitorEvents(me())` See: [Chrome Blog](https://developer.chrome.com/blog/quickly-monitor-events-from-the-console-panel-2/) Benchmarking / Time It! * πŸ”₯ `console.time('name')` * πŸ”₯ `console.timeEnd('name')` Text / HTML Content * πŸ”₯ `me().textContent = "hello world"` * XSS Safe! See: [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) * πŸ”₯ `me().innerHTML = "<p>hello world</p>"` * πŸ”₯ `me().innerText = "hello world"` Children * πŸ”₯ `me().children` * πŸ”₯ `me().children.hidden = true` Append / Prepend elements. * πŸ”₯ `me().prepend(new_element)` * πŸ”₯ `me().appendChild(new_element)` * πŸ”₯ `me().insertBefore(element, other_element.firstChild)` * πŸ”₯ `me().insertAdjacentHTML("beforebegin", new_element)` AJAX (replace jQuery `ajax()`) * Use [htmx](https://htmx.org/) or [htmz](https://leanrada.com/htmz/) or [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or [XMLHttpRequest()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) * Example using `fetch()` ```js me().on("click", async event => { let e = me(event) // EXAMPLE 1: Hit an endpoint. if((await fetch("/webhook")).ok) console.log("Did the thing.") // EXAMPLE 2: Get content and replace me() try { let response = await fetch('/endpoint') if (response.ok) e.innerHTML = await response.text() else console.warn('fetch(): Bad response') } catch (error) { console.warn(`fetch(): ${error}`) } }) ``` * Example using `XMLHttpRequest()` ```js me().on("click", async event => { let e = me(event) // EXAMPLE 1: Hit an endpoint. var xhr = new XMLHttpRequest() xhr.open("GET", "/webhook") xhr.send() // EXAMPLE 2: Get content and replace me() var xhr = new XMLHttpRequest() xhr.open("GET", "/endpoint") xhr.onreadystatechange = () => { if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300) e.innerHTML = xhr.responseText } xhr.send() }) ``` ## πŸ’Ž Conventions & Tips * Many ideas can be done in HTML / CSS (ex: dropdowns) * `_` = for temporary or unused variables. Keep it short and sweet! * `e`, `el`, `elt` = element * `e`, `ev`, `evt` = event * `f`, `fn` = function #### Scope functions and variables inside `<script>` * ⭐ Use a block `{ let note = "hi"; function hey(text) { alert(text) }; me().on('click', ev => { hey(note) }) }` * `let` and `function` is scoped within `{ }` * ⭐ Use `me()` * `me().hey = (text) => { alert(text) }` * `me().on('click', (ev) => { me(ev).hey("hi") })` * ⭐ Use an event `me().on('click', ev => { /* add and call function here */ })` * Use an inline module: `<script type="module">` * Note: `me()` in modules will not see `parentElement`, explicit selectors are required: `me(".mybutton")` #### Select a void element like `<input type="text" />` * Use: `me('-')` or `me('prev')` or `me('previous')` * πŸ”₯ `<input type="text" /> <script>me('-').value = "hello"</script>` * Inspired by the CSS "next sibling" combinator `+` but in reverse `-` * Or, use a relative start. * πŸ”₯ `<form> <input type="text" n1 /> <script>me('[n1]', me()).value = "hello"</script> </form>` #### Ignore call chain when element is missing. * πŸ”₯ `me("#i_dont_exist")?.classAdd('active')` * No warnings: πŸ”₯ `me("#i_dont_exist", document, false)?.classAdd('active')` ## <a name="plugins"></a>πŸ”Œ Your own plugin Feel free to edit Surreal directly- but if you prefer, you can use plugins to effortlessly merge with new versions. ```javascript function pluginHello(e) { function hello(e, name="World") { console.log(`Hello ${name} from ${e}`) return e // Make chainable. } // Add sugar e.hello = (name) => { return hello(e, name) } } surreal.plugins.push(pluginHello) ``` Now use your function like: `me().hello("Internet")` * See the included `pluginEffects` for a more comprehensive example. * Your functions are added globally by `globalsAdd()` If you do not want this, add it to the `restricted` list. * Refer to an existing function to see how to make yours work with 1 or many elements. Make an [issue](https://github.com/gnat/surreal/issues) or [pull request](https://github.com/gnat/surreal/pulls) if you think people would like to use it! If it's useful enough we'll want it in core. ### ⭐ Awesome Surreal examples, plugins, and resources: [awesome-surreal](https://github.com/gnat/awesome-surreal) ! ## πŸ“šοΈ Inspired by * [jQuery](https://jquery.com/) for the chainable syntax we all love. * [BlingBling.js](https://github.com/argyleink/blingblingjs) for modern minimalism. * [Bliss.js](https://blissfuljs.com/) for a focus on single elements and extensibility. * [Hyperscript](https://hyperscript.org) for Locality of Behavior and awesome ergonomics. * Shout out to [Umbrella](https://umbrellajs.com/), [Cash](https://github.com/fabiospampinato/cash), [Zepto](https://zeptojs.com/)- Not quite as ergonomic. Requires build step to extend. ## 🌘 Future * Always more `example.html` goodies! * Automated browser testing perhaps with: * [Fava](https://github.com/fabiospampinato/fava). See: https://github.com/avajs/ava/issues/24#issuecomment-885949036 * [Ava](https://github.com/avajs/ava/blob/main/docs/recipes/browser-testing.md) * [jsdom](https://github.com/jsdom/jsdom) * [jsdom notes](https://github.com/jsdom/jsdom#executing-scripts)
https://raw.githubusercontent.com/AnswerDotAI/surreal/main/README.md
main_README.md
# 🌘 CSS Scope Inline ![cover](https://github.com/gnat/css-scope-inline/assets/24665/c4935c1b-34e3-4220-9d42-11f064999a57) (Art by [shahabalizadeh](https://www.artstation.com/artwork/zDgdd)) ## Why does this exist? * You want an easy inline vanilla CSS experience without Tailwind CSS. * Hate creating unique class names over.. and over.. to use once. * You want to co-locate your styles for ⚑️ [Locality of Behavior (LoB)](https://htmx.org/essays/locality-of-behaviour/) * You wish `this` would work in `<style>` tags. * Want all CSS features: [Nesting](https://caniuse.com/css-nesting), animations. Get scoped [`@keyframes`](https://github.com/gnat/css-scope-inline/blob/main/example.html#L50)! * You wish `@media` queries were shorter for [responsive design](https://tailwindcss.com/docs/responsive-design). * Only 16 lines. No build step. No dependencies. * Pairs well with [htmx](https://htmx.org) and [Surreal](https://github.com/gnat/surreal) * Want fewer layers, less complexity. Are aware of the cargo cult. ✈️ ✨ Want to also scope your `<script>` tags? See our companion project [Surreal](https://github.com/gnat/surreal) ## πŸ‘οΈ How does it look? ```html <div> <style> me { background: red; } /* ✨ this & self also work! */ me button { background: blue; } /* style child elements inline! */ </style> <button>I'm blue</button> </div> ``` See the [Live Example](https://gnat.github.io/css-scope-inline/example.html)! Then [view source](https://github.com/gnat/css-scope-inline/blob/main/example.html). ## 🌘 How does it work? This uses `MutationObserver` to monitor the DOM, and the moment a `<style>` tag is seen, it scopes the styles to whatever the parent element is. No flashing or popping. This method also leaves your existing styles untouched, allowing you to mix and match at your leisure. ## 🎁 Install βœ‚οΈ copy + πŸ“‹ paste the snippet into `<script>` in your `<head>` Or, [πŸ“₯ download](https://raw.githubusercontent.com/gnat/css-scope-inline/main/script.js) into your project, and add `<script src="script.js"></script>` in your `<head>` Or, 🌐 CDN: `<script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script>` ## πŸ€” Why consider this over Tailwind CSS? Use whatever you'd like, but there's a few advantages with this approach over Tailwind, Twind, UnoCSS: * No [repeated styles](https://tailwindcss.com/docs/reusing-styles) on child elements (..no [@apply](https://tailwindcss.com/docs/reusing-styles#extracting-classes-with-apply), no `[&>thing]` on each style). * No repeated prefixes for media queries, hover, focus, etc. * No visual noise on every `<div>`. Use a local `<style>` per group. * Share syntax between local and external styles. It's just CSS. * Regain your "inspect, play with styles, paste" workflow in your web browser! * No suffering from lost syntax highlighting on properties and units. * No high risk of eventually requiring a build step. * No chance of [deprecations](https://windicss.org/posts/sunsetting.html). 16 lines is infinitely maintainable. * No suffering from FOUC (a flash of unstyled content). * Zero friction movement of styles between inline and `.css` files. Just replace `me` * No special tooling or plugins to install. ## ⚑ Workflow Tips * Flat, 1 selector per line can be very short like Tailwind. See the examples. * Use just plain CSS variables in your design system. * Use the short `@media` queries for responsive design. * Mobile First (flow: **above** breakpoint): **🟒 None (xs)** `sm` `md` `lg` `xl` `xx` 🏁 * Desktop First (flow: **below** breakpoint): 🏁 `xs-` `sm-` `md-` `lg-` `xl-` **🟒 None (xx)** * 🟒 = No breakpoint. Default. See the [Live Example](https://gnat.github.io/css-scope-inline/example.html)! * Based on [Tailwind](https://tailwindcss.com/docs/responsive-design) breakpoints. We use `xx` not `2xl` to not break CSS highlighters. * Unlike Tailwind, you can [nest your @media styles](https://developer.chrome.com/articles/css-nesting/#nesting-media)! * Positional selectors may be easier using `div[n1]` for `<div n1>` instead of `div:nth-child(1)` * Try tools like- Auto complete styles: [VSCode](https://code.visualstudio.com/) or [Sublime](https://packagecontrol.io/packages/Emmet) ## πŸ‘οΈ CSS Scope Inline vs Tailwind CSS Showdowns ### Basics Tailwind verbosity goes up with more child elements. ```html <!-- CSS Scope Inline --> <div> <style> me { background: red; } me div { background: green; } me [n1] { background: yellow; } me [n2] { background: blue; } </style> red <div>green</div> <div>green</div> <div>green</div> <div n1>yellow</div> <div n2>blue</div> <div>green</div> <div>green</div> </div> <!-- Tailwind --> <div class="bg-[red]"> red <div class="bg-[green]">green</div> <div class="bg-[green]">green</div> <div class="bg-[green]">green</div> <div class="bg-[yellow]">yellow</div> <div class="bg-[blue]">blue</div> <div class="bg-[green]">green</div> <div class="bg-[green]">green</div> </div> ``` ### CSS variables and child elements At first glance, **Tailwind Example 2** looks very promising! Exciting ...but: * πŸ”΄ **Every child style requires an explicit selector.** * Tailwinds' shorthand advantages sadly disappear. * Any more child styles added in Tailwind will become longer than vanilla CSS. * This limited example is the best case scenario for Tailwind. * πŸ”΄ Not visible on github: **no highlighting for properties and units** begins to be painful. ```html <!doctype html> <html> <head> <style> :root { --color-1: hsl(0 0% 88%); --color-1-active: hsl(214 20% 70%); } </style> <script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script> </head> <body> <!-- CSS Scope Inline --> <div> <style> me { margin:8px 6px; } me div a { display:block; padding:8px 12px; margin:10px 0; background:var(--color-1); border-radius:10px; text-align:center; } me div a:hover { background:var(--color-1-active); color:white; } </style> <div><a href="#">Home</a></div> <div><a href="#">Team</a></div> <div><a href="#">Profile</a></div> <div><a href="#">Settings</a></div> <div><a href="#">Log Out</a></div> </div> <!-- Tailwind Example 1 --> <div class="mx-2 my-4"> <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Home</a></div> <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Team</a></div> <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Profile</a></div> <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Settings</a></div> <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Log Out</a></div> </div> <!-- Tailwind Example 2 --> <div class="mx-2 my-4 [&_div_a]:block [&_div_a]:py-2 [&_div_a]:px-3 [&_div_a]:my-2 [&_div_a]:bg-[--color-1] [&_div_a]:rounded-lg [&_div_a]:text-center [&_div_a:hover]:bg-[--color-1-active] [&_div_a:hover]:text-white"> <div><a href="#">Home</a></div> <div><a href="#">Team</a></div> <div><a href="#">Profile</a></div> <div><a href="#">Settings</a></div> <div><a href="#">Log Out</a></div> </div> </body> </html> ``` ## πŸ”Ž Technical FAQ * Why do you use `querySelectorAll()` and not just process the `MutationObserver` results directly? * This was indeed the original design; it will work well up until you begin recieving subtrees (ex: DOM swaps with [htmx](https://htmx.org), ajax, jquery, etc.) which requires walking all subtree elements to ensure we do not miss a `<style>`. This unfortunately involves re-scanning thousands of repeated elements. This is why `querySelectorAll()` ends up the performance (and simplicity) winner.
https://raw.githubusercontent.com/gnat/css-scope-inline/main/README.md
main_README.md
# 🌟 Starlette Quick Manual <!-- originally from bofeng.github.io --> 2020-02-09 Starlette is the ASGI web framework used as the foundation of FastHTML. Listed here are some Starlette features FastHTML developers can use directly, since the `FastHTML` class inherits from the `Starlette` class (but note that FastHTML has its own customised `RouteX` and `RouterX` classes for routing, to handle FT element trees etc). ## Get uploaded file content ``` async def handler(request): inp = await request.form() uploaded_file = inp["filename"] filename = uploaded_file.filename # abc.png content_type = uploaded.content_type # MIME type, e.g. image/png content = await uploaded_file.read() # image content ``` ## Return a customized response (status code and headers) ``` import json from starlette.responses import Response async def handler(request): data = { "name": "Bo" } return Response(json.dumps(data), media_type="application/json") ``` `Response` takes `status_code`, `headers` and `media_type`, so if we want to change a response's status code, we can do: ``` return Response(content, statu_code=404) ``` And customized headers: ``` headers = { "x-extra-key": "value" } return Response(content, status_code=200, headers=headers) ``` ## Redirect ``` from starlette.responses import RedirectResponse async handler(request): # Customize status_code: # 301: permanent redirect # 302: temporary redirect # 303: see others # 307: temporary redirect (default) return RedirectResponse(url=url, status_code=303) ``` ## Request context ### URL Object: `request.url` * Get request full url: `url = str(request.url)` * Get scheme: `request.url.scheme` (http, https, ws, wss) * Get netloc: `request.url.netloc`, e.g.: example.com:8080 * Get path: `request.url.path`, e.g.: /search * Get query string: `request.url.query`, e.g.: kw=hello * Get hostname: `request.url.hostname`, e.g.: example.com * Get port: `request.url.port`, e.g.: 8080 * If using secure scheme: `request.url.is_secure`, True is schme is `https` or `wss` ### Headers: `request.headers` ``` { 'host': 'example.com:8080', 'connection': 'keep-alive', 'cache-control': 'max-age=0', 'sec-ch-ua': 'Google Chrome 80', 'dnt': '1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) ...', 'sec-fetch-dest': 'document', 'accept': 'text/html,image/apng,*/*;q=0.8;v=b3;q=0.9', 'sec-origin-policy': '0', 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '?1', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6', 'cookie': 'session=eyJhZG1pbl91c2_KiQ...' } ``` ### Client: `request.client` * `request.client.host`: get client sock IP * `request.client.port`: get client sock port ### Method: `request.method` * `request.method`: GET, POST, etc. ### Get Data * `await request.body()`: get raw data from body * `await request.json()`: get passed data and parse it as JSON * `await request.form()`: get posted data and pass it as dictionary ### Scope: `request.scope` ``` { 'type': 'http', 'http_version': '1.1', 'server': ('127.0.0.1', 9092), 'client': ('127.0.0.1', 53102), 'scheme': 'https', 'method': 'GET', 'root_path': '', 'path': '/', 'raw_path': b'/', 'query_string': b'kw=hello', 'headers': [ (b'host', b'example.com:8080'), (b'connection', b'keep-alive'), (b'cache-control', b'max-age=0'), ... ], 'app': <starlette.applications.Starlette object at 0x1081bd650>, 'session': {'uid': '57ba03ea7333f72a25f837cf'}, 'router': <starlette.routing.Router object at 0x1081bd6d0>, 'endpoint': <class 'app.index.Index'>, 'path_params': {} } ``` ## Put varaible in request & app scope ``` app.state.dbconn = get_db_conn() request.state.start_time = time.time() # use app-scope state variable in a request request.app.state.dbconn ``` ## Utility functions ### Use `State` to wrap a dictionary ``` from starlette.datastructures import State data = { "name": "Bo" } print(data["name"]) # now wrap it with State function wrapped = State(data) # You can use the dot syntaxt, but can't use `wrapped["name"]` any more. print(wrapped.name) ``` ### login_required wrapper function NB: This is easier to do in FastHTML using Beforeware. ``` import functools from starlette.endpoints import HTTPEndpoint from starlette.responses import Response def login_required(login_url="/signin"): def decorator(handler): @functools.wraps(handler) async def new_handler(obj, req, *args, **kwargs): user = req.session.get("login_user") if user is None: return seeother(login_url) return await handler(obj, req, *args, **kwargs) return new_handler return decorator class MyAccount(HTTPEndpiont): @login_required() async def get(self, request): # some logic here content = "hello" return Response(content) ``` ## Exceptions Handle exception and customize 403, 404, 503, 500 page: ``` from starlette.exceptions import HTTPException async def exc_handle_403(request, exc): return HTMLResponse("My 403 page", status_code=exc.status_code) async def exc_handle_404(request, exc): return HTMLResponse("My 404 page", status_code=exc.status_code) async def exc_handle_503(request, exc): return HTMLResponse("Failed, please try it later", status_code=exc.status_code) # error is not exception, 500 is server side unexpected error, all other status code will be treated as Exception async def err_handle_500(request, exc): import traceback Log.error(traceback.format_exc()) return HTMLResponse("My 500 page", status_code=500) # To add handler, we can add either status_code or Exception itself as key exception_handlers = { 403: exc_handle_403, 404: exc_handle_404, 503: exc_handle_503, 500: err_handle_500, #HTTPException: exc_handle_500, } app = Starlette(routes=routes, exception_handlers=exception_handlers) ``` ## Background Task ### Put some async task as background task ``` import aiofiles from starlette.background import BackgroundTask from starlette.responses import Response aiofiles_remove = aiofiles.os.wrap(os.remove) async def del_file(fpath): await aiofiles_remove(fpath) async def handler(request): content = "" fpath = "/tmp/tmpfile.txt" task = BackgroundTask(del_file, fpath=fpath) return Response(content, background=task) ``` ### Put multiple tasks as background task ``` from starlette.background import BackgroundTasks async def task1(name): pass async def task2(email): pass async def handler(request): tasks = BackgroundTasks() tasks.add_task(task1, name="John") tasks.add_task(task2, email="[email protected]") content = "" return Response(content, background=tasks) ``` ## Write middleware There are 2 ways to write middleware: ### Define `__call__` function: ``` class MyMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): # see above scope dictionary as reference headers = dict(scope["headers"]) # do something # pass to next middleware return await self.app(scope, receive, send) ``` ### Use `BaseHTTPMiddleware` ``` from starlette.middleware.base import BaseHTTPMiddleware class CustomHeaderMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # do something before pass to next middleware response = await call_next(request) # do something after next middleware returned response.headers['X-Author'] = 'John' return response ```
https://gist.githubusercontent.com/jph00/e91192e9bdc1640f5421ce3c904f2efb/raw/61a2774912414029edaf1a55b506f0e283b93c46/starlette-quick.md
61a2774912414029edaf1a55b506f0e283b93c46_starlette-quick.md
# fasthtml Module Documentation ## fasthtml.authmw - `class BasicAuthMiddleware` - `def __init__(self, app, cb, skip)` - `def __call__(self, scope, receive, send)` - `def authenticate(self, conn)` ## fasthtml.cli - `@call_parse def railway_link()` Link the current directory to the current project's Railway service - `@call_parse def railway_deploy(name, mount)` Deploy a FastHTML app to Railway ## fasthtml.components > `ft_html` and `ft_hx` functions to add some conveniences to `ft`, along with a full set of basic HTML components, and functions to work with forms and `FT` conversion - `def show(ft, *rest)` Renders FT Components into HTML within a Jupyter notebook. - `def File(fname)` Use the unescaped text in file `fname` directly - `def fill_form(form, obj)` Fills named items in `form` using attributes in `obj` - `def fill_dataclass(src, dest)` Modifies dataclass in-place and returns it - `def find_inputs(e, tags, **kw)` Recursively find all elements in `e` with `tags` and attrs matching `kw` - `def html2ft(html, attr1st)` Convert HTML to an `ft` expression - `def sse_message(elm, event)` Convert element `elm` into a format suitable for SSE streaming ## fasthtml.core > The `FastHTML` subclass of `Starlette`, along with the `RouterX` and `RouteX` classes it automatically uses. - `def parsed_date(s)` Convert `s` to a datetime - `def snake2hyphens(s)` Convert `s` from snake case to hyphenated and capitalised - `@dataclass class HtmxHeaders` - `def __bool__(self)` - `def __init__(self, boosted, current_url, history_restore_request, prompt, request, target, trigger_name, trigger)` - `@dataclass class HttpHeader` - `def __init__(self, k, v)` - `@use_kwargs_dict(**htmx_resps) def HtmxResponseHeaders(**kwargs)` HTMX response headers - `def form2dict(form)` Convert starlette form data to a dict - `def parse_form(req)` Starlette errors on empty multipart forms, so this checks for that situation - `def flat_xt(lst)` Flatten lists - `class Beforeware` - `def __init__(self, f, skip)` - `def EventStream(s)` Create a text/event-stream response from `s` - `def flat_tuple(o)` Flatten lists - `def noop_body(c, req)` Default Body wrap function which just returns the content - `def respond(req, heads, bdy)` Default FT response creation function - `class Redirect` Use HTMX or Starlette RedirectResponse as required to redirect to `loc` - `def __init__(self, loc)` - `def __response__(self, req)` - `def qp(p, **kw)` Add parameters kw to path p - `def def_hdrs(htmx, surreal)` Default headers for a FastHTML app - `class FastHTML` - `def __init__(self, debug, routes, middleware, title, exception_handlers, on_startup, on_shutdown, lifespan, hdrs, ftrs, exts, before, after, surreal, htmx, default_hdrs, sess_cls, secret_key, session_cookie, max_age, sess_path, same_site, sess_https_only, sess_domain, key_fname, body_wrap, htmlkw, nb_hdrs, **bodykw)` - `def add_route(self, route)` - `@patch def ws(self, path, conn, disconn, name, middleware)` Add a websocket route at `path` - `def nested_name(f)` Get name of function `f` using '_' to join nested function names - `@patch def route(self, path, methods, name, include_in_schema, body_wrap)` Add a route at `path` - `def serve(appname, app, host, port, reload, reload_includes, reload_excludes)` Run the app in an async server, with live reload set as the default. - `class Client` A simple httpx ASGI client that doesn't require `async` - `def __init__(self, app, url)` - `class RouteFuncs` - `def __init__(self)` - `def __setattr__(self, name, value)` - `def __getattr__(self, name)` - `def __dir__(self)` - `class APIRouter` Add routes to an app - `def __init__(self, prefix, body_wrap)` - `def __call__(self, path, methods, name, include_in_schema, body_wrap)` Add a route at `path` - `def __getattr__(self, name)` - `def to_app(self, app)` Add routes to `app` - `def ws(self, path, conn, disconn, name, middleware)` Add a websocket route at `path` - `def cookie(key, value, max_age, expires, path, domain, secure, httponly, samesite)` Create a 'set-cookie' `HttpHeader` - `@patch def static_route_exts(self, prefix, static_path, exts)` Add a static route at URL path `prefix` with files from `static_path` and `exts` defined by `reg_re_param()` - `@patch def static_route(self, ext, prefix, static_path)` Add a static route at URL path `prefix` with files from `static_path` and single `ext` (including the '.') - `class MiddlewareBase` - `def __call__(self, scope, receive, send)` - `class FtResponse` Wrap an FT response with any Starlette `Response` - `def __init__(self, content, status_code, headers, cls, media_type)` - `def __response__(self, req)` ## fasthtml.fastapp > The `fast_app` convenience wrapper - `def fast_app(db_file, render, hdrs, ftrs, tbls, before, middleware, live, debug, routes, exception_handlers, on_startup, on_shutdown, lifespan, default_hdrs, pico, surreal, htmx, exts, secret_key, key_fname, session_cookie, max_age, sess_path, same_site, sess_https_only, sess_domain, htmlkw, bodykw, reload_attempts, reload_interval, static_path, body_wrap, nb_hdrs, **kwargs)` Create a FastHTML or FastHTMLWithLiveReload app. ## fasthtml.js > Basic external Javascript lib wrappers - `def light_media(css)` Render light media for day mode views - `def dark_media(css)` Render dark media for night mode views - `def MarkdownJS(sel)` Implements browser-based markdown rendering. - `def HighlightJS(sel, langs, light, dark)` Implements browser-based syntax highlighting. Usage example [here](/tutorials/quickstart_for_web_devs.html#code-highlighting). - `def MermaidJS(sel, theme)` Implements browser-based Mermaid diagram rendering. ## fasthtml.jupyter > Use FastHTML in Jupyter notebooks - `def nb_serve(app, log_level, port, host, **kwargs)` Start a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level` - `def nb_serve_async(app, log_level, port, host, **kwargs)` Async version of `nb_serve` - `def is_port_free(port, host)` Check if `port` is free on `host` - `def wait_port_free(port, host, max_wait)` Wait for `port` to be free on `host` - `class JupyUvi` Start and stop a Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level` - `def __init__(self, app, log_level, host, port, start, **kwargs)` - `def start(self)` - `def stop(self)` - `class JupyUviAsync` Start and stop an async Jupyter compatible uvicorn server with ASGI `app` on `port` with `log_level` - `def __init__(self, app, log_level, host, port, **kwargs)` - `def start(self)` - `def stop(self)` - `def HTMX(path, app, host, port, height, link, iframe)` An iframe which displays the HTMX application in a notebook. ## fasthtml.live_reload - `class FastHTMLWithLiveReload` `FastHTMLWithLiveReload` enables live reloading. This means that any code changes saved on the server will automatically trigger a reload of both the server and browser window. How does it work? - a websocket is created at `/live-reload` - a small js snippet `LIVE_RELOAD_SCRIPT` is injected into each webpage - this snippet connects to the websocket at `/live-reload` and listens for an `onclose` event - when the `onclose` event is detected the browser is reloaded Why do we listen for an `onclose` event? When code changes are saved the server automatically reloads if the --reload flag is set. The server reload kills the websocket connection. The `onclose` event serves as a proxy for "developer has saved some changes". Usage >>> from fasthtml.common import * >>> app = FastHTMLWithLiveReload() Run: serve() - `def __init__(self, *args, **kwargs)` ## fasthtml.oauth > Basic scaffolding for handling OAuth - `class GoogleAppClient` A `WebApplicationClient` for Google oauth2 - `def __init__(self, client_id, client_secret, code, scope, **kwargs)` - `@classmethod def from_file(cls, fname, code, scope, **kwargs)` - `class GitHubAppClient` A `WebApplicationClient` for GitHub oauth2 - `def __init__(self, client_id, client_secret, code, scope, **kwargs)` - `class HuggingFaceClient` A `WebApplicationClient` for HuggingFace oauth2 - `def __init__(self, client_id, client_secret, code, scope, state, **kwargs)` - `class DiscordAppClient` A `WebApplicationClient` for Discord oauth2 - `def __init__(self, client_id, client_secret, is_user, perms, scope, **kwargs)` - `def login_link(self)` - `def parse_response(self, code)` - `class Auth0AppClient` A `WebApplicationClient` for Auth0 OAuth2 - `def __init__(self, domain, client_id, client_secret, code, scope, redirect_uri, **kwargs)` - `def login_link(self, req)` - `@patch def login_link(self, redirect_uri, scope, state)` Get a login link for this client - `def redir_url(request, redir_path, scheme)` Get the redir url for the host in `request` - `@patch def parse_response(self, code, redirect_uri)` Get the token from the oauth2 server response - `@patch def get_info(self, token)` Get the info for authenticated user - `@patch def retr_info(self, code, redirect_uri)` Combines `parse_response` and `get_info` - `@patch def retr_id(self, code, redirect_uri)` Call `retr_info` and then return id/subscriber value - `class OAuth` - `def __init__(self, app, cli, skip, redir_path, error_path, logout_path, login_path, https, http_patterns)` - `def redir_login(self, session)` - `def redir_url(self, req)` - `def login_link(self, req, scope, state)` - `def check_invalid(self, req, session, auth)` - `def logout(self, session)` - `def get_auth(self, info, ident, session, state)` ## fasthtml.pico > Basic components for generating Pico CSS tags - `@delegates(ft_hx, keep=True) def Card(*c, **kwargs)` A PicoCSS Card, implemented as an Article with optional Header and Footer - `@delegates(ft_hx, keep=True) def Group(*c, **kwargs)` A PicoCSS Group, implemented as a Fieldset with role 'group' - `@delegates(ft_hx, keep=True) def Search(*c, **kwargs)` A PicoCSS Search, implemented as a Form with role 'search' - `@delegates(ft_hx, keep=True) def Grid(*c, **kwargs)` A PicoCSS Grid, implemented as child Divs in a Div with class 'grid' - `@delegates(ft_hx, keep=True) def DialogX(*c, **kwargs)` A PicoCSS Dialog, with children inside a Card - `@delegates(ft_hx, keep=True) def Container(*args, **kwargs)` A PicoCSS Container, implemented as a Main with class 'container' ## fasthtml.svg > Simple SVG FT elements - `def Svg(*args, **kwargs)` An SVG tag; xmlns is added automatically, and viewBox defaults to height and width if not provided - `@delegates(ft_hx) def ft_svg(tag, *c, **kwargs)` Create a standard `FT` element with some SVG-specific attrs - `@delegates(ft_svg) def Rect(width, height, x, y, fill, stroke, stroke_width, rx, ry, **kwargs)` A standard SVG `rect` element - `@delegates(ft_svg) def Circle(r, cx, cy, fill, stroke, stroke_width, **kwargs)` A standard SVG `circle` element - `@delegates(ft_svg) def Ellipse(rx, ry, cx, cy, fill, stroke, stroke_width, **kwargs)` A standard SVG `ellipse` element - `def transformd(translate, scale, rotate, skewX, skewY, matrix)` Create an SVG `transform` kwarg dict - `@delegates(ft_svg) def Line(x1, y1, x2, y2, stroke, w, stroke_width, **kwargs)` A standard SVG `line` element - `@delegates(ft_svg) def Polyline(*args, **kwargs)` A standard SVG `polyline` element - `@delegates(ft_svg) def Polygon(*args, **kwargs)` A standard SVG `polygon` element - `@delegates(ft_svg) def Text(*args, **kwargs)` A standard SVG `text` element - `class PathFT` - `def M(self, x, y)` Move to. - `def L(self, x, y)` Line to. - `def H(self, x)` Horizontal line to. - `def V(self, y)` Vertical line to. - `def Z(self)` Close path. - `def C(self, x1, y1, x2, y2, x, y)` Cubic BΓ©zier curve. - `def S(self, x2, y2, x, y)` Smooth cubic BΓ©zier curve. - `def Q(self, x1, y1, x, y)` Quadratic BΓ©zier curve. - `def T(self, x, y)` Smooth quadratic BΓ©zier curve. - `def A(self, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, x, y)` Elliptical Arc. - `def SvgOob(*args, **kwargs)` Wraps an SVG shape as required for an HTMX OOB swap - `def SvgInb(*args, **kwargs)` Wraps an SVG shape as required for an HTMX inband swap ## fasthtml.xtend > Simple extensions to standard HTML components, such as adding sensible defaults - `@delegates(ft_hx, keep=True) def A(*c, **kwargs)` An A tag; `href` defaults to '#' for more concise use with HTMX - `@delegates(ft_hx, keep=True) def AX(txt, hx_get, target_id, hx_swap, href, **kwargs)` An A tag with just one text child, allowing hx_get, target_id, and hx_swap to be positional params - `@delegates(ft_hx, keep=True) def Form(*c, **kwargs)` A Form tag; identical to plain `ft_hx` version except default `enctype='multipart/form-data'` - `@delegates(ft_hx, keep=True) def Hidden(value, id, **kwargs)` An Input of type 'hidden' - `@delegates(ft_hx, keep=True) def CheckboxX(checked, label, value, id, name, **kwargs)` A Checkbox optionally inside a Label, preceded by a `Hidden` with matching name - `@delegates(ft_html, keep=True) def Script(code, **kwargs)` A Script tag that doesn't escape its code - `@delegates(ft_html, keep=True) def Style(*c, **kwargs)` A Style tag that doesn't escape its code - `def double_braces(s)` Convert single braces to double braces if next to special chars or newline - `def undouble_braces(s)` Convert double braces to single braces if next to special chars or newline - `def loose_format(s, **kw)` String format `s` using `kw`, without being strict about braces outside of template params - `def ScriptX(fname, src, nomodule, type, _async, defer, charset, crossorigin, integrity, **kw)` A `script` element with contents read from `fname` - `def replace_css_vars(css, pre, **kwargs)` Replace `var(--)` CSS variables with `kwargs` if name prefix matches `pre` - `def StyleX(fname, **kw)` A `style` element with contents read from `fname` and variables replaced from `kw` - `def Nbsp()` A non-breaking space - `def Surreal(code)` Wrap `code` in `domReadyExecute` and set `m=me()` and `p=me('-')` - `def On(code, event, sel, me)` An async surreal.js script block event handler for `event` on selector `sel,p`, making available parent `p`, event `ev`, and target `e` - `def Prev(code, event)` An async surreal.js script block event handler for `event` on previous sibling, with same vars as `On` - `def Now(code, sel)` An async surreal.js script block on selector `me(sel)` - `def AnyNow(sel, code)` An async surreal.js script block on selector `any(sel)` - `def run_js(js, id, **kw)` Run `js` script, auto-generating `id` based on name of caller if needed, and js-escaping any `kw` params - `def jsd(org, repo, root, path, prov, typ, ver, esm, **kwargs)` jsdelivr `Script` or CSS `Link` tag, or URL - `@delegates(ft_hx, keep=True) def Titled(title, *args, **kwargs)` An HTML partial containing a `Title`, and `H1`, and any provided children - `def Socials(title, site_name, description, image, url, w, h, twitter_site, creator, card)` OG and Twitter social card headers - `def Favicon(light_icon, dark_icon)` Light and dark favicon headers
https://docs.fastht.ml/apilist.txt
docs.fastht.ml_apilist.txt
from asyncio import sleep from fasthtml.common import * app = FastHTML(exts='ws') rt = app.route def mk_inp(): return Input(id='msg') nid = 'notifications' @rt('/') async def get(): cts = Div( Div(id=nid), Form(mk_inp(), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) async def on_connect(send): await send(Div('Hello, you have connected', id=nid)) async def on_disconnect( ): print('Disconnected!') @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str, send): await send(Div('Hello ' + msg, id=nid)) await sleep(2) return Div('Goodbye ' + msg, id=nid), mk_inp() serve()
https://raw.githubusercontent.com/AnswerDotAI/fasthtml/main/examples/basic_ws.py
examples_basic_ws.py
### # Walkthrough of an idiomatic fasthtml app ### # This fasthtml app includes functionality from fastcore, starlette, fastlite, and fasthtml itself. # Run with: `python adv_app.py` # Importing from `fasthtml.common` brings the key parts of all of these together. # For simplicity, you can just `from fasthtml.common import *`: from fasthtml.common import * # ...or you can import everything into a namespace: # from fasthtml import common as fh # ...or you can import each symbol explicitly (which we're commenting out here but including for completeness): """ from fasthtml.common import ( # These are the HTML components we use in this app A, AX, Button, Card, CheckboxX, Container, Div, Form, Grid, Group, H1, H2, Hidden, Input, Li, Main, Script, Style, Textarea, Title, Titled, Ul, # These are FastHTML symbols we'll use Beforeware, FastHTML, fast_app, SortableJS, fill_form, picolink, serve, # These are from Starlette, Fastlite, fastcore, and the Python stdlib FileResponse, NotFoundError, RedirectResponse, database, patch, dataclass ) """ from hmac import compare_digest # You can use any database you want; it'll be easier if you pick a lib that supports the MiniDataAPI spec. # Here we are using SQLite, with the FastLite library, which supports the MiniDataAPI spec. db = database('data/utodos.db') # The `t` attribute is the table collection. The `todos` and `users` tables are not created if they don't exist. # Instead, you can use the `create` method to create them if needed. todos,users = db.t.todos,db.t.users if todos not in db.t: # You can pass a dict, or kwargs, to most MiniDataAPI methods. users.create(dict(name=str, pwd=str), pk='name') todos.create(id=int, title=str, done=bool, name=str, details=str, priority=int, pk='id') # Although you can just use dicts, it can be helpful to have types for your DB objects. # The `dataclass` method creates that type, and stores it in the object, so it will use it for any returned items. Todo,User = todos.dataclass(),users.dataclass() # Any Starlette response class can be returned by a FastHTML route handler. # In that case, FastHTML won't change it at all. # Status code 303 is a redirect that can change POST to GET, so it's appropriate for a login page. login_redir = RedirectResponse('/login', status_code=303) # The `before` function is a *Beforeware* function. These are functions that run before a route handler is called. def before(req, sess): # This sets the `auth` attribute in the request scope, and gets it from the session. # The session is a Starlette session, which is a dict-like object which is cryptographically signed, # so it can't be tampered with. # The `auth` key in the scope is automatically provided to any handler which requests it, and can not # be injected by the user using query params, cookies, etc, so it should be secure to use. auth = req.scope['auth'] = sess.get('auth', None) # If the session key is not there, it redirects to the login page. if not auth: return login_redir # `xtra` is part of the MiniDataAPI spec. It adds a filter to queries and DDL statements, # to ensure that the user can only see/edit their own todos. todos.xtra(name=auth) markdown_js = """ import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js"; proc_htmx('.markdown', e => e.innerHTML = marked.parse(e.textContent)); """ # We will use this in our `exception_handlers` dict def _not_found(req, exc): return Titled('Oh no!', Div('We could not find that page :(')) # To create a Beforeware object, we pass the function itself, and optionally a list of regexes to skip. bware = Beforeware(before, skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', '/login']) # The `FastHTML` class is a subclass of `Starlette`, so you can use any parameters that `Starlette` accepts. # In addition, you can add your Beforeware here, and any headers you want included in HTML responses. # FastHTML includes the "HTMX" and "Surreal" libraries in headers, unless you pass `default_hdrs=False`. app = FastHTML(before=bware, # These are the same as Starlette exception_handlers, except they also support `FT` results exception_handlers={404: _not_found}, # PicoCSS is a particularly simple CSS framework, with some basic integration built in to FastHTML. # `picolink` is pre-defined with the header for the PicoCSS stylesheet. # You can use any CSS framework you want, or none at all. hdrs=(picolink, # `Style` is an `FT` object, which are 3-element lists consisting of: # (tag_name, children_list, attrs_dict). # FastHTML composes them from trees and auto-converts them to HTML when needed. # You can also use plain HTML strings in handlers and headers, # which will be auto-escaped, unless you use `NotStr(...string...)`. Style(':root { --pico-font-size: 100%; }'), # Have a look at fasthtml/js.py to see how these Javascript libraries are added to FastHTML. # They are only 5-10 lines of code each, and you can add your own too. SortableJS('.sortable'), # MarkdownJS is actually provided as part of FastHTML, but we've included the js code here # so that you can see how it works. Script(markdown_js, type='module')) ) # We add `rt` as a shortcut for `app.route`, which is what we'll use to decorate our route handlers. # When using `app.route` (or this shortcut), the only required argument is the path. # The name of the decorated function (eg `get`, `post`, etc) is used as the HTTP verb for the handler. rt = app.route # For instance, this function handles GET requests to the `/login` path. @rt("/login") def get(): # This creates a form with two input fields, and a submit button. # All of these components are `FT` objects. All HTML tags are provided in this form by FastHTML. # If you want other custom tags (e.g. `MyTag`), they can be auto-generated by e.g # `from fasthtml.components import MyTag`. # Alternatively, manually call e.g `ft(tag_name, *children, **attrs)`. frm = Form( # Tags with a `name` attr will have `name` auto-set to the same as `id` if not provided Input(id='name', placeholder='Name'), Input(id='pwd', type='password', placeholder='Password'), Button('login'), action='/login', method='post') # If a user visits the URL directly, FastHTML auto-generates a full HTML page. # However, if the URL is accessed by HTMX, then one HTML partial is created for each element of the tuple. # To avoid this auto-generation of a full page, return a `HTML` object, or a Starlette `Response`. # `Titled` returns a tuple of a `Title` with the first arg and a `Container` with the rest. # See the comments for `Title` later for details. return Titled("Login", frm) # Handlers are passed whatever information they "request" in the URL, as keyword arguments. # Dataclasses, dicts, namedtuples, TypedDicts, and custom classes are automatically instantiated # from form data. # In this case, the `Login` class is a dataclass, so the handler will be passed `name` and `pwd`. @dataclass class Login: name:str; pwd:str # This handler is called when a POST request is made to the `/login` path. # The `login` argument is an instance of the `Login` class, which has been auto-instantiated from the form data. # There are a number of special parameter names, which will be passed useful information about the request: # `session`: the Starlette session; `request`: the Starlette request; `auth`: the value of `scope['auth']`, # `htmx`: the HTMX headers, if any; `app`: the FastHTML app object. # You can also pass any string prefix of `request` or `session`. @rt("/login") def post(login:Login, sess): if not login.name or not login.pwd: return login_redir # Indexing into a MiniDataAPI table queries by primary key, which is `name` here. # It returns a dataclass object, if `dataclass()` has been called at some point, or a dict otherwise. try: u = users[login.name] # If the primary key does not exist, the method raises a `NotFoundError`. # Here we use this to just generate a user -- in practice you'd probably to redirect to a signup page. except NotFoundError: u = users.insert(login) # This compares the passwords using a constant time string comparison # https://sqreen.github.io/DevelopersSecurityBestPractices/timing-attack/python if not compare_digest(u.pwd.encode("utf-8"), login.pwd.encode("utf-8")): return login_redir # Because the session is signed, we can securely add information to it. It's stored in the browser cookies. # If you don't pass a secret signing key to `FastHTML`, it will auto-generate one and store it in a file `./sesskey`. sess['auth'] = u.name return RedirectResponse('/', status_code=303) # Instead of using `app.route` (or the `rt` shortcut), you can also use `app.get`, `app.post`, etc. # In this case, the function name is not used to determine the HTTP verb. @app.get("/logout") def logout(sess): del sess['auth'] return login_redir # FastHTML uses Starlette's path syntax, and adds a `static` type which matches standard static file extensions. # You can define your own regex path specifiers -- for instance this is how `static` is defined in FastHTML # `reg_re_param("static", "ico|gif|jpg|jpeg|webm|css|js|woff|png|svg|mp4|webp|ttf|otf|eot|woff2|txt|xml|html")` # In this app, we only actually have one static file, which is `favicon.ico`. But it would also be needed if # we were referencing images, CSS/JS files, etc. # Note, this function is unnecessary, as the `fast_app()` call already includes this functionality. # However, it's included here to show how you can define your own static file handler. @rt("/{fname:path}.{ext:static}") def get(fname:str, ext:str): return FileResponse(f'{fname}.{ext}') # The `patch` decorator, which is defined in `fastcore`, adds a method to an existing class. # Here we are adding a method to the `Todo` class, which is returned by the `todos` table. # The `__ft__` method is a special method that FastHTML uses to convert the object into an `FT` object, # so that it can be composed into an FT tree, and later rendered into HTML. @patch def __ft__(self:Todo): # Some FastHTML tags have an 'X' suffix, which means they're "extended" in some way. # For instance, here `AX` is an extended `A` tag, which takes 3 positional arguments: # `(text, hx_get, target_id)`. # All underscores in FT attrs are replaced with hyphens, so this will create an `hx-get` attr, # which HTMX uses to trigger a GET request. # Generally, most of your route handlers in practice (as in this demo app) are likely to be HTMX handlers. # For instance, for this demo, we only have two full-page handlers: the '/login' and '/' GET handlers. show = AX(self.title, f'/todos/{self.id}', 'current-todo') edit = AX('edit', f'/edit/{self.id}' , 'current-todo') dt = 'βœ… ' if self.done else '' # FastHTML provides some shortcuts. For instance, `Hidden` is defined as simply: # `return Input(type="hidden", value=value, **kwargs)` cts = (dt, show, ' | ', edit, Hidden(id="id", value=self.id), Hidden(id="priority", value="0")) # Any FT object can take a list of children as positional args, and a dict of attrs as keyword args. return Li(*cts, id=f'todo-{self.id}') # This is the handler for the main todo list application. # By including the `auth` parameter, it gets passed the current username, for displaying in the title. @rt("/") def get(auth): title = f"{auth}'s Todo list" top = Grid(H1(title), Div(A('logout', href='/logout'), style='text-align: right')) # We don't normally need separate "screens" for adding or editing data. Here for instance, # we're using an `hx-post` to add a new todo, which is added to the start of the list (using 'afterbegin'). new_inp = Input(id="new-title", name="title", placeholder="New Todo") add = Form(Group(new_inp, Button("Add")), hx_post="/", target_id='todo-list', hx_swap="afterbegin") # In the MiniDataAPI spec, treating a table as a callable (i.e with `todos(...)` here) queries the table. # Because we called `xtra` in our Beforeware, this queries the todos for the current user only. # We can include the todo objects directly as children of the `Form`, because the `Todo` class has `__ft__` defined. # This is automatically called by FastHTML to convert the `Todo` objects into `FT` objects when needed. # The reason we put the todo list inside a form is so that we can use the 'sortable' js library to reorder them. # That library calls the js `end` event when dragging is complete, so our trigger here causes our `/reorder` # handler to be called. frm = Form(*todos(order_by='priority'), id='todo-list', cls='sortable', hx_post="/reorder", hx_trigger="end") # We create an empty 'current-todo' Div at the bottom of our page, as a target for the details and editing views. card = Card(Ul(frm), header=add, footer=Div(id='current-todo')) # PicoCSS uses `<Main class='container'>` page content; `Container` is a tiny function that generates that. # A handler can return either a single `FT` object or string, or a tuple of them. # In the case of a tuple, the stringified objects are concatenated and returned to the browser. # The `Title` tag has a special purpose: it sets the title of the page. return Title(title), Container(top, card) # This is the handler for the reordering of todos. # It's a POST request, which is used by the 'sortable' js library. # Because the todo list form created earlier included hidden inputs with the todo IDs, # they are passed as form data. By using a parameter called (e.g) "id", FastHTML will try to find # something suitable in the request with this name. In order, it searches as follows: # path; query; cookies; headers; session keys; form data. # Although all these are provided in the request as strings, FastHTML will use your parameter's type # annotation to try to cast the value to the requested type. # In the case of form data, there can be multiple values with the same key. So in this case, # the parameter is a list of ints. @rt("/reorder") def post(id:list[int]): for i,id_ in enumerate(id): todos.update({'priority':i}, id_) # HTMX by default replaces the inner HTML of the calling element, which in this case is the todo list form. # Therefore, we return the list of todos, now in the correct order, which will be auto-converted to FT for us. # In this case, it's not strictly necessary, because sortable.js has already reorder the DOM elements. # However, by returning the updated data, we can be assured that there aren't sync issues between the DOM # and the server. return tuple(todos(order_by='priority')) # Refactoring components in FastHTML is as simple as creating Python functions. # The `clr_details` function creates a Div with specific HTMX attributes. # `hx_swap_oob='innerHTML'` tells HTMX to swap the inner HTML of the target element out-of-band, # meaning it will update this element regardless of where the HTMX request originated from. def clr_details(): return Div(hx_swap_oob='innerHTML', id='current-todo') # This route handler uses a path parameter `{id}` which is automatically parsed and passed as an int. @rt("/todos/{id}") def delete(id:int): # The `delete` method is part of the MiniDataAPI spec, removing the item with the given primary key. todos.delete(id) # Returning `clr_details()` ensures the details view is cleared after deletion, # leveraging HTMX's out-of-band swap feature. # Note that we are not returning *any* FT component that doesn't have an "OOB" swap, so the target element # inner HTML is simply deleted. That's why the deleted todo is removed from the list. return clr_details() @rt("/edit/{id}") def get(id:int): # The `hx_put` attribute tells HTMX to send a PUT request when the form is submitted. # `target_id` specifies which element will be updated with the server's response. res = Form(Group(Input(id="title"), Button("Save")), Hidden(id="id"), CheckboxX(id="done", label='Done'), Textarea(id="details", name="details", rows=10), hx_put="/", target_id=f'todo-{id}', id="edit") # `fill_form` populates the form with existing todo data, and returns the result. # Indexing into a table (`todos`) queries by primary key, which is `id` here. It also includes # `xtra`, so this will only return the id if it belongs to the current user. return fill_form(res, todos[id]) @rt("/") def put(todo: Todo): # `update` is part of the MiniDataAPI spec. # Note that the updated todo is returned. By returning the updated todo, we can update the list directly. # Because we return a tuple with `clr_details()`, the details view is also cleared. return todos.update(todo), clr_details() @rt("/") def post(todo:Todo): # `hx_swap_oob='true'` tells HTMX to perform an out-of-band swap, updating this element wherever it appears. # This is used to clear the input field after adding the new todo. new_inp = Input(id="new-title", name="title", placeholder="New Todo", hx_swap_oob='true') # `insert` returns the inserted todo, which is appended to the start of the list, because we used # `hx_swap='afterbegin'` when creating the todo list form. return todos.insert(todo), new_inp @rt("/todos/{id}") def get(id:int): todo = todos[id] # `hx_swap` determines how the update should occur. We use "outerHTML" to replace the entire todo `Li` element. btn = Button('delete', hx_delete=f'/todos/{todo.id}', target_id=f'todo-{todo.id}', hx_swap="outerHTML") # The "markdown" class is used here because that's the CSS selector we used in the JS earlier. # Therefore this will trigger the JS to parse the markdown in the details field. # Because `class` is a reserved keyword in Python, we use `cls` instead, which FastHTML auto-converts. return Div(H2(todo.title), Div(todo.details, cls="markdown"), btn) serve()
https://raw.githubusercontent.com/AnswerDotAI/fasthtml/main/examples/adv_app.py
examples_adv_app.py
# index.md --- # Starlette Introduction Starlette is a lightweight [ASGI][asgi] framework/toolkit, which is ideal for building async web services in Python. It is production-ready, and gives you the following: * A lightweight, low-complexity HTTP web framework. * WebSocket support. * In-process background tasks. * Startup and shutdown events. * Test client built on `httpx`. * CORS, GZip, Static Files, Streaming responses. * Session and Cookie support. * 100% test coverage. * 100% type annotated codebase. * Few hard dependencies. * Compatible with `asyncio` and `trio` backends. * Great overall performance [against independent benchmarks][techempower]. ## Requirements Python 3.8+ ## Installation ```shell $ pip3 install starlette ``` You'll also want to install an ASGI server, such as [uvicorn](http://www.uvicorn.org/), [daphne](https://github.com/django/daphne/), or [hypercorn](https://pgjones.gitlab.io/hypercorn/). ```shell $ pip3 install uvicorn ``` ## Example **example.py**: ```python from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route async def homepage(request): return JSONResponse({'hello': 'world'}) app = Starlette(debug=True, routes=[ Route('/', homepage), ]) ``` Then run the application... ```shell $ uvicorn example:app ``` For a more complete example, [see here](https://github.com/encode/starlette-example). ## Dependencies Starlette only requires `anyio`, and the following dependencies are optional: * [`httpx`][httpx] - Required if you want to use the `TestClient`. * [`jinja2`][jinja2] - Required if you want to use `Jinja2Templates`. * [`python-multipart`][python-multipart] - Required if you want to support form parsing, with `request.form()`. * [`itsdangerous`][itsdangerous] - Required for `SessionMiddleware` support. * [`pyyaml`][pyyaml] - Required for `SchemaGenerator` support. You can install all of these with `pip3 install starlette[full]`. ## Framework or Toolkit Starlette is designed to be used either as a complete framework, or as an ASGI toolkit. You can use any of its components independently. ```python from starlette.responses import PlainTextResponse async def app(scope, receive, send): assert scope['type'] == 'http' response = PlainTextResponse('Hello, world!') await response(scope, receive, send) ``` Run the `app` application in `example.py`: ```shell $ uvicorn example:app INFO: Started server process [11509] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` Run uvicorn with `--reload` to enable auto-reloading on code changes. ## Modularity The modularity that Starlette is designed on promotes building re-usable components that can be shared between any ASGI framework. This should enable an ecosystem of shared middleware and mountable applications. The clean API separation also means it's easier to understand each component in isolation. --- # applications.md Starlette includes an application class `Starlette` that nicely ties together all of its other functionality. ```python from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route, Mount, WebSocketRoute from starlette.staticfiles import StaticFiles def homepage(request): return PlainTextResponse('Hello, world!') def user_me(request): username = "John Doe" return PlainTextResponse('Hello, %s!' % username) def user(request): username = request.path_params['username'] return PlainTextResponse('Hello, %s!' % username) async def websocket_endpoint(websocket): await websocket.accept() await websocket.send_text('Hello, websocket!') await websocket.close() def startup(): print('Ready to go') routes = [ Route('/', homepage), Route('/user/me', user_me), Route('/user/{username}', user), WebSocketRoute('/ws', websocket_endpoint), Mount('/static', StaticFiles(directory="static")), ] app = Starlette(debug=True, routes=routes, on_startup=[startup]) ``` ### Instantiating the application ::: starlette.applications.Starlette :docstring: ### Storing state on the app instance You can store arbitrary extra state on the application instance, using the generic `app.state` attribute. For example: ```python app.state.ADMIN_EMAIL = '[email protected]' ``` ### Accessing the app instance Where a `request` is available (i.e. endpoints and middleware), the app is available on `request.app`. # requests.md Starlette includes a `Request` class that gives you a nicer interface onto the incoming request, rather than accessing the ASGI scope and receive channel directly. ### Request Signature: `Request(scope, receive=None)` ```python from starlette.requests import Request from starlette.responses import Response async def app(scope, receive, send): assert scope['type'] == 'http' request = Request(scope, receive) content = '%s %s' % (request.method, request.url.path) response = Response(content, media_type='text/plain') await response(scope, receive, send) ``` Requests present a mapping interface, so you can use them in the same way as a `scope`. For instance: `request['path']` will return the ASGI path. If you don't need to access the request body you can instantiate a request without providing an argument to `receive`. #### Method The request method is accessed as `request.method`. #### URL The request URL is accessed as `request.url`. The property is a string-like object that exposes all the components that can be parsed out of the URL. For example: `request.url.path`, `request.url.port`, `request.url.scheme`. #### Headers Headers are exposed as an immutable, case-insensitive, multi-dict. For example: `request.headers['content-type']` #### Query Parameters Query parameters are exposed as an immutable multi-dict. For example: `request.query_params['search']` #### Path Parameters Router path parameters are exposed as a dictionary interface. For example: `request.path_params['username']` #### Client Address The client's remote address is exposed as a named two-tuple `request.client` (or `None`). The hostname or IP address: `request.client.host` The port number from which the client is connecting: `request.client.port` #### Cookies Cookies are exposed as a regular dictionary interface. For example: `request.cookies.get('mycookie')` Cookies are ignored in case of an invalid cookie. (RFC2109) #### Body There are a few different interfaces for returning the body of the request: The request body as bytes: `await request.body()` The request body, parsed as form data or multipart: `async with request.form() as form:` The request body, parsed as JSON: `await request.json()` You can also access the request body as a stream, using the `async for` syntax: ```python from starlette.requests import Request from starlette.responses import Response async def app(scope, receive, send): assert scope['type'] == 'http' request = Request(scope, receive) body = b'' async for chunk in request.stream(): body += chunk response = Response(body, media_type='text/plain') await response(scope, receive, send) ``` If you access `.stream()` then the byte chunks are provided without storing the entire body to memory. Any subsequent calls to `.body()`, `.form()`, or `.json()` will raise an error. In some cases such as long-polling, or streaming responses you might need to determine if the client has dropped the connection. You can determine this state with `disconnected = await request.is_disconnected()`. #### Request Files Request files are normally sent as multipart form data (`multipart/form-data`). Signature: `request.form(max_files=1000, max_fields=1000)` You can configure the number of maximum fields or files with the parameters `max_files` and `max_fields`: ```python async with request.form(max_files=1000, max_fields=1000): ... ``` !!! info These limits are for security reasons, allowing an unlimited number of fields or files could lead to a denial of service attack by consuming a lot of CPU and memory parsing too many empty fields. When you call `async with request.form() as form` you receive a `starlette.datastructures.FormData` which is an immutable multidict, containing both file uploads and text input. File upload items are represented as instances of `starlette.datastructures.UploadFile`. `UploadFile` has the following attributes: * `filename`: An `str` with the original file name that was uploaded or `None` if its not available (e.g. `myimage.jpg`). * `content_type`: An `str` with the content type (MIME type / media type) or `None` if it's not available (e.g. `image/jpeg`). * `file`: A <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" target="_blank">file-like</a> object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object. * `headers`: A `Headers` object. Often this will only be the `Content-Type` header, but if additional headers were included in the multipart field they will be included here. Note that these headers have no relationship with the headers in `Request.headers`. * `size`: An `int` with uploaded file's size in bytes. This value is calculated from request's contents, making it better choice to find uploaded file's size than `Content-Length` header. `None` if not set. `UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`). * `async write(data)`: Writes `data` (`bytes`) to the file. * `async read(size)`: Reads `size` (`int`) bytes of the file. * `async seek(offset)`: Goes to the byte position `offset` (`int`) in the file. * E.g., `await myfile.seek(0)` would go to the start of the file. * `async close()`: Closes the file. As all these methods are `async` methods, you need to "await" them. For example, you can get the file name and the contents with: ```python async with request.form() as form: filename = form["upload_file"].filename contents = await form["upload_file"].read() ``` !!! info As settled in [RFC-7578: 4.2](https://www.ietf.org/rfc/rfc7578.txt), form-data content part that contains file assumed to have `name` and `filename` fields in `Content-Disposition` header: `Content-Disposition: form-data; name="user"; filename="somefile"`. Though `filename` field is optional according to RFC-7578, it helps Starlette to differentiate which data should be treated as file. If `filename` field was supplied, `UploadFile` object will be created to access underlying file, otherwise form-data part will be parsed and available as a raw string. #### Application The originating Starlette application can be accessed via `request.app`. #### Other state If you want to store additional information on the request you can do so using `request.state`. For example: `request.state.time_started = time.time()` # responses.md Starlette includes a few response classes that handle sending back the appropriate ASGI messages on the `send` channel. ### Response Signature: `Response(content, status_code=200, headers=None, media_type=None)` * `content` - A string or bytestring. * `status_code` - An integer HTTP status code. * `headers` - A dictionary of strings. * `media_type` - A string giving the media type. eg. "text/html" Starlette will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types, unless a charset has already been specified in the `media_type`. Once you've instantiated a response, you can send it by calling it as an ASGI application instance. ```python from starlette.responses import Response async def app(scope, receive, send): assert scope['type'] == 'http' response = Response('Hello, world!', media_type='text/plain') await response(scope, receive, send) ``` #### Set Cookie Starlette provides a `set_cookie` method to allow you to set cookies on the response object. Signature: `Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax")` * `key` - A string that will be the cookie's key. * `value` - A string that will be the cookie's value. * `max_age` - An integer that defines the lifetime of the cookie in seconds. A negative integer or a value of `0` will discard the cookie immediately. `Optional` * `expires` - Either an integer that defines the number of seconds until the cookie expires, or a datetime. `Optional` * `path` - A string that specifies the subset of routes to which the cookie will apply. `Optional` * `domain` - A string that specifies the domain for which the cookie is valid. `Optional` * `secure` - A bool indicating that the cookie will only be sent to the server if request is made using SSL and the HTTPS protocol. `Optional` * `httponly` - A bool indicating that the cookie cannot be accessed via JavaScript through `Document.cookie` property, the `XMLHttpRequest` or `Request` APIs. `Optional` * `samesite` - A string that specifies the samesite strategy for the cookie. Valid values are `'lax'`, `'strict'` and `'none'`. Defaults to `'lax'`. `Optional` #### Delete Cookie Conversely, Starlette also provides a `delete_cookie` method to manually expire a set cookie. Signature: `Response.delete_cookie(key, path='/', domain=None)` ### HTMLResponse Takes some text or bytes and returns an HTML response. ```python from starlette.responses import HTMLResponse async def app(scope, receive, send): assert scope['type'] == 'http' response = HTMLResponse('<html><body><h1>Hello, world!</h1></body></html>') await response(scope, receive, send) ``` ### PlainTextResponse Takes some text or bytes and returns a plain text response. ```python from starlette.responses import PlainTextResponse async def app(scope, receive, send): assert scope['type'] == 'http' response = PlainTextResponse('Hello, world!') await response(scope, receive, send) ``` ### JSONResponse Takes some data and returns an `application/json` encoded response. ```python from starlette.responses import JSONResponse async def app(scope, receive, send): assert scope['type'] == 'http' response = JSONResponse({'hello': 'world'}) await response(scope, receive, send) ``` #### Custom JSON serialization If you need fine-grained control over JSON serialization, you can subclass `JSONResponse` and override the `render` method. For example, if you wanted to use a third-party JSON library such as [orjson](https://pypi.org/project/orjson/): ```python from typing import Any import orjson from starlette.responses import JSONResponse class OrjsonResponse(JSONResponse): def render(self, content: Any) -> bytes: return orjson.dumps(content) ``` In general you *probably* want to stick with `JSONResponse` by default unless you are micro-optimising a particular endpoint or need to serialize non-standard object types. ### RedirectResponse Returns an HTTP redirect. Uses a 307 status code by default. ```python from starlette.responses import PlainTextResponse, RedirectResponse async def app(scope, receive, send): assert scope['type'] == 'http' if scope['path'] != '/': response = RedirectResponse(url='/') else: response = PlainTextResponse('Hello, world!') await response(scope, receive, send) ``` ### StreamingResponse Takes an async generator or a normal generator/iterator and streams the response body. ```python from starlette.responses import StreamingResponse import asyncio async def slow_numbers(minimum, maximum): yield '<html><body><ul>' for number in range(minimum, maximum + 1): yield '<li>%d</li>' % number await asyncio.sleep(0.5) yield '</ul></body></html>' async def app(scope, receive, send): assert scope['type'] == 'http' generator = slow_numbers(1, 10) response = StreamingResponse(generator, media_type='text/html') await response(scope, receive, send) ``` Have in mind that <a href="https://docs.python.org/3/glossary.html#term-file-like-object" target="_blank">file-like</a> objects (like those created by `open()`) are normal iterators. So, you can return them directly in a `StreamingResponse`. ### FileResponse Asynchronously streams a file as the response. Takes a different set of arguments to instantiate than the other response types: * `path` - The filepath to the file to stream. * `headers` - Any custom headers to include, as a dictionary. * `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type. * `filename` - If set, this will be included in the response `Content-Disposition`. * `content_disposition_type` - will be included in the response `Content-Disposition`. Can be set to "attachment" (default) or "inline". File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. ```python from starlette.responses import FileResponse async def app(scope, receive, send): assert scope['type'] == 'http' response = FileResponse('statics/favicon.ico') await response(scope, receive, send) ``` ## Third party responses #### [EventSourceResponse](https://github.com/sysid/sse-starlette) A response class that implements [Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html). It enables event streaming from the server to the client without the complexity of websockets. #### [baize.asgi.FileResponse](https://baize.aber.sh/asgi#fileresponse) As a smooth replacement for Starlette [`FileResponse`](https://www.starlette.io/responses/#fileresponse), it will automatically handle [Head method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) and [Range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests). # websockets.md Starlette includes a `WebSocket` class that fulfils a similar role to the HTTP request, but that allows sending and receiving data on a websocket. ### WebSocket Signature: `WebSocket(scope, receive=None, send=None)` ```python from starlette.websockets import WebSocket async def app(scope, receive, send): websocket = WebSocket(scope=scope, receive=receive, send=send) await websocket.accept() await websocket.send_text('Hello, world!') await websocket.close() ``` WebSockets present a mapping interface, so you can use them in the same way as a `scope`. For instance: `websocket['path']` will return the ASGI path. #### URL The websocket URL is accessed as `websocket.url`. The property is actually a subclass of `str`, and also exposes all the components that can be parsed out of the URL. For example: `websocket.url.path`, `websocket.url.port`, `websocket.url.scheme`. #### Headers Headers are exposed as an immutable, case-insensitive, multi-dict. For example: `websocket.headers['sec-websocket-version']` #### Query Parameters Query parameters are exposed as an immutable multi-dict. For example: `websocket.query_params['search']` #### Path Parameters Router path parameters are exposed as a dictionary interface. For example: `websocket.path_params['username']` ### Accepting the connection * `await websocket.accept(subprotocol=None, headers=None)` ### Sending data * `await websocket.send_text(data)` * `await websocket.send_bytes(data)` * `await websocket.send_json(data)` JSON messages default to being sent over text data frames, from version 0.10.0 onwards. Use `websocket.send_json(data, mode="binary")` to send JSON over binary data frames. ### Receiving data * `await websocket.receive_text()` * `await websocket.receive_bytes()` * `await websocket.receive_json()` May raise `starlette.websockets.WebSocketDisconnect()`. JSON messages default to being received over text data frames, from version 0.10.0 onwards. Use `websocket.receive_json(data, mode="binary")` to receive JSON over binary data frames. ### Iterating data * `websocket.iter_text()` * `websocket.iter_bytes()` * `websocket.iter_json()` Similar to `receive_text`, `receive_bytes`, and `receive_json` but returns an async iterator. ```python hl_lines="7-8" from starlette.websockets import WebSocket async def app(scope, receive, send): websocket = WebSocket(scope=scope, receive=receive, send=send) await websocket.accept() async for message in websocket.iter_text(): await websocket.send_text(f"Message text was: {message}") await websocket.close() ``` When `starlette.websockets.WebSocketDisconnect` is raised, the iterator will exit. ### Closing the connection * `await websocket.close(code=1000, reason=None)` ### Sending and receiving messages If you need to send or receive raw ASGI messages then you should use `websocket.send()` and `websocket.receive()` rather than using the raw `send` and `receive` callables. This will ensure that the websocket's state is kept correctly updated. * `await websocket.send(message)` * `await websocket.receive()` ### Send Denial Response If you call `websocket.close()` before calling `websocket.accept()` then the server will automatically send a HTTP 403 error to the client. If you want to send a different error response, you can use the `websocket.send_denial_response()` method. This will send the response and then close the connection. * `await websocket.send_denial_response(response)` This requires the ASGI server to support the WebSocket Denial Response extension. If it is not supported a `RuntimeError` will be raised. # routing.md ## HTTP Routing Starlette has a simple but capable request routing system. A routing table is defined as a list of routes, and passed when instantiating the application. ```python from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.routing import Route async def homepage(request): return PlainTextResponse("Homepage") async def about(request): return PlainTextResponse("About") routes = [ Route("/", endpoint=homepage), Route("/about", endpoint=about), ] app = Starlette(routes=routes) ``` The `endpoint` argument can be one of: * A regular function or async function, which accepts a single `request` argument and which should return a response. * A class that implements the ASGI interface, such as Starlette's [HTTPEndpoint](endpoints.md#httpendpoint). ## Path Parameters Paths can use URI templating style to capture path components. ```python Route('/users/{username}', user) ``` By default this will capture characters up to the end of the path or the next `/`. You can use convertors to modify what is captured. The available convertors are: * `str` returns a string, and is the default. * `int` returns a Python integer. * `float` returns a Python float. * `uuid` return a Python `uuid.UUID` instance. * `path` returns the rest of the path, including any additional `/` characters. Convertors are used by prefixing them with a colon, like so: ```python Route('/users/{user_id:int}', user) Route('/floating-point/{number:float}', floating_point) Route('/uploaded/{rest_of_path:path}', uploaded) ``` If you need a different converter that is not defined, you can create your own. See below an example on how to create a `datetime` convertor, and how to register it: ```python from datetime import datetime from starlette.convertors import Convertor, register_url_convertor class DateTimeConvertor(Convertor): regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?" def convert(self, value: str) -> datetime: return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") def to_string(self, value: datetime) -> str: return value.strftime("%Y-%m-%dT%H:%M:%S") register_url_convertor("datetime", DateTimeConvertor()) ``` After registering it, you'll be able to use it as: ```python Route('/history/{date:datetime}', history) ``` Path parameters are made available in the request, as the `request.path_params` dictionary. ```python async def user(request): user_id = request.path_params['user_id'] ... ``` ## Handling HTTP methods Routes can also specify which HTTP methods are handled by an endpoint: ```python Route('/users/{user_id:int}', user, methods=["GET", "POST"]) ``` By default function endpoints will only accept `GET` requests, unless specified. ## Submounting routes In large applications you might find that you want to break out parts of the routing table, based on a common path prefix. ```python routes = [ Route('/', homepage), Mount('/users', routes=[ Route('/', users, methods=['GET', 'POST']), Route('/{username}', user), ]) ] ``` This style allows you to define different subsets of the routing table in different parts of your project. ```python from myproject import users, auth routes = [ Route('/', homepage), Mount('/users', routes=users.routes), Mount('/auth', routes=auth.routes), ] ``` You can also use mounting to include sub-applications within your Starlette application. For example... ```python # This is a standalone static files server: app = StaticFiles(directory="static") # This is a static files server mounted within a Starlette application, # underneath the "/static" path. routes = [ ... Mount("/static", app=StaticFiles(directory="static"), name="static") ] app = Starlette(routes=routes) ``` ## Reverse URL lookups You'll often want to be able to generate the URL for a particular route, such as in cases where you need to return a redirect response. * Signature: `url_for(name, **path_params) -> URL` ```python routes = [ Route("/", homepage, name="homepage") ] # We can use the following to return a URL... url = request.url_for("homepage") ``` URL lookups can include path parameters... ```python routes = [ Route("/users/{username}", user, name="user_detail") ] # We can use the following to return a URL... url = request.url_for("user_detail", username=...) ``` If a `Mount` includes a `name`, then submounts should use a `{prefix}:{name}` style for reverse URL lookups. ```python routes = [ Mount("/users", name="users", routes=[ Route("/", user, name="user_list"), Route("/{username}", user, name="user_detail") ]) ] # We can use the following to return URLs... url = request.url_for("users:user_list") url = request.url_for("users:user_detail", username=...) ``` Mounted applications may include a `path=...` parameter. ```python routes = [ ... Mount("/static", app=StaticFiles(directory="static"), name="static") ] # We can use the following to return URLs... url = request.url_for("static", path="/css/base.css") ``` For cases where there is no `request` instance, you can make reverse lookups against the application, although these will only return the URL path. ```python url = app.url_path_for("user_detail", username=...) ``` ## Host-based routing If you want to use different routes for the same path based on the `Host` header. Note that port is removed from the `Host` header when matching. For example, `Host (host='example.org:3600', ...)` will be processed even if the `Host` header contains or does not contain a port other than `3600` (`example.org:5600`, `example.org`). Therefore, you can specify the port if you need it for use in `url_for`. There are several ways to connect host-based routes to your application ```python site = Router() # Use eg. `@site.route()` to configure this. api = Router() # Use eg. `@api.route()` to configure this. news = Router() # Use eg. `@news.route()` to configure this. routes = [ Host('api.example.org', api, name="site_api") ] app = Starlette(routes=routes) app.host('www.example.org', site, name="main_site") news_host = Host('news.example.org', news) app.router.routes.append(news_host) ``` URL lookups can include host parameters just like path parameters ```python routes = [ Host("{subdomain}.example.org", name="sub", app=Router(routes=[ Mount("/users", name="users", routes=[ Route("/", user, name="user_list"), Route("/{username}", user, name="user_detail") ]) ])) ] ... url = request.url_for("sub:users:user_detail", username=..., subdomain=...) url = request.url_for("sub:users:user_list", subdomain=...) ``` ## Route priority Incoming paths are matched against each `Route` in order. In cases where more that one route could match an incoming path, you should take care to ensure that more specific routes are listed before general cases. For example: ```python # Don't do this: `/users/me` will never match incoming requests. routes = [ Route('/users/{username}', user), Route('/users/me', current_user), ] # Do this: `/users/me` is tested first. routes = [ Route('/users/me', current_user), Route('/users/{username}', user), ] ``` ## Working with Router instances If you're working at a low-level you might want to use a plain `Router` instance, rather that creating a `Starlette` application. This gives you a lightweight ASGI application that just provides the application routing, without wrapping it up in any middleware. ```python app = Router(routes=[ Route('/', homepage), Mount('/users', routes=[ Route('/', users, methods=['GET', 'POST']), Route('/{username}', user), ]) ]) ``` ## WebSocket Routing When working with WebSocket endpoints, you should use `WebSocketRoute` instead of the usual `Route`. Path parameters, and reverse URL lookups for `WebSocketRoute` work the the same as HTTP `Route`, which can be found in the HTTP [Route](#http-routing) section above. The `endpoint` argument can be one of: * An async function, which accepts a single `websocket` argument. * A class that implements the ASGI interface, such as Starlette's [WebSocketEndpoint](endpoints.md#websocketendpoint). # endpoints.md Starlette includes the classes `HTTPEndpoint` and `WebSocketEndpoint` that provide a class-based view pattern for handling HTTP method dispatching and WebSocket sessions. ### HTTPEndpoint The `HTTPEndpoint` class can be used as an ASGI application: ```python from starlette.responses import PlainTextResponse from starlette.endpoints import HTTPEndpoint class App(HTTPEndpoint): async def get(self, request): return PlainTextResponse(f"Hello, world!") ``` If you're using a Starlette application instance to handle routing, you can dispatch to an `HTTPEndpoint` class. Make sure to dispatch to the class itself, rather than to an instance of the class: ```python from starlette.applications import Starlette from starlette.responses import PlainTextResponse from starlette.endpoints import HTTPEndpoint from starlette.routing import Route class Homepage(HTTPEndpoint): async def get(self, request): return PlainTextResponse(f"Hello, world!") class User(HTTPEndpoint): async def get(self, request): username = request.path_params['username'] return PlainTextResponse(f"Hello, {username}") routes = [ Route("/", Homepage), Route("/{username}", User) ] app = Starlette(routes=routes) ``` HTTP endpoint classes will respond with "405 Method not allowed" responses for any request methods which do not map to a corresponding handler. ### WebSocketEndpoint The `WebSocketEndpoint` class is an ASGI application that presents a wrapper around the functionality of a `WebSocket` instance. The ASGI connection scope is accessible on the endpoint instance via `.scope` and has an attribute `encoding` which may optionally be set, in order to validate the expected websocket data in the `on_receive` method. The encoding types are: * `'json'` * `'bytes'` * `'text'` There are three overridable methods for handling specific ASGI websocket message types: * `async def on_connect(websocket, **kwargs)` * `async def on_receive(websocket, data)` * `async def on_disconnect(websocket, close_code)` The `WebSocketEndpoint` can also be used with the `Starlette` application class. # middleware.md Starlette includes several middleware classes for adding behavior that is applied across your entire application. These are all implemented as standard ASGI middleware classes, and can be applied either to Starlette or to any other ASGI application. ## Using middleware The Starlette application class allows you to include the ASGI middleware in a way that ensures that it remains wrapped by the exception handler. ```python from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware from starlette.middleware.trustedhost import TrustedHostMiddleware routes = ... # Ensure that all requests include an 'example.com' or # '*.example.com' host header, and strictly enforce https-only access. middleware = [ Middleware( TrustedHostMiddleware, allowed_hosts=['example.com', '*.example.com'], ), Middleware(HTTPSRedirectMiddleware) ] app = Starlette(routes=routes, middleware=middleware) ``` Every Starlette application automatically includes two pieces of middleware by default: * `ServerErrorMiddleware` - Ensures that application exceptions may return a custom 500 page, or display an application traceback in DEBUG mode. This is *always* the outermost middleware layer. * `ExceptionMiddleware` - Adds exception handlers, so that particular types of expected exception cases can be associated with handler functions. For example raising `HTTPException(status_code=404)` within an endpoint will end up rendering a custom 404 page. Middleware is evaluated from top-to-bottom, so the flow of execution in our example application would look like this: * Middleware * `ServerErrorMiddleware` * `TrustedHostMiddleware` * `HTTPSRedirectMiddleware` * `ExceptionMiddleware` * Routing * Endpoint The following middleware implementations are available in the Starlette package: - CORSMiddleware - SessionMiddleware - HTTPSRedirectMiddleware - TrustedHostMiddleware - GZipMiddleware - BaseHTTPMiddleware # lifespan.md Starlette applications can register a lifespan handler for dealing with code that needs to run before the application starts up, or when the application is shutting down. ```python import contextlib from starlette.applications import Starlette @contextlib.asynccontextmanager async def lifespan(app): async with some_async_resource(): print("Run at startup!") yield print("Run on shutdown!") routes = [ ... ] app = Starlette(routes=routes, lifespan=lifespan) ``` Starlette will not start serving any incoming requests until the lifespan has been run. The lifespan teardown will run once all connections have been closed, and any in-process background tasks have completed. Consider using [`anyio.create_task_group()`](https://anyio.readthedocs.io/en/stable/tasks.html) for managing asynchronous tasks. ## Lifespan State The lifespan has the concept of `state`, which is a dictionary that can be used to share the objects between the lifespan, and the requests. ```python import contextlib from typing import AsyncIterator, TypedDict import httpx from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import PlainTextResponse from starlette.routing import Route class State(TypedDict): http_client: httpx.AsyncClient @contextlib.asynccontextmanager async def lifespan(app: Starlette) -> AsyncIterator[State]: async with httpx.AsyncClient() as client: yield {"http_client": client} async def homepage(request: Request) -> PlainTextResponse: client = request.state.http_client response = await client.get("https://www.example.com") return PlainTextResponse(response.text) app = Starlette( lifespan=lifespan, routes=[Route("/", homepage)] ) ``` The `state` received on the requests is a **shallow** copy of the state received on the lifespan handler. ## Running lifespan in tests You should use `TestClient` as a context manager, to ensure that the lifespan is called. ```python from example import app from starlette.testclient import TestClient def test_homepage(): with TestClient(app) as client: # Application's lifespan is called on entering the block. response = client.get("/") assert response.status_code == 200 # And the lifespan's teardown is run when exiting the block. ``` # background.md Starlette includes a `BackgroundTask` class for in-process background tasks. A background task should be attached to a response, and will run only once the response has been sent. ### Background Task Used to add a single background task to a response. Signature: `BackgroundTask(func, *args, **kwargs)` ```python from starlette.applications import Starlette from starlette.responses import JSONResponse from starlette.routing import Route from starlette.background import BackgroundTask ... async def signup(request): data = await request.json() username = data['username'] email = data['email'] task = BackgroundTask(send_welcome_email, to_address=email) message = {'status': 'Signup successful'} return JSONResponse(message, background=task) async def send_welcome_email(to_address): ... routes = [ ... Route('/user/signup', endpoint=signup, methods=['POST']) ] app = Starlette(routes=routes) ``` ### BackgroundTasks Used to add multiple background tasks to a response. Signature: `BackgroundTasks(tasks=[])` !!! important The tasks are executed in order. In case one of the tasks raises an exception, the following tasks will not get the opportunity to be executed. # server-push.md Starlette includes support for HTTP/2 and HTTP/3 server push, making it possible to push resources to the client to speed up page load times. ### `Request.send_push_promise` Used to initiate a server push for a resource. If server push is not available this method does nothing. Signature: `send_push_promise(path)` * `path` - A string denoting the path of the resource. ```python from starlette.applications import Starlette from starlette.responses import HTMLResponse from starlette.routing import Route, Mount from starlette.staticfiles import StaticFiles async def homepage(request): """ Homepage which uses server push to deliver the stylesheet. """ await request.send_push_promise("/static/style.css") return HTMLResponse( '<html><head><link rel="stylesheet" href="/static/style.css"/></head></html>' ) routes = [ Route("/", endpoint=homepage), Mount("/static", StaticFiles(directory="static"), name="static") ] app = Starlette(routes=routes) ``` # exceptions.md Starlette allows you to install custom exception handlers to deal with how you return responses when errors or handled exceptions occur. ```python from starlette.applications import Starlette from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import HTMLResponse HTML_404_PAGE = ... HTML_500_PAGE = ... async def not_found(request: Request, exc: HTTPException): return HTMLResponse(content=HTML_404_PAGE, status_code=exc.status_code) async def server_error(request: Request, exc: HTTPException): return HTMLResponse(content=HTML_500_PAGE, status_code=exc.status_code) exception_handlers = { 404: not_found, 500: server_error } app = Starlette(routes=routes, exception_handlers=exception_handlers) ``` If `debug` is enabled and an error occurs, then instead of using the installed 500 handler, Starlette will respond with a traceback response. ```python app = Starlette(debug=True, routes=routes, exception_handlers=exception_handlers) ``` As well as registering handlers for specific status codes, you can also register handlers for classes of exceptions. In particular you might want to override how the built-in `HTTPException` class is handled. For example, to use JSON style responses: ```python async def http_exception(request: Request, exc: HTTPException): return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) exception_handlers = { HTTPException: http_exception } ``` The `HTTPException` is also equipped with the `headers` argument. Which allows the propagation of the headers to the response class: ```python async def http_exception(request: Request, exc: HTTPException): return JSONResponse( {"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers ) ``` You might also want to override how `WebSocketException` is handled: ```python async def websocket_exception(websocket: WebSocket, exc: WebSocketException): await websocket.close(code=1008) exception_handlers = { WebSocketException: websocket_exception } ``` ## Errors and handled exceptions It is important to differentiate between handled exceptions and errors. Handled exceptions do not represent error cases. They are coerced into appropriate HTTP responses, which are then sent through the standard middleware stack. By default the `HTTPException` class is used to manage any handled exceptions. Errors are any other exception that occurs within the application. These cases should bubble through the entire middleware stack as exceptions. Any error logging middleware should ensure that it re-raises the exception all the way up to the server. In practical terms, the error handled used is `exception_handler[500]` or `exception_handler[Exception]`. Both keys `500` and `Exception` can be used. See below: ```python async def handle_error(request: Request, exc: HTTPException): # Perform some logic return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) exception_handlers = { Exception: handle_error # or "500: handle_error" } ``` It's important to notice that in case a [`BackgroundTask`](https://www.starlette.io/background/) raises an exception, it will be handled by the `handle_error` function, but at that point, the response was already sent. In other words, the response created by `handle_error` will be discarded. In case the error happens before the response was sent, then it will use the response object - in the above example, the returned `JSONResponse`. In order to deal with this behaviour correctly, the middleware stack of a `Starlette` application is configured like this: * `ServerErrorMiddleware` - Returns 500 responses when server errors occur. * Installed middleware * `ExceptionMiddleware` - Deals with handled exceptions, and returns responses. * Router * Endpoints ## HTTPException The `HTTPException` class provides a base class that you can use for any handled exceptions. The `ExceptionMiddleware` implementation defaults to returning plain-text HTTP responses for any `HTTPException`. * `HTTPException(status_code, detail=None, headers=None)` You should only raise `HTTPException` inside routing or endpoints. Middleware classes should instead just return appropriate responses directly. ## WebSocketException You can use the `WebSocketException` class to raise errors inside of WebSocket endpoints. * `WebSocketException(code=1008, reason=None)` You can set any code valid as defined [in the specification](https://tools.ietf.org/html/rfc6455#section-7.4.1). # testclient.md The test client allows you to make requests against your ASGI application, using the `httpx` library. ```python from starlette.responses import HTMLResponse from starlette.testclient import TestClient async def app(scope, receive, send): assert scope['type'] == 'http' response = HTMLResponse('<html><body>Hello, world!</body></html>') await response(scope, receive, send) def test_app(): client = TestClient(app) response = client.get('/') assert response.status_code == 200 ``` The test client exposes the same interface as any other `httpx` session. In particular, note that the calls to make a request are just standard function calls, not awaitables. You can use any of `httpx` standard API, such as authentication, session cookies handling, or file uploads. For example, to set headers on the TestClient you can do: ```python client = TestClient(app) # Set headers on the client for future requests client.headers = {"Authorization": "..."} response = client.get("/") # Set headers for each request separately response = client.get("/", headers={"Authorization": "..."}) ``` And for example to send files with the TestClient: ```python client = TestClient(app) # Send a single file with open("example.txt", "rb") as f: response = client.post("/form", files={"file": f}) # Send multiple files with open("example.txt", "rb") as f1: with open("example.png", "rb") as f2: files = {"file1": f1, "file2": ("filename", f2, "image/png")} response = client.post("/form", files=files) ``` ### Testing WebSocket sessions You can also test websocket sessions with the test client. The `httpx` library will be used to build the initial handshake, meaning you can use the same authentication options and other headers between both http and websocket testing. ```python from starlette.testclient import TestClient from starlette.websockets import WebSocket async def app(scope, receive, send): assert scope['type'] == 'websocket' websocket = WebSocket(scope, receive=receive, send=send) await websocket.accept() await websocket.send_text('Hello, world!') await websocket.close() def test_app(): client = TestClient(app) with client.websocket_connect('/') as websocket: data = websocket.receive_text() assert data == 'Hello, world!' ``` #### Sending data * `.send_text(data)` - Send the given text to the application. * `.send_bytes(data)` - Send the given bytes to the application. * `.send_json(data, mode="text")` - Send the given data to the application. Use `mode="binary"` to send JSON over binary data frames. #### Receiving data * `.receive_text()` - Wait for incoming text sent by the application and return it. * `.receive_bytes()` - Wait for incoming bytestring sent by the application and return it. * `.receive_json(mode="text")` - Wait for incoming json data sent by the application and return it. Use `mode="binary"` to receive JSON over binary data frames. May raise `starlette.websockets.WebSocketDisconnect`. #### Closing the connection * `.close(code=1000)` - Perform a client-side close of the websocket connection. ### Asynchronous tests Sometimes you will want to do async things outside of your application. For example, you might want to check the state of your database after calling your app using your existing async database client / infrastructure. For these situations, using `TestClient` is difficult because it creates it's own event loop and async resources (like a database connection) often cannot be shared across event loops. The simplest way to work around this is to just make your entire test async and use an async client, like [httpx.AsyncClient]. Here is an example of such a test: ```python from httpx import AsyncClient from starlette.applications import Starlette from starlette.routing import Route from starlette.requests import Request from starlette.responses import PlainTextResponse def hello(request: Request) -> PlainTextResponse: return PlainTextResponse("Hello World!") app = Starlette(routes=[Route("/", hello)]) # if you're using pytest, you'll need to to add an async marker like: # @pytest.mark.anyio # using https://github.com/agronholm/anyio # or install and configure pytest-asyncio (https://github.com/pytest-dev/pytest-asyncio) async def test_app() -> None: # note: you _must_ set `base_url` for relative urls like "/" to work async with AsyncClient(app=app, base_url="http://testserver") as client: r = await client.get("/") assert r.status_code == 200 assert r.text == "Hello World!" ```
https://gist.githubusercontent.com/jph00/809e4a4808d4510be0e3dc9565e9cbd3/raw/9b717589ca44cedc8aaf00b2b8cacef922964c0f/starlette-sml.md
9b717589ca44cedc8aaf00b2b8cacef922964c0f_starlette-sml.md
# JS App Walkthrough <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> ## Installation You’ll need the following software to complete the tutorial, read on for specific installation instructions: 1. Python 2. A Python package manager such as pip (which normally comes with Python) or uv 3. FastHTML 4. Web browser 5. Railway.app account If you haven’t worked with Python before, we recommend getting started with [Miniconda](https://docs.anaconda.com/miniconda/). Note that you will only need to follow the steps in the installation section once per environment. If you create a new repo, you won’t need to redo these. ### Install FastHTML For Mac, Windows and Linux, enter: ``` sh pip install python-fasthtml ``` ## First steps By the end of this section you’ll have your own FastHTML website with tests deployed to railway.app. ### Create a hello world Create a new folder to organize all the files for your project. Inside this folder, create a file called `main.py` and add the following code to it: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app = FastHTML() rt = app.route @rt('/') def get(): return 'Hello, world!' serve() ``` </div> Finally, run `python main.py` in your terminal and open your browser to the β€˜Link’ that appears. ### QuickDraw: A FastHTML Adventure 🎨✨ The end result of this tutorial will be QuickDraw, a real-time collaborative drawing app using FastHTML. Here is what the final site will look like: <figure> <img src="imgs/quickdraw.png" alt="QuickDraw" /> <figcaption aria-hidden="true">QuickDraw</figcaption> </figure> #### Drawing Rooms Drawing rooms are the core concept of our application. Each room represents a separate drawing space where a user can let their inner Picasso shine. Here’s a detailed breakdown: 1. Room Creation and Storage <div class="code-with-filename"> **main.py** ``` python db = database('data/drawapp.db') rooms = db.t.rooms if rooms not in db.t: rooms.create(id=int, name=str, created_at=str, pk='id') Room = rooms.dataclass() @patch def __ft__(self:Room): return Li(A(self.name, href=f"/rooms/{self.id}")) ``` </div> Or you can use our `fast_app` function to create a FastHTML app with a SQLite database and dataclass in one line: <div class="code-with-filename"> **main.py** ``` python def render(room): return Li(A(room.name, href=f"/rooms/{room.id}")) app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, pk='id') ``` </div> We are specifying a render function to convert our dataclass into HTML, which is the same as extending the `__ft__` method from the `patch` decorator we used before. We will use this method for the rest of the tutorial since it is a lot cleaner and easier to read. - We’re using a SQLite database (via FastLite) to store our rooms. - Each room has an id (integer), a name (string), and a created_at timestamp (string). - The Room dataclass is automatically generated based on this structure. 2. Creating a room <div class="code-with-filename"> **main.py** ``` python @rt("/") def get(): # The 'Input' id defaults to the same as the name, so you can omit it if you wish create_room = Form(Input(id="name", name="name", placeholder="New Room Name"), Button("Create Room"), hx_post="/rooms", hx_target="#rooms-list", hx_swap="afterbegin") rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list') return Titled("DrawCollab", H1("DrawCollab"), create_room, rooms_list) @rt("/rooms") async def post(room:Room): room.created_at = datetime.now().isoformat() return rooms.insert(room) ``` </div> - When a user submits the β€œCreate Room” form, this route is called. - It creates a new Room object, sets the creation time, and inserts it into the database. - It returns an HTML list item with a link to the new room, which is dynamically added to the room list on the homepage thanks to HTMX. 3. Let’s give our rooms shape <div class="code-with-filename"> **main.py** ``` python @rt("/rooms/{id}") async def get(id:int): room = rooms[id] return Titled(f"Room: {room.name}", H1(f"Welcome to {room.name}"), A(Button("Leave Room"), href="/")) ``` </div> - This route renders the interface for a specific room. - It fetches the room from the database and renders a title, heading, and paragraph. Here is the full code so far: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * from datetime import datetime def render(room): return Li(A(room.name, href=f"/rooms/{room.id}")) app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, pk='id') @rt("/") def get(): create_room = Form(Input(id="name", name="name", placeholder="New Room Name"), Button("Create Room"), hx_post="/rooms", hx_target="#rooms-list", hx_swap="afterbegin") rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list') return Titled("DrawCollab", create_room, rooms_list) @rt("/rooms") async def post(room:Room): room.created_at = datetime.now().isoformat() return rooms.insert(room) @rt("/rooms/{id}") async def get(id:int): room = rooms[id] return Titled(f"Room: {room.name}", H1(f"Welcome to {room.name}"), A(Button("Leave Room"), href="/")) serve() ``` </div> Now run `python main.py` in your terminal and open your browser to the β€˜Link’ that appears. You should see a page with a form to create a new room and a list of existing rooms. #### The Canvas - Let’s Get Drawing! πŸ–ŒοΈ Time to add the actual drawing functionality. We’ll use Fabric.js for this: <div class="code-with-filename"> **main.py** ``` python # ... (keep the previous imports and database setup) @rt("/rooms/{id}") async def get(id:int): room = rooms[id] canvas = Canvas(id="canvas", width="800", height="600") color_picker = Input(type="color", id="color-picker", value="#3CDD8C") brush_size = Input(type="range", id="brush-size", min="1", max="50", value="10") js = """ var canvas = new fabric.Canvas('canvas'); canvas.isDrawingMode = true; canvas.freeDrawingBrush.color = '#3CDD8C'; canvas.freeDrawingBrush.width = 10; document.getElementById('color-picker').onchange = function() { canvas.freeDrawingBrush.color = this.value; }; document.getElementById('brush-size').oninput = function() { canvas.freeDrawingBrush.width = parseInt(this.value, 10); }; """ return Titled(f"Room: {room.name}", A(Button("Leave Room"), href="/"), canvas, Div(color_picker, brush_size), Script(src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"), Script(js)) # ... (keep the serve() part) ``` </div> Now we’ve got a drawing canvas! FastHTML makes it easy to include external libraries and add custom JavaScript. #### Saving and Loading Canvases πŸ’Ύ Now that we have a working drawing canvas, let’s add the ability to save and load drawings. We’ll modify our database schema to include a `canvas_data` field, and add new routes for saving and loading canvas data. Here’s how we’ll update our code: 1. Modify the database schema: <div class="code-with-filename"> **main.py** ``` python app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, canvas_data=str, pk='id') ``` </div> 2. Add a save button that grabs the canvas’ state and sends it to the server: <div class="code-with-filename"> **main.py** ``` python @rt("/rooms/{id}") async def get(id:int): room = rooms[id] canvas = Canvas(id="canvas", width="800", height="600") color_picker = Input(type="color", id="color-picker", value="#3CDD8C") brush_size = Input(type="range", id="brush-size", min="1", max="50", value="10") save_button = Button("Save Canvas", id="save-canvas", hx_post=f"/rooms/{id}/save", hx_vals="js:{canvas_data: JSON.stringify(canvas.toJSON())}") # ... (rest of the function remains the same) ``` </div> 3. Add routes for saving and loading canvas data: <div class="code-with-filename"> **main.py** ``` python @rt("/rooms/{id}/save") async def post(id:int, canvas_data:str): rooms.update({'canvas_data': canvas_data}, id) return "Canvas saved successfully" @rt("/rooms/{id}/load") async def get(id:int): room = rooms[id] return room.canvas_data if room.canvas_data else "{}" ``` </div> 4. Update the JavaScript to load existing canvas data: <div class="code-with-filename"> **main.py** ``` javascript js = f""" var canvas = new fabric.Canvas('canvas'); canvas.isDrawingMode = true; canvas.freeDrawingBrush.color = '#3CDD8C'; canvas.freeDrawingBrush.width = 10; // Load existing canvas data fetch(`/rooms/{id}/load`) .then(response => response.json()) .then(data => {{ if (data && Object.keys(data).length > 0) {{ canvas.loadFromJSON(data, canvas.renderAll.bind(canvas)); }} }}); // ... (rest of the JavaScript remains the same) """ ``` </div> With these changes, users can now save their drawings and load them when they return to the room. The canvas data is stored as a JSON string in the database, allowing for easy serialization and deserialization. Try it out! Create a new room, make a drawing, save it, and then reload the page. You should see your drawing reappear, ready for further editing. Here is the completed code: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * from datetime import datetime def render(room): return Li(A(room.name, href=f"/rooms/{room.id}")) app,rt,rooms,Room = fast_app('data/drawapp.db', render=render, id=int, name=str, created_at=str, canvas_data=str, pk='id') @rt("/") def get(): create_room = Form(Input(id="name", name="name", placeholder="New Room Name"), Button("Create Room"), hx_post="/rooms", hx_target="#rooms-list", hx_swap="afterbegin") rooms_list = Ul(*rooms(order_by='id DESC'), id='rooms-list') return Titled("QuickDraw", create_room, rooms_list) @rt("/rooms") async def post(room:Room): room.created_at = datetime.now().isoformat() return rooms.insert(room) @rt("/rooms/{id}") async def get(id:int): room = rooms[id] canvas = Canvas(id="canvas", width="800", height="600") color_picker = Input(type="color", id="color-picker", value="#000000") brush_size = Input(type="range", id="brush-size", min="1", max="50", value="10") save_button = Button("Save Canvas", id="save-canvas", hx_post=f"/rooms/{id}/save", hx_vals="js:{canvas_data: JSON.stringify(canvas.toJSON())}") js = f""" var canvas = new fabric.Canvas('canvas'); canvas.isDrawingMode = true; canvas.freeDrawingBrush.color = '#000000'; canvas.freeDrawingBrush.width = 10; // Load existing canvas data fetch(`/rooms/{id}/load`) .then(response => response.json()) .then(data => {{ if (data && Object.keys(data).length > 0) {{ canvas.loadFromJSON(data, canvas.renderAll.bind(canvas)); }} }}); document.getElementById('color-picker').onchange = function() {{ canvas.freeDrawingBrush.color = this.value; }}; document.getElementById('brush-size').oninput = function() {{ canvas.freeDrawingBrush.width = parseInt(this.value, 10); }}; """ return Titled(f"Room: {room.name}", A(Button("Leave Room"), href="/"), canvas, Div(color_picker, brush_size, save_button), Script(src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"), Script(js)) @rt("/rooms/{id}/save") async def post(id:int, canvas_data:str): rooms.update({'canvas_data': canvas_data}, id) return "Canvas saved successfully" @rt("/rooms/{id}/load") async def get(id:int): room = rooms[id] return room.canvas_data if room.canvas_data else "{}" serve() ``` </div> ### Deploying to Railway You can deploy your website to a number of hosting providers, for this tutorial we’ll be using Railway. To get started, make sure you create an [account](https://railway.app/) and install the [Railway CLI](https://docs.railway.app/guides/cli). Once installed, make sure to run `railway login` to log in to your account. To make deploying your website as easy as possible, FastHTMl comes with a built in CLI tool that will handle most of the deployment process for you. To deploy your website, run the following command in your terminal in the root directory of your project: ``` sh fh_railway_deploy quickdraw ``` <div> > **Note** > > Your app must be located in a `main.py` file for this to work. </div> ### Conclusion: You’re a FastHTML Artist Now! πŸŽ¨πŸš€ Congratulations! You’ve just built a sleek, interactive web application using FastHTML. Let’s recap what we’ve learned: 1. FastHTML allows you to create dynamic web apps with minimal code. 2. We used FastHTML’s routing system to handle different pages and actions. 3. We integrated with a SQLite database to store room information and canvas data. 4. We utilized Fabric.js to create an interactive drawing canvas. 5. We implemented features like color picking, brush size adjustment, and canvas saving. 6. We used HTMX for seamless, partial page updates without full reloads. 7. We learned how to deploy our FastHTML application to Railway for easy hosting. You’ve taken your first steps into the world of FastHTML development. From here, the possibilities are endless! You could enhance the drawing app further by adding features like: - Implementing different drawing tools (e.g., shapes, text) - Adding user authentication - Creating a gallery of saved drawings - Implementing real-time collaborative drawing using WebSockets Whatever you choose to build next, FastHTML has got your back. Now go forth and create something awesome! Happy coding! πŸ–ΌοΈπŸš€
https://docs.fastht.ml/tutorials/e2e.html.md
tutorials_e2e.html.md
# FastHTML By Example <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> This tutorial provides an alternate introduction to FastHTML by building out example applications. We also illustrate how to use FastHTML foundations to create custom web apps. Finally, this document serves as minimal context for a LLM to turn it into a FastHTML assistant. Let’s get started. ## FastHTML Basics FastHTML is *just Python*. You can install it with `pip install python-fasthtml`. Extensions/components built for it can likewise be distributed via PyPI or as simple Python files. The core usage of FastHTML is to define routes, and then to define what to do at each route. This is similar to the [FastAPI](https://fastapi.tiangolo.com/) web framework (in fact we implemented much of the functionality to match the FastAPI usage examples), but where FastAPI focuses on returning JSON data to build APIs, FastHTML focuses on returning HTML data. Here’s a simple FastHTML app that returns a β€œHello, World” message: ``` python from fasthtml.common import FastHTML, serve app = FastHTML() @app.get("/") def home(): return "<h1>Hello, World</h1>" serve() ``` To run this app, place it in a file, say `app.py`, and then run it with `python app.py`. INFO: Will watch for changes in these directories: ['/home/jonathan/fasthtml-example'] INFO: Uvicorn running on http://127.0.0.1:5001 (Press CTRL+C to quit) INFO: Started reloader process [871942] using WatchFiles INFO: Started server process [871945] INFO: Waiting for application startup. INFO: Application startup complete. If you navigate to <http://127.0.0.1:5001> in a browser, you’ll see your β€œHello, World”. If you edit the `app.py` file and save it, the server will reload and you’ll see the updated message when you refresh the page in your browser. ## Constructing HTML Notice we wrote some HTML in the previous example. We don’t want to do that! Some web frameworks require that you learn HTML, CSS, JavaScript AND some templating language AND python. We want to do as much as possible with just one language. Fortunately, the Python module [fastcore.xml](https://fastcore.fast.ai/xml.html) has all we need for constructing HTML from Python, and FastHTML includes all the tags you need to get started. For example: ``` python from fasthtml.common import * page = Html( Head(Title('Some page')), Body(Div('Some text, ', A('A link', href='https://example.com'), Img(src="https://placehold.co/200"), cls='myclass'))) print(to_xml(page)) ``` <!doctype html></!doctype> <html> <head> <title>Some page</title> </head> <body> <div class="myclass"> Some text, <a href="https://example.com">A link</a> <img src="https://placehold.co/200"> </div> </body> </html> ``` python show(page) ``` <!doctype html></!doctype> &#10;<html> <head> <title>Some page</title> </head> <body> <div class="myclass"> Some text, <a href="https://example.com">A link</a> <img src="https://placehold.co/200"> </div> </body> </html> If that `import *` worries you, you can always import only the tags you need. FastHTML is smart enough to know about fastcore.xml, and so you don’t need to use the `to_xml` function to convert your FT objects to HTML. You can just return them as you would any other Python object. For example, if we modify our previous example to use fastcore.xml, we can return an FT object directly: ``` python from fasthtml.common import * app = FastHTML() @app.get("/") def home(): page = Html( Head(Title('Some page')), Body(Div('Some text, ', A('A link', href='https://example.com'), Img(src="https://placehold.co/200"), cls='myclass'))) return page serve() ``` This will render the HTML in the browser. For debugging, you can right-click on the rendered HTML in the browser and select β€œInspect” to see the underlying HTML that was generated. There you’ll also find the β€˜network’ tab, which shows you the requests that were made to render the page. Refresh and look for the request to `127.0.0.1` - and you’ll see it’s just a `GET` request to `/`, and the response body is the HTML you just returned. <div> > **Live Reloading** > > You can also enable [live reloading](../ref/live_reload.ipynb) so you > don’t have to manually refresh your browser to view updates. </div> You can also use Starlette’s `TestClient` to try it out in a notebook: ``` python from starlette.testclient import TestClient client = TestClient(app) r = client.get("/") print(r.text) ``` <html> <head><title>Some page</title> </head> <body><div class="myclass"> Some text, <a href="https://example.com">A link</a> <img src="https://placehold.co/200"> </div> </body> </html> FastHTML wraps things in an Html tag if you don’t do it yourself (unless the request comes from htmx, in which case you get the element directly). See [FT objects and HTML](#ft-objects-and-html) for more on creating custom components or adding HTML rendering to existing Python objects. To give the page a non-default title, return a Title before your main content: ``` python app = FastHTML() @app.get("/") def home(): return Title("Page Demo"), Div(H1('Hello, World'), P('Some text'), P('Some more text')) client = TestClient(app) print(client.get("/").text) ``` <!doctype html></!doctype> <html> <head> <title>Page Demo</title> <meta charset="utf-8"></meta> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"></meta> <script src="https://unpkg.com/htmx.org@next/dist/htmx.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/answerdotai/[email protected]/surreal.js"></script> <script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script> </head> <body> <div> <h1>Hello, World</h1> <p>Some text</p> <p>Some more text</p> </div> </body> </html> We’ll use this pattern often in the examples to follow. ## Defining Routes The HTTP protocol defines a number of methods (β€˜verbs’) to send requests to a server. The most common are GET, POST, PUT, DELETE, and HEAD. We saw β€˜GET’ in action before - when you navigate to a URL, you’re making a GET request to that URL. We can do different things on a route for different HTTP methods. For example: ``` python @app.route("/", methods='get') def home(): return H1('Hello, World') @app.route("/", methods=['post', 'put']) def post_or_put(): return "got a POST or PUT request" ``` This says that when someone navigates to the root URL β€œ/” (i.e.Β sends a GET request), they will see the big β€œHello, World” heading. When someone submits a POST or PUT request to the same URL, the server should return the string β€œgot a post or put request”. <div> > **Test the POST request** > > You can test the POST request with > `curl -X POST http://127.0.0.1:8000 -d "some data"`. This sends some > data to the server, you should see the response β€œgot a post or put > request” printed in the terminal. </div> There are a few other ways you can specify the route+method - FastHTML has `.get`, `.post`, etc. as shorthand for `route(..., methods=['get'])`, etc. ``` python @app.get("/") def my_function(): return "Hello World from a GET request" ``` Or you can use the `@rt` decorator without a method but specify the method with the name of the function. For example: ``` python rt = app.route @rt("/") def post(): return "Hello World from a POST request" ``` ``` python client.post("/").text ``` 'Hello World from a POST request' You’re welcome to pick whichever style you prefer. Using routes lets you show different content on different pages - β€˜/home’, β€˜/about’ and so on. You can also respond differently to different kinds of requests to the same route, as shown above. You can also pass data via the route: <div class="panel-tabset"> ## `@app.get` ``` python @app.get("/greet/{nm}") def greet(nm:str): return f"Good day to you, {nm}!" client.get("/greet/Dave").text ``` 'Good day to you, Dave!' ## `@rt` ``` python @rt("/greet/{nm}") def get(nm:str): return f"Good day to you, {nm}!" client.get("/greet/Dave").text ``` 'Good day to you, Dave!' </div> More on this in the [More on Routing and Request Parameters](#more-on-routing-and-request-parameters) section, which goes deeper into the different ways to get information from a request. ## Styling Basics Plain HTML probably isn’t quite what you imagine when you visualize your beautiful web app. CSS is the go-to language for styling HTML. But again, we don’t want to learn extra languages unless we absolutely have to! Fortunately, there are ways to get much more visually appealing sites by relying on the hard work of others, using existing CSS libraries. One of our favourites is [PicoCSS](https://picocss.com/). A common way to add CSS files to web pages is to use a [`<link>`](https://www.w3schools.com/tags/tag_link.asp) tag inside your [HTML header](https://www.w3schools.com/tags/tag_header.asp), like this: ``` html <header> ... <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@latest/css/pico.min.css"> </header> ``` For convenience, FastHTML already defines a Pico component for you with `picolink`: ``` python print(to_xml(picolink)) ``` <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@latest/css/pico.min.css"> <style>:root { --pico-font-size: 100%; }</style> <div> > **Note** > > `picolink` also includes a `<style>` tag, as we found that setting the > font-size to 100% to be a good default. We show you how to override > this below. </div> Since we typically want CSS styling on all pages of our app, FastHTML lets you define a shared HTML header with the `hdrs` argument as shown below: ``` python from fasthtml.common import * css = Style(':root {--pico-font-size:90%,--pico-font-family: Pacifico, cursive;}') app = FastHTML(hdrs=(picolink, css)) @app.route("/") def get(): return (Title("Hello World"), Main(H1('Hello, World'), cls="container")) ``` Line 2 Custom styling to override the pico defaults Line 3 Define shared headers for all pages Line 8 As per the [pico docs](https://picocss.com/docs), we put all of our content inside a `<main>` tag with a class of `container`: <div> > **Returning Tuples** > > We’re returning a tuple here (a title and the main page). Returning a > tuple, list, `FT` object, or an object with a `__ft__` method tells > FastHTML to turn the main body into a full HTML page that includes the > headers (including the pico link and our custom css) which we passed > in. This only occurs if the request isn’t from HTMX (for HTMX requests > we need only return the rendered components). </div> You can check out the Pico [examples](https://picocss.com/examples) page to see how different elements will look. If everything is working, the page should now render nice text with our custom font, and it should respect the user’s light/dark mode preferences too. If you want to [override the default styles](https://picocss.com/docs/css-variables) or add more custom CSS, you can do so by adding a `<style>` tag to the headers as shown above. So you are allowed to write CSS to your heart’s content - we just want to make sure you don’t necessarily have to! Later on we’ll see examples using other component libraries and tailwind css to do more fancy styling things, along with tips to get an LLM to write all those fiddly bits so you don’t have to. ## Web Page -\> Web App Showing content is all well and good, but we typically expect a bit more *interactivity* from something calling itself a web app! So, let’s add a few different pages, and use a form to let users add messages to a list: ``` python app = FastHTML() messages = ["This is a message, which will get rendered as a paragraph"] @app.get("/") def home(): return Main(H1('Messages'), *[P(msg) for msg in messages], A("Link to Page 2 (to add messages)", href="/page2")) @app.get("/page2") def page2(): return Main(P("Add a message with the form below:"), Form(Input(type="text", name="data"), Button("Submit"), action="/", method="post")) @app.post("/") def add_message(data:str): messages.append(data) return home() ``` We re-render the entire homepage to show the newly added message. This is fine, but modern web apps often don’t re-render the entire page, they just update a part of the page. In fact even very complicated applications are often implemented as β€˜Single Page Apps’ (SPAs). This is where HTMX comes in. ## HTMX [HTMX](https://htmx.org/) addresses some key limitations of HTML. In vanilla HTML, links can trigger a GET request to show a new page, and forms can send requests containing data to the server. A lot of β€˜Web 1.0’ design revolved around ways to use these to do everything we wanted. But why should only *some* elements be allowed to trigger requests? And why should we refresh the *entire page* with the result each time one does? HTMX extends HTML to allow us to trigger requests from *any* element on all kinds of events, and to update a part of the page without refreshing the entire page. It’s a powerful tool for building modern web apps. It does this by adding attributes to HTML tags to make them do things. For example, here’s a page with a counter and a button that increments it: ``` python app = FastHTML() count = 0 @app.get("/") def home(): return Title("Count Demo"), Main( H1("Count Demo"), P(f"Count is set to {count}", id="count"), Button("Increment", hx_post="/increment", hx_target="#count", hx_swap="innerHTML") ) @app.post("/increment") def increment(): print("incrementing") global count count += 1 return f"Count is set to {count}" ``` The button triggers a POST request to `/increment` (since we set `hx_post="/increment"`), which increments the count and returns the new count. The `hx_target` attribute tells HTMX where to put the result. If no target is specified it replaces the element that triggered the request. The `hx_swap` attribute specifies how it adds the result to the page. Useful options are: - *`innerHTML`*: Replace the target element’s content with the result. - *`outerHTML`*: Replace the target element with the result. - *`beforebegin`*: Insert the result before the target element. - *`beforeend`*: Insert the result inside the target element, after its last child. - *`afterbegin`*: Insert the result inside the target element, before its first child. - *`afterend`*: Insert the result after the target element. You can also use an hx_swap of `delete` to delete the target element regardless of response, or of `none` to do nothing. By default, requests are triggered by the β€œnatural” event of an element - click in the case of a button (and most other elements). You can also specify different triggers, along with various modifiers - see the [HTMX docs](https://htmx.org/docs/#triggers) for more. This pattern of having elements trigger requests that modify or replace other elements is a key part of the HTMX philosophy. It takes a little getting used to, but once mastered it is extremely powerful. ### Replacing Elements Besides the Target Sometimes having a single target is not enough, and we’d like to specify some additional elements to update or remove. In these cases, returning elements with an id that matches the element to be replaced and `hx_swap_oob='true'` will replace those elements too. We’ll use this in the next example to clear an input field when we submit a form. ## Full Example \#1 - ToDo App The canonical demo web app! A TODO list. Rather than create yet another variant for this tutorial, we recommend starting with this video tutorial from Jeremy: <https://www.youtube.com/embed/Auqrm7WFc0I> <figure> <img src="by_example_files/figure-commonmark/cell-53-1-image.png" alt="image.png" /> <figcaption aria-hidden="true">image.png</figcaption> </figure> We’ve made a number of variants of this app - so in addition to the version shown in the video you can browse [this](https://github.com/AnswerDotAI/fasthtml-tut) series of examples with increasing complexity, the heavily-commented [β€œidiomatic” version here](https://github.com/AnswerDotAI/fasthtml/blob/main/examples/adv_app.py), and the [example](https://github.com/AnswerDotAI/fasthtml-example/tree/main/01_todo_app) linked from the [FastHTML homepage](https://fastht.ml/). ## Full Example \#2 - Image Generation App Let’s create an image generation app. We’d like to wrap a text-to-image model in a nice UI, where the user can type in a prompt and see a generated image appear. We’ll use a model hosted by [Replicate](https://replicate.com) to actually generate the images. Let’s start with the homepage, with a form to submit prompts and a div to hold the generated images: ``` python # Main page @app.get("/") def get(): inp = Input(id="new-prompt", name="prompt", placeholder="Enter a prompt") add = Form(Group(inp, Button("Generate")), hx_post="/", target_id='gen-list', hx_swap="afterbegin") gen_list = Div(id='gen-list') return Title('Image Generation Demo'), Main(H1('Magic Image Generation'), add, gen_list, cls='container') ``` Submitting the form will trigger a POST request to `/`, so next we need to generate an image and add it to the list. One problem: generating images is slow! We’ll start the generation in a separate thread, but this now surfaces a different problem: we want to update the UI right away, but our image will only be ready a few seconds later. This is a common pattern - think about how often you see a loading spinner online. We need a way to return a temporary bit of UI which will eventually be replaced by the final image. Here’s how we might do this: ``` python def generation_preview(id): if os.path.exists(f"gens/{id}.png"): return Div(Img(src=f"/gens/{id}.png"), id=f'gen-{id}') else: return Div("Generating...", id=f'gen-{id}', hx_post=f"/generations/{id}", hx_trigger='every 1s', hx_swap='outerHTML') @app.post("/generations/{id}") def get(id:int): return generation_preview(id) @app.post("/") def post(prompt:str): id = len(generations) generate_and_save(prompt, id) generations.append(prompt) clear_input = Input(id="new-prompt", name="prompt", placeholder="Enter a prompt", hx_swap_oob='true') return generation_preview(id), clear_input @threaded def generate_and_save(prompt, id): ... ``` The form sends the prompt to the `/` route, which starts the generation in a separate thread then returns two things: - A generation preview element that will be added to the top of the `gen-list` div (since that is the target_id of the form which triggered the request) - An input field that will replace the form’s input field (that has the same id), using the hx_swap_oob=β€˜true’ trick. This clears the prompt field so the user can type another prompt. The generation preview first returns a temporary β€œGenerating…” message, which polls the `/generations/{id}` route every second. This is done by setting hx_post to the route and hx_trigger to β€˜every 1s’. The `/generations/{id}` route returns the preview element every second until the image is ready, at which point it returns the final image. Since the final image replaces the temporary one (hx_swap=β€˜outerHTML’), the polling stops running and the generation preview is now complete. This works nicely - the user can submit several prompts without having to wait for the first one to generate, and as the images become available they are added to the list. You can see the full code of this version [here](https://github.com/AnswerDotAI/fasthtml-example/blob/main/image_app_simple/draft1.py). ### Again, with Style The app is functional, but can be improved. The [next version](https://github.com/AnswerDotAI/fasthtml-example/blob/main/image_app_simple/main.py) adds more stylish generation previews, lays out the images in a grid layout that is responsive to different screen sizes, and adds a database to track generations and make them persistent. The database part is very similar to the todo list example, so let’s just quickly look at how we add the nice grid layout. This is what the result looks like: <figure> <img src="by_example_files/figure-commonmark/cell-58-1-image.png" alt="image.png" /> <figcaption aria-hidden="true">image.png</figcaption> </figure> Step one was looking around for existing components. The Pico CSS library we’ve been using has a rudimentary grid but recommends using an alternative layout system. One of the options listed was [Flexbox](http://flexboxgrid.com/). To use Flexbox you create a β€œrow” with one or more elements. You can specify how wide things should be with a specific syntax in the class name. For example, `col-xs-12` means a box that will take up 12 columns (out of 12 total) of the row on extra small screens, `col-sm-6` means a column that will take up 6 columns of the row on small screens, and so on. So if you want four columns on large screens you would use `col-lg-3` for each item (i.e.Β each item is using 3 columns out of 12). ``` html <div class="row"> <div class="col-xs-12"> <div class="box">This takes up the full width</div> </div> </div> ``` This was non-intuitive to me. Thankfully ChatGPT et al know web stuff quite well, and we can also experiment in a notebook to test things out: ``` python grid = Html( Link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css", type="text/css"), Div( Div(Div("This takes up the full width", cls="box", style="background-color: #800000;"), cls="col-xs-12"), Div(Div("This takes up half", cls="box", style="background-color: #008000;"), cls="col-xs-6"), Div(Div("This takes up half", cls="box", style="background-color: #0000B0;"), cls="col-xs-6"), cls="row", style="color: #fff;" ) ) show(grid) ``` <!doctype html></!doctype> &#10;<html> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css" type="text/css"> <div class="row" style="color: #fff;"> <div class="col-xs-12"> <div class="box" style="background-color: #800000;">This takes up the full width</div> </div> <div class="col-xs-6"> <div class="box" style="background-color: #008000;">This takes up half</div> </div> <div class="col-xs-6"> <div class="box" style="background-color: #0000B0;">This takes up half</div> </div> </div> </html> Aside: when in doubt with CSS stuff, add a background color or a border so you can see what’s happening! Translating this into our app, we have a new homepage with a `div (class="row")` to store the generated images / previews, and a `generation_preview` function that returns boxes with the appropriate classes and styles to make them appear in the grid. I chose a layout with different numbers of columns for different screen sizes, but you could also *just* specify the `col-xs` class if you wanted the same layout on all devices. ``` python gridlink = Link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/flexboxgrid/6.3.1/flexboxgrid.min.css", type="text/css") app = FastHTML(hdrs=(picolink, gridlink)) # Main page @app.get("/") def get(): inp = Input(id="new-prompt", name="prompt", placeholder="Enter a prompt") add = Form(Group(inp, Button("Generate")), hx_post="/", target_id='gen-list', hx_swap="afterbegin") gen_containers = [generation_preview(g) for g in gens(limit=10)] # Start with last 10 gen_list = Div(*gen_containers[::-1], id='gen-list', cls="row") # flexbox container: class = row return Title('Image Generation Demo'), Main(H1('Magic Image Generation'), add, gen_list, cls='container') # Show the image (if available) and prompt for a generation def generation_preview(g): grid_cls = "box col-xs-12 col-sm-6 col-md-4 col-lg-3" image_path = f"{g.folder}/{g.id}.png" if os.path.exists(image_path): return Div(Card( Img(src=image_path, alt="Card image", cls="card-img-top"), Div(P(B("Prompt: "), g.prompt, cls="card-text"),cls="card-body"), ), id=f'gen-{g.id}', cls=grid_cls) return Div(f"Generating gen {g.id} with prompt {g.prompt}", id=f'gen-{g.id}', hx_get=f"/gens/{g.id}", hx_trigger="every 2s", hx_swap="outerHTML", cls=grid_cls) ``` You can see the final result in [main.py](https://github.com/AnswerDotAI/fasthtml-example/blob/main/image_app_simple/main.py) in the `image_app_simple` example directory, along with info on deploying it (tl;dr don’t!). We’ve also deployed a version that only shows *your* generations (tied to browser session) and has a credit system to save our bank accounts. You can access that [here](https://image-gen-public-credit-pool.replit.app/). Now for the next question: how do we keep track of different users? ### Again, with Sessions At the moment everyone sees all images! How do we keep some sort of unique identifier tied to a user? Before going all the way to setting up users, login pages etc., let’s look at a way to at least limit generations to the user’s *session*. You could do this manually with cookies. For convenience and security, fasthtml (via Starlette) has a special mechanism for storing small amounts of data in the user’s browser via the `session` argument to your route. This acts like a dictionary and you can set and get values from it. For example, here we look for a `session_id` key, and if it doesn’t exist we generate a new one: ``` python @app.get("/") def get(session): if 'session_id' not in session: session['session_id'] = str(uuid.uuid4()) return H1(f"Session ID: {session['session_id']}") ``` Refresh the page a few times - you’ll notice that the session ID remains the same. If you clear your browsing data, you’ll get a new session ID. And if you load the page in a different browser (but not a different tab), you’ll get a new session ID. This will persist within the current browser, letting us use it as a key for our generations. As a bonus, someone can’t spoof this session id by passing it in another way (for example, sending a query parameter). Behind the scenes, the data *is* stored in a browser cookie but it is signed with a secret key that stops the user or anyone nefarious from being able to tamper with it. The cookie is decoded back into a dictionary by something called a middleware function, which we won’t cover here. All you need to know is that we can use this to store bits of state in the user’s browser. In the image app example, we can add a `session_id` column to our database, and modify our homepage like so: ``` python @app.get("/") def get(session): if 'session_id' not in session: session['session_id'] = str(uuid.uuid4()) inp = Input(id="new-prompt", name="prompt", placeholder="Enter a prompt") add = Form(Group(inp, Button("Generate")), hx_post="/", target_id='gen-list', hx_swap="afterbegin") gen_containers = [generation_preview(g) for g in gens(limit=10, where=f"session_id == '{session['session_id']}'")] ... ``` So we check if the session id exists in the session, add one if not, and then limit the generations shown to only those tied to this session id. We filter the database with a where clause - see \[TODO link Jeremy’s example for a more reliable way to do this\]. The only other change we need to make is to store the session id in the database when a generation is made. You can check out this version [here](https://github.com/AnswerDotAI/fasthtml-example/blob/main/image_app_session_credits/session.py). You could instead write this app without relying on a database at all - simply storing the filenames of the generated images in the session, for example. But this more general approach of linking some kind of unique session identifier to users or data in our tables is a useful general pattern for more complex examples. ### Again, with Credits! Generating images with replicate costs money. So next let’s add a pool of credits that get used up whenever anyone generates an image. To recover our lost funds, we’ll also set up a payment system so that generous users can buy more credits for everyone. You could modify this to let users buy credits tied to their session ID, but at that point you risk having angry customers losing their money after wiping their browser history, and should consider setting up proper account management :) Taking payments with Stripe is intimidating but very doable. [Here’s a tutorial](https://testdriven.io/blog/flask-stripe-tutorial/) that shows the general principle using Flask. As with other popular tasks in the web-dev world, ChatGPT knows a lot about Stripe - but you should exercise extra caution when writing code that handles money! For the [finished example](https://github.com/AnswerDotAI/fasthtml-example/blob/main/image_app_session_credits/main.py) we add the bare minimum: - A way to create a Stripe checkout session and redirect the user to the session URL - β€˜Success’ and β€˜Cancel’ routes to handle the result of the checkout - A route that listens for a webhook from Stripe to update the number of credits when a payment is made. In a typical application you’ll want to keep track of which users make payments, catch other kinds of stripe events and so on. This example is more a β€˜this is possible, do your own research’ than β€˜this is how you do it’. But hopefully it does illustrate the key idea: there is no magic here. Stripe (and many other technologies) relies on sending users to different routes and shuttling data back and forth in requests. And we know how to do that! ## More on Routing and Request Parameters There are a number of ways information can be passed to the server. When you specify arguments to a route, FastHTML will search the request for values with the same name, and convert them to the correct type. In order, it searches - The path parameters - The query parameters - The cookies - The headers - The session - Form data There are also a few special arguments - `request` (or any prefix like `req`): gets the raw Starlette `Request` object - `session` (or any prefix like `sess`): gets the session object - `auth` - `htmx` - `app` In this section let’s quickly look at some of these in action. ``` python from fasthtml.common import * from starlette.testclient import TestClient app = FastHTML() cli = TestClient(app) ``` Part of the route (path parameters): ``` python @app.get('/user/{nm}') def _(nm:str): return f"Good day to you, {nm}!" cli.get('/user/jph').text ``` 'Good day to you, jph!' Matching with a regex: ``` python reg_re_param("imgext", "ico|gif|jpg|jpeg|webm") @app.get(r'/static/{path:path}/{fn}.{ext:imgext}') def get_img(fn:str, path:str, ext:str): return f"Getting {fn}.{ext} from /{path}" cli.get('/static/foo/jph.ico').text ``` 'Getting jph.ico from /foo/' Using an enum (try using a string that isn’t in the enum): ``` python ModelName = str_enum('ModelName', "alexnet", "resnet", "lenet") @app.get("/models/{nm}") def model(nm:ModelName): return nm print(cli.get('/models/alexnet').text) ``` alexnet Casting to a Path: ``` python @app.get("/files/{path}") def txt(path: Path): return path.with_suffix('.txt') print(cli.get('/files/foo').text) ``` foo.txt An integer with a default value: ``` python fake_db = [{"name": "Foo"}, {"name": "Bar"}] @app.get("/items/") def read_item(idx: int = 0): return fake_db[idx] print(cli.get('/items/?idx=1').text) ``` {"name":"Bar"} ``` python # Equivalent to `/items/?idx=0`. print(cli.get('/items/').text) ``` {"name":"Foo"} Boolean values (takes anything β€œtruthy” or β€œfalsy”): ``` python @app.get("/booly/") def booly(coming:bool=True): return 'Coming' if coming else 'Not coming' print(cli.get('/booly/?coming=true').text) ``` Coming ``` python print(cli.get('/booly/?coming=no').text) ``` Not coming Getting dates: ``` python @app.get("/datie/") def datie(d:parsed_date): return d date_str = "17th of May, 2024, 2p" print(cli.get(f'/datie/?d={date_str}').text) ``` 2024-05-17 14:00:00 Matching a dataclass: ``` python from dataclasses import dataclass, asdict @dataclass class Bodie: a:int;b:str @app.route("/bodie/{nm}") def post(nm:str, data:Bodie): res = asdict(data) res['nm'] = nm return res cli.post('/bodie/me', data=dict(a=1, b='foo')).text ``` '{"a":1,"b":"foo","nm":"me"}' ### Cookies Cookies can be set via a Starlette Response object, and can be read back by specifying the name: ``` python from datetime import datetime @app.get("/setcookie") def setc(req): now = datetime.now() res = Response(f'Set to {now}') res.set_cookie('now', str(now)) return res cli.get('/setcookie').text ``` 'Set to 2024-07-20 23:14:54.364793' ``` python @app.get("/getcookie") def getc(now:parsed_date): return f'Cookie was set at time {now.time()}' cli.get('/getcookie').text ``` 'Cookie was set at time 23:14:54.364793' ### User Agent and HX-Request An argument of `user_agent` will match the header `User-Agent`. This holds for special headers like `HX-Request` (used by HTMX to signal when a request comes from an HTMX request) - the general pattern is that β€œ-” is replaced with β€œ\_” and strings are turned to lowercase. ``` python @app.get("/ua") async def ua(user_agent:str): return user_agent cli.get('/ua', headers={'User-Agent':'FastHTML'}).text ``` 'FastHTML' ``` python @app.get("/hxtest") def hxtest(htmx): return htmx.request cli.get('/hxtest', headers={'HX-Request':'1'}).text ``` '1' ### Starlette Requests If you add an argument called `request`(or any prefix of that, for example `req`) it will be populated with the Starlette `Request` object. This is useful if you want to do your own processing manually. For example, although FastHTML will parse forms for you, you could instead get form data like so: ``` python @app.get("/form") async def form(request:Request): form_data = await request.form() a = form_data.get('a') ``` See the [Starlette docs](https://starlette.io/docs/) for more information on the `Request` object. ### Starlette Responses You can return a Starlette Response object from a route to control the response. For example: ``` python @app.get("/redirect") def redirect(): return RedirectResponse(url="/") ``` We used this to set cookies in the previous example. See the [Starlette docs](https://starlette.io/docs/) for more information on the `Response` object. ### Static Files We often want to serve static files like images. This is easily done! For common file types (images, CSS etc) we can create a route that returns a Starlette `FileResponse` like so: ``` python # For images, CSS, etc. @app.get("/{fname:path}.{ext:static}") def static(fname: str, ext: str): return FileResponse(f'{fname}.{ext}') ``` You can customize it to suit your needs (for example, only serving files in a certain directory). You’ll notice some variant of this route in all our complete examples - even for apps with no static files the browser will typically request a `/favicon.ico` file, for example, and as the astute among you will have noticed this has sparked a bit of competition between Johno and Jeremy regarding which country flag should serve as the default! ### WebSockets For certain applications such as multiplayer games, websockets can be a powerful feature. Luckily HTMX and FastHTML has you covered! Simply specify that you wish to include the websocket header extension from HTMX: ``` python app = FastHTML(exts='ws') rt = app.route ``` With that, you are now able to specify the different websocket specific HTMX goodies. For example, say we have a website we want to setup a websocket, you can simply: ``` python def mk_inp(): return Input(id='msg') @rt('/') async def get(request): cts = Div( Div(id='notifications'), Form(mk_inp(), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) ``` And this will setup a connection on the route `/ws` along with a form that will send a message to the websocket whenever the form is submitted. Let’s go ahead and handle this route: ``` python @app.ws('/ws') async def ws(msg:str, send): await send(Div('Hello ' + msg, id="notifications")) await sleep(2) return Div('Goodbye ' + msg, id="notifications"), mk_inp() ``` One thing you might have noticed is a lack of target id for our websocket trigger for swapping HTML content. This is because HTMX always swaps content with websockets with Out of Band Swaps. Therefore, HTMX will look for the id in the returned HTML content from the server for determining what to swap. To send stuff to the client, you can either use the `send` parameter or simply return the content or both! Now, sometimes you might want to perform actions when a client connects or disconnects such as add or remove a user from a player queue. To hook into these events, you can pass your connection or disconnection function to the `app.ws` decorator: ``` python async def on_connect(send): print('Connected!') await send(Div('Hello, you have connected', id="notifications")) async def on_disconnect(ws): print('Disconnected!') @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str, send): await send(Div('Hello ' + msg, id="notifications")) await sleep(2) return Div('Goodbye ' + msg, id="notifications"), mk_inp() ``` ## Full Example \#3 - Chatbot Example with DaisyUI Components Let’s go back to the topic of adding components or styling beyond the simple PicoCSS examples so far. How might we adopt a component or framework? In this example, let’s build a chatbot UI leveraging the [DaisyUI chat bubble](https://daisyui.com/components/chat/). The final result will look like this: <figure> <img src="by_example_files/figure-commonmark/cell-101-1-image.png" alt="image.png" /> <figcaption aria-hidden="true">image.png</figcaption> </figure> At first glance, DaisyUI’s chat component looks quite intimidating. The examples look like this: ``` html <div class="chat chat-start"> <div class="chat-image avatar"> <div class="w-10 rounded-full"> <img alt="Tailwind CSS chat bubble component" src="https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.jpg" /> </div> </div> <div class="chat-header"> Obi-Wan Kenobi <time class="text-xs opacity-50">12:45</time> </div> <div class="chat-bubble">You were the Chosen One!</div> <div class="chat-footer opacity-50"> Delivered </div> </div> <div class="chat chat-end"> <div class="chat-image avatar"> <div class="w-10 rounded-full"> <img alt="Tailwind CSS chat bubble component" src="https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.jpg" /> </div> </div> <div class="chat-header"> Anakin <time class="text-xs opacity-50">12:46</time> </div> <div class="chat-bubble">I hate you!</div> <div class="chat-footer opacity-50"> Seen at 12:46 </div> </div> ``` We have several things going for us however. - ChatGPT knows DaisyUI and Tailwind (DaisyUI is a Tailwind component library) - We can build things up piece by piece with AI standing by to help. <https://h2f.answer.ai/> is a tool that can convert HTML to FT (fastcore.xml) and back, which is useful for getting a quick starting point when you have an HTML example to start from. We can strip out some unnecessary bits and try to get the simplest possible example working in a notebook first: ``` python # Loading tailwind and daisyui headers = (Script(src="https://cdn.tailwindcss.com"), Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/full.min.css")) # Displaying a single message d = Div( Div("Chat header here", cls="chat-header"), Div("My message goes here", cls="chat-bubble chat-bubble-primary"), cls="chat chat-start" ) # show(Html(*headers, d)) # uncomment to view ``` Now we can extend this to render multiple messages, with the message being on the left (`chat-start`) or right (`chat-end`) depending on the role. While we’re at it, we can also change the color (`chat-bubble-primary`) of the message and put them all in a `chat-box` div: ``` python messages = [ {"role":"user", "content":"Hello"}, {"role":"assistant", "content":"Hi, how can I assist you?"} ] def ChatMessage(msg): return Div( Div(msg['role'], cls="chat-header"), Div(msg['content'], cls=f"chat-bubble chat-bubble-{'primary' if msg['role'] == 'user' else 'secondary'}"), cls=f"chat chat-{'end' if msg['role'] == 'user' else 'start'}") chatbox = Div(*[ChatMessage(msg) for msg in messages], cls="chat-box", id="chatlist") # show(Html(*headers, chatbox)) # Uncomment to view ``` Next, it was back to the ChatGPT to tweak the chat box so it wouldn’t grow as messages were added. I asked: "I have something like this (it's working now) [code] The messages are added to this div so it grows over time. Is there a way I can set it's height to always be 80% of the total window height with a scroll bar if needed?" Based on this query GPT4o helpfully shared that β€œThis can be achieved using Tailwind CSS utility classes. Specifically, you can use h-\[80vh\] to set the height to 80% of the viewport height, and overflow-y-auto to add a vertical scroll bar when needed.” To put it another way: none of the CSS classes in the following example were written by a human, and what edits I did make were informed by advice from the AI that made it relatively painless! The actual chat functionality of the app is based on our [claudette](https://claudette.answer.ai/) library. As with the image example, we face a potential hiccup in that getting a response from an LLM is slow. We need a way to have the user message added to the UI immediately, and then have the response added once it’s available. We could do something similar to the image generation example above, or use websockets. Check out the [full example](https://github.com/AnswerDotAI/fasthtml-example/tree/main/02_chatbot) for implementations of both, along with further details. ## Full Example \#4 - Multiplayer Game of Life Example with Websockets Let’s see how we can implement a collaborative website using Websockets in FastHTML. To showcase this, we will use the famous [Conway’s Game of Life](https://en.wikipedia.org/wiki/Conway's_Game_of_Life), which is a game that takes place in a grid world. Each cell in the grid can be either alive or dead. The cell’s state is initially given by a user before the game is started and then evolves through the iteration of the grid world once the clock starts. Whether a cell’s state will change from the previous state depends on simple rules based on its neighboring cells’ states. Here is the standard Game of Life logic implemented in Python courtesy of ChatGPT: ``` python grid = [[0 for _ in range(20)] for _ in range(20)] def update_grid(grid: list[list[int]]) -> list[list[int]]: new_grid = [[0 for _ in range(20)] for _ in range(20)] def count_neighbors(x, y): directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] count = 0 for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]): count += grid[nx][ny] return count for i in range(len(grid)): for j in range(len(grid[0])): neighbors = count_neighbors(i, j) if grid[i][j] == 1: if neighbors < 2 or neighbors > 3: new_grid[i][j] = 0 else: new_grid[i][j] = 1 elif neighbors == 3: new_grid[i][j] = 1 return new_grid ``` This would be a very dull game if we were to run it, since the initial state of everything would remain dead. Therefore, we need a way of letting the user give an initial state before starting the game. FastHTML to the rescue! ``` python def Grid(): cells = [] for y, row in enumerate(game_state['grid']): for x, cell in enumerate(row): cell_class = 'alive' if cell else 'dead' cell = Div(cls=f'cell {cell_class}', hx_put='/update', hx_vals={'x': x, 'y': y}, hx_swap='none', hx_target='#gol', hx_trigger='click') cells.append(cell) return Div(*cells, id='grid') @rt('/update') async def put(x: int, y: int): grid[y][x] = 1 if grid[y][x] == 0 else 0 ``` Above is a component for representing the game’s state that the user can interact with and update on the server using cool HTMX features such as `hx_vals` for determining which cell was clicked to make it dead or alive. Now, you probably noticed that the HTTP request in this case is a PUT request, which does not return anything and this means our client’s view of the grid world and the server’s game state will immediately become out of sync :(. We could of course just return a new Grid component with the updated state, but that would only work for a single client, if we had more, they quickly get out of sync with each other and the server. Now Websockets to the rescue! Websockets are a way for the server to keep a persistent connection with clients and send data to the client without explicitly being requested for information, which is not possible with HTTP. Luckily FastHTML and HTMX work well with Websockets. Simply state you wish to use websockets for your app and define a websocket route: ``` python ... app = FastHTML(hdrs=(picolink, gridlink, css, htmx_ws), exts='ws') player_queue = [] async def update_players(): for i, player in enumerate(player_queue): try: await player(Grid()) except: player_queue.pop(i) async def on_connect(send): player_queue.append(send) async def on_disconnect(send): await update_players() @app.ws('/gol', conn=on_connect, disconn=on_disconnect) async def ws(msg:str, send): pass def Home(): return Title('Game of Life'), Main(gol, Div(Grid(), id='gol', cls='row center-xs'), hx_ext="ws", ws_connect="/gol") @rt('/update') async def put(x: int, y: int): grid[y][x] = 1 if grid[y][x] == 0 else 0 await update_players() ... ``` Here we simply keep track of all the players that have connected or disconnected to our site and when an update occurs, we send updates to all the players still connected via websockets. Via HTMX, you are still simply exchanging HTML from the server to the client and will swap in the content based on how you setup your `hx_swap` attribute. There is only one difference, that being all swaps are OOB. You can find more information on the HTMX websocket extension documentation page [here](https://github.com/bigskysoftware/htmx-extensions/blob/main/src/ws/README.md). You can find a full fledge hosted example of this app [here](https://game-of-life-production-ed7f.up.railway.app/). ## FT objects and HTML These FT objects create a β€˜FastTag’ structure \[tag,children,attrs\] for `to_xml()`. When we call `Div(...)`, the elements we pass in are the children. Attributes are passed in as keywords. `class` and `for` are special words in python, so we use `cls`, `klass` or `_class` instead of `class` and `fr` or `_for` instead of `for`. Note these objects are just 3-element lists - you can create custom ones too as long as they’re also 3-element lists. Alternately, leaf nodes can be strings instead (which is why you can do `Div('some text')`). If you pass something that isn’t a 3-element list or a string, it will be converted to a string using str()… unless (our final trick) you define a `__ft__` method that will run before str(), so you can render things a custom way. For example, here’s one way we could make a custom class that can be rendered into HTML: ``` python class Person: def __init__(self, name, age): self.name = name self.age = age def __ft__(self): return ['div', [f'{self.name} is {self.age} years old.'], {}] p = Person('Jonathan', 28) print(to_xml(Div(p, "more text", cls="container"))) ``` <div class="container"> <div>Jonathan is 28 years old.</div> more text </div> In the examples, you’ll see we often patch in `__ft__` methods to existing classes to control how they’re rendered. For example, if Person didn’t have a `__ft__` method or we wanted to override it, we could add a new one like this: ``` python from fastcore.all import patch @patch def __ft__(self:Person): return Div("Person info:", Ul(Li("Name:",self.name), Li("Age:", self.age))) show(p) ``` <div> Person info: <ul> <li> Name: Jonathan </li> <li> Age: 28 </li> </ul> </div> Some tags from fastcore.xml are overwritten by fasthtml.core and a few are further extended by fasthtml.xtend using this method. Over time, we hope to see others developing custom components too, giving us a larger and larger ecosystem of reusable components. ## Custom Scripts and Styling There are many popular JavaScript and CSS libraries that can be used via a simple [`Script`](https://docs.fastht.ml/api/xtend.html#script) or [`Style`](https://docs.fastht.ml/api/xtend.html#style) tag. But in some cases you will need to write more custom code. FastHTML’s [js.py](https://github.com/AnswerDotAI/fasthtml/blob/main/fasthtml/js.py) contains a few examples that may be useful as reference. For example, to use the [marked.js](https://marked.js.org/) library to render markdown in a div, including in components added after the page has loaded via htmx, we do something like this: ``` javascript import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js"; proc_htmx('%s', e => e.innerHTML = marked.parse(e.textContent)); ``` `proc_htmx` is a shortcut that we wrote to apply a function to elements matching a selector, including the element that triggered the event. Here’s the code for reference: ``` javascript export function proc_htmx(sel, func) { htmx.onLoad(elt => { const elements = htmx.findAll(elt, sel); if (elt.matches(sel)) elements.unshift(elt) elements.forEach(func); }); } ``` The [AI Pictionary example](https://github.com/AnswerDotAI/fasthtml-example/tree/main/03_pictionary) uses a larger chunk of custom JavaScript to handle the drawing canvas. It’s a good example of the type of application where running code on the client side makes the most sense, but still shows how you can integrate it with FastHTML on the server side to add functionality (like the AI responses) easily. Adding styling with custom CSS and libraries such as tailwind is done the same way we add custom JavaScript. The [doodle example](https://github.com/AnswerDotAI/fasthtml-example/tree/main/doodle) uses [Doodle.CSS](https://github.com/chr15m/DoodleCSS) to style the page in a quirky way. ## Deploying Your App We can deploy FastHTML almost anywhere you can deploy python apps. We’ve tested Railway, Replit, [HuggingFace](https://github.com/AnswerDotAI/fasthtml-hf), and [PythonAnywhere](https://github.com/AnswerDotAI/fasthtml-example/blob/main/deploying-to-pythonanywhere.md). ### Railway 1. [Install the Railway CLI](https://docs.railway.app/guides/cli) and sign up for an account. 2. Set up a folder with our app as `main.py` 3. In the folder, run `railway login`. 4. Use the `fh_railway_deploy` script to deploy our project: ``` bash fh_railway_deploy MY_APP_NAME ``` What the script does for us: 4. Do we have an existing railway project? - Yes: Link the project folder to our existing Railway project. - No: Create a new Railway project. 5. Deploy the project. We’ll see the logs as the service is built and run! 6. Fetches and displays the URL of our app. 7. By default, mounts a `/app/data` folder on the cloud to our app’s root folder. The app is run in `/app` by default, so from our app anything we store in `/data` will persist across restarts. A final note about Railway: We can add secrets like API keys that can be accessed as environment variables from our apps via [β€˜Variables’](https://docs.railway.app/guides/variables). For example, for the [image generation app](https://github.com/AnswerDotAI/fasthtml-example/tree/main/image_app_simple), we can add a `REPLICATE_API_KEY` variable, and then in `main.py` we can access it as `os.environ['REPLICATE_API_KEY']`. ### Replit Fork [this repl](https://replit.com/@johnowhitaker/FastHTML-Example) for a minimal example you can edit to your heart’s content. `.replit` has been edited to add the right run command (`run = ["uvicorn", "main:app", "--reload"]`) and to set up the ports correctly. FastHTML was installed with `poetry add python-fasthtml`, you can add additional packages as needed in the same way. Running the app in Replit will show you a webview, but you may need to open in a new tab for all features (such as cookies) to work. When you’re ready, you can deploy your app by clicking the β€˜Deploy’ button. You pay for usage - for an app that is mostly idle the cost is usually a few cents per month. You can store secrets like API keys via the β€˜Secrets’ tab in the Replit project settings. ### HuggingFace Follow the instructions in [this repository](https://github.com/AnswerDotAI/fasthtml-hf) to deploy to HuggingFace spaces. ## Where Next? We’ve covered a lot of ground here! Hopefully this has given you plenty to work with in building your own FastHTML apps. If you have any questions, feel free to ask in the \#fasthtml Discord channel (in the fastai Discord community). You can look through the other examples in the [fasthtml-example repository](https://github.com/AnswerDotAI/fasthtml-example) for more ideas, and keep an eye on Jeremy’s [YouTube channel](https://www.youtube.com/@howardjeremyp) where we’ll be releasing a number of β€œdev chats” related to FastHTML in the near future.
https://docs.fastht.ml/tutorials/by_example.html.md
tutorials_by_example.html.md
# Using Jupyter to write FastHTML <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> Writing FastHTML applications in Jupyter notebooks requires a slightly different process than normal Python applications. <div> > **Download this notebook and try it yourself** > > The source code for this page is a [Jupyter > notebook](https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/tutorials/jupyter_and_fasthtml.ipynb). > That makes it easy to directly experiment with it. However, as this is > working code that means we have to comment out a few things in order > for the documentation to build. </div> The first step is to import necessary libraries. As using FastHTML inside a Jupyter notebook is a special case, it remains a special import. ``` python from fasthtml.common import * from fasthtml.jupyter import JupyUvi, HTMX ``` Let’s create an app with `fast_app`. ``` python app, rt = fast_app(pico=True) ``` Define a route to test the application. ``` python @rt def index(): return Titled('Hello, Jupyter', P('Welcome to the FastHTML + Jupyter example'), Button('Click', hx_get='/click', hx_target='#dest'), Div(id='dest') ) ``` Create a `server` object using [`JupyUvi`](https://docs.fastht.ml/api/jupyter.html#jupyuvi), which also starts Uvicorn. The `server` runs in a separate thread from Jupyter, so it can use normal HTTP client functions in a notebook. ``` python server = JupyUvi(app) ``` <script> document.body.addEventListener('htmx:configRequest', (event) => { if(event.detail.path.includes('://')) return; htmx.config.selfRequestsOnly=false; event.detail.path = `${location.protocol}//${location.hostname}:8000${event.detail.path}`; }); </script> The [`HTMX`](https://docs.fastht.ml/api/jupyter.html#htmx) callable displays the server’s HTMX application in an iframe which can be displayed by Jupyter notebook. Pass in the same `port` variable used in the [`JupyUvi`](https://docs.fastht.ml/api/jupyter.html#jupyuvi) callable above or leave it blank to use the default (8000). ``` python # This doesn't display in the docs - uncomment and run it to see it in action # HTMX() ``` We didn’t define the `/click` route, but that’s fine - we can define (or change) it any time, and it’s dynamically inserted into the running app. No need to restart or reload anything! ``` python @rt def click(): return P('You clicked me!') ``` ## Full screen view You can view your app outside of Jupyter by going to `localhost:PORT`, where `PORT` is usually the default 8000, so in most cases just click [this link](localhost:8000/). ## Graceful shutdowns Use the `server.stop()` function displayed below. If you restart Jupyter without calling this line the thread may not be released and the [`HTMX`](https://docs.fastht.ml/api/jupyter.html#htmx) callable above may throw errors. If that happens, a quick temporary fix is to specify a different port number in JupyUvi and HTMX with the `port` parameter. Cleaner solutions to the dangling thread are to kill the dangling thread (dependant on each operating system) or restart the computer. ``` python server.stop() ```
https://docs.fastht.ml/tutorials/jupyter_and_fasthtml.html.md
tutorials_jupyter_and_fasthtml.html.md
# **FT** Components <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> **FT**, or β€˜FastTags’, are the display components of FastHTML. In fact, the word β€œcomponents” in the context of FastHTML is often synonymous with **FT**. For example, when we look at a FastHTML app, in particular the views, as well as various functions and other objects, we see something like the code snippet below. It’s the `return` statement that we want to pay attention to: ``` python from fasthtml.common import * def example(): # The code below is a set of ft components return Div( H1("FastHTML APP"), P("Let's do this"), cls="go" ) ``` Let’s go ahead and call our function and print the result: ``` python example() ``` ``` xml <div class="go"> <h1>FastHTML APP</h1> <p>Let&#x27;s do this</p> </div> ``` As you can see, when returned to the user from a Python callable, like a function, the ft components are transformed into their string representations of XML or XML-like content such as HTML. More concisely, *ft turns Python objects into HTML*. Now that we know what ft components look and behave like we can begin to understand them. At their most fundamental level, ft components: 1. Are Python callables, specifically functions, classes, methods of classes, lambda functions, and anything else called with parenthesis that returns a value. 2. Return a sequence of values which has three elements: 1. The tag to be generated 2. The content of the tag, which is a tuple of strings/tuples. If a tuple, it is the three-element structure of an ft component 3. A dictionary of XML attributes and their values 3. FastHTML’s default ft components words begin with an uppercase letter. Examples include `Title()`, `Ul()`, and `Div()` Custom components have included things like `BlogPost` and `CityMap`. ## How FastHTML names ft components When it comes to naming ft components, FastHTML appears to break from PEP8. Specifically, PEP8 specifies that when naming variables, functions and instantiated classes we use the `snake_case_pattern`. That is to say, lowercase with words separated by underscores. However, FastHTML uses `PascalCase` for ft components. There’s a couple of reasons for this: 1. ft components can be made from any callable type, so adhering to any one pattern doesn’t make much sense 2. It makes for easier reading of FastHTML code, as anything that is PascalCase is probably an ft component ## Default **FT** components FastHTML has over 150 **FT** components designed to accelerate web development. Most of these mirror HTML tags such as `<div>`, `<p>`, `<a>`, `<title>`, and more. However, there are some extra tags added, including: - [`Titled`](https://docs.fastht.ml/api/xtend.html#titled), a combination of the `Title()` and `H1()` tags - [`Socials`](https://docs.fastht.ml/api/xtend.html#socials), renders popular social media tags ## The `fasthtml.ft` Namespace Some people prefer to write code using namespaces while adhering to PEP8. If that’s a preference, projects can be coded using the `fasthtml.ft` namespace. ``` python from fasthtml import ft ft.Ul( ft.Li("one"), ft.Li("two"), ft.Li("three") ) ``` ``` xml <ul> <li>one</li> <li>two</li> <li>three</li> </ul> ``` ## Attributes This example demonstrates many important things to know about how ft components handle attributes. ``` python #| echo: False Label( "Choose an option", Select( Option("one", value="1", selected=True), Option("two", value="2", selected=False), Option("three", value=3), cls="selector", _id="counter", **{'@click':"alert('Clicked');"}, ), _for="counter", ) ``` Line 2 Line 2 demonstrates that FastHTML appreciates `Label`s surrounding their fields. Line 5 On line 5, we can see that attributes set to the `boolean` value of `True` are rendered with just the name of the attribute. Line 6 On line 6, we demonstrate that attributes set to the `boolean` value of `False` do not appear in the rendered output. Line 7 Line 7 is an example of how integers and other non-string values in the rendered output are converted to strings. Line 8 Line 8 is where we set the HTML class using the `cls` argument. We use `cls` here as `class` is a reserved word in Python. During the rendering process this will be converted to the word β€œclass”. Line 9 Line 9 demonstrates that any named argument passed into an ft component will have the leading underscore stripped away before rendering. Useful for handling reserved words in Python. Line 10 On line 10 we have an attribute name that cannot be represented as a python variable. In cases like these, we can use an unpacked `dict` to represent these values. Line 12 The use of `_for` on line 12 is another demonstration of an argument having the leading underscore stripped during render. We can also use `fr` as that will be expanded to `for`. This renders the following HTML snippet: ``` python Label( "Choose an option", Select( Option("one", value="1", selected=True), Option("two", value="2", selected=False), Option("three", value=3), # <4>, cls="selector", _id="counter", **{'@click':"alert('Clicked');"}, ), _for="counter", ) ``` ``` xml <label for="counter"> Choose an option <select id="counter" @click="alert(&#x27;Clicked&#x27;);" class="selector" name="counter"> <option value="1" selected>one</option> <option value="2" >two</option> <option value="3">three</option> </select> </label> ``` ## Defining new ft components It is possible and sometimes useful to create your own ft components that generate non-standard tags that are not in the FastHTML library. FastHTML supports created and defining those new tags flexibly. For more information, see the [Defining new ft components](../ref/defining_xt_component) reference page. ## FT components and type hints If you use type hints, we strongly suggest that FT components be treated as the `Any` type. The reason is that FastHTML leverages python’s dynamic features to a great degree. Especially when it comes to `FT` components, which can evaluate out to be `FT|str|None|tuple` as well as anything that supports the `__ft__`, `__html__`, and `__str__` method. That’s enough of the Python stack that assigning anything but `Any` to be the FT type will prove an exercise in frustation.
https://docs.fastht.ml/explains/explaining_xt_components.html.md
explains_explaining_xt_components.html.md
# FAQ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> ## Why does my editor say that I have errors in my FastHTML code? Many editors, including Visual Studio Code, use PyLance to provide error checking for Python. However, PyLance’s error checking is just a guess – it can’t actually know whether your code is correct or not. PyLance particularly struggles with FastHTML’s syntax, which leads to it often reporting false error messages in FastHTML projects. To avoid these misleading error messages, it’s best to disable some PyLance error checking in your FastHTML projects. Here’s how to do it in Visual Studio Code (the same approach should also work in other editors based on vscode, such as Cursor and GitHub Codespaces): 1. Open your FastHTML project 2. Press `Ctrl+Shift+P` (or `Cmd+Shift+P` on Mac) to open the Command Palette 3. Type β€œPreferences: Open Workspace Settings (JSON)” and select it 4. In the JSON file that opens, add the following lines: ``` json { "python.analysis.diagnosticSeverityOverrides": { "reportGeneralTypeIssues": "none", "reportOptionalMemberAccess": "none", "reportWildcardImportFromLibrary": "none", "reportRedeclaration": "none", "reportAttributeAccessIssue": "none", "reportInvalidTypeForm": "none", "reportAssignmentType": "none", } } ``` 5. Save the file Even with PyLance diagnostics turned off, your FastHTML code will still run correctly. If you’re still seeing some false errors from PyLance, you can disable it entirely by adding this to your settings: ``` json { "python.analysis.ignore": [ "*" ] } ``` ## Why the distinctive coding style? FastHTML coding style is the [fastai coding style](https://docs.fast.ai/dev/style.html). If you are coming from a data science background the **fastai coding style** may already be your preferred style. If you are coming from a PEP-8 background where the use of ruff is encouraged, there is a learning curve. However, once you get used to the **fastai coding style** you may discover yourself appreciating the concise nature of this style. It also encourages using more functional programming tooling, which is both productive and fun. Having said that, it’s entirely optional! ## Why not JSX? Many have asked! We think there’s no benefit… Python’s positional and kw args precisely 1:1 map already to html/xml children and attrs, so there’s no need for a new syntax. We wrote some more thoughts on Why Python HTML components over Jinja2, Mako, or JSX [here](https://www.answer.ai/posts/2024-08-03-fasthtml.html#why). ## Why use `import *` First, through the use of the [`__all__`](https://docs.python.org/3/tutorial/modules.html#importing-from-a-package) attribute in our Python modules we control what actually gets imported. So there’s no risk of namespace pollution. Second, our style lends itself to working in rather compact Jupyter notebooks and small Python modules. Hence we know about the source code whose libraries we `import *` from. This terseness means we can develop faster. We’re a small team, and any edge we can gain is important to us. Third, for external libraries, be it core Python, SQLAlchemy, or other things we do tend to use explicit imports. In part to avoid namespace collisions, and also as reference to know where things are coming from. We’ll finish by saying a lot of our users employ explicit imports. If that’s the path you want to take, we encourage the use of `from fasthtml import common as fh`. The acronym of `fh` makes it easy to recognize that a symbol is from the FastHTML library. ## Can FastHTML be used for dashboards? Yes it can. In fact, it excels at building dashboards. In addition to being great for building static dashboards, because of its [foundation](https://about.fastht.ml/foundation) in ASGI and [tech stack](https://about.fastht.ml/tech), FastHTML natively supports Websockets. That means using FastHTML we can create dashboards that autoupdate. ## Why is FastHTML developed using notebooks? Some people are under the impression that writing software in notebooks is bad. [Watch this video](https://www.youtube.com/watch?v=9Q6sLbz37gk&ab_channel=JeremyHoward). We’ve used Jupyter notebooks exported via `nbdev` to write a wide range of β€œvery serious” software projects over the last three years. This includes deep learning libraries, API clients, Python language extensions, terminal user interfaces, web frameworks, and more! [nbdev](https://nbdev.fast.ai/) is a Jupyter-powered tool for writing software. Traditional programming environments throw away the result of your exploration in REPLs or notebooks. `nbdev` makes exploration an integral part of your workflow, all while promoting software engineering best practices. ## Why not pyproject.toml for packaging? FastHTML uses a `setup.py` module instead of a `pyproject.toml` file to configure itself for installation. The reason for this is `pyproject.toml` is not compatible with [nbdev](https://nbdev.fast.ai/), which is what is used to write and build FastHTML. The nbdev project spent around a year trying to move to pyproject.toml but there was insufficient functionality in the toml-based approach to complete the transition.
https://docs.fastht.ml/explains/faq.html.md
explains_faq.html.md
# MiniDataAPI Spec <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> The `MiniDataAPI` is a persistence API specification that designed to be small and relatively easy to implement across a wide range of datastores. While early implementations have been SQL-based, the specification can be quickly implemented in key/value stores, document databases, and more. <div> > **Work in Progress** > > The MiniData API spec is a work in progress, subject to change. While > the majority of design is complete, expect there could be breaking > changes. </div> ## Why? The MiniDataAPI specification allows us to use the same API for many different database engines. Any application using the MiniDataAPI spec for interacting with its database requires no modification beyond import and configuration changes to switch database engines. For example, to convert an application from Fastlite running SQLite to FastSQL running PostgreSQL, should require only changing these two lines: <div class="columns"> <div class="column" width="19%" style="border-right: 1px solid #ccc; padding-right: 10px;"> FastLite version ``` python from fastlite import * db = database('test.db') ``` </div> <div class="column" width="79%" style="padding-left: 10px;"> FastSQL version ``` python from fastsql import * db = Database('postgres:...') ``` </div> </div> As both libraries adhere to the MiniDataAPI specification, the rest of the code in the application should remain the same. The advantage of the MiniDataAPI spec is that it allows people to use whatever datastores they have access to or prefer. <div> > **Note** > > Switching databases won’t migrate any existing data between databases. </div> ### Easy to learn, quick to implement The MiniDataAPI specification is designed to be easy-to-learn and quick to implement. It focuses on straightforward Create, Read, Update, and Delete (CRUD) operations. MiniDataAPI databases aren’t limited to just row-based systems. In fact, the specification is closer in design to a key/value store than a set of records. What’s exciting about this is we can write implementations for tools like Python dict stored as JSON, Redis, and even the venerable ZODB. ### Limitations of the MiniDataAPI Specification > β€œMini refers to the lightweightness of specification, not the data.” > > – Jeremy Howard The advantages of the MiniDataAPI come at a cost. The MiniDataAPI specification focuses a very small set of features compared to what can be found in full-fledged ORMs and query languages. It intentionally avoids nuances or sophisticated features. This means the specification does not include joins or formal foreign keys. Complex data stored over multiple tables that require joins isn’t handled well. For this kind of scenario it’s probably for the best to use more sophisticated ORMs or even direct database queries. ### Summary of the MiniDataAPI Design - Easy-to-learn - Relative quick to implement for new database engines - An API for CRUD operations - For many different types of databases including row- and key/value-based designs - Intentionally small in terms of features: no joins, no foreign keys, no database specific features - Best for simpler designs, complex architectures will need more sophisticated tools. ## Connect/construct the database We connect or construct the database by passing in a string connecting to the database endpoint or a filepath representing the database’s location. While this example is for SQLite running in memory, other databases such as PostgreSQL, Redis, MongoDB, might instead use a URI pointing at the database’s filepath or endpoint. The method of connecting to a DB is *not* part of this API, but part of the underlying library. For instance, for fastlite: ``` python db = database(':memory:') ``` Here’s a complete list of the available methods in the API, all documented below (assuming `db` is a database and `t` is a table): - `db.create` - `t.insert` - `t.delete` - `t.update` - `t[key]` - `t(...)` - `t.xtra` ## Tables For the sake of expediency, this document uses a SQL example. However, tables can represent anything, not just the fundamental construct of a SQL databases. They might represent keys within a key/value structure or files on a hard-drive. ### Creating tables We use a `create()` method attached to `Database` object (`db` in our example) to create the tables. ``` python class User: name:str; email: str; year_started:int users = db.create(User, pk='name') users ``` <Table user (name, email, year_started)> ``` python class User: name:str; email: str; year_started:int users = db.create(User, pk='name') users ``` <Table user (name, email, year_started)> If no `pk` is provided, `id` is assumed to be the primary key. Regardless of whether you mark a class as a dataclass or not, it will be turned into one – specifically into a [`flexiclass`](https://fastcore.fast.ai/xtras.html#flexiclass). ``` python @dataclass class Todo: id: int; title: str; detail: str; status: str; name: str todos = db.create(Todo) todos ``` <Table todo (id, title, detail, status, name)> ### Compound primary keys The MiniData API spec supports compound primary keys, where more than one column is used to identify records. We’ll also use this example to demonstrate creating a table using a dict of keyword arguments. ``` python class Publication: authors: str; year: int; title: str publications = db.create(Publication, pk=('authors', 'year')) ``` ### Transforming tables Depending on the database type, this method can include transforms - the ability to modify the tables. Let’s go ahead and add a password field for our table called `pwd`. ``` python class User: name:str; email: str; year_started:int; pwd:str users = db.create(User, pk='name', transform=True) users ``` <Table user (name, email, year_started, pwd)> ## Manipulating data The specification is designed to provide as straightforward CRUD API (Create, Read, Update, and Delete) as possible. Additional features like joins are out of scope. ### .insert() Add a new record to the database. We want to support as many types as possible, for now we have tests for Python classes, dataclasses, and dicts. Returns an instance of the new record. Here’s how to add a record using a Python class: ``` python users.insert(User(name='Braden', email='[email protected]', year_started=2018)) ``` User(name='Braden', email='[email protected]', year_started=2018, pwd=None) We can also use keyword arguments directly: ``` python users.insert(name='Alma', email='[email protected]', year_started=2019) ``` User(name='Alma', email='[email protected]', year_started=2019, pwd=None) And now Charlie gets added via a Python dict. ``` python users.insert({'name': 'Charlie', 'email': '[email protected]', 'year_started': 2018}) ``` User(name='Charlie', email='[email protected]', year_started=2018, pwd=None) And now TODOs. Note that the inserted row is returned: ``` python todos.insert(Todo(title='Write MiniDataAPI spec', status='open', name='Braden')) todos.insert(title='Implement SSE in FastHTML', status='open', name='Alma') todo = todos.insert(dict(title='Finish development of FastHTML', status='closed', name='Charlie')) todo ``` Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie') Let’s do the same with the `Publications` table. ``` python publications.insert(Publication(authors='Alma', year=2019, title='FastHTML')) publications.insert(authors='Alma', year=2030, title='FastHTML and beyond') publication= publications.insert((dict(authors='Alma', year=2035, title='FastHTML, the early years'))) publication ``` Publication(authors='Alma', year=2035, title='FastHTML, the early years') ### Square bracket search \[\] Get a single record by entering a primary key into a table object within square brackets. Let’s see if we can find Alma. ``` python user = users['Alma'] user ``` User(name='Alma', email='[email protected]', year_started=2019, pwd=None) If no record is found, a `NotFoundError` error is raised. Here we look for David, who hasn’t yet been added to our users table. ``` python try: users['David'] except NotFoundError: print(f'User not found') ``` User not found Here’s a demonstration of a ticket search, demonstrating how this works with non-string primary keys. ``` python todos[1] ``` Todo(id=1, title='Write MiniDataAPI spec', detail=None, status='open', name='Braden') Compound primary keys can be supplied in lists or tuples, in the order they were defined. In this case it is the `authors` and `year` columns. Here’s a query by compound primary key done with a `list`: ``` python publications[['Alma', 2019]] ``` Publication(authors='Alma', year=2019, title='FastHTML') Here’s the same query done directly with index args. ``` python publications['Alma', 2030] ``` Publication(authors='Alma', year=2030, title='FastHTML and beyond') ### Parentheses search () Get zero to many records by entering values with parentheses searches. If nothing is in the parentheses, then everything is returned. ``` python users() ``` [User(name='Braden', email='[email protected]', year_started=2018, pwd=None), User(name='Alma', email='[email protected]', year_started=2019, pwd=None), User(name='Charlie', email='[email protected]', year_started=2018, pwd=None)] We can order the results. ``` python users(order_by='name') ``` [User(name='Alma', email='[email protected]', year_started=2019, pwd=None), User(name='Braden', email='[email protected]', year_started=2018, pwd=None), User(name='Charlie', email='[email protected]', year_started=2018, pwd=None)] We can filter on the results: ``` python users(where="name='Alma'") ``` [User(name='Alma', email='[email protected]', year_started=2019, pwd=None)] Generally you probably want to use placeholders, to avoid SQL injection attacks: ``` python users("name=?", ('Alma',)) ``` [User(name='Alma', email='[email protected]', year_started=2019, pwd=None)] We can limit results with the `limit` keyword: ``` python users(limit=1) ``` [User(name='Braden', email='[email protected]', year_started=2018, pwd=None)] If we’re using the `limit` keyword, we can also use the `offset` keyword to start the query later. ``` python users(limit=5, offset=1) ``` [User(name='Alma', email='[email protected]', year_started=2019, pwd=None), User(name='Charlie', email='[email protected]', year_started=2018, pwd=None)] ### .update() Update an existing record of the database. Must accept Python dict, dataclasses, and standard classes. Uses the primary key for identifying the record to be changed. Returns an instance of the updated record. Here’s with a normal Python class: ``` python user ``` User(name='Alma', email='[email protected]', year_started=2019, pwd=None) ``` python user.year_started = 2099 users.update(user) ``` User(name='Alma', email='[email protected]', year_started=2099, pwd=None) Or use a dict: ``` python users.update(dict(name='Alma', year_started=2199, email='[email protected]')) ``` User(name='Alma', email='[email protected]', year_started=2199, pwd=None) Or use kwargs: ``` python users.update(name='Alma', year_started=2149) ``` User(name='Alma', email='[email protected]', year_started=2149, pwd=None) If the primary key doesn’t match a record, raise a `NotFoundError`. John hasn’t started with us yet so doesn’t get the chance yet to travel in time. ``` python try: users.update(User(name='John', year_started=2024, email='[email protected]')) except NotFoundError: print('User not found') ``` User not found ### .delete() Delete a record of the database. Uses the primary key for identifying the record to be removed. Returns a table object. Charlie decides to not travel in time. He exits our little group. ``` python users.delete('Charlie') ``` <Table user (name, email, year_started, pwd)> If the primary key value can’t be found, raises a `NotFoundError`. ``` python try: users.delete('Charlies') except NotFoundError: print('User not found') ``` User not found In John’s case, he isn’t time travelling with us yet so can’t be removed. ``` python try: users.delete('John') except NotFoundError: print('User not found') ``` User not found Deleting records with compound primary keys requires providing the entire key. ``` python publications.delete(['Alma' , 2035]) ``` <Table publication (authors, year, title)> ### `in` keyword Are `Alma` and `John` contained `in` the Users table? Or, to be technically precise, is the item with the specified primary key value `in` this table? ``` python 'Alma' in users, 'John' in users ``` (True, False) Also works with compound primary keys, as shown below. You’ll note that the operation can be done with either a `list` or `tuple`. ``` python ['Alma', 2019] in publications ``` True And now for a `False` result, where John has no publications. ``` python ('John', 1967) in publications ``` False ### .xtra() If we set fields within the `.xtra` function to a particular value, then indexing is also filtered by those. This applies to every database method except for record creation. This makes it easier to limit users (or other objects) access to only things for which they have permission. This is a one-way operation, once set it can’t be undone for a particular table object. For example, if we query all our records below without setting values via the `.xtra` function, we can see todos for everyone. Pay special attention to the `id` values of all three records, as we are about to filter most of them away. ``` python todos() ``` [Todo(id=1, title='Write MiniDataAPI spec', detail=None, status='open', name='Braden'), Todo(id=2, title='Implement SSE in FastHTML', detail=None, status='open', name='Alma'), Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie')] Let’s use `.xtra` to constrain results just to Charlie. We set the `name` field in Todos, but it could be any field defined for this table. ``` python todos.xtra(name='Charlie') ``` We’ve now set a field to a value with `.xtra`, if we loop over all the records again, only those assigned to records with a `name` of `Charlie` will be displayed. ``` python todos() ``` [Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie')] The `in` keyword is also affected. Only records with a `name` of Charlie will evaluate to be `True`. Let’s demonstrate by testing it with a Charlie record: ``` python ct = todos[3] ct ``` Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie') Charlie’s record has an ID of 3. Here we demonstrate that Charlie’s TODO can be found in the list of todos: ``` python ct.id in todos ``` True If we try `in` with the other IDs the query fails because the filtering is now set to just records with a name of Charlie. ``` python 1 in todos, 2 in todos ``` (False, False) ``` python try: todos[2] except NotFoundError: print('Record not found') ``` Record not found We are also constrained by what records we can update. In the following example we try to update a TODO not named β€˜Charlie’. Because the name is wrong, the `.update` function will raise a `NotFoundError`. ``` python try: todos.update(Todo(id=1, title='Finish MiniDataAPI Spec', status='closed', name='Braden')) except NotFoundError as e: print('Record not updated') ``` Record not updated Unlike poor Braden, Charlie isn’t filtered out. Let’s update his TODO. ``` python todos.update(Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie')) ``` Todo(id=3, title='Finish development of FastHTML', detail=None, status='closed', name='Charlie') Finally, once constrained by `.xtra`, only records with Charlie as the name can be deleted. ``` python try: todos.delete(1) except NotFoundError as e: print('Record not updated') ``` Record not updated Charlie’s TODO was to finish development of FastHTML. While the framework will stabilize, like any good project it will see new features added and the odd bug corrected for many years to come. Therefore, Charlie’s TODO is nonsensical. Let’s delete it. ``` python todos.delete(ct.id) ``` <Table todo (id, title, detail, status, name)> When a TODO is inserted, the `xtra` fields are automatically set. This ensures that we don’t accidentally, for instance, insert items for others users. Note that here we don’t set the `name` field, but it’s still included in the resultant row: ``` python ct = todos.insert(Todo(title='Rewrite personal site in FastHTML', status='open')) ct ``` Todo(id=3, title='Rewrite personal site in FastHTML', detail=None, status='open', name='Charlie') If we try to change the username to someone else, the change is ignored, due to `xtra`: ``` python ct.name = 'Braden' todos.update(ct) ``` Todo(id=3, title='Rewrite personal site in FastHTML', detail=None, status='open', name='Charlie') ## SQL-first design ``` python users = None User = None ``` ``` python users = db.t.user users ``` <Table user (name, email, year_started, pwd)> (This section needs to be documented properly.) From the table objects we can extract a Dataclass version of our tables. Usually this is given an singular uppercase version of our table name, which in this case is `User`. ``` python User = users.dataclass() ``` ``` python User(name='Braden', email='[email protected]', year_started=2018) ``` User(name='Braden', email='[email protected]', year_started=2018, pwd=UNSET) ## Implementations ### Implementing MiniDataAPI for a new datastore For creating new implementations, the code examples in this specification are the test case for the API. New implementations should pass the tests in order to be compliant with the specification. ### Implementations - [fastlite](https://github.com/AnswerDotAI/fastlite) - The original implementation, only for Sqlite - [fastsql](https://github.com/AnswerDotAI/fastsql) - An SQL database agnostic implementation based on the excellent SQLAlchemy library.
https://docs.fastht.ml/explains/minidataapi.html.md
explains_minidataapi.html.md
# OAuth <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> OAuth is an open standard for β€˜access delegation’, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It is the mechanism that enables β€œLog in with Google” on many sites, saving you from having to remember and manage yet another password. Like many auth-related topics, there’s a lot of depth and complexity to the OAuth standard, but once you understand the basic usage it can be a very convenient alternative to managing your own user accounts. On this page you’ll see how to use OAuth with FastHTML to implement some common pieces of functionality. ## Creating an Client FastHTML has Client classes for managing settings and state for different OAuth providers. Currently implemented are: GoogleAppClient, GitHubAppClient, HuggingFaceClient and DiscordAppClient - see the [source](https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/api/08_oauth.ipynb) if you need to add other providers. You’ll need a `client_id` and `client_secret` from the provider (see the from-scratch example later in this page for an example of registering with GitHub) to create the client. We recommend storing these in environment variables, rather than hardcoding them in your code. ``` python import os from fasthtml.oauth import GoogleAppClient client = GoogleAppClient(os.getenv("AUTH_CLIENT_ID"), os.getenv("AUTH_CLIENT_SECRET")) ``` The client is used to obtain a login link and to manage communications between your app and the OAuth provider (`client.login_link(redirect_uri="/redirect")`). ## Using the OAuth class Once you’ve set up a client, adding OAuth to a FastHTML app can be as simple as: ``` python from fasthtml.oauth import OAuth from fasthtml.common import FastHTML, RedirectResponse class Auth(OAuth): def get_auth(self, info, ident, session, state): email = info.email or '' if info.email_verified and email.split('@')[-1]=='answer.ai': return RedirectResponse('/', status_code=303) app = FastHTML() oauth = Auth(app, client) @app.get('/') def home(auth): return P('Logged in!'), A('Log out', href='/logout') @app.get('/login') def login(req): return Div(P("Not logged in"), A('Log in', href=oauth.login_link(req))) ``` There’s a fair bit going on here, so let’s unpack what’s happening in that code: - OAuth (and by extension our custom Auth class) has a number of default arguments, including some key URLs: `redir_path='/redirect', error_path='/error', logout_path='/logout', login_path='/login'`. It will create and handle the redirect and logout paths, and it’s up to you to handle `/login` (where unsuccessful login attempts will be redirected) and `/error` (for oauth errors). - When we run `oauth = Auth(app, client)` it adds the redirect and logout paths to the app and also adds some beforeware. This beforeware runs on any requests (apart from any specified with the `skip` parameter). The added beforeware specifies some app behaviour: - If someone who isn’t logged in attempts to visit our homepage (`/`) here, they will be redirected to `/login`. - If they are logged in, it calls a `check_invalid` method. This defaults to False, which let’s the user continue to the page they requested. The behaviour can be modified by defining your own `check_invalid` method in the Auth class - for example, you could have this forcibly log out users who have recently been banned. So how does someone log in? If they visit (or are redirected to) the login page at `/login`, we show them a login link. This sends them to the OAuth provider, where they’ll go through the steps of selecting their account, giving permissions etc. Once done they will be redirected back to `/redirect`. Behind the scenes a code that comes as part of their request gets turned into user info, which is then passed to the key function `get_auth(self, info, ident, session, state)`. Here is where you’d handle looking up or adding a user in a database, checking for some condition (for example, this code checks if the email is an answer.ai email address) or choosing the destination based on state. The arguments are: - `self`: the Auth object, which you can use to access the client (`self.cli`) - `info`: the information provided by the OAuth provider, typically including a unique user id, email address, username and other metadata. - `ident`: a unique identifier for this user. What this looks like varies between providers. This is useful for managing a database of users, for example. - `session`: the current session, that you can store information in securely - `state`: you can optionally pass in some state when creating the login link. This persists and is returned after the user goes through the Oath steps, which is useful for returning them to the same page they left. It can also be used as added security against CSRF attacks. In our example, we check the email in `info` (we use a GoogleAppClient, not all providers will include an email). If we aren’t happy, and get_auth returns False or nothing (as in the case here for non-answerai people) then the user is redirected back to the login page. But if everything looks good we return a redirect to the homepage, and an `auth` key is added to the session and the scope containing the users identity `ident`. So, for example, in the homepage route we could use `auth` to look up this particular user’s profile info and customize the page accordingly. This auth will persist in their session until they clear the browser cache, so by default they’ll stay logged in. To log them out, remove it ( `session.pop('auth', None)`) or send them to `/logout` which will do that for you. ## Explaining OAuth with a from-scratch implementation Hopefully the example above is enough to get you started. You can also check out the (fairly minimal) [source code](https://github.com/AnswerDotAI/fasthtml/blob/main/nbs/api/08_oauth.ipynb) where this is implemented, and the [examples here](https://github.com/AnswerDotAI/fasthtml-example/blob/main/oauth_example). If you’re wanting to learn more about how this works, and to see where you might add additional functionality, the rest of this page will walk through some examples **without** the OAuth convenience class, to illustrate the concepts. This was writted before said OAuth class was available, and is kep here for educational purposes - we recommend you stick with the new approach shown above in most cases. ## A Minimal Login Flow (GitHub) Let’s begin by building a minimal β€˜Sign in with GitHub’ flow. This will demonstrate the basic steps of OAuth. OAuth requires a β€œprovider” (in this case, GitHub) to authenticate the user. So the first step when setting up our app is to register with GitHub to set things up. Go to https://github.com/settings/developers and click β€œNew OAuth App”. Fill in the form with the following values, then click β€˜Register application’. - Application name: Your app name - Homepage URL: http://localhost:8000 (or whatever URL you’re using - you can change this later) - Authorization callback URL: http://localhost:8000/auth_redirect (you can modify this later too) <div style="text-align:center;margin:50px 0 45px;"> <img src="imgs/gh-oauth.png" alt="Setting up an OAuth app in GitHub" width="500" /> </div> After you register, you’ll see a screen where you can view the client ID and generate a client secret. Store these values in a safe place. You’ll use them to create a [`GitHubAppClient`](https://docs.fastht.ml/api/oauth.html#githubappclient) object in FastHTML. This `client` object is responsible for handling the parts of the OAuth flow which depend on direct communication between your app and GitHub, as opposed to interactions which go through the user’s browser via redirects. Here is how to setup the client object: ``` python client = GitHubAppClient( client_id="your_client_id", client_secret="your_client_secret" ) ``` You should also save the path component of the authorization callback URL which you provided on registration. This route is where GitHub will redirect the user’s browser in order to send an authorization code to your app. You should save only the URL’s path component rather than the entire URL because you want your code to work automatically in deployment, when the host and port part of the URL change from `localhost:8000` to your real DNS name. Save the special authorization callback path under an obvious name: ``` python auth_callback_path = "/auth_redirect" ``` <div> > **Note** > > It’s recommended to store the client ID, and secret, in environment > variables, rather than hardcoding them in your code. </div> When the user visit a normal page of your app, if they are not already logged in, then you’ll want to redirect them to your app’s login page, which will live at the `/login` path. We accomplish that by using this piece of β€œbeforeware”, which defines logic which runs before other work for all routes except ones we specify to be skipped: ``` python def before(req, session): auth = req.scope['auth'] = session.get('user_id', None) if not auth: return RedirectResponse('/login', status_code=303) counts.xtra(name=auth) bware = Beforeware(before, skip=['/login', auth_callback_path]) ``` We configure the beforeware to skip `/login` because that’s where the user goes to login, and we also skip the special authorization callback path because that is used by OAuth itself to receive information from GitHub. It’s only at your login page that we start the OAuth flow. To start the OAuth flow, you need to give the user a link to GitHub’s login for your app. You’ll need the `client` object to generate that link, and the client object will in turn need the full authorization callback URL, which we need to build from the authorization callback path, so it is a multi-step process to produce this GitHub login link. Here is an implementation of your own `/login` route handler. It generates the GitHub login link and presents it to the user: ``` python @app.get('/login') def login(request) redir = redir_url(request,auth_callback_path) login_link = client.login_link(redir) return P(A('Login with GitHub', href=login_link)) ``` Once the user follows that link, GitHub will ask them to grant permission to your app to access their GitHub account. If they agree, GitHub will redirect them back to your app’s authorization callback URL, carrying an authorization code which your app can use to generate an access token. To receive this code, you need to set up a route in FastHTML that listens for requests at the authorization callback path. For example: ``` python @app.get(auth_callback_path) def auth_redirect(code:str): return P(f"code: {code}") ``` This authorization code is temporary, and is used by your app to directly ask the provider for user information like an access token. To recap, you can think of the exchange so far as: - User to us: β€œI want to log in with you, app.” - Us to User: β€œOkay but first, here’s a special link to log in with GitHub” - User to GitHub: β€œI want to log in with you, GitHub, to use this app.” - GitHub to User: β€œOK, redirecting you back to the app’s URL (with an auth code)” - User to Us: β€œHi again, app. Here’s the GitHub auth code you need to ask GitHub for info about me” (delivered via `/auth_redirect?code=...`) The final steps we need to implement are as follows: - Us to GitHUb: β€œA user just gave me this auth code. May I have the user info (e.g., an access token)?” - GitHub to us: β€œSince you have an auth code, here’s the user info” It’s critical for us to derive the user info from the auth code immediately in the authorization callback, because the auth code may be used only once. So we use it that once in order to get information like an access token, which will remain valid for longer. To go from the auth code to user info, you use `info = client.retr_info(code,redirect_uri)`. From the user info, you can extract the `user_id`, which is a unique identifier for the user: ``` python @app.get(auth_callback_path) def auth_redirect(code:str, request): redir = redir_url(request, auth_callback_path) user_info = client.retr_info(code, redir) user_id = info[client.id_key] return P(f"User id: {user_id}") ``` But we want the user ID not to print it but to remember the user. So let us store it in the `session` object, to remember who is logged in: ``` python @app.get(auth_callback_path) def auth_redirect(code:str, request, session): redir = redir_url(request, auth_callback_path) user_info = client.retr_info(code, redir) user_id = user_info[client.id_key] # get their ID session['user_id'] = user_id # save ID in the session return RedirectResponse('/', status_code=303) ``` The session object is derived from values visible to the user’s browser, but it is cryptographically signed so the user can’t read it themselves. This makes it safe to store even information we don’t want to expose to the user. For larger quantities of data, we’d want to save that information in a database and use the session to hold keys to lookup information from that database. Here’s a minimal app that puts all these pieces together. It uses the user info to get the user_id. It stores that in the session object. It then uses the user_id as a key into a database, which tracks how frequently every user has hit an increment button. ``` python import os from fasthtml.common import * from fasthtml.oauth import GitHubAppClient, redir_url db = database('data/counts.db') counts = db.t.counts if counts not in db.t: counts.create(dict(name=str, count=int), pk='name') Count = counts.dataclass() # Auth client setup for GitHub client = GitHubAppClient(os.getenv("AUTH_CLIENT_ID"), os.getenv("AUTH_CLIENT_SECRET")) auth_callback_path = "/auth_redirect" def before(req, session): # if not logged in, we send them to our login page # logged in means: # - 'user_id' in the session object, # - 'auth' in the request object auth = req.scope['auth'] = session.get('user_id', None) if not auth: return RedirectResponse('/login', status_code=303) counts.xtra(name=auth) bware = Beforeware(before, skip=['/login', auth_callback_path]) app = FastHTML(before=bware) # User asks us to Login @app.get('/login') def login(request): redir = redir_url(request,auth_callback_path) login_link = client.login_link(redir) # we tell user to login at github return P(A('Login with GitHub', href=login_link)) # User comes back to us with an auth code from Github @app.get(auth_callback_path) def auth_redirect(code:str, request, session): redir = redir_url(request, auth_callback_path) user_info = client.retr_info(code, redir) user_id = user_info[client.id_key] # get their ID session['user_id'] = user_id # save ID in the session # create a db entry for the user if user_id not in counts: counts.insert(name=user_id, count=0) return RedirectResponse('/', status_code=303) @app.get('/') def home(auth): return Div( P("Count demo"), P(f"Count: ", Span(counts[auth].count, id='count')), Button('Increment', hx_get='/increment', hx_target='#count'), P(A('Logout', href='/logout')) ) @app.get('/increment') def increment(auth): c = counts[auth] c.count += 1 return counts.upsert(c).count @app.get('/logout') def logout(session): session.pop('user_id', None) return RedirectResponse('/login', status_code=303) serve() ``` Some things to note: - The `before` function is used to check if the user is authenticated. If not, they are redirected to the login page. - To log the user out, we remove the user ID from the session. - Calling `counts.xtra(name=auth)` ensures that only the row corresponding to the current user is accessible when responding to a request. This is often nicer than trying to remember to filter the data in every route, and lowers the risk of accidentally leaking data. - In the `auth_redirect` route, we store the user ID in the session and create a new row in the `user_counts` table if it doesn’t already exist. You can find more heavily-commented version of this code in the [oauth directory in fasthtml-example](https://github.com/AnswerDotAI/fasthtml-example/tree/main/oauth_example), along with an even more minimal example. More examples may be added in the future. ### Revoking Tokens (Google) When the user in the example above logs out, we remove their user ID from the session. However, the user is still logged in to GitHub. If they click β€˜Login with GitHub’ again, they’ll be redirected back to our site without having to log in again. This is because GitHub remembers that they’ve already granted our app permission to access their account. Most of the time this is convenient, but for testing or security purposes you may want a way to revoke this permission. As a user, you can usually revoke access to an app from the provider’s website (for example, <https://github.com/settings/applications>). But as a developer, you can also revoke access programmatically - at least with some providers. This requires keeping track of the access token (stored in `client.token["access_token"]` after you call `retr_info`), and sending a request to the provider’s revoke URL: ``` python auth_revoke_url = "https://accounts.google.com/o/oauth2/revoke" def revoke_token(token): response = requests.post(auth_revoke_url, params={"token": token}) return response.status_code == 200 # True if successful ``` Not all providers support token revocation, and it is not built into FastHTML clients at the moment. ### Using State (Hugging Face) Imagine a user (not logged in) comes to your AI image editing site, starts testing things out, and then realizes they need to sign in before they can click β€œRun (Pro)” on the edit they’re working on. They click β€œSign in with Hugging Face”, log in, and are redirected back to your site. But now they’ve lost their in-progress edit and are left just looking at the homepage! This is an example of a case where you might want to keep track of some additional state. Another strong use case for being able to pass some uniqie state through the OAuth flow is to prevent something called a [CSRF attack](https://en.wikipedia.org/wiki/Cross-site_request_forgery). To add a state string to the OAuth flow, you can use `client.login_link_with_state(state)` instead of `client.login_link()`, like so: ``` python # in login page: link = A('Login with GitHub', href=client.login_link_with_state(state='current_prompt: add a unicorn')) # in auth_redirect: @app.get('/auth_redirect') def auth_redirect(code:str, session, state:str=None): print(f"state: {state}") # Use as needed ... ``` The state string is passed through the OAuth flow and back to your site. ### A Work in Progress This page (and OAuth support in FastHTML) is a work in progress. Questions, PRs, and feedback are welcome!
https://docs.fastht.ml/explains/oauth.html.md
explains_oauth.html.md
# Routes <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> Behaviour in FastHTML apps is defined by routes. The syntax is largely the same as the wonderful [FastAPI](https://fastapi.tiangolo.com/) (which is what you should be using instead of this if you’re creating a JSON service. FastHTML is mainly for making HTML web apps, not APIs). <div> > **Unfinished** > > We haven’t yet written complete documentation of all of FastHTML’s > routing features – until we add that, the best place to see all the > available functionality is to look over [the > tests](../api/core.html#tests) </div> Note that you need to include the types of your parameters, so that [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) knows what to pass to your function. Here, we’re just expecting a string: ``` python from fasthtml.common import * ``` ``` python app = FastHTML() @app.get('/user/{nm}') def get_nm(nm:str): return f"Good day to you, {nm}!" ``` Normally you’d save this into a file such as main.py, and then run it in `uvicorn` using: uvicorn main:app However, for testing, we can use Starlette’s `TestClient` to try it out: ``` python from starlette.testclient import TestClient ``` ``` python client = TestClient(app) r = client.get('/user/Jeremy') r ``` <Response [200 OK]> TestClient uses `httpx` behind the scenes, so it returns a `httpx.Response`, which has a `text` attribute with our response body: ``` python r.text ``` 'Good day to you, Jeremy!' In the previous example, the function name (`get_nm`) didn’t actually matter – we could have just called it `_`, for instance, since we never actually call it directly. It’s just called through HTTP. In fact, we often do call our functions `_` when using this style of route, since that’s one less thing we have to worry about, naming. An alternative approach to creating a route is to use `app.route` instead, in which case, you make the function name the HTTP method you want. Since this is such a common pattern, you might like to give a shorter name to `app.route` – we normally use `rt`: ``` python rt = app.route @rt('/') def post(): return "Going postal!" client.post('/').text ``` 'Going postal!' ### Route-specific functionality FastHTML supports custom decorators for adding specific functionality to routes. This allows you to implement authentication, authorization, middleware, or other custom behaviors for individual routes. Here’s an example of a basic authentication decorator: ``` python from functools import wraps def basic_auth(f): @wraps(f) async def wrapper(req, *args, **kwargs): token = req.headers.get("Authorization") if token == 'abc123': return await f(req, *args, **kwargs) return Response('Not Authorized', status_code=401) return wrapper @app.get("/protected") @basic_auth async def protected(req): return "Protected Content" client.get('/protected', headers={'Authorization': 'abc123'}).text ``` 'Protected Content' The decorator intercepts the request before the route function executes. If the decorator allows the request to proceed, it calls the original route function, passing along the request and any other arguments. One of the key advantages of this approach is the ability to apply different behaviors to different routes. You can also stack multiple decorators on a single route for combined functionality. ``` python def app_beforeware(): print('App level beforeware') app = FastHTML(before=Beforeware(app_beforeware)) client = TestClient(app) def route_beforeware(f): @wraps(f) async def decorator(*args, **kwargs): print('Route level beforeware') return await f(*args, **kwargs) return decorator def second_route_beforeware(f): @wraps(f) async def decorator(*args, **kwargs): print('Second route level beforeware') return await f(*args, **kwargs) return decorator @app.get("/users") @route_beforeware @second_route_beforeware async def users(): return "Users Page" client.get('/users').text ``` App level beforeware Route level beforeware Second route level beforeware 'Users Page' This flexiblity allows for granular control over route behaviour, enabling you to tailor each endpoint’s functionality as needed. While app-level beforeware remains useful for global operations, decorators provide a powerful tool for route-specific customization. ## Combining Routes Sometimes a FastHTML project can grow so weildy that putting all the routes into `main.py` becomes unweildy. Or, we install a FastHTML- or Starlette-based package that requires us to add routes. First let’s create a `books.py` module, that represents all the user-related views: ``` python # books.py books_app, rt = fast_app() books = ['A Guide to FastHTML', 'FastHTML Cookbook', 'FastHTML in 24 Hours'] @rt("/", name="list") def get(): return Titled("Books", *[P(book) for book in books]) ``` Let’s mount it in our main module: ``` python from books import books_app app, rt = fast_app(routes=[Mount("/books", books_app, name="books")]) @rt("/") def get(): return Titled("Dashboard", P(A(href="/books")("Books")), Hr(), P(A(link=uri("books:list"))("Books")), ) serve() ``` Line 3 We use `starlette.Mount` to add the route to our routes list. We provide the name of `books` to make discovery and management of the links easier. More on that in items 2 and 3 of this annotations list Line 8 This example link to the books list view is hand-crafted. Obvious in purpose, it makes changing link patterns in the future harder Line 10 This example link uses the named URL route for the books. The advantage of this approach is it makes management of large numbers of link items easier.
https://docs.fastht.ml/explains/routes.html.md
explains_routes.html.md
# WebSockets <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> Websockets are a protocol for two-way, persistent communication between a client and server. This is different from HTTP, which uses a request/response model where the client sends a request and the server responds. With websockets, either party can send messages at any time, and the other party can respond. This allows for different applications to be built, including things like chat apps, live-updating dashboards, and real-time collaborative tools, which would require constant polling of the server for updates with HTTP. In FastHTML, you can create a websocket route using the `@app.ws` decorator. This decorator takes a route path, and optional `conn` and `disconn` parameters representing the `on_connect` and `on_disconnect` callbacks in websockets, respectively. The function decorated by `@app.ws` is the main function that is called when a message is received. Here’s an example of a basic websocket route: ``` python @app.ws('/ws', conn=on_conn, disconn=on_disconn) async def on_message(msg:str, send): await send(Div('Hello ' + msg, id='notifications')) await send(Div('Goodbye ' + msg, id='notifications')) ``` The `on_message` function is the main function that is called when a message is received and can be named however you like. Similar to standard routes, the arguments to `on_message` are automatically parsed from the websocket payload for you, so you don’t need to manually parse the message content. However, certain argument names are reserved for special purposes. Here are the most important ones: - `send` is a function that can be used to send text data to the client. - `data` is a dictionary containing the data sent by the client. - `ws` is a reference to the websocket object. For example, we can send a message to the client that just connected like this: ``` python async def on_conn(send): await send(Div('Hello, world!')) ``` Or if we receive a message from the client, we can send a message back to them: ``` python @app.ws('/ws', conn=on_conn, disconn=on_disconn) async def on_message(msg:str, send): await send(Div('You said: ' + msg, id='notifications')) # or... return Div('You said: ' + msg, id='notifications') ``` On the client side, we can use HTMX’s websocket extension to open a websocket connection and send/receive messages. For example: ``` python from fasthtml.common import * app = FastHTML(exts='ws') @app.get('/') def home(): cts = Div( Div(id='notifications'), Form(Input(id='msg'), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) ``` This will create a websocket connection to the server on route `/ws`, and send any form submissions to the server via the websocket. The server will then respond by sending a message back to the client. The client will then update the message div with the message from the server using Out of Band Swaps, which means that the content is swapped with the same id without reloading the page. <div> > **Note** > > Make sure you set `exts='ws'` when creating your > [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) object if > you want to use websockets so the extension is loaded. </div> Putting it all together, the code for the client and server should look like this: ``` python from fasthtml.common import * app = FastHTML(exts='ws') rt = app.route @rt('/') def get(): cts = Div( Div(id='notifications'), Form(Input(id='msg'), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) @app.ws('/ws') async def ws(msg:str, send): await send(Div('Hello ' + msg, id='notifications')) serve() ``` This is a fairly simple example and could be done just as easily with standard HTTP requests, but it illustrates the basic idea of how websockets work. Let’s look at a more complex example next. ## Session data in Websockets Session data is shared between standard HTTP routes and Websockets. This means you can access, for example, logged in user ID inside websocket handler: ``` python from fasthtml.common import * app = FastHTML(exts='ws') rt = app.route @rt('/login') def get(session): session["person"] = "Bob" return "ok" @app.ws('/ws') async def ws(msg:str, send, session): await send(Div(f'Hello {session.get("person")}' + msg, id='notifications')) serve() ``` ## Real-Time Chat App Let’s put our new websocket knowledge to use by building a simple chat app. We will create a chat app where multiple users can send and receive messages in real time. Let’s start by defining the app and the home page: ``` python from fasthtml.common import * app = FastHTML(exts='ws') rt = app.route msgs = [] @rt('/') def home(): return Div( Div(Ul(*[Li(m) for m in msgs], id='msg-list')), Form(Input(id='msg'), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') ``` Now, let’s handle the websocket connection. We’ll add a new route for this along with an `on_conn` and `on_disconn` function to keep track of the users currently connected to the websocket. Finally, we will handle the logic for sending messages to all connected users. ``` python users = {} def on_conn(ws, send): users[str(id(ws))] = send def on_disconn(ws): users.pop(str(id(ws)), None) @app.ws('/ws', conn=on_conn, disconn=on_disconn) async def ws(msg:str): msgs.append(msg) # Use associated `send` function to send message to each user for u in users.values(): await u(Ul(*[Li(m) for m in msgs], id='msg-list')) serve() ``` We can now run this app with `python chat_ws.py` and open multiple browser tabs to `http://localhost:5001`. You should be able to send messages in one tab and see them appear in the other tabs. ### A Work in Progress This page (and Websocket support in FastHTML) is a work in progress. Questions, PRs, and feedback are welcome!
https://docs.fastht.ml/explains/websockets.html.md
explains_websockets.html.md
Error: 404 Client Error: Not Found for url: https://docs.fastht.ml/ref/defining_xt_component.html.md
https://docs.fastht.ml/ref/defining_xt_component.html.md
ref_defining_xt_component.html.md
# Handling handlers <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> ``` python from fasthtml.common import * from collections import namedtuple from typing import TypedDict from datetime import datetime import json,time ``` ``` python app = FastHTML() ``` The [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) class is the main application class for FastHTML apps. ``` python rt = app.route ``` `app.route` is used to register route handlers. It is a decorator, which means we place it before a function that is used as a handler. Because it’s used frequently in most FastHTML applications, we often alias it as `rt`, as we do here. ## Basic Route Handling ``` python @rt("/hi") def get(): return 'Hi there' ``` Handler functions can return strings directly. These strings are sent as the response body to the client. ``` python cli = Client(app) ``` [`Client`](https://docs.fastht.ml/api/core.html#client) is a test client for FastHTML applications. It allows you to simulate requests to your app without running a server. ``` python cli.get('/hi').text ``` 'Hi there' The `get` method on a [`Client`](https://docs.fastht.ml/api/core.html#client) instance simulates GET requests to the app. It returns a response object that has a `.text` attribute, which you can use to access the body of the response. It calls `httpx.get` internally – all httpx HTTP verbs are supported. ``` python @rt("/hi") def post(): return 'Postal' cli.post('/hi').text ``` 'Postal' Handler functions can be defined for different HTTP methods on the same route. Here, we define a `post` handler for the `/hi` route. The [`Client`](https://docs.fastht.ml/api/core.html#client) instance can simulate different HTTP methods, including POST requests. ## Request and Response Objects ``` python @app.get("/hostie") def show_host(req): return req.headers['host'] cli.get('/hostie').text ``` 'testserver' Handler functions can accept a `req` (or `request`) parameter, which represents the incoming request. This object contains information about the request, including headers. In this example, we return the `host` header from the request. The test client uses β€˜testserver’ as the default host. In this example, we use `@app.get("/hostie")` instead of `@rt("/hostie")`. The `@app.get()` decorator explicitly specifies the HTTP method (GET) for the route, while `@rt()` by default handles both GET and POST requests. ``` python @rt def yoyo(): return 'a yoyo' cli.post('/yoyo').text ``` 'a yoyo' If the `@rt` decorator is used without arguments, it uses the function name as the route path. Here, the `yoyo` function becomes the handler for the `/yoyo` route. This handler responds to GET and POST methods, since a specific method wasn’t provided. ``` python @rt def ft1(): return Html(Div('Text.')) print(cli.get('/ft1').text) ``` <!doctype html> <html> <div>Text.</div> </html> Handler functions can return [`FT`](https://docs.fastht.ml/explains/explaining_xt_components.html) objects, which are automatically converted to HTML strings. The `FT` class can take other `FT` components as arguments, such as `Div`. This allows for easy composition of HTML elements in your responses. ``` python @app.get def autopost(): return Html(Div('Text.', hx_post=yoyo.to())) print(cli.get('/autopost').text) ``` <!doctype html> <html> <div hx-post="/yoyo">Text.</div> </html> The `rt` decorator modifies the `yoyo` function by adding a `to()` method. This method returns the route path associated with the handler. It’s a convenient way to reference the route of a handler function dynamically. In the example, `yoyo.to()` is used as the value for `hx_post`. This means when the div is clicked, it will trigger an HTMX POST request to the route of the `yoyo` handler. This approach allows for flexible, DRY code by avoiding hardcoded route strings and automatically updating if the route changes. This pattern is particularly useful in larger applications where routes might change, or when building reusable components that need to reference their own routes dynamically. ``` python @app.get def autoget(): return Html(Body(Div('Text.', cls='px-2', hx_post=show_host.to(a='b')))) print(cli.get('/autoget').text) ``` <!doctype html> <html> <body> <div hx-post="/hostie?a=b" class="px-2">Text.</div> </body> </html> The `rt()` method of handler functions can also accept parameters. When called with parameters, it returns the route path with a query string appended. In this example, `show_host.to(a='b')` generates the path `/hostie?a=b`. The `Body` component is used here to demonstrate nesting of FT components. `Div` is nested inside `Body`, showcasing how you can create more complex HTML structures. The `cls` parameter is used to add a CSS class to the `Div`. This translates to the `class` attribute in the rendered HTML. (`class` can’t be used as a parameter name directly in Python since it’s a reserved word.) ``` python @rt('/ft2') def get(): return Title('Foo'),H1('bar') print(cli.get('/ft2').text) ``` <!doctype html> <html> <head> <title>Foo</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <script src="https://unpkg.com/[email protected]/dist/htmx.min.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/[email protected]/fasthtml.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js"></script><script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script><script> function sendmsg() { window.parent.postMessage({height: document.documentElement.offsetHeight}, '*'); } window.onload = function() { sendmsg(); document.body.addEventListener('htmx:afterSettle', sendmsg); document.body.addEventListener('htmx:wsAfterMessage', sendmsg); };</script> </head> <body> <h1>bar</h1> </body> </html> Handler functions can return multiple `FT` objects as a tuple. The first item is treated as the `Title`, and the rest are added to the `Body`. When the request is not an HTMX request, FastHTML automatically adds necessary HTML boilerplate, including default `head` content with required scripts. When using `app.route` (or `rt`), if the function name matches an HTTP verb (e.g., `get`, `post`, `put`, `delete`), that HTTP method is automatically used for the route. In this case, a path must be explicitly provided as an argument to the decorator. ``` python hxhdr = {'headers':{'hx-request':"1"}} print(cli.get('/ft2', **hxhdr).text) ``` <title>Foo</title> <h1>bar</h1> For HTMX requests (indicated by the `hx-request` header), FastHTML returns only the specified components without the full HTML structure. This allows for efficient partial page updates in HTMX applications. ``` python @rt('/ft3') def get(): return H1('bar') print(cli.get('/ft3', **hxhdr).text) ``` <h1>bar</h1> When a handler function returns a single `FT` object for an HTMX request, it’s rendered as a single HTML partial. ``` python @rt('/ft4') def get(): return Html(Head(Title('hi')), Body(P('there'))) print(cli.get('/ft4').text) ``` <!doctype html> <html> <head> <title>hi</title> </head> <body> <p>there</p> </body> </html> Handler functions can return a complete `Html` structure, including `Head` and `Body` components. When a full HTML structure is returned, FastHTML doesn’t add any additional boilerplate. This gives you full control over the HTML output when needed. ``` python @rt def index(): return "welcome!" print(cli.get('/').text) ``` welcome! The `index` function is a special handler in FastHTML. When defined without arguments to the `@rt` decorator, it automatically becomes the handler for the root path (`'/'`). This is a convenient way to define the main page or entry point of your application. ## Path and Query Parameters ``` python @rt('/user/{nm}', name='gday') def get(nm:str=''): return f"Good day to you, {nm}!" cli.get('/user/Alexis').text ``` 'Good day to you, Alexis!' Handler functions can use path parameters, defined using curly braces in the route – this is implemented by Starlette directly, so all Starlette path parameters can be used. These parameters are passed as arguments to the function. The `name` parameter in the decorator allows you to give the route a name, which can be used for URL generation. In this example, `{nm}` in the route becomes the `nm` parameter in the function. The function uses this parameter to create a personalized greeting. ``` python @app.get def autolink(): return Html(Div('Text.', link=uri('gday', nm='Alexis'))) print(cli.get('/autolink').text) ``` <!doctype html> <html> <div href="/user/Alexis">Text.</div> </html> The [`uri`](https://docs.fastht.ml/api/core.html#uri) function is used to generate URLs for named routes. It takes the route name as its first argument, followed by any path or query parameters needed for that route. In this example, `uri('gday', nm='Alexis')` generates the URL for the route named β€˜gday’ (which we defined earlier as β€˜/user/{nm}’), with β€˜Alexis’ as the value for the β€˜nm’ parameter. The `link` parameter in FT components sets the `href` attribute of the rendered HTML element. By using [`uri()`](https://docs.fastht.ml/api/core.html#uri), we can dynamically generate correct URLs even if the underlying route structure changes. This approach promotes maintainable code by centralizing route definitions and avoiding hardcoded URLs throughout the application. ``` python @rt('/link') def get(req): return f"{req.url_for('gday', nm='Alexis')}; {req.url_for('show_host')}" cli.get('/link').text ``` 'http://testserver/user/Alexis; http://testserver/hostie' The `url_for` method of the request object can be used to generate URLs for named routes. It takes the route name as its first argument, followed by any path parameters needed for that route. In this example, `req.url_for('gday', nm='Alexis')` generates the full URL for the route named β€˜gday’, including the scheme and host. Similarly, `req.url_for('show_host')` generates the URL for the β€˜show_host’ route. This method is particularly useful when you need to generate absolute URLs, such as for email links or API responses. It ensures that the correct host and scheme are included, even if the application is accessed through different domains or protocols. ``` python app.url_path_for('gday', nm='Jeremy') ``` '/user/Jeremy' The `url_path_for` method of the application can be used to generate URL paths for named routes. Unlike `url_for`, it returns only the path component of the URL, without the scheme or host. In this example, `app.url_path_for('gday', nm='Jeremy')` generates the path β€˜/user/Jeremy’ for the route named β€˜gday’. This method is useful when you need relative URLs or just the path component, such as for internal links or when constructing URLs in a host-agnostic manner. ``` python @rt('/oops') def get(nope): return nope r = cli.get('/oops?nope=1') print(r) r.text ``` <Response [200 OK]> /Users/iflath/git/AnswerDotAI/fasthtml/build/__editable__.python_fasthtml-0.12.1-py3-none-any/fasthtml/core.py:188: UserWarning: `nope has no type annotation and is not a recognised special name, so is ignored. if arg!='resp': warn(f"`{arg} has no type annotation and is not a recognised special name, so is ignored.") '' Handler functions can include parameters, but they must be type-annotated or have special names (like `req`) to be recognized. In this example, the `nope` parameter is not annotated, so it’s ignored, resulting in a warning. When a parameter is ignored, it doesn’t receive the value from the query string. This can lead to unexpected behavior, as the function attempts to return `nope`, which is undefined. The `cli.get('/oops?nope=1')` call succeeds with a 200 OK status because the handler doesn’t raise an exception, but it returns an empty response, rather than the intended value. To fix this, you should either add a type annotation to the parameter (e.g., `def get(nope: str):`) or use a recognized special name like `req`. ``` python @rt('/html/{idx}') def get(idx:int): return Body(H4(f'Next is {idx+1}.')) print(cli.get('/html/1', **hxhdr).text) ``` <body> <h4>Next is 2.</h4> </body> Path parameters can be type-annotated, and FastHTML will automatically convert them to the specified type if possible. In this example, `idx` is annotated as `int`, so it’s converted from the string in the URL to an integer. ``` python reg_re_param("imgext", "ico|gif|jpg|jpeg|webm") @rt(r'/static/{path:path}{fn}.{ext:imgext}') def get(fn:str, path:str, ext:str): return f"Getting {fn}.{ext} from /{path}" print(cli.get('/static/foo/jph.ico').text) ``` Getting jph.ico from /foo/ The [`reg_re_param`](https://docs.fastht.ml/api/core.html#reg_re_param) function is used to register custom path parameter types using regular expressions. Here, we define a new path parameter type called β€œimgext” that matches common image file extensions. Handler functions can use complex path patterns with multiple parameters and custom types. In this example, the route pattern `r'/static/{path:path}{fn}.{ext:imgext}'` uses three path parameters: 1. `path`: A Starlette built-in type that matches any path segments 2. `fn`: The filename without extension 3. `ext`: Our custom β€œimgext” type that matches specific image extensions ``` python ModelName = str_enum('ModelName', "alexnet", "resnet", "lenet") @rt("/models/{nm}") def get(nm:ModelName): return nm print(cli.get('/models/alexnet').text) ``` alexnet We define `ModelName` as an enum with three possible values: β€œalexnet”, β€œresnet”, and β€œlenet”. Handler functions can use these enum types as parameter annotations. In this example, the `nm` parameter is annotated with `ModelName`, which ensures that only valid model names are accepted. When a request is made with a valid model name, the handler function returns that name. This pattern is useful for creating type-safe APIs with a predefined set of valid values. ``` python @rt("/files/{path}") async def get(path: Path): return path.with_suffix('.txt') print(cli.get('/files/foo').text) ``` foo.txt Handler functions can use [`Path`](https://docs.fastht.ml/api/svg.html#path) objects as parameter types. The [`Path`](https://docs.fastht.ml/api/svg.html#path) type is from Python’s standard library `pathlib` module, which provides an object-oriented interface for working with file paths. In this example, the `path` parameter is annotated with [`Path`](https://docs.fastht.ml/api/svg.html#path), so FastHTML automatically converts the string from the URL to a [`Path`](https://docs.fastht.ml/api/svg.html#path) object. This approach is particularly useful when working with file-related routes, as it provides a convenient and platform-independent way to handle file paths. ``` python fake_db = [{"name": "Foo"}, {"name": "Bar"}] @rt("/items/") def get(idx:int|None = 0): return fake_db[idx] print(cli.get('/items/?idx=1').text) ``` {"name":"Bar"} Handler functions can use query parameters, which are automatically parsed from the URL. In this example, `idx` is a query parameter with a default value of 0. It’s annotated as `int|None`, allowing it to be either an integer or None. The function uses this parameter to index into a fake database (`fake_db`). When a request is made with a valid `idx` query parameter, the handler returns the corresponding item from the database. ``` python print(cli.get('/items/').text) ``` {"name":"Foo"} When no `idx` query parameter is provided, the handler function uses the default value of 0. This results in returning the first item from the `fake_db` list, which is `{"name":"Foo"}`. This behavior demonstrates how default values for query parameters work in FastHTML. They allow the API to have a sensible default behavior when optional parameters are not provided. ``` python print(cli.get('/items/?idx=g')) ``` <Response [404 Not Found]> When an invalid value is provided for a typed query parameter, FastHTML returns a 404 Not Found response. In this example, β€˜g’ is not a valid integer for the `idx` parameter, so the request fails with a 404 status. This behavior ensures type safety and prevents invalid inputs from reaching the handler function. ``` python @app.get("/booly/") def _(coming:bool=True): return 'Coming' if coming else 'Not coming' print(cli.get('/booly/?coming=true').text) print(cli.get('/booly/?coming=no').text) ``` Coming Not coming Handler functions can use boolean query parameters. In this example, `coming` is a boolean parameter with a default value of `True`. FastHTML automatically converts string values like β€˜true’, β€˜false’, β€˜1’, β€˜0’, β€˜on’, β€˜off’, β€˜yes’, and β€˜no’ to their corresponding boolean values. The underscore `_` is used as the function name in this example to indicate that the function’s name is not important or won’t be referenced elsewhere. This is a common Python convention for throwaway or unused variables, and it works here because FastHTML uses the route decorator parameter, when provided, to determine the URL path, not the function name. By default, both `get` and `post` methods can be used in routes that don’t specify an http method (by either using `app.get`, `def get`, or the `methods` parameter to `app.route`). ``` python @app.get("/datie/") def _(d:parsed_date): return d date_str = "17th of May, 2024, 2p" print(cli.get(f'/datie/?d={date_str}').text) ``` 2024-05-17 14:00:00 Handler functions can use `date` objects as parameter types. FastHTML uses `dateutil.parser` library to automatically parse a wide variety of date string formats into `date` objects. ``` python @app.get("/ua") async def _(user_agent:str): return user_agent print(cli.get('/ua', headers={'User-Agent':'FastHTML'}).text) ``` FastHTML Handler functions can access HTTP headers by using parameter names that match the header names. In this example, `user_agent` is used as a parameter name, which automatically captures the value of the β€˜User-Agent’ header from the request. The [`Client`](https://docs.fastht.ml/api/core.html#client) instance allows setting custom headers for test requests. Here, we set the β€˜User-Agent’ header to β€˜FastHTML’ in the test request. ``` python @app.get("/hxtest") def _(htmx): return htmx.request print(cli.get('/hxtest', headers={'HX-Request':'1'}).text) @app.get("/hxtest2") def _(foo:HtmxHeaders, req): return foo.request print(cli.get('/hxtest2', headers={'HX-Request':'1'}).text) ``` 1 1 Handler functions can access HTMX-specific headers using either the special `htmx` parameter name, or a parameter annotated with [`HtmxHeaders`](https://docs.fastht.ml/api/core.html#htmxheaders). Both approaches provide access to HTMX-related information. In these examples, the `htmx.request` attribute returns the value of the β€˜HX-Request’ header. ``` python app.chk = 'foo' @app.get("/app") def _(app): return app.chk print(cli.get('/app').text) ``` foo Handler functions can access the [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) application instance using the special `app` parameter name. This allows handlers to access application-level attributes and methods. In this example, we set a custom attribute `chk` on the application instance. The handler function then uses the `app` parameter to access this attribute and return its value. ``` python @app.get("/app2") def _(foo:FastHTML): return foo.chk,HttpHeader("mykey", "myval") r = cli.get('/app2', **hxhdr) print(r.text) print(r.headers) ``` foo Headers({'mykey': 'myval', 'content-length': '3', 'content-type': 'text/html; charset=utf-8'}) Handler functions can access the [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) application instance using a parameter annotated with [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml). This allows handlers to access application-level attributes and methods, just like using the special `app` parameter name. Handlers can return tuples containing both content and [`HttpHeader`](https://docs.fastht.ml/api/core.html#httpheader) objects. [`HttpHeader`](https://docs.fastht.ml/api/core.html#httpheader) allows setting custom HTTP headers in the response. In this example: - We define a handler that returns both the `chk` attribute from the application and a custom header. - The `HttpHeader("mykey", "myval")` sets a custom header in the response. - We use the test client to make a request and examine both the response text and headers. - The response includes the custom header β€œmykey” along with standard headers like content-length and content-type. ``` python @app.get("/app3") def _(foo:FastHTML): return HtmxResponseHeaders(location="http://example.org") r = cli.get('/app3') print(r.headers) ``` Headers({'hx-location': 'http://example.org', 'content-length': '0', 'content-type': 'text/html; charset=utf-8'}) Handler functions can return [`HtmxResponseHeaders`](https://docs.fastht.ml/api/core.html#htmxresponseheaders) objects to set HTMX-specific response headers. This is useful for HTMX-specific behaviors like client-side redirects. In this example we define a handler that returns an [`HtmxResponseHeaders`](https://docs.fastht.ml/api/core.html#htmxresponseheaders) object with a `location` parameter, which sets the `HX-Location` header in the response. HTMX uses this for client-side redirects. ``` python @app.get("/app4") def _(foo:FastHTML): return Redirect("http://example.org") cli.get('/app4', follow_redirects=False) ``` <Response [303 See Other]> Handler functions can return [`Redirect`](https://docs.fastht.ml/api/core.html#redirect) objects to perform HTTP redirects. This is useful for redirecting users to different pages or external URLs. In this example: - We define a handler that returns a [`Redirect`](https://docs.fastht.ml/api/core.html#redirect) object with the URL β€œhttp://example.org”. - The `cli.get('/app4', follow_redirects=False)` call simulates a GET request to the β€˜/app4’ route without following redirects. - The response has a 303 See Other status code, indicating a redirect. The `follow_redirects=False` parameter is used to prevent the test client from automatically following the redirect, allowing us to inspect the redirect response itself. ``` python Redirect.__response__ ``` <function fasthtml.core.Redirect.__response__(self, req)> The [`Redirect`](https://docs.fastht.ml/api/core.html#redirect) class in FastHTML implements a `__response__` method, which is a special method recognized by the framework. When a handler returns a [`Redirect`](https://docs.fastht.ml/api/core.html#redirect) object, FastHTML internally calls this `__response__` method to replace the original response. The `__response__` method takes a `req` parameter, which represents the incoming request. This allows the method to access request information if needed when constructing the redirect response. ``` python @rt def meta(): return ((Title('hi'),H1('hi')), (Meta(property='image'), Meta(property='site_name'))) print(cli.post('/meta').text) ``` <!doctype html> <html> <head> <title>hi</title> <meta property="image"> <meta property="site_name"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <script src="https://unpkg.com/[email protected]/dist/htmx.min.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/[email protected]/fasthtml.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js"></script><script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script><script> function sendmsg() { window.parent.postMessage({height: document.documentElement.offsetHeight}, '*'); } window.onload = function() { sendmsg(); document.body.addEventListener('htmx:afterSettle', sendmsg); document.body.addEventListener('htmx:wsAfterMessage', sendmsg); };</script> </head> <body> <h1>hi</h1> </body> </html> FastHTML automatically identifies elements typically placed in the `<head>` (like `Title` and `Meta`) and positions them accordingly, while other elements go in the `<body>`. In this example: - `(Title('hi'), H1('hi'))` defines the title and main heading. The title is placed in the head, and the H1 in the body. - `(Meta(property='image'), Meta(property='site_name'))` defines two meta tags, which are both placed in the head. ## APIRouter [`APIRouter`](https://docs.fastht.ml/api/core.html#apirouter) is useful when you want to split your application routes across multiple `.py` files that are part of a single FastHTMl application. It accepts an optional `prefix` argument that will be applied to all routes within that instance of [`APIRouter`](https://docs.fastht.ml/api/core.html#apirouter). Below we define several hypothetical product related routes in a `products.py` and then demonstrate how they can seamlessly be incorporated into a FastHTML app instance. ``` python # products.py ar = APIRouter(prefix="/products") @ar("/all") def all_products(req): return Div( "Welcome to the Products Page! Click the button below to look at the details for product 42", Div( Button( "Details", hx_get=req.url_for("details", pid=42), hx_target="#products_list", hx_swap="outerHTML", ), ), id="products_list", ) @ar.get("/{pid}", name="details") def details(pid: int): return f"Here are the product details for ID: {pid}" ``` Since we specified the `prefix=/products` in our hypothetical `products.py` file, all routes defined in that file will be found under `/products`. ``` python print(str(ar.rt_funcs.all_products)) print(str(ar.rt_funcs.details)) ``` /products/all /products/{pid} ``` python # main.py # from products import ar app, rt = fast_app() ar.to_app(app) @rt def index(): return Div( "Click me for a look at our products", hx_get=ar.rt_funcs.all_products, hx_swap="outerHTML", ) ``` Note how you can reference our python route functions via `APIRouter.rt_funcs` in your `hx_{http_method}` calls like normal. ## Form Data and JSON Handling ``` python app = FastHTML() rt = app.route cli = Client(app) ``` ``` python @app.post('/profile/me') def profile_update(username: str): return username r = cli.post('/profile/me', data={'username' : 'Alexis'}).text assert r == 'Alexis' print(r) ``` Alexis Handler functions can accept form data parameters, without needing to manually extract it from the request. In this example, `username` is expected to be sent as form data. The `data` parameter in the `cli.post()` method simulates sending form data in the request. ``` python r = cli.post('/profile/me', data={}) assert r.status_code == 400 print(r.text) r ``` Missing required field: username <Response [400 Bad Request]> If required form data is missing, FastHTML automatically returns a 400 Bad Request response with an error message. ``` python @app.post('/pet/dog') def pet_dog(dogname: str = None): return dogname or 'unknown name' r = cli.post('/pet/dog', data={}).text r ``` 'unknown name' Handlers can have optional form data parameters with default values. In this example, `dogname` is an optional parameter with a default value of `None`. Here, if the form data doesn’t include the `dogname` field, the function uses the default value. The function returns either the provided `dogname` or β€˜unknown name’ if `dogname` is `None`. ``` python @dataclass class Bodie: a:int;b:str @rt("/bodie/{nm}") def post(nm:str, data:Bodie): res = asdict(data) res['nm'] = nm return res print(cli.post('/bodie/me', data=dict(a=1, b='foo', nm='me')).text) ``` {"a":1,"b":"foo","nm":"me"} You can use dataclasses to define structured form data. In this example, `Bodie` is a dataclass with `a` (int) and `b` (str) fields. FastHTML automatically converts the incoming form data to a `Bodie` instance where attribute names match parameter names. Other form data elements are matched with parameters with the same names (in this case, `nm`). Handler functions can return dictionaries, which FastHTML automatically JSON-encodes. ``` python @app.post("/bodied/") def bodied(data:dict): return data d = dict(a=1, b='foo') print(cli.post('/bodied/', data=d).text) ``` {"a":"1","b":"foo"} `dict` parameters capture all form data as a dictionary. In this example, the `data` parameter is annotated with `dict`, so FastHTML automatically converts all incoming form data into a dictionary. Note that when form data is converted to a dictionary, all values become strings, even if they were originally numbers. This is why the β€˜a’ key in the response has a string value β€œ1” instead of the integer 1. ``` python nt = namedtuple('Bodient', ['a','b']) @app.post("/bodient/") def bodient(data:nt): return asdict(data) print(cli.post('/bodient/', data=d).text) ``` {"a":"1","b":"foo"} Handler functions can use named tuples to define structured form data. In this example, `Bodient` is a named tuple with `a` and `b` fields. FastHTML automatically converts the incoming form data to a `Bodient` instance where field names match parameter names. As with the previous example, all form data values are converted to strings in the process. ``` python class BodieTD(TypedDict): a:int;b:str='foo' @app.post("/bodietd/") def bodient(data:BodieTD): return data print(cli.post('/bodietd/', data=d).text) ``` {"a":1,"b":"foo"} You can use `TypedDict` to define structured form data with type hints. In this example, `BodieTD` is a `TypedDict` with `a` (int) and `b` (str) fields, where `b` has a default value of β€˜foo’. FastHTML automatically converts the incoming form data to a `BodieTD` instance where keys match the defined fields. Unlike with regular dictionaries or named tuples, FastHTML respects the type hints in `TypedDict`, converting values to the specified types when possible (e.g., converting β€˜1’ to the integer 1 for the β€˜a’ field). ``` python class Bodie2: a:int|None; b:str def __init__(self, a, b='foo'): store_attr() @app.post("/bodie2/") def bodie(d:Bodie2): return f"a: {d.a}; b: {d.b}" print(cli.post('/bodie2/', data={'a':1}).text) ``` a: 1; b: foo Custom classes can be used to define structured form data. Here, `Bodie2` is a custom class with `a` (int|None) and `b` (str) attributes, where `b` has a default value of β€˜foo’. The `store_attr()` function (from fastcore) automatically assigns constructor parameters to instance attributes. FastHTML automatically converts the incoming form data to a `Bodie2` instance, matching form fields to constructor parameters. It respects type hints and default values. ``` python @app.post("/b") def index(it: Bodie): return Titled("It worked!", P(f"{it.a}, {it.b}")) s = json.dumps({"b": "Lorem", "a": 15}) print(cli.post('/b', headers={"Content-Type": "application/json", 'hx-request':"1"}, data=s).text) ``` <title>It worked!</title> <main class="container"> <h1>It worked!</h1> <p>15, Lorem</p> </main> Handler functions can accept JSON data as input, which is automatically parsed into the specified type. In this example, `it` is of type `Bodie`, and FastHTML converts the incoming JSON data to a `Bodie` instance. The [`Titled`](https://docs.fastht.ml/api/xtend.html#titled) component is used to create a page with a title and main content. It automatically generates an `<h1>` with the provided title, wraps the content in a `<main>` tag with a β€œcontainer” class, and adds a `title` to the head. When making a request with JSON data: - Set the β€œContent-Type” header to β€œapplication/json” - Provide the JSON data as a string in the `data` parameter of the request ## Cookies, Sessions, File Uploads, and more ``` python @rt("/setcookie") def get(): return cookie('now', datetime.now()) @rt("/getcookie") def get(now:parsed_date): return f'Cookie was set at time {now.time()}' print(cli.get('/setcookie').text) time.sleep(0.01) cli.get('/getcookie').text ``` 'Cookie was set at time 16:19:27.811570' Handler functions can set and retrieve cookies. In this example: - The `/setcookie` route sets a cookie named β€˜now’ with the current datetime. - The `/getcookie` route retrieves the β€˜now’ cookie and returns its value. The [`cookie()`](https://docs.fastht.ml/api/core.html#cookie) function is used to create a cookie response. FastHTML automatically converts the datetime object to a string when setting the cookie, and parses it back to a date object when retrieving it. ``` python cookie('now', datetime.now()) ``` HttpHeader(k='set-cookie', v='now="2025-01-30 16:19:29.997374"; Path=/; SameSite=lax') The [`cookie()`](https://docs.fastht.ml/api/core.html#cookie) function returns an [`HttpHeader`](https://docs.fastht.ml/api/core.html#httpheader) object with the β€˜set-cookie’ key. You can return it in a tuple along with `FT` elements, along with anything else FastHTML supports in responses. ``` python app = FastHTML(secret_key='soopersecret') cli = Client(app) rt = app.route ``` ``` python @rt("/setsess") def get(sess, foo:str=''): now = datetime.now() sess['auth'] = str(now) return f'Set to {now}' @rt("/getsess") def get(sess): return f'Session time: {sess["auth"]}' print(cli.get('/setsess').text) time.sleep(0.01) cli.get('/getsess').text ``` Set to 2025-01-30 16:19:31.078650 'Session time: 2025-01-30 16:19:31.078650' Sessions store and retrieve data across requests. To use sessions, you should to initialize the FastHTML application with a `secret_key`. This is used to cryptographically sign the cookie used by the session. The `sess` parameter in handler functions provides access to the session data. You can set and get session variables using dictionary-style access. ``` python @rt("/upload") async def post(uf:UploadFile): return (await uf.read()).decode() with open('../../CHANGELOG.md', 'rb') as f: print(cli.post('/upload', files={'uf':f}, data={'msg':'Hello'}).text[:15]) ``` # Release notes Handler functions can accept file uploads using Starlette’s `UploadFile` type. In this example: - The `/upload` route accepts a file upload named `uf`. - The `UploadFile` object provides an asynchronous `read()` method to access the file contents. - We use `await` to read the file content asynchronously and decode it to a string. We added `async` to the handler function because it uses `await` to read the file content asynchronously. In Python, any function that uses `await` must be declared as `async`. This allows the function to be run asynchronously, potentially improving performance by not blocking other operations while waiting for the file to be read. ``` python app.static_route('.md', static_path='../..') print(cli.get('/README.md').text[:10]) ``` # FastHTML The `static_route` method of the FastHTML application allows serving static files with specified extensions from a given directory. In this example: - `.md` files are served from the `../..` directory (two levels up from the current directory). - Accessing `/README.md` returns the contents of the README.md file from that directory. ``` python help(app.static_route_exts) ``` Help on method static_route_exts in module fasthtml.core: static_route_exts(prefix='/', static_path='.', exts='static') method of fasthtml.core.FastHTML instance Add a static route at URL path `prefix` with files from `static_path` and `exts` defined by `reg_re_param()` ``` python app.static_route_exts() assert cli.get('/README.txt').status_code == 404 print(cli.get('/README.txt').text[:50]) ``` 404 Not Found The `static_route_exts` method of the FastHTML application allows serving static files with specified extensions from a given directory. By default: - It serves files from the current directory (β€˜.’). - It uses the β€˜static’ regex, which includes common static file extensions like β€˜ico’, β€˜gif’, β€˜jpg’, β€˜css’, β€˜js’, etc. - The URL prefix is set to β€˜/’. The β€˜static’ regex is defined by FastHTML using this code: ``` python reg_re_param("static", "ico|gif|jpg|jpeg|webm|css|js|woff|png|svg|mp4|webp|ttf|otf|eot|woff2|txt|html|map") ``` ``` python @rt("/form-submit/{list_id}") def options(list_id: str): headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*', } return Response(status_code=200, headers=headers) print(cli.options('/form-submit/2').headers) ``` Headers({'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST', 'access-control-allow-headers': '*', 'content-length': '0', 'set-cookie': 'session_=eyJhdXRoIjogIjIwMjUtMDEtMzAgMTY6MTk6MzEuMDc4NjUwIn0=.Z5vtZA.1ooY2RCWopWAbLYDy6660g_LlHI; path=/; Max-Age=31536000; httponly; samesite=lax'}) FastHTML handlers can handle OPTIONS requests and set custom headers. In this example: - The `/form-submit/{list_id}` route handles OPTIONS requests. - Custom headers are set to allow cross-origin requests (CORS). - The function returns a Starlette `Response` object with a 200 status code and the custom headers. You can return any Starlette Response type from a handler function, giving you full control over the response when needed. ``` python def _not_found(req, exc): return Div('nope') app = FastHTML(exception_handlers={404:_not_found}) cli = Client(app) rt = app.route r = cli.get('/') print(r.text) ``` <!doctype html> <html> <head> <title>FastHTML page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <script src="https://unpkg.com/[email protected]/dist/htmx.min.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/[email protected]/fasthtml.js"></script><script src="https://cdn.jsdelivr.net/gh/answerdotai/surreal@main/surreal.js"></script><script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script><script> function sendmsg() { window.parent.postMessage({height: document.documentElement.offsetHeight}, '*'); } window.onload = function() { sendmsg(); document.body.addEventListener('htmx:afterSettle', sendmsg); document.body.addEventListener('htmx:wsAfterMessage', sendmsg); };</script> </head> <body> <div>nope</div> </body> </html> FastHTML allows you to define custom exception handlers – in this case, a custom 404 (Not Found) handler function `_not_found`, which returns a `Div` component with the text β€˜nope’.
https://docs.fastht.ml/ref/handlers.html.md
ref_handlers.html.md
# Live Reloading <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! --> When building your app it can be useful to view your changes in a web browser as you make them. FastHTML supports live reloading which means that it watches for any changes to your code and automatically refreshes the webpage in your browser. To enable live reloading simply replace [`FastHTML`](https://docs.fastht.ml/api/core.html#fasthtml) in your app with `FastHTMLWithLiveReload`. ``` python from fasthtml.common import * app = FastHTMLWithLiveReload() ``` Then in your terminal run `uvicorn` with reloading enabled. uvicorn main:app --reload **⚠️ Gotchas** - A reload is only triggered when you save your changes. - `FastHTMLWithLiveReload` should only be used during development. - If your app spans multiple directories you might need to use the `--reload-dir` flag to watch all files in each directory. See the uvicorn [docs](https://www.uvicorn.org/settings/#development) for more info. - The live reload script is only injected into the page when rendering [ft components](https://docs.fastht.ml/explains/explaining_xt_components.html). ## Live reloading with `fast_app` In development the `fast_app` function provides the same functionality. It instantiates the `FastHTMLWithLiveReload` class if you pass `live=True`: <div class="code-with-filename"> **main.py** ``` python from fasthtml.common import * app, rt = fast_app(live=True) serve() ``` </div> Line 3 `fast_app()` instantiates the `FastHTMLWithLiveReload` class. Line 5 [`serve()`](https://docs.fastht.ml/api/core.html#serve) is a wrapper around a `uvicorn` call. To run `main.py` in live reload mode, just do `python main.py`. We recommend turning off live reload when deploying your app to production.
https://docs.fastht.ml/ref/live_reload.html.md
ref_live_reload.html.md
import plotly.express as px from fasthtml.common import * # Add the Plotly library to the headers app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.24.1.min.js"),)) def create_scatter_plot(): # Create simple scatter plot with 5 points fig = px.scatter( x=[1, 2, 3, 4, 5], y=[2, 4, 1, 3, 5], labels={"x": "X Value", "y": "Y Value"} ) return fig.to_json() @rt def index(): return Titled("Interactive Plotly Selection", P("Click any point to see its x-value!"), # point-info will be updated based on what is clicked Div(id="point-info")(P("No point selected yet")), # plotly-container will be updated with the plot Div(id="plotly-container"), # Initialize the plot Script( f""" // All the plot data is given in json form by `create_scatter_plot` const plotData = {create_scatter_plot()}; // Create the plot with that data in location with id `plotly-container` Plotly.newPlot('plotly-container', plotData.data, plotData.layout); // Add click event handler // Get thing with id `plotly-container`, and on plotly_click event, // run the function document.getElementById('plotly-container').on('plotly_click', function(data) {{ // Get the first point clicked const point = data.points[0]; // Make HTMX request when point is clicked with the x-value htmx.ajax('GET', `point/${{point.x}}`, {{target: '#point-info'}}); }}); """ )) @rt("/point/{x_val}") def get(x_val: float): # Return the x-value of the point clicked to the UI! return P(Strong(f"You clicked the point with x-value: {x_val}")) serve()
https://gallery.fastht.ml/split/visualizations/plotly_selections
FastHTML page
from fasthtml.common import * import numpy as np plot_js = """ function createPlot(data) { const plot = Plot.rectY(data, Plot.binX({y: "count"},{x: d => d.value,fill:"steelblue"})).plot(); const div = document.querySelector("#plot"); div.replaceChildren(plot); } // Set up initial load via HTMX htmx.on('htmx:afterSettle', evt => { if (evt.detail.target.id === 'data-store') { // The data is now properly JSON-encoded const data = JSON.parse(evt.detail.target.textContent); createPlot(data); } }); """ app, rt = fast_app( hdrs=(Script(src="https://cdn.jsdelivr.net/npm/d3@7"), Script(src="https://cdn.jsdelivr.net/npm/@observablehq/[email protected]"))) @rt def index(): return Div( Section( H1(A("Observable", href="https://observablehq.com/@observablehq/plot", target="_blank"), " Plot Demo"), P("The data is randomly generated on the server and is fetched on initial page load."), P("Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request."), # On bytton click it sends a get request to the `get_data` route and puts the response in the `data-store` div Button("Fetch New Data", get=get_data, hx_target="#data-store")), # Store for the JSON chart data Div(id="data-store", get=get_data, hx_trigger="load", hidden=True), # Plot container Div(id="plot"), # Include the JavaScript for the plot Script(plot_js) ) @rt def get_data(): # Generate sample data data = [{"value": float(x)} for x in np.random.randn(100)] # Return as proper JSON response return JSONResponse(data) serve()
https://gallery.fastht.ml/split/visualizations/observable_plot
FastHTML page
from fasthtml.common import * import pandas as pd import numpy as np import plotly.express as px from fh_plotly import plotly2fasthtml, plotly_headers app, rt = fast_app(hdrs=(plotly_headers,)) y_data = [1, 2, 3, 2] x_data = [3, 1, 2, 4] def generate_line_chart(): df = pd.DataFrame({'y': y_data, 'x': x_data}) fig = px.line(df, x='x', y='y') return plotly2fasthtml(fig) def generate_bar_chart(): df = pd.DataFrame({'y': y_data, 'x': ['A', 'B', 'C','D']}) fig = px.bar(df, x='x', y='y') return plotly2fasthtml(fig) def generate_scatter_chart(): df = pd.DataFrame({'y': y_data, 'x': x_data, 'size': [10, 20, 30, 40]}) fig = px.scatter(df, x='x', y='y', size='size') return plotly2fasthtml(fig) def generate_3d_scatter_chart(): df = pd.DataFrame({ 'x': [1, 2, 3, 4, 5, 6], 'y': [7, 8, 6, 9, 7, 8], 'z': [3, 5, 4, 6, 5, 7] }) fig = px.scatter_3d(df, x='x', y='y', z='z') return plotly2fasthtml(fig) @rt def index(): return Div( H1("Plotly Interactive Charts Demo with FastHTML"), P("Try interacting with the charts by hovering over data points, zooming in and out, panning, rotating (3D), and more!."), Div(Div(Strong("Plot 1: Line Chart"), Div(generate_line_chart()),), Div(Strong("Plot 2: Bar Chart"), Div(generate_bar_chart()),), Div(Strong("Plot 3: Scatter Chart"), Div(generate_scatter_chart()),), Div(Strong("Plot 4: 3D Scatter Chart"), Div(generate_3d_scatter_chart()),), style="display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 20px; width: 100%; height: 800px;" ) ) serve()
https://gallery.fastht.ml/split/visualizations/plotly_charts
FastHTML page
from fasthtml.common import * import pandas as pd import numpy as np import plotly.express as px from fh_plotly import plotly2fasthtml, plotly_headers app, rt = fast_app(hdrs=(plotly_headers,)) y_data = [1, 2, 3, 2] x_data = [3, 1, 2, 4] def generate_line_chart(): df = pd.DataFrame({'y': y_data, 'x': x_data}) fig = px.line(df, x='x', y='y') return plotly2fasthtml(fig) def generate_bar_chart(): df = pd.DataFrame({'y': y_data, 'x': ['A', 'B', 'C','D']}) fig = px.bar(df, x='x', y='y') return plotly2fasthtml(fig) def generate_scatter_chart(): df = pd.DataFrame({'y': y_data, 'x': x_data, 'size': [10, 20, 30, 40]}) fig = px.scatter(df, x='x', y='y', size='size') return plotly2fasthtml(fig) def generate_3d_scatter_chart(): df = pd.DataFrame({ 'x': [1, 2, 3, 4, 5, 6], 'y': [7, 8, 6, 9, 7, 8], 'z': [3, 5, 4, 6, 5, 7] }) fig = px.scatter_3d(df, x='x', y='y', z='z') return plotly2fasthtml(fig) @rt def index(): return Div( H1("Plotly Interactive Charts Demo with FastHTML"), P("Try interacting with the charts by hovering over data points, zooming in and out, panning, rotating (3D), and more!."), Div(Div(Strong("Plot 1: Line Chart"), Div(generate_line_chart()),), Div(Strong("Plot 2: Bar Chart"), Div(generate_bar_chart()),), Div(Strong("Plot 3: Scatter Chart"), Div(generate_scatter_chart()),), Div(Strong("Plot 4: 3D Scatter Chart"), Div(generate_3d_scatter_chart()),), style="display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; gap: 20px; width: 100%; height: 800px;" ) ) serve()
https://gallery.fastht.ml/code/visualizations/plotly_charts
FastHTML page
from fh_matplotlib import matplotlib2fasthtml from fasthtml.common import * import numpy as np import matplotlib.pylab as plt app, rt = fast_app() @matplotlib2fasthtml def generate_chart(num_points): plotdata = [np.random.exponential(1) for _ in range(num_points)] plt.plot(range(len(plotdata)), plotdata) @rt def index(): return Div( Div(id="chart"), H3("Move the slider to change the graph"), Input( type="range", min="1", max="10", value="1", get=update_chart, hx_target="#chart", name='slider') ) @rt def update_chart(slider: int): return Div( generate_chart(slider), P(f"Number of data points: {slider}") )
https://gallery.fastht.ml/code/visualizations/matplotlib_charts
FastHTML page
from fasthtml.common import * import numpy as np plot_js = """ function createPlot(data) { const plot = Plot.rectY(data, Plot.binX({y: "count"},{x: d => d.value,fill:"steelblue"})).plot(); const div = document.querySelector("#plot"); div.replaceChildren(plot); } // Set up initial load via HTMX htmx.on('htmx:afterSettle', evt => { if (evt.detail.target.id === 'data-store') { // The data is now properly JSON-encoded const data = JSON.parse(evt.detail.target.textContent); createPlot(data); } }); """ app, rt = fast_app( hdrs=(Script(src="https://cdn.jsdelivr.net/npm/d3@7"), Script(src="https://cdn.jsdelivr.net/npm/@observablehq/[email protected]"))) @rt def index(): return Div( Section( H1(A("Observable", href="https://observablehq.com/@observablehq/plot", target="_blank"), " Plot Demo"), P("The data is randomly generated on the server and is fetched on initial page load."), P("Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request."), # On bytton click it sends a get request to the `get_data` route and puts the response in the `data-store` div Button("Fetch New Data", get=get_data, hx_target="#data-store")), # Store for the JSON chart data Div(id="data-store", get=get_data, hx_trigger="load", hidden=True), # Plot container Div(id="plot"), # Include the JavaScript for the plot Script(plot_js) ) @rt def get_data(): # Generate sample data data = [{"value": float(x)} for x in np.random.randn(100)] # Return as proper JSON response return JSONResponse(data) serve()
https://gallery.fastht.ml/code/visualizations/observable_plot
FastHTML page
from functools import cache import polars as pl from great_tables import GT, html from great_tables.data import sza from fasthtml.common import * app, rt = fast_app() @cache def get_sza_pivot(): # Filter and pivot the data return (pl.from_pandas(sza) .filter((pl.col("latitude") == "20") & (pl.col("tst") <= "1200")) .select(pl.col("*").exclude("latitude")) .drop_nulls() .pivot(values="sza", index="month", on="tst", sort_columns=True)) def get_notstr_table(color1: str = "#663399", color2: str = "#FFA500"): # Create the table sza_gt = (GT(get_sza_pivot(), rowname_col="month") .data_color( domain=[90, 0], palette=[color1, "white", color2], na_color="white",) .tab_header( title="Solar Zenith Angles from 05:30 to 12:00", subtitle=html("Average monthly values at latitude of 20&deg;N.")) .sub_missing(missing_text="")) # Return the table by converting to raw HTML return Div(NotStr(sza_gt.as_raw_html())) @app.post("/submit", name="submit") def post(d: dict): return get_notstr_table(**d) @rt def index(): return (Title("FastHTML-GT Website"), Titled("Great Tables shown in FastHTML", style="text-align:center"), Main(cls='container')( Form(post="submit", hx_target="#gt", hx_trigger="input")( Grid(Card(H2("Color1"), Input(type="color",id="color1", value="#663399")), Card(H2("Color2"), Input(type="color",id="color2", value="#FFA500")))), Div(get_notstr_table(), id="gt")))
https://gallery.fastht.ml/code/visualizations/great_tables_tables
FastHTML page
from fh_matplotlib import matplotlib2fasthtml from fasthtml.common import * import numpy as np import matplotlib.pylab as plt app, rt = fast_app() @matplotlib2fasthtml def generate_chart(num_points): plotdata = [np.random.exponential(1) for _ in range(num_points)] plt.plot(range(len(plotdata)), plotdata) @rt def index(): return Div( Div(id="chart"), H3("Move the slider to change the graph"), Input( type="range", min="1", max="10", value="1", get=update_chart, hx_target="#chart", name='slider') ) @rt def update_chart(slider: int): return Div( generate_chart(slider), P(f"Number of data points: {slider}") )
https://gallery.fastht.ml/split/visualizations/matplotlib_charts
FastHTML page
from functools import cache import polars as pl from great_tables import GT, html from great_tables.data import sza from fasthtml.common import * app, rt = fast_app() @cache def get_sza_pivot(): # Filter and pivot the data return (pl.from_pandas(sza) .filter((pl.col("latitude") == "20") & (pl.col("tst") <= "1200")) .select(pl.col("*").exclude("latitude")) .drop_nulls() .pivot(values="sza", index="month", on="tst", sort_columns=True)) def get_notstr_table(color1: str = "#663399", color2: str = "#FFA500"): # Create the table sza_gt = (GT(get_sza_pivot(), rowname_col="month") .data_color( domain=[90, 0], palette=[color1, "white", color2], na_color="white",) .tab_header( title="Solar Zenith Angles from 05:30 to 12:00", subtitle=html("Average monthly values at latitude of 20&deg;N.")) .sub_missing(missing_text="")) # Return the table by converting to raw HTML return Div(NotStr(sza_gt.as_raw_html())) @app.post("/submit", name="submit") def post(d: dict): return get_notstr_table(**d) @rt def index(): return (Title("FastHTML-GT Website"), Titled("Great Tables shown in FastHTML", style="text-align:center"), Main(cls='container')( Form(post="submit", hx_target="#gt", hx_trigger="input")( Grid(Card(H2("Color1"), Input(type="color",id="color1", value="#663399")), Card(H2("Color2"), Input(type="color",id="color2", value="#FFA500")))), Div(get_notstr_table(), id="gt")))
https://gallery.fastht.ml/split/visualizations/great_tables_tables
FastHTML page
Tic Tac Toe Web App This project is a web-based implementation of the classic Tic Tac Toe game built by Adedara Adeloro using FastHTML, HTMX, and Tailwind CSS. The build steps from the original project were simplifed to use CDNs for the FastHTML Gallery version. To check out the original project, click here Key Technologies and Techniques FastHTML: A Python-based framework for building web applications with a focus web fundamentals HTMX: HTMX is used to create the dynamic server-side content updates that lets you interact with the app without page reloads. Tailwind CSS: Tailwind classes are used throughout the HTML to style the app, providing a clean and responsive design. For example cls="grid grid-cols-3 grid-rows-3 creates a 3x3 grid for the Tic Tac Toe board. How It Works Server-Side Logic The app uses FastHTML to define routes and handle game logic on the server. Key routes include: /: The main page that renders the initial game board. /on_click: Handles player moves and updates the game state. /restart: Resets the game board. State Management The game state is managed server-side using global variables: button_states: A 2D array storing snapshots of the board. current_state_index: Tracks the current state of the game. winner_found_game_ended: A flag to indicate if the game has ended. Dynamic Content HTMX is used extensively to create a dynamic user interface
https://gallery.fastht.ml/info/applications/tic_tac_toe
FastHTML page
import numpy as np from fasthtml.common import * import plotly.graph_objects as go from fh_plotly import plotly2fasthtml, plotly_headers ######################## ### FastHTML Section ### ######################## app, rt = fast_app(hdrs=(plotly_headers,)) @rt def index(): desc = """ The Bloch Sphere is a 3D visualization of a single quantum state. You can interact with the buttons (Gates) to see how the state changes. See the description below for more information on what each gate represents. """ hx_vals = 'js:{"gates": document.getElementById("quantum_circuit").textContent}' return (Title("Interactive Bloch Sphere"), Main(P(desc), *[Button(gate, hx_get=f"apply_gate/{gate}", hx_target="#chart", hx_swap="innerHTML", hx_vals=hx_vals, title=f"Apply {gate} gate") for gate in single_qubit_gates.keys()], Button("Reset", hx_get="reset", hx_target="#chart", hx_swap="innerHTML", title="Reset the circuit"), Div(update_state_apply_gate.__wrapped__(), id="chart"), H4("Available gates"), Ul(Li(Strong("H :"),"Hadamard gate. Puts the state in superposition. "), Li(Strong("X :"),"Pauli-X (NOT) gate. Rotate 180 degrees around the X-Axis."), Li(Strong("Y :"),"Pauli-Y (\"bit-flip\") gate. Rotate 180 degrees around the Y-Axis."), Li(Strong("Z :"),"Pauli-Z (\"phase-flip\") gate. Rotate 180 degrees around the Z-Axis."), Li(Strong("S :"),"Phase gate. Rotates around the Z-axis by 90 degrees."), Li(Strong("T :"),"Ο€/8 gate. Rotates around the Z-axis by 45 degrees.")))) @rt def reset(): return update_state_apply_gate.__wrapped__() @app.get('/apply_gate/{gate}') def update_state_apply_gate(gate: str=None, gates: str=None): if gates is None: gates = [] else: # Transform from circuit representation to gate names gates = [g for g in gates if g in single_qubit_gates.keys()] gates.append(gate) # Create initial state state = np.array([1, 0]) # |0> basis state for gate in gates: state = single_qubit_gates[gate] @ state # Create visualization return Div(plot_bloch(state), H4(f"Quantum Circuit: {visualize_circuit(gates)}", id="quantum_circuit"), id="chart") def visualize_circuit(gates: list[str]): circuit = "|0⟩-" circuit += "".join([f"[{gate}]─" for gate in gates]) + "|" return circuit ############################ ### Math/Quantum Section ### ############################ def calculate_coordinates(theta, phi): x = np.sin(theta) * np.cos(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(theta) return x, y, z def create_scenes(): axis2ticktext = {'X': ['|-⟩', '|+⟩'], 'Y': ['|-i⟩', '|i⟩'], 'Z': ['|1⟩', '|0⟩']} scenes = {} for axis in ['X','Y','Z']: scenes[f'{axis.lower()}axis'] = dict(title=dict(text=axis, font=dict(size=25)), range=[-1.2, 1.2], tickvals=[-1, 1], ticktext=axis2ticktext[axis], tickfont=dict(size=15) ) return scenes def plot_bloch(state: np.array): fig = go.Figure() # State vector coordinates alpha, beta = state[0], state[1] theta = 2 * np.arccos(np.abs(alpha)) phi = np.angle(beta) - np.angle(alpha) x, y, z = calculate_coordinates(theta, phi) # Surface coordinates surface_phi, surface_theta = np.mgrid[0:2*np.pi:100j, 0:np.pi:50j] xs, ys, zs = calculate_coordinates(surface_theta, surface_phi) fig.add_trace(go.Surface(x=xs, y=ys, z=zs, opacity=0.5, colorscale='Blues', showscale=False)) fig.add_trace(go.Scatter3d(x=[0, x],y=[0, y],z=[0, z], mode='lines+markers+text', marker=dict(size=10, color='green'), line=dict(color='green', width=8), textposition="top center", showlegend=True,name=f"{alpha:.2f}|0⟩ + {beta:.2f}|1⟩")) # Mark basis states fig.add_trace(go.Scatter3d(x=[0, 0, 1, -1, 0, 0],y=[0, 0, 0, 0, 1, -1], z=[1, -1, 0, 0, 0, 0], mode='markers', marker=dict(size=5, color='black'), hovertext=['|0⟩', '|1⟩', '|+⟩', '|-⟩', '|i⟩', '|-i⟩'], showlegend=False, name="Basis states")) # Add lines across axes boundary_phi = np.linspace(0, 2 * np.pi, 100) coords = [(np.cos(boundary_phi), np.sin(boundary_phi), np.zeros_like(boundary_phi)), (np.zeros_like(boundary_phi), np.cos(boundary_phi), np.sin(boundary_phi)), (np.cos(boundary_phi), np.zeros_like(boundary_phi), np.sin(boundary_phi)) ] for x, y, z in coords: fig.add_trace(go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='black', width=2), showlegend=False, name="Axes")) fig.update_layout(scene=dict(**create_scenes(), aspectmode='cube',), legend=dict( font=dict(size=20), x=0.05,y=0.95, xanchor='left', yanchor='top', bgcolor='rgba(0,0,0,0)',), margin=dict(l=0, r=0, t=0, b=0)) return plotly2fasthtml(fig) single_qubit_gates = { # Hadamard "H": np.array([[1, 1], [1, -1]]) / np.sqrt(2), # Pauli matrices "X": np.array([[0, 1], [1, 0]]), "Y": np.array([[0, -1j], [1j, 0]]), "Z": np.array([[1, 0], [0, -1]]), # Phase gates "S": np.array([[1, 0], [0, 1j]]), "T": np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]]) }
https://gallery.fastht.ml/code/visualizations/bloch_sphere
FastHTML page
import numpy as np from fasthtml.common import * import plotly.graph_objects as go from fh_plotly import plotly2fasthtml, plotly_headers ######################## ### FastHTML Section ### ######################## app, rt = fast_app(hdrs=(plotly_headers,)) @rt def index(): desc = """ The Bloch Sphere is a 3D visualization of a single quantum state. You can interact with the buttons (Gates) to see how the state changes. See the description below for more information on what each gate represents. """ hx_vals = 'js:{"gates": document.getElementById("quantum_circuit").textContent}' return (Title("Interactive Bloch Sphere"), Main(P(desc), *[Button(gate, hx_get=f"apply_gate/{gate}", hx_target="#chart", hx_swap="innerHTML", hx_vals=hx_vals, title=f"Apply {gate} gate") for gate in single_qubit_gates.keys()], Button("Reset", hx_get="reset", hx_target="#chart", hx_swap="innerHTML", title="Reset the circuit"), Div(update_state_apply_gate.__wrapped__(), id="chart"), H4("Available gates"), Ul(Li(Strong("H :"),"Hadamard gate. Puts the state in superposition. "), Li(Strong("X :"),"Pauli-X (NOT) gate. Rotate 180 degrees around the X-Axis."), Li(Strong("Y :"),"Pauli-Y (\"bit-flip\") gate. Rotate 180 degrees around the Y-Axis."), Li(Strong("Z :"),"Pauli-Z (\"phase-flip\") gate. Rotate 180 degrees around the Z-Axis."), Li(Strong("S :"),"Phase gate. Rotates around the Z-axis by 90 degrees."), Li(Strong("T :"),"Ο€/8 gate. Rotates around the Z-axis by 45 degrees.")))) @rt def reset(): return update_state_apply_gate.__wrapped__() @app.get('/apply_gate/{gate}') def update_state_apply_gate(gate: str=None, gates: str=None): if gates is None: gates = [] else: # Transform from circuit representation to gate names gates = [g for g in gates if g in single_qubit_gates.keys()] gates.append(gate) # Create initial state state = np.array([1, 0]) # |0> basis state for gate in gates: state = single_qubit_gates[gate] @ state # Create visualization return Div(plot_bloch(state), H4(f"Quantum Circuit: {visualize_circuit(gates)}", id="quantum_circuit"), id="chart") def visualize_circuit(gates: list[str]): circuit = "|0⟩-" circuit += "".join([f"[{gate}]─" for gate in gates]) + "|" return circuit ############################ ### Math/Quantum Section ### ############################ def calculate_coordinates(theta, phi): x = np.sin(theta) * np.cos(phi) y = np.sin(theta) * np.sin(phi) z = np.cos(theta) return x, y, z def create_scenes(): axis2ticktext = {'X': ['|-⟩', '|+⟩'], 'Y': ['|-i⟩', '|i⟩'], 'Z': ['|1⟩', '|0⟩']} scenes = {} for axis in ['X','Y','Z']: scenes[f'{axis.lower()}axis'] = dict(title=dict(text=axis, font=dict(size=25)), range=[-1.2, 1.2], tickvals=[-1, 1], ticktext=axis2ticktext[axis], tickfont=dict(size=15) ) return scenes def plot_bloch(state: np.array): fig = go.Figure() # State vector coordinates alpha, beta = state[0], state[1] theta = 2 * np.arccos(np.abs(alpha)) phi = np.angle(beta) - np.angle(alpha) x, y, z = calculate_coordinates(theta, phi) # Surface coordinates surface_phi, surface_theta = np.mgrid[0:2*np.pi:100j, 0:np.pi:50j] xs, ys, zs = calculate_coordinates(surface_theta, surface_phi) fig.add_trace(go.Surface(x=xs, y=ys, z=zs, opacity=0.5, colorscale='Blues', showscale=False)) fig.add_trace(go.Scatter3d(x=[0, x],y=[0, y],z=[0, z], mode='lines+markers+text', marker=dict(size=10, color='green'), line=dict(color='green', width=8), textposition="top center", showlegend=True,name=f"{alpha:.2f}|0⟩ + {beta:.2f}|1⟩")) # Mark basis states fig.add_trace(go.Scatter3d(x=[0, 0, 1, -1, 0, 0],y=[0, 0, 0, 0, 1, -1], z=[1, -1, 0, 0, 0, 0], mode='markers', marker=dict(size=5, color='black'), hovertext=['|0⟩', '|1⟩', '|+⟩', '|-⟩', '|i⟩', '|-i⟩'], showlegend=False, name="Basis states")) # Add lines across axes boundary_phi = np.linspace(0, 2 * np.pi, 100) coords = [(np.cos(boundary_phi), np.sin(boundary_phi), np.zeros_like(boundary_phi)), (np.zeros_like(boundary_phi), np.cos(boundary_phi), np.sin(boundary_phi)), (np.cos(boundary_phi), np.zeros_like(boundary_phi), np.sin(boundary_phi)) ] for x, y, z in coords: fig.add_trace(go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='black', width=2), showlegend=False, name="Axes")) fig.update_layout(scene=dict(**create_scenes(), aspectmode='cube',), legend=dict( font=dict(size=20), x=0.05,y=0.95, xanchor='left', yanchor='top', bgcolor='rgba(0,0,0,0)',), margin=dict(l=0, r=0, t=0, b=0)) return plotly2fasthtml(fig) single_qubit_gates = { # Hadamard "H": np.array([[1, 1], [1, -1]]) / np.sqrt(2), # Pauli matrices "X": np.array([[0, 1], [1, 0]]), "Y": np.array([[0, -1j], [1j, 0]]), "Z": np.array([[1, 0], [0, -1]]), # Phase gates "S": np.array([[1, 0], [0, 1j]]), "T": np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]]) }
https://gallery.fastht.ml/split/visualizations/bloch_sphere
FastHTML page
from fasthtml.common import * style = Style("""body{ min-height: 100vh; margin:0; background-color: #1A1A1E; display:grid; }""") # custom style to be applied globally. hdrs = (Script(src="https://cdn.tailwindcss.com") , Link(rel="stylesheet", href="/files/examples/applications/tic_tac_toe/output.css")) app, rt = fast_app(hdrs=(hdrs, style), pico=False) current_state_index = -1 #Used to navigate the current snapshot of the board button_states = [[None for _ in range(9)] for _ in range(9)] #2D array to store snapshots of board win_states = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ] #possible win streaks/states for Xs and Os winner_found_game_ended = False def check_win(player) -> bool: global button_states, current_state_index, winner_found_game_ended """Checks if there's a win streak present in the board. Uses the win states list to check If text at all text indices are equal and its not the placeholder text ("."), change the global variable "winner_found_game_ended" to True""" for cell_1, cell_2, cell_3 in win_states: if ( button_states[current_state_index][cell_1] != None and button_states[current_state_index][cell_1] == button_states[current_state_index][cell_2] and button_states[current_state_index][cell_2] == button_states[current_state_index][cell_3]): winner_found_game_ended = True return f"Player {player} wins the game!" if all(value is not None for value in button_states[current_state_index]): #if the current snapshot of the board doesn't have any placeholder text and there is no winning streak winner_found_game_ended = True return "No Winner :(" #will keep returning this value [because its called after every button click], until a winner or none is found return f'''Player {'X' if player == 'O' else 'O'}'s turn!''' def handle_click(index: int): """This function handles what text gets sent to the button's face depending on whose turn it is uses a weird algorithm""" global button_states, current_state_index next_index = current_state_index + 1 button_states[next_index] = button_states[current_state_index][:] #make a copy of the current snapshot to add to the next snapshot if button_states[current_state_index][index] is None: if "X" not in button_states[current_state_index] or button_states[ current_state_index ].count("X") <= button_states[current_state_index].count("O"): button_states[next_index][index] = "X" else: button_states[next_index][index] = "O" current_state_index += 1 return button_states[next_index][index] @app.get("/on_click") # On click, call helper function to alternate between X and O def render_button(index:int): global button_states, current_state_index player = handle_click(index) winner = check_win(player) # function that checks if there's a winner buttons = [Button( f'''{text if text is not None else '.' }''', cls="tic-button-disabled" if (text is not None) or winner_found_game_ended else "tic-button", disabled=True if (text is not None) or winner_found_game_ended else False, hx_get=f"on_click?index={idx}", hx_target=".buttons-div", hx_swap='outerHTML') for idx, text in enumerate(button_states[current_state_index]) ] """rerenders buttons based on the next snapshot. I initially made this to render only the button that gets clicked. But to be able to check the winner and stop the game, I have to use the next snapshot instead if you wanna see the previous implementation, it should be in one of the commits.""" board = Div( Div(winner, cls="justify-self-center"), Div(*buttons, cls="grid grid-cols-3 grid-rows-3"), cls="buttons-div font-bevan text-white font-light grid justify-center") return board # Rerenders the board if the restart button is clicked. # Also responsible for initial rendering of board when webpage is reloaded @app.get("/restart") def render_board(): global button_states, current_state_index, winner_found_game_ended current_state_index = -1 button_states = [[None for _ in range(9)] for _ in range(9)] winner_found_game_ended = False # button component buttons = [ Button( ".", cls="tic-button", hx_get=f"on_click?index={i}", hx_swap="outerHTML", hx_target=".buttons-div") for i, _ in enumerate(button_states[current_state_index]) ] return Div(Div("Player X starts the game",cls="font-bevan text-white justify-self-center"), Div(*buttons, cls="grid grid-cols-3 grid-rows-3"), cls="buttons-div grid") @app.get("/") def homepage(): global button_states return Div( Div( H1("Tic Tac Toe!", cls="font-bevan text-5xl text-white"), P("A FastHTML app by Adedara Adeloro", cls="font-bevan text-custom-blue font-light"), cls="m-14"), Div( render_board.__wrapped__(), # render buttons. Div( Button( "Restart!", disabled=False, cls="restart-button", hx_get="restart", hx_target=".buttons-div", hx_swap="outerHTML"), cls="flex flex-col items-center justify-center m-10"), cls="flex flex-col items-center justify-center"), cls="justify-center items-center min-h-screen bg-custom-background")
https://gallery.fastht.ml/code/applications/tic_tac_toe
FastHTML page
from fasthtml.common import * style = Style("""body{ min-height: 100vh; margin:0; background-color: #1A1A1E; display:grid; }""") # custom style to be applied globally. hdrs = (Script(src="https://cdn.tailwindcss.com") , Link(rel="stylesheet", href="/files/examples/applications/tic_tac_toe/output.css")) app, rt = fast_app(hdrs=(hdrs, style), pico=False) current_state_index = -1 #Used to navigate the current snapshot of the board button_states = [[None for _ in range(9)] for _ in range(9)] #2D array to store snapshots of board win_states = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ] #possible win streaks/states for Xs and Os winner_found_game_ended = False def check_win(player) -> bool: global button_states, current_state_index, winner_found_game_ended """Checks if there's a win streak present in the board. Uses the win states list to check If text at all text indices are equal and its not the placeholder text ("."), change the global variable "winner_found_game_ended" to True""" for cell_1, cell_2, cell_3 in win_states: if ( button_states[current_state_index][cell_1] != None and button_states[current_state_index][cell_1] == button_states[current_state_index][cell_2] and button_states[current_state_index][cell_2] == button_states[current_state_index][cell_3]): winner_found_game_ended = True return f"Player {player} wins the game!" if all(value is not None for value in button_states[current_state_index]): #if the current snapshot of the board doesn't have any placeholder text and there is no winning streak winner_found_game_ended = True return "No Winner :(" #will keep returning this value [because its called after every button click], until a winner or none is found return f'''Player {'X' if player == 'O' else 'O'}'s turn!''' def handle_click(index: int): """This function handles what text gets sent to the button's face depending on whose turn it is uses a weird algorithm""" global button_states, current_state_index next_index = current_state_index + 1 button_states[next_index] = button_states[current_state_index][:] #make a copy of the current snapshot to add to the next snapshot if button_states[current_state_index][index] is None: if "X" not in button_states[current_state_index] or button_states[ current_state_index ].count("X") <= button_states[current_state_index].count("O"): button_states[next_index][index] = "X" else: button_states[next_index][index] = "O" current_state_index += 1 return button_states[next_index][index] @app.get("/on_click") # On click, call helper function to alternate between X and O def render_button(index:int): global button_states, current_state_index player = handle_click(index) winner = check_win(player) # function that checks if there's a winner buttons = [Button( f'''{text if text is not None else '.' }''', cls="tic-button-disabled" if (text is not None) or winner_found_game_ended else "tic-button", disabled=True if (text is not None) or winner_found_game_ended else False, hx_get=f"on_click?index={idx}", hx_target=".buttons-div", hx_swap='outerHTML') for idx, text in enumerate(button_states[current_state_index]) ] """rerenders buttons based on the next snapshot. I initially made this to render only the button that gets clicked. But to be able to check the winner and stop the game, I have to use the next snapshot instead if you wanna see the previous implementation, it should be in one of the commits.""" board = Div( Div(winner, cls="justify-self-center"), Div(*buttons, cls="grid grid-cols-3 grid-rows-3"), cls="buttons-div font-bevan text-white font-light grid justify-center") return board # Rerenders the board if the restart button is clicked. # Also responsible for initial rendering of board when webpage is reloaded @app.get("/restart") def render_board(): global button_states, current_state_index, winner_found_game_ended current_state_index = -1 button_states = [[None for _ in range(9)] for _ in range(9)] winner_found_game_ended = False # button component buttons = [ Button( ".", cls="tic-button", hx_get=f"on_click?index={i}", hx_swap="outerHTML", hx_target=".buttons-div") for i, _ in enumerate(button_states[current_state_index]) ] return Div(Div("Player X starts the game",cls="font-bevan text-white justify-self-center"), Div(*buttons, cls="grid grid-cols-3 grid-rows-3"), cls="buttons-div grid") @app.get("/") def homepage(): global button_states return Div( Div( H1("Tic Tac Toe!", cls="font-bevan text-5xl text-white"), P("A FastHTML app by Adedara Adeloro", cls="font-bevan text-custom-blue font-light"), cls="m-14"), Div( render_board.__wrapped__(), # render buttons. Div( Button( "Restart!", disabled=False, cls="restart-button", hx_get="restart", hx_target=".buttons-div", hx_swap="outerHTML"), cls="flex flex-col items-center justify-center m-10"), cls="flex flex-col items-center justify-center"), cls="justify-center items-center min-h-screen bg-custom-background")
https://gallery.fastht.ml/split/applications/tic_tac_toe
FastHTML page
from fasthtml.common import * from uuid import uuid4 db = database('sqlite.db') hdrs = (Style(''' button,input { margin: 0 1rem; } [role="group"] { border: 1px solid #ccc; } .edited { outline: 2px solid orange; } '''), ) app, rt = fast_app(hdrs=hdrs) @rt async def get_test_file(): import httpx url = "https://raw.githubusercontent.com/AnswerDotAI/FastHTML-Gallery/refs/heads/main/examples/applications/csv_editor/ex_data.csv" response = await httpx.AsyncClient().get(url) return Response(response.text, media_type="text/csv", headers={'Content-Disposition': 'attachment; filename="ex_data.csv"'}) @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Titled("CSV Uploader", A('Download Example CSV', href="get_test_file", download="ex_data.csv"), Group(Input(type="file", name="csv_file", accept=".csv"), Button("Upload", hx_post="upload", hx_target="#results", hx_encoding="multipart/form-data", hx_include='previous input'), A('Download', href='download', type="button")), Div(id="results")) def render_row(row): vals = [Td(Input(value=v, name=k, oninput="this.classList.add('edited')")) for k,v in row.items()] vals.append(Td(Group(Button('delete', hx_delete=remove.to(id=row['id']).lstrip('/')), Button('update', hx_post='update', hx_include="closest tr")))) return Tr(*vals, hx_target='closest tr', hx_swap='outerHTML') @rt def download(sess): tbl = db[sess['id']] csv_data = [",".join(map(str, tbl.columns_dict))] csv_data += [",".join(map(str, row.values())) for row in tbl()] headers = {'Content-Disposition': 'attachment; filename="data.csv"'} return Response("\n".join(csv_data), media_type="text/csv", headers=headers) @rt('/update') def post(d:dict, sess): return render_row(db[sess['id']].update(d)) @app.delete('/remove') def remove(id:int, sess): db[sess['id']].delete(id) @rt("/upload") def post(csv_file: UploadFile, sess): db[sess['id']].drop(ignore=True) if not csv_file.filename.endswith('.csv'): return "Please upload a CSV file" content = b'' for i, line in enumerate(csv_file.file): if i >= 51: break content += line tbl = db.import_file(sess['id'], content, pk='id') header = Tr(*map(Th, tbl.columns_dict)) vals = [render_row(row) for row in tbl()] return (Span('First 50 rows only', style="color: red;") if i>=51 else '', Table(Thead(header), Tbody(*vals))) serve()
https://gallery.fastht.ml/code/applications/csv_editor
FastHTML page
CSV Editor App This project is a web-based CSV editor built using FastHTML, HTMX, and SQLite. Key Technologies and Techniques FastHTML: A Python-based framework for building web applications with a focus on web fundamentals. HTMX: Used to create dynamic server-side content updates that let you interact with the app without page reloads. SQLite: A lightweight, serverless database used to store and manage CSV data. FastSQL: A library that simplifies database operations and integrates well with FastHTML. httpx: An asynchronous HTTP client for Python, used to fetch example CSV data. How It Works Server-Side Logic The app uses FastHTML to define routes and handle CSV operations. Key routes include: GET /: The main page that renders the CSV upload interface. GET /get_test_file: Provides an example CSV file for download. POST /upload: Handles CSV file uploads and displays the data. POST /update: Updates individual CSV rows. DELETE /remove: Deletes specific rows from the CSV data. GET /download: Allows downloading the current CSV data. Data Management CSV data is stored in an SQLite database: A unique table is created for each session, storing the CSV data with an 'id' column as the primary key. Dynamic Content HTMX is used to create a dynamic user interface: hx-post attribute on the upload button triggers a POST request to upload and display CSV data. hx-delete and hx-post attributes on row buttons handle row deletion and updates. hx-target specifies where the response from the server should be inserted. hx-swap determines how the new content should be added or replaced. hx-include is used to include specific form data in requests. Key Features CSV Upload: Users can upload CSV files to view and edit the data. Example CSV: An example CSV file is provided for download. Data Display: Uploaded CSV data is displayed in an editable table format. Row Editing: Each row can be updated or deleted individually. Data Download: The current state of the CSV data can be downloaded at any time. Session Management: Each user session has its own unique data storage. File Size Limit: Only the first 50 rows of a CSV file are processed and displayed. This CSV Editor app demonstrates how FastHTML and HTMX can be combined to create a responsive, server-side web application for data manipulation tasks.
https://gallery.fastht.ml/info/applications/csv_editor
FastHTML page
from fasthtml.common import * from uuid import uuid4 db = database('sqlite.db') hdrs = (Style(''' button,input { margin: 0 1rem; } [role="group"] { border: 1px solid #ccc; } .edited { outline: 2px solid orange; } '''), ) app, rt = fast_app(hdrs=hdrs) @rt async def get_test_file(): import httpx url = "https://raw.githubusercontent.com/AnswerDotAI/FastHTML-Gallery/refs/heads/main/examples/applications/csv_editor/ex_data.csv" response = await httpx.AsyncClient().get(url) return Response(response.text, media_type="text/csv", headers={'Content-Disposition': 'attachment; filename="ex_data.csv"'}) @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Titled("CSV Uploader", A('Download Example CSV', href="get_test_file", download="ex_data.csv"), Group(Input(type="file", name="csv_file", accept=".csv"), Button("Upload", hx_post="upload", hx_target="#results", hx_encoding="multipart/form-data", hx_include='previous input'), A('Download', href='download', type="button")), Div(id="results")) def render_row(row): vals = [Td(Input(value=v, name=k, oninput="this.classList.add('edited')")) for k,v in row.items()] vals.append(Td(Group(Button('delete', hx_delete=remove.to(id=row['id']).lstrip('/')), Button('update', hx_post='update', hx_include="closest tr")))) return Tr(*vals, hx_target='closest tr', hx_swap='outerHTML') @rt def download(sess): tbl = db[sess['id']] csv_data = [",".join(map(str, tbl.columns_dict))] csv_data += [",".join(map(str, row.values())) for row in tbl()] headers = {'Content-Disposition': 'attachment; filename="data.csv"'} return Response("\n".join(csv_data), media_type="text/csv", headers=headers) @rt('/update') def post(d:dict, sess): return render_row(db[sess['id']].update(d)) @app.delete('/remove') def remove(id:int, sess): db[sess['id']].delete(id) @rt("/upload") def post(csv_file: UploadFile, sess): db[sess['id']].drop(ignore=True) if not csv_file.filename.endswith('.csv'): return "Please upload a CSV file" content = b'' for i, line in enumerate(csv_file.file): if i >= 51: break content += line tbl = db.import_file(sess['id'], content, pk='id') header = Tr(*map(Th, tbl.columns_dict)) vals = [render_row(row) for row in tbl()] return (Span('First 50 rows only', style="color: red;") if i>=51 else '', Table(Thead(header), Tbody(*vals))) serve()
https://gallery.fastht.ml/split/applications/csv_editor
FastHTML page
from fasthtml.common import * from starlette.responses import Response from uuid import uuid4 generator = {} bindict = { (1,1,1):0, (1,1,0):1, (1,0,1):2, (1,0,0):3, (0,1,1):4, (0,1,0):5, (0,0,1):6, (0,0,0):7} initial_row = [0]*50 + [1] + [0]*50 color_map = {0:"white", 1:"black"} #################### ### HTML Widgets ### #################### explanation = Div( H1("Cellular Automata"), H4("Input explanations:"), Ul(Li(Strong("Rule: "),"Determines the next state of a cell based on the current state of the cell and its neighbors."), Li(Strong("Generations: "),"Determines how many generations to run the automaton."), Li(Strong("Width: "),"Determines the width of the grid."),)) def progress_bar(percent_complete: float): return Div(hx_swap_oob="innerHTML:#progress_bar")( Progress(value=percent_complete)) def mk_box(color,size=5): return Div(cls="box", style=f"background-color:{color_map[color]};height:{size}px;width:{size}px;margin:0;display:inline-block;") def mk_row(colors,font_size=0,size=5): return Div(*[mk_box(color,size) for color in colors], cls="row",style=f"font-size:{font_size}px;") def mk_button(show): return Button("Hide Rule" if show else "Show Rule", hx_get="show_rule?show=" + ("False" if show else "True"), hx_target="#rule", id="sh_rule", hx_swap_oob="outerHTML", hx_include="[name='rule_number']") ######################## ### FastHTML Section ### ######################## app, rt = fast_app() @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Title("Cellular Automata"),Main(Div( Div(P(explanation,id="explanations")), Form(Group( Div(hx_target='this', hx_swap='outerHTML')(Label(_for="rule_number", cls="form-label")("Rule"), Input(type='number', name="rule_number", id='rule_set', value="30",hx_post='validate/rule_number')), Div(hx_target='this', hx_swap='outerHTML')(Label("Generations", cls="form-label"), Input(type='number',name="generations", id='generations_set', value="50",hx_post='validate/generations', hx_indicator='#generationsind')), Div(hx_target='this', hx_swap='outerHTML')(Label("Width", cls="form-label"), Input(type='number',name="width", id='width_set', value="100", hx_post='validate/width', hx_indicator='#widthind')), Button(cls="btn btn-active btn-primary", type="submit", hx_get="run", hx_target="#grid", hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"))), Group( Div(style="margin-left:50px")( Div(id="progress_bar"), Div(id="grid")), Div(style="margin-right:50px; max-width:200px")( mk_button(False), Div(id="rule"), )))) @rt('/show_rule') def get(rule_number: int, show: bool): rule = [int(x) for x in f'{rule_number:08b}'] return Div( Div(mk_button(show)), Div(*[Group( Div(mk_row(list(k),font_size=10,size=20),style="max-width:100px"), Div(P(" -> "),style="max-width:100px"), Div(mk_box(rule[v],size=20),style="max-width:100px")) for k,v in bindict.items()] if show else '') ) @rt('/run') def get(rule_number: int, generations: int, width: int, sess): errors = {'rule_number': validate_rule_number(rule_number), 'generations': validate_generations(generations), 'width': validate_width(width)} # Removes the None values from the errors dictionary (No errors) errors = {k: v for k, v in errors.items() if v is not None} # Return Button with error message if they exist if errors: return Div(Div(id="grid"), Div(id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"), Div(id='submit-btn-container',hx_swap_oob="outerHTML:#submit-btn-container")( Button(cls="btn btn-active btn-primary", type="submit", hx_get="run", hx_target="#grid", hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"), *[Div(error, style='color: red;') for error in errors.values()])) start = [0]*(width//2) + [1] + [0]*(width//2) global generator generator[sess['id']] = run(rule=rule_number,generations=generations,start=start) return Div( Div(style=f"width: {(width+1)*5}px",id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"), Div(id="next",hx_trigger="every .1s", hx_get="next", hx_target="#grid",hx_swap="beforeend"),id="grid") @rt('/next') def get(sess): global generator g,val = next(generator[sess['id']],(False,False)) if val: return Div( progress_bar(g), mk_row(val)) else: del generator[sess['id']] return Response(status_code=286) @rt('/validate/rule_number') def post(rule_number: int): return inputTemplate('Rule Number', 'rule_number',rule_number, validate_rule_number(rule_number)) @rt('/validate/generations') def post(generations: int): return inputTemplate('Generations', 'generations', generations, validate_generations(generations)) @rt('/validate/width') def post(width: int): return inputTemplate('Width', 'width', width, validate_width(width)) ######################### ### Application Logic ### ######################### def run(rule=30, start = initial_row, generations = 100): rule = [int(x) for x in f'{rule:08b}'] yield 0, start old_row = [0] + start + [0] new_row = [] for g in range(1,generations): for i in range(1,len(old_row)-1): key=tuple(old_row[i-1:i+2]) new_row.append(rule[bindict[key]]) yield (g+1)/generations,new_row old_row = [0] + new_row + [0] new_row = [] ######################## ### Validation Logic ### ######################## def validate_rule_number(rule_number: int): if (rule_number < 0) or (rule_number > 255 ): return "Enter an integer between 0 and 255 (inclusive)" def validate_generations(generations: int): if generations < 0: return "Enter a positive integer" if generations > 200: return "Enter a number less than 200" def validate_width(width: int): if width < 0: return "Enter a positive integer" if width > 200: return "Enter a number less than 200" def inputTemplate(label, name, val, errorMsg=None, input_type='number'): # Generic template for replacing the input field and showing the validation message return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")( Label(label), # Creates label for the input field Input(name=name,type=input_type,value=f'{val}',style="width: 340px;",hx_post=f'validate/{name.lower()}'), # Creates input field Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
https://gallery.fastht.ml/code/applications/cellular_automata
FastHTML page
Cellular Automata Cellular automata are a class of models used to simulate complex systems. They are used in a wide range of applications, including modeling the spread of diseases, traffic flow, and crowd behavior. This project is a one-dimensional cellular automata. Cellular Automata Details We start with an initial row. In this app, the row is a series of white squares followed by a single black square and more white squares. A cell is created based on the state of the three cells above it (directly above and to the left and right). That means there are eight possible combinations of the three cells. We consider a white square to be a 0 and a black square to be a 1. This gives us a number between 0 and 7 (the cell update number). The rule is a number between 0 and 255 (inclusive). We take that number and convert it to its binary representation, which will be a sequence of 8x 0s and 1s. We look at the corresponding digit in the rule by taking the cell update number. If it is a 1, the cell becomes black; if it is a 0, the cell becomes white. The cellular automata is visualized as a grid of white and black boxes, representing the 0 and 1 states, respectively. User Interface The app provides three main inputs: Rule (0-255): Determines the cellular automata rule Generations (1-200): Sets how many rows will be generated Width (1-200): Defines the width of the grid Key Technologies and Techniques HTMX Polling: We use polling to update the grid every 100ms. This is done by setting the hx-trigger attribute every .1s. This triggers a GET request until we run out of generations, and then the Response(status_code=286) stops the polling. See the HTMX documentation for polling Progress Bar: A progress bar that shows the progress of the cellular automata. Check out the FastHTML Gallery page for progress bars! Show Hide Button: A button that shows and hides the rule number. Check out the FastHTML Gallery page for show hide buttons! Inline Input Validation: Real-time validation for rule number, generations, and width inputs. Check out the FastHTML Gallery page for inline validation! Dynamic Grid Generation: The automata grid is generated row by row, creating an animated effect. Server-Side Session State: The state of each in-progress generation is stored on the server by a session ID. Server-Side Logic The app uses FastHTML to define routes and handle the cellular automata logic on the server. Key routes include: /: The main page that renders the initial form and explanation. /run: Initializes and runs the cellular automata based on user input. /next: Generates the next row of the automata. /validate/*: Handles input validation for rule number, generations, and width. /show_rule: Toggles the display of the rule visualization. State Management The automata state is managed server-side using a generator function: generator: A global variable that stores the cellular automata generator for each session. run(): A yields each automata generation. Dynamic Content HTMX is used extensively to create a dynamic user interface:
https://gallery.fastht.ml/info/applications/cellular_automata
FastHTML page
from fasthtml.common import * from starlette.responses import Response from uuid import uuid4 generator = {} bindict = { (1,1,1):0, (1,1,0):1, (1,0,1):2, (1,0,0):3, (0,1,1):4, (0,1,0):5, (0,0,1):6, (0,0,0):7} initial_row = [0]*50 + [1] + [0]*50 color_map = {0:"white", 1:"black"} #################### ### HTML Widgets ### #################### explanation = Div( H1("Cellular Automata"), H4("Input explanations:"), Ul(Li(Strong("Rule: "),"Determines the next state of a cell based on the current state of the cell and its neighbors."), Li(Strong("Generations: "),"Determines how many generations to run the automaton."), Li(Strong("Width: "),"Determines the width of the grid."),)) def progress_bar(percent_complete: float): return Div(hx_swap_oob="innerHTML:#progress_bar")( Progress(value=percent_complete)) def mk_box(color,size=5): return Div(cls="box", style=f"background-color:{color_map[color]};height:{size}px;width:{size}px;margin:0;display:inline-block;") def mk_row(colors,font_size=0,size=5): return Div(*[mk_box(color,size) for color in colors], cls="row",style=f"font-size:{font_size}px;") def mk_button(show): return Button("Hide Rule" if show else "Show Rule", hx_get="show_rule?show=" + ("False" if show else "True"), hx_target="#rule", id="sh_rule", hx_swap_oob="outerHTML", hx_include="[name='rule_number']") ######################## ### FastHTML Section ### ######################## app, rt = fast_app() @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Title("Cellular Automata"),Main(Div( Div(P(explanation,id="explanations")), Form(Group( Div(hx_target='this', hx_swap='outerHTML')(Label(_for="rule_number", cls="form-label")("Rule"), Input(type='number', name="rule_number", id='rule_set', value="30",hx_post='validate/rule_number')), Div(hx_target='this', hx_swap='outerHTML')(Label("Generations", cls="form-label"), Input(type='number',name="generations", id='generations_set', value="50",hx_post='validate/generations', hx_indicator='#generationsind')), Div(hx_target='this', hx_swap='outerHTML')(Label("Width", cls="form-label"), Input(type='number',name="width", id='width_set', value="100", hx_post='validate/width', hx_indicator='#widthind')), Button(cls="btn btn-active btn-primary", type="submit", hx_get="run", hx_target="#grid", hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"))), Group( Div(style="margin-left:50px")( Div(id="progress_bar"), Div(id="grid")), Div(style="margin-right:50px; max-width:200px")( mk_button(False), Div(id="rule"), )))) @rt('/show_rule') def get(rule_number: int, show: bool): rule = [int(x) for x in f'{rule_number:08b}'] return Div( Div(mk_button(show)), Div(*[Group( Div(mk_row(list(k),font_size=10,size=20),style="max-width:100px"), Div(P(" -> "),style="max-width:100px"), Div(mk_box(rule[v],size=20),style="max-width:100px")) for k,v in bindict.items()] if show else '') ) @rt('/run') def get(rule_number: int, generations: int, width: int, sess): errors = {'rule_number': validate_rule_number(rule_number), 'generations': validate_generations(generations), 'width': validate_width(width)} # Removes the None values from the errors dictionary (No errors) errors = {k: v for k, v in errors.items() if v is not None} # Return Button with error message if they exist if errors: return Div(Div(id="grid"), Div(id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"), Div(id='submit-btn-container',hx_swap_oob="outerHTML:#submit-btn-container")( Button(cls="btn btn-active btn-primary", type="submit", hx_get="run", hx_target="#grid", hx_include="[name='rule_number'],[name='generations'],[name='width']", hx_swap="outerHTML")("Run"), *[Div(error, style='color: red;') for error in errors.values()])) start = [0]*(width//2) + [1] + [0]*(width//2) global generator generator[sess['id']] = run(rule=rule_number,generations=generations,start=start) return Div( Div(style=f"width: {(width+1)*5}px",id="progress_bar",hx_swap_oob="outerHTML:#progress_bar"), Div(id="next",hx_trigger="every .1s", hx_get="next", hx_target="#grid",hx_swap="beforeend"),id="grid") @rt('/next') def get(sess): global generator g,val = next(generator[sess['id']],(False,False)) if val: return Div( progress_bar(g), mk_row(val)) else: del generator[sess['id']] return Response(status_code=286) @rt('/validate/rule_number') def post(rule_number: int): return inputTemplate('Rule Number', 'rule_number',rule_number, validate_rule_number(rule_number)) @rt('/validate/generations') def post(generations: int): return inputTemplate('Generations', 'generations', generations, validate_generations(generations)) @rt('/validate/width') def post(width: int): return inputTemplate('Width', 'width', width, validate_width(width)) ######################### ### Application Logic ### ######################### def run(rule=30, start = initial_row, generations = 100): rule = [int(x) for x in f'{rule:08b}'] yield 0, start old_row = [0] + start + [0] new_row = [] for g in range(1,generations): for i in range(1,len(old_row)-1): key=tuple(old_row[i-1:i+2]) new_row.append(rule[bindict[key]]) yield (g+1)/generations,new_row old_row = [0] + new_row + [0] new_row = [] ######################## ### Validation Logic ### ######################## def validate_rule_number(rule_number: int): if (rule_number < 0) or (rule_number > 255 ): return "Enter an integer between 0 and 255 (inclusive)" def validate_generations(generations: int): if generations < 0: return "Enter a positive integer" if generations > 200: return "Enter a number less than 200" def validate_width(width: int): if width < 0: return "Enter a positive integer" if width > 200: return "Enter a number less than 200" def inputTemplate(label, name, val, errorMsg=None, input_type='number'): # Generic template for replacing the input field and showing the validation message return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")( Label(label), # Creates label for the input field Input(name=name,type=input_type,value=f'{val}',style="width: 340px;",hx_post=f'validate/{name.lower()}'), # Creates input field Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
https://gallery.fastht.ml/split/applications/cellular_automata
FastHTML page
Text Annotation Web App This project is a web-based tool for annotating LLM-generated text, built using FastHTML, HTMX, and Tailwind CSS, originally built by Alex Volkov in the fasthtml-examples repo Key Technologies and Techniques FastHTML: A Python-based framework for building web applications with a focus on web fundamentals. HTMX: Used to create dynamic server-side content updates that allow interaction with the app without page reloads. Tailwind CSS: Tailwind classes are used throughout the HTML to style the app, providing a clean and responsive design. DaisyUI: A Tailwind CSS component library used for additional styling. How It Works Server-Side Logic The app uses FastHTML to define routes and handle annotation logic on the server. Key routes include: /: The main page that renders the initial annotation interface. /{idx}: Handles both GET and POST requests for specific annotation items. State Management The app state is managed server-side using a SQLite database: texts_db: Stores annotation items, including messages, feedback, and notes. total_items_length: Tracks the total number of items in the database. Dynamic Content HTMX is used extensively to create a dynamic user interface: hx-post attributes on forms trigger POST requests to update annotations. hx-get attributes on navigation buttons load new items. hx-swap determines how the new content should replace the old content, using outerHTML to replace entire elements. Key Components Arrow Navigation: Allows users to move between annotation items. Annotation Buttons: Provides options to mark text as correct or incorrect. Notes Field: Allows users to add additional notes to each annotation. Text Display: Shows the LLM-generated text to be annotated. SQLite database integration This app demonstrates the power of combining FastHTML, HTMX, and Tailwind CSS to create a responsive and efficient web application for text annotation tasks.
https://gallery.fastht.ml/info/applications/annotate_text
FastHTML page
Observable Plot Demo The data is randomly generated on the server and is fetched on initial page load. Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request.
https://gallery.fastht.ml/app/visualizations/observable_plot/
FastHTML page
Move the slider to change the graph
https://gallery.fastht.ml/app/visualizations/matplotlib_charts/
FastHTML page
Plotly Interactive Charts Demo with FastHTML Try interacting with the charts by hovering over data points, zooming in and out, panning, rotating (3D), and more!.
https://gallery.fastht.ml/app/visualizations/plotly_charts/
FastHTML page
The Bloch Sphere is a 3D visualization of a single quantum state. You can interact with the buttons (Gates) to see how the state changes. See the description below for more information on what each gate represents. Available gates
https://gallery.fastht.ml/app/visualizations/bloch_sphere/
Interactive Bloch Sphere
from fasthtml.common import * import json import httpx # Set up the app, including daisyui and tailwind for the chat component tlink = Script(src="https://cdn.tailwindcss.com?plugins=typography"), dlink = Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/full.min.css") def Arrow(arrow, hx_get, id): # Grey out button if you're at the end if arrow == "←": ptr_evnts = "pointer-events-none opacity-50" if id == 1 else "" elif arrow == "β†’": ptr_evnts = " pointer-events-none opacity-50" if id == total_items_length - 1 else "" # CSS Styling for both arrow buttons common_classes = "relative inline-flex items-center bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" return A(Span(arrow, cls="sr-only"), Span(arrow, cls="h-5 w-5", aria_hidden="true"), hx_get=hx_get, hx_swap="outerHTML", cls=f" {'' if arrow=='←' else '-ml-px'} rounded-{'l' if arrow=='←' else 'r'}-md {common_classes} {ptr_evnts}") def AnnotateButton(value, feedback): # Different button styling if it's already marked as correct/incorrect classes = '' if feedback=='correct' else 'btn-outline' # Green for correct red for incorrect classes += f" btn-{'success' if value=='correct' else 'error'}" classes += ' mr-2' if value=='correct' else '' return Button(value.capitalize(), name='feedback', value=value, cls='btn hover:text-white '+classes) def render(Item): messages = json.loads(Item.messages) card_header = Div(cls="border-b border-gray-200 bg-white p-4")( Div(cls="flex justify-between items-center mb-4")( H3(f"Sample {Item.id} out of {total_items_length}" if total_items_length else "No samples in DB", cls="text-base font-semibold leading-6 text-gray-9000"), Div(cls="flex-shrink-0")( Arrow("←", f"{Item.id - 2}" if Item.id > 0 else "#", Item.id), Arrow("β†’", f"{Item.id}" if Item.id < total_items_length - 1 else "#", Item.id))), Div(cls="-ml-4 -mt-4 flex flex-wrap items-center justify-between sm:flex-nowrap")( Div(cls="ml-4 mt-4")( P(messages[0]['content'], cls="mt-1 text-sm text-gray-500 max-h-16 overflow-y-auto whitespace-pre-wrap")))) card_buttons_form = Div(cls="mt-4")( Form(cls="flex items-center", method="post", hx_post=f"{Item.id}", target_id=f"item_{Item.id}", hx_swap="outerHTML", hx_encoding="multipart/form-data")( Input(type="text", name="notes", value=Item.notes, placeholder="Additional notes?", cls="flex-grow p-2 my-4 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-transparent"), Div(cls="flex-shrink-0 ml-4")( AnnotateButton('correct', Item.feedback), AnnotateButton('incorrect', Item.feedback)))) # Card component card = Div(cls=" flex flex-col h-full flex-grow overflow-auto", id=f"item_{Item.id}", style="min-height: calc(100vh - 6rem); max-height: calc(100vh - 16rem);")( card_header, Div(cls="bg-white shadow rounded-b-lg p-4 pt-0 pb-10 flex-grow overflow-scroll")( Div(messages[1]['content'], id="main_text", cls="mt-2 w-full rounded-t-lg text-sm whitespace-pre-wrap h-auto marked")), card_buttons_form) return card hdrs=(tlink, dlink, picolink, MarkdownJS(), HighlightJS()) app, rt, texts_db, Item = fast_app('texts.db',hdrs=hdrs, render=render, bodykw={"data-theme":"light"}, id=int, messages=list, feedback=bool, notes=str, pk='id') # Get Dummy Data data_url = 'https://raw.githubusercontent.com/AnswerDotAI/fasthtml-example/main/annotate_text/data/dummy_data.jsonl' response = httpx.get(data_url) # Insert Dummy Data into Db for line in response.text.splitlines(): item = json.loads(line) texts_db.insert(messages=json.dumps(item), feedback=None, notes='') # Set total_items_length after inserting dummy data total_items_length = len(texts_db()) print(f"Inserted {total_items_length} items from dummy data") @rt("/{idx}") def post(idx: int, feedback: str = None, notes: str = None): print(f"Posting feedback: {feedback} and notes: {notes} for item {idx}") items = texts_db() item = texts_db.get(idx) item.feedback, item.notes = feedback, notes texts_db.update(item) next_item = next((i for i in items if i.id > item.id), items[0]) print(f"Updated item {item.id} with feedback: {feedback} and notes: {notes} moving to {next_item.id}") return next_item @rt("/") @rt("/{idx}") def get(idx:int = 0): items = texts_db() index = idx if index >= len(items): index = len(items) - 1 if items else 0 # Container for card and buttons content = Div(cls="w-full max-w-2xl mx-auto flex flex-col max-h-full")( H1('LLM generated text annotation tool with FastHTML (and Tailwind)',cls="text-xl font-bold text-center text-gray-800 mb-8"), items[index]) return Main(content, cls="container mx-auto min-h-screen bg-gray-100 p-8 flex flex-col", hx_target="this")
https://gallery.fastht.ml/code/applications/annotate_text
FastHTML page
from fasthtml.common import * import json import httpx # Set up the app, including daisyui and tailwind for the chat component tlink = Script(src="https://cdn.tailwindcss.com?plugins=typography"), dlink = Link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/[email protected]/dist/full.min.css") def Arrow(arrow, hx_get, id): # Grey out button if you're at the end if arrow == "←": ptr_evnts = "pointer-events-none opacity-50" if id == 1 else "" elif arrow == "β†’": ptr_evnts = " pointer-events-none opacity-50" if id == total_items_length - 1 else "" # CSS Styling for both arrow buttons common_classes = "relative inline-flex items-center bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" return A(Span(arrow, cls="sr-only"), Span(arrow, cls="h-5 w-5", aria_hidden="true"), hx_get=hx_get, hx_swap="outerHTML", cls=f" {'' if arrow=='←' else '-ml-px'} rounded-{'l' if arrow=='←' else 'r'}-md {common_classes} {ptr_evnts}") def AnnotateButton(value, feedback): # Different button styling if it's already marked as correct/incorrect classes = '' if feedback=='correct' else 'btn-outline' # Green for correct red for incorrect classes += f" btn-{'success' if value=='correct' else 'error'}" classes += ' mr-2' if value=='correct' else '' return Button(value.capitalize(), name='feedback', value=value, cls='btn hover:text-white '+classes) def render(Item): messages = json.loads(Item.messages) card_header = Div(cls="border-b border-gray-200 bg-white p-4")( Div(cls="flex justify-between items-center mb-4")( H3(f"Sample {Item.id} out of {total_items_length}" if total_items_length else "No samples in DB", cls="text-base font-semibold leading-6 text-gray-9000"), Div(cls="flex-shrink-0")( Arrow("←", f"{Item.id - 2}" if Item.id > 0 else "#", Item.id), Arrow("β†’", f"{Item.id}" if Item.id < total_items_length - 1 else "#", Item.id))), Div(cls="-ml-4 -mt-4 flex flex-wrap items-center justify-between sm:flex-nowrap")( Div(cls="ml-4 mt-4")( P(messages[0]['content'], cls="mt-1 text-sm text-gray-500 max-h-16 overflow-y-auto whitespace-pre-wrap")))) card_buttons_form = Div(cls="mt-4")( Form(cls="flex items-center", method="post", hx_post=f"{Item.id}", target_id=f"item_{Item.id}", hx_swap="outerHTML", hx_encoding="multipart/form-data")( Input(type="text", name="notes", value=Item.notes, placeholder="Additional notes?", cls="flex-grow p-2 my-4 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-transparent"), Div(cls="flex-shrink-0 ml-4")( AnnotateButton('correct', Item.feedback), AnnotateButton('incorrect', Item.feedback)))) # Card component card = Div(cls=" flex flex-col h-full flex-grow overflow-auto", id=f"item_{Item.id}", style="min-height: calc(100vh - 6rem); max-height: calc(100vh - 16rem);")( card_header, Div(cls="bg-white shadow rounded-b-lg p-4 pt-0 pb-10 flex-grow overflow-scroll")( Div(messages[1]['content'], id="main_text", cls="mt-2 w-full rounded-t-lg text-sm whitespace-pre-wrap h-auto marked")), card_buttons_form) return card hdrs=(tlink, dlink, picolink, MarkdownJS(), HighlightJS()) app, rt, texts_db, Item = fast_app('texts.db',hdrs=hdrs, render=render, bodykw={"data-theme":"light"}, id=int, messages=list, feedback=bool, notes=str, pk='id') # Get Dummy Data data_url = 'https://raw.githubusercontent.com/AnswerDotAI/fasthtml-example/main/annotate_text/data/dummy_data.jsonl' response = httpx.get(data_url) # Insert Dummy Data into Db for line in response.text.splitlines(): item = json.loads(line) texts_db.insert(messages=json.dumps(item), feedback=None, notes='') # Set total_items_length after inserting dummy data total_items_length = len(texts_db()) print(f"Inserted {total_items_length} items from dummy data") @rt("/{idx}") def post(idx: int, feedback: str = None, notes: str = None): print(f"Posting feedback: {feedback} and notes: {notes} for item {idx}") items = texts_db() item = texts_db.get(idx) item.feedback, item.notes = feedback, notes texts_db.update(item) next_item = next((i for i in items if i.id > item.id), items[0]) print(f"Updated item {item.id} with feedback: {feedback} and notes: {notes} moving to {next_item.id}") return next_item @rt("/") @rt("/{idx}") def get(idx:int = 0): items = texts_db() index = idx if index >= len(items): index = len(items) - 1 if items else 0 # Container for card and buttons content = Div(cls="w-full max-w-2xl mx-auto flex flex-col max-h-full")( H1('LLM generated text annotation tool with FastHTML (and Tailwind)',cls="text-xl font-bold text-center text-gray-800 mb-8"), items[index]) return Main(content, cls="container mx-auto min-h-screen bg-gray-100 p-8 flex flex-col", hx_target="this")
https://gallery.fastht.ml/split/applications/annotate_text
FastHTML page
from fasthtml.common import * from datetime import date,datetime from monsterui.all import * # fast_app is doing a lot of work here. # It creates a table in the database if it doesn't exist with columns id and title making id the primary key # it returns a connector object todos # it returns a model class Todo app, rt, todos, Todo= fast_app('intermediate_todo.db',hdrs=Theme.slate.headers(), title=str,done=bool,due=date, id=int,pk='id') def tid(id): return f'todo-{id}' # Render all the todos ordered by todo due date def mk_todo_list(): return Grid(*todos(order_by='due'), cols=1) @app.delete async def delete_todo(id:int): "Delete if it exists, if not someone else already deleted it so no action needed" try: todos.delete(id) except NotFoundError: pass # Because there is no return, the todo will be swapped with None and removed from UI # patch is a decorator that patches the __ft__ method of the Todo class # this is used to customize the html representation of the Todo object @patch def __ft__(self:Todo): # Set color to red if the due date is passed dd = datetime.strptime(self.due, '%Y-%m-%d').date() due_date = Strong(dd.strftime('%Y-%m-%d'),style= "" if date.today() <= dd else "background-color: red;") # Action Buttons _targets = {'hx_target':f'#{tid(self.id)}', 'hx_swap':'outerHTML'} done = CheckboxX( hx_get =toggle_done.to(id=self.id).lstrip('/'), **_targets, checked=self.done), delete = Button('delete', hx_delete=delete_todo.to(id=self.id).lstrip('/'), **_targets) edit = Button('edit', hx_get =edit_todo .to(id=self.id).lstrip('/'), **_targets) # Strike through todo if it is completed style = Del if self.done else noop return Card(DivLAligned(done, style(Strong(self.title, target_id='current-todo')), style(P(due_date,cls=TextPresets.muted_sm)), edit, delete), id=tid(self.id)) @rt async def index(): "Main page of the app" return Titled('Todo List',mk_todo_form(),Div(mk_todo_list(),id='todo-list')) @rt async def upsert_todo(todo:Todo): # Create/update a todo if there is content if todo.title.strip(): todos.insert(todo,replace=True) # Reload main page with updated database content return mk_todo_list(),mk_todo_form()(hx_swap_oob='true',hx_target='#todo-input',hx_swap='outerHTML') @rt async def toggle_done(id:int): "Reverses done boolean in the database and returns the todo (rendered with __ft__)" return todos.update(Todo(id=id, done=not todos[id].done)) def mk_todo_form(todo=Todo(title=None, done=False, due=date.today(), id=None), btn_text="Add"): """Create a form for todo creation/editing with optional pre-filled values""" inputs = [Input(id='new-title', name='title',value=todo.title, placeholder='New Todo'), Input(id='new-done', name='done', value=todo.done, hidden=True), Input(id='new-due', name='due', value=todo.due)] # If there is an ID use it for editing existing row in db if todo.id: inputs.append(Input(id='new-id', name='id', value=todo.id, hidden=True)) return Form(DivLAligned( *inputs, Button(btn_text, cls=ButtonT.primary, post=upsert_todo,hx_target='#todo-list', hx_swap='innerHTML')), id='todo-input', cls='mb-6') @rt async def edit_todo(id:int): return Card(mk_todo_form(todos.get(id), btn_text="Save")) serve()
https://gallery.fastht.ml/code/todo_series/intermediate
FastHTML page
from fasthtml.common import * from datetime import date,datetime from monsterui.all import * # fast_app is doing a lot of work here. # It creates a table in the database if it doesn't exist with columns id and title making id the primary key # it returns a connector object todos # it returns a model class Todo app, rt, todos, Todo= fast_app('intermediate_todo.db',hdrs=Theme.slate.headers(), title=str,done=bool,due=date, id=int,pk='id') def tid(id): return f'todo-{id}' # Render all the todos ordered by todo due date def mk_todo_list(): return Grid(*todos(order_by='due'), cols=1) @app.delete async def delete_todo(id:int): "Delete if it exists, if not someone else already deleted it so no action needed" try: todos.delete(id) except NotFoundError: pass # Because there is no return, the todo will be swapped with None and removed from UI # patch is a decorator that patches the __ft__ method of the Todo class # this is used to customize the html representation of the Todo object @patch def __ft__(self:Todo): # Set color to red if the due date is passed dd = datetime.strptime(self.due, '%Y-%m-%d').date() due_date = Strong(dd.strftime('%Y-%m-%d'),style= "" if date.today() <= dd else "background-color: red;") # Action Buttons _targets = {'hx_target':f'#{tid(self.id)}', 'hx_swap':'outerHTML'} done = CheckboxX( hx_get =toggle_done.to(id=self.id).lstrip('/'), **_targets, checked=self.done), delete = Button('delete', hx_delete=delete_todo.to(id=self.id).lstrip('/'), **_targets) edit = Button('edit', hx_get =edit_todo .to(id=self.id).lstrip('/'), **_targets) # Strike through todo if it is completed style = Del if self.done else noop return Card(DivLAligned(done, style(Strong(self.title, target_id='current-todo')), style(P(due_date,cls=TextPresets.muted_sm)), edit, delete), id=tid(self.id)) @rt async def index(): "Main page of the app" return Titled('Todo List',mk_todo_form(),Div(mk_todo_list(),id='todo-list')) @rt async def upsert_todo(todo:Todo): # Create/update a todo if there is content if todo.title.strip(): todos.insert(todo,replace=True) # Reload main page with updated database content return mk_todo_list(),mk_todo_form()(hx_swap_oob='true',hx_target='#todo-input',hx_swap='outerHTML') @rt async def toggle_done(id:int): "Reverses done boolean in the database and returns the todo (rendered with __ft__)" return todos.update(Todo(id=id, done=not todos[id].done)) def mk_todo_form(todo=Todo(title=None, done=False, due=date.today(), id=None), btn_text="Add"): """Create a form for todo creation/editing with optional pre-filled values""" inputs = [Input(id='new-title', name='title',value=todo.title, placeholder='New Todo'), Input(id='new-done', name='done', value=todo.done, hidden=True), Input(id='new-due', name='due', value=todo.due)] # If there is an ID use it for editing existing row in db if todo.id: inputs.append(Input(id='new-id', name='id', value=todo.id, hidden=True)) return Form(DivLAligned( *inputs, Button(btn_text, cls=ButtonT.primary, post=upsert_todo,hx_target='#todo-list', hx_swap='innerHTML')), id='todo-input', cls='mb-6') @rt async def edit_todo(id:int): return Card(mk_todo_form(todos.get(id), btn_text="Save")) serve()
https://gallery.fastht.ml/split/todo_series/intermediate
FastHTML page
Intermediate Todo App (SQLite) This project is a web-based implementation of an intermediate todo app built using FastHTML, HTMX, and SQLite. This builds on the minimal todo app by adding a due date and a done field to todos. Functionality related to these new fields has been added to the app. Key Technologies and Techniques FastHTML: A Python-based framework for building web applications with a focus on web fundamentals. HTMX: Used to create dynamic server-side content updates that let you interact with the app without page reloads. SQLite: A lightweight, serverless database used to store and manage todo items. FastSQL: A library that simplifies database operations and integrates well with FastHTML. MonsterUI: A library that creates modern UI components for FastHTML How It Works Server-Side Logic The app uses FastHTML to define routes and handle todo list operations. Key routes include: GET /: The main page that renders the initial todo list. POST /: Handles adding new todo items. DELETE /{id}: Handles deleting todo items. Data Management Todo items are stored in an SQLite database: todos: A table storing todo items with id, title, done, and duefields. Dynamic Content HTMX is used to create a dynamic user interface: hx-post attribute on the form triggers a POST request to add new todos. hx-delete attribute on delete links triggers DELETE requests to remove todos. hx-target specifies where the response from the server should be inserted. hx-swap determines how the new content should be added or replaced. beforeend: Adds the new content at the end of the target element. This is used to add the new list item to end of the todo list. outerHTML: Replaces the entire target element with the new content. This is used to replaces the todo list item completely with None to remove it from the list. Key Features Add Todo: Users can add new todos using a form at the top of the list. Delete Todo: Each todo item has a delete link to remove it from the list. Real-time Updates: The list updates dynamically without full page reloads. Persistent Storage: Todos are stored in an SQLite database for data persistence. Due Date: Each todo item has a due date field and the list is sorted by due date. If the item is past due the date is displayed in red. Done: Each todo item has a done field. Items can be marked as done and the list shows completed items crossed out. MonsterUI: Simple styling is done using the MonsterUI library. Edit Todo: Each todo item has an edit link to edit the item. The edit form is displayed in a card and the todo list is updated with the new values.
https://gallery.fastht.ml/info/todo_series/intermediate
FastHTML page
Minimal Todo App (SQLite) This project is a web-based implementation of a minimal todo app built using FastHTML, HTMX, and SQLite. Key Technologies and Techniques FastHTML: A Python-based framework for building web applications with a focus on web fundamentals. HTMX: Used to create dynamic server-side content updates that let you interact with the app without page reloads. SQLite: A lightweight, serverless database used to store and manage todo items. FastSQL: A library that simplifies database operations and integrates well with FastHTML. How It Works Server-Side Logic The app uses FastHTML to define routes and handle todo list operations. Key routes include: GET /: The main page that renders the initial todo list. POST /: Handles adding new todo items. DELETE /{id}: Handles deleting todo items. Data Management Todo items are stored in an SQLite database: todos: A table storing todo items with id and title fields. Dynamic Content HTMX is used to create a dynamic user interface: hx-post attribute on the form triggers a POST request to add new todos. hx-delete attribute on delete links triggers DELETE requests to remove todos. hx-target specifies where the response from the server should be inserted. hx-swap determines how the new content should be added or replaced. beforeend: Adds the new content at the end of the target element. This is used to add the new list item to end of the todo list. outerHTML: Replaces the entire target element with the new content. This is used to replaces the todo list item completely with None to remove it from the list. Key Features Add Todo: Users can add new todos using a form at the top of the list. Delete Todo: Each todo item has a delete link to remove it from the list. Real-time Updates: The list updates dynamically without full page reloads. Persistent Storage: Todos are stored in an SQLite database for data persistence.
https://gallery.fastht.ml/info/todo_series/beginner
FastHTML page
from fasthtml.common import * from fasthtml.svg import * app, rt = fast_app() def mk_shape(shape): if shape == "circle": return Circle(cx=15, cy=15, r=10, fill="red")(hx_get="mk/rect",hx_swap="outerHTML") elif shape == "rect": return Rect(x=10, y=10, width=10, height=10, fill="blue")(hx_get="mk/circle",hx_swap="outerHTML") @rt def index(): return Div( P("Click the object to swap it with another shape"), Svg(viewBox="0 0 150 100")( mk_shape("rect"))) @rt("/mk/{shape}") def get(shape: str): return SvgInb(mk_shape(shape),) serve()
https://gallery.fastht.ml/code/svg/inb_replacement
FastHTML page
from fasthtml.common import * from fastsql import * from apswutils.db import NotFoundError app,rt,todos,Todo = fast_app( 'data/todos.db', id=int, title=str, pk='id') def tid(id): return f'todo-{id}' @app.delete("/delete_todo", name='delete_todo') async def delete_todo(id:int): try: todos.delete(id) except NotFoundError: pass # If someone else deleted it already we don't have to do anything @patch def __ft__(self:Todo): show = Strong(self.title, target_id='current-todo') delete = A('delete', hx_delete=delete_todo.to(id=self.id).lstrip('/'), hx_target=f'#{tid(self.id)}', hx_swap='outerHTML') return Li(show, ' | ', delete, id=tid(self.id)) def mk_input(**kw): return Input( id="new-title", name="title", placeholder="New Todo",required=True,**kw ) @rt async def index(): add = Form(Group(mk_input(), Button("Add")), post="insert_todo", target_id='todo-list', hx_swap="beforeend") card = Card(Ul(*todos(), id='todo-list'), header=add, footer=Div(id='current-todo')), title = 'Todo list' return Title(title), Main(H1(title), card, cls='container') @rt async def insert_todo(todo:Todo): if not todo.title.strip(): return mk_input(hx_swap_oob='true') return todos.insert(todo), mk_input( hx_swap_oob='true') serve()
https://gallery.fastht.ml/code/todo_series/beginner
FastHTML page
from fasthtml.common import * from fastsql import * from apswutils.db import NotFoundError app,rt,todos,Todo = fast_app( 'data/todos.db', id=int, title=str, pk='id') def tid(id): return f'todo-{id}' @app.delete("/delete_todo", name='delete_todo') async def delete_todo(id:int): try: todos.delete(id) except NotFoundError: pass # If someone else deleted it already we don't have to do anything @patch def __ft__(self:Todo): show = Strong(self.title, target_id='current-todo') delete = A('delete', hx_delete=delete_todo.to(id=self.id).lstrip('/'), hx_target=f'#{tid(self.id)}', hx_swap='outerHTML') return Li(show, ' | ', delete, id=tid(self.id)) def mk_input(**kw): return Input( id="new-title", name="title", placeholder="New Todo",required=True,**kw ) @rt async def index(): add = Form(Group(mk_input(), Button("Add")), post="insert_todo", target_id='todo-list', hx_swap="beforeend") card = Card(Ul(*todos(), id='todo-list'), header=add, footer=Div(id='current-todo')), title = 'Todo list' return Title(title), Main(H1(title), card, cls='container') @rt async def insert_todo(todo:Todo): if not todo.title.strip(): return mk_input(hx_swap_oob='true') return todos.insert(todo), mk_input( hx_swap_oob='true') serve()
https://gallery.fastht.ml/split/todo_series/beginner
FastHTML page
Yes, Zig can compile and link to C++ code, allowing you to leverage existing C++ libraries or integrate C++ code within your Zig projects. Here’s how you can do that: ### 1. Using Zig to Call C++ Code To call C++ code from Zig, you typically need to follow these steps: #### Step 1: Create C++ Code You can create a simple C++ file, for example, `hello.cpp`: ```cpp // hello.cpp #include <iostream> extern "C" { void say_hello() { std::cout << "Hello from C++!" << std::endl; } } ``` - The `extern "C"` is used to prevent name mangling, allowing Zig to link correctly to C++ functions. #### Step 2: Create a Zig File Next, create a Zig file, for example, `main.zig`: ```zig const std = @import("std"); extern "C" { fn say_hello(); } pub fn main() !void { say_hello(); } ``` #### Step 3: Compile and Link You will need to compile both the C++ and Zig files together. The simplest way to do this is by using the Zig build system or directly using command-line tools. ##### Using Command Line You can compile and link them using the following commands: ```bash # Compile the C++ code to an object file g++ -c hello.cpp -o hello.o # Compile the Zig code and link with the C++ object file zig build-exe main.zig hello.o --link-lib c++ ``` - **Note**: The `--link-lib c++` flag tells Zig to link against the C++ standard library. ### 2. Using Zig Build System You can also use the Zig build system to simplify the process. Create a `build.zig` file: ```zig const Builder = @import("std").build; pub fn build(b: *Builder.Build) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("main", "main.zig"); exe.linkLibC(); exe.linkLibCxx(); // Link against C++ standard library exe.addObjectFile("hello.o"); // Add the C++ object file b.default_step.dependOn(&exe.step); } ``` ### 3. Build the Project To build your project, run: ```bash zig build ``` This command uses the `build.zig` file to compile the Zig and C++ code together, generating the executable. ### 4. Running the Executable After building, you can run the executable: ```bash ./zig-out/bin/main ``` You should see: ``` Hello from C++! ``` ### Important Notes - **C++ ABI Compatibility**: When linking C++ code with Zig, ensure that you are aware of the C++ ABI (Application Binary Interface) compatibility, especially if you are using C++ libraries. - **Linking C++ Libraries**: If you are linking against precompiled C++ libraries, you can specify them using `exe.linkLib(...)` in the `build.zig` file. - **Compiler Settings**: You may need to adjust compiler settings based on your development environment, including paths to headers or libraries. ### Conclusion Zig can effectively compile and link C++ code, allowing you to take advantage of both languages in your projects. By using the Zig build system or command-line tools, you can manage the integration smoothly.
https://gallery.fastht.ml/app/applications/annotate_text/
FastHTML page
from fasthtml.common import * from fasthtml.svg import * app, rt = fast_app() def mk_shape(shape): if shape == "circle": return Circle(cx=15, cy=15, r=10, fill="red")(hx_get="mk/rect",hx_swap="outerHTML") elif shape == "rect": return Rect(x=10, y=10, width=10, height=10, fill="blue")(hx_get="mk/circle",hx_swap="outerHTML") @rt def index(): return Div( P("Click the object to swap it with another shape"), Svg(viewBox="0 0 150 100")( mk_shape("rect"))) @rt("/mk/{shape}") def get(shape: str): return SvgInb(mk_shape(shape),) serve()
https://gallery.fastht.ml/split/svg/inb_replacement
FastHTML page
from fasthtml.common import * from fasthtml.svg import * from random import randint from uuid import uuid4 import time timer = {} app, rt = fast_app(hdrs=[Script(src="https://d3js.org/d3.v7.min.js")]) class Timer: def __init__(self): self.start = time.time() def stop(self): self.stop = time.time() return self.stop - self.start def mk_circle(count): return Circle(cx=randint(20,180),cy=randint(10,70),r=randint(5,15),fill="red", id="circle",hx_get=f"click/{count+1}", hx_swap="outerHTML") def mk_click_count(count): return P(f"You have clicked {count} times",id="click-count") @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Div( P("Click the circle 3 times"), mk_click_count(0),P(id="timer"), Svg(viewBox="0 0 200 80",id="svg-box")(mk_circle(0))) @rt("/click/{count}") def click(count: int,sess): et = "" if count == 1: timer[sess['id']] = Timer() if count == 3: elapsed_time=timer[sess['id']].stop() count = 0 et=f"Time to click 3 times: {elapsed_time:.2f} seconds" return SvgInb(mk_circle(count)),mk_click_count(count)(hx_swap_oob="outerHTML"),P(et,id="timer",hx_swap_oob="outerHTML") serve()
https://gallery.fastht.ml/code/svg/find_and_click
FastHTML page
from fasthtml.common import * from fasthtml.svg import * from random import randint from uuid import uuid4 import time timer = {} app, rt = fast_app(hdrs=[Script(src="https://d3js.org/d3.v7.min.js")]) class Timer: def __init__(self): self.start = time.time() def stop(self): self.stop = time.time() return self.stop - self.start def mk_circle(count): return Circle(cx=randint(20,180),cy=randint(10,70),r=randint(5,15),fill="red", id="circle",hx_get=f"click/{count+1}", hx_swap="outerHTML") def mk_click_count(count): return P(f"You have clicked {count} times",id="click-count") @rt def index(sess): if 'id' not in sess: sess['id'] = str(uuid4()) return Div( P("Click the circle 3 times"), mk_click_count(0),P(id="timer"), Svg(viewBox="0 0 200 80",id="svg-box")(mk_circle(0))) @rt("/click/{count}") def click(count: int,sess): et = "" if count == 1: timer[sess['id']] = Timer() if count == 3: elapsed_time=timer[sess['id']].stop() count = 0 et=f"Time to click 3 times: {elapsed_time:.2f} seconds" return SvgInb(mk_circle(count)),mk_click_count(count)(hx_swap_oob="outerHTML"),P(et,id="timer",hx_swap_oob="outerHTML") serve()
https://gallery.fastht.ml/split/svg/find_and_click
FastHTML page
from fasthtml.common import * from fasthtml.svg import * app, rt = fast_app(hdrs=[Script(src="https://d3js.org/d3.v7.min.js")]) @rt def index(): return Div( P("Click and drag an SVG rectangle with D3"), Svg(viewBox="0 0 200 200",id="svg-box")( Rect(x=5,y=5,width=10,height=10,fill="red",id="rect")), Script(''' window.onload = function() { var svg = d3.select("svg"); var dragHandler = d3.drag() .on("start", function (e) { var current = d3.select(this); deltaX = current.attr("x") - e.x; deltaY = current.attr("y") - e.y;}) .on("drag", function (e) { d3.select(this) .attr("x", e.x+deltaX) .attr("y", e.y+deltaY);}); svg.select("#rect").call(dragHandler);} ''')) serve()
https://gallery.fastht.ml/code/svg/click_and_drag
FastHTML page
from fasthtml.common import * from fasthtml.svg import * app, rt = fast_app(hdrs=[Script(src="https://d3js.org/d3.v7.min.js")]) @rt def index(): return Div( P("Click and drag an SVG rectangle with D3"), Svg(viewBox="0 0 200 200",id="svg-box")( Rect(x=5,y=5,width=10,height=10,fill="red",id="rect")), Script(''' window.onload = function() { var svg = d3.select("svg"); var dragHandler = d3.drag() .on("start", function (e) { var current = d3.select(this); deltaX = current.attr("x") - e.x; deltaY = current.attr("y") - e.y;}) .on("drag", function (e) { d3.select(this) .attr("x", e.x+deltaX) .attr("y", e.y+deltaY);}); svg.select("#rect").call(dragHandler);} ''')) serve()
https://gallery.fastht.ml/split/svg/click_and_drag
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt('/') def homepage(): return Div(*[create_chat_message(**msg, msg_num=i) for i, msg in enumerate(example_messages)]) def create_chat_message(role, content, msg_num): text_color = '#1F2937' match role: case 'system': color = '#8B5CF6' case 'user': color = "#F000B8" case _: color = "#37CDBE" # msg 0 = left, msg 1 = right, msg 2 = left, etc. alignment = 'flex-end' if msg_num % 2 == 1 else 'flex-start' message = Div(Div( Div(# Shows the Role Strong(role.capitalize()), style=f"color: {text_color}; font-size: 0.9em; letter-spacing: 0.05em;"), Div(# Shows content and applies font color to stuff other than syntax highlighting Style(f".marked *:not(code):not([class^='hljs']) {{ color: {text_color} !important; }}"), Div(content), style=f"margin-top: 0.5em; color: {text_color} !important;"), # extra styling to make things look better style=f""" margin-bottom: 1em; padding: 1em; border-radius: 24px; background-color: {color}; max-width: 70%; position: relative; color: {text_color} !important; """), style=f"display: flex; justify-content: {alignment};") return message example_messages = [ { "role": "system", "content": "Hello, world! I am a chatbot that can answer questions about the world.", }, { "role": "user", "content": "I have always wondered why the sky is blue. Can you tell me?", }, { "role": "assistant", "content": "The sky is blue because of the atmosphere. As white light passes through air molecules cause it to scatter. Because of the wavelengths, blue light is scattered the most.", }, { "role": "user", "content": "What is the meaning of life?", }, { "role": "assistant", "content": "42 is the meaning of life. It is the answer to the question of life, the universe, and everything.", } ] serve()
https://gallery.fastht.ml/split/widgets/chat_bubble
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt('/') def homepage(): return Div(*[create_chat_message(**msg, msg_num=i) for i, msg in enumerate(example_messages)]) def create_chat_message(role, content, msg_num): text_color = '#1F2937' match role: case 'system': color = '#8B5CF6' case 'user': color = "#F000B8" case _: color = "#37CDBE" # msg 0 = left, msg 1 = right, msg 2 = left, etc. alignment = 'flex-end' if msg_num % 2 == 1 else 'flex-start' message = Div(Div( Div(# Shows the Role Strong(role.capitalize()), style=f"color: {text_color}; font-size: 0.9em; letter-spacing: 0.05em;"), Div(# Shows content and applies font color to stuff other than syntax highlighting Style(f".marked *:not(code):not([class^='hljs']) {{ color: {text_color} !important; }}"), Div(content), style=f"margin-top: 0.5em; color: {text_color} !important;"), # extra styling to make things look better style=f""" margin-bottom: 1em; padding: 1em; border-radius: 24px; background-color: {color}; max-width: 70%; position: relative; color: {text_color} !important; """), style=f"display: flex; justify-content: {alignment};") return message example_messages = [ { "role": "system", "content": "Hello, world! I am a chatbot that can answer questions about the world.", }, { "role": "user", "content": "I have always wondered why the sky is blue. Can you tell me?", }, { "role": "assistant", "content": "The sky is blue because of the atmosphere. As white light passes through air molecules cause it to scatter. Because of the wavelengths, blue light is scattered the most.", }, { "role": "user", "content": "What is the meaning of life?", }, { "role": "assistant", "content": "42 is the meaning of life. It is the answer to the question of life, the universe, and everything.", } ] serve()
https://gallery.fastht.ml/code/widgets/chat_bubble
FastHTML page
Click the object to swap it with another shape
https://gallery.fastht.ml/app/svg/inb_replacement/
FastHTML page
import base64, requests from fasthtml.common import * app, rt = fast_app() @rt def index(): audio_path = "https://ucarecdn.com/abb35276-b3cb-4a5c-bba0-878f264e5976/AfricanFellaCumbiaDelishort.mp3" return Audio(src=f"data:audio/mp4;base64,{load_audio_base64(audio_path)}", controls=True) def load_audio_base64(audio_path: str): """ Convert audio file to base64. """ response = requests.get(audio_path) response.raise_for_status() return base64.b64encode(response.content).decode('ascii')
https://gallery.fastht.ml/code/widgets/audio
FastHTML page
import base64, requests from fasthtml.common import * app, rt = fast_app() @rt def index(): audio_path = "https://ucarecdn.com/abb35276-b3cb-4a5c-bba0-878f264e5976/AfricanFellaCumbiaDelishort.mp3" return Audio(src=f"data:audio/mp4;base64,{load_audio_base64(audio_path)}", controls=True) def load_audio_base64(audio_path: str): """ Convert audio file to base64. """ response = requests.get(audio_path) response.raise_for_status() return base64.b64encode(response.content).decode('ascii')
https://gallery.fastht.ml/split/widgets/audio
FastHTML page
from fasthtml.common import * import numpy as np, seaborn as sns, matplotlib.pylab as plt app,rt = fast_app() data = np.random.rand(4,10) def fh_svg(func): "show svg in fasthtml decorator" def wrapper(*args, **kwargs): func(*args, **kwargs) # calls plotting function f = io.StringIO() # create a buffer to store svg data plt.savefig(f, format='svg', bbox_inches='tight') f.seek(0) # beginning of file svg_data = f.getvalue() plt.close() return NotStr(svg_data) return wrapper @fh_svg def plot_heatmap(matrix,figsize=(6,7),**kwargs): plt.figure(figsize=figsize) sns.heatmap(matrix, cmap='coolwarm', annot=False,**kwargs) @rt def index(): return Div(Label(H3("Heatmap Columns"), _for='n_cols'), Input(type="range", min="1", max="10", value="1", get=update_heatmap, hx_target="#plot", id='n_cols'), Div(id="plot")) @app.get("/update_charts") def update_heatmap(n_cols:int): svg_plot = plot_heatmap(data[:,:n_cols]) return svg_plot serve()
https://gallery.fastht.ml/code/visualizations/seaborn_svg
FastHTML page