input.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from typing import Any, Callable, Dict, List, Optional
  2. from .icon import Icon
  3. from .mixins.disableable_element import DisableableElement
  4. from .mixins.validation_element import ValidationElement
  5. class Input(ValidationElement, DisableableElement):
  6. LOOPBACK = False
  7. def __init__(self,
  8. label: Optional[str] = None, *,
  9. placeholder: Optional[str] = None,
  10. value: str = '',
  11. password: bool = False,
  12. password_toggle_button: bool = False,
  13. on_change: Optional[Callable[..., Any]] = None,
  14. autocomplete: Optional[List[str]] = None,
  15. validation: Dict[str, Callable[..., bool]] = {}) -> None:
  16. """Text Input
  17. This element is based on Quasar's `QInput <https://quasar.dev/vue-components/input>`_ component.
  18. The `on_change` event is called on every keystroke and the value updates accordingly.
  19. If you want to wait until the user confirms the input, you can register a custom event callback, e.g.
  20. `ui.input(...).on('keydown.enter', ...)` or `ui.input(...).on('blur', ...)`.
  21. You can use the `validation` parameter to define a dictionary of validation rules.
  22. The key of the first rule that fails will be displayed as an error message.
  23. :param label: displayed label for the text input
  24. :param placeholder: text to show if no value is entered
  25. :param value: the current value of the text input
  26. :param password: whether to hide the input (default: False)
  27. :param password_toggle_button: whether to show a button to toggle the password visibility (default: False)
  28. :param on_change: callback to execute when the value changes
  29. :param autocomplete: optional list of strings for autocompletion
  30. :param validation: dictionary of validation rules, e.g. ``{'Too long!': lambda value: len(value) < 3}``
  31. """
  32. super().__init__(tag='q-input', value=value, on_value_change=on_change, validation=validation)
  33. if label is not None:
  34. self._props['label'] = label
  35. if placeholder is not None:
  36. self._props['placeholder'] = placeholder
  37. self._props['type'] = 'password' if password else 'text'
  38. if password_toggle_button:
  39. with self.add_slot('append'):
  40. def toggle_type(_):
  41. is_hidden = self._props.get('type') == 'password'
  42. icon.props(f'name={"visibility" if is_hidden else "visibility_off"}')
  43. self.props(f'type={"text" if is_hidden else "password"}')
  44. icon = Icon('visibility_off').classes('cursor-pointer').on('click', toggle_type)
  45. if autocomplete:
  46. def find_autocompletion() -> Optional[str]:
  47. if self.value:
  48. needle = str(self.value).casefold()
  49. for item in autocomplete or []:
  50. if item.casefold().startswith(needle):
  51. return item
  52. return None # required by mypy
  53. def autocomplete_input() -> None:
  54. match = find_autocompletion() or ''
  55. self.props(f'shadow-text="{match[len(self.value):]}"')
  56. def complete_input() -> None:
  57. match = find_autocompletion()
  58. if match:
  59. self.set_value(match)
  60. self.props('shadow-text=""')
  61. self.on('keyup', autocomplete_input)
  62. self.on('keydown.tab', complete_input)