input.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from typing import Any, Callable, Dict, Optional
  2. from .icon import Icon
  3. from .mixins.disableable_element import DisableableElement
  4. from .mixins.value_element import ValueElement
  5. class Input(ValueElement, 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] = None,
  14. autocomplete: Optional[list] = None,
  15. validation: Dict[str, Callable] = {}) -> 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: options for autocompletition
  30. :param validation: dictionary of validation rules, e.g. ``{'Too short!': lambda value: len(value) < 3}``
  31. """
  32. super().__init__(tag='q-input', value=value, on_value_change=on_change)
  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. self.validation = validation
  46. if autocomplete is not None:
  47. def AutoCompleteInput():
  48. if len(self.value) > 0:
  49. for item in autocomplete:
  50. if item.startswith(self.value):
  51. self.props(f'shadow-text="{item[len(self.value):]}"')
  52. wordcomplete = item
  53. return wordcomplete
  54. else:
  55. self.props(f'shadow-text=" "')
  56. def CompleteInput():
  57. word = AutoCompleteInput()
  58. self.set_value(word)
  59. self.props(f'shadow-text=" "')
  60. self.on("keyup", AutoCompleteInput)
  61. self.on("keydown.tab", CompleteInput)
  62. def on_value_change(self, value: Any) -> None:
  63. super().on_value_change(value)
  64. for message, check in self.validation.items():
  65. if not check(value):
  66. self.props(f'error error-message="{message}"')
  67. break
  68. else:
  69. self.props(remove='error')