### Run Rio Project with Rio CLI Source: https://rio.dev/docs/howto/project-setup This snippet shows how to run an existing Rio project using the `rio run` command. It includes instructions for navigating into the project directory and provides alternative commands for Python environments. This command starts the project for development or testing. ```Bash # Change into the new project directory cd project-name # Run the project rio run # Once again, if the command above doesn't work, try one of the following: python -m rio run python3 -m rio run py -m rio run ``` -------------------------------- ### Arrange Components Horizontally with rio.Row Source: https://rio.dev/docs/howto/layout-guide Shows how to use `rio.Row` to arrange child components horizontally. Includes examples of controlling the container's alignment and distributing space among children using `grow_x` and `rio.Spacer`. ```python rio.Row( ComponentA(), ComponentB(), ComponentC(), align_x=0, ) rio.Row( ComponentA(), ComponentB(), ComponentC(grow_x=True), ) rio.Row( ComponentA(), ComponentB(), rio.Spacer(), ComponentC(), ) ``` -------------------------------- ### Basic ListView Example with Single Selection (Python) Source: https://rio.dev/docs/api/listview Illustrates a basic Rio `ListView` setup displaying two items with single selection enabled. It shows how to preselect an item using the `selected_items` argument. This example is useful for simple list displays where only one item can be active at a time. ```python rio.ListView( rio.SimpleListItem("Item 1", key="item1"), rio.SimpleListItem("Item 2", key="item2"), selection_mode="single", selected_items=["item1"], # Preselect the first item ) ``` -------------------------------- ### Complete Example: Rio Persistent Settings with Dropdown Source: https://rio.dev/docs/howto/persistent-settings This comprehensive example illustrates using persistent settings with a Rio `Dropdown` component. It shows how to initialize settings, update them based on user interaction, and save the changes. ```python import rio class MyUserSettings(rio.UserSettings): language: str = "en" class MyRoot(rio.Component): def on_change_language(self, event: rio.DropdownChangeEvent) -> None: # Get the settings settings = self.session[MyUserSettings] # Update them settings.language = event.value # Re-attach to save the changes self.session.attach(settings) def build(self) -> rio.Component: settings = self.session[MyUserSettings] return rio.Dropdown( label="Language", options=["en", "de", "fr", "es"], selected_value=settings.language, on_change=self.on_change_language, min_width=20, align_x=0.5, align_y=0.5, ) app = rio.App( build=MyRoot, default_attachments=[ MyUserSettings(), ], ) ``` -------------------------------- ### Run Rio Project via CLI Source: https://rio.dev/docs/howto/run-project Standard commands to start a Rio application. These snippets demonstrate navigating to the project directory and executing the run command using the rio tool or Python interpreters. ```Bash cd your_project rio run ``` ```Bash python -m rio run ``` ```Bash python3 -m rio run ``` ```Bash py -m rio run ``` -------------------------------- ### Image Component Examples Source: https://rio.dev/docs/api/image Examples demonstrating how to use the Rio Image component with different image sources. ```APIDOC ## Image Component Examples ### Displaying an image from a URL This minimal example will display an image hosted on the web: ```python import rio rio.Image( rio.URL("https://example.com/image.png"), min_width=20, min_height=20, ) ``` ### Displaying an image from a local path You can also display images from a path. Note that Rio uses modern python `pathlib.Path` objects rather than plain strings. The image will be scaled to fit the shape, and the corners will be rounded with a radius of 2: ```python from pathlib import Path rio.Image( Path("example_image.png"), fill_mode="fit", min_width=20, min_height=20, corner_radius=2, ) ``` ### Displaying an image from the app's assets directory You can access the `App`'s assets directory using the `assets` property. This will return a `pathlib.Path` object pointing to the assets directory. The image will be scaled to fit the shape, and the corners will be rounded with a radius of 2: ```python # Assuming 'self.session.assets' is available and points to the assets directory from pathlib import Path rio.Image( Path(self.session.assets / "example_image.png"), fill_mode="fit", min_width=20, min_height=20, corner_radius=2, ) ``` ``` -------------------------------- ### Displaying Images in Rio Source: https://rio.dev/docs/api/image Examples demonstrating how to render images in a Rio application using URLs, local file paths, and the application's internal assets directory. These examples highlight the use of layout parameters like min_width, min_height, fill_mode, and corner_radius. ```python rio.Image( rio.URL("https://example.com/image.png"), min_width=20, min_height=20, ) ``` ```python from pathlib import Path rio.Image( Path("example_image.png"), fill_mode="fit", min_width=20, min_height=20, corner_radius=2, ) ``` ```python from pathlib import Path rio.Image( Path(self.session.assets / "example_image.png"), fill_mode="fit", min_width=20, min_height=20, corner_radius=2, ) ``` -------------------------------- ### Using Margins for Spacing in Python Source: https://rio.dev/docs/howto/layout-guide Illustrates how to add space around a component using margin parameters. This includes individual side margins, shorthand properties like `margin_x` and `margin_y`, and a universal `margin` property. ```python SampleComponent( # ... other parameters margin_left=5.0, margin_top=2.0, margin_right=5.0, margin_bottom=2.0 ) # Using shorthand properties SampleComponent( # ... other parameters margin_x=5.0, # Applies to left and right margin_y=2.0 # Applies to top and bottom ) # Using universal margin SampleComponent( # ... other parameters margin=3.0 # Applies to all sides ) ``` -------------------------------- ### Install Rio Window Extra Source: https://rio.dev/docs/api/app Command to install the necessary 'window' extra for running Rio applications in a local window. This enables the `run_in_window` functionality. ```bash pip install "rio-ui[window]" ``` -------------------------------- ### Display a Card Component Source: https://rio.dev/docs/api/card A minimal example demonstrating how to instantiate a Rio Card component with an icon. ```python rio.Card(content=rio.Icon("material/castle")) ``` -------------------------------- ### Set Component Margin in Rio Source: https://rio.dev/docs/howto/layout-guide Demonstrates how to apply margins to a component to create visual separation. Margins are specified in font heights, and more specific margin parameters override general ones. ```python rio.Row( ComponentA(), ComponentB(), ComponentC(), margin=3 ) rio.Row( ComponentA(), ComponentB(), ComponentC(), margin=1, margin_left=10 ) ``` -------------------------------- ### Custom Dialog Example Source: https://rio.dev/docs/api/session Demonstrates spawning a custom dialog with a dropdown for user selection. The selected value is returned upon closing the dialog. ```APIDOC ## Custom Dialog Example ### Description This example demonstrates how to spawn a custom dialog that allows the user to select a value from a Dropdown menu. Once the user selects an option, the dialog closes, and the selected value is returned. ### Method `session.show_custom_dialog` (internal) ### Endpoint N/A (Client-side interaction) ### Parameters N/A (Programmatic invocation within Python code) ### Request Example ```python class MyComponent(rio.Component): value: str = "Vanilla" async def _create_dialog(self, options: list[str]) -> str | None: # This function will be called to create the dialog's content. # It builds up a UI using Rio components, just like a regular # `build` function would. def build_dialog_content() -> rio.Component: # Build the dialog return rio.Card( rio.Column( rio.Text( "Which ice cream would you like?", align_x=0.5, ), rio.Dropdown( label="ice cream", options=options, selected_value=self.value, on_change=on_value_change, ), spacing=1, margin=2, ), align_x=0.5, align_y=0.5, ) async def on_value_change(event: rio.DropdownChangeEvent) -> None: # This function will be called whenever the user selects an # Item. It simply closes the dialog with the selected value. await dialog.close(event.value) # Show the dialog dialog = await self.session.show_custom_dialog( build=build_dialog_content, # Prevent the user from interacting with the rest of the app # while the dialog is open modal=True, # Don't close the dialog if the user clicks outside of it user_closable=False, ) # Wait for the user to select an option result = await dialog.wait_for_close() # Return the selected value return result async def on_spawn_dialog(self) -> None: # Show a dialog and wait for the user to make a choice value = await self._create_dialog( options=["Vanilla", "Chocolate", "Strawberry"], ) # Store the value, but only if one was selected. If the dialog # gets closed without a selection, `value` will be `None`. if value is not None: self.value = value def build(self) -> rio.Component: return rio.Column( rio.Button( "Open Dialog", on_press=self.on_spawn_dialog, ), rio.Text(f"You've chosen: {self.value}"), spacing=1, align_x=0.5, align_y=0.5, ) ``` ### Response #### Success Response (200) - **result** (str | None) - The value selected by the user, or None if the dialog was closed without a selection. #### Response Example ```json "Chocolate" ``` ``` -------------------------------- ### Containers for Multiple Components in Python Source: https://rio.dev/docs/howto/layout-guide Shows how to use container components like `rio.Row`, `rio.Column`, and `rio.Grid` to arrange multiple child components. These containers provide layout management and options like `spacing` to control the space between elements. ```python import rio rio.Column( rio.Button("Button 1"), rio.Button("Button 2"), rio.Button("Button 3"), spacing=10 # Adds 10 units of space between buttons ) rio.Row( rio.Text("Label"), rio.Input(), spacing=5 ) rio.Grid( [rio.Button("A1"), rio.Button("B1")], [rio.Button("A2"), rio.Button("B2")] ) ``` -------------------------------- ### Component Alignment in Python Source: https://rio.dev/docs/howto/layout-guide Demonstrates how to set horizontal and vertical alignment for a component using `align_x` and `align_y` parameters. These parameters accept float values between 0 and 1 to control positioning within the available space. ```python SampleComponent( # ... other parameters align_x=0.5, # Center horizontally align_y=0.25 # Align towards the top vertically ) ``` -------------------------------- ### LinearGradientFill Constructor Example (Python) Source: https://rio.dev/docs/api/lineargradientfill Demonstrates how to create a LinearGradientFill object in Python. It shows the usage of stops with colors and positions, and setting the gradient angle. ```python import rio # Example with two stops gradient1 = rio.LinearGradientFill(rio.Color.RED, rio.Color.BLUE, angle_degrees=45.0) # Example with multiple stops and explicit positions gradient2 = rio.LinearGradientFill( (rio.Color.GREEN, 0.0), (rio.Color.YELLOW, 0.5), (rio.Color.PURPLE, 1.0), angle_degrees=90.0 ) ``` -------------------------------- ### Overlay Component Constructor and Usage (Python) Source: https://rio.dev/docs/api/overlay Demonstrates the constructor for the Overlay component, which takes a child component to display. It highlights the 'content' and 'key' properties and provides an example of centering text within the overlay. ```Python class Overlay: def __init__(self, content: Component, *, key: str | int | None = None): pass # Example usage: rio.Overlay( rio.Text("Hello, world!"), ) ``` -------------------------------- ### Create a Simple Text Link with Rio Source: https://rio.dev/docs/api/link This example shows how to create a basic Rio Link that displays text and navigates to a specified URL when clicked. It requires the 'rio' library. ```python rio.Link("Click me!", "https://example.com") ``` -------------------------------- ### Display PDF from URL or Local Path using Rio Source: https://rio.dev/docs/api/pdfviewer Demonstrates how to initialize the PdfViewer component using a web URL or a local file path. These examples show the basic implementation for rendering PDF documents in a Rio interface. ```python rio.PdfViewer( rio.URL("https://example.com/document.pdf"), ) ``` ```python from pathlib import Path rio.PdfViewer( Path("example_document.pdf"), ) ``` -------------------------------- ### Setting Minimum Component Size in Python Source: https://rio.dev/docs/howto/layout-guide Explains how to define the minimum width and height for a component using `min_width` and `min_height` parameters. These ensure a component does not shrink below a certain size, even when placed within a container that might allocate less space. ```python SampleComponent( # ... other parameters min_width=30.0, min_height=30.0 ) ``` -------------------------------- ### Initialize and Run a Rio App Source: https://rio.dev/docs/api/app Demonstrates how to instantiate a Rio App and execute it using various deployment methods, including windowed mode, web server, and FastAPI integration. ```python app = rio.App( name="My App", build=MyAppRoot, ) # Run in a window app.run_in_window() # Run as a web server app.run_as_web_server() # Integrate with FastAPI fastapi_app = app.as_fastapi() ``` -------------------------------- ### Create and Apply a Custom Theme in Rio Source: https://rio.dev/docs/api/theme Demonstrates how to instantiate a new theme using the from_colors method and apply it to a Rio application instance. ```python # Create a new theme theme = rio.Theme.from_colors( # Configure your theme here ) # And apply it to your app app = rio.App( theme=theme, # ... ) ``` -------------------------------- ### Writing a Dockerfile for a Python Rio App Source: https://rio.dev/docs/howto/deployment-in-docker This Dockerfile defines the steps to build a Docker image for a Python-based Rio application. It assumes the project uses `pyproject.toml` for dependency management and installs dependencies using `uv`. The `CMD` instruction starts the Rio server in release mode. ```dockerfile # Use the official Python image as a base. This ensures that typical Python # dependencies are already installed in the container. FROM python:3.12-slim # Make port 8000 available to the outside world. This is the port Rio will run # at EXPOSE 8000 # Set environment variables to prevent Python from writing `.pyc` files and # creating a buffer for stdout ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 # Set the working directory in the container WORKDIR /app # Install the latest version of `uv`. `uv` is similar to `pip`, but much faster # and supports additional commands we'll use below COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/ # Docker caches the results of each RUN instruction. Whenever a container is # rebuilt, Docker will avoid running any steps whose results are still valid # from last time. # # To make sure the dependencies don't all have to be reinstalled every time you # change a single line of code, we'll install them before adding the bulk of the # project files. # # Some build tools, like `poetry` require the project's README file to be # present for this step. If your file is named differently or you don't have one # at all, update this line or add a file. COPY pyproject.toml README.md /app/ RUN uv pip install -r pyproject.toml --system --pre # Alternatively, if you're using a `requirements.txt` file instead of # `pyproject.toml`, you can use the following commands instead: # # COPY requirements.txt /app # RUN uv pip install -r requirements.txt --pre # Now copy the remainder of the project. This way if anything in the project # changes the dependencies don't have to be reinstalled. COPY . /app # This command will be run by docker once you run the container. It starts the # Rio server in release mode, on port 8000. We also make the port publicly # available, so that Docker can expose it to the outside world. CMD ["python", "-m", "rio", "run", "--release", "--port=8000", "--public"] ``` -------------------------------- ### Text Input Component Example Source: https://rio.dev/docs/api/textinput Example of a Rio TextInput component that displays user input. ```APIDOC ## Examples ### Text Input with Attribute Binding This example demonstrates how to create a text input field and display its value using attribute binding. #### Method ```python class MyComponent(rio.Component): text: str = "Hello, World!" def build(self) -> rio.Component: return rio.Column( rio.TextInput( text=self.bind().text, label="Enter a Text", ), rio.Text(f"You've typed: {self.text}"), ) ``` ### Text Input with Event Handler This example shows how to use an event handler to react to changes in the text input. #### Method ```python class MyComponent(rio.Component): text: str = "Hello, World!" def on_value_change(self, event: rio.TextInputChangeEvent): self.text = event.text print(f"You've typed: {self.text}") def build(self) -> rio.Component: return rio.TextInput( text=self.text, label="Enter a Text", on_change=self.on_value_change, ) ``` ``` -------------------------------- ### Create a Rio Website Instance Source: https://rio.dev/docs/api/website Demonstrates how to create a basic Rio Website instance with a given URL. This is a fundamental step for displaying web content using the Rio framework. ```python rio.Website( url=rio.URL("https://www.example.com"), ) ``` -------------------------------- ### Create New Project with Rio CLI Source: https://rio.dev/docs/howto/project-setup This snippet demonstrates how to create a new project using the `rio new` command. It includes instructions for changing directories and alternative commands for Python environments where direct command execution might fail. The command prompts the user for project details. ```Bash # Change into the directory where you want to create the new project cd /path/to/your/projects # Run the `rio new` command rio new # On some platforms, python packages aren't available right in the terminal. If # the command above doesn't work, try one of the following: python -m rio new python3 -m rio new py -m rio new ``` -------------------------------- ### ThemeContextSwitcher Example in Python Source: https://rio.dev/docs/api/themecontextswitcher A minimal example demonstrating the creation of a ThemeContextSwitcher component in Python. This component is used to switch themes and accepts content and a color theme as arguments. ```python rio.ThemeContextSwitcher( content=rio.Button("Button"), color="secondary", ) ``` -------------------------------- ### Implement Rio Components with Type Hints Source: https://rio.dev/docs/howto/type-hints Illustrates the mandatory use of type hints for Rio component attributes and recommended usage for component methods to ensure proper framework functionality. ```python class MyComponent(rio.Component): label: str = 'Click Me!' async def on_button_press(self) -> None: self.label = 'Button Pressed!' def build(self) -> rio.Component: return rio.Button( self.label, on_press=self.on_button_press, ) ``` -------------------------------- ### Python: Rio List Component Example Source: https://rio.dev/docs/api/list Demonstrates how to use the experimental Rio List component to create a dynamic list that automatically updates UI elements when its content changes. This example showcases adding elements and displaying them in real-time. ```Python class ElementAdder(rio.Component): list: rio.List[str] def build(self): return rio.Button( "add an element", on_press=lambda: self.list.append("foo"), ) class Display(rio.Component): list: rio.List[str] def build(self): return rio.Text("\n".join(self.list)) class ListDemo(rio.Component): list: rio.List[str] = rio.List() def build(self): return rio.Column( ElementAdder(self.list), Display(self.list), ) ``` -------------------------------- ### MediaPlayer Constructor and Options Source: https://rio.dev/docs/api/mediaplayer Demonstrates the instantiation of the MediaPlayer component with various configuration options. It highlights parameters for media source, playback behavior (loop, autoplay), user controls, audio settings (muted, volume), background styling, and event handling. ```python import rio import pathlib # Example usage of MediaPlayer media_player = rio.MediaPlayer( media=pathlib.Path("path/to/your/media.mp4"), # or rio.URL("http://example.com/media.mp4") or bytes media_type="video/mp4", loop=True, autoplay=False, controls=True, muted=False, volume=0.8, background=rio.Color("#333333"), on_playback_end=lambda: print("Playback ended!"), on_error=lambda: print("An error occurred!"), key="my_media_player", margin=10 ) ``` -------------------------------- ### GET /components/markdown Source: https://rio.dev/docs/api/markdown Displays markdown-formatted text within the Rio application. ```APIDOC ## POST /components/markdown ### Description Initializes a Markdown component to render formatted text strings. ### Method POST ### Request Body - **content** (string) - Required - The markdown formatted string to render. ### Request Example { "content": "# Hello, world!\n\nI am a **Markdown** component." } ### Response #### Success Response (200) - **status** (string) - Component successfully initialized. ``` -------------------------------- ### Python Dataclass Example Source: https://rio.dev/docs/howto/introduction-to-dataclasses Demonstrates a standard Python class definition for data storage, including `__init__`, `__repr__`, and `__eq__` methods. ```python class Person: def __init__(self, name: str, age: int): self.name = name self.age = age def __repr__(self): return f"Person(name={self.name}, age={self.age})" def __eq__(self, other): if isinstance(other, Person): return self.name == other.name and self.age == other.age return False ``` -------------------------------- ### Rio Set Component Constructor and Usage (Python) Source: https://rio.dev/docs/api/set Demonstrates the constructor and practical application of the `rio.Set` component in Python. It shows how to initialize a `Set` and integrate it with Rio components for dynamic UI updates, specifically in scenarios where adding elements to the set triggers component re-renders. ```Python class ElementAdder(rio.Component): set: rio.Set[str] def build(self): return rio.Button( "add an element", on_press=lambda: self.set.add(len(self.set)), ) class Display(rio.Component): set: rio.Set[str] def build(self): return rio.Text("\n".join(self.set)) class SetDemo(rio.Component): set: rio.Set[str] = rio.Set() def build(self): return rio.Column( ElementAdder(self.set), Display(self.set), ) ``` -------------------------------- ### Create a basic Column in Python Source: https://rio.dev/docs/api/column A minimal example showing how to initialize a Column component with multiple child components directly in the constructor. ```python rio.Column(rio.Text("Hello"), rio.Text("World!")) ``` -------------------------------- ### Using Spacer in a Row layout Source: https://rio.dev/docs/api/spacer This example demonstrates how to use a Spacer within a rio.Row to push two text elements to opposite ends of the container. ```python rio.Row( rio.Text("Hello"), rio.Spacer(), rio.Text("World"), ) ``` -------------------------------- ### Display a Simple List Item in Rio Source: https://rio.dev/docs/api/simplelistitem A minimal example demonstrating how to instantiate a SimpleListItem component. This component is used to display a single item within a list structure. ```Python rio.SimpleListItem("Click me!", key="item1") ``` -------------------------------- ### Build a complex Column layout in Python Source: https://rio.dev/docs/api/column An example of a custom component that uses a Column to arrange text and icons inside a Card, demonstrating the use of spacing and margin properties. ```python class MyComponent(rio.Component): def build(self) -> rio.Component: return rio.Card( content=rio.Column( rio.Text("Hello"), rio.Icon("material/castle"), rio.Text("World!"), spacing=1, margin=1, ), ) ``` -------------------------------- ### Rio App Lifecycle Initialization and Event Handling Source: https://rio.dev/docs/howto/app-lifecycle Demonstrates the basic structure for handling the Rio app lifecycle events, including app start, session start/close, and app close. This is essential for managing application state and resources. ```python import rio app = rio.App(...) @app.on_app_start def on_app_start(): print("App starting...") # Initialize app-level resources here @app.on_session_start def on_session_start(): print("Session started.") # Initialize user-specific session data here @app.on_session_close def on_session_close(): print("Session closed.") # Clean up user-specific session data here @app.on_app_close def on_app_close(): print("App closing...") # Clean up app-level resources here ``` -------------------------------- ### Rio Component Attribute Binding Example Source: https://rio.dev/docs/api/component Illustrates how to create an attribute binding between a parent component and its child using `self.bind()`. This allows child components to pass values up to their parent. ```Python class AttributeBindingExample(rio.Component): toggle_is_on: bool = False def build(self) -> rio.Component: return rio.Column( # Thanks to the attribute binding, toggling the Switch will # also update this component's `toggle_is_on` attribute rio.Switch(self.bind().toggle_is_on), rio.Text("ON" if self.toggle_is_on else "OFF"), ) ``` -------------------------------- ### escape_markdown_code Source: https://rio.dev/docs/api/escape_markdown_code Escapes text to be displayed verbatim within a markdown code block. This is useful for preventing markdown interpretation of special characters in code examples or raw text. ```APIDOC ## escape_markdown_code ### Description Escape text such that it appears as-is inside a markdown code block. Given any text, this function returns a string which, when rendered inside a markdown code block, will look identical to the original text. ### Method N/A (This appears to be a function description rather than an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **text** (str) - Required - The text to escape. ### Request Example ```json { "text": "This is **bold** text." } ``` ### Response #### Success Response (200) - **escaped_text** (str) - The escaped text suitable for markdown code blocks. #### Response Example ```json { "escaped_text": "This is **bold** text." } ``` ```