element.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. from __future__ import annotations
  2. import re
  3. import warnings
  4. from copy import deepcopy
  5. from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Union
  6. from typing_extensions import Self
  7. from nicegui import json
  8. from . import binding, events, globals, outbox, storage
  9. from .elements.mixins.visibility import Visibility
  10. from .event_listener import EventListener
  11. from .slot import Slot
  12. from .tailwind import Tailwind
  13. if TYPE_CHECKING:
  14. from .client import Client
  15. PROPS_PATTERN = re.compile(r'([:\w\-]+)(?:=(?:("[^"\\]*(?:\\.[^"\\]*)*")|([\w\-.%:\/]+)))?(?:$|\s)')
  16. class Element(Visibility):
  17. def __init__(self, tag: str, *, _client: Optional[Client] = None) -> None:
  18. """Generic Element
  19. This class is the base class for all other UI elements.
  20. But you can use it to create elements with arbitrary HTML tags.
  21. :param tag: HTML tag of the element
  22. :param _client: client for this element (for internal use only)
  23. """
  24. super().__init__()
  25. self.client = _client or globals.get_client()
  26. self.id = self.client.next_element_id
  27. self.client.next_element_id += 1
  28. self.tag = tag
  29. self._classes: List[str] = []
  30. self._style: Dict[str, str] = {}
  31. self._props: Dict[str, Any] = {'key': self.id} # HACK: workaround for #600 and #898
  32. self._event_listeners: Dict[str, EventListener] = {}
  33. self._text: Optional[str] = None
  34. self.slots: Dict[str, Slot] = {}
  35. self.default_slot = self.add_slot('default')
  36. self.client.elements[self.id] = self
  37. self.parent_slot: Optional[Slot] = None
  38. slot_stack = globals.get_slot_stack()
  39. if slot_stack:
  40. self.parent_slot = slot_stack[-1]
  41. self.parent_slot.children.append(self)
  42. self.tailwind = Tailwind(self)
  43. outbox.enqueue_update(self)
  44. if self.parent_slot:
  45. outbox.enqueue_update(self.parent_slot.parent)
  46. def add_slot(self, name: str, template: Optional[str] = None) -> Slot:
  47. """Add a slot to the element.
  48. :param name: name of the slot
  49. :param template: Vue template of the slot
  50. :return: the slot
  51. """
  52. self.slots[name] = Slot(self, name, template)
  53. return self.slots[name]
  54. def __enter__(self) -> Self:
  55. self.default_slot.__enter__()
  56. return self
  57. def __exit__(self, *_):
  58. self.default_slot.__exit__(*_)
  59. def __iter__(self) -> Iterator[Element]:
  60. for slot in self.slots.values():
  61. for child in slot:
  62. yield child
  63. def _collect_slot_dict(self) -> Dict[str, Any]:
  64. return {
  65. name: {'template': slot.template, 'ids': [child.id for child in slot]}
  66. for name, slot in self.slots.items()
  67. }
  68. def _to_dict(self) -> Dict[str, Any]:
  69. return {
  70. 'id': self.id,
  71. 'tag': self.tag,
  72. 'class': self._classes,
  73. 'style': self._style,
  74. 'props': self._props,
  75. 'text': self._text,
  76. 'slots': self._collect_slot_dict(),
  77. 'events': [listener.to_dict() for listener in self._event_listeners.values()],
  78. }
  79. @staticmethod
  80. def _update_classes_list(
  81. classes: List[str],
  82. add: Optional[str] = None, remove: Optional[str] = None, replace: Optional[str] = None) -> List[str]:
  83. class_list = classes if replace is None else []
  84. class_list = [c for c in class_list if c not in (remove or '').split()]
  85. class_list += (add or '').split()
  86. class_list += (replace or '').split()
  87. return list(dict.fromkeys(class_list)) # NOTE: remove duplicates while preserving order
  88. def classes(self, add: Optional[str] = None, *, remove: Optional[str] = None, replace: Optional[str] = None) \
  89. -> Self:
  90. """Apply, remove, or replace HTML classes.
  91. This allows modifying the look of the element or its layout using `Tailwind <https://tailwindcss.com/>`_ or `Quasar <https://quasar.dev/>`_ classes.
  92. Removing or replacing classes can be helpful if predefined classes are not desired.
  93. :param add: whitespace-delimited string of classes
  94. :param remove: whitespace-delimited string of classes to remove from the element
  95. :param replace: whitespace-delimited string of classes to use instead of existing ones
  96. """
  97. new_classes = self._update_classes_list(self._classes, add, remove, replace)
  98. if self._classes != new_classes:
  99. self._classes = new_classes
  100. self.update()
  101. return self
  102. @staticmethod
  103. def _parse_style(text: Optional[str]) -> Dict[str, str]:
  104. result = {}
  105. for word in (text or '').split(';'):
  106. word = word.strip()
  107. if word:
  108. key, value = word.split(':', 1)
  109. result[key.strip()] = value.strip()
  110. return result
  111. def style(self, add: Optional[str] = None, *, remove: Optional[str] = None, replace: Optional[str] = None) -> Self:
  112. """Apply, remove, or replace CSS definitions.
  113. Removing or replacing styles can be helpful if the predefined style is not desired.
  114. :param add: semicolon-separated list of styles to add to the element
  115. :param remove: semicolon-separated list of styles to remove from the element
  116. :param replace: semicolon-separated list of styles to use instead of existing ones
  117. """
  118. style_dict = deepcopy(self._style) if replace is None else {}
  119. for key in self._parse_style(remove):
  120. style_dict.pop(key, None)
  121. style_dict.update(self._parse_style(add))
  122. style_dict.update(self._parse_style(replace))
  123. if self._style != style_dict:
  124. self._style = style_dict
  125. self.update()
  126. return self
  127. @staticmethod
  128. def _parse_props(text: Optional[str]) -> Dict[str, Any]:
  129. dictionary = {}
  130. for match in PROPS_PATTERN.finditer(text or ''):
  131. key = match.group(1)
  132. value = match.group(2) or match.group(3)
  133. if value and value.startswith('"') and value.endswith('"'):
  134. value = json.loads(value)
  135. dictionary[key] = value or True
  136. return dictionary
  137. def props(self, add: Optional[str] = None, *, remove: Optional[str] = None) -> Self:
  138. """Add or remove props.
  139. This allows modifying the look of the element or its layout using `Quasar <https://quasar.dev/>`_ props.
  140. Since props are simply applied as HTML attributes, they can be used with any HTML element.
  141. Boolean properties are assumed ``True`` if no value is specified.
  142. :param add: whitespace-delimited list of either boolean values or key=value pair to add
  143. :param remove: whitespace-delimited list of property keys to remove
  144. """
  145. needs_update = False
  146. for key in self._parse_props(remove):
  147. if key in self._props:
  148. needs_update = True
  149. del self._props[key]
  150. for key, value in self._parse_props(add).items():
  151. if self._props.get(key) != value:
  152. needs_update = True
  153. self._props[key] = value
  154. if needs_update:
  155. self.update()
  156. return self
  157. def tooltip(self, text: str) -> Self:
  158. """Add a tooltip to the element.
  159. :param text: text of the tooltip
  160. """
  161. with self:
  162. tooltip = Element('q-tooltip')
  163. tooltip._text = text
  164. return self
  165. def on(self,
  166. type: str,
  167. handler: Optional[Callable[..., Any]] = None,
  168. args: Optional[List[str]] = None, *,
  169. throttle: float = 0.0,
  170. leading_events: bool = True,
  171. trailing_events: bool = True,
  172. ) -> Self:
  173. """Subscribe to an event.
  174. :param type: name of the event (e.g. "click", "mousedown", or "update:model-value")
  175. :param handler: callback that is called upon occurrence of the event
  176. :param args: arguments included in the event message sent to the event handler (default: `None` meaning all)
  177. :param throttle: minimum time (in seconds) between event occurrences (default: 0.0)
  178. :param leading_events: whether to trigger the event handler immediately upon the first event occurrence (default: `True`)
  179. :param trailing_events: whether to trigger the event handler after the last event occurrence (default: `True`)
  180. """
  181. if handler:
  182. if args and '*' in args:
  183. url = f'https://github.com/zauberzeug/nicegui/issues/644'
  184. warnings.warn(DeprecationWarning(f'Event args "*" is deprecated, omit this parameter instead ({url})'))
  185. args = None
  186. listener = EventListener(
  187. element_id=self.id,
  188. type=type,
  189. args=args,
  190. handler=handler,
  191. throttle=throttle,
  192. leading_events=leading_events,
  193. trailing_events=trailing_events,
  194. request=storage.request_contextvar.get()
  195. )
  196. self._event_listeners[listener.id] = listener
  197. self.update()
  198. return self
  199. def _handle_event(self, msg: Dict) -> None:
  200. listener = self._event_listeners[msg['listener_id']]
  201. storage.request_contextvar.set(listener.request)
  202. events.handle_event(listener.handler, msg, sender=self)
  203. def update(self) -> None:
  204. """Update the element on the client side."""
  205. outbox.enqueue_update(self)
  206. def run_method(self, name: str, *args: Any) -> None:
  207. """Run a method on the client side.
  208. :param name: name of the method
  209. :param args: arguments to pass to the method
  210. """
  211. if not globals.loop:
  212. return
  213. data = {'id': self.id, 'name': name, 'args': args}
  214. outbox.enqueue_message('run_method', data, globals._socket_id or self.client.id)
  215. def _collect_descendant_ids(self) -> List[int]:
  216. ids: List[int] = [self.id]
  217. for child in self:
  218. ids.extend(child._collect_descendant_ids())
  219. return ids
  220. def clear(self) -> None:
  221. """Remove all child elements."""
  222. descendants = [self.client.elements[id] for id in self._collect_descendant_ids()[1:]]
  223. binding.remove(descendants, Element)
  224. for element in descendants:
  225. del self.client.elements[element.id]
  226. for slot in self.slots.values():
  227. slot.children.clear()
  228. self.update()
  229. def move(self, target_container: Optional[Element] = None, target_index: int = -1):
  230. """Move the element to another container.
  231. :param target_container: container to move the element to (default: the parent container)
  232. :param target_index: index within the target slot (default: append to the end)
  233. """
  234. assert self.parent_slot is not None
  235. self.parent_slot.children.remove(self)
  236. self.parent_slot.parent.update()
  237. target_container = target_container or self.parent_slot.parent
  238. target_index = target_index if target_index >= 0 else len(target_container.default_slot.children)
  239. target_container.default_slot.children.insert(target_index, self)
  240. self.parent_slot = target_container.default_slot
  241. target_container.update()
  242. def remove(self, element: Union[Element, int]) -> None:
  243. """Remove a child element.
  244. :param element: either the element instance or its ID
  245. """
  246. if isinstance(element, int):
  247. children = list(self)
  248. element = children[element]
  249. binding.remove([element], Element)
  250. del self.client.elements[element.id]
  251. for slot in self.slots.values():
  252. slot.children[:] = [e for e in slot if e.id != element.id]
  253. self.update()
  254. def delete(self) -> None:
  255. """Called when the corresponding client is deleted.
  256. Can be overridden to perform cleanup.
  257. """