element.py 14 KB

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