Skip to content

SlashedApp

Base classes

Name Children Inherits
App
textual.app
The base class for Textual Applications.
Generic
typing
Abstract base class for generic types.

â‹” Inheritance diagram

graph TD
  1346404068["app.SlashedApp"]
  3799205450["app.App"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3946681048["dom.DOMNode"]
  53685856["message_pump.MessagePump"]
  3799205450 --> 1346404068
  3481597255 --> 3799205450
  2751680898 --> 3481597255
  3946681048 --> 3799205450
  53685856 --> 3946681048
  2751680898 --> 53685856
  3481597255 --> 1346404068

🛈 DocStrings

Bases: App[TResult]

Base app with slash command support.

This app provides slash command functionality with optional typed context data. Commands can access the context data through self.context.get_data().

Class Type Parameters:

Name Bound or Constraints Description Default
TContext

Type of the command context data. When using typed context, access it via self.context.get_data() to get proper type checking.

required
TResult

Type of value returned by app.run(). Use None if the app doesn't return anything.

required
Example
@dataclass
class AppState:
    count: int = 0

class MyApp(SlashedApp[AppState, None]):
    @SlashedApp.command_input("input-id")
    async def handle_input(self, value: str) -> None:
        state = self.context.get_data()
        state.count += 1
        await self.context.print(f"Count: {state.count}")
Source code in src/slashed/textual_adapter/app.py
class SlashedApp[TContext, TResult](App[TResult]):
    """Base app with slash command support.

    This app provides slash command functionality with optional typed context data.
    Commands can access the context data through self.context.get_data().

    Type Parameters:
        TContext: Type of the command context data. When using typed context,
                 access it via self.context.get_data() to get proper type checking.
        TResult: Type of value returned by app.run(). Use None if the app
                doesn't return anything.

    Example:
        ```python
        @dataclass
        class AppState:
            count: int = 0

        class MyApp(SlashedApp[AppState, None]):
            @SlashedApp.command_input("input-id")
            async def handle_input(self, value: str) -> None:
                state = self.context.get_data()
                state.count += 1
                await self.context.print(f"Count: {state.count}")
        ```
    """

    # Class-level storage for command input handlers
    _command_handlers: ClassVar[dict[str, dict[str, str]]] = {}

    def __init__(
        self,
        store: CommandStore | None = None,
        data: TContext | None = None,
        commands: list[type[SlashedCommand] | BaseCommand] | None = None,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        """Initialize app with command store.

        Args:
            data: Optional context data
            commands: Optional list of commands to register
            store: Optional command store (creates new one if not provided)
            *args: Arguments passed to textual.App
            **kwargs: Keyword arguments passed to textual.App
        """
        super().__init__(*args, **kwargs)
        self.store = store or CommandStore()
        self.store._initialize_sync()
        writer = TextualOutputWriter(self)
        self.context = self.store.create_context(data=data, output_writer=writer)
        if commands:
            for command in commands:
                self.store.register_command(command)

    def get_suggester(self) -> SlashedSuggester:
        """Get a suggester configured for this app's store and context."""
        return SlashedSuggester(store=self.store, context=self.context)

    def bind_output(self, output_id: str, widget_query: str, default: bool = False) -> None:
        """Bind an output stream to a widget.

        Args:
            output_id: ID for this output stream
            widget_query: CSS query to find the target widget
            default: Whether this is the default output
        """
        writer = self.context.output
        if not isinstance(writer, TextualOutputWriter):
            msg = "Output writer is not a TextualOutputWriter"
            raise TypeError(msg)
        writer.bind(output_id, widget_query, default=default)

    @classmethod
    def command_input(
        cls,
        input_id: str,
    ) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]:
        """Register an Input widget to handle commands.

        Args:
            input_id: ID of the Input widget that should handle commands

        Example:
            ```python
            @command_input("my-input")
            async def handle_my_input(self, value: str) -> None:
                # Handle non-command text input here
                await self.context.print(f"Echo: {value}")
            ```
        """

        def decorator(
            method: Callable[[Any, str], Awaitable[None]],
        ) -> Callable[[Any, str], Awaitable[None]]:
            # Store the handler method name for this class and input
            cls._command_handlers.setdefault(cls.__name__, {})[input_id] = getattr(
                method, "__name__", "unknown"
            )
            return method

        return decorator

    async def on_input_submitted(self) -> None:
        """Handle input submission."""
        input_widget = self.query_one("#command-input", Input)
        value = input_widget.value

        if value.startswith("/"):
            # Execute command
            cmd = value[1:]
            try:
                await self.store.execute_command(cmd, self.context)
            except Exception as e:  # noqa: BLE001
                self.log(f"Error: {e}")
            input_widget.value = ""
            return

        # For non-command input, call handler only if registered
        handlers = self._command_handlers.get(self.__class__.__name__, {})
        if input_widget.id in handlers:
            handler_name = handlers[input_widget.id]
            handler = getattr(self, handler_name)
            await handler(value)
            input_widget.value = ""

__init__

__init__(
    store: CommandStore | None = None,
    data: TContext | None = None,
    commands: list[type[SlashedCommand] | BaseCommand] | None = None,
    *args: Any,
    **kwargs: Any,
) -> None

Initialize app with command store.

Parameters:

Name Type Description Default
data TContext | None

Optional context data

None
commands list[type[SlashedCommand] | BaseCommand] | None

Optional list of commands to register

None
store CommandStore | None

Optional command store (creates new one if not provided)

None
*args Any

Arguments passed to textual.App

()
**kwargs Any

Keyword arguments passed to textual.App

{}
Source code in src/slashed/textual_adapter/app.py
def __init__(
    self,
    store: CommandStore | None = None,
    data: TContext | None = None,
    commands: list[type[SlashedCommand] | BaseCommand] | None = None,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize app with command store.

    Args:
        data: Optional context data
        commands: Optional list of commands to register
        store: Optional command store (creates new one if not provided)
        *args: Arguments passed to textual.App
        **kwargs: Keyword arguments passed to textual.App
    """
    super().__init__(*args, **kwargs)
    self.store = store or CommandStore()
    self.store._initialize_sync()
    writer = TextualOutputWriter(self)
    self.context = self.store.create_context(data=data, output_writer=writer)
    if commands:
        for command in commands:
            self.store.register_command(command)

bind_output

bind_output(output_id: str, widget_query: str, default: bool = False) -> None

Bind an output stream to a widget.

Parameters:

Name Type Description Default
output_id str

ID for this output stream

required
widget_query str

CSS query to find the target widget

required
default bool

Whether this is the default output

False
Source code in src/slashed/textual_adapter/app.py
def bind_output(self, output_id: str, widget_query: str, default: bool = False) -> None:
    """Bind an output stream to a widget.

    Args:
        output_id: ID for this output stream
        widget_query: CSS query to find the target widget
        default: Whether this is the default output
    """
    writer = self.context.output
    if not isinstance(writer, TextualOutputWriter):
        msg = "Output writer is not a TextualOutputWriter"
        raise TypeError(msg)
    writer.bind(output_id, widget_query, default=default)

command_input classmethod

command_input(
    input_id: str,
) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]

Register an Input widget to handle commands.

Parameters:

Name Type Description Default
input_id str

ID of the Input widget that should handle commands

required
Example
@command_input("my-input")
async def handle_my_input(self, value: str) -> None:
    # Handle non-command text input here
    await self.context.print(f"Echo: {value}")
Source code in src/slashed/textual_adapter/app.py
@classmethod
def command_input(
    cls,
    input_id: str,
) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]:
    """Register an Input widget to handle commands.

    Args:
        input_id: ID of the Input widget that should handle commands

    Example:
        ```python
        @command_input("my-input")
        async def handle_my_input(self, value: str) -> None:
            # Handle non-command text input here
            await self.context.print(f"Echo: {value}")
        ```
    """

    def decorator(
        method: Callable[[Any, str], Awaitable[None]],
    ) -> Callable[[Any, str], Awaitable[None]]:
        # Store the handler method name for this class and input
        cls._command_handlers.setdefault(cls.__name__, {})[input_id] = getattr(
            method, "__name__", "unknown"
        )
        return method

    return decorator

get_suggester

get_suggester() -> SlashedSuggester

Get a suggester configured for this app's store and context.

Source code in src/slashed/textual_adapter/app.py
def get_suggester(self) -> SlashedSuggester:
    """Get a suggester configured for this app's store and context."""
    return SlashedSuggester(store=self.store, context=self.context)

on_input_submitted async

on_input_submitted() -> None

Handle input submission.

Source code in src/slashed/textual_adapter/app.py
async def on_input_submitted(self) -> None:
    """Handle input submission."""
    input_widget = self.query_one("#command-input", Input)
    value = input_widget.value

    if value.startswith("/"):
        # Execute command
        cmd = value[1:]
        try:
            await self.store.execute_command(cmd, self.context)
        except Exception as e:  # noqa: BLE001
            self.log(f"Error: {e}")
        input_widget.value = ""
        return

    # For non-command input, call handler only if registered
    handlers = self._command_handlers.get(self.__class__.__name__, {})
    if input_widget.id in handlers:
        handler_name = handlers[input_widget.id]
        handler = getattr(self, handler_name)
        await handler(value)
        input_widget.value = ""

:fa-brands-github: Show source on GitHub