### Run Shiny Example Application Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/templates/package/js-output/README.md Execute the example application from the command line after building the necessary assets. ```bash Shiny run example-app/app.py ``` -------------------------------- ### Install Shiny for Development Source: https://github.com/posit-dev/py-shiny/blob/main/tests/playwright/shiny/components/MarkdownStream/basic/README.md Install Shiny with development and testing dependencies for local development. ```sh pip install -e ".[dev,test]" ``` -------------------------------- ### Install Build Dependencies Source: https://github.com/posit-dev/py-shiny/blob/main/docs/README.md Installs the necessary Python dependencies and Quarto extensions for building the documentation. ```bash make deps ``` -------------------------------- ### Install rsconnect-python Source: https://github.com/posit-dev/py-shiny/wiki/Deploying-on-Connect Install the rsconnect command line tool via pip. ```bash pip3 install rsconnect-python ``` -------------------------------- ### Install Shiny from PyPI Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Install the latest stable version of Shiny for Python using pip. ```sh pip install shiny ``` -------------------------------- ### Test an example app with create_example_fixture Source: https://github.com/posit-dev/py-shiny/blob/main/tests/playwright/README.md Demonstrates testing an app located in the ../examples directory by creating a custom fixture. ```python import re from playwright.sync_api import Locator, Page, expect ShinyAppProc from conftest import create_example_fixture airmass_app = create_example_fixture("airmass") def test_airmass(page: Page, airmass_app: ShinyAppProc): page.goto(airmass_app.url) plot = page.locator("#plot") expect(plot).to_have_class(re.compile(r"\bshiny-bound-output\b")) ``` -------------------------------- ### Install and Load Shiny Source: https://github.com/posit-dev/py-shiny/blob/main/examples/code-editor/examples/markdown.md Use these commands to install the package from CRAN and load it into your R session. ```r install.packages("shiny") library(shiny) ``` -------------------------------- ### Install Development Version of Shiny Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Install the latest development versions of htmltools and Shiny from GitHub. Ensure htmltools is installed first. ```sh # First install htmltools, then shiny pip install git+https://github.com/posit-dev/py-htmltools.git#egg=htmltools pip install git+https://github.com/posit-dev/py-shiny.git#egg=shiny ``` -------------------------------- ### Run Shiny Application Source: https://github.com/posit-dev/py-shiny/blob/main/examples/open-telemetry/README.md Execute the application script to start the Shiny server. ```bash python app.py ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Install pre-commit hooks to automatically format and lint code upon committing. To disable, use 'pre-commit uninstall'. ```sh pre-commit install ``` -------------------------------- ### Create API Example for Express Mode Source: https://github.com/posit-dev/py-shiny/blob/main/scripts/README-porting-from-bslib.md Example application demonstrating a new component's usage in py-shiny's Express mode. This shows how to define the UI element and render its server-side value. ```python # app-express.py from shiny.express import input, render, ui ui.input_submit_textarea("text", placeholder="Enter some input...") @render.text def value(): if "text" in input: return f"You entered: {input.text()}" else: return "Submit some input to see it here." ``` -------------------------------- ### Install JavaScript Dependencies Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/templates/package/js-input/README.md Install the necessary Node.js dependencies for building the JavaScript assets of the custom component. This command should be run from the repository root. ```bash npm install ``` -------------------------------- ### Install Shiny with Development Dependencies Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Install Shiny along with development and testing dependencies using pip. This command requires git tags to be present. ```sh pip install -e ".[dev,test,doc]" ``` -------------------------------- ### Get Shinylive Extension Info Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Prints information about the Shinylive extension, including version, assets version, and script paths. This is useful for verifying the extension's installation and configuration. ```json { "version": "0.1.0", "assets_version": "0.2.0", "scripts": { "codeblock-to-json": "//shinylive-0.2.0/scripts/codeblock-to-json.js" } } ``` -------------------------------- ### Install Python Package in Editable Mode Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/templates/package/js-output/README.md Run this command from the repository root to install the package in editable mode. ```bash pip install -e . ``` -------------------------------- ### Install Shiny Dependencies Source: https://github.com/posit-dev/py-shiny/wiki/Getting-started Install required packages using a requirements file from the RStudio repository. ```sh curl https://rstudio.github.io/prism/requirements.txt > requirements.txt python3 -m pip install -r requirements.txt ``` -------------------------------- ### Run essential development commands Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Commands for installing dependencies, formatting code, type checking, and running tests. ```bash # Install dev dependencies pip install -e ".[dev,test,doc]" # Format code (always run before committing) make format # Auto-fix with black and isort make check-format # Check only # Type checking make check-types # Run pyright (requires typings) # Run tests make test # Unit tests only (pytest) make playwright # All end-to-end tests (slow) make playwright-shiny SUB_FILE="inputs/test_foo.py" # Single test # Comprehensive checks make check # Format, lint, types, unit tests make check-fix # Same but auto-fixes formatting ``` -------------------------------- ### Complete Shiny App with Bookmarking Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md This example demonstrates a full Shiny app with bookmarking enabled. It shows how to exclude inputs from automatic saving, handle custom value storage, and restore specific input states. ```python from starlette.requests import Request from shiny import App, Inputs, Outputs, Session, reactive, render, ui from shiny.bookmark import BookmarkState, RestoreState def app_ui(request: Request): return ui.page_fluid( ui.markdown( "Directions: " "\n1. Change the radio buttons below" "\n2. Refresh your browser." "\n3. The radio buttons should be restored to their previous state." ), ui.hr(), ui.input_radio_buttons( "letter", "Choose a letter (Store in Bookmark 'input')", choices=["A", "B", "C"], ), ui.input_radio_buttons( "letter_values", "Choose a letter (Stored in Bookmark 'values' as lowercase)", choices=["A", "B", "C"], ), "Selection:", ui.output_code("letters"), ) def server(input: Inputs, output: Outputs, session: Session): # Exclude "letter_values" from being saved automatically session.bookmark.exclude.append("letter_values") lowercase_letter = reactive.value() @reactive.effect @reactive.event(input.letter_values) async def _(): lowercase_letter.set(input.letter_values().lower()) @render.code def letters(): return str([input.letter(), lowercase_letter()]) # Bookmark when inputs change @reactive.effect @reactive.event(input.letter, lowercase_letter, ignore_init=True) async def _(): await session.bookmark() # Store custom values before bookmarking @session.bookmark.on_bookmark async def _(state: BookmarkState): state.values["lowercase"] = lowercase_letter() # Update URL after bookmarking @session.bookmark.on_bookmarked async def _(url: str): await session.bookmark.update_query_string(url) # Restore custom values @session.bookmark.on_restore def _(state: RestoreState): if "lowercase" in state.values: uppercase = state.values["lowercase"].upper() ui.update_radio_buttons("letter_values", selected=uppercase) app = App(app_ui, server, bookmark_store="url") ``` -------------------------------- ### Manage JavaScript Dependencies and Builds Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/templates/package/js-output/README.md Commands for installing dependencies and managing the build process for the component's JavaScript assets. ```bash npm install ``` ```bash npm run build ``` ```bash npm run watch ``` -------------------------------- ### Shiny Reactive Primitives Example Source: https://context7.com/posit-dev/py-shiny/llms.txt Demonstrates Shiny's reactive primitives: reactive.Value for mutable state, reactive.calc for cached computed values, and reactive.effect for side effects triggered by dependencies. Includes a counter example. ```python from shiny import App, Inputs, Outputs, Session, reactive, render, ui app_ui = ui.page_fluid( ui.input_action_button("increment", "Increment"), ui.input_action_button("reset", "Reset"), ui.output_text_verbatim("counter_display"), ui.output_text_verbatim("doubled_display"), ) def server(input: Inputs, output: Outputs, session: Session): # reactive.Value: mutable reactive state counter = reactive.Value(0) # reactive.effect: side effects triggered by reactive dependencies @reactive.effect @reactive.event(input.increment) def _increment(): counter.set(counter() + 1) @reactive.effect @reactive.event(input.reset) def _reset(): counter.set(0) # reactive.calc: cached computed value @reactive.calc def doubled(): return counter() * 2 @render.text def counter_display(): return f"Counter: {counter()}" @render.text def doubled_display(): return f"Doubled: {doubled()}" app = App(app_ui, server) ``` -------------------------------- ### Python Docstring Example Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Follows Google-style docstrings with markdown formatting. Use this for function and class documentation. ```python def foo(x: int, name: str) -> bool: """ Brief one-line description. Longer description paragraph if needed. Can use markdown formatting like `code`, **bold**, and even code blocks. Parameters ---------- x Description of x parameter. name Description of name parameter. Returns ------- : Description of return value. Examples -------- ```python result = foo(42, "test") ``` See Also -------- * `bar()` - Related function that does something similar * `baz()` - Another related function """ pass ``` -------------------------------- ### Shiny Input Components Example Source: https://context7.com/posit-dev/py-shiny/llms.txt Demonstrates various Shiny input components including sliders, text inputs, selection inputs, boolean inputs, date inputs, action inputs, and file inputs. The server function displays the current values of selected inputs. ```python from shiny import App, render, ui app_ui = ui.page_fluid( # Numeric inputs ui.input_slider("slider", "Slider:", min=0, max=100, value=50), ui.input_numeric("num", "Numeric:", value=10, min=0, max=100), # Text inputs ui.input_text("text", "Text input:", value="Hello"), ui.input_text_area("textarea", "Text area:", rows=3), ui.input_password("password", "Password:"), # Selection inputs ui.input_select("select", "Select:", choices=["A", "B", "C"]), ui.input_selectize("selectize", "Selectize:", choices=["X", "Y", "Z"], multiple=True), ui.input_radio_buttons("radio", "Radio:", choices=["One", "Two", "Three"]), ui.input_checkbox_group("checks", "Checkboxes:", choices=["a", "b", "c"]), # Boolean inputs ui.input_checkbox("check", "Single checkbox", value=True), ui.input_switch("switch", "Switch", value=False), # Date inputs ui.input_date("date", "Date:"), ui.input_date_range("daterange", "Date range:"), # Action inputs ui.input_action_button("btn", "Click me!"), ui.input_action_link("link", "Click this link"), # File input ui.input_file("file", "Upload file:", multiple=True), # Display the values ui.output_text_verbatim("values"), ) def server(input, output, session): @render.text def values(): return f""" Slider: {input.slider()} Text: {input.text()} Select: {input.select()} Checkbox: {input.check()} Date: {input.date()} """ app = App(app_ui, server) ``` -------------------------------- ### Install Local Shiny Checkout as Editable Package Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Install a local checkout of the py-shiny repository as an editable package. This is useful for developing new features and testing them in an application. ```sh # Rather than # pip install shiny # run: pip install -e ../py-shiny --config-settings editable_mode=compat ``` -------------------------------- ### Shiny Render Decorators Example Source: https://context7.com/posit-dev/py-shiny/llms.txt Illustrates Shiny's render decorators for displaying dynamic content. Includes rendering text, code, matplotlib plots, static tables, dynamic UI elements, and interactive data frames. ```python from shiny import App, render, ui import matplotlib.pyplot as plt import pandas as pd import numpy as np app_ui = ui.page_fluid( ui.input_slider("n", "N:", min=10, max=100, value=50), ui.output_text("text_out"), ui.output_text_verbatim("code_out"), ui.output_plot("plot_out"), ui.output_table("table_out"), ui.output_ui("ui_out"), ui.output_data_frame("df_out"), ) def server(input, output, session): # Render text @render.text def text_out(): return f"You selected {input.n()}" # Render code (monospace) @render.code def code_out(): return f"result = compute({input.n()})" # Render matplotlib plot @render.plot def plot_out(): fig, ax = plt.subplots() x = np.random.randn(input.n()) ax.hist(x, bins=20) ax.set_title(f"Histogram of {input.n()} values") return fig # Render static table @render.table def table_out(): return pd.DataFrame({"x": range(5), "y": range(5, 10)}) # Render dynamic UI @render.ui def ui_out(): return ui.tags.div( ui.tags.strong(f"Dynamic content for n={input.n()}"), ui.tags.ul([ui.tags.li(str(i)) for i in range(min(5, input.n()))]) ) # Render interactive data frame @render.data_frame def df_out(): df = pd.DataFrame({ "A": np.random.randn(input.n()), "B": np.random.randn(input.n()), }) return render.DataGrid(df, selection_mode="rows", filters=True) app = App(app_ui, server) ``` -------------------------------- ### Access Restored State in Bookmark Callbacks Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md This example demonstrates how to access restored input values and custom data within the @session.on_restore callback using the provided RestoreState object. ```python @session.bookmark.on_restore def _(state: RestoreState): # Access restored inputs if "choice" in state.input: print(f"Restoring choice: {state.input['choice']}") # Access restored custom values if "custom_data" in state.values: print(f"Restoring custom data: {state.values['custom_data']}") # Access bookmark directory (for server bookmarks) if state.dir: print(f"Bookmark directory: {state.dir}") ``` -------------------------------- ### Get Shinylive Language Resources Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Prints language-specific resource files for the Shinylive Quarto HTML dependency. This includes files for R (webr) and Python (Pyodide, Pyright). ```json [ { "name": "shinylive/webr/esbuild.d.ts", "path": "//shinylive-0.2.0/shinylive/webr/esbuild.d.ts" }, { "name": "shinylive/webr/libRblas.so", "path": "//shinylive-0.2.0/shinylive/webr/libRblas.so" }, ... # [ truncated ] ] ``` -------------------------------- ### Get Shinylive Base HTML Dependencies Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Prints the language-agnostic Quarto HTML dependencies for Shinylive. This includes service workers and base dependencies containing core scripts, stylesheets, and resources. ```json [ { "name": "shinylive-serviceworker", "version": "0.2.0", "meta": { "shinylive:serviceworker_dir": "." }, "serviceworkers": [ { "source": "//shinylive-0.2.0/shinylive-sw.js", "destination": "/shinylive-sw.js" } ] }, { "name": "shinylive", "version": "0.2.0", "scripts": [{ "name": "shinylive/load-shinylive-sw.js", "path": "//shinylive-0.2.0/shinylive/load-shinylive-sw.js", "attribs": { "type": "module" } }], "stylesheets": [{ "name": "shinylive/shinylive.css", "path": "//shinylive-0.2.0/shinylive/shinylive.css" }], "resources": [ { "name": "shinylive/shinylive.js", "path": "//shinylive-0.2.0/shinylive/shinylive.js" }, ... # [ truncated ] ] } ] ``` -------------------------------- ### Add Upstream Tags to Fork Source: https://github.com/posit-dev/py-shiny/blob/main/README.md If working from a fork, add tags from the original repository to enable installation. Fetch tags from the upstream remote. ```sh git remote add upstream https://github.com/posit-dev/py-shiny.git git fetch --tags upstream ``` -------------------------------- ### Get Shinylive App Resources Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Prints app-specific resource files as JSON for the Shinylive Quarto HTML dependency. Currently, r-shinylive does not return any resource files, but py-shinylive includes Python package wheels. ```json [ { "name": "shinylive/pyodide/anyio-3.7.0-py3-none-any.whl", "path": "//shinylive-0.2.0/shinylive/pyodide/anyio-3.7.0-py3-none-any.whl" }, { "name": "shinylive/pyodide/appdirs-1.4.4-py2.py3-none-any.whl", "path": "//shinylive-0.2.0/shinylive/pyodide/appdirs-1.4.4-py2.py3-none-any.whl" }, ... # [ truncated ] ] ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/posit-dev/py-shiny/blob/main/docs/README.md Builds the documentation site, serves it locally, and watches for changes in the .qmd files for live updates. ```bash make serve ``` -------------------------------- ### Build project documentation Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Commands for generating and previewing API documentation. ```bash # Build API docs (slow, run at the end) make docs # Build with quartodoc make docs-preview # Build and serve locally ``` -------------------------------- ### Build Documentation Site Once Source: https://github.com/posit-dev/py-shiny/blob/main/docs/README.md Builds the documentation site a single time without serving it locally or watching for changes. ```bash make site ``` -------------------------------- ### Register Connect Server Source: https://github.com/posit-dev/py-shiny/wiki/Deploying-on-Connect Register a Connect server and account using the CLI. ```bash rsconnect add -n -s -k ``` ```bash rsconnect add -n rstudioservices -s https://connect.rstudioservices.com/ -k ``` -------------------------------- ### Initialize Project Directory Source: https://github.com/posit-dev/py-shiny/wiki/Getting-started Create and navigate to a new directory for the Shiny application. ```sh mkdir my-shiny-app cd my-shiny-app ``` -------------------------------- ### Deploy Application Source: https://github.com/posit-dev/py-shiny/wiki/Deploying-on-Connect Deploy the application using the fastapi entrypoint. ```bash rsconnect deploy fastapi . --entrypoint app:app ``` -------------------------------- ### Configure Virtual Environment Source: https://github.com/posit-dev/py-shiny/wiki/Getting-started Set up and activate a Python virtual environment for the project. ```sh # Create a virtual environment in the .venv subdirectory python3 -m venv .venv # Activate the virtual environment source .venv/bin/activate ``` -------------------------------- ### View Span Hierarchy Source: https://github.com/posit-dev/py-shiny/blob/main/examples/open-telemetry/README.md Example structure of telemetry spans generated when collection is enabled. ```text session_start └─ reactive_update ├─ reactive.calc result ├─ reactive.effect └─ output result_private (suppressed with @otel.suppress) ``` -------------------------------- ### Implement Page Layouts Source: https://context7.com/posit-dev/py-shiny/llms.txt Demonstrates the use of page_sidebar and page_navbar for organizing application structure. ```python from shiny import App, render, ui # Page with sidebar layout app_ui = ui.page_sidebar( ui.sidebar( ui.input_select("var", "Variable:", choices=["mpg", "hp", "wt"]), ui.input_switch("smooth", "Add smoother", value=True), ), ui.output_plot("scatter"), title="Sidebar App", ) # Page with navbar for multi-page apps navbar_ui = ui.page_navbar( ui.nav_panel("Home", ui.output_text("home_content")), ui.nav_panel("Data", ui.output_data_frame("data_table")), ui.nav_panel("About", ui.markdown("## About this app")), title="Multi-Page App", id="navbar", ) def server(input, output, session): @render.plot def scatter(): import matplotlib.pyplot as plt import numpy as np x = np.random.randn(100) y = x + np.random.randn(100) * 0.5 plt.scatter(x, y) if input.smooth(): z = np.polyfit(x, y, 1) p = np.poly1d(z) plt.plot(sorted(x), p(sorted(x)), "r--") app = App(app_ui, server) ``` -------------------------------- ### PR Title Examples Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md PR titles should also follow the conventional commit format for consistency. ```git feat: Add Toolbar component ``` ```git fix: Pin griffe to <2.0.0 for quartodoc compatibility ``` ```git refactor: Simplify reactive graph invalidation logic ``` -------------------------------- ### Define HTML Attributes and Children Source: https://github.com/posit-dev/py-shiny/wiki/Getting-started Examples of using htmltools to define attributes and nested children in Python. ```python >>> from shiny.ui import * >>> a(href="help.html") ``` ```python >>> tags.span("Hello", strong("world")) Hello world ``` ```python >>> a(span("Learn more", class_ = "help-text"), href="help.html") Learn more ``` ```python a({"href": "help.html"}, span({"class": "help-text"}, "Learn more" ) ) ``` -------------------------------- ### Configure server-side bookmark storage Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Define custom directories for saving and restoring bookmark data when using server-side persistence. ```python from pathlib import Path from shiny.bookmark import set_global_save_dir_fn, set_global_restore_dir_fn bookmark_dir = Path(__file__).parent / "bookmarks" def save_bookmark_dir(id: str) -> Path: save_dir = bookmark_dir / id save_dir.mkdir(parents=True, exist_ok=True) return save_dir def restore_bookmark_dir(id: str) -> Path: return bookmark_dir / id # Set global defaults for bookmark saving and restoring set_global_restore_dir_fn(restore_bookmark_dir) set_global_save_dir_fn(save_bookmark_dir) app = App(app_ui, server, bookmark_store="server") ``` -------------------------------- ### Conventional Commits Example Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Use conventional commits for messages and PR titles. The format includes a type, scope, and description. ```git : [optional body] Co-Authored-By: Claude Opus 4.6 ``` -------------------------------- ### Commit Type Examples Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Common commit types include feat, fix, docs, refactor, test, chore, perf, and style. ```git feat: Add input_submit_textarea component ``` ```git fix: Resolve session context error in modules ``` ```git docs: Update reactive programming guide ``` -------------------------------- ### Define requirements.txt Source: https://github.com/posit-dev/py-shiny/wiki/Deploying-on-Connect Include necessary dependencies and wheel file URLs in a requirements.txt file located next to app.py. ```text https://rstudio.github.io/prism/shiny-0.0.0.9000-py2.py3-none-any.whl https://rstudio.github.io/prism/htmltools-0.0.1-py3-none-any.whl packaging uvicorn==0.14.0 matplotlib==3.4.2 fastapi==0.70.0 contextvars==2.4 websockets==10.0 typing_extensions==4.0.1 python-multipart ``` -------------------------------- ### Process XML documentation with process_docs.py Source: https://github.com/posit-dev/py-shiny/blob/main/tests/inspect-ai/utils/scripts/README.md Converts XML documentation into structured JSON for AI model consumption. ```bash python process_docs.py input.xml output.json python process_docs.py --input docs.xml --output result.json ``` -------------------------------- ### Initialize Slider Widget Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/www/shared/jqueryui/index.html Initializes a range slider widget on an element with the ID 'slider'. 'range: true' enables a range selection, and 'values' sets the initial start and end points. ```javascript $( "#slider" ).slider({ range: true, values: [ 17, 67 ] }); ``` -------------------------------- ### Create Downloadable Files with @render.download Source: https://context7.com/posit-dev/py-shiny/llms.txt Use the @render.download decorator to generate files dynamically based on user input. The decorated function must return a file path. ```python from shiny import App, render, ui import pandas as pd import tempfile import os app_ui = ui.page_fluid( ui.input_numeric("rows", "Number of rows:", value=10, min=1, max=100), ui.download_button("download_csv", "Download CSV"), ui.download_button("download_plot", "Download Plot"), ) def server(input, output, session): @render.download(filename="data.csv") def download_csv(): # Create data based on user input df = pd.DataFrame({ "x": range(input.rows()), "y": [i**2 for i in range(input.rows())], }) # Write to temp file and return path path = os.path.join(tempfile.mkdtemp(), "data.csv") df.to_csv(path, index=False) return path @render.download(filename="plot.png") def download_plot(): import matplotlib.pyplot as plt fig, ax = plt.subplots() x = range(input.rows()) ax.plot(x, [i**2 for i in x]) ax.set_title("Sample Plot") path = os.path.join(tempfile.mkdtemp(), "plot.png") fig.savefig(path) plt.close(fig) return path app = App(app_ui, server) ``` -------------------------------- ### Manage project assets Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Commands for vendoring upstream assets and building JavaScript/TypeScript components. ```bash # Vendor assets from upstream (bslib, shiny, sass, htmltools) make upgrade-html-deps # Requires R installed # Build JavaScript/TypeScript make js-build # One-time build make js-watch # Continuous rebuild ``` -------------------------------- ### Shinylive CLI: extension app-resources Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Outputs app-specific resource files for the Shinylive Quarto HTML dependency. ```APIDOC ## CLI: extension app-resources ### Description Prints app-specific resource files as a JSON array that should be added to the `"shinylive"` Quarto HTML dependency. Currently, R-Shinylive does not return any resource files. ### Method ```bash shinylive extension app-resources ``` ### Response Example ```json [ { "name": "shinylive/pyodide/anyio-3.7.0-py3-none-any.whl", "path": "//shinylive-0.2.0/shinylive/pyodide/anyio-3.7.0-py3-none-any.whl" }, { "name": "shinylive/pyodide/appdirs-1.4.4-py2.py3-none-any.whl", "path": "//shinylive-0.2.0/shinylive/pyodide/appdirs-1.4.4-py2.py3-none-any.whl" }, ... ] ``` ``` -------------------------------- ### Manage bookmark restoration lifecycle Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Use these callbacks to access or modify state before and after the application UI is restored. ```python # Called before restoring bookmark state @session.bookmark.on_restore def _(state: RestoreState): # Access restored state before UI updates if "custom_data" in state.values: print(f"Restoring custom data: {state.values['custom_data']}") # Called after bookmark state is fully restored @session.bookmark.on_restored def _(state: RestoreState): # Perform actions after the session is fully restored pass ``` -------------------------------- ### Shinylive CLI: extension language-resources Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Outputs language-specific resource files for the Shinylive Quarto HTML dependency. ```APIDOC ## CLI: extension language-resources ### Description Prints language-specific resource files as a JSON array that should be added to the Quarto HTML dependency. For R, this includes Webr resource files; for Python, it includes Pyodide and Pyright resource files. ### Method ```bash shinylive extension language-resources ``` ### Response Example ```json [ { "name": "shinylive/webr/esbuild.d.ts", "path": "//shinylive-0.2.0/shinylive/webr/esbuild.d.ts" }, { "name": "shinylive/webr/libRblas.so", "path": "//shinylive-0.2.0/shinylive/webr/libRblas.so" }, ... ] ``` ``` -------------------------------- ### Run Shinylive Python CLI Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Execute Shinylive Python CLI methods with arguments. ```bash shinylive [methods] [args] ``` -------------------------------- ### Shinylive CLI: extension info Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Retrieves information about the Shinylive extension, including package version, assets version, and script paths. ```APIDOC ## CLI: extension info ### Description Prints information about the Shinylive extension, including its version, the version of its web assets, and the paths to essential scripts like `codeblock-to-json`. ### Method ```bash shinylive extension info ``` ### Response Example ```json { "version": "0.1.0", "assets_version": "0.2.0", "scripts": { "codeblock-to-json": "//shinylive-0.2.0/scripts/codeblock-to-json.js" } } ``` ``` -------------------------------- ### Run Development Checks Source: https://github.com/posit-dev/py-shiny/blob/main/README.md Execute the 'check' target, which typically runs tests and linters. Use 'make check-fix' to apply formatting fixes. ```sh make check ``` -------------------------------- ### Create HTML tags with attributes Source: https://github.com/posit-dev/py-shiny/blob/main/scripts/README-porting-from-bslib.md Use ui.tags to create HTML elements and pass attributes directly as keyword arguments. ```python ui.tags.div(class_="fw-bold", ...) ``` -------------------------------- ### Execute testing shortcuts Source: https://github.com/posit-dev/py-shiny/blob/main/CLAUDE.md Commands for updating snapshots, debugging Playwright tests, and running specific test suites. ```bash # Update test snapshots make test-update-snapshots # Debug Playwright tests (headed, chromium only) make playwright-debug TEST_FILE="tests/playwright/shiny/inputs/test_foo.py" # Show trace of failed Playwright tests make playwright-show-trace # Run specific test suites make playwright-shiny # Tests in tests/playwright/shiny/ make playwright-examples # Tests in tests/playwright/examples/ ``` -------------------------------- ### Display User Feedback with Notifications and Modals Source: https://context7.com/posit-dev/py-shiny/llms.txt Use ui.notification_show for transient messages and ui.modal_show for dialog boxes. Toasts provide a customizable, non-blocking feedback mechanism. ```python from shiny import App, reactive, ui app_ui = ui.page_fluid( ui.input_action_button("notify", "Show Notification"), ui.input_action_button("modal", "Show Modal"), ui.input_action_button("toast", "Show Toast"), ) def server(input, output, session): @reactive.effect @reactive.event(input.notify) def _(): ui.notification_show( "This is a notification message!", duration=5, # Auto-dismiss after 5 seconds type="message", # "message", "warning", "error" ) @reactive.effect @reactive.event(input.modal) def _(): ui.modal_show( ui.modal( ui.markdown("## Confirmation\nAre you sure you want to proceed?"), ui.input_text("reason", "Reason (optional):"), title="Confirm Action", easy_close=True, footer=ui.TagList( ui.modal_button("Cancel"), ui.input_action_button("confirm", "Confirm", class_="btn-primary"), ), ) ) @reactive.effect @reactive.event(input.confirm) def _(): ui.modal_remove() ui.notification_show("Action confirmed!", type="message") @reactive.effect @reactive.event(input.toast) def _(): ui.show_toast( ui.toast( "Operation completed successfully!", ui.toast_header("Success", icon="✓"), ), position="top-right", duration=3000, ) app = App(app_ui, server) ``` -------------------------------- ### Server Processes Bookmark Request in Shiny Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Define callbacks to handle bookmark creation and restoration. `on_bookmark` callbacks set bookmark values, and `on_bookmarked` callbacks handle the generated URL. ```python # 1. All on_bookmark callbacks execute @session.bookmark.on_bookmark def _(state): # Set bookmark values state.values["some_value"] = compute_value() # 2. Bookmark state is saved to disk/url # 3. All on_bookmarked callbacks execute @session.bookmark.on_bookmarked async def _(url): # Handle the bookmark URL await session.bookmark.update_query_string(url) ``` -------------------------------- ### Add a bookmark button to UI Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Include a button in the user interface to allow users to trigger the bookmarking process. ```python ui.input_bookmark_button(label="Save current state") ``` -------------------------------- ### Create Cards and Layouts in Shiny Source: https://context7.com/posit-dev/py-shiny/llms.txt Use ui.layout_columns and ui.layout_sidebar to structure content with cards. Cards can contain headers, footers, and support full-screen mode. Value boxes offer styled display of key metrics. ```python from shiny import App, render, ui app_ui = ui.page_fillable( # Layout with columns ui.layout_columns( # Card with full_screen support ui.card( ui.card_header("Chart"), ui.output_plot("plot"), ui.card_footer("Updated in real-time"), full_screen=True, ), # Card with value box styling ui.value_box( title="Total Sales", value="$1.2M", showcase=ui.tags.span("📈"), theme="primary", ), # Nested layout ui.card( ui.card_header("Settings"), ui.input_slider("n", "Sample size:", 10, 100, 50), ui.input_switch("log", "Log scale"), ), col_widths=[6, 3, 3], # Column widths (out of 12) ), # Sidebar layout within the page ui.layout_sidebar( ui.sidebar( ui.input_select("var", "Variable:", ["A", "B", "C"]), open="desktop", # Open by default on desktop ), ui.output_data_frame("table"), ), ) def server(input, output, session): @render.plot def plot(): import matplotlib.pyplot as plt import numpy as np x = np.random.randn(input.n()) plt.hist(x, bins=20) app = App(app_ui, server) ``` -------------------------------- ### Implement bookmarking within modules Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Manage state bookmarking locally within a module, including excluding specific inputs and handling custom data. ```python @module.server def my_module(input: Inputs, output: Outputs, session: Session): # Exclude specific inputs from bookmarking session.bookmark.exclude.append("transient_input") # Store custom values @session.bookmark.on_bookmark def _(state: BookmarkState): state.values["module_data"] = input.some_input() # Restore custom values @session.bookmark.on_restore def _(state: RestoreState): if "module_data" in state.values: ui.update_input("some_input", state.values["module_data"]) ``` -------------------------------- ### Export New Component in shiny/ui/__init__.py Source: https://github.com/posit-dev/py-shiny/blob/main/scripts/README-porting-from-bslib.md Update `shiny/ui/__init__.py` to export newly defined component functions. Ensure these functions are included in the `__all__` tuple for public access. ```python from ._input_submit_textarea import input_submit_textarea, update_submit_textarea __all__ = ( # ... existing exports ... "input_submit_textarea", "update_submit_textarea", ) ``` -------------------------------- ### Format CHANGELOG Entry Source: https://github.com/posit-dev/py-shiny/blob/main/scripts/README-porting-from-bslib.md Add new feature documentation to the CHANGELOG.md file using the specified markdown format. ```markdown ### New features * Added `input_new_feature()` [description of function, new features and salient details in 1-3 sentences]. (#[PR_NUMBER]) ``` -------------------------------- ### Test Selectize Input with Playwright Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/pytest/_generate/_data/testing-SYSTEM_PROMPT.md Demonstrates testing a selectize input component and verifying its state and associated output. ```python # test_app_selectize.py from playwright.sync_api import Page from shiny.playwright import controller from shiny.pytest import create_app_fixture from shiny.run import ShinyAppProc app = create_app_fixture(["app_selectize.py"]) def test_selectize(page: Page, app: ShinyAppProc) -> None: page.goto(app.url) select1 = controller.InputSelectize(page, "select1") output = controller.OutputText(page, "output") btn = controller.InputActionButton(page, "update_btn") # Initial state select1.expect_selected(["NY"]) output.expect_value("Selected: NY") # Act btn.click() # Final state select1.expect_selected(["CA"]) output.expect_value("Selected: CA") ``` -------------------------------- ### Generate Quartodoc Files Source: https://github.com/posit-dev/py-shiny/blob/main/docs/README.md Generates the .qmd files for the Shiny API documentation using quartodoc. These files are placed in the `api/` directory. ```bash make quartodoc ``` -------------------------------- ### Execute end-to-end tests via Makefile Source: https://github.com/posit-dev/py-shiny/blob/main/tests/playwright/README.md Commands to run various test suites or specific subsets of tests from the repository root. ```sh # Run tests related to shiny (in `./shiny` folder) make playwright-shiny # Run tests related to examples (in `./examples` folder) make playwright-examples # Run tests on apps that should be deployed (in `./deploys` folder) make playwright-deploys # Run just the tests in playwright/shiny/async/ make playwright-shiny SUB_FILE=e2e/async # Run just the tests in playwright/shiny/async/, in headed mode make playwright-shiny SUB_FILE="--headed e2e/async" # Run **all** tests on with pytest options best for debugging make playwright-debug ``` -------------------------------- ### Build Apps with Shiny Express Mode Source: https://context7.com/posit-dev/py-shiny/llms.txt Uses a simplified, script-like syntax where UI elements and render functions are defined directly in the script. ```python from shiny import render from shiny.express import input, ui # Set page options ui.page_opts(title="Express App", fillable=True) # UI elements are placed directly ui.input_slider("n", "Number:", min=1, max=100, value=50) # Render functions auto-register @render.text def result(): return f"You selected: {input.n()}" ``` -------------------------------- ### Create a Shiny Application with the App Class Source: https://context7.com/posit-dev/py-shiny/llms.txt Defines a standard Shiny application using explicit UI and server function separation. ```python from shiny import App, Inputs, Outputs, Session, render, ui # Define the UI app_ui = ui.page_fluid( ui.panel_title("My Shiny App"), ui.input_slider("n", "Number:", min=1, max=100, value=50), ui.output_text_verbatim("result"), ) # Define the server logic def server(input: Inputs, output: Outputs, session: Session): @render.text def result(): return f"You selected: {input.n()}" # Create the app app = App(app_ui, server) # Run with: shiny run app.py --reload ``` -------------------------------- ### Shinylive CLI: extension base-htmldeps Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Outputs the Quarto HTML dependencies for the base Shinylive integration. ```APIDOC ## CLI: extension base-htmldeps ### Description Prints the language-agnostic Quarto HTML dependencies as a JSON array. This includes the Shinylive service workers and the base Shinylive dependencies, which contain core JavaScript files, stylesheets, and other resources. ### Method ```bash shinylive extension base-htmldeps ``` ### Response Example ```json [ { "name": "shinylive-serviceworker", "version": "0.2.0", "meta": { "shinylive:serviceworker_dir": "." }, "serviceworkers": [ { "source": "//shinylive-0.2.0/shinylive-sw.js", "destination": "/shinylive-sw.js" } ] }, { "name": "shinylive", "version": "0.2.0", "scripts": [{ "name": "shinylive/load-shinylive-sw.js", "path": "//shinylive-0.2.0/shinylive/load-shinylive-sw.js", "attribs": { "type": "module" } }], "stylesheets": [{ "name": "shinylive/shinylive.css", "path": "//shinylive-0.2.0/shinylive/shinylive.css" }], "resources": [ { "name": "shinylive/shinylive.js", "path": "//shinylive-0.2.0/shinylive/shinylive.js" }, ... ] } ] ``` ``` -------------------------------- ### Create Reusable Modules Source: https://context7.com/posit-dev/py-shiny/llms.txt Encapsulate UI and server logic within modules to maintain isolated namespaces. Modules return reactive values to the parent application for state management. ```python from shiny import App, Inputs, Outputs, Session, module, reactive, render, ui # Define the module UI @module.ui def counter_ui(label: str = "Increment") -> ui.TagChild: return ui.card( ui.card_header(label), ui.input_action_button("button", label), ui.output_text("count_display"), ) # Define the module server @module.server def counter_server( input: Inputs, output: Outputs, session: Session, starting_value: int = 0 ) -> reactive.Value[int]: count = reactive.value(starting_value) @reactive.effect @reactive.event(input.button) def _(): count.set(count() + 1) @render.text def count_display(): return f"Count: {count()}" return count # Return reactive value for parent to use # Use the module in an app app_ui = ui.page_fluid( counter_ui("counter1", "First Counter"), counter_ui("counter2", "Second Counter"), ui.output_text_verbatim("total"), ) def server(input: Inputs, output: Outputs, session: Session): count1 = counter_server("counter1", starting_value=0) count2 = counter_server("counter2", starting_value=10) @render.text def total(): return f"Total: {count1() + count2()}" app = App(app_ui, server) ``` -------------------------------- ### Test a local app.py with ShinyAppProc Source: https://github.com/posit-dev/py-shiny/blob/main/tests/playwright/README.md Uses the local_app fixture to launch and test an app.py file located in the same directory as the test file. ```python import re from playwright.sync_api import Locator, Page, expect ShinyAppProc, expect def test_airmass(page: Page, local_app: ShinyAppProc): page.goto(local_app.url) plot = page.locator("#plot") expect(plot).to_have_class(re.compile(r"\bshiny-bound-output\b")) ``` -------------------------------- ### Run Shinylive Rscript Extension Source: https://github.com/posit-dev/py-shiny/blob/main/docs/_extensions/quarto-ext/shinylive/README.md Execute Shinylive Rscript extension methods with arguments. ```bash Rscript -e 'shinylive:::quarto_ext()' [methods] [args] ``` -------------------------------- ### Restore Input Values on Restore Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md Use bookmark values to update input elements during the on_restore callback phase. This ensures that inputs are correctly restored to their bookmarked state before reactive expressions run. ```python # 1. on_restore callbacks execute first @session.bookmark.on_restore def _(state): # Use bookmark values to update inputs ui.update_input("input_id", state.values["some_value"]) ``` -------------------------------- ### Define Shiny Application Source: https://github.com/posit-dev/py-shiny/wiki/Getting-started Basic structure of an app.py file including UI definition and server logic. ```python from shiny import * app_ui = ui.page_fluid( ui.input_slider("n", "N", 0, 100, 20), ui.output_text_verbatim("txt", placeholder=True), ) def server(input: Inputs, output: Outputs, session: Session): @reactive.calc() def r(): return input.n() * 2 @output() @render_text() async def txt(): val = r() return f"n*2 is {val}, session id is {session.id}" app = App(app_ui, server) ``` -------------------------------- ### Store Transient Input Metadata Source: https://github.com/posit-dev/py-shiny/blob/main/shiny/bookmark/README.md For transient inputs like file uploads, store only relevant metadata (e.g., filename) instead of the entire content when bookmarking. This is handled within an @session.bookmark.on_bookmark decorated function. ```python @session.bookmark.on_bookmark def _(state): # Store just the filename instead of the file content if input.file_upload() is not None: state.values["uploaded_filename"] = input.file_upload()["name"] ```