Giter Club home page Giter Club logo

textual-inputs's Introduction

Textual Inputs ๐Ÿ”ก

Not Maintained Python Versions License: MIT Code style: black Imports: isort

Textual Inputs is a collection of input widgets for the Textual TUI framework.

News

No Longer Maintained Due to Native Textual Support

Thanks to all the developers who contributed or used Textual Inputs. These widgets filled a gap in the early stages of Textual, which is now supported natively. Special thanks to @willmcgugan for creating this fun and functional framework -> Textual Widget Docs

Quick Start

Installation

python -m pip install textual-inputs~=0.2.6

To use Textual Inputs

from textual_inputs import TextInput, IntegerInput

Checkout the examples for reference.

git clone https://github.com/sirfuzzalot/textual-inputs.git
cd textual-inputs
python3 -m venv venv
source venv/bin/activate
python -m pip install -e .
python examples/simple_form.py

Widgets

TextInput ๐Ÿ”ก

  • value - string
  • one line of text with overflow support
  • placeholder and title support
  • password mode to hide input
  • syntax mode to highlight code
  • support for Unicode characters
  • controls: arrow right/left, home, end, delete, backspace/ctrl+h, escape
  • emits - InputOnChange, InputOnFocus messages

IntegerInput ๐Ÿ”ข

  • value - integer or None
  • placeholder and title support
  • type a number or arrow up/down to increment/decrement the integer.
  • controls: arrow right/left, home, end, delete, backspace/ctrl+h, escape
  • emits - InputOnChange, InputOnFocus messages

Features

One-Line Syntax Highlighting

Textual Inputs takes advantage of rich's built-in Syntax feature. To add highlighting to your input text set the syntax argument to a language supported by pygments. Currently this is set to the default theme.

โš ๏ธ THIS FEATURE IS LIMITED TO ONE LINE OF TEXT

TextInput(
    name="code",
    placeholder="enter some python code...",
    title="Code",
    syntax="python",
)

Event Handlers

Textual Inputs helps make the event handler process easier by providing the following convenient properties for inputs.

  • on_change_handler_name
  • on_focus_handler_name
email = TextInput(name="email", title="Email")
email.on_change_handler_name = "handle_email_on_change"
email.on_focus_handler_name = "handle_email_on_focus"

Under the hood setting this attribute this will generate a Message class with the appropriate name for Textual to send it to the handler name provided. You'll then want add the handler to the input's parent or the App instance. If you opt not to customize these handlers, their values will be the default handle_input_on_change and handle_input_on_focus. See examples/simple_form.py for a working example.

API Reference

Textual Inputs has two widgets, here are their attributes.

class TextInput(Widget):
    """
    A simple text input widget.

    Args:
        name (Optional[str]): The unique name of the widget. If None, the
            widget will be automatically named.
        value (str, optional): Defaults to "". The starting text value.
        placeholder (str, optional): Defaults to "". Text that appears
            in the widget when value is "" and the widget is not focused.
        title (str, optional): Defaults to "". A title on the top left
            of the widget's border.
        password (bool, optional): Defaults to False. Hides the text
            input, replacing it with bullets.
        syntax (Optional[str]): the name of the language for syntax highlighting.

    Attributes:
        value (str): the value of the text field
        placeholder (str): The placeholder message.
        title (str): The displayed title of the widget.
        has_password (bool): True if the text field masks the input.
        syntax (Optional[str]): the name of the language for syntax highlighting.
        has_focus (bool): True if the widget is focused.
        cursor (Tuple[str, Style]): The character used for the cursor
            and a rich Style object defining its appearance.
        on_change_handler_name (str): name of handler function to be
            called when an on change event occurs. Defaults to
            handle_input_on_change.
        on_focus_handler_name (name): name of handler function to be
            called when an on focus event occurs. Defaults to
            handle_input_on_focus.

    Events:
        InputOnChange: Emitted when the contents of the input changes.
        InputOnFocus: Emitted when the widget becomes focused.

    Examples:

    .. code-block:: python

        from textual_inputs import TextInput

        email_input = TextInput(
            name="email",
            placeholder="enter your email address...",
            title="Email",
        )

    """
class IntegerInput(Widget):
    """
    A simple integer input widget.

    Args:
        name (Optional[str]): The unique name of the widget. If None, the
            widget will be automatically named.
        value (Optional[int]): The starting integer value.
        placeholder (Union[str, int, optional): Defaults to "". Text that
            appears in the widget when value is "" and the widget is not focused.
        title (str, optional): Defaults to "". A title on the top left
            of the widget's border.

    Attributes:
        value (Union[int, None]): the value of the input field
        placeholder (str): The placeholder message.
        title (str): The displayed title of the widget.
        has_focus (bool): True if the widget is focused.
        cursor (Tuple[str, Style]): The character used for the cursor
            and a rich Style object defining its appearance.
        on_change_handler_name (str): name of handler function to be
            called when an on change event occurs. Defaults to
            handle_input_on_change.
        on_focus_handler_name (name): name of handler function to be
            called when an on focus event occurs. Defaults to
            handle_input_on_focus.

    Events:
        InputOnChange: Emitted when the contents of the input changes.
        InputOnFocus: Emitted when the widget becomes focused.

    Examples:

    .. code-block:: python

        from textual_inputs import IntegerInput

        age_input = IntegerInput(
            name="age",
            placeholder="enter your age...",
            title="Age",
        )

    """

Contributing

See the Contributing Guide.

textual-inputs's People

Contributors

adamlwgriffiths avatar bbugyi200 avatar danmou avatar davidbrochart avatar samdobson avatar sanders41 avatar sirfuzzalot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

textual-inputs's Issues

made some simplifications to the source code

class TextInput(Widget):
    """
    A simple text input widget based on https://github.com/sirfuzzalot/textual-inputs
    Args:
        name (Optional[str]): The unique name of the widget. If None, the widget will be automatically named.
        value (str, optional): Defaults to "". The starting text value.
        placeholder (str, optional), default="".
            Text that appears in the widget when value is "" and the widget is not focused.
        title (str, optional): Defaults to "". A title on the top left of the widget's border.
        password (bool, optional): Defaults to False. Hides the text input, replacing it with bullets.
    Attributes:
        value (str): the value of the text field
        placeholder (str): The placeholder message.
        title (str): The displayed title of the widget.
        has_password (bool): True if the text field masks the input.
        has_focus (bool): True if the widget is focused.
        cursor (Tuple[str, Style]): The character used for the cursor and a rich Style object defining its appearance.
    Messages:
        InputOnChange: Emitted when the contents of the input changes.
        InputOnFocus: Emitted when the widget becomes focused.
    Examples:
    .. code-block:: python
        from textual_inputs import TextInput
        email_input = TextInput(
            name="email",
            placeholder="enter your email address...",
            title="Email",
        )
    """
    value: Reactive[str] = Reactive("")
    cursor: Tuple[str, Style] = ("|", Style(color="white", blink=True, bold=True))
    _cursor_position: Reactive[int] = Reactive(0)
    _has_focus: Reactive[bool] = Reactive(False)

    def __init__(self, *, name: Optional[str] = None, value: str = "", placeholder: str = "",
                 title: str = "", password: bool = False, **kwargs: Any,) -> None:
        super().__init__(name, **kwargs)
        self.value = value
        self.placeholder = placeholder
        self.title = title
        self.has_password = password
        self._cursor_position = len(self.value)

    def __rich_repr__(self):
        yield from (("name", self.name), ("title", self.title), ("value", self._conceal_or_reveal(self.value)))

    @property
    def has_focus(self) -> bool:
        """Produces True if widget is focused"""
        return self._has_focus

    def render(self) -> RenderableType:
        """ Produce a Panel object containing placeholder text or value and cursor. """
        segments = self._render_text_with_cursor() if self.has_focus else\
                   [self._conceal_or_reveal(self.value)] if self.value else\
                   [self.title] if self.title and not self.placeholder else\
                   [self.placeholder]
        text = Text.assemble(*segments)
        title = "" if self.title and not any([self.placeholder, self.value, self.has_focus]) else self.title
        return Panel(text, title=title, title_align="left", height=3, style=self.style or "",
                     border_style=self.border_style or Style(color="blue"),
                     box=rich.box.DOUBLE if self.has_focus else rich.box.SQUARE)

    def _conceal_or_reveal(self, segment: str) -> str:
        """ Produce the segment either concealed like a password or as it was passed. """
        return "โ€ข" * len(segment) if self.has_password else segment

    def _render_text_with_cursor(self) -> List[Union[str, Tuple[str, Style]]]:
        """ Produces the renderable Text object combining value and cursor """
        return [self._conceal_or_reveal(self.value[: self._cursor_position]), self.cursor,
                self._conceal_or_reveal(self.value[self._cursor_position+1:])]

    async def on_focus(self, event: events.Focus) -> None:
        self._has_focus = True
        await self._emit_on_focus()

    async def on_blur(self, event: events.Blur) -> None:
        self._has_focus = False

    async def on_key(self, event: events.Key) -> None:
        if event.key == "left":
            if self._cursor_position: self._cursor_position -= 1
        elif event.key == "right":
            if self._cursor_position <= len(self.value): self._cursor_position += 1
        elif event.key == "home":
            self._cursor_position = 0
        elif event.key == "end":
            self._cursor_position = len(self.value)
        elif event.key == "ctrl+h":  # Backspace
            if self._cursor_position:
                self.value = self.value[:self._cursor_position - 1] + self.value[self._cursor_position:]
                self._cursor_position -= 1
                await self._emit_on_change(event)
        elif event.key == "delete":
            if self._cursor_position <= len(self.value):
                self.value = self.value[:self._cursor_position] + self.value[self._cursor_position+1:]
                if self._cursor_position == len(self.value): self._cursor_position -= 1
                await self._emit_on_change(event)
        elif event.key in string.printable:
            self.value = self.value[: self._cursor_position] + event.key + self.value[self._cursor_position :]
            self._cursor_position += 1
            await self._emit_on_change(event)

    async def _emit_on_change(self, event: events.Key) -> None:
        event.stop()
        await self.emit(InputOnChange(self))

    async def _emit_on_focus(self) -> None:
        await self.emit(InputOnFocus(self))

Pin v0.2 to textual v0.1

Textual will introduce a breaking public API change soon as v0.2. We'll be pinning Textual Inputs to prevent breakage of the library while we update.

Customizable Border Type

Would be good if we can customize the border type when its focused or not.
will be needing this to match the rounded borders on my Textual program

Add a Datetime Input

  • support an input allowing for both date and time inputs
  • support on change event
  • accept datetime.datetime as starting value
  • output value should be a datetime.datetime object
  • widget should resemble browser datetime component

Passing kwargs to TextInput and IntegerInput causes errors

Passing arguments such as style="blue" to the TextInput and IntegerInput constructor causes the Widget.init function to fail. This is because Widget only supports the name parameter.

  • remove kwargs parameter from TextInput and IntegerInput constructors
  • stop passing kwargs to the Widget constructor.

Example Form message handlers broken

Updating to textual 0.1.11 breaks custom message handlers by changing thier function prefixes from message_ to handle_.

  • update hanndlers
  • update textual minimum version
  • bump textual-inputs version

Add pre-commit framework to project

USER STORY
As a developer I want to get up and running on a contribution fast

REQUIREMENTS

  • explore the pre-commit framework
  • add a config and notes if we decide to go this route.

Syntax highlighting

Great project!
Something I would be interested in, is having syntax highlighting as you type, maybe using pygments.
Do you think it is feasible?

backspace as first action on IntegerInput

Using the example sample form, when you focus the Age field, if the first key you press is backspace (or cntr+h) the program will fail with the following error:
ValueError: invalid literal for int() with base 10: ''

Add Contributing Guide

USER STORY
As a developer I want clear guidance on how I may contribute my work to this project

REQUIREMENTS

  • add a contributing guide

File input/upload

Hey there,
First of all: this plugin looks / works great!

I'd like to see a field acting on file drag/drop / input, when using the current text field, this results in all path characters being inserted after one another ๐Ÿ˜€

What do you think? Could this be something worth it?

Add configurable dimensions and styles

As a consumer I want to be able to override the following properties when initialising a new instance of an input class.

  • width
  • height
  • style
  • border_style

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.