element.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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, List, Optional, Union
  6. from typing_extensions import Self
  7. from nicegui import json
  8. from . import binding, events, globals, outbox
  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 = f'c{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.components: List[str] = []
  35. self.libraries: List[str] = []
  36. self.slots: Dict[str, Slot] = {}
  37. self.default_slot = self.add_slot('default')
  38. self.client.elements[self.id] = self
  39. self.parent_slot: Optional[Slot] = None
  40. slot_stack = globals.get_slot_stack()
  41. if slot_stack:
  42. self.parent_slot = slot_stack[-1]
  43. self.parent_slot.children.append(self)
  44. self.tailwind = Tailwind(self)
  45. outbox.enqueue_update(self)
  46. if self.parent_slot:
  47. outbox.enqueue_update(self.parent_slot.parent)
  48. def add_slot(self, name: str, template: Optional[str] = None) -> Slot:
  49. """Add a slot to the element.
  50. :param name: name of the slot
  51. :param template: Vue template of the slot
  52. :return: the slot
  53. """
  54. self.slots[name] = Slot(self, name, template)
  55. return self.slots[name]
  56. def __enter__(self) -> Self:
  57. self.default_slot.__enter__()
  58. return self
  59. def __exit__(self, *_):
  60. self.default_slot.__exit__(*_)
  61. def _collect_slot_dict(self) -> Dict[str, List[int]]:
  62. return {
  63. name: {'template': slot.template, 'ids': [child.id for child in slot.children]}
  64. for name, slot in self.slots.items()
  65. }
  66. def _to_dict(self) -> Dict[str, Any]:
  67. return {
  68. 'id': self.id,
  69. 'tag': self.tag,
  70. 'class': self._classes,
  71. 'style': self._style,
  72. 'props': self._props,
  73. 'text': self._text,
  74. 'slots': self._collect_slot_dict(),
  75. 'events': [listener.to_dict() for listener in self._event_listeners.values()],
  76. 'libraries': self.libraries,
  77. 'components': self.components,
  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],
  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. )
  195. self._event_listeners[listener.id] = listener
  196. self.update()
  197. return self
  198. def _handle_event(self, msg: Dict) -> None:
  199. listener = self._event_listeners[msg['listener_id']]
  200. events.handle_event(listener.handler, msg, sender=self)
  201. def update(self) -> None:
  202. """Update the element on the client side."""
  203. outbox.enqueue_update(self)
  204. def run_method(self, name: str, *args: Any) -> None:
  205. """Run a method on the client side.
  206. :param name: name of the method
  207. :param args: arguments to pass to the method
  208. """
  209. if not globals.loop:
  210. return
  211. data = {'id': self.id, 'name': name, 'args': args}
  212. outbox.enqueue_message('run_method', data, globals._socket_id or self.client.id)
  213. def _collect_descendant_ids(self) -> List[int]:
  214. ids: List[int] = [self.id]
  215. for slot in self.slots.values():
  216. for child in slot.children:
  217. ids.extend(child._collect_descendant_ids())
  218. return ids
  219. def clear(self) -> None:
  220. """Remove all child elements."""
  221. descendants = [self.client.elements[id] for id in self._collect_descendant_ids()[1:]]
  222. binding.remove(descendants, Element)
  223. for element in descendants:
  224. del self.client.elements[element.id]
  225. for slot in self.slots.values():
  226. slot.children.clear()
  227. self.update()
  228. def move(self, target_container: Optional[Element] = None, target_index: int = -1):
  229. """Move the element to another container.
  230. :param target_container: container to move the element to (default: the parent container)
  231. :param target_index: index within the target slot (default: append to the end)
  232. """
  233. self.parent_slot.children.remove(self)
  234. self.parent_slot.parent.update()
  235. target_container = target_container or self.parent_slot.parent
  236. target_index = target_index if target_index >= 0 else len(target_container.default_slot.children)
  237. target_container.default_slot.children.insert(target_index, self)
  238. self.parent_slot = target_container.default_slot
  239. target_container.update()
  240. def remove(self, element: Union[Element, int]) -> None:
  241. """Remove a child element.
  242. :param element: either the element instance or its ID
  243. """
  244. if isinstance(element, int):
  245. children = [child for slot in self.slots.values() for child in slot.children]
  246. element = children[element]
  247. binding.remove([element], Element)
  248. del self.client.elements[element.id]
  249. for slot in self.slots.values():
  250. slot.children[:] = [e for e in slot.children if e.id != element.id]
  251. self.update()
  252. def delete(self) -> None:
  253. """Called when the corresponding client is deleted.
  254. Can be overridden to perform cleanup.
  255. """
  256. def use_component(self, name: str) -> Self:
  257. self.components.append(f'vue_{name}')
  258. return self
  259. def use_library(self, name: str) -> Self:
  260. self.libraries.append(f'lib_{name}')
  261. return self