text
stringlengths
27
54.3k
url
stringlengths
31
137
page_name
stringlengths
7
59
from fh_altair import altair2fasthml, altair_headers from fasthtml.common import * import numpy as np import pandas as pd import altair as alt app, rt = fast_app(hdrs=(altair_headers,)) count = 0 plotdata = [] def generate_chart(): global plotdata if len(plotdata) > 250: plotdata = plotdata[-250:] pltr = pd.DataFrame({'y': plotdata, 'x': range(len(plotdata))}) chart = alt.Chart(pltr).mark_line().encode(x='x', y='y').properties(width=400, height=200) return altair2fasthml(chart) @rt def index(): return Title("Altair Demo"), Main( H1("Altair Demo"), Div(id="chart"), Button("Increment", get=increment, hx_target="#chart", hx_swap="innerHTML"), style="margin: 20px" ) @rt def increment(): global plotdata, count count += 1 plotdata.append(np.random.exponential(1)) return Div( generate_chart(), P(f"You have pressed the button {count} times."), ) serve()
https://gallery.fastht.ml/code/visualizations/altair_charts
FastHTML page
import plotly.express as px from fasthtml.common import * # Add the Plotly library to the headers app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.24.1.min.js"),)) def create_scatter_plot(): # Create simple scatter plot with 5 points fig = px.scatter( x=[1, 2, 3, 4, 5], y=[2, 4, 1, 3, 5], labels={"x": "X Value", "y": "Y Value"} ) return fig.to_json() @rt def index(): return Titled("Interactive Plotly Selection", P("Click any point to see its x-value!"), # point-info will be updated based on what is clicked Div(id="point-info")(P("No point selected yet")), # plotly-container will be updated with the plot Div(id="plotly-container"), # Initialize the plot Script( f""" // All the plot data is given in json form by `create_scatter_plot` const plotData = {create_scatter_plot()}; // Create the plot with that data in location with id `plotly-container` Plotly.newPlot('plotly-container', plotData.data, plotData.layout); // Add click event handler // Get thing with id `plotly-container`, and on plotly_click event, // run the function document.getElementById('plotly-container').on('plotly_click', function(data) {{ // Get the first point clicked const point = data.points[0]; // Make HTMX request when point is clicked with the x-value htmx.ajax('GET', `point/${{point.x}}`, {{target: '#point-info'}}); }}); """ )) @rt("/point/{x_val}") def get(x_val: float): # Return the x-value of the point clicked to the UI! return P(Strong(f"You clicked the point with x-value: {x_val}")) serve()
https://gallery.fastht.ml/code/visualizations/plotly_selections
FastHTML page
Click the circle 3 times You have clicked 0 times
https://gallery.fastht.ml/app/svg/find_and_click/
FastHTML page
Click and drag an SVG rectangle with D3
https://gallery.fastht.ml/app/svg/click_and_drag/
FastHTML page
from fasthtml.common import * import numpy as np, seaborn as sns, matplotlib.pylab as plt app,rt = fast_app() data = np.random.rand(4,10) def fh_svg(func): "show svg in fasthtml decorator" def wrapper(*args, **kwargs): func(*args, **kwargs) # calls plotting function f = io.StringIO() # create a buffer to store svg data plt.savefig(f, format='svg', bbox_inches='tight') f.seek(0) # beginning of file svg_data = f.getvalue() plt.close() return NotStr(svg_data) return wrapper @fh_svg def plot_heatmap(matrix,figsize=(6,7),**kwargs): plt.figure(figsize=figsize) sns.heatmap(matrix, cmap='coolwarm', annot=False,**kwargs) @rt def index(): return Div(Label(H3("Heatmap Columns"), _for='n_cols'), Input(type="range", min="1", max="10", value="1", get=update_heatmap, hx_target="#plot", id='n_cols'), Div(id="plot")) @app.get("/update_charts") def update_heatmap(n_cols:int): svg_plot = plot_heatmap(data[:,:n_cols]) return svg_plot serve()
https://gallery.fastht.ml/split/visualizations/seaborn_svg
FastHTML page
from fh_altair import altair2fasthml, altair_headers from fasthtml.common import * import numpy as np import pandas as pd import altair as alt app, rt = fast_app(hdrs=(altair_headers,)) count = 0 plotdata = [] def generate_chart(): global plotdata if len(plotdata) > 250: plotdata = plotdata[-250:] pltr = pd.DataFrame({'y': plotdata, 'x': range(len(plotdata))}) chart = alt.Chart(pltr).mark_line().encode(x='x', y='y').properties(width=400, height=200) return altair2fasthml(chart) @rt def index(): return Title("Altair Demo"), Main( H1("Altair Demo"), Div(id="chart"), Button("Increment", get=increment, hx_target="#chart", hx_swap="innerHTML"), style="margin: 20px" ) @rt def increment(): global plotdata, count count += 1 plotdata.append(np.random.exponential(1)) return Div( generate_chart(), P(f"You have pressed the button {count} times."), ) serve()
https://gallery.fastht.ml/split/visualizations/altair_charts
FastHTML page
Hello, world! I am a chatbot that can answer questions about the world. I have always wondered why the sky is blue. Can you tell me? The sky is blue because of the atmosphere. As white light passes through air molecules cause it to scatter. Because of the wavelengths, blue light is scattered the most.
https://gallery.fastht.ml/app/widgets/chat_bubble/
FastHTML page
from fasthtml.common import * from collections import deque app, rt = fast_app(exts='ws') # All messages here, but only most recent 15 are stored messages = deque(maxlen=15) users = {} # Takes all the messages and renders them box_style = "border: 1px solid #ccc; border-radius: 10px; padding: 10px; margin: 5px 0;" def render_messages(messages): return Div(*[Div(m, style=box_style) for m in messages], id='msg-list') # Input field is reset via hx_swap_oob after submitting a message def mk_input(): return Input(id='msg', placeholder="Type your message", value="", hx_swap_oob="true") @rt def index(): return Titled("Leave a message for others!"),Div( Form(mk_input(), ws_send=True), # input field P("Leave a message for others!"), Div(render_messages(messages),id='msg-list'), # All the Messages hx_ext='ws', ws_connect='ws') # Use a web socket def on_connect(ws, send): users[id(ws)] = send def on_disconnect(ws):users.pop(id(ws),None) @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str,send): await send(mk_input()) # reset the input field immediately messages.appendleft(msg) # New messages first for u in users.values(): # Get `send` function for a user await u(render_messages(messages)) # Send the message to that user serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/web_sockets
FastHTML page
from fasthtml.common import * from collections import deque app, rt = fast_app(exts='ws') # All messages here, but only most recent 15 are stored messages = deque(maxlen=15) users = {} # Takes all the messages and renders them box_style = "border: 1px solid #ccc; border-radius: 10px; padding: 10px; margin: 5px 0;" def render_messages(messages): return Div(*[Div(m, style=box_style) for m in messages], id='msg-list') # Input field is reset via hx_swap_oob after submitting a message def mk_input(): return Input(id='msg', placeholder="Type your message", value="", hx_swap_oob="true") @rt def index(): return Titled("Leave a message for others!"),Div( Form(mk_input(), ws_send=True), # input field P("Leave a message for others!"), Div(render_messages(messages),id='msg-list'), # All the Messages hx_ext='ws', ws_connect='ws') # Use a web socket def on_connect(ws, send): users[id(ws)] = send def on_disconnect(ws):users.pop(id(ws),None) @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str,send): await send(mk_input()) # reset the input field immediately messages.appendleft(msg) # New messages first for u in users.values(): # Get `send` function for a user await u(render_messages(messages)) # Send the message to that user serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/web_sockets
FastHTML page
from fasthtml.common import * app,rt = fast_app() def mk_row(name, email): return Tr(Td(name), Td(email)), @rt def index(): return Div(H2("Contacts"), Table( Thead(Tr(map(Th, ("Name", "Email")))), Tbody( mk_row("Audrey", "[email protected]"), mk_row("Uma" , "[email protected]"), mk_row("Daniel", "[email protected]")), id="contacts-table"), H2("Add a Contact"), Form( Label("Name", Input(name="name", type="text")), Label("Email", Input(name="email", type="email")), Button("Save"), # When button is clicked run contacts route/function post=contacts, # Send the results of contacts to #contacts-table hx_target="#contacts-table", # Add the new row to the end of the target hx_swap="beforeend", # Reset the form hx_on__after_request="this.reset()")) @rt def contacts(name:str,email:str): print(f"Adding {name} and {email} to table") return mk_row(name,email) serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/update_other_content
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt def index(): return Titled('Try editing fields:', Grid(Div( Form(post="submit", hx_target="#result", hx_trigger="input delay:200ms")( Select(Option("One"), Option("Two"), id="select"), Input(value='j', id="name", placeholder="Name"), Input(value='h', id="email", placeholder="Email"))), Div(id="result"))) @rt def submit(d:dict): return Div(*[Div(P(Strong(k),': ',v)) for k,v in d.items()]) serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/two_column_grid
FastHTML page
from fasthtml.common import * app,rt = fast_app() def mk_row(name, email): return Tr(Td(name), Td(email)), @rt def index(): return Div(H2("Contacts"), Table( Thead(Tr(map(Th, ("Name", "Email")))), Tbody( mk_row("Audrey", "[email protected]"), mk_row("Uma" , "[email protected]"), mk_row("Daniel", "[email protected]")), id="contacts-table"), H2("Add a Contact"), Form( Label("Name", Input(name="name", type="text")), Label("Email", Input(name="email", type="email")), Button("Save"), # When button is clicked run contacts route/function post=contacts, # Send the results of contacts to #contacts-table hx_target="#contacts-table", # Add the new row to the end of the target hx_swap="beforeend", # Reset the form hx_on__after_request="this.reset()")) @rt def contacts(name:str,email:str): print(f"Adding {name} and {email} to table") return mk_row(name,email) serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/update_other_content
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt def index(): return Titled('Try editing fields:', Grid(Div( Form(post="submit", hx_target="#result", hx_trigger="input delay:200ms")( Select(Option("One"), Option("Two"), id="select"), Input(value='j', id="name", placeholder="Name"), Input(value='h', id="email", placeholder="Email"))), Div(id="result"))) @rt def submit(d:dict): return Div(*[Div(P(Strong(k),': ',v)) for k,v in d.items()]) serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/two_column_grid
FastHTML page
from fasthtml.common import * app, rt = fast_app() content = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet volutpat tellus, in tincidunt magna. Vivamus congue posuere ligula a cursus. Sed efficitur tortor quis nisi mollis, eu aliquet nunc malesuada. Nulla semper lacus lacus, non sollicitudin velit mollis nec. Phasellus pharetra lobortis nisi ac eleifend. Suspendisse commodo dolor vitae efficitur lobortis. Nulla a venenatis libero, a congue nibh. Fusce ac pretium orci, in vehicula lorem. Aenean lacus ipsum, molestie quis magna id, lacinia finibus neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas ac ex luctus, dictum erat ut, bibendum enim. Curabitur et est quis sapien consequat fringilla a sit amet purus.""" def mk_button(show): return Button("Hide" if show else "Show", hx_get="toggle?show=" + ("False" if show else "True"), hx_target="#content", id="toggle", hx_swap_oob="outerHTML") @rt def index(): return Div(mk_button(False), Div(id="content")) @rt def toggle(show: bool): return Div( Div(mk_button(show)), Div(content if show else ''))
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/show_hide
FastHTML page
from fasthtml.common import * app, rt = fast_app() content = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet volutpat tellus, in tincidunt magna. Vivamus congue posuere ligula a cursus. Sed efficitur tortor quis nisi mollis, eu aliquet nunc malesuada. Nulla semper lacus lacus, non sollicitudin velit mollis nec. Phasellus pharetra lobortis nisi ac eleifend. Suspendisse commodo dolor vitae efficitur lobortis. Nulla a venenatis libero, a congue nibh. Fusce ac pretium orci, in vehicula lorem. Aenean lacus ipsum, molestie quis magna id, lacinia finibus neque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Interdum et malesuada fames ac ante ipsum primis in faucibus. Maecenas ac ex luctus, dictum erat ut, bibendum enim. Curabitur et est quis sapien consequat fringilla a sit amet purus.""" def mk_button(show): return Button("Hide" if show else "Show", hx_get="toggle?show=" + ("False" if show else "True"), hx_target="#content", id="toggle", hx_swap_oob="outerHTML") @rt def index(): return Div(mk_button(False), Div(id="content")) @rt def toggle(show: bool): return Div( Div(mk_button(show)), Div(content if show else ''))
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/show_hide
FastHTML page
from fasthtml.common import * import random app, rt = fast_app() def get_progress(percent_complete: int): "Simulate progress check" return percent_complete + random.random()/3 @rt def index(): return (Div(H3("Start the job to see progress!"),id='progress_bar'), Button("Start Job",post=update_status, hx_target="#progress_bar")) @rt def update_status(): "Start job and progress bar" return progress_bar(percent_complete=0) @rt def update_progress(percent_complete: float): # Check if done if percent_complete >= 1: return H3("Job Complete!", id="progress_bar") # get progress percent_complete = get_progress(percent_complete) # Update progress bar return progress_bar(percent_complete) def progress_bar(percent_complete: float): return Progress(id="progress_bar",value=percent_complete, get=update_progress,hx_target="#progress_bar",hx_trigger="every 500ms", hx_vals=f"js:'percent_complete': '{percent_complete}'") serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/progress_bar
FastHTML page
Click any point to see its x-value!
https://gallery.fastht.ml/app/visualizations/plotly_selections/
Interactive Plotly Selection
from fasthtml.common import * import random app, rt = fast_app() def get_progress(percent_complete: int): "Simulate progress check" return percent_complete + random.random()/3 @rt def index(): return (Div(H3("Start the job to see progress!"),id='progress_bar'), Button("Start Job",post=update_status, hx_target="#progress_bar")) @rt def update_status(): "Start job and progress bar" return progress_bar(percent_complete=0) @rt def update_progress(percent_complete: float): # Check if done if percent_complete >= 1: return H3("Job Complete!", id="progress_bar") # get progress percent_complete = get_progress(percent_complete) # Update progress bar return progress_bar(percent_complete) def progress_bar(percent_complete: float): return Progress(id="progress_bar",value=percent_complete, get=update_progress,hx_target="#progress_bar",hx_trigger="every 500ms", hx_vals=f"js:'percent_complete': '{percent_complete}'") serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/progress_bar
FastHTML page
from base64 import b64encode from fasthtml.common import * app, rt = fast_app() @rt def index(): inp = Card( H3("Drag and drop images here", style="text-align: center;"), # HTMX for uploading multiple images Input(type="file",name="images", multiple=True, required=True, # Call the upload route on change post=upload, hx_target="#image-list", hx_swap="afterbegin", hx_trigger="change", # encoding for multipart hx_encoding="multipart/form-data",accept="image/*"), # Make a nice border to show the drop zone style="border: 2px solid #ccc; border-radius: 8px;",) return Titled("Multi Image Upload", inp, H3("πŸ‘‡ Uploaded images πŸ‘‡", style="text-align: center;"), Div(id="image-list")) async def ImageCard(image): contents = await image.read() # Create a base64 string img_data = f"data:{image.content_type};base64,{b64encode(contents).decode()}" # Create a card with the image return Card(H4(image.filename), Img(src=img_data, alt=image.filename)) @rt async def upload(images: list[UploadFile]): # Create a grid filled with 1 image card per image return Grid(*[await ImageCard(image) for image in images]) serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/multi_image_upload
FastHTML page
from base64 import b64encode from fasthtml.common import * app, rt = fast_app() @rt def index(): inp = Card( H3("Drag and drop images here", style="text-align: center;"), # HTMX for uploading multiple images Input(type="file",name="images", multiple=True, required=True, # Call the upload route on change post=upload, hx_target="#image-list", hx_swap="afterbegin", hx_trigger="change", # encoding for multipart hx_encoding="multipart/form-data",accept="image/*"), # Make a nice border to show the drop zone style="border: 2px solid #ccc; border-radius: 8px;",) return Titled("Multi Image Upload", inp, H3("πŸ‘‡ Uploaded images πŸ‘‡", style="text-align: center;"), Div(id="image-list")) async def ImageCard(image): contents = await image.read() # Create a base64 string img_data = f"data:{image.content_type};base64,{b64encode(contents).decode()}" # Create a card with the image return Card(H4(image.filename), Img(src=img_data, alt=image.filename)) @rt async def upload(images: list[UploadFile]): # Create a grid filled with 1 image card per image return Grid(*[await ImageCard(image) for image in images]) serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/multi_image_upload
FastHTML page
from fasthtml.common import * from monsterui.all import * import asyncio app, rt = fast_app(hdrs=Theme.blue.headers()) @rt def index(): return Titled("Loading Demo", # Button to trigger an HTMX request Button("Load", id='load', # Trigger HTMX request to add content to #content get=load, hx_target='#content', hx_swap='beforeend', # While request in flight, show loading indicator hx_indicator='#loading'), # A place to put content from request Div(id='content'), # Loading indicator ready for htmx use # For more options see https://monsterui.answer.ai/api_ref/docs_loading Loading(id='loading', htmx_indicator=True)) @rt async def load(): # Sleep for a second to simulate a long request await asyncio.sleep(1) return P("Loading Demo") serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/loading_indicator
FastHTML page
Leave a message for others!
https://gallery.fastht.ml/app/dynamic_user_interface_(htmx)/web_sockets/
Leave a message for others!
from fasthtml.common import * import re ################ ### FastHTML ### ################ app, rt = fast_app() @rt def index(): return Form(post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')( # Calls /email route to validate email Div(hx_target='this', hx_swap='outerHTML')( Label(_for='email')('Email Address'), Input(type='text', name='email', id='email', post='email')), # Calls /cool route to validate cool Div(hx_target='this', hx_swap='outerHTML')( Label(_for='cool')('Is this cool?'), Input(type='text', name='cool', id='cool', post='cool')), # Calls /coolscale route to validate coolscale Div(hx_target='this', hx_swap='outerHTML')( Label(_for='CoolScale')('How cool (scale of 1 - 10)?'), Input(type='number', name='CoolScale', id='CoolScale', post='coolscale')), # Submits the form which calls /submit route to validate whole form Div(id='submit-btn-container')( Button(type='submit', id='submit-btn',)('Submit'))) ### Field Validation Routing ### # Validates the field and generates FastHTML with appropriate validation and template function @rt def email(email: str): return inputTemplate('Email Address', 'email', email, validate_email(email)) @rt def cool(cool: str): return inputTemplate('Is this cool?', 'cool', cool, validate_cool(cool)) @rt def coolscale(CoolScale: int): return inputTemplate('How cool (scale of 1 - 10)?', 'CoolScale', CoolScale, validate_coolscale(CoolScale), input_type='number') @rt def submit(email: str, cool: str, CoolScale: int): # Validates all fields in the form errors = {'email': validate_email(email), 'cool': validate_cool(cool), 'coolscale': validate_coolscale(CoolScale) } # Removes the None values from the errors dictionary (No errors) errors = {k: v for k, v in errors.items() if v is not None} # Return Button with error message if they exist return Div(id='submit-btn-container')( Button(type='submit', id='submit-btn', post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')('Submit'), *[Div(error, style='color: red;') for error in errors.values()]) ######################## ### Validation Logic ### ######################## def validate_email(email: str): # Check if email address is a valid one email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' if not re.match(email_regex, email): return "Please enter a valid email address" # Check if email address is already taken (in this case only [email protected] will pass) elif email != "[email protected]": return "That email is already taken. Please enter another email (only [email protected] will pass)." # If no errors, return None (default of python) def validate_cool(cool: str): if cool.lower() not in ["yes", "definitely"]: return "Yes or definitely are the only correct answers" def validate_coolscale(CoolScale: int): if CoolScale < 1 or CoolScale > 10: return "Please enter a number between 1 and 10" ###################### ### HTML Templates ### ###################### def inputTemplate(label, name, val, errorMsg=None, input_type='text'): # Generic template for replacing the input field and showing the validation message return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")( Label(label), # Creates label for the input field Input(name=name,type=input_type,value=f'{val}',post=f'{name.lower()}'), # Creates input field Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/inline_validation
FastHTML page
from fasthtml.common import * import uuid column_names = ('name', 'email', 'id') def generate_contact(id: int) -> Dict[str, str]: return {'name': 'Agent Smith', 'email': f'void{str(id)}@matrix.com', 'id': str(uuid.uuid4()) } def generate_table_row(row_num: int) -> Tr: contact = generate_contact(row_num) return Tr(*[Td(contact[key]) for key in column_names]) def generate_table_part(part_num: int = 1, size: int = 20) -> Tuple[Tr]: paginated = [generate_table_row((part_num - 1) * size + i) for i in range(size)] paginated[-1].attrs.update({ 'get': f'page?idx={part_num + 1}', 'hx-trigger': 'revealed', 'hx-swap': 'afterend'}) return tuple(paginated) app, rt = fast_app() @rt def index(): return Titled('Infinite Scroll', Div(Table( Thead(Tr(*[Th(key) for key in column_names])), Tbody(generate_table_part(1))))) @rt def page(idx:int|None = 0): return generate_table_part(idx)
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/infinite_scroll
FastHTML page
from fasthtml.common import * import re ################ ### FastHTML ### ################ app, rt = fast_app() @rt def index(): return Form(post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')( # Calls /email route to validate email Div(hx_target='this', hx_swap='outerHTML')( Label(_for='email')('Email Address'), Input(type='text', name='email', id='email', post='email')), # Calls /cool route to validate cool Div(hx_target='this', hx_swap='outerHTML')( Label(_for='cool')('Is this cool?'), Input(type='text', name='cool', id='cool', post='cool')), # Calls /coolscale route to validate coolscale Div(hx_target='this', hx_swap='outerHTML')( Label(_for='CoolScale')('How cool (scale of 1 - 10)?'), Input(type='number', name='CoolScale', id='CoolScale', post='coolscale')), # Submits the form which calls /submit route to validate whole form Div(id='submit-btn-container')( Button(type='submit', id='submit-btn',)('Submit'))) ### Field Validation Routing ### # Validates the field and generates FastHTML with appropriate validation and template function @rt def email(email: str): return inputTemplate('Email Address', 'email', email, validate_email(email)) @rt def cool(cool: str): return inputTemplate('Is this cool?', 'cool', cool, validate_cool(cool)) @rt def coolscale(CoolScale: int): return inputTemplate('How cool (scale of 1 - 10)?', 'CoolScale', CoolScale, validate_coolscale(CoolScale), input_type='number') @rt def submit(email: str, cool: str, CoolScale: int): # Validates all fields in the form errors = {'email': validate_email(email), 'cool': validate_cool(cool), 'coolscale': validate_coolscale(CoolScale) } # Removes the None values from the errors dictionary (No errors) errors = {k: v for k, v in errors.items() if v is not None} # Return Button with error message if they exist return Div(id='submit-btn-container')( Button(type='submit', id='submit-btn', post='submit', hx_target='#submit-btn-container', hx_swap='outerHTML')('Submit'), *[Div(error, style='color: red;') for error in errors.values()]) ######################## ### Validation Logic ### ######################## def validate_email(email: str): # Check if email address is a valid one email_regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' if not re.match(email_regex, email): return "Please enter a valid email address" # Check if email address is already taken (in this case only [email protected] will pass) elif email != "[email protected]": return "That email is already taken. Please enter another email (only [email protected] will pass)." # If no errors, return None (default of python) def validate_cool(cool: str): if cool.lower() not in ["yes", "definitely"]: return "Yes or definitely are the only correct answers" def validate_coolscale(CoolScale: int): if CoolScale < 1 or CoolScale > 10: return "Please enter a number between 1 and 10" ###################### ### HTML Templates ### ###################### def inputTemplate(label, name, val, errorMsg=None, input_type='text'): # Generic template for replacing the input field and showing the validation message return Div(hx_target='this', hx_swap='outerHTML', cls=f"{errorMsg if errorMsg else 'Valid'}")( Label(label), # Creates label for the input field Input(name=name,type=input_type,value=f'{val}',post=f'{name.lower()}'), # Creates input field Div(f'{errorMsg}', style='color: red;') if errorMsg else None) # Creates red error message below if there is an error
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/inline_validation
FastHTML page
from fasthtml.common import * from monsterui.all import * import asyncio app, rt = fast_app(hdrs=Theme.blue.headers()) @rt def index(): return Titled("Loading Demo", # Button to trigger an HTMX request Button("Load", id='load', # Trigger HTMX request to add content to #content get=load, hx_target='#content', hx_swap='beforeend', # While request in flight, show loading indicator hx_indicator='#loading'), # A place to put content from request Div(id='content'), # Loading indicator ready for htmx use # For more options see https://monsterui.answer.ai/api_ref/docs_loading Loading(id='loading', htmx_indicator=True)) @rt async def load(): # Sleep for a second to simulate a long request await asyncio.sleep(1) return P("Loading Demo") serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/loading_indicator
FastHTML page
from fasthtml.common import * import uuid column_names = ('name', 'email', 'id') def generate_contact(id: int) -> Dict[str, str]: return {'name': 'Agent Smith', 'email': f'void{str(id)}@matrix.com', 'id': str(uuid.uuid4()) } def generate_table_row(row_num: int) -> Tr: contact = generate_contact(row_num) return Tr(*[Td(contact[key]) for key in column_names]) def generate_table_part(part_num: int = 1, size: int = 20) -> Tuple[Tr]: paginated = [generate_table_row((part_num - 1) * size + i) for i in range(size)] paginated[-1].attrs.update({ 'get': f'page?idx={part_num + 1}', 'hx-trigger': 'revealed', 'hx-swap': 'afterend'}) return tuple(paginated) app, rt = fast_app() @rt def index(): return Titled('Infinite Scroll', Div(Table( Thead(Tr(*[Th(key) for key in column_names])), Tbody(generate_table_part(1))))) @rt def page(idx:int|None = 0): return generate_table_part(idx)
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/infinite_scroll
FastHTML page
from fasthtml.common import * app, rt = fast_app() # This represents the data we are rendering # The data could original from a database, or any other datastore @dataclass class Contact: # Data points id: int name: str email: str status: str def __ft__(self): # __ft__ method is used by FastHTML to render an item in the UI # By defining this, a `Contact` will show up as a table row automatically return Tr( *map(Td, (self.name, self.email, self.status)), Td(Button('Delete', hx_delete=delete.to(id=self.id).lstrip('/'), # Give a confirmation prompt before deleting hx_confirm="Are you sure?", # Target the closest row (The one you clicked on) hx_target="closest tr", # Removes the row with htmx hx_swap="delete"))) # Sample data # Often this would come from a database contacts = [{'id':1, 'name': "Bob Deer", 'email': "[email protected]", 'status': "Active" }, {'id':2, 'name': "Jon Doe", 'email': "[email protected]", 'status': "Inactive"}, {'id':3, 'name': "Jane Smith",'email': "[email protected]",'status': "Active" }] @rt def index(sess): # Save a copy of contacts in your session # This is the demo doesn't conflict with other users sess['contacts'] = contacts # Create initial table return Table( Thead(Tr(*map(Th, ["Name", "Email", "Status", ""]))), # A `Contact` object is rendered as a row automatically using the `__ft__` method Tbody(*(Contact(**x) for x in sess['contacts']))) @app.delete def delete(id: int, sess): sess['contacts'] = [c for c in sess['contacts'] if c['id'] != id] serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/delete_row
FastHTML page
from fasthtml.common import * app, rt = fast_app() # This represents the data we are rendering # The data could original from a database, or any other datastore @dataclass class Contact: # Data points id: int name: str email: str status: str def __ft__(self): # __ft__ method is used by FastHTML to render an item in the UI # By defining this, a `Contact` will show up as a table row automatically return Tr( *map(Td, (self.name, self.email, self.status)), Td(Button('Delete', hx_delete=delete.to(id=self.id).lstrip('/'), # Give a confirmation prompt before deleting hx_confirm="Are you sure?", # Target the closest row (The one you clicked on) hx_target="closest tr", # Removes the row with htmx hx_swap="delete"))) # Sample data # Often this would come from a database contacts = [{'id':1, 'name': "Bob Deer", 'email': "[email protected]", 'status': "Active" }, {'id':2, 'name': "Jon Doe", 'email': "[email protected]", 'status': "Inactive"}, {'id':3, 'name': "Jane Smith",'email': "[email protected]",'status': "Active" }] @rt def index(sess): # Save a copy of contacts in your session # This is the demo doesn't conflict with other users sess['contacts'] = contacts # Create initial table return Table( Thead(Tr(*map(Th, ["Name", "Email", "Status", ""]))), # A `Contact` object is rendered as a row automatically using the `__ft__` method Tbody(*(Contact(**x) for x in sess['contacts']))) @app.delete def delete(id: int, sess): sess['contacts'] = [c for c in sess['contacts'] if c['id'] != id] serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/delete_row
FastHTML page
Start the job to see progress!
https://gallery.fastht.ml/app/dynamic_user_interface_(htmx)/progress_bar/
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt def index():return Titled( "Custom Keybindings with HTMX", render_button("DO IT (Press `Shift + u`)")) @rt def doit(): return render_button("πŸ˜€ DID IT! ") def render_button(text): return Button(text, # Auto-focus on load autofocus=True, # Activate with click or U key as long as focus is in body hx_trigger="click, keyup[key=='U'] from:body", get=doit) serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/custom_keybindings
FastHTML page
from fasthtml.common import * app, rt = fast_app() @rt def index():return Titled( "Custom Keybindings with HTMX", render_button("DO IT (Press `Shift + u`)")) @rt def doit(): return render_button("πŸ˜€ DID IT! ") def render_button(text): return Button(text, # Auto-focus on load autofocus=True, # Activate with click or U key as long as focus is in body hx_trigger="click, keyup[key=='U'] from:body", get=doit) serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/custom_keybindings
FastHTML page
from fasthtml.common import * from monsterui.all import * app, rt = fast_app(hdrs=Theme.blue.headers()) @rt def index(): return Container(H1('Configurable Select'), mk_form()) @rt def mk_form(add_option:str=None, options:str='isaac,hamel,curtis'): opts = options.split(',') if add_option: opts.append(add_option) return Form( # fh-frankenui helper that adds both a form label and input # and does proper linking with for, id, and name automatically LabelInput("Add an Option", id="add_option"), Button("Add"), # fh-frankenui select allows for search boxes Select(map(Option, opts), searchable=True), # When the "Add" button is pressed, make a new form get=mk_form, # Store options state in DOM hx_vals={"options": ','.join(opts)}, # Replace the whole form hx_swap="outerHTML") serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/configurable_select
FastHTML page
from uuid import uuid4 from fasthtml.common import * app, rt = fast_app() agent_num = 0 @rt def add_row(): global agent_num agent_num += 1 return Tr(map(Td, ( f"Agent Smith {agent_num}", f"smith{agent_num}@matrix.com", uuid4()))) @rt def index(): first_row = add_row() return Div( H1("Click to Load"), P("Dynamically add rows to a table using HTMX."), Table(Tr(map(Th, ("Name", "Email", "ID"))), first_row, id='tbl'), Button("Load More...", get=add_row, hx_target="#tbl", hx_swap="beforeend"), style="text-align: center;") serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/click_to_load
FastHTML page
from uuid import uuid4 from fasthtml.common import * app, rt = fast_app() agent_num = 0 @rt def add_row(): global agent_num agent_num += 1 return Tr(map(Td, ( f"Agent Smith {agent_num}", f"smith{agent_num}@matrix.com", uuid4()))) @rt def index(): first_row = add_row() return Div( H1("Click to Load"), P("Dynamically add rows to a table using HTMX."), Table(Tr(map(Th, ("Name", "Email", "ID"))), first_row, id='tbl'), Button("Load More...", get=add_row, hx_target="#tbl", hx_swap="beforeend"), style="text-align: center;") serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/click_to_load
FastHTML page
from fasthtml.common import * from monsterui.all import * app, rt = fast_app(hdrs=Theme.blue.headers()) @rt def index(): return Container(H1('Configurable Select'), mk_form()) @rt def mk_form(add_option:str=None, options:str='isaac,hamel,curtis'): opts = options.split(',') if add_option: opts.append(add_option) return Form( # fh-frankenui helper that adds both a form label and input # and does proper linking with for, id, and name automatically LabelInput("Add an Option", id="add_option"), Button("Add"), # fh-frankenui select allows for search boxes Select(map(Option, opts), searchable=True), # When the "Add" button is pressed, make a new form get=mk_form, # Store options state in DOM hx_vals={"options": ','.join(opts)}, # Replace the whole form hx_swap="outerHTML") serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/configurable_select
FastHTML page
from fasthtml.common import * app, rt = fast_app() flds = dict(firstName='First Name', lastName='Last Name', email='Email') @dataclass class Contact: firstName:str; lastName:str; email:str; edit:bool=False def __ft__(self): def item(k, v): val = getattr(self,v) return Div(Label(Strong(k), val), Hidden(val, id=v)) return Form( *(item(v,k) for k,v in flds.items()), Button('Click To Edit'), post='form', hx_swap='outerHTML') contacts = [Contact('Joe', 'Blow', '[email protected]')] @rt def index(): return contacts[0] @rt def form(c:Contact): def item(k,v): return Div(Label(k), Input(name=v, value=getattr(c,v))) return Form( *(item(v,k) for k,v in flds.items()), Button('Submit', name='btn', value='submit'), Button('Cancel', name='btn', value='cancel'), post="contact", hx_swap='outerHTML' ) @rt def contact(c:Contact, btn:str): if btn=='submit': contacts[0] = c return contacts[0]
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/click_to_edit
FastHTML page
from fasthtml.common import * app, rt = fast_app() flds = dict(firstName='First Name', lastName='Last Name', email='Email') @dataclass class Contact: firstName:str; lastName:str; email:str; edit:bool=False def __ft__(self): def item(k, v): val = getattr(self,v) return Div(Label(Strong(k), val), Hidden(val, id=v)) return Form( *(item(v,k) for k,v in flds.items()), Button('Click To Edit'), post='form', hx_swap='outerHTML') contacts = [Contact('Joe', 'Blow', '[email protected]')] @rt def index(): return contacts[0] @rt def form(c:Contact): def item(k,v): return Div(Label(k), Input(name=v, value=getattr(c,v))) return Form( *(item(v,k) for k,v in flds.items()), Button('Submit', name='btn', value='submit'), Button('Cancel', name='btn', value='cancel'), post="contact", hx_swap='outerHTML' ) @rt def contact(c:Contact, btn:str): if btn=='submit': contacts[0] = c return contacts[0]
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/click_to_edit
FastHTML page
Email Address Is this cool?
https://gallery.fastht.ml/app/dynamic_user_interface_(htmx)/inline_validation/
FastHTML page
from fasthtml.common import * app, rt = fast_app() chapters = ['ch1', 'ch2', 'ch3'] lessons = { 'ch1': ['lesson1', 'lesson2', 'lesson3'], 'ch2': ['lesson4', 'lesson5', 'lesson6'], 'ch3': ['lesson7', 'lesson8', 'lesson9']} def mk_opts(nm, cs): return ( Option(f'-- select {nm} --', disabled='', selected='', value=''), *map(Option, cs)) @rt def get_lessons(chapter: str): return Select(*mk_opts('lesson', lessons[chapter]), name='lesson') @rt def index(): chapter_dropdown = Select( *mk_opts('chapter', chapters), name='chapter', get='get_lessons', hx_target='#lessons') return Div( Div(Label("Chapter:", for_="chapter"), chapter_dropdown), Div(Label("Lesson:", for_="lesson"), Div(Div(id='lessons')),))
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/cascading_dropdowns
FastHTML page
from fasthtml.common import * from collections import defaultdict app, rt = fast_app() default_data = [ {'id': 1, 'name': 'Alice', 'age': 25}, {'id': 2, 'name': 'Bob', 'age': 30}, {'id': 3, 'name': 'Charlie', 'age': 28}, ] data = defaultdict(lambda: [dict(d) for d in default_data]) @rt def index(session): # if no id, create one so diff users changes don't conflict if not session.get('id'): session['id'] = unqid() # Create a table based on the current users data rows = [] for item in data[session['id']]: rows.append( Tr(Td(str(item['id'])), Td(Input(value=item['name'], name=f"name{item['id']}", _id=f"name{item['id']}")), Td(Input(value=str(item['age']), name=f"age{item['id']}", _id=f"age{item['id']}")))) return Div( Form( Table( Thead(Tr(map(Th, ('ID', 'Name', 'Age')))), Tbody(*rows)), # Bulk update button that submits all inputs from the table because it's inside fot form. Button('Bulk Update', hx_post="update", hx_target='#response', hx_indicator="#loading", _type="button", hx_vals={'id': session['id']})), # Response div that will be updated with the result of the bulk update Div(id='response'), # Loading indicator that will be shown when the bulk update is happening Div(id="loading", style="display:none;", _class="loader")) @rt async def update(request, id:str): changes = [] form_data = await request.form() # Iterate over the items in the users data for item in data[id]: # Get the new name and age from the form data new_name = form_data.get(f"name{item['id']}") new_age = form_data.get(f"age{item['id']}") # Check if the item has changed and if so add it to the changes list if new_name != item['name'] or new_age != str(item['age']): changes.append(f"Row {item['id']} changed: Name {item['name']} β†’ {new_name}, Age {item['age']} β†’ {new_age}") item['name'] = new_name item['age'] = int(new_age) # Return the changes or a message if there are no changes return Div(*[Div(change) for change in changes]) if changes else Div("No changes detected") serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/bulk_update
FastHTML page
from fasthtml.common import * from collections import defaultdict app, rt = fast_app() default_data = [ {'id': 1, 'name': 'Alice', 'age': 25}, {'id': 2, 'name': 'Bob', 'age': 30}, {'id': 3, 'name': 'Charlie', 'age': 28}, ] data = defaultdict(lambda: [dict(d) for d in default_data]) @rt def index(session): # if no id, create one so diff users changes don't conflict if not session.get('id'): session['id'] = unqid() # Create a table based on the current users data rows = [] for item in data[session['id']]: rows.append( Tr(Td(str(item['id'])), Td(Input(value=item['name'], name=f"name{item['id']}", _id=f"name{item['id']}")), Td(Input(value=str(item['age']), name=f"age{item['id']}", _id=f"age{item['id']}")))) return Div( Form( Table( Thead(Tr(map(Th, ('ID', 'Name', 'Age')))), Tbody(*rows)), # Bulk update button that submits all inputs from the table because it's inside fot form. Button('Bulk Update', hx_post="update", hx_target='#response', hx_indicator="#loading", _type="button", hx_vals={'id': session['id']})), # Response div that will be updated with the result of the bulk update Div(id='response'), # Loading indicator that will be shown when the bulk update is happening Div(id="loading", style="display:none;", _class="loader")) @rt async def update(request, id:str): changes = [] form_data = await request.form() # Iterate over the items in the users data for item in data[id]: # Get the new name and age from the form data new_name = form_data.get(f"name{item['id']}") new_age = form_data.get(f"age{item['id']}") # Check if the item has changed and if so add it to the changes list if new_name != item['name'] or new_age != str(item['age']): changes.append(f"Row {item['id']} changed: Name {item['name']} β†’ {new_name}, Age {item['age']} β†’ {new_age}") item['name'] = new_name item['age'] = int(new_age) # Return the changes or a message if there are no changes return Div(*[Div(change) for change in changes]) if changes else Div("No changes detected") serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/bulk_update
FastHTML page
Bulk Data Update with Fasthtml and HTMX This example demonstrates how to create a simple web application using Fasthtml and HTMX that allows users to bulk update data displayed in an HTML table. Users can modify the values in the table's input fields and then click a button to submit all the changes at once. Key Features Dynamic Table Generation: The HTML table is dynamically generated from a Python list of dictionaries. Each dictionary represents a row in the table. Client-Side Updates (with HTMX): The changes are submitted via an AJAX-like request using HTMX. This avoids a full page reload, providing a smoother user experience. Server-Side Processing: The updates are processed on the server using a Python function. Data Persistence (In-Memory): The example uses an in-memory data structure (a list of dictionaries) to store the data. In a real-world application, you would replace this with a database or other persistent storage. Preventing Accidental Submissions: The "Bulk Update" button uses _type="button" to prevent the form from being submitted when the user presses Enter in the input fields. This ensures that only a button click triggers the update process. How it Works Data Initialization: The data list of dictionaries holds the initial data for the table. index Route (Table Display): The index route function generates the HTML for the table. It iterates through the data list and creates table rows (<tr>) with cells (<td>). Each cell in the 'Name' and 'Age' columns contains an <input> element, allowing the user to edit the values. The table is wrapped in a <form> element. A "Bulk Update" button is included in the form. The hx_post attribute on the button specifies the route (/update) that will handle the form submission. The hx_target attribute specifies where the response from the server should be displayed (#response). hx_indicator shows a loading indicator while the request is in progress. _type="button" prevents form submission on Enter key press. /update Route (Data Processing): The update route function handles the POST request when the "Bulk Update" button is clicked. It retrieves the form data using await request.form(). It iterates through the data list and compares the new values from the form with the original values. If a value has changed, it updates the data list and adds a message to the changes list. Finally, it returns a Div containing the messages about the changes. How to Use Run the example. The table will be displayed in your browser. Edit the 'Name' and 'Age' values in the input fields as needed. Click the "Bulk Update" button. The changes will be processed, and a message will appear below the button indicating which rows were updated. Code Explanation (Key Parts)
https://gallery.fastht.ml/info/dynamic_user_interface_(htmx)/bulk_update
FastHTML page
from fasthtml.common import * app, rt = fast_app() chapters = ['ch1', 'ch2', 'ch3'] lessons = { 'ch1': ['lesson1', 'lesson2', 'lesson3'], 'ch2': ['lesson4', 'lesson5', 'lesson6'], 'ch3': ['lesson7', 'lesson8', 'lesson9']} def mk_opts(nm, cs): return ( Option(f'-- select {nm} --', disabled='', selected='', value=''), *map(Option, cs)) @rt def get_lessons(chapter: str): return Select(*mk_opts('lesson', lessons[chapter]), name='lesson') @rt def index(): chapter_dropdown = Select( *mk_opts('chapter', chapters), name='chapter', get='get_lessons', hx_target='#lessons') return Div( Div(Label("Chapter:", for_="chapter"), chapter_dropdown), Div(Label("Lesson:", for_="lesson"), Div(Div(id='lessons')),))
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/cascading_dropdowns
FastHTML page
import random from fasthtml.common import * app, rt = fast_app(hdrs=(Style(""" /* CSS to center content of the app */ body { max-width: 800px; padding: 20px; width: 90%; margin: 0 auto; } * { text-align: center; } /* CSS to fade in to full opacity in 1 second */ #fade-me-in.htmx-added { opacity: 0; } #fade-me-in { opacity: 1; transition: opacity 1s ease-out; } /* CSS to fade out to 0 opacity in 1 second */ .fade-me-out { opacity: 1; } .fade-me-out.htmx-swapping { opacity: 0; transition: opacity 1s ease-out; } """),)) @rt def color_throb_demo(): # Each time this route is called it chooses a random color random_color = random.choice(['red', 'blue', 'green', 'yellow', 'orange', 'purple', 'pink']) return P("Groovy baby, yeah!", id="color-demo", # Make text random color and do a smooth transition style=f"color: {random_color}; transition: all 1s ease-in;", # Call this route and replace the text every 1 second get=color_throb_demo, hx_swap="outerHTML", hx_trigger="every 1s") # 2. Settling Transitions @rt def fade_in_demo(): return Button( "Fade Me In", id="fade-me-in", class_="btn primary", # hx_trigger defaults to click so we do not have to specify it # When the button is clicked, create a new button with a 1 second settling transition post=fade_in_demo, hx_swap="outerHTML settle:1s") def in_flight_animation_demo(): " Create a form that changes its look on click. In this case it displays a 'Submitted!' response. " return Form( Input(name="name", style="width: 300px;", placeholder="Content field"), Button("Submit", class_="btn primary"), # When the button is clicked, swap it with the button specified in form_completion_message post=form_completion_message, hx_swap="outerHTML") @rt def form_completion_message(): # A button with green background and white text return Button("Submitted!", class_="btn primary", style="background-color: green; color: white;") # Helper function to create a section for an example def section(title, desc, content): return Card(H2(title), P(desc), Br(), content, Br()) @rt def index(): return Div( H1("Text Animations"), Br(), section("Color Throb", "Change text color every second in a smooth transition.", color_throb_demo()), section("Settling Transitions", "Make a button disappear on click and gradually fade in.", fade_in_demo()), section("Request In Flight Animation", "Let a form change its look on click. In this case it displays a 'Submitted!' response.", in_flight_animation_demo())) serve()
https://gallery.fastht.ml/code/dynamic_user_interface_(htmx)/animations
FastHTML page
Click to Load Dynamically add rows to a table using HTMX. Name Email ID Agent Smith 10 [email protected] ad464f20-3c84-4c42-a4a6-e775c65277dc
https://gallery.fastht.ml/app/dynamic_user_interface_(htmx)/click_to_load/
FastHTML page
import random from fasthtml.common import * app, rt = fast_app(hdrs=(Style(""" /* CSS to center content of the app */ body { max-width: 800px; padding: 20px; width: 90%; margin: 0 auto; } * { text-align: center; } /* CSS to fade in to full opacity in 1 second */ #fade-me-in.htmx-added { opacity: 0; } #fade-me-in { opacity: 1; transition: opacity 1s ease-out; } /* CSS to fade out to 0 opacity in 1 second */ .fade-me-out { opacity: 1; } .fade-me-out.htmx-swapping { opacity: 0; transition: opacity 1s ease-out; } """),)) @rt def color_throb_demo(): # Each time this route is called it chooses a random color random_color = random.choice(['red', 'blue', 'green', 'yellow', 'orange', 'purple', 'pink']) return P("Groovy baby, yeah!", id="color-demo", # Make text random color and do a smooth transition style=f"color: {random_color}; transition: all 1s ease-in;", # Call this route and replace the text every 1 second get=color_throb_demo, hx_swap="outerHTML", hx_trigger="every 1s") # 2. Settling Transitions @rt def fade_in_demo(): return Button( "Fade Me In", id="fade-me-in", class_="btn primary", # hx_trigger defaults to click so we do not have to specify it # When the button is clicked, create a new button with a 1 second settling transition post=fade_in_demo, hx_swap="outerHTML settle:1s") def in_flight_animation_demo(): " Create a form that changes its look on click. In this case it displays a 'Submitted!' response. " return Form( Input(name="name", style="width: 300px;", placeholder="Content field"), Button("Submit", class_="btn primary"), # When the button is clicked, swap it with the button specified in form_completion_message post=form_completion_message, hx_swap="outerHTML") @rt def form_completion_message(): # A button with green background and white text return Button("Submitted!", class_="btn primary", style="background-color: green; color: white;") # Helper function to create a section for an example def section(title, desc, content): return Card(H2(title), P(desc), Br(), content, Br()) @rt def index(): return Div( H1("Text Animations"), Br(), section("Color Throb", "Change text color every second in a smooth transition.", color_throb_demo()), section("Settling Transitions", "Make a button disappear on click and gradually fade in.", fade_in_demo()), section("Request In Flight Animation", "Let a form change its look on click. In this case it displays a 'Submitted!' response.", in_flight_animation_demo())) serve()
https://gallery.fastht.ml/split/dynamic_user_interface_(htmx)/animations
FastHTML page
A cascading dropdown component where values in second dropdown are dependent on the value in the first dropdown A searchable dropdown menu with a text box that allows user to add additional options to it via HTMX A table with infinite scroll over a large dataset (appending rows to the table as the user reaches the end of the table). A form with inline field validation on individual inputs with the submit aditionally validating the whole form. A loading indicator that shows when a button is pressed until content is loaded using HTMX's hx-indicator A component that visually represents the completion status of a task or operation as it moves towards completion. A simple two column grid with inputs on the left and outputs on the right based on fasthtml-example form demo A demonstration on web sockets to have a multi-user messaging/chat use Change the appearance of a Polars dataFrame based on selected colors using the Great Tables library. Interactive Plotly chart using the fh-plotly plugin by Carlo Lepelaars that lets you zoom, pan, hover over data points and much more Example showing how to create interactive Plotly charts that communicate with FastHTML routes when data points are selected, enabling dynamic updates and actions based on user selections A component that shows a rectangle which can be dragged with the mouse The component shows a circle which can be clicked. The first click starts a timer and after 10 clicks the elasped time is reported. Each click causes the circle to move. A component that shows how to do an inband swap of an SVG element
https://gallery.fastht.ml/table
FastHTML page
Text Animations Color Throb Change text color every second in a smooth transition. Groovy baby, yeah! Settling Transitions Make a button disappear on click and gradually fade in.
https://gallery.fastht.ml/app/dynamic_user_interface_(htmx)/animations/
FastHTML page