Curtis Turner 2 anni fa
parent
commit
d4b5c78406
4 ha cambiato i file con 35 aggiunte e 0 eliminazioni
  1. 7 0
      pynecone/.templates/web/utils/state.js
  2. 1 0
      pynecone/__init__.py
  3. 16 0
      pynecone/event.py
  4. 11 0
      tests/test_event.py

+ 7 - 0
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;

+ 1 - 0
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

+ 16 - 0
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.
 

+ 11 - 0
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", "")