diff --git a/pynecone/.templates/web/utils/state.js b/pynecone/.templates/web/utils/state.js index f9e4ce4bd..9c8e0a4a0 100644 --- a/pynecone/.templates/web/utils/state.js +++ b/pynecone/.templates/web/utils/state.js @@ -97,6 +97,13 @@ export const applyEvent = async (event, router, socket) => { return false; } + if (event.name == "_set_focus") { + const ref = + event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref; + ref.current.focus(); + return false; + } + if (event.name == "_set_value") { const ref = event.payload.ref in refs ? refs[event.payload.ref] : event.payload.ref; diff --git a/pynecone/__init__.py b/pynecone/__init__.py index 3bc97f122..946ffb1d7 100644 --- a/pynecone/__init__.py +++ b/pynecone/__init__.py @@ -22,6 +22,7 @@ from .event import EventChain as EventChain from .event import FileUpload as upload_files from .event import console_log as console_log from .event import redirect as redirect +from .event import set_focus as set_focus from .event import set_value as set_value from .event import window_alert as window_alert from .middleware import Middleware as Middleware diff --git a/pynecone/event.py b/pynecone/event.py index a86c9748b..a606f7a19 100644 --- a/pynecone/event.py +++ b/pynecone/event.py @@ -202,6 +202,22 @@ def window_alert(message: Union[str, Var[str]]) -> EventSpec: return server_side("_alert", get_fn_signature(window_alert), message=message) +def set_focus(ref: str) -> EventSpec: + """Set focus to specified ref. + + Args: + ref: The ref. + + Returns: + An event to set focus on the ref + """ + return server_side( + "_set_focus", + get_fn_signature(set_focus), + ref=Var.create_safe(format.format_ref(ref)), + ) + + def set_value(ref: str, value: Any) -> EventSpec: """Set the value of a ref. diff --git a/tests/test_event.py b/tests/test_event.py index 46e462ab5..9e29a64ce 100644 --- a/tests/test_event.py +++ b/tests/test_event.py @@ -118,6 +118,17 @@ def test_event_window_alert(): assert format.format_event(spec) == 'E("_alert", {message:message})' +def test_set_focus(): + """Test the event set focus function.""" + spec = event.set_focus("input1") + assert isinstance(spec, EventSpec) + assert spec.handler.fn.__qualname__ == "_set_focus" + assert spec.args == (("ref", Var.create_safe("ref_input1")),) + assert format.format_event(spec) == 'E("_set_focus", {ref:ref_input1})' + spec = event.set_focus("input1") + assert format.format_event(spec) == 'E("_set_focus", {ref:ref_input1})' + + def test_set_value(): """Test the event window alert function.""" spec = event.set_value("input1", "")