diff --git a/src/myfasthtml/controls/Search.py b/src/myfasthtml/controls/Search.py index 687d0bb..67fbd58 100644 --- a/src/myfasthtml/controls/Search.py +++ b/src/myfasthtml/controls/Search.py @@ -4,7 +4,7 @@ from typing import Callable, Any from fasthtml.components import * from myfasthtml.controls.BaseCommands import BaseCommands -from myfasthtml.controls.helpers import Ids, mk +from myfasthtml.controls.helpers import mk from myfasthtml.core.commands import Command from myfasthtml.core.instances import MultipleInstance, BaseInstance from myfasthtml.core.matching_utils import subsequence_matching, fuzzy_matching diff --git a/src/myfasthtml/core/commands.py b/src/myfasthtml/core/commands.py index 1483166..c58272b 100644 --- a/src/myfasthtml/core/commands.py +++ b/src/myfasthtml/core/commands.py @@ -45,7 +45,7 @@ class BaseCommand: def execute(self, client_response: dict = None): raise NotImplementedError - def htmx(self, target="this", swap="outerHTML", trigger=None): + def htmx(self, target: Optional[str] = "this", swap="outerHTML", trigger=None): # Note that the default value is the same than in get_htmx_params() if target is None: self._htmx_extra["hx-swap"] = "none" @@ -180,6 +180,15 @@ class Command(BaseCommand): return [ret] + ret_from_bindings +class LambdaCommand(Command): + def __init__(self, delegate, name="LambdaCommand", description="Lambda Command"): + super().__init__(name, description, delegate) + self.htmx(target=None) + + def execute(self, client_response: dict = None): + return self.callback(client_response) + + class CommandsManager: commands = {} diff --git a/tests/core/test_commands.py b/tests/core/test_commands.py index 34f77f7..5105623 100644 --- a/tests/core/test_commands.py +++ b/tests/core/test_commands.py @@ -5,7 +5,7 @@ import pytest from fasthtml.components import Button, Div from myutils.observable import make_observable, bind -from myfasthtml.core.commands import Command, CommandsManager +from myfasthtml.core.commands import Command, CommandsManager, LambdaCommand from myfasthtml.core.constants import ROUTE_ROOT, Routes from myfasthtml.test.matcher import matches @@ -183,3 +183,14 @@ class TestCommandExecute: assert "hx-swap-oob" not in res[0].attrs assert "hx-swap-oob" not in res[1].attrs assert "hx-swap-oob" not in res[3].attrs + + +class TestLambaCommand: + + def test_i_can_create_a_command_from_lambda(self): + command = LambdaCommand(lambda resp: "Hello World") + assert command.execute() == "Hello World" + + def test_by_default_target_is_none(self): + command = LambdaCommand(lambda resp: "Hello World") + assert command.get_htmx_params()["hx-swap"] == "none"