Things to remembers when using Fh_Frankenui: - While Pico CSS is commonly used in FastHTML apps, that is *completely incompatible* with Fh_Frankenui. - Fh_Frankenui is *not* compatible with FastAPI syntax and is not targeted at creating API services.# Tailwind CSS Cheat Sheet ## Spacing ``` px 0.5 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 10 11 12 14 16 20 24 28 32 36 40 44 48 52 56 60 64 72 80 96 ``` ## Breakpoints ``` <640px - flex 640px - sm:flex 768px - md:flex 1024px - lg:flex 1280px - xl:flex 1536px - 2xl:flex ``` ## Pseudo Class ``` hover focus focus-within focus-visible active visited target first last only odd even first-of-type last-of-type only-of-type empty disabled enabled checked indeterminate default required valid invalid in-range out-of-range placeholder-shown autofill read-only before after first-letter first-line marker selection file backdrop placeholder supports(-,_) data(-,_) ltr rtl ``` ## Pseudo Class - Media ``` sm md lg xl 2xl min-[] max-sm max-md max-lg max-xl max-2xl []-dark portrait landscape motion-safe motion-reduce contrast-more contrast-less print ``` ## Functions & Directives ``` detailwind @apply eApply @config theme() screen() ``` ## Opacity ``` 0 5 10 20 25 30 38 40 50 60 70 75 80 89 90 95 100 ``` ## Colors ``` slate gray zinc neutral stone amber yellow lime green emerald teal cyan sky blue indigo violet purple fuchsia pink rose red orange 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 300 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 400 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 500 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 600 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 700 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 800 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 900 ``` ## Flex ``` flex flex-basis basis-auto basis-1/2 basis-1/3 basis-1/4 basis-1/5 basis-1/6 basis-1/12 basis-full flex-initial flex-none flex-auto grow grow-0 grow-1 shrink shrink-0 shrink-1 flex-dir flex-row flex-row-reverse flex-col flex-col-reverse flex-wrap wrap flex-wrap-reverse order-first order-last order-none order-1 order-2 ``` ## Grid ``` grid-template-rows grid-rows-none grid-rows-1 grid-rows-2 grid-rows-3 grid-rows-4 grid-rows-5 grid-rows-6 grid-rows-auto grid-template-columns grid-cols-1 grid-cols-2 grid-cols-3 grid-cols-4 grid-cols-5 grid-cols-6 grid-cols-7 grid-cols-8 grid-cols-9 grid-cols-10 grid-cols-11 grid-cols-12 grid-cols-auto grid-auto-flow grid-flow-row grid-flow-col grid-flow-row-dense grid-flow-col-dense grid-auto-rows auto-rows-auto auto-rows-min auto-rows-max auto-rows-fr grid-auto-cols auto-cols-auto auto-cols-min auto-cols-max auto-cols-fr grid-row-start row-span-full row-span-1 row-span-2 row-start-auto row-end-auto row-start-1 row-end-1 ``` ## Spacing ``` padding p-[spacing] p-t-[spacing] p-r-[spacing] p-b-[spacing] p-l-[spacing] margin m-auto m-[spacing] m-t-[spacing] m-r-[spacing] m-b-[spacing] m-l-[spacing] space-between space-x-[spacing] space-y-[spacing] space-x-reverse space-y-reverse ``` ## FlexGrid ``` gap gap-[spacing] gap-x-[spacing] gap-y-[spacing] justify-content justify-start justify-end justify-center justify-between justify-around justify-evenly justify-items justify-items-start justify-items-end justify-items-center justify-items-stretch justify-items-baseline justify-items-auto justify-self justify-self-auto justify-self-start justify-self-end justify-self-center justify-self-stretch align-content content-start content-end content-center content-between content-around content-evenly content-baseline align-items items-start items-end items-center items-stretch items-baseline items-auto place-content place-content-start place-content-end place-content-center place-content-between place-content-around place-content-evenly place-content-baseline place-items place-items-auto place-items-start place-items-end place-items-center place-items-stretch place-items-baseline place-self place-self-auto place-self-start place-self-end place-self-center place-self-stretch ``` ## Border ``` border-divide-outline-ring-offset-color border-divide-ring-offset-fast-1 border-divide-ring-offset-others-current border-divide-ring-offset-white border-divide-ring-offset-black border-divide-ring-offset-[color] border-divide-outline-ring-style border-divide-outline border-divide-dotted border-divide-dashed border-divide-solid border-divide-double border-hidden outline border-width border border-[1|2|3|4] border-x-[1|2|3|4] border-y-[1|2|3|4] border-t-[1|2|3|4] border-r-[1|2|3|4] border-b-[1|2|3|4] border-l-[1|2|3|4] divide-width divide divide-x divide-y divide-reverse ring-width ring ring-inset ring-offset-width ring-offset-[1|2|3|4] outline-width outline outline-offset-width outline-offset-[1|2|3|4] border-radius rounded rounded-sm rounded-md rounded-lg rounded-xl rounded-2xl rounded-full rounded-[1|2|3|4] rounded-t-[1|2|3|4] rounded-r-[1|2|3|4] rounded-b-[1|2|3|4] rounded-l-[1|2|3|4] rounded-tr-[1|2|3|4] rounded-br-[1|2|3|4] rounded-bl-[1|2|3|4] rounded-tl-[1|2|3|4] ``` ## Layout ``` container columns columns-1 columns-2 columns-3 columns-4 columns-5 columns-6 columns-7 columns-auto columns-[...nums] box-sizing box-border box-content float float-left float-right float-none clear clear-left clear-right clear-both clear-none positions static relative absolute fixed sticky visible invisible collapse display block inline-block inline flex grid inline-flex table table-caption table-cell table-row table-row-group table-header-group table-footer-group table-col table-col-group hidden contents flow-root positions-t-b [top|right|bottom|left] [top|right|bottom|left]-[spacing] [top|right|bottom|left]-auto [top|right|bottom|left]-full inset inset-auto inset-[spacing] inset-0 inset-x-[1|2|3|4] inset-y-[1|2|3|4] inset-t-[1|2|3|4] inset-r-[1|2|3|4] inset-b-[1|2|3|4] inset-l-[1|2|3|4] break-before break-before:auto break-before:column break-before:page break-before:avoid-page break-before:left break-before:right break-before:avoid-column break-inside break-inside:auto break-inside:avoid-page break-inside:avoid-column overflow overflow-auto overflow-hidden overflow-visible overflow-x-auto overflow-x-hidden overflow-x-visible overflow-y-auto overflow-y-hidden overflow-y-visible overflow-clip overflow-scroll overscroll-behavior overscroll-auto overscroll-none overscroll-contain overscroll-x-auto overscroll-x-none overscroll-x-contain overscroll-y-auto overscroll-y-none overscroll-y-contain aspect-ratio aspect-auto aspect-video aspect-square box-decoration-break box-decoration-clone box-decoration-slice isolation isolate isolation-auto object-fit object-contain object-cover object-fill object-none object-scale-down object-positions object-center object-left object-right object-top object-bottom object-[left|top|right|bottom] z-index z-0 z-10 z-20 z-30 z-40 z-50 z-auto ``` ## Typography ``` family font-sans font-serif font-mono font-size text-xs text-sm text-base text-lg text-xl text-2xl text-3xl text-4xl text-5xl text-6xl text-7xl text-8xl text-9xl text-[] line-height leading-none leading-tight leading-snug leading-normal leading-relaxed leading-loose text-align text-left text-center text-right text-justify text-start text-end text-transform uppercase lowercase capitalize normal-case text-overflow truncate text-ellipsis text-clip style italic not-italic weight font-thin font-light font-medium font-semibold font-bold font-extrabold font-black variant-numeric ordinal slashed-zero lining-nums oldstyle-nums proportional-nums tabular-nums diagonal-fractions stacked-fractions letter-spacing tracking-tight tracking-tighter tracking-normal tracking-wide tracking-wider placeholder-color [placeholder-color]-[color] [placeholder-color]-[transparent] [placeholder-color]-[current] vertical-align align-baseline align-top align-middle align-bottom align-text-bottom align-text-top align-sub align-super text-indent indent-[spacing] text-opacity opacity-[opacity] text-decoration underline line-through overline no-underline text-decoration-color decoration-current decoration-transparent decoration-inherit decoration-white decoration-black decoration-[color] text-decoration-style decoration-solid decoration-dashed decoration-dotted decoration-wavy text-decoration-thickness decoration-from-font decoration-auto decoration-[1|2|3|4] text-decoration-offset underline-offset-auto underline-offset-[1|2|3|4] smoothing antialiased subpixel-antialiased list-style-type list-none list-disc list-decimal list-inside list-outside list-style-position list-inside list-outside white-space whitespace-normal whitespace-nowrap whitespace-pre whitespace-pre-wrap whitespace-pre-line word-break break-normal break-words break-all break-keep content content-none ``` ## Background ``` bg-attachment bg-fixed bg-local bg-scroll bg-clip bg-clip-border bg-clip-padding bg-clip-content bg-clip-text bg-color [bg-color]-[color] [bg-color]-[transparent] [bg-color]-[current] [bg-color]-[inherit] [bg-color]-[black] [bg-color]-[white] [bg-color]-[color] bg-position bg-center bg-left bg-right bg-top bg-bottom bg-[left|right|top|bottom] bg-image bg-none bg-gradient-to-[direction] bg-gradient-to-[t|r|b|l] bg-gradient-to-t bg-gradient-to-r bg-gradient-to-b bg-gradient-to-l bg-repeat bg-no-repeat bg-repeat-x bg-repeat-y bg-repeat-round bg-repeat-space bg-size bg-auto bg-cover bg-contain bg-origin bg-border bg-padding bg-content bg-origin-border ``` ## Interactivity ``` accent-color accent-transparent accent-current accent-white accent-black accent-[color] appearance appearance-none cursor cursor-auto cursor-default cursor-pointer cursor-grab cursor-grabbing cursor-crosshair cursor-move cursor-not-allowed cursor-context-menu cursor-help cursor-wait cursor-text cursor-resize cursor-ns-resize cursor-ew-resize cursor-ne-resize cursor-nw-resize cursor-se-resize cursor-sw-resize cursor-zoom-in cursor-zoom-out pointer-events pointer-events-none pointer-events-auto scroll-behavior scroll-auto scroll-smooth scroll-margin [scroll-margin]-[spacing] [scroll-margin]-[spacing] [scroll-margin]-[spacing] [scroll-margin]-[spacing] scroll-padding [scroll-padding]-[spacing] [scroll-padding]-[spacing] [scroll-padding]-[spacing] [scroll-padding]-[spacing] scroll-snap-align start end center snap-align-none scroll-snap-stop normal always scroll-snap-type snap-none snap-x snap-y snap-both snap-mandatory snap-proximity resize resize resize-none resize-x resize-y touch-action touch-auto touch-none touch-pan-x touch-pan-y touch-pan-left touch-pan-right touch-pan-down touch-pan-up touch-manipulation user-select user-select-none select-text select-all select-auto will-change will-change-auto will-change-scroll will-change-contents will-change-transform ``` ## Filters ``` brightness brightness-[0|1|2|3|4|5|6|7|8|9] brightness-[100|150|200] backdrop-brightness-[0|1|2|3|4|5|6|7|8|9] backdrop-brightness-[100|150|200] contrast contrast-[0|1|2|3|4|5|6|7|8|9] contrast-[100|150|200] backdrop-contrast-[0|1|2|3|4|5|6|7|8|9] backdrop-contrast-[100|150|200] hue-rotate hue-rotate-[0|1|2|3|4|5|6|7|8|9] hue-rotate-[100|150|200] backdrop-hue-rotate-[0|1|2|3|4|5|6|7|8|9] backdrop-hue-rotate-[100|150|200] backdrop-opacity backdrop-opacity-[opacity] saturate saturate-[0|1|2|3|4|5|6|7|8|9] saturate-[100|150|200] backdrop-saturate-[0|1|2|3|4|5|6|7|8|9] backdrop-saturate-[100|150|200] blur blur-blur blur-blur-2xl blur-blur-xl blur-blur-lg blur-blur-md blur-blur-sm drop-shadow drop-shadow drop-shadow-[sm|md|lg|xl|2xl] grayscale grayscale grayscale-50 grayscale-75 grayscale-100 grayscale-invert grayscale-invert grayscale-invert-50 grayscale-invert-75 grayscale-invert-100 backdrop-grayscale-invert-[sepia] ``` ## Table ``` border-collapse border-collapse border-separate border-spacing border-spacing-[spacing] border-spacing-[spacing] border-spacing-[spacing] border-spacing-[spacing] table-layout table-auto table-fixed ``` ## Sizing ``` width|height w-[width|height] w-[spacing] w-auto w-full w-screen w-1/2 w-1/3 w-1/4 w-1/5 w-1/6 w-1/12 w-2/3 w-2/4 w-2/5 w-2/6 w-3/4 w-3/5 w-3/6 w-4/5 w-4/6 w-5/6 w-11/12 w-full min-width|height min-w-[width|height] min-w-[spacing] min-w-0 min-w-full min-w-screen min-w-[0|1|2|3|4|5|6] min-w-max max-width max-w-0 max-w-none max-w-xs max-w-sm max-w-md max-w-lg max-w-xl max-w-2xl max-w-screen-sm max-w-screen-md max-w-screen-lg max-w-screen-xl max-w-full max-w-[spacing] max-height max-h-[height] max-h-[spacing] max-h-0 max-h-full max-h-screen max-h-[spacing] max-h-max ``` ## Transition & Animation ``` property transition-none transition-all transition-colors transition-opacity transition-shadow transition-transform duration|delay [duration|delay]-[75|100|150|200|300|500|700|1000] [duration|delay]-[75|100|150|200|300|500|700|1000] [duration|delay]-[75|100|150|200|300|500|700|1000] timing function ease-linear ease-in ease-out ease-in-out animation animate-none animate-spin animate-ping animate-pulse animate-bounce ``` ## Transform ``` transform-origin origin-top origin-right origin-bottom origin-left origin-top-right origin-bottom-right origin-bottom-left origin-top-left origin-center scale scale-0 scale-50 scale-75 scale-90 scale-95 scale-100 scale-105 scale-110 scale-125 scale-150 scale-x-[0|1|2|3|4|5|6|7|8|9] scale-x-[100|150|200] scale-y-[0|1|2|3|4|5|6|7|8|9] scale-y-[100|150|200] rotate rotate-0 rotate-1 rotate-2 rotate-3 rotate-6 rotate-12 rotate-45 rotate-90 rotate-180 rotate-[0|1|2|3|4|5|6|7|8|9] rotate-[100|150|200] translate translate-x-[spacing] translate-x-[spacing] translate-x-[spacing] translate-x-[spacing] translate-y-[spacing] translate-y-[spacing] translate-y-[spacing] translate-y-[spacing] skew skew-x-[0|1|2|3|4|5|6|7|8|9] skew-x-[100|150|200] skew-y-[0|1|2|3|4|5|6|7|8|9] skew-y-[100|150|200] ``` ## Effect ``` mix-blend-mode mix-blend-normal mix-blend-multiply mix-blend-screen mix-blend-overlay mix-blend-darken mix-blend-lighten mix-blend-color-dodge mix-blend-color-burn mix-blend-hard-light mix-blend-soft-light mix-blend-difference mix-blend-exclusion mix-blend-hue mix-blend-saturation mix-blend-luminosity mix-blend-color mix-blend-plus-lighter box-shadow shadow shadow-[sm|md|lg|xl|2xl] shadow-none shadow-inner shadow-lg shadow-xl shadow-2xl box-shadow-color shadow-transparent shadow-inherit shadow-current shadow-white shadow-black shadow-[color] opacity opacity-[opacity] ``` ## Svg ``` fill [fill|stroke]-none [fill|stroke]-transparent [fill|stroke]-current [fill|stroke]-inherit [fill|stroke]-black [fill|stroke]-white [fill|stroke]-[color] stroke-width stroke stroke-[0|1|2] ``` ## Accessibility ``` screen-reader sr-only not-sr-only ```# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_core.ipynb. # %% auto 0 __all__ = ['franken_class_map', 'enum_to_markdown_table', 'fast_app', 'FastHTML', 'Theme', 'TextT', 'TextFont', 'ButtonT', 'Button', 'ButtonSubmit', 'H1', 'H2', 'H3', 'H4', 'Main', 'Titled', 'DividerT', 'Divider', 'DividerSplit', 'DividerLine', 'Article', 'ArticleTitle', 'ArticleMeta', 'ContainerT', 'Container', 'SectionT', 'Section', 'Fieldset', 'Legend', 'Input', 'Select', 'Radio', 'CheckboxX', 'Range', 'Toggle_switch', 'TextArea', 'Switch', 'FormLabel', 'LabelT', 'Label', 'UkFormSection', 'GenericLabelInput', 'LabelInput', 'LabelRadio', 'LabelCheckboxX', 'LabelRange', 'LabelTextArea', 'LabelSwitch', 'LabelSelect', 'Options', 'UkSelect', 'LabelUkSelect', 'AT', 'ListT', 'List', 'ModalContainer', 'ModalDialog', 'ModalHeader', 'ModalBody', 'ModalFooter', 'ModalTitle', 'ModalCloseButton', 'Modal', 'PaddingT', 'PositionT', 'Placeholder', 'Progress', 'UkIcon', 'UkIconLink', 'DiceBearAvatar', 'FlexT', 'Grid', 'DivFullySpaced', 'DivCentered', 'DivLAligned', 'DivRAligned', 'DivVStacked', 'DivHStacked', 'NavT', 'NavContainer', 'NavParentLi', 'NavDividerLi', 'NavHeaderLi', 'NavSubtitle', 'NavCloseLi', 'NavBarContainer', 'NavBarLSide', 'NavBarRSide', 'NavBarCenter', 'NavBarNav', 'NavBarSubtitle', 'NavBarNavContainer', 'NavBarParentIcon', 'DropDownNavContainer', 'TabContainer', 'CardT', 'CardTitle', 'CardHeader', 'CardBody', 'CardFooter', 'CardContainer', 'Card', 'TableT', 'Table', 'Td', 'Th', 'Tr', 'Thead', 'Tbody', 'TableFromLists', 'TableFromDicts', 'apply_classes', 'render_md'] # %% ../nbs/01_core.ipynb import fasthtml.common as fh from .foundations import * from fasthtml.common import is_listy, Div, P, Span, Script, FastHTML, FT, to_xml, show,fast_app from fasthtml.svg import Svg from fasthtml.components import Uk_theme_switcher, Main from enum import Enum, auto from fasthtml.components import Uk_select,Uk_input_tag,Uk_icon from functools import partial from itertools import zip_longest from typing import Union, Tuple, Optional from fastcore.all import * import copy, re # %% ../nbs/01_core.ipynb def enum_to_markdown_table(enum_class): headers = ["Option", "Value"] rows = [[name, value.value] for name, value in enum_class.__members__.items()] max_name_len = max(len(row[0]) for row in rows) max_value_len = max(len(row[1]) for row in rows) header = f"| {'Option':<{max_name_len}} | {'Value':<{max_value_len}} |" separator = f"|{'-'*(max_name_len+2)}|{'-'*(max_value_len+2)}|" body = "\n".join(f"| {row[0]:<{max_name_len}} | {row[1]:<{max_value_len}} |" for row in rows) return f"{header}\n{separator}\n{body}" # %% ../nbs/01_core.ipynb @delegates(fh.fast_app, but=['pico']) def fast_app(*args, pico=False, **kwargs): "Adds `bg-background text-foreground` to bodykw for frankenui themes" if 'bodykw' not in kwargs: kwargs['bodykw'] = {} if 'class' not in kwargs['bodykw']: kwargs['bodykw']['class'] = '' kwargs['bodykw']['class'] = stringify((kwargs['bodykw']['class'],'bg-background text-foreground')) return fh.fast_app(*args, pico=False, **kwargs) # %% ../nbs/01_core.ipynb @delegates(fh.FastHTML, but=['pico']) def FastHTML(*args, pico=False, **kwargs): "Adds `bg-background text-foreground` to bodykw for frankenui themes" if 'bodykw' not in kwargs: kwargs['bodykw'] = {} if 'class' not in kwargs['bodykw']: kwargs['bodykw']['class'] = '' kwargs['bodykw']['class'] = stringify((kwargs['bodykw']['class'],'bg-background text-foreground')) return fh.FastHTML(*args, pico=False, **kwargs) # %% ../nbs/01_core.ipynb def _headers_theme(color): return fh.Script(f'''const htmlElement = document.documentElement; if ( localStorage.getItem("mode") === "dark" || (!("mode" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches) ) {{ htmlElement.classList.add("dark"); }} else {{ htmlElement.classList.remove("dark"); }} htmlElement.classList.add(localStorage.getItem("theme") || "uk-theme-{color}"); ''') # %% ../nbs/01_core.ipynb class Theme(Enum): "Selector to choose theme and get all headers needed for app. Includes frankenui + tailwind" def _generate_next_value_(name, start, count, last_values): return name slate = auto() stone = auto() gray = auto() neutral = auto() red = auto() rose = auto() orange = auto() green = auto() blue = auto() yellow = auto() violet = auto() zinc = auto() def headers(self): return (fh.Link(rel="stylesheet", href="https://unpkg.com/franken-ui@1.1.0/dist/css/core.min.css"), fh.Script( type="module", src ="https://unpkg.com/franken-ui@1.1.0/dist/js/core.iife.js"), # fh.Script( type="module", src ="https://unpkg.com/franken-ui@1.1.0/dist/js/icon.iife.js"), fh.Script( type="module", src = "https://cdn.jsdelivr.net/gh/answerdotai/fh-frankenui@main/fh_frankenui/icon.iife.js"), fh.Script(src="https://cdn.tailwindcss.com"), _headers_theme(self.value),) # %% ../nbs/01_core.ipynb class TextT(VEnum): 'Text Styles from https://franken-ui.dev/docs/text' def _generate_next_value_(name, start, count, last_values): return str2ukcls('text', name) # Text Style lead,meta, italic = auto(), auto(), auto() # Text Size small, default, large = auto(), 'uk-text', auto() # Text Weight light, normal, bold, lighter, bolder = auto(),auto(),auto(),auto(),auto() # Text Transform capitalize,uppercase, lowercase = auto(),auto(),auto() # Text Decoration decoration_none = auto() # Text Color muted,primary,secondary, success,warning, danger = auto(),auto(),auto(),auto(),auto(),auto() # Text Alignment left, right,center,justify = auto(), auto(), auto(), auto() # Vertical Alignment top,middle,bottom, baseline = auto(),auto(),auto(),auto() # Text Wrapping truncate,break_,nowrap = auto(),auto(),auto() # %% ../nbs/01_core.ipynb class TextFont(Enum): "Combinations of TextT that are particularly useful" def __add__(self, other): return stringify((self, other)) def __radd__(self, other): return stringify((other, self)) def __str__(self): return self.value muted_sm = stringify((TextT.muted, TextT.small)) muted_lg = stringify((TextT.muted, TextT.large)) bold_sm = stringify((TextT.bold, TextT.small)) # %% ../nbs/01_core.ipynb class ButtonT(VEnum): "Options for styling Buttons" def _generate_next_value_(name, start, count, last_values): return str2ukcls('button', name) default = auto() primary = auto() secondary = auto() danger = auto() text = auto() link = auto() ghost = auto() # %% ../nbs/01_core.ipynb def Button(*c: Union[str, FT], cls: Union[str, Enum]=ButtonT.default, submit=True, **kwargs ) -> FT: "A Button with Styling (defaults to `type=submit` for form submission)" return fh.Button(*c, cls=('uk-button', stringify(cls)), type='submit' if submit else 'button', **kwargs) # %% ../nbs/01_core.ipynb def ButtonSubmit(*c: Union[str, FT], cls: Union[str, Enum]=ButtonT.default, **kwargs ) -> FT: "A Button with Styling to be used for submitting forms" return fh.Button(*c, cls=('uk-button', stringify(cls)), type='submit', **kwargs) # %% ../nbs/01_core.ipynb def H1(*c:FT|str, cls:Enum|str|tuple=(), **kwargs)->FT: "A H1 with Styling" return fh.H1(*c, cls=('uk-h1',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def H2(*c:FT|str, cls:Enum|str|tuple=(), **kwargs)->FT: "A H2 with Styling" return fh.H2(*c, cls=('uk-h2',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def H3(*c:FT|str, cls:Enum|str|tuple=(), **kwargs)->FT: "A H3 with Styling" return fh.H3(*c, cls=('uk-h3',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def H4(*c:FT|str, cls:Enum|str|tuple=(), **kwargs)->FT: "A H4 with Styling" return fh.H4(*c, cls=('uk-h4',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Main(*args, **kwargs): return fh.Main(*args, **kwargs) # %% ../nbs/01_core.ipynb def Titled(title:str="FastHTML app", *args, cls="container", **kwargs)->FT: "A H1 with styling, whose title is also used in the page's title tag" return fh.Title(title), fh.Main(H1(title), *args, cls=cls, **kwargs) # %% ../nbs/01_core.ipynb class DividerT(VEnum): " Divider Styles from https://franken-ui.dev/docs/divider" def _generate_next_value_(name, start, count, last_values): return str2ukcls('divider', name) icon=auto() small=auto() vertical=auto() # %% ../nbs/01_core.ipynb def Divider(*args, cls=('my-4', DividerT.icon), **kwargs): "Divider with default styling and margin" cls = stringify(cls) container = Div if 'uk-divider-vertical' in cls else Hr return container(*args, cls=cls, **kwargs) # %% ../nbs/01_core.ipynb def DividerSplit(*c, cls=(), line_cls=(), text_cls=()): cls, line_cls, text_cls = map(stringify,(cls, line_cls, text_cls)) return Div(cls='relative ' + cls)( Div(cls="absolute inset-0 flex items-center " + line_cls)(Span(cls="w-full border-t border-border")), Div(cls="relative flex justify-center " + text_cls)(Span(cls="bg-background px-2 ")(*c))) # %% ../nbs/01_core.ipynb def DividerLine(lwidth=2, y_space=4): return Hr(cls=f"my-{y_space} h-[{lwidth}px] w-full bg-secondary") # %% ../nbs/01_core.ipynb def Article(*c, cls=(), **kwargs): return fh.Article(*c, cls=('uk-article',stringify(cls)), **kwargs) def ArticleTitle(*c, cls=(), **kwargs): return H1(*c, cls=('uk-article-title',stringify(cls)), **kwargs) def ArticleMeta(*c, cls=(), **kwargs): return P(*c, cls=('uk-article-meta',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb class ContainerT(VEnum): 'Max width container sizes from https://franken-ui.dev/docs/container' def _generate_next_value_(name, start, count, last_values): return str2ukcls('container', name) xsmall = auto() small = auto() large = auto() xlarge = auto() expand = auto() # %% ../nbs/01_core.ipynb def Container(*c, cls=(), **kwargs): "A Div to be used as a container that often wraps large sections or a page of content" return Div(*c, cls=('uk-container',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb class SectionT(VEnum): 'Section styles from https://franken-ui.dev/docs/section' def _generate_next_value_(name, start, count, last_values): return str2ukcls('section', name) default = auto() muted = auto() primary = auto() secondary = auto() xsmall = auto() small = auto() large = auto() xlarge = auto() remove_vertical = auto() # %% ../nbs/01_core.ipynb def Section(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-section',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Fieldset(*c, cls=(), **kwargs): return fh.Fieldset(*c, cls=('uk-fieldset',stringify(cls)), **kwargs) def Legend(*c, cls=(), **kwargs): return fh.Legend(*c, cls=('uk-legend',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Input(*c, cls=(), **kwargs): return fh.Input(*c, cls=('uk-input',stringify(cls)), **kwargs) def Select(*option, cls=(), **kwargs): return fh.Select(*option, cls=('uk-select',stringify(cls)), **kwargs) def Radio(*c, cls=(), **kwargs): return fh.Input(*c, cls=('uk-radio',stringify(cls)), type='radio', **kwargs) def CheckboxX(*c, cls=(), **kwargs): return fh.Input(*c, cls=('uk-checkbox',stringify(cls)), type='checkbox', **kwargs) def Range(*c, cls=(), **kwargs): return fh.Input(*c, cls=('uk-range',stringify(cls)), type='range', **kwargs) def Toggle_switch(*c, cls=(), **kwargs): return fh.Input(*c, cls=('uk-toggle-switch uk-toggle-switch-primary',stringify(cls)), type='checkbox', **kwargs) def TextArea(*c, cls=(), **kwargs): return fh.Textarea(*c, cls=('uk-textarea',stringify(cls)), **kwargs) def Switch(*c, cls='min-w-9', **kwargs): return fh.Input(*c, cls=('uk-toggle-switch uk-toggle-switch-primary',stringify(cls)), type='checkbox', **kwargs) # %% ../nbs/01_core.ipynb def FormLabel(*c, cls=(), **kwargs): return fh.Label(*c, cls=('uk-form-label',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb class LabelT(VEnum): def _generate_next_value_(name, start, count, last_values): return str2ukcls('label', name) primary = auto() secondary = auto() danger = auto() # %% ../nbs/01_core.ipynb def Label(*c, cls=(), **kwargs): "FrankenUI labels, which look like pills" return fh.Label(*c, cls=('uk-label',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def UkFormSection(title, description, *c, button_txt='Update', outer_margin=6, inner_margin=6): return Div(cls=f'space-y-{inner_margin} py-{outer_margin}')( Div(H3(title), P(description, cls=TextFont.muted_sm)), DividerSplit(), *c, Div(Button(button_txt, cls=ButtonT.primary)) if button_txt else None) # %% ../nbs/01_core.ipynb def GenericLabelInput( label:str|FT, lbl_cls='', input_cls='', container=Div, cls='', id='', input_fn=noop, **kwargs ): "`Div(Label,Input)` component with Uk styling injected appropriately. Generally you should higher level API, such as `UkTextArea` which is created for you in this library" if isinstance(label, str) or label.tag != 'label': label = FormLabel(cls=stringify(lbl_cls), fr=id)(label) inp = input_fn(id=id, cls=stringify(input_cls), **kwargs) if container: return container(label, inp, cls=stringify(cls)) return label, inp # %% ../nbs/01_core.ipynb @delegates(GenericLabelInput, but=['input_fn','cls']) def LabelInput(*args, cls='space-y-2', **kwargs): "A Label and Input pair that provides default spacing and links/names them based on id" return GenericLabelInput(*args, cls=stringify(cls),input_fn=Input, **kwargs) # %% ../nbs/01_core.ipynb def LabelRadio(label:str|FT, lbl_cls='', input_cls='', container=Div, cls='flex items-center space-x-2', id='', **kwargs ): "A Label and Radio pair that provides default spacing and links/names them based on id" if isinstance(label, str) or label.tag != 'label': label = FormLabel(cls=stringify(lbl_cls), fr=id)(label) inp = Radio(id=id, cls=stringify(input_cls), **kwargs) if container: return container(inp, label, cls=stringify(cls)) return inp, label # %% ../nbs/01_core.ipynb def LabelCheckboxX(label:str|FT, lbl_cls='', input_cls='', container=Div, cls='flex items-center space-x-2', **kwargs ): "`Div(Label,Input)` component with Uk styling injected appropriately. Generally you should higher level API, such as `UkTextArea` which is created for you in this library" id = kwargs.pop('id', fh.unqid()) if isinstance(label, str) or label.tag != 'label': label = FormLabel(cls=stringify(lbl_cls), fr=id)(label) inp = CheckboxX(id=id, cls=stringify(input_cls), **kwargs) if container: return container(inp, label, cls=stringify(cls)) return inp, label # %% ../nbs/01_core.ipynb # @delegates(GenericLabelInput, but=['input_fn','cls']) # def LabelCheckboxX(*args, cls='space-x-2', **kwargs): return GenericLabelInput(*args, cls=stringify(cls), input_fn=CheckboxX, **kwargs) # %% ../nbs/01_core.ipynb @delegates(GenericLabelInput, but=['input_fn','cls']) def LabelRange(*args, cls='space-y-2', **kwargs): return GenericLabelInput(*args, cls=stringify(cls), input_fn=Range, **kwargs) # %% ../nbs/01_core.ipynb @delegates(GenericLabelInput, but=['input_fn','cls']) def LabelTextArea(*args, cls='space-y-2', **kwargs): return GenericLabelInput(*args, cls=stringify(cls), input_fn=TextArea, **kwargs) # %% ../nbs/01_core.ipynb @delegates(GenericLabelInput, but=['input_fn','cls']) def LabelSwitch(*args, cls='space-x-2', **kwargs): return GenericLabelInput(*args, cls=stringify(cls), input_fn=Toggle_switch, **kwargs) # %% ../nbs/01_core.ipynb def LabelSelect(*option, label:str|FT, lbl_cls='', input_cls='', container=Div, cls='space-y-2', id='', **kwargs ): "`Div(Label,Input)` component with Uk styling injected appropriately. Generally you should higher level API, such as `UkTextArea` which is created for you in this library" if isinstance(label, str) or label.tag != 'label': label = FormLabel(lbl_cls=stringify(lbl_cls), fr=id)(label) inp = Select(*option, id=id, cls=stringify(input_cls), **kwargs) if container: return container(label, inp, cls=stringify(cls)) return label, inp # %% ../nbs/01_core.ipynb def Options(*c, # Content for an `Option` selected_idx:int=None, # Index location of selected `Option` disabled_idxs:set=None # Idex locations of disabled `Options` ): "Helper function to wrap things into `Option`s for use in `UkSelect`" return [fh.Option(o,selected=i==selected_idx, disabled=disabled_idxs and i in disabled_idxs) for i,o in enumerate(c)] # %% ../nbs/01_core.ipynb def UkSelect(*option, # Options for the select dropdown (can use `Options` helper function to create) inp_cls=(), # Additional classes for the select input cls=('space-y-2',), # Classes for the outer div id="", # ID for the select input name="", # Name attribute for the select input placeholder="", # Placeholder text for the select input searchable=False, # Whether the select should be searchable **kwargs): # Additional arguments passed to Uk_select "Creates a select dropdown with uk styling" inp_cls, cls = map(stringify, (inp_cls, cls)) select = Uk_select(*option, cls=inp_cls, uk_cloak=True, id=id, name=name, placeholder=placeholder, searchable=searchable, **kwargs) return Div(cls=cls)(select) # %% ../nbs/01_core.ipynb def LabelUkSelect(*option, # Options for the select dropdown (can use `Options` helper function to create) label=(), # String or FT component for the label lbl_cls=(), # Additional classes for the label inp_cls=(), # Additional classes for the select input cls=('space-y-2',), # Classes for the outer div id="", # ID for the select input name="", # Name attribute for the select input placeholder="", # Placeholder text for the select input searchable=False, # Whether the select should be searchable **kwargs): # Additional arguments passed to Uk_select "Creates a select dropdown with uk styling" lbl_cls, inp_cls, cls = map(stringify, (lbl_cls, inp_cls, cls)) if label: lbl = FormLabel(cls=f'{lbl_cls}', fr=id)(label) select = Uk_select(*option, cls=inp_cls, uk_cloak=True, id=id, name=name, placeholder=placeholder, searchable=searchable, **kwargs) return Div(cls=cls)(lbl, select) if label else Div(cls=cls)(select) # %% ../nbs/01_core.ipynb class AT(VEnum): 'Link styles from https://franken-ui.dev/docs/link' def _generate_next_value_(name, start, count, last_values): return str2ukcls('link', name) muted = auto() text = auto() reset = auto() # %% ../nbs/01_core.ipynb # def Link(*c, cls=(), **kwargs): # return fh.A(*c, cls=('uk-link',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb class ListT(VEnum): 'List styles from https://franken-ui.dev/docs/list' def _generate_next_value_(name, start, count, last_values): return str2ukcls('list', name) disc = auto() circle = auto() square = auto() decimal = auto() hyphen = auto() muted = auto() primary = auto() secondary = auto() bullet = auto() divider = auto() striped = auto() # %% ../nbs/01_core.ipynb def List(*c, cls=(), **kwargs): return fh.Ul(*c, cls=('uk-list',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def ModalContainer(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-modal-container',stringify(cls)), uk_modal=True, **kwargs) def ModalDialog(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-modal-dialog', stringify(cls)), **kwargs) def ModalHeader(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-modal-header', stringify(cls)), **kwargs) def ModalBody(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-modal-body', stringify(cls)), **kwargs) def ModalFooter(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-modal-footer', stringify(cls)), **kwargs) def ModalTitle(*c, cls=(), **kwargs): return fh.H2(*c, cls=('uk-modal-title', stringify(cls)), **kwargs) def ModalCloseButton(*c, cls=(), **kwargs): return Button(*c, cls=('uk-modal-close', stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Modal(*c, header=None, # Components that go in the header footer=None, # Components that go in the footer cls=(), # class for outermost container dialog_cls=(), # classes for the dialog header_cls='p-6', # classes for the header body_cls='space-y-6', # classes for the body footer_cls=(), # classes for the footer id='', # id for the outermost container **kwargs # classes for the outermost container ): # Modal "Create a Modal using the appropriate Modal* classes to put the boilerplate in the appropriate places for you" cls, dialog_cls, header_cls, body_cls, footer_cls = map(stringify, (cls, dialog_cls, header_cls, body_cls, footer_cls)) res = [] if header: res.append(ModalHeader(cls=header_cls)(header)) res.append(ModalBody(cls=body_cls)(*c)) if footer: res.append(ModalFooter(cls=footer_cls)(footer)) return ModalContainer(ModalDialog(*res, cls=dialog_cls), cls=cls, id=id, **kwargs) # %% ../nbs/01_core.ipynb class PaddingT(VEnum): 'Padding Modifiers from https://franken-ui.dev/docs/padding' def _generate_next_value_(name, start, count, last_values): return str2ukcls('padding', name) xsmall = auto() small = auto() default = '' medium = auto() large = auto() xlarge = auto() remove = auto() remove_top = auto() remove_bottom = auto() remove_left = auto() remove_right = auto() remove_vertical = auto() remove_horizontal = auto() # %% ../nbs/01_core.ipynb class PositionT(VEnum): 'Position modifiers from https://franken-ui.dev/docs/position' def _generate_next_value_(name, start, count, last_values): return str2ukcls('position', name) top = auto() bottom = auto() left = auto() right = auto() top_left = auto() top_center = auto() top_right = auto() center = auto() center_left = auto() center_right = auto() bottom_left = auto() bottom_center = auto() bottom_right = auto() center_horizontal = auto() center_vertical = auto() # %% ../nbs/01_core.ipynb def Placeholder(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-placeholder',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Progress(*c, cls=(), value="", max="", **kwargs): return fh.Progress(*c, value=value, max=max, cls=('uk-progress',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def UkIcon(icon,height=None,width=None,stroke_width=None,cls=(), **kwargs): return Uk_icon(icon=icon, height=height, width=width, stroke_width=stroke_width, cls=cls, **kwargs) # %% ../nbs/01_core.ipynb def UkIconLink(icon, height=None, width=None, stroke_width=None, cls=(), button=False, **kwargs): fn = fh.Button if button else fh.A return fh.A(cls=(f"uk-icon-{'button' if button else 'link'}", stringify(cls)), **kwargs)( UkIcon(icon=icon, height=height, width=width, stroke_width=stroke_width)) # %% ../nbs/01_core.ipynb def DiceBearAvatar(seed_name, # Seed name (ie 'Isaac Flath') h=20, # Height w=20, # Width ): # Span with Avatar url = 'https://api.dicebear.com/8.x/lorelei/svg?seed=' return Span(cls=f"relative flex h-{h} w-{w} shrink-0 overflow-hidden rounded-full bg-accent")( fh.Img(cls=f"aspect-square h-{h} w-{w}", alt="Avatar", loading="lazy", src=f"{url}{seed_name}")) # %% ../nbs/01_core.ipynb class FlexT(VEnum): 'Flexbox modifiers from UIkit' def _generate_next_value_(name, start, count, last_values): return str2ukcls('flex', name) # Display block, inline = 'uk-flex', auto() # Horizontal Alignment left, center, right, between, around = auto(), auto(), auto(), auto(), auto() # Vertical Alignment stretch, top, middle, bottom = auto(), auto(), auto(), auto() # Direction row, row_reverse, column, column_reverse = auto(), auto(), auto(), auto() # Wrap nowrap, wrap, wrap_reverse = auto(), auto(), auto() # %% ../nbs/01_core.ipynb def Grid(*div, # Divs/Containers that should be divided into a grid cols_min=None, # defaults to min(len(div),1) cols_sm=None, # defaults to min(len(div),2) cols_md=None, # defaults to min(len(div),3) cols_lg=None, # defaults to min(len(div),4) cols=None, # Size at every breakpoint cls='gap-4', # Additional classes for Grid Div **kwargs # Additional args for Grid Div ): """Creates a grid with the given number of columns, often used for a grid of cards""" cols_min = cols_min if cols_min else cols if cols else 1 cols_sm = cols_sm if cols_sm else cols if cols else max(min(len(div), 2), cols_min+1) cols_md = cols_md if cols_md else cols if cols else max(min(len(div), 3), cols_min+2) cols_lg = cols_lg if cols_lg else cols if cols else max(min(len(div), 3), cols_min+2) cls = stringify(cls) return Div(cls=(f'grid grid-cols-{cols_min} sm:grid-cols-{cols_sm} md:grid-cols-{cols_md} lg:grid-cols-{cols_lg}',cls), **kwargs)(*div) # %% ../nbs/01_core.ipynb def DivFullySpaced(*c, # Components cls='uk-width-1-1',# Classes for outer div **kwargs # Additional args for outer div ): # Div with spaced components via flex classes "Creates a flex div with it's components having as much space between them as possible" cls = stringify(cls) return Div(cls=(FlexT.block,FlexT.between,FlexT.middle,cls), **kwargs)(*c) # %% ../nbs/01_core.ipynb def DivCentered(*c, # Components cls='space-y-4', # Classes for outer div **kwargs # Additional args for outer div ): # Div with components centered in it "Creates a flex div with it's components centered in it" cls=stringify(cls) return Div(cls=(FlexT.block,FlexT.column,FlexT.middle,FlexT.center,cls),**kwargs)(*c) # %% ../nbs/01_core.ipynb def DivLAligned(*c, # Components cls='space-x-4', # Classes for outer div **kwargs # Additional args for outer div ): # Div with components aligned to the left "Creates a flex div with it's components aligned to the left" cls=stringify(cls) return Div(cls=(FlexT.block,FlexT.left,FlexT.middle,cls), **kwargs)(*c) # %% ../nbs/01_core.ipynb def DivRAligned(*c, # Components cls='space-x-4', # Classes for outer div **kwargs # Additional args for outer div ): # Div with components aligned to the right "Creates a flex div with it's components aligned to the right" cls=stringify(cls) return Div(cls=(FlexT.block,FlexT.right,FlexT.middle,cls), **kwargs)(*c) # %% ../nbs/01_core.ipynb def DivVStacked(*c, cls='space-y-4', **kwargs): cls=stringify(cls) return Div(cls=(FlexT.block,FlexT.column,FlexT.middle,cls), **kwargs)(*c) # %% ../nbs/01_core.ipynb def DivHStacked(*c, cls='space-x-4', **kwargs): cls=stringify(cls) return Div(cls=(FlexT.block,FlexT.row,FlexT.middle,cls), **kwargs)(*c) # %% ../nbs/01_core.ipynb class NavT(VEnum): def _generate_next_value_(name, start, count, last_values): return str2ukcls('nav', name) default = auto() primary = auto() secondary = auto() # %% ../nbs/01_core.ipynb def NavContainer(*li, cls=NavT.primary, parent=True, uk_nav=False, #True for default collapsible behavior, see https://franken-ui.dev/docs/nav#component-options for more advanced options **kwargs): return fh.Ul(*li, uk_nav=uk_nav, cls=(f"uk-nav{'' if parent else '-sub'}", stringify(cls)),**kwargs) # %% ../nbs/01_core.ipynb def NavParentLi(*nav_container, cls=(), **kwargs): return fh.Li(*nav_container, cls=('uk-parent', stringify(cls)),**kwargs) def NavDividerLi(*c,cls=(), **kwargs): return fh.Li(*c, cls=('uk-nav-divider', stringify(cls)),**kwargs) def NavHeaderLi(*c,cls=(), **kwargs): return fh.Li(*c, cls=('uk-nav-header', stringify(cls)),**kwargs) def NavSubtitle(*c,cls=TextFont.muted_sm, **kwargs): return fh.Div(*c, cls=('uk-nav-subtitle', stringify(cls)),**kwargs) def NavCloseLi(*c,cls=(), **kwargs): return fh.Li(*c, cls=('uk-drop-close', stringify(cls)),**kwargs) # %% ../nbs/01_core.ipynb def NavBarContainer(*c, cls=(), container_cls=ContainerT.expand, uk_navbar=True, **kwargs): return fh.Div(Container(Div(*c, uk_navbar=uk_navbar),cls=stringify(container_cls)), cls=('',stringify(cls)), **kwargs) #uk-navbar-container def NavBarLSide(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-navbar-left', stringify(cls)), **kwargs) def NavBarRSide(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-navbar-right', stringify(cls)), **kwargs) def NavBarCenter(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-navbar-center',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def NavBarNav(*li, cls=(), **kwargs): return fh.Nav(*li, cls=('uk-navbar-nav', stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def NavBarSubtitle(title, subtitle, cls=(), subtitle_cls=TextFont.muted_sm, **kwargs): return fh.Div(title,fh.Div(subtitle, cls=('uk-navbar-subtitle', stringify(subtitle_cls))), cls=stringify(cls), **kwargs) # %% ../nbs/01_core.ipynb def NavBarNavContainer(*li, cls=NavT.primary, parent=True, uk_nav=False, #True for default collapsible behavior, see https://franken-ui.dev/docs/nav#component-options for more advanced options **kwargs): return Div(cls="uk-navbar-dropdown")(NavContainer(*li, cls=('uk-navbar-dropdown-nav',stringify(cls)), uk_nav=uk_nav, parent=parent, **kwargs)) # %% ../nbs/01_core.ipynb def NavBarParentIcon(): return Span(uk_navbar_parent_icon=True) # %% ../nbs/01_core.ipynb def DropDownNavContainer(*li, cls=NavT.primary, parent=True, uk_nav=False, #True for default collapsible behavior, see https://franken-ui.dev/docs/nav#component-options for more advanced options uk_dropdown=True, **kwargs): return Div(cls = 'uk-drop uk-dropdown',uk_dropdown=uk_dropdown)(NavContainer(*li, cls=('uk-dropdown-nav',stringify(cls)), uk_nav=uk_nav, parent=parent, **kwargs)) # %% ../nbs/01_core.ipynb def TabContainer(*li,cls='', alt=False, **kwargs): cls = stringify(cls) return Ul(cls=(f"uk-tab{'-alt' if alt else ''}",stringify(cls)),**kwargs)(*li) # %% ../nbs/01_core.ipynb class CardT(VEnum): 'Card styles from UIkit' def _generate_next_value_(name, start, count, last_values): return str2ukcls('card', name) default = auto() primary = auto() secondary = auto() danger = auto() # %% ../nbs/01_core.ipynb def CardTitle(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-card-title',stringify(cls)), **kwargs) def CardHeader(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-card-header',stringify(cls)), **kwargs) def CardBody(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-card-body',stringify(cls)), **kwargs) def CardFooter(*c, cls=(), **kwargs): return fh.Div(*c, cls=('uk-card-footer',stringify(cls)), **kwargs) def CardContainer(*c, cls=CardT.default, **kwargs): return fh.Div(*c, cls=('uk-card',stringify(cls)), **kwargs) # %% ../nbs/01_core.ipynb def Card(*c, # Components that go in the body header=None, # Components that go in the header footer=None, # Components that go in the footer body_cls='space-y-6', # classes for the body header_cls=(), # classes for the header footer_cls=(), # classes for the footer cls=(), #class for outermost component **kwargs # classes that for the card itself ): header_cls, footer_cls, body_cls, cls = map(stringify, (header_cls, footer_cls, body_cls, cls)) res = [] if header: res.append(CardHeader(cls=header_cls)(header)) res.append(CardBody(cls=body_cls)(*c)) if footer: res.append(CardFooter(cls=footer_cls)(footer)) return CardContainer(cls=cls, **kwargs)(*res) # %% ../nbs/01_core.ipynb class TableT(VEnum): def _generate_next_value_(name, start, count, last_values): return str2ukcls('table', name) divider = auto() striped = auto() hover = auto() small = auto() large = auto() justify = auto() middle = auto() responsive = auto() # %% ../nbs/01_core.ipynb def Table(*args, cls=(TableT.middle, TableT.divider, TableT.hover, TableT.small), **kwargs): return fh.Table(cls=('uk-table', stringify(cls)), *args, **kwargs) # %% ../nbs/01_core.ipynb def _TableCell(Component, *args, cls=(), shrink=False, expand=False, small=False, **kwargs): cls = stringify(cls) if shrink: cls += ' uk-table-shrink' if expand: cls += ' uk-table-expand' if small: cls += ' uk-table-small' return Component(*args,cls=cls, **kwargs) @delegates(_TableCell, but=['Component']) def Td(*args,**kwargs): return _TableCell(fh.Td, *args, **kwargs) @delegates(_TableCell, but=['Component']) def Th(*args,**kwargs): return _TableCell(fh.Th, *args, **kwargs) def Tr(*cells, cls=(), **kwargs): return fh.Tr(*cells, cls=stringify(cls), **kwargs) def Thead(*rows, cls=(), **kwargs): return fh.Thead(*rows, cls=stringify(cls), **kwargs) def Tbody(*rows, cls=(), sortable=False, **kwargs): return fh.Tbody(*rows, cls=stringify(cls), uk_sortable=sortable, **kwargs) # %% ../nbs/01_core.ipynb def TableFromLists(header_data, body_data, footer_data=None, header_cell_render=Th,body_cell_render=Td, footer_cell_render=Td, cls=(TableT.middle, TableT.divider, TableT.hover, TableT.small), sortable=False, **kwargs): return Table( Thead(Tr(*map(header_cell_render, header_data))), Tbody(*[Tr(*map(body_cell_render, r)) for r in body_data], sortable=sortable), Tfoot(Tr(*map(footer_cell_render, footer_data))) if footer_data else '', cls=stringify(cls), **kwargs) # %% ../nbs/01_core.ipynb def TableFromDicts(header_data:Sequence, body_data:Sequence[dict], footer_data=None, header_cell_render=Th, body_cell_render=lambda k,v : Td(v), footer_cell_render=lambda k,v : Td(v), cls=(TableT.middle, TableT.divider, TableT.hover, TableT.small), sortable=False, **kwargs): return Table( Thead(Tr(*[header_cell_render(h) for h in header_data])), Tbody(*[Tr(*[body_cell_render(k, r.get(k, '')) for k in header_data]) for r in body_data], sortable=sortable), Tfoot(Tr(*[footer_cell_render(k, footer_data.get(k.lower(), '')) for k in header_data])) if footer_data else '', cls=stringify(cls), **kwargs ) # %% ../nbs/01_core.ipynb franken_class_map = { 'h1': 'uk-h1 my-4 mb-4', 'h2': 'uk-h2 my-8', 'h3': 'uk-h3 my-8', 'h4': 'uk-h4 my-8', 'ul': "uk-list uk-list-disc mb-4", 'a': "uk-link", 'p': 'my-1', 'blockquote': "uk-blockquote mb-8", 'hr':'uk-divider-icon my-4', 'table':'uk-table-middle uk-table-divider uk-table-hover uk-table-small', 'ol': 'uk-list-decimal', 'li': 'uk-list-disc', } # %% ../nbs/01_core.ipynb def apply_classes(html_str:str, class_map=None, class_map_mods=None): from lxml import html, etree class_map = ifnone(class_map, franken_class_map) if class_map_mods: class_map = {**class_map, **class_map_mods} html_str = html.fromstring(html_str) for tag, classes in class_map.items(): for element in html_str.xpath(f'//{tag}'): existing_class = element.get('class', '') new_class = f"{existing_class} {classes}".strip() element.set('class', new_class) return etree.tostring(html_str, encoding='unicode', method='html') # %% ../nbs/01_core.ipynb def render_md(md_content, class_map=None, class_map_mods=None): try: import markdown2 except ImportError: raise ImportError("Install 'markdown2' to use the 'render_md' function") html_content = markdown2.markdown(md_content, extras={'fenced-code-blocks':None})#, 'html-classes': franken_class_map}) return NotStr(apply_classes(html_content, class_map, class_map_mods))404: Not Found404: Not Found404: Not Found404: Not Found404: Not Found404: Not Found404: Not Found404: Not Found404: Not FoundThings 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.# Web Devs Quickstart ## Installation ``` bash pip install python-fasthtml ``` ## A Minimal Application A minimal FastHTML application looks something like this:
**main.py** ``` python from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) serve() ```
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()` 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)
> **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).
## A Minimal Charting Application The [`Script`](https://AnswerDotAI.github.io/fasthtml/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:
**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() ```
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).
> **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.
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:
**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() ```
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.
> **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/).
## 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.
**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() ```
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.
**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() ```
Line 4 By setting `pico` to `False`, FastHTML will not include `pico.min.css`. Line 7 This will generate an HTML `` tag for sourcing the css for Sakura. Line 8 If you want an inline styles, the `Style()` function will put the result into the HTML. ## Other Static Media File Locations As you saw, [`Script`](https://AnswerDotAI.github.io/fasthtml/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

Hello World

This is a hero statement

``` ### 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

Dashboard

  • 0
  • 1
  • 2

Some content

``` ### 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

Hello World

This is a hero statement

``` ## 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) ``` FastHTML is awesome

FastHTML is awesome

The fastest way to create web apps in Python

## 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
``` 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='john@example.com', phone='123456789', age=5) profile ``` Profile(email='john@example.com', phone='123456789', age=5) Then add that data to the `profile_form` using FastHTML’s [`fill_form`](https://AnswerDotAI.github.io/fasthtml/api/components.html#fill_form) class: ``` python fill_form(profile_form, profile) ``` ``` html
``` ### 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='john@example.com', 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/john@example.com").text) ``` Line 3 Fetch the profile using the profile table’s `email` primary key Line 4 Fill the form for display. Profile for john@example.com

Profile for john@example.com

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='john@example.com', 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. Profile for john@example.com

Profile for john@example.com

## 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("

Hello World

", "This is a hero statement") ) ``` ``` html
Hero(title='

Hello World

', statement='This is a hero statement')
``` ``` python # This will display the HTML as text on your page Div("Let's include some HTML here:
Some HTML
") ``` ``` html
Let's include some HTML here: <div>Some HTML</div>
``` ``` python # Keep the string untouched, will be rendered on the page Div(NotStr("

Some HTML

")) ``` ``` html

Some HTML

``` ## Custom exception handlers FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the `` 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()` 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) ``` FastHTML page

Set to 2024-09-26 15:33:48.141869

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. ## 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://AnswerDotAI.github.io/fasthtml/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/htmx-ext-sse@2.2.1/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://AnswerDotAI.github.io/fasthtml/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. This examples below are for uploading files to the hosting server, with information about the uploaded file presented to the user.
> **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).
### 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://AnswerDotAI.github.io/fasthtml/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://AnswerDotAI.github.io/fasthtml/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.
+++ 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.
| 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) |
## Additional Attribute Reference {#attributes-additional} All other attributes available in htmx.
| 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)) |
## CSS Class Reference {#classes}
| 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).
## HTTP Header Reference {#headers} ### Request Headers Reference {#request_headers}
| 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
### Response Headers Reference {#response_headers}
| 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
## Event Reference {#events}
| 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: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
## JavaScript API Reference {#api}
| 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
## Configuration Reference {#config} Htmx has some configuration options that can be accessed either programmatically or declaratively. They are listed below:
| 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.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). |
You can set them directly in javascript, or you can use a `meta` tag: ```html ```
# 🗿 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)) ## 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 ` ``` 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 `` in your `` Or, 🌐 via CDN: `` ## ⚡ Usage ### 🔍️ 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 ` ``` 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 ` red
green
green
green
yellow
blue
green
green
red
green
green
green
yellow
blue
green
green
``` ### 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
``` ## 🔎 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 `