element.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. from __future__ import annotations
  2. import ast
  3. import inspect
  4. import re
  5. from copy import copy, deepcopy
  6. from pathlib import Path
  7. from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional, Sequence, Union
  8. from typing_extensions import Self
  9. from . import context, core, events, json, outbox, storage
  10. from .awaitable_response import AwaitableResponse, NullResponse
  11. from .dependencies import Component, Library, register_library, register_resource, register_vue_component
  12. from .elements.mixins.visibility import Visibility
  13. from .event_listener import EventListener
  14. from .slot import Slot
  15. from .tailwind import Tailwind
  16. from .version import __version__
  17. if TYPE_CHECKING:
  18. from .client import Client
  19. PROPS_PATTERN = re.compile(r'''
  20. # Match a key-value pair optionally followed by whitespace or end of string
  21. ([:\w\-]+) # Capture group 1: Key
  22. (?: # Optional non-capturing group for value
  23. = # Match the equal sign
  24. (?: # Non-capturing group for value options
  25. ( # Capture group 2: Value enclosed in double quotes
  26. " # Match double quote
  27. [^"\\]* # Match any character except quotes or backslashes zero or more times
  28. (?:\\.[^"\\]*)* # Match any escaped character followed by any character except quotes or backslashes zero or more times
  29. " # Match the closing quote
  30. )
  31. |
  32. ( # Capture group 3: Value enclosed in single quotes
  33. ' # Match a single quote
  34. [^'\\]* # Match any character except quotes or backslashes zero or more times
  35. (?:\\.[^'\\]*)* # Match any escaped character followed by any character except quotes or backslashes zero or more times
  36. ' # Match the closing quote
  37. )
  38. | # Or
  39. ([\w\-.%:\/]+) # Capture group 4: Value without quotes
  40. )
  41. )? # End of optional non-capturing group for value
  42. (?:$|\s) # Match end of string or whitespace
  43. ''', re.VERBOSE)
  44. # https://www.w3.org/TR/xml/#sec-common-syn
  45. TAG_START_CHAR = r':|[A-Z]|_|[a-z]|[\u00C0-\u00D6]|[\u00D8-\u00F6]|[\u00F8-\u02FF]|[\u0370-\u037D]|[\u037F-\u1FFF]|[\u200C-\u200D]|[\u2070-\u218F]|[\u2C00-\u2FEF]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]|[\U00010000-\U000EFFFF]'
  46. TAG_CHAR = TAG_START_CHAR + r'|-|\.|[0-9]|\u00B7|[\u0300-\u036F]|[\u203F-\u2040]'
  47. TAG_PATTERN = re.compile(fr'^({TAG_START_CHAR})({TAG_CHAR})*$')
  48. class Element(Visibility):
  49. component: Optional[Component] = None
  50. libraries: List[Library] = []
  51. extra_libraries: List[Library] = []
  52. exposed_libraries: List[Library] = []
  53. _default_props: Dict[str, Any] = {}
  54. _default_classes: List[str] = []
  55. _default_style: Dict[str, str] = {}
  56. def __init__(self, tag: Optional[str] = None, *, _client: Optional[Client] = None) -> None:
  57. """Generic Element
  58. This class is the base class for all other UI elements.
  59. But you can use it to create elements with arbitrary HTML tags.
  60. :param tag: HTML tag of the element
  61. :param _client: client for this element (for internal use only)
  62. """
  63. super().__init__()
  64. self.client = _client or context.get_client()
  65. self.id = self.client.next_element_id
  66. self.client.next_element_id += 1
  67. self.tag = tag if tag else self.component.tag if self.component else 'div'
  68. if not TAG_PATTERN.match(self.tag):
  69. raise ValueError(f'Invalid HTML tag: {self.tag}')
  70. self._classes: List[str] = []
  71. self._classes.extend(self._default_classes)
  72. self._style: Dict[str, str] = {}
  73. self._style.update(self._default_style)
  74. self._props: Dict[str, Any] = {'key': self.id} # HACK: workaround for #600 and #898
  75. self._props.update(self._default_props)
  76. self._event_listeners: Dict[str, EventListener] = {}
  77. self._text: Optional[str] = None
  78. self.slots: Dict[str, Slot] = {}
  79. self.default_slot = self.add_slot('default')
  80. self._deleted: bool = False
  81. self.client.elements[self.id] = self
  82. self.parent_slot: Optional[Slot] = None
  83. slot_stack = context.get_slot_stack()
  84. if slot_stack:
  85. self.parent_slot = slot_stack[-1]
  86. self.parent_slot.children.append(self)
  87. self.tailwind = Tailwind(self)
  88. outbox.enqueue_update(self)
  89. if self.parent_slot:
  90. outbox.enqueue_update(self.parent_slot.parent)
  91. def __init_subclass__(cls, *,
  92. component: Union[str, Path, None] = None,
  93. libraries: List[Union[str, Path]] = [],
  94. exposed_libraries: List[Union[str, Path]] = [],
  95. extra_libraries: List[Union[str, Path]] = [],
  96. ) -> None:
  97. super().__init_subclass__()
  98. base = Path(inspect.getfile(cls)).parent
  99. def glob_absolute_paths(file: Union[str, Path]) -> List[Path]:
  100. path = Path(file)
  101. if not path.is_absolute():
  102. path = base / path
  103. return sorted(path.parent.glob(path.name), key=lambda p: p.stem)
  104. cls.component = copy(cls.component)
  105. cls.libraries = copy(cls.libraries)
  106. cls.extra_libraries = copy(cls.extra_libraries)
  107. cls.exposed_libraries = copy(cls.exposed_libraries)
  108. if component:
  109. for path in glob_absolute_paths(component):
  110. cls.component = register_vue_component(path)
  111. for library in libraries:
  112. for path in glob_absolute_paths(library):
  113. cls.libraries.append(register_library(path))
  114. for library in extra_libraries:
  115. for path in glob_absolute_paths(library):
  116. cls.extra_libraries.append(register_library(path))
  117. for library in exposed_libraries:
  118. for path in glob_absolute_paths(library):
  119. cls.exposed_libraries.append(register_library(path, expose=True))
  120. cls._default_props = copy(cls._default_props)
  121. cls._default_classes = copy(cls._default_classes)
  122. cls._default_style = copy(cls._default_style)
  123. def add_resource(self, path: Union[str, Path]) -> None:
  124. """Add a resource to the element.
  125. :param path: path to the resource (e.g. folder with CSS and JavaScript files)
  126. """
  127. resource = register_resource(Path(path))
  128. self._props['resource_path'] = f'/_nicegui/{__version__}/resources/{resource.key}'
  129. def add_slot(self, name: str, template: Optional[str] = None) -> Slot:
  130. """Add a slot to the element.
  131. :param name: name of the slot
  132. :param template: Vue template of the slot
  133. :return: the slot
  134. """
  135. self.slots[name] = Slot(self, name, template)
  136. return self.slots[name]
  137. def __enter__(self) -> Self:
  138. self.default_slot.__enter__()
  139. return self
  140. def __exit__(self, *_) -> None:
  141. self.default_slot.__exit__(*_)
  142. def __iter__(self) -> Iterator[Element]:
  143. for slot in self.slots.values():
  144. for child in slot:
  145. yield child
  146. def _collect_slot_dict(self) -> Dict[str, Any]:
  147. return {
  148. name: {'template': slot.template, 'ids': [child.id for child in slot]}
  149. for name, slot in self.slots.items()
  150. }
  151. def _to_dict(self) -> Dict[str, Any]:
  152. return {
  153. 'id': self.id,
  154. 'tag': self.tag,
  155. 'class': self._classes,
  156. 'style': self._style,
  157. 'props': self._props,
  158. 'text': self._text,
  159. 'slots': self._collect_slot_dict(),
  160. 'events': [listener.to_dict() for listener in self._event_listeners.values()],
  161. 'component': {
  162. 'key': self.component.key,
  163. 'name': self.component.name,
  164. 'tag': self.component.tag
  165. } if self.component else None,
  166. 'libraries': [
  167. {
  168. 'key': library.key,
  169. 'name': library.name,
  170. } for library in self.libraries
  171. ],
  172. }
  173. @staticmethod
  174. def _update_classes_list(classes: List[str],
  175. add: Optional[str] = None,
  176. remove: Optional[str] = None,
  177. replace: Optional[str] = None) -> List[str]:
  178. class_list = classes if replace is None else []
  179. class_list = [c for c in class_list if c not in (remove or '').split()]
  180. class_list += (add or '').split()
  181. class_list += (replace or '').split()
  182. return list(dict.fromkeys(class_list)) # NOTE: remove duplicates while preserving order
  183. def classes(self,
  184. add: Optional[str] = None, *,
  185. remove: Optional[str] = None,
  186. replace: Optional[str] = None) -> Self:
  187. """Apply, remove, or replace HTML classes.
  188. This allows modifying the look of the element or its layout using `Tailwind <https://tailwindcss.com/>`_ or `Quasar <https://quasar.dev/>`_ classes.
  189. Removing or replacing classes can be helpful if predefined classes are not desired.
  190. :param add: whitespace-delimited string of classes
  191. :param remove: whitespace-delimited string of classes to remove from the element
  192. :param replace: whitespace-delimited string of classes to use instead of existing ones
  193. """
  194. new_classes = self._update_classes_list(self._classes, add, remove, replace)
  195. if self._classes != new_classes:
  196. self._classes = new_classes
  197. self.update()
  198. return self
  199. @classmethod
  200. def default_classes(cls,
  201. add: Optional[str] = None, *,
  202. remove: Optional[str] = None,
  203. replace: Optional[str] = None) -> type[Self]:
  204. """Apply, remove, or replace default HTML classes.
  205. This allows modifying the look of the element or its layout using `Tailwind <https://tailwindcss.com/>`_ or `Quasar <https://quasar.dev/>`_ classes.
  206. Removing or replacing classes can be helpful if predefined classes are not desired.
  207. All elements of this class will share these HTML classes.
  208. These must be defined before element instantiation.
  209. :param add: whitespace-delimited string of classes
  210. :param remove: whitespace-delimited string of classes to remove from the element
  211. :param replace: whitespace-delimited string of classes to use instead of existing ones
  212. """
  213. cls._default_classes = cls._update_classes_list(cls._default_classes, add, remove, replace)
  214. return cls
  215. @staticmethod
  216. def _parse_style(text: Optional[str]) -> Dict[str, str]:
  217. result = {}
  218. for word in (text or '').split(';'):
  219. word = word.strip()
  220. if word:
  221. key, value = word.split(':', 1)
  222. result[key.strip()] = value.strip()
  223. return result
  224. def style(self,
  225. add: Optional[str] = None, *,
  226. remove: Optional[str] = None,
  227. replace: Optional[str] = None) -> Self:
  228. """Apply, remove, or replace CSS definitions.
  229. Removing or replacing styles can be helpful if the predefined style is not desired.
  230. :param add: semicolon-separated list of styles to add to the element
  231. :param remove: semicolon-separated list of styles to remove from the element
  232. :param replace: semicolon-separated list of styles to use instead of existing ones
  233. """
  234. style_dict = deepcopy(self._style) if replace is None else {}
  235. for key in self._parse_style(remove):
  236. style_dict.pop(key, None)
  237. style_dict.update(self._parse_style(add))
  238. style_dict.update(self._parse_style(replace))
  239. if self._style != style_dict:
  240. self._style = style_dict
  241. self.update()
  242. return self
  243. @classmethod
  244. def default_style(cls,
  245. add: Optional[str] = None, *,
  246. remove: Optional[str] = None,
  247. replace: Optional[str] = None) -> type[Self]:
  248. """Apply, remove, or replace default CSS definitions.
  249. Removing or replacing styles can be helpful if the predefined style is not desired.
  250. All elements of this class will share these CSS definitions.
  251. These must be defined before element instantiation.
  252. :param add: semicolon-separated list of styles to add to the element
  253. :param remove: semicolon-separated list of styles to remove from the element
  254. :param replace: semicolon-separated list of styles to use instead of existing ones
  255. """
  256. if replace is not None:
  257. cls._default_style.clear()
  258. for key in cls._parse_style(remove):
  259. cls._default_style.pop(key, None)
  260. cls._default_style.update(cls._parse_style(add))
  261. cls._default_style.update(cls._parse_style(replace))
  262. return cls
  263. @staticmethod
  264. def _parse_props(text: Optional[str]) -> Dict[str, Any]:
  265. dictionary = {}
  266. for match in PROPS_PATTERN.finditer(text or ''):
  267. key = match.group(1)
  268. value = match.group(2) or match.group(3) or match.group(4)
  269. if value is None:
  270. dictionary[key] = True
  271. else:
  272. if (value.startswith("'") and value.endswith("'")) or (value.startswith('"') and value.endswith('"')):
  273. value = ast.literal_eval(value)
  274. dictionary[key] = value
  275. return dictionary
  276. def props(self,
  277. add: Optional[str] = None, *,
  278. remove: Optional[str] = None) -> Self:
  279. """Add or remove props.
  280. This allows modifying the look of the element or its layout using `Quasar <https://quasar.dev/>`_ props.
  281. Since props are simply applied as HTML attributes, they can be used with any HTML element.
  282. Boolean properties are assumed ``True`` if no value is specified.
  283. :param add: whitespace-delimited list of either boolean values or key=value pair to add
  284. :param remove: whitespace-delimited list of property keys to remove
  285. """
  286. needs_update = False
  287. for key in self._parse_props(remove):
  288. if key in self._props:
  289. needs_update = True
  290. del self._props[key]
  291. for key, value in self._parse_props(add).items():
  292. if self._props.get(key) != value:
  293. needs_update = True
  294. self._props[key] = value
  295. if needs_update:
  296. self.update()
  297. return self
  298. @classmethod
  299. def default_props(cls,
  300. add: Optional[str] = None, *,
  301. remove: Optional[str] = None) -> type[Self]:
  302. """Add or remove default props.
  303. This allows modifying the look of the element or its layout using `Quasar <https://quasar.dev/>`_ props.
  304. Since props are simply applied as HTML attributes, they can be used with any HTML element.
  305. All elements of this class will share these props.
  306. These must be defined before element instantiation.
  307. Boolean properties are assumed ``True`` if no value is specified.
  308. :param add: whitespace-delimited list of either boolean values or key=value pair to add
  309. :param remove: whitespace-delimited list of property keys to remove
  310. """
  311. for key in cls._parse_props(remove):
  312. if key in cls._default_props:
  313. del cls._default_props[key]
  314. for key, value in cls._parse_props(add).items():
  315. cls._default_props[key] = value
  316. return cls
  317. def tooltip(self, text: str) -> Self:
  318. """Add a tooltip to the element.
  319. :param text: text of the tooltip
  320. """
  321. with self:
  322. tooltip = Element('q-tooltip')
  323. tooltip._text = text # pylint: disable=protected-access
  324. return self
  325. def on(self,
  326. type: str, # pylint: disable=redefined-builtin
  327. handler: Optional[Callable[..., Any]] = None,
  328. args: Union[None, Sequence[str], Sequence[Optional[Sequence[str]]]] = None, *,
  329. throttle: float = 0.0,
  330. leading_events: bool = True,
  331. trailing_events: bool = True,
  332. ) -> Self:
  333. """Subscribe to an event.
  334. :param type: name of the event (e.g. "click", "mousedown", or "update:model-value")
  335. :param handler: callback that is called upon occurrence of the event
  336. :param args: arguments included in the event message sent to the event handler (default: `None` meaning all)
  337. :param throttle: minimum time (in seconds) between event occurrences (default: 0.0)
  338. :param leading_events: whether to trigger the event handler immediately upon the first event occurrence (default: `True`)
  339. :param trailing_events: whether to trigger the event handler after the last event occurrence (default: `True`)
  340. """
  341. if handler:
  342. listener = EventListener(
  343. element_id=self.id,
  344. type=type,
  345. args=[args] if args and isinstance(args[0], str) else args, # type: ignore
  346. handler=handler,
  347. throttle=throttle,
  348. leading_events=leading_events,
  349. trailing_events=trailing_events,
  350. request=storage.request_contextvar.get(),
  351. )
  352. self._event_listeners[listener.id] = listener
  353. self.update()
  354. return self
  355. def _handle_event(self, msg: Dict) -> None:
  356. listener = self._event_listeners[msg['listener_id']]
  357. storage.request_contextvar.set(listener.request)
  358. args = events.GenericEventArguments(sender=self, client=self.client, args=msg['args'])
  359. events.handle_event(listener.handler, args)
  360. def update(self) -> None:
  361. """Update the element on the client side."""
  362. outbox.enqueue_update(self)
  363. def run_method(self, name: str, *args: Any, timeout: float = 1, check_interval: float = 0.01) -> AwaitableResponse:
  364. """Run a method on the client side.
  365. If the function is awaited, the result of the method call is returned.
  366. Otherwise, the method is executed without waiting for a response.
  367. :param name: name of the method
  368. :param args: arguments to pass to the method
  369. :param timeout: maximum time to wait for a response (default: 1 second)
  370. :param check_interval: time between checks for a response (default: 0.01 seconds)
  371. """
  372. if not core.loop:
  373. return NullResponse()
  374. return self.client.run_javascript(f'return runMethod({self.id}, "{name}", {json.dumps(args)})',
  375. timeout=timeout, check_interval=check_interval)
  376. def _collect_descendants(self, *, include_self: bool = False) -> List[Element]:
  377. elements: List[Element] = [self] if include_self else []
  378. for child in self:
  379. elements.extend(child._collect_descendants(include_self=True)) # pylint: disable=protected-access
  380. return elements
  381. def clear(self) -> None:
  382. """Remove all child elements."""
  383. descendants = self._collect_descendants()
  384. self.client.remove_elements(descendants)
  385. for slot in self.slots.values():
  386. slot.children.clear()
  387. self.update()
  388. def move(self, target_container: Optional[Element] = None, target_index: int = -1):
  389. """Move the element to another container.
  390. :param target_container: container to move the element to (default: the parent container)
  391. :param target_index: index within the target slot (default: append to the end)
  392. """
  393. assert self.parent_slot is not None
  394. self.parent_slot.children.remove(self)
  395. self.parent_slot.parent.update()
  396. target_container = target_container or self.parent_slot.parent
  397. target_index = target_index if target_index >= 0 else len(target_container.default_slot.children)
  398. target_container.default_slot.children.insert(target_index, self)
  399. self.parent_slot = target_container.default_slot
  400. target_container.update()
  401. def remove(self, element: Union[Element, int]) -> None:
  402. """Remove a child element.
  403. :param element: either the element instance or its ID
  404. """
  405. if isinstance(element, int):
  406. children = list(self)
  407. element = children[element]
  408. elements = element._collect_descendants(include_self=True) # pylint: disable=protected-access
  409. self.client.remove_elements(elements)
  410. assert element.parent_slot is not None
  411. element.parent_slot.children.remove(element)
  412. self.update()
  413. def delete(self) -> None:
  414. """Delete the element."""
  415. self.client.remove_elements([self])
  416. assert self.parent_slot is not None
  417. self.parent_slot.children.remove(self)
  418. def _handle_delete(self) -> None:
  419. """Called when the element is deleted.
  420. This method can be overridden in subclasses to perform cleanup tasks.
  421. """
  422. @property
  423. def is_deleted(self) -> bool:
  424. """Whether the element has been deleted."""
  425. return self._deleted