element.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. from __future__ import annotations
  2. import inspect
  3. import re
  4. from copy import copy
  5. from pathlib import Path
  6. from typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterator, List, Optional, Sequence, Union, cast, overload
  7. from typing_extensions import Self
  8. from . import core, events, helpers, json, storage
  9. from .awaitable_response import AwaitableResponse, NullResponse
  10. from .classes import Classes
  11. from .context import context
  12. from .dependencies import Component, Library, register_library, register_resource, register_vue_component
  13. from .elements.mixins.visibility import Visibility
  14. from .event_listener import EventListener
  15. from .props import Props
  16. from .slot import Slot
  17. from .style import Style
  18. from .tailwind import Tailwind
  19. from .version import __version__
  20. if TYPE_CHECKING:
  21. from .client import Client
  22. # https://www.w3.org/TR/xml/#sec-common-syn
  23. 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]'
  24. TAG_CHAR = TAG_START_CHAR + r'|-|\.|[0-9]|\u00B7|[\u0300-\u036F]|[\u203F-\u2040]'
  25. TAG_PATTERN = re.compile(fr'^({TAG_START_CHAR})({TAG_CHAR})*$')
  26. class Element(Visibility):
  27. component: Optional[Component] = None
  28. libraries: ClassVar[List[Library]] = []
  29. extra_libraries: ClassVar[List[Library]] = []
  30. exposed_libraries: ClassVar[List[Library]] = []
  31. _default_props: ClassVar[Dict[str, Any]] = {}
  32. _default_classes: ClassVar[List[str]] = []
  33. _default_style: ClassVar[Dict[str, str]] = {}
  34. def __init__(self, tag: Optional[str] = None, *, _client: Optional[Client] = None) -> None:
  35. """Generic Element
  36. This class is the base class for all other UI elements.
  37. But you can use it to create elements with arbitrary HTML tags.
  38. :param tag: HTML tag of the element
  39. :param _client: client for this element (for internal use only)
  40. """
  41. super().__init__()
  42. self.client = _client or context.client
  43. self.id = self.client.next_element_id
  44. self.client.next_element_id += 1
  45. self.tag = tag if tag else self.component.tag if self.component else 'div'
  46. if not TAG_PATTERN.match(self.tag):
  47. raise ValueError(f'Invalid HTML tag: {self.tag}')
  48. self._classes: Classes[Self] = Classes(self._default_classes, element=cast(Self, self))
  49. self._style: Style[Self] = Style(self._default_style, element=cast(Self, self))
  50. self._props: Props[Self] = Props(self._default_props, element=cast(Self, self))
  51. self._markers: List[str] = []
  52. self._event_listeners: Dict[str, EventListener] = {}
  53. self._text: Optional[str] = None
  54. self.slots: Dict[str, Slot] = {}
  55. self.default_slot = self.add_slot('default')
  56. self._deleted: bool = False
  57. self.client.elements[self.id] = self
  58. self.parent_slot: Optional[Slot] = None
  59. slot_stack = context.slot_stack
  60. if slot_stack:
  61. self.parent_slot = slot_stack[-1]
  62. self.parent_slot.children.append(self)
  63. self.tailwind = Tailwind(self)
  64. self.client.outbox.enqueue_update(self)
  65. if self.parent_slot:
  66. self.client.outbox.enqueue_update(self.parent_slot.parent)
  67. def __init_subclass__(cls, *,
  68. component: Union[str, Path, None] = None,
  69. dependencies: List[Union[str, Path]] = [], # noqa: B006
  70. libraries: List[Union[str, Path]] = [], # noqa: B006 # DEPRECATED
  71. exposed_libraries: List[Union[str, Path]] = [], # noqa: B006 # DEPRECATED
  72. extra_libraries: List[Union[str, Path]] = [], # noqa: B006 # DEPRECATED
  73. ) -> None:
  74. super().__init_subclass__()
  75. base = Path(inspect.getfile(cls)).parent
  76. def glob_absolute_paths(file: Union[str, Path]) -> List[Path]:
  77. path = Path(file)
  78. if not path.is_absolute():
  79. path = base / path
  80. return sorted(path.parent.glob(path.name), key=lambda p: p.stem)
  81. if libraries:
  82. helpers.warn_once(f'The `libraries` parameter for subclassing "{cls.__name__}" is deprecated. '
  83. 'It will be removed in NiceGUI 3.0. '
  84. 'Use `dependencies` instead.')
  85. if exposed_libraries:
  86. helpers.warn_once(f'The `exposed_libraries` parameter for subclassing "{cls.__name__}" is deprecated. '
  87. 'It will be removed in NiceGUI 3.0. '
  88. 'Use `dependencies` instead.')
  89. if extra_libraries:
  90. helpers.warn_once(f'The `extra_libraries` parameter for subclassing "{cls.__name__}" is deprecated. '
  91. 'It will be removed in NiceGUI 3.0. '
  92. 'Use `dependencies` instead.')
  93. cls.component = copy(cls.component)
  94. cls.libraries = copy(cls.libraries)
  95. cls.extra_libraries = copy(cls.extra_libraries)
  96. cls.exposed_libraries = copy(cls.exposed_libraries)
  97. if component:
  98. for path in glob_absolute_paths(component):
  99. cls.component = register_vue_component(path)
  100. for library in libraries:
  101. for path in glob_absolute_paths(library):
  102. cls.libraries.append(register_library(path))
  103. for library in extra_libraries:
  104. for path in glob_absolute_paths(library):
  105. cls.extra_libraries.append(register_library(path))
  106. for library in exposed_libraries + dependencies:
  107. for path in glob_absolute_paths(library):
  108. cls.exposed_libraries.append(register_library(path, expose=True))
  109. cls._default_props = copy(cls._default_props)
  110. cls._default_classes = copy(cls._default_classes)
  111. cls._default_style = copy(cls._default_style)
  112. def add_resource(self, path: Union[str, Path]) -> None:
  113. """Add a resource to the element.
  114. :param path: path to the resource (e.g. folder with CSS and JavaScript files)
  115. """
  116. resource = register_resource(Path(path))
  117. self._props['resource_path'] = f'/_nicegui/{__version__}/resources/{resource.key}'
  118. def add_slot(self, name: str, template: Optional[str] = None) -> Slot:
  119. """Add a slot to the element.
  120. NiceGUI is using the slot concept from Vue:
  121. Elements can have multiple slots, each possibly with a number of children.
  122. Most elements only have one slot, e.g. a `ui.card` (QCard) only has a default slot.
  123. But more complex elements like `ui.table` (QTable) can have more slots like "header", "body" and so on.
  124. If you nest NiceGUI elements via with `ui.row(): ...` you place new elements inside of the row's default slot.
  125. But if you use with `table.add_slot(...): ...`, you enter a different slot.
  126. The slot stack helps NiceGUI to keep track of which slot is currently used for new elements.
  127. The `parent` field holds a reference to its element.
  128. Whenever an element is entered via a `with` expression, its default slot is automatically entered as well.
  129. :param name: name of the slot
  130. :param template: Vue template of the slot
  131. :return: the slot
  132. """
  133. self.slots[name] = Slot(self, name, template)
  134. return self.slots[name]
  135. def __enter__(self) -> Self:
  136. self.default_slot.__enter__()
  137. return self
  138. def __exit__(self, *_) -> None:
  139. self.default_slot.__exit__(*_)
  140. def __iter__(self) -> Iterator[Element]:
  141. for slot in self.slots.values():
  142. yield from slot
  143. def _collect_slot_dict(self) -> Dict[str, Any]:
  144. return {
  145. name: {
  146. 'ids': [child.id for child in slot],
  147. **({'template': slot.template} if slot.template is not None else {}),
  148. }
  149. for name, slot in self.slots.items()
  150. if slot != self.default_slot
  151. }
  152. def _to_dict(self) -> Dict[str, Any]:
  153. return {
  154. 'tag': self.tag,
  155. **({'text': self._text} if self._text is not None else {}),
  156. **{
  157. key: value
  158. for key, value in {
  159. 'class': self._classes,
  160. 'style': self._style,
  161. 'props': self._props,
  162. 'slots': self._collect_slot_dict(),
  163. 'children': [child.id for child in self.default_slot.children],
  164. 'events': [listener.to_dict() for listener in self._event_listeners.values()],
  165. 'component': {
  166. 'key': self.component.key,
  167. 'name': self.component.name,
  168. 'tag': self.component.tag
  169. } if self.component else None,
  170. 'libraries': [
  171. {
  172. 'key': library.key,
  173. 'name': library.name,
  174. } for library in self.libraries
  175. ],
  176. }.items()
  177. if value
  178. },
  179. }
  180. @property
  181. def classes(self) -> Classes[Self]:
  182. """The classes of the element."""
  183. return self._classes
  184. @classmethod
  185. def default_classes(cls,
  186. add: Optional[str] = None, *,
  187. remove: Optional[str] = None,
  188. replace: Optional[str] = None) -> type[Self]:
  189. """Apply, remove, or replace default HTML classes.
  190. This allows modifying the look of the element or its layout using `Tailwind <https://tailwindcss.com/>`_ or `Quasar <https://quasar.dev/>`_ classes.
  191. Removing or replacing classes can be helpful if predefined classes are not desired.
  192. All elements of this class will share these HTML classes.
  193. These must be defined before element instantiation.
  194. :param add: whitespace-delimited string of classes
  195. :param remove: whitespace-delimited string of classes to remove from the element
  196. :param replace: whitespace-delimited string of classes to use instead of existing ones
  197. """
  198. cls._default_classes = Classes.update_list(cls._default_classes, add, remove, replace)
  199. return cls
  200. @property
  201. def style(self) -> Style[Self]:
  202. """The style of the element."""
  203. return self._style
  204. @classmethod
  205. def default_style(cls,
  206. add: Optional[str] = None, *,
  207. remove: Optional[str] = None,
  208. replace: Optional[str] = None) -> type[Self]:
  209. """Apply, remove, or replace default CSS definitions.
  210. Removing or replacing styles can be helpful if the predefined style is not desired.
  211. All elements of this class will share these CSS definitions.
  212. These must be defined before element instantiation.
  213. :param add: semicolon-separated list of styles to add to the element
  214. :param remove: semicolon-separated list of styles to remove from the element
  215. :param replace: semicolon-separated list of styles to use instead of existing ones
  216. """
  217. if replace is not None:
  218. cls._default_style.clear()
  219. for key in Style.parse(remove):
  220. cls._default_style.pop(key, None)
  221. cls._default_style.update(Style.parse(add))
  222. cls._default_style.update(Style.parse(replace))
  223. return cls
  224. @property
  225. def props(self) -> Props[Self]:
  226. """The props of the element."""
  227. return self._props
  228. @classmethod
  229. def default_props(cls,
  230. add: Optional[str] = None, *,
  231. remove: Optional[str] = None) -> type[Self]:
  232. """Add or remove default props.
  233. This allows modifying the look of the element or its layout using `Quasar <https://quasar.dev/>`_ props.
  234. Since props are simply applied as HTML attributes, they can be used with any HTML element.
  235. All elements of this class will share these props.
  236. These must be defined before element instantiation.
  237. Boolean properties are assumed ``True`` if no value is specified.
  238. :param add: whitespace-delimited list of either boolean values or key=value pair to add
  239. :param remove: whitespace-delimited list of property keys to remove
  240. """
  241. for key in Props.parse(remove):
  242. if key in cls._default_props:
  243. del cls._default_props[key]
  244. for key, value in Props.parse(add).items():
  245. cls._default_props[key] = value
  246. return cls
  247. def mark(self, *markers: str) -> Self:
  248. """Replace markers of the element.
  249. Markers are used to identify elements for querying with `ElementFilter </documentation/element_filter>`_
  250. which is heavily used in testing
  251. but can also be used to reduce the number of global variables or passing around dependencies.
  252. :param markers: list of strings or single string with whitespace-delimited markers; replaces existing markers
  253. """
  254. self._markers = [word for marker in markers for word in marker.split()]
  255. return self
  256. def tooltip(self, text: str) -> Self:
  257. """Add a tooltip to the element.
  258. :param text: text of the tooltip
  259. """
  260. from .elements.tooltip import Tooltip # pylint: disable=import-outside-toplevel, cyclic-import
  261. with self:
  262. Tooltip(text)
  263. return self
  264. @overload
  265. def on(self,
  266. type: str, # pylint: disable=redefined-builtin
  267. *,
  268. js_handler: Optional[str] = None,
  269. ) -> Self:
  270. ...
  271. @overload
  272. def on(self,
  273. type: str, # pylint: disable=redefined-builtin
  274. handler: Optional[events.Handler[events.GenericEventArguments]] = None,
  275. args: Union[None, Sequence[str], Sequence[Optional[Sequence[str]]]] = None,
  276. *,
  277. throttle: float = 0.0,
  278. leading_events: bool = True,
  279. trailing_events: bool = True,
  280. ) -> Self:
  281. ...
  282. def on(self,
  283. type: str, # pylint: disable=redefined-builtin
  284. handler: Optional[events.Handler[events.GenericEventArguments]] = None,
  285. args: Union[None, Sequence[str], Sequence[Optional[Sequence[str]]]] = None,
  286. *,
  287. throttle: float = 0.0,
  288. leading_events: bool = True,
  289. trailing_events: bool = True,
  290. js_handler: Optional[str] = None,
  291. ) -> Self:
  292. """Subscribe to an event.
  293. :param type: name of the event (e.g. "click", "mousedown", or "update:model-value")
  294. :param handler: callback that is called upon occurrence of the event
  295. :param args: arguments included in the event message sent to the event handler (default: `None` meaning all)
  296. :param throttle: minimum time (in seconds) between event occurrences (default: 0.0)
  297. :param leading_events: whether to trigger the event handler immediately upon the first event occurrence (default: `True`)
  298. :param trailing_events: whether to trigger the event handler after the last event occurrence (default: `True`)
  299. :param js_handler: JavaScript code that is executed upon occurrence of the event, e.g. `(evt) => alert(evt)` (default: `None`)
  300. """
  301. if handler and js_handler:
  302. raise ValueError('Either handler or js_handler can be specified, but not both')
  303. if handler or js_handler:
  304. listener = EventListener(
  305. element_id=self.id,
  306. type=helpers.kebab_to_camel_case(type),
  307. args=[args] if args and isinstance(args[0], str) else args, # type: ignore
  308. handler=handler,
  309. js_handler=js_handler,
  310. throttle=throttle,
  311. leading_events=leading_events,
  312. trailing_events=trailing_events,
  313. request=storage.request_contextvar.get(),
  314. )
  315. self._event_listeners[listener.id] = listener
  316. self.update()
  317. return self
  318. def _handle_event(self, msg: Dict) -> None:
  319. listener = self._event_listeners[msg['listener_id']]
  320. storage.request_contextvar.set(listener.request)
  321. args = events.GenericEventArguments(sender=self, client=self.client, args=msg['args'])
  322. events.handle_event(listener.handler, args)
  323. def update(self) -> None:
  324. """Update the element on the client side."""
  325. if self.is_deleted:
  326. return
  327. self.client.outbox.enqueue_update(self)
  328. def run_method(self, name: str, *args: Any, timeout: float = 1) -> AwaitableResponse:
  329. """Run a method on the client side.
  330. If the function is awaited, the result of the method call is returned.
  331. Otherwise, the method is executed without waiting for a response.
  332. :param name: name of the method
  333. :param args: arguments to pass to the method
  334. :param timeout: maximum time to wait for a response (default: 1 second)
  335. """
  336. if not core.loop:
  337. return NullResponse()
  338. return self.client.run_javascript(f'return runMethod({self.id}, "{name}", {json.dumps(args)})', timeout=timeout)
  339. def get_computed_prop(self, prop_name: str, *, timeout: float = 1) -> AwaitableResponse:
  340. """Return a computed property.
  341. This function should be awaited so that the computed property is properly returned.
  342. :param prop_name: name of the computed prop
  343. :param timeout: maximum time to wait for a response (default: 1 second)
  344. """
  345. if not core.loop:
  346. return NullResponse()
  347. return self.client.run_javascript(f'return getComputedProp({self.id}, "{prop_name}")', timeout=timeout)
  348. def ancestors(self, *, include_self: bool = False) -> Iterator[Element]:
  349. """Iterate over the ancestors of the element.
  350. :param include_self: whether to include the element itself in the iteration
  351. """
  352. if include_self:
  353. yield self
  354. if self.parent_slot:
  355. yield from self.parent_slot.parent.ancestors(include_self=True)
  356. def descendants(self, *, include_self: bool = False) -> Iterator[Element]:
  357. """Iterate over the descendants of the element.
  358. :param include_self: whether to include the element itself in the iteration
  359. """
  360. if include_self:
  361. yield self
  362. for child in self:
  363. yield from child.descendants(include_self=True)
  364. def clear(self) -> None:
  365. """Remove all child elements."""
  366. self.client.remove_elements(self.descendants())
  367. for slot in self.slots.values():
  368. slot.children.clear()
  369. self.update()
  370. def move(self,
  371. target_container: Optional[Element] = None,
  372. target_index: int = -1, *,
  373. target_slot: Optional[str] = None) -> None:
  374. """Move the element to another container.
  375. :param target_container: container to move the element to (default: the parent container)
  376. :param target_index: index within the target slot (default: append to the end)
  377. :param target_slot: slot within the target container (default: default slot)
  378. """
  379. assert self.parent_slot is not None
  380. self.parent_slot.children.remove(self)
  381. self.parent_slot.parent.update()
  382. target_container = target_container or self.parent_slot.parent
  383. if target_slot is None:
  384. self.parent_slot = target_container.default_slot
  385. elif target_slot in target_container.slots:
  386. self.parent_slot = target_container.slots[target_slot]
  387. else:
  388. raise ValueError(f'Slot "{target_slot}" does not exist in the target container. '
  389. f'Add it first using `add_slot("{target_slot}")`.')
  390. target_index = target_index if target_index >= 0 else len(self.parent_slot.children)
  391. self.parent_slot.children.insert(target_index, self)
  392. target_container.update()
  393. def remove(self, element: Union[Element, int]) -> None:
  394. """Remove a child element.
  395. :param element: either the element instance or its ID
  396. """
  397. if isinstance(element, int):
  398. children = list(self)
  399. element = children[element]
  400. self.client.remove_elements(element.descendants(include_self=True))
  401. assert element.parent_slot is not None
  402. element.parent_slot.children.remove(element)
  403. self.update()
  404. def delete(self) -> None:
  405. """Delete the element and all its children."""
  406. assert self.parent_slot is not None
  407. self.parent_slot.parent.remove(self)
  408. def _handle_delete(self) -> None:
  409. """Called when the element is deleted.
  410. This method can be overridden in subclasses to perform cleanup tasks.
  411. """
  412. @property
  413. def is_deleted(self) -> bool:
  414. """Whether the element has been deleted."""
  415. return self._deleted
  416. def __str__(self) -> str:
  417. result = self.tag if type(self) is Element else self.__class__.__name__ # pylint: disable=unidiomatic-typecheck
  418. def shorten(content: Any, length: int = 20) -> str:
  419. text = str(content).replace('\n', ' ').replace('\r', ' ')
  420. return text[:length].strip() + '...' if len(text) > length else text
  421. additions = []
  422. if self._markers:
  423. additions.append(f'markers={", ".join(self._markers)}')
  424. if self._text:
  425. additions.append(f'text={shorten(self._text)}')
  426. if hasattr(self, 'content') and self.content: # pylint: disable=no-member
  427. additions.append(f'content={shorten(self.content)}') # pylint: disable=no-member
  428. IGNORED_PROPS = {'loopback', 'color', 'view', 'innerHTML', 'codehilite_css_url'}
  429. additions += [
  430. f'{key}={shorten(value)}'
  431. for key, value in self._props.items()
  432. if not key.startswith('_') and key not in IGNORED_PROPS and value
  433. ]
  434. if additions:
  435. result += f' [{", ".join(additions)}]'
  436. for child in self.default_slot.children:
  437. for line in str(child).split('\n'):
  438. result += f'\n {line}'
  439. return result