### Run Mesop Development Server Source: https://mesop-dev.github.io/mesop/internal/codespaces Execute this command in the terminal after the Codespace setup is complete to start the Mesop development server. This may take some time on the first run. ```bash ./scripts/cli.sh ``` -------------------------------- ### Define Example Prompts for Home Page Source: https://mesop-dev.github.io/mesop/codelab/5 Defines a list of example prompts and a function to render them as clickable boxes. Clicking an example sets the input state to the example text. ```python EXAMPLES = [ "Create a file-lock in Python", "Write an email to Congress to have free milk for all", "Make a nice box shadow in CSS", ] def examples_row(): with me.box( style=me.Style( display="flex", flex_direction="row", gap=16, margin=me.Margin(bottom=24) ) ): for i in EXAMPLES: example(i) def example(text: str): with me.box( key=text, on_click=click_example, style=me.Style( cursor="pointer", background="#b9e1ff", width="215px", height=160, font_weight=500, line_height="1.5", padding=me.Padding.all(16), border_radius=16, border=me.Border.all(me.BorderSide(width=1, color="blue", style="none")), ), ): me.text(text) def click_example(e: me.ClickEvent): state = me.state(State) state.input = e.key ``` -------------------------------- ### Install Mesop Source: https://mesop-dev.github.io/mesop/getting-started/installing Install the Mesop package using pip. This is the primary installation command. ```bash pip install mesop ``` -------------------------------- ### Basic Navigation Example Source: https://mesop-dev.github.io/mesop/api/commands/navigate Demonstrates how to navigate between pages using `me.navigate` triggered by a button click. This example sets up two pages, 'home' and 'about', and a button on the home page to navigate to the about page. ```python import mesop as me def navigate(event: me.ClickEvent): me.navigate("/examples/navigate/about") @me.page(path="/examples/navigate/home") def home(): me.text("This is the home page") me.button("navigate to about page", on_click=navigate) @me.page(path="/examples/navigate/about") def about(): me.text("This is the about page") ``` -------------------------------- ### Install Project Dependencies Source: https://mesop-dev.github.io/mesop/codelab Install the project dependencies using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Example Mesop Application Source: https://mesop-dev.github.io/mesop/guides/deployment This Python file defines a simple Mesop page with a 'Hello, world' text. ```python import mesop as me @me.page(title="Home") def home(): me.text("Hello, world") ``` -------------------------------- ### Setup Proto Python Modules Source: https://mesop-dev.github.io/mesop/internal/development Sets up a symlink required for Python IDE support for protos. ```bash ./scripts/setup_proto_py_modules.sh ``` -------------------------------- ### Simple Event Handler Example Source: https://mesop-dev.github.io/mesop/guides/event-handlers A basic example demonstrating a button click that increments a counter stored in the application state. ```python def counter(): me.button("Increment", on_click=on_click) def on_click(event: me.ClickEvent): state = me.state(State) state.count += 1 @me.stateclass class State: count: int = 0 ``` -------------------------------- ### Simple Page Setup Source: https://mesop-dev.github.io/mesop/api/page Use the `me.page()` decorator to create a basic Mesop page. If no path is specified, it defaults to the root path '/'. ```python import mesop as me @me.page() def foo(): me.text("bar") ``` -------------------------------- ### Example of Focusing a Component with me.focus_component Source: https://mesop-dev.github.io/mesop/api/commands/focus-component This example demonstrates how to use `me.focus_component` to focus on different UI elements based on user selection. It sets up a page with various input components and a select dropdown. When a user selects an option from the dropdown, the corresponding component is focused. ```python import mesop as me @me.page(path="/focus_component") def page(): with me.box(style=me.Style(margin=me.Margin.all(15))): me.select( options=[ me.SelectOption(label="Autocomplete", value="autocomplete"), me.SelectOption(label="Checkbox", value="checkbox"), me.SelectOption(label="Input", value="input"), me.SelectOption(label="Link", value="link"), me.SelectOption(label="Radio", value="radio"), me.SelectOption(label="Select", value="select"), me.SelectOption(label="Slider", value="slider"), me.SelectOption(label="Slide Toggle", value="slide_toggle"), me.SelectOption(label="Textarea", value="textarea"), me.SelectOption(label="Uploader", value="uploader"), ], on_selection_change=on_selection_change, ) me.divider() with me.box( style=me.Style( display="grid", gap=5, grid_template_columns="1fr 1fr", margin=me.Margin.all(15), ) ): with me.box(): me.autocomplete( key="autocomplete", label="Autocomplete", options=[ me.AutocompleteOption(label="Test", value="Test"), me.AutocompleteOption(label="Test2", value="Tes2t"), ], ) with me.box(): me.checkbox("Checkbox", key="checkbox") with me.box(): me.input(key="input", label="Input") with me.box(): me.link(key="link", text="Test", url="https://google.com") with me.box(): me.radio( key="radio", options=[ me.RadioOption(label="Option 1", value="1"), me.RadioOption(label="Option 2", value="2"), ], ) with me.box(): me.select( key="select", label="Select", options=[ me.SelectOption(label="label 1", value="value1"), me.SelectOption(label="label 2", value="value2"), me.SelectOption(label="label 3", value="value3"), ], ) with me.box(): me.slider(key="slider") with me.box(): me.slide_toggle(key="slide_toggle", label="Slide toggle") with me.box(): me.textarea(key="textarea", label="Textarea") with me.box(): me.uploader( key="uploader", label="Upload Image", accepted_file_types=["image/jpeg", "image/png"], type="flat", color="primary", style=me.Style(font_weight="bold"), ) def on_selection_change(e: me.SelectSelectionChangeEvent): me.focus_component(key=e.value) ``` -------------------------------- ### Mesop Scroll into View Example Source: https://mesop-dev.github.io/mesop/api/commands/scroll-into-view Demonstrates how to use `me.scroll_into_view` to scroll to different components within a Mesop application. Includes examples for scrolling to a middle line, a bottom line, and dynamically adding content while scrolling. ```python import time import mesop as me @me.stateclass class State: more_lines: int = 0 @me.page(path="/scroll_into_view") def app(): me.button("Scroll to middle line", on_click=scroll_to_middle) me.button("Scroll to bottom line", on_click=scroll_to_bottom) me.button( "Scroll to bottom line & generate lines", on_click=scroll_to_bottom_and_generate_lines, ) for _ in range(100): me.text("Filler line") me.text("middle_line", key="middle_line") for _ in range(100): me.text("Filler line") me.text("bottom_line", key="bottom_line") for _ in range(me.state(State).more_lines): me.text("More lines") def scroll_to_middle(e: me.ClickEvent): me.scroll_into_view(key="middle_line") def scroll_to_bottom(e: me.ClickEvent): me.scroll_into_view(key="bottom_line") def scroll_to_bottom_and_generate_lines(e: me.ClickEvent): state = me.state(State) me.scroll_into_view(key="bottom_line") yield state.more_lines += 5 time.sleep(1) yield state.more_lines += 5 time.sleep(1) yield state.more_lines += 5 time.sleep(1) yield state.more_lines += 5 time.sleep(1) yield ``` -------------------------------- ### Install Pre-commit Hooks Source: https://mesop-dev.github.io/mesop/internal/development Installs pre-commit hooks for the repository to automatically format and lint code before committing. ```bash pre-commit install ``` -------------------------------- ### Mesop Link Examples Source: https://mesop-dev.github.io/mesop/components/link Demonstrates how to use the me.link component to create links that open in the same tab, a new tab, or with custom styling. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/link", ) def link(): with me.box( style=me.Style( margin=me.Margin.all(15), display="flex", flex_direction="column", gap=10 ) ): me.link( text="Open in same tab", url="https://mesop-dev.github.io/mesop/", style=me.Style(color=me.theme_var("primary")), ) me.link( text="Open in new tab", open_in_new_tab=True, url="https://mesop-dev.github.io/mesop/", style=me.Style(color=me.theme_var("primary")), ) me.link( text="Styled link", url="https://mesop-dev.github.io/mesop/", style=me.Style(color=me.theme_var("tertiary"), text_decoration="none"), ) ``` -------------------------------- ### Basic Chat Interface Example Source: https://mesop-dev.github.io/mesop/components/chat This example demonstrates how to create a basic chat interface using the `mel.chat` component. It includes a `transform` function that simulates a bot's response with a delay and yields text line by line. The `on_load` function sets the theme mode. ```python import random import time import mesop as me import mesop.labs as mel def on_load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/chat", title="Mesop Demo Chat", on_load=on_load, ) def page(): mel.chat(transform, title="Mesop Demo Chat", bot_user="Mesop Bot") def transform(input: str, history: list[mel.ChatMessage]): for line in random.sample(LINES, random.randint(3, len(LINES) - 1)): time.sleep(0.3) yield line + " " LINES = [ "Mesop is a Python-based UI framework designed to simplify web UI development for engineers without frontend experience.", "It leverages the power of the Angular web framework and Angular Material components, allowing rapid construction of web demos and internal tools.", "With Mesop, developers can enjoy a fast build-edit-refresh loop thanks to its hot reload feature, making UI tweaks and component integration seamless.", "Deployment is straightforward, utilizing standard HTTP technologies.", "Mesop's component library aims for comprehensive Angular Material component coverage, enhancing UI flexibility and composability.", "It supports custom components for specific use cases, ensuring developers can extend its capabilities to fit their unique requirements.", "Mesop's roadmap includes expanding its component library and simplifying the onboarding processs.", ] ``` -------------------------------- ### Install Third-Party Dependencies Source: https://mesop-dev.github.io/mesop/internal/development Installs third-party dependencies using pip. You may need to run with `sudo` if permission errors occur. ```bash pip install -r build_defs/requirements_lock.txt ``` -------------------------------- ### Mesop Card Component Examples Source: https://mesop-dev.github.io/mesop/components/card Demonstrates the usage of the mesop.card component with different appearances and configurations, including header, content, and actions. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"], ), path="/card", ) def app(): with me.box( style=me.Style( display="flex", flex_direction="column", gap=15, margin=me.Margin.all(15), max_width=500, ) ): with me.card(appearance="outlined"): me.card_header( title="Grapefruit", subtitle="Kind of fruit", image="https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg", ) me.image( style=me.Style( width="100%", ), src="https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg", ) with me.card_content(): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) with me.card_actions(align="end"): me.button(label="Add to cart") me.button(label="Buy") with me.card(appearance="raised"): me.card_header( title="Grapefruit", subtitle="Kind of fruit", image="https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg", image_type="small", ) with me.card_content(): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) with me.card_actions(align="start"): me.button(label="Add to cart") me.button(label="Buy") with me.card(appearance="outlined"): me.card_header( title="Grapefruit", subtitle="Kind of fruit", image="https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg", image_type="medium", ) with me.card_content(): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) with me.card_actions(align="start"): me.button(label="Add to cart") me.button(label="Buy") me.card_header( title="Grapefruit", image="https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg", image_type="large", ) with me.card_content(): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) with me.card_actions(align="end"): me.button(label="Add to cart") me.button(label="Buy") me.card_header( title="Grapefruit", image_type="large", ) with me.card_content(): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) ``` -------------------------------- ### Basic Text to Text Component Usage Source: https://mesop-dev.github.io/mesop/components/text-to-text Demonstrates how to use the text_to_text component to take user input and display a capitalized version of it. This example sets up a page with the component and defines a simple transformation function. ```python import mesop as me import mesop.labs as mel def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/text_to_text", title="Text to Text Example", ) def app(): mel.text_to_text( upper_case_stream, title="Text to Text Example", ) def upper_case_stream(s: str): return "Echo: " + s.capitalize() ``` -------------------------------- ### Basic Expansion Panel Example Source: https://mesop-dev.github.io/mesop/components/expansion-panel A simple expansion panel with a title and content. This is a fundamental building block for collapsible content. ```python with me.expansion_panel( key="pie", title="Pie", description="Type of snack", icon="pie_chart", ): me.text( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed augue ultricies, laoreet nunc eget, ultricies augue. In ornare bibendum mauris vel sodales. Donec ut interdum felis. Nulla facilisi. Morbi a laoreet turpis, sed posuere arcu. Nam nisi neque, molestie vitae euismod eu, sollicitudin eu lectus. Pellentesque orci metus, finibus id faucibus et, ultrices quis dui. Duis in augue ac metus tristique lacinia." ) ``` -------------------------------- ### Define and Insert a Web Component Source: https://mesop-dev.github.io/mesop/web-components/api Example of defining a web component using the `@me.web_component` decorator and then inserting it into the component tree with `me.insert_web_component`. ```python import mesop as me @me.web_component(...) def a_web_component(): me.insert_web_component(...) ``` -------------------------------- ### Run Docker Compose Source: https://mesop-dev.github.io/mesop/guides/deployment Command to start Mesop application services defined in docker-compose.yaml in detached mode. ```bash docker-compose up -d ``` -------------------------------- ### Text to Image Component Example Source: https://mesop-dev.github.io/mesop/components/text-to-image Demonstrates how to use the `mel.text_to_image` component to create a UI for generating images from text prompts. The `generate_image` function is a placeholder that returns a sample image URL. ```python import mesop as me import mesop.labs as mel def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/text_to_image", title="Text to Image Example", ) def app(): mel.text_to_image( generate_image, title="Text to Image Example", ) def generate_image(prompt: str): return "https://www.google.com/logos/doodles/2024/earth-day-2024-6753651837110453-2xa.gif" ``` -------------------------------- ### Explicit Page Setup Source: https://mesop-dev.github.io/mesop/api/page Explicitly set the URL path for a Mesop page using the `path` argument in the `me.page()` decorator. ```python import mesop as me @me.page(path="/") def foo(): me.text("bar") ``` -------------------------------- ### SQLAlchemy Table Setup for Mesop State Sessions Source: https://mesop-dev.github.io/mesop/api/config Sets up a SQLAlchemy table for storing Mesop state sessions. Ensure `TABLE_NAME` matches `MESOP_STATE_SESSION_BACKEND_SQL_TABLE` if overridden. ```python TABLE_NAME = "mesop_state_session" db = create_engine(CONNECTION_URI) metadata = MetaData() table = Table( TABLE_NAME, metadata, Column("token", String(23), primary_key=True), Column("states", LargeBinary, nullable=False), Column("created_at", DateTime, nullable=False, index=True), ) metadata.create_all(db) ``` -------------------------------- ### Mesop Date Range Picker Example Source: https://mesop-dev.github.io/mesop/components/date_range_picker Demonstrates how to use the date_range_picker component in a Mesop application. It includes state management for selected dates and an event handler for changes. ```python from dataclasses import field from datetime import date import mesop as me @me.stateclass class State: picked_start_date: date | None = field( default_factory=lambda: date(2024, 10, 1) ) picked_end_date: date | None = field( default_factory=lambda: date(2024, 11, 1) ) def on_load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( path="/date_range_picker", security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), on_load=on_load, ) def app(): state = me.state(State) with me.box( style=me.Style( display="flex", flex_direction="column", gap=15, padding=me.Padding.all(15), ) ): me.date_range_picker( label="Date Range", disabled=False, placeholder_start_date="9/1/2024", placeholder_end_date="10/1/2024", required=True, start_date=state.picked_start_date, end_date=state.picked_end_date, readonly=False, hide_required_marker=False, color="accent", float_label="always", appearance="outline", on_change=on_date_range_change, ) me.text("Start date: " + _render_date(state.picked_start_date)) me.text("End date: " + _render_date(state.picked_end_date)) def on_date_range_change(e: me.DateRangePickerChangeEvent): state = me.state(State) state.picked_start_date = e.start_date state.picked_end_date = e.end_date def _render_date(maybe_date: date | None) -> str: if maybe_date: return maybe_date.strftime("%Y-%m-%d") return "None" ``` -------------------------------- ### Basic Date Picker Example Source: https://mesop-dev.github.io/mesop/components/date_picker This snippet demonstrates how to create a basic date picker with a label, placeholder, and required marker. It also shows how to handle date changes and display the selected date. ```python from dataclasses import field from datetime import date import mesop as me @me.stateclass class State: picked_date: date | None = field(default_factory=lambda: date(2024, 10, 1)) def on_load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( path="/date_picker", security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), on_load=on_load, ) def app(): state = me.state(State) with me.box( style=me.Style( display="flex", flex_direction="column", gap=15, padding=me.Padding.all(15), ) ): me.date_picker( label="Date", disabled=False, placeholder="9/1/2024", required=True, value=state.picked_date, readonly=False, hide_required_marker=False, color="accent", float_label="always", appearance="outline", on_change=on_date_change, ) me.text("Selected date: " + _render_date(state.picked_date)) def on_date_change(e: me.DatePickerChangeEvent): state = me.state(State) state.picked_date = e.date def _render_date(maybe_date: date | None) -> str: if maybe_date: return maybe_date.strftime("%Y-%m-%d") return "None" ``` -------------------------------- ### Basic Tooltip Example Source: https://mesop-dev.github.io/mesop/components/tooltip Demonstrates how to create a simple tooltip with a message that appears when hovering over text. This snippet requires importing the mesop library and setting up a basic page structure. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/tooltip", ) def app(): with me.box(style=me.Style(margin=me.Margin.all(15))): with me.tooltip(message="Tooltip message"): me.text(text="Hello, World") ``` -------------------------------- ### Navigate Between Mesop Pages with Button Source: https://mesop-dev.github.io/mesop/guides/multi-pages Implement navigation to another page when a button is clicked using me.navigate. This example demonstrates sharing state across pages. ```python import mesop as me def on_click(e: me.ClickEvent): state = me.state(State) state.count += 1 me.navigate("/multi_page_nav/page_2") @me.page(path="/multi_page_nav") def main_page(): me.button("Navigate to Page 2", on_click=on_click) @me.page(path="/multi_page_nav/page_2") def page_2(): state = me.state(State) me.text(f"Page 2 - count: {state.count}") @me.stateclass class State: count: int ``` -------------------------------- ### Basic Button Toggle Example Source: https://mesop-dev.github.io/mesop/components/button_toggle Demonstrates how to create a button toggle group with multiple selection enabled. It displays the currently selected values below the toggle. ```python from dataclasses import field import mesop as me @me.stateclass class State: selected_values: list[str] = field( default_factory=lambda: ["bold", "underline"] ) def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/button_toggle", ) def app(): state = me.state(State) with me.box(style=me.Style(margin=me.Margin.all(15))): me.button_toggle( value=state.selected_values, buttons=[ me.ButtonToggleButton(label="Bold", value="bold"), me.ButtonToggleButton(label="Italic", value="italic"), me.ButtonToggleButton(label="Underline", value="underline"), ], multiple=True, hide_selection_indicator=False, disabled=False, on_change=on_change, style=me.Style(margin=me.Margin(bottom=20)), ) me.text("Select buttons: " + " ".join(state.selected_values)) def on_change(e: me.ButtonToggleChangeEvent): state = me.state(State) state.selected_values = e.values ``` -------------------------------- ### Sidenav with Navigation and Content Source: https://mesop-dev.github.io/mesop/components/sidenav This example demonstrates how to implement a Sidenav component in Mesop. It includes a button to toggle the sidenav and displays main content that adjusts its margin based on the sidenav's state. Use this for creating navigation sidebars. ```python import mesop as me SIDENAV_WIDTH = 200 @me.stateclass class State: sidenav_open: bool def on_click(e: me.ClickEvent): s = me.state(State) s.sidenav_open = not s.sidenav_open def opened_changed(e: me.SidenavOpenedChangedEvent): s = me.state(State) s.sidenav_open = e.opened def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/sidenav", ) def app(): state = me.state(State) with me.sidenav( opened=state.sidenav_open, disable_close=False, on_opened_changed=opened_changed, style=me.Style( border_radius=0, width=SIDENAV_WIDTH, background=me.theme_var("surface-container-low"), padding=me.Padding.all(15), ), ): me.text("Inside sidenav") with me.box( style=me.Style( margin=me.Margin(left=SIDENAV_WIDTH if state.sidenav_open else 0), padding=me.Padding.all(15), ), ): with me.content_button(on_click=on_click): me.icon("menu") me.markdown("Main content") ``` -------------------------------- ### Build an Interactive Counter App Source: https://mesop-dev.github.io/mesop/getting-started/core-concepts This example demonstrates Mesop's interactivity by creating a counter that increments on button clicks. It involves defining state, an event handler, and a component to display the count and trigger the event. ```python import mesop as me @me.stateclass class State: clicks: int def button_click(event: me.ClickEvent): state = me.state(State) state.clicks += 1 @me.page(path="/counter") def main(): state = me.state(State) me.text(f"Clicks: {state.clicks}") me.button("Increment", on_click=button_click) ``` -------------------------------- ### Set Mesop state session backend via environment variable Source: https://mesop-dev.github.io/mesop/api/config Configure the state session backend for Mesop using the MESOP_STATE_SESSION_BACKEND environment variable. This example sets it to 'memory'. ```bash MESOP_STATE_SESSION_BACKEND=memory mesop main.py ``` -------------------------------- ### Mesop Box Component Example Source: https://mesop-dev.github.io/mesop/components/box Demonstrates the usage of the Box component with various styling options for background, padding, margin, borders, and border-radius. This snippet shows how to create nested boxes and apply different border styles. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/box", ) def app(): with me.box(style=me.Style(background="red", padding=me.Padding.all(16))): with me.box( style=me.Style( background="green", height=50, margin=me.Margin.symmetric(vertical=24, horizontal=12), border=me.Border.symmetric( horizontal=me.BorderSide(width=2, color="pink", style="solid"), vertical=me.BorderSide(width=2, color="orange", style="solid"), ), ) ): me.text(text="hi1") me.text(text="hi2") with me.box( style=me.Style( background="blue", height=50, margin=me.Margin.all(16), border=me.Border.all( me.BorderSide(width=2, color="yellow", style="dotted") ), border_radius=10, ) ): me.text(text="Example with all sides bordered") with me.box( style=me.Style( background="purple", height=50, margin=me.Margin.symmetric(vertical=24, horizontal=12), border=me.Border.symmetric( vertical=me.BorderSide(width=4, color="white", style="double") ), ) ): me.text(text="Example with top and bottom borders") with me.box( style=me.Style( background="cyan", height=50, margin=me.Margin.symmetric(vertical=24, horizontal=12), border=me.Border.symmetric( horizontal=me.BorderSide(width=2, color="black", style="groove") ), ) ): me.text(text="Example with left and right borders") ``` -------------------------------- ### Basic Badge Example Source: https://mesop-dev.github.io/mesop/components/badge Demonstrates how to use the Badge component to display a count on a text element. This snippet shows a basic implementation with content and size specified. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/badge", ) def app(): with me.box( style=me.Style( display="block", padding=me.Padding(top=16, right=16, bottom=16, left=16), height=50, width=30, ) ): with me.badge(content="1", size="medium"): me.text(text="text with badge") ``` -------------------------------- ### Basic Embed Example Source: https://mesop-dev.github.io/mesop/components/embed This snippet demonstrates how to embed a Mesop website within another Mesop page. It sets up a security policy to allow iframes from a specific parent URL and configures the embed's size. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/embed", ) def app(): src = "https://mesop-dev.github.io/mesop/" me.text("Embedding: " + src, style=me.Style(padding=me.Padding.all(15))) me.embed( src=src, style=me.Style(width="100%", height="100%"), ) ``` -------------------------------- ### Mesop Page Setup with AI Integration Source: https://mesop-dev.github.io/mesop/codelab/4 Updates the main Mesop application to integrate Gemini and Claude models. Includes functions for displaying conversations and messages. ```python import mesop as me from data_model import State, Models, ModelDialogState, Conversation, ChatMessage from dialog import dialog, dialog_actions import claude import gemini # ... (keep the existing imports and styles) # Replace page() with this: @me.page( path="/", stylesheets=[ "https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" ], ) def page(): model_picker_dialog() with me.box(style=ROOT_BOX_STYLE): header() with me.box( style=me.Style( width="min(680px, 100%)", margin=me.Margin.symmetric(horizontal="auto", vertical=36), ) ): me.text( "Chat with multiple models at once", style=me.Style(font_size=20, margin=me.Margin(bottom=24)), ) chat_input() display_conversations() # Add display_conversations and display_message: def display_conversations(): state = me.state(State) for conversation in state.conversations: with me.box(style=me.Style(margin=me.Margin(bottom=24))): me.text(f"Model: {conversation.model}", style=me.Style(font_weight=500)) for message in conversation.messages: display_message(message) def display_message(message: ChatMessage): style = me.Style( padding=me.Padding.all(12), border_radius=8, margin=me.Margin(bottom=8), ) if message.role == "user": style.background = "#e7f2ff" else: style.background = "#ffffff" with me.box(style=style): me.markdown(message.content) if message.in_progress: me.progress_spinner() ``` -------------------------------- ### Basic Progress Spinner Source: https://mesop-dev.github.io/mesop/components/progress-spinner Demonstrates how to use the basic progress spinner component within a Mesop page. This snippet shows the import, page setup, and the direct usage of the `me.progress_spinner()` function. ```python import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/progress_spinner", ) def app(): with me.box(style=me.Style(margin=me.Margin.all(15))): me.progress_spinner() ``` -------------------------------- ### Create a Basic 'Hello World' Page Source: https://mesop-dev.github.io/mesop/getting-started/core-concepts This snippet shows how to create a root component for a specific path using the `@me.page` decorator and render simple text. Ensure you import mesop as me. ```python import mesop as me @me.page(path="/hello_world") def app(): me.text("Hello World") ``` -------------------------------- ### Render Matplotlib Figure with Plot Component Source: https://mesop-dev.github.io/mesop/components/plot This example demonstrates how to create a Matplotlib figure programmatically and render it using the `me.plot` component within a Mesop page. Ensure Matplotlib is installed. ```python from matplotlib.figure import Figure import mesop as me def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/plot", ) def app(): with me.box(style=me.Style(margin=me.Margin.all(15))): # Create matplotlib figure without using pyplot: fig = Figure() ax = fig.subplots() # type: ignore ax.plot([1, 2]) # type: ignore me.text("Example using matplotlib:", type="headline-5") me.plot(fig, style=me.Style(width="100%")) ``` -------------------------------- ### Create Project Directory Source: https://mesop-dev.github.io/mesop/codelab Create a new directory for your project and navigate into it. ```bash mkdir duochat cd duochat ``` -------------------------------- ### Start Python Debug Server Source: https://mesop-dev.github.io/mesop/guides/debugging Include this snippet at the top of your Mesop app to start a debug server that VS Code can attach to. ```python import debugpy debugpy.listen(5678) ``` -------------------------------- ### Basic Mesop Application Source: https://mesop-dev.github.io/mesop/codelab Create a simple Mesop application with a welcome message. This sets up the main page route. ```python import mesop as me @me.page(path="/") def page(): me.text("Welcome to DuoChat!") ``` -------------------------------- ### Install Mesop RC Version on Colab Source: https://mesop-dev.github.io/mesop/internal/publishing When testing on Colab, explicitly install the RC version of Mesop. Replace `0.X.Yrc1` with the specific RC version. ```python !pip install mesop==0.X.Yrc1 ``` -------------------------------- ### Set Page Title Example Source: https://mesop-dev.github.io/mesop/api/commands/set-page-title This example demonstrates how to use `me.set_page_title` to update the browser tab title when an input field loses focus. The title is reset when navigating to a new page. ```python import mesop as me def on_blur(e: me.InputBlurEvent): me.set_page_title(e.value) def load(e: me.LoadEvent): me.set_theme_mode("system") @me.page( on_load=load, security_policy=me.SecurityPolicy( allowed_iframe_parents=["https://mesop-dev.github.io"] ), path="/set_page_title", ) def app(): with me.box(style=me.Style(margin=me.Margin.all(15))): me.input(label="Page title", on_blur=on_blur) ``` -------------------------------- ### Enable Static Folder 'assets' and Default URL Path Source: https://mesop-dev.github.io/mesop/guides/static-assets Sets the static folder to 'assets' relative to the current working directory. Files will be accessible under the default '/static' URL path. ```bash cd /some/path/mesop-app MESOP_STATIC_FOLDER=assets mesop main.py ``` -------------------------------- ### Check Python Version Source: https://mesop-dev.github.io/mesop/getting-started/installing Verify that your Python installation meets the minimum version requirement (3.10 or later). ```bash python --version ``` -------------------------------- ### Mesop Page with Query Param Read/Write Source: https://mesop-dev.github.io/mesop/api/query-params Demonstrates reading query parameters and updating them via button clicks. Navigates to a new page with updated query parameters. ```python import mesop as me @me.page(path="/examples/query_params/page_2") def page_2(): me.text(f"query_params={me.query_params}") me.button("Add query param", on_click=add_query_param) me.button("Navigate", on_click=navigate) def add_query_param(e: me.ClickEvent): me.query_params["key"] = "value" def navigate(e: me.ClickEvent): me.navigate("/examples/query_params", query_params=me.query_params) ``` -------------------------------- ### Import Mesop Labs Source: https://mesop-dev.github.io/mesop/guides/labs Add this import statement to your Mesop application to start using Mesop Labs components. ```python import mesop.labs as mel ``` -------------------------------- ### Enable Static Folder 'assets' with Custom URL Path Source: https://mesop-dev.github.io/mesop/guides/static-assets Sets the static folder to 'assets' and customizes the URL path to '/assets'. Files will be accessible under the specified '/assets' URL path. ```bash cd /some/path MESOP_STATIC_FOLDER=assets mesop mesop-app/main.py ``` -------------------------------- ### Enable Static Folder and URL Path via Environment Variables Source: https://mesop-dev.github.io/mesop/guides/static-assets Configures the static folder to 'assets' and the URL path to '/assets' using environment variables directly in the command line. ```bash MESOP_STATIC_FOLDER=assets MESOP_STATIC_URL_PATH=/assets mesop main.py ``` -------------------------------- ### Get All Values for a Repeated Query Param Source: https://mesop-dev.github.io/mesop/api/query-params Retrieves all values associated with a query parameter key, useful when a key is repeated. ```python all_values = me.query_params.get_all('param_name') ```