add set_focus (#1092)

This commit is contained in:
Curtis Turner 2023-05-30 13:04:09 -07:00 committed by GitHub
parent bf93113b26
commit d4b5c78406
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 35 additions and 0 deletions

View File

@ -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;

View File

@ -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

View File

@ -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.

View File

@ -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", "")