number.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. from typing import Any, Callable, Dict, Optional, Union
  2. from ..events import GenericEventArguments
  3. from .mixins.disableable_element import DisableableElement
  4. from .mixins.validation_element import ValidationElement
  5. class Number(ValidationElement, DisableableElement):
  6. LOOPBACK = False
  7. def __init__(self,
  8. label: Optional[str] = None, *,
  9. placeholder: Optional[str] = None,
  10. value: Optional[float] = None,
  11. min: Optional[float] = None, # pylint: disable=redefined-builtin
  12. max: Optional[float] = None, # pylint: disable=redefined-builtin
  13. precision: Optional[int] = None,
  14. step: Optional[float] = None,
  15. prefix: Optional[str] = None,
  16. suffix: Optional[str] = None,
  17. format: Optional[str] = None, # pylint: disable=redefined-builtin
  18. on_change: Optional[Callable[..., Any]] = None,
  19. validation: Optional[Union[Callable[..., Optional[str]], Dict[str, Callable[..., bool]]]] = None,
  20. ) -> None:
  21. """Number Input
  22. This element is based on Quasar's `QInput <https://quasar.dev/vue-components/input>`_ component.
  23. You can use the `validation` parameter to define a dictionary of validation rules,
  24. e.g. ``{'Too small!': lambda value: value < 3}``.
  25. The key of the first rule that fails will be displayed as an error message.
  26. Alternatively, you can pass a callable that returns an optional error message.
  27. :param label: displayed name for the number input
  28. :param placeholder: text to show if no value is entered
  29. :param value: the initial value of the field
  30. :param min: the minimum value allowed
  31. :param max: the maximum value allowed
  32. :param precision: the number of decimal places allowed (default: no limit, negative: decimal places before the dot)
  33. :param step: the step size for the stepper buttons
  34. :param prefix: a prefix to prepend to the displayed value
  35. :param suffix: a suffix to append to the displayed value
  36. :param format: a string like "%.2f" to format the displayed value
  37. :param on_change: callback to execute when the value changes
  38. :param validation: dictionary of validation rules or a callable that returns an optional error message
  39. """
  40. self.format = format
  41. super().__init__(tag='q-input', value=value, on_value_change=on_change, validation=validation)
  42. self._props['type'] = 'number'
  43. if label is not None:
  44. self._props['label'] = label
  45. if placeholder is not None:
  46. self._props['placeholder'] = placeholder
  47. if min is not None:
  48. self._props['min'] = min
  49. if max is not None:
  50. self._props['max'] = max
  51. self._precision = precision
  52. if step is not None:
  53. self._props['step'] = step
  54. if prefix is not None:
  55. self._props['prefix'] = prefix
  56. if suffix is not None:
  57. self._props['suffix'] = suffix
  58. self.on('blur', self.sanitize, [])
  59. @property
  60. def min(self) -> float:
  61. """The minimum value allowed."""
  62. return self._props.get('min', -float('inf'))
  63. @min.setter
  64. def min(self, value: float) -> None:
  65. self._props['min'] = value
  66. self.sanitize()
  67. @property
  68. def max(self) -> float:
  69. """The maximum value allowed."""
  70. return self._props.get('max', float('inf'))
  71. @max.setter
  72. def max(self, value: float) -> None:
  73. self._props['max'] = value
  74. self.sanitize()
  75. @property
  76. def precision(self) -> Optional[int]:
  77. """The number of decimal places allowed (default: no limit, negative: decimal places before the dot)."""
  78. return self._precision
  79. @precision.setter
  80. def precision(self, value: Optional[int]) -> None:
  81. self._precision = value
  82. self.sanitize()
  83. @property
  84. def out_of_limits(self) -> bool:
  85. """Whether the current value is out of the allowed limits."""
  86. return not self.min <= self.value <= self.max
  87. def sanitize(self) -> None:
  88. """Sanitize the current value to be within the allowed limits."""
  89. if self.value is None:
  90. return
  91. value = float(self.value)
  92. value = max(value, self.min)
  93. value = min(value, self.max)
  94. if self.precision is not None:
  95. value = float(round(value, self.precision))
  96. self.set_value(float(self.format % value) if self.format else value)
  97. def _event_args_to_value(self, e: GenericEventArguments) -> Any:
  98. if not e.args:
  99. return None
  100. return float(e.args)
  101. def _value_to_model_value(self, value: Any) -> Any:
  102. if value is None:
  103. return None
  104. if self.format is None:
  105. return str(value)
  106. if value == '':
  107. return 0
  108. return self.format % float(value)
  109. def _value_to_event_value(self, value: Any) -> Any:
  110. return float(value) if value else 0