|
| 1 | +"""View implementation for PersistentDialog.""" |
| 2 | + |
| 3 | +from typing import Any, Tuple, Union |
| 4 | +from warnings import warn |
| 5 | + |
| 6 | +from trame.app import get_server |
| 7 | +from trame.widgets import vuetify3 as vuetify |
| 8 | +from trame_server.core import State |
| 9 | + |
| 10 | +from nova.trame._internal.utils import get_state_name, get_state_param |
| 11 | + |
| 12 | + |
| 13 | +class PersistentDialog(vuetify.VDialog): |
| 14 | + """Component for creating a Vuetify dialog that closes on the escape key but not outside clicks.""" |
| 15 | + |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + v_model: Union[str, Tuple], |
| 19 | + close_on_escape: bool = True, |
| 20 | + **kwargs: Any, |
| 21 | + ) -> None: |
| 22 | + """Constructor for PersistentDialog. |
| 23 | +
|
| 24 | + For all parameters, tuples have a special syntax. See :ref:`TrameTuple <api_trame_tuple>` for a description of |
| 25 | + it. |
| 26 | +
|
| 27 | + Parameters |
| 28 | + ---------- |
| 29 | + v_model : Union[str, Tuple] |
| 30 | + The state variable determining if the dialog is opened or closed. |
| 31 | + close_on_escape : bool |
| 32 | + If true, then the dialog will still close when the user presses the escape key. Defaults to true. This |
| 33 | + parameter does not support binding as dynamic behavior here would present a confusing user experience. |
| 34 | + **kwargs |
| 35 | + All other arguments will be passed to the underlying |
| 36 | + `Dialog component <https://trame.readthedocs.io/en/latest/trame.widgets.vuetify3.html#trame.widgets.vuetify3.VDialog>`_. |
| 37 | +
|
| 38 | + Returns |
| 39 | + ------- |
| 40 | + None |
| 41 | + """ |
| 42 | + self._server = get_server(None, client_type="vue3") |
| 43 | + self._v_model = v_model |
| 44 | + self._field_name = get_state_param(self.state, v_model) |
| 45 | + self._model_name = get_state_name(self._field_name) |
| 46 | + |
| 47 | + if "persistent" in kwargs: |
| 48 | + warn( |
| 49 | + "PersistentDialog will ignore the provided 'persistent' parameter as it forces persistent=True.", |
| 50 | + stacklevel=1, |
| 51 | + ) |
| 52 | + kwargs.pop("persistent", None) |
| 53 | + |
| 54 | + if close_on_escape: |
| 55 | + super().__init__( |
| 56 | + v_model=self._v_model, |
| 57 | + v_on_keydown_esc=( |
| 58 | + f"window.trame.state.state.{self._field_name} = false; flushState('{self._model_name}');" |
| 59 | + ), |
| 60 | + persistent=True, |
| 61 | + **kwargs, |
| 62 | + ) |
| 63 | + else: |
| 64 | + super().__init__(v_model=self._v_model, persistent=True, **kwargs) |
| 65 | + |
| 66 | + @property |
| 67 | + def state(self) -> State: |
| 68 | + return self._server.state |
0 commit comments