bookmark.Bookmark

bookmark.Bookmark()

Attributes

Name Description
exclude A list of scoped Input names to exclude from bookmarking.
store App’s bookmark store value

Methods

Name Description
do_bookmark Perform bookmarking.
get_bookmark_url Get the URL of the current bookmark state
on_bookmark Registers a function that will be called just before bookmarking state.
on_bookmarked Registers a function that will be called just after bookmarking state.
on_restore Registers a function that will be called just before restoring state.
on_restored Registers a function that will be called just after restoring state.
show_bookmark_url_modal Display a modal dialog for displaying the bookmark URL.
update_query_string Update the query string of the current URL.

do_bookmark

bookmark.Bookmark.do_bookmark()

Perform bookmarking.

This method will also call the on_bookmark and on_bookmarked callbacks to alter the bookmark state. Then, the bookmark state will be either saved to the server or encoded in the URL, depending on the .store option.

No actions will be performed if the .store option is set to "disable".

Note: this method is called when session.bookmark() is executed.

get_bookmark_url

bookmark.Bookmark.get_bookmark_url()

Get the URL of the current bookmark state

This method should return the full URL, including the query string.

As a side effect, all on_bookmark callbacks will be invoked to allow the bookmark state to be modified before it is serialized. This will cause the bookmark state to be serialized to disk when session.bookmark.store == "server".

Returns

: str | None

The full URL of the current bookmark state, including the query string. None if bookmarking is not enabled.

on_bookmark

bookmark.Bookmark.on_bookmark(callback, /)

Registers a function that will be called just before bookmarking state.

This callback will be executed before the bookmark state is saved serverside or in the URL.

Parameters

callback : Callable[[BookmarkState], None] | Callable[[BookmarkState], Awaitable[None]]

The callback function to call when the session is bookmarked. This method should accept a single argument, which is a ShinySaveState object.

Examples

#| standalone: true
#| components: [editor, viewer]
#| layout: vertical
#| viewerHeight: 400

## file: app.py
from starlette.requests import Request

from shiny import App, Inputs, Outputs, Session, reactive, render, ui
from shiny.bookmark import BookmarkState


# App UI **must** be a function to ensure that each user restores their own UI values.
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."
            "\n4. Check the console messages for bookmarking events."
        ),
        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 in the bookmark as we'll store it manually for example's sake
    # Append or adjust this list as needed.
    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()])

    # When the user interacts with the input, we will bookmark the state.
    @reactive.effect
    @reactive.event(input.letter, lowercase_letter, ignore_init=True)
    async def _():
        await session.bookmark()

    # Before saving state, we can adjust the bookmark state values object
    @session.bookmark.on_bookmark
    async def _(state: BookmarkState):
        print("Bookmark state:", state.input, state.values, state.dir)
        state.values["lowercase"] = lowercase_letter()

    # After saving state, we will update the query string with the bookmark URL.
    @session.bookmark.on_bookmarked
    async def _(url: str):
        print("Bookmarked url:", url)
        await session.bookmark.update_query_string(url)

    @session.bookmark.on_restore
    def _(state: BookmarkState):
        print("Restore state:", state.input, state.values, state.dir)

        # Update the radio button selection based on the restored state.
        if "lowercase" in state.values:
            uppercase = state.values["lowercase"].upper()
            # This may produce a small blip in the UI as the original value was restored on the client's HTML request, _then_ a message is received by the client to update the value.
            ui.update_radio_buttons("letter_values", selected=uppercase)

    @session.bookmark.on_restored
    def _(state: BookmarkState):
        # For rare cases, you can update the UI after the session has been fully restored.
        print("Restored state:", state.input, state.values, state.dir)


# Make sure to set the bookmark_store to `"url"` (or `"server"`)
# to store the bookmark information/key in the URL query string.
app = App(app_ui, server, bookmark_store="url")

on_bookmarked

bookmark.Bookmark.on_bookmarked(callback, /)

Registers a function that will be called just after bookmarking state.

This callback will be executed after the bookmark state is saved serverside or in the URL.

Parameters

callback : Callable[[str], None] | Callable[[str], Awaitable[None]]

The callback function to call when the session is bookmarked. This method should accept a single argument, the string representing the query parameter component of the URL.

Examples

#| standalone: true
#| components: [editor, viewer]
#| layout: vertical
#| viewerHeight: 400

## file: app.py
from starlette.requests import Request

from shiny import App, Inputs, Outputs, Session, reactive, render, ui
from shiny.bookmark import BookmarkState


# App UI **must** be a function to ensure that each user restores their own UI values.
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."
            "\n4. Check the console messages for bookmarking events."
        ),
        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 in the bookmark as we'll store it manually for example's sake
    # Append or adjust this list as needed.
    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()])

    # When the user interacts with the input, we will bookmark the state.
    @reactive.effect
    @reactive.event(input.letter, lowercase_letter, ignore_init=True)
    async def _():
        await session.bookmark()

    # Before saving state, we can adjust the bookmark state values object
    @session.bookmark.on_bookmark
    async def _(state: BookmarkState):
        print("Bookmark state:", state.input, state.values, state.dir)
        state.values["lowercase"] = lowercase_letter()

    # After saving state, we will update the query string with the bookmark URL.
    @session.bookmark.on_bookmarked
    async def _(url: str):
        print("Bookmarked url:", url)
        await session.bookmark.update_query_string(url)

    @session.bookmark.on_restore
    def _(state: BookmarkState):
        print("Restore state:", state.input, state.values, state.dir)

        # Update the radio button selection based on the restored state.
        if "lowercase" in state.values:
            uppercase = state.values["lowercase"].upper()
            # This may produce a small blip in the UI as the original value was restored on the client's HTML request, _then_ a message is received by the client to update the value.
            ui.update_radio_buttons("letter_values", selected=uppercase)

    @session.bookmark.on_restored
    def _(state: BookmarkState):
        # For rare cases, you can update the UI after the session has been fully restored.
        print("Restored state:", state.input, state.values, state.dir)


# Make sure to set the bookmark_store to `"url"` (or `"server"`)
# to store the bookmark information/key in the URL query string.
app = App(app_ui, server, bookmark_store="url")

on_restore

bookmark.Bookmark.on_restore(callback)

Registers a function that will be called just before restoring state.

This callback will be executed before the bookmark state is restored.

on_restored

bookmark.Bookmark.on_restored(callback)

Registers a function that will be called just after restoring state.

This callback will be executed after the bookmark state is restored.

show_bookmark_url_modal

bookmark.Bookmark.show_bookmark_url_modal(url=None)

Display a modal dialog for displaying the bookmark URL.

This method should be called when the bookmark button is clicked, and it should display a modal dialog with the current bookmark URL.

Parameters

url : str | None = None

The URL to display in the modal dialog. If None, the current bookmark URL will be retrieved using session.bookmark.get_bookmark_url().

update_query_string

bookmark.Bookmark.update_query_string(query_string=None, mode='replace')

Update the query string of the current URL.

Parameters

query_string : Optional[str] = None

The query string to set. If None, the current bookmark state URL will be used.

mode : Literal[‘replace’, ‘push’] = 'replace'

Whether to replace the current URL or push a new one. Pushing a new value will add to the user’s browser history.