-
Notifications
You must be signed in to change notification settings - Fork 17
feat: DH-22062: add create_global_state and create_user_state shared state hooks #1324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
mofojed
wants to merge
8
commits into
deephaven:main
Choose a base branch
from
mofojed:DH-22062-user-user-state
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4a0a18d
feat: DH-22062: add create_global_state and create_user_state shared …
mofojed f52788d
docs: add examples and custom hooks sections to create_global_state a…
mofojed 716b1d3
Update API reference
mofojed e4aa1d1
Clean up docs based on review
mofojed dbe40a5
Update doc snapshots
mofojed f20c6bc
feat: support callable initializer for create_global_state and create…
mofojed 4678cce
refactor: move ValueWithLiveness to utils.py, reset shared state on u…
mofojed c2c6e2d
Update docs based on self-review
mofojed File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| # Plan for implementing a global user state in Deephaven UI | ||
|
|
||
| Proof of concept (not production): | ||
|
|
||
| ```python | ||
| from deephaven import empty_table, ui | ||
|
|
||
|
|
||
| def create_store(initial_value=None): | ||
| store_value = initial_value | ||
| set_values = set() | ||
|
|
||
| def use_store(): | ||
| value, set_value = ui.use_state(store_value) | ||
|
|
||
| def add_set_value(): | ||
| set_values.add(set_value) | ||
|
|
||
| # Clean up the set values when the component unmounts | ||
| return lambda: set_values.discard(set_value) | ||
|
|
||
| ui.use_effect(add_set_value, [set_value]) | ||
|
|
||
| def do_set_value(new_value): | ||
| nonlocal store_value | ||
| store_value = new_value | ||
| for set_value in set_values: | ||
| set_value(new_value) | ||
|
|
||
| return value, do_set_value | ||
|
|
||
| return use_store | ||
|
|
||
|
|
||
| use_value_store = create_store(0) | ||
|
|
||
|
|
||
| @ui.component | ||
| def my_slider(): | ||
| value, set_value = use_value_store() | ||
| return ui.slider(label="Value", value=value, on_change=set_value) | ||
|
|
||
|
|
||
| @ui.component | ||
| def my_table(): | ||
| value, set_value = use_value_store() | ||
| t = ui.use_memo( | ||
| lambda: empty_table(1000).update(["x=i", f"y=x*Math.sin({value})"]), [value] | ||
| ) | ||
| return t | ||
|
|
||
|
|
||
| s = my_slider() | ||
| t = my_table() | ||
| ``` | ||
|
|
||
| You can get user context: | ||
|
|
||
| ```python | ||
| from deephaven_enterprise import auth_context | ||
| from deephaven import ui | ||
|
|
||
| query_user = auth_context.get_authenticated_user() | ||
| query_effective = auth_context.get_effective_user() | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_show_auth_context(): | ||
| component_user = auth_context.get_authenticated_user() | ||
| component_effective = auth_context.get_effective_user() | ||
| return [ | ||
| ui.heading(f"Query auth user: {query_user}"), | ||
| ui.heading(f"Query effective user: {query_effective}"), | ||
| ui.heading(f"Component auth user: {component_user}"), | ||
| ui.heading(f"Component effective user: {component_effective}"), | ||
| ] | ||
|
|
||
|
|
||
| auth = ui_show_auth_context() | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| # create_global_state | ||
|
|
||
| `create_global_state` is a factory function that creates a shared state hook. Unlike `use_state`, which creates state local to a single component, the state created by `create_global_state` is shared across all components that call the returned hook. When any component updates the shared state, all other components using the same hook will re-render with the new value. | ||
|
|
||
| Call `create_global_state` at module level (outside of any component) to create a store. Then call the returned hook inside `@ui.component` functions to subscribe to the shared state. | ||
|
|
||
| When all components using a shared store unmount, the state resets to the initial value. | ||
|
|
||
| ## Examples | ||
|
|
||
| ### Basic example | ||
|
|
||
| ```python | ||
| from deephaven import ui | ||
|
|
||
| # Create the shared state at module level | ||
| use_shared_counter = ui.create_global_state(0) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_counter_controls(): | ||
| count, set_count = use_shared_counter() | ||
| return ui.flex( | ||
| ui.button(f"Count: {count}", on_press=lambda: set_count(count + 1)), | ||
| ui.button("Reset", on_press=lambda: set_count(0)), | ||
| ) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_counter_display(): | ||
| count, _ = use_shared_counter() | ||
| return ui.text(f"The shared count is: {count}") | ||
|
|
||
|
|
||
| controls = ui_counter_controls() | ||
| display = ui_counter_display() | ||
| ``` | ||
|
|
||
| In this example, clicking the button in `ui_counter_controls` will update the count displayed in both `ui_counter_controls` and `ui_counter_display`. | ||
|
|
||
| ## Recommendations | ||
|
|
||
| 1. **Create stores at module level**: Call `create_global_state` at module level, not inside a component. The returned hook is then used inside components. | ||
| 2. **Naming convention**: Name the returned hook starting with `use_`, e.g. `use_shared_counter = ui.create_global_state(0)`. This makes it clear that it follows hook rules. | ||
| 3. **Keep state serializable**: As with `use_state`, use simple serializable values (numbers, strings, lists, dicts) when possible for best compatibility. | ||
| 4. **Prefer `create_user_state` for user-specific data**: If the state should be independent per user (e.g., user preferences or user-specific selections), use [`create_user_state`](create_user_state.md) instead. | ||
|
|
||
| ### Using updater functions | ||
|
|
||
| Like `use_state`, the setter function supports updater functions for state that depends on the previous value: | ||
|
|
||
| ```python | ||
| from deephaven import ui | ||
|
|
||
| use_shared_counter = ui.create_global_state(0) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_increment_buttons(): | ||
| count, set_count = use_shared_counter() | ||
|
|
||
| def increase_by(n): | ||
| for _ in range(n): | ||
| set_count(lambda prev: prev + 1) | ||
|
|
||
| return ui.flex( | ||
| ui.button("+1", on_press=lambda: increase_by(1)), | ||
| ui.button("+10", on_press=lambda: increase_by(10)), | ||
| ui.text(f"Count: {count}"), | ||
| ) | ||
|
|
||
|
|
||
| buttons = ui_increment_buttons() | ||
| ``` | ||
|
|
||
| When an updater function is passed, it is resolved once using the current store value and the resolved value is broadcast to all subscribers. This ensures all components see the same value regardless of timing. | ||
|
|
||
| ### Shared filter example | ||
|
|
||
| A common use case is sharing filter criteria across multiple views: | ||
|
|
||
| ```python | ||
| from deephaven import ui, empty_table | ||
|
|
||
| use_filter_value = ui.create_global_state(50) | ||
|
|
||
| t = empty_table(1000).update(["x = i", "y = Math.sin(i / 10.0) * 100"]) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_filter_slider(): | ||
| threshold, set_threshold = use_filter_value() | ||
| return ui.slider( | ||
| label=f"Filter threshold: {threshold}", | ||
| value=threshold, | ||
| on_change=set_threshold, | ||
| min_value=0, | ||
| max_value=100, | ||
| ) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_filtered_table(): | ||
| threshold, _ = use_filter_value() | ||
| filtered = ui.use_memo(lambda: t.where(f"y > {threshold}"), [threshold]) | ||
| return filtered | ||
|
|
||
|
|
||
| slider = ui_filter_slider() | ||
| filtered = ui_filtered_table() | ||
| ``` | ||
|
|
||
| ### Color theme toggler example | ||
|
|
||
| ```python | ||
| from deephaven import ui | ||
|
|
||
| use_theme = ui.create_global_state("light") | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_theme_toggle(): | ||
| theme, set_theme = use_theme() | ||
| return ui.switch( | ||
| "Dark mode", | ||
| is_selected=theme == "dark", | ||
| on_change=lambda is_dark: set_theme("dark" if is_dark else "light"), | ||
| ) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_themed_card(): | ||
| theme, _ = use_theme() | ||
| bg = "#1a1a2e" if theme == "dark" else "#ffffff" | ||
| fg = "#ffffff" if theme == "dark" else "#000000" | ||
| return ui.view( | ||
| ui.text(f"Current theme: {theme}", color=fg), | ||
| background_color=bg, | ||
| padding="size-200", | ||
| ) | ||
|
|
||
|
|
||
| toggle = ui_theme_toggle() | ||
| card = ui_themed_card() | ||
| ``` | ||
|
|
||
| ### Custom hooks | ||
|
|
||
| You can wrap the hook returned by `create_global_state` to build a custom hook with prepackaged behavior: | ||
|
|
||
| ```python | ||
| from deephaven import ui | ||
|
|
||
| _use_items = ui.create_global_state([]) | ||
|
|
||
|
|
||
| def use_items(): | ||
| """A custom hook that adds convenience methods on top of shared state.""" | ||
| items, set_items = _use_items() | ||
|
|
||
| def add(item): | ||
| set_items(lambda prev: prev + [item]) | ||
|
|
||
| def clear(): | ||
| set_items([]) | ||
|
|
||
| return items, add, clear | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_item_input(): | ||
| text, set_text = ui.use_state("") | ||
| items, add, _ = use_items() | ||
|
|
||
| def handle_add(_e): | ||
| if text.strip(): | ||
| add(text.strip()) | ||
| set_text("") | ||
|
|
||
| return ui.flex( | ||
| ui.text_field(label="Add item", value=text, on_change=set_text), | ||
| ui.action_button(f"Add ({len(items)})", on_press=handle_add), | ||
| direction="row", | ||
| gap="size-100", | ||
| align_items="end", | ||
| ) | ||
|
|
||
|
|
||
| @ui.component | ||
| def ui_item_list(): | ||
| items, _, clear = use_items() | ||
| return ui.flex( | ||
| ui.list_view( | ||
| *[ui.item(t) for t in items], | ||
| aria_label="Items", | ||
| selection_mode=None, | ||
| ) | ||
| if items | ||
| else ui.text("No items yet"), | ||
| ui.action_button( | ||
| "Clear", on_press=lambda _e: clear(), is_disabled=len(items) == 0 | ||
| ), | ||
| direction="column", | ||
| gap="size-100", | ||
| ) | ||
|
|
||
|
|
||
| item_input = ui_item_input() | ||
| item_list = ui_item_list() | ||
| ``` | ||
|
|
||
| Components call `use_items()` and get back `add` and `clear` functions instead of a raw setter. The button label in the input panel shows the count, which updates when items are cleared from the list panel. | ||
|
|
||
| ## Cleanup behavior | ||
|
|
||
| When all components that subscribe to a shared store unmount (e.g., all panels using the hook are closed), the store automatically resets to the initial value. This prevents stale state from persisting across sessions. | ||
|
|
||
| If at least one subscriber remains active, the state is preserved. | ||
|
|
||
| ## Thread safety | ||
|
|
||
| `create_global_state` is thread-safe. Multiple components can safely read and update the shared state concurrently. State updates are serialized internally using a lock. | ||
|
|
||
| ## API Reference | ||
|
|
||
| ```{eval-rst} | ||
| .. dhautofunction:: deephaven.ui.create_global_state | ||
| ``` | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is one thing I don't particularly like about Python vs. JS. In JS you could destructure this nicely, e.g.
const { items, clear } = useItems()I think closest thing we could do here is
NamedTuple:... I kind of like that a bit better, but then you have to define the
ItemStateand such, which is more verbose.Or DataClass:
Though you still need to declare
ItemState.Or SimpleNamespace
Seems to be the simplest. But doesn't give you any autocomplete/type suggestions. I don't think it's necessary for an example, and AI will be able to figure it out anyways... but should I put that in the example?
@dsmmcken @jnumainville any thoughts/comments about that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Basically I think that should just be left up to the user when building their custom hook, and this example is fine for showing you can build a custom hook. AI should be able to figure it out anyways.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah I wish there was something like destructuring in Python. I don't think it's worth adding any details on that to an example. I think most people with python are so used to ignoring args with
_That said, I think
operator.itemgetteris something that gets close.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You lose the type hints/inference with itemgetter I think