This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3153 lines
69 KiB

  1. # -*- coding: utf-8 -*
  2. ########################################################################################################################
  3. # DOM-access functions and variables
  4. ########################################################################################################################
  5. try:
  6. # Pyodide
  7. from js import window, eval as jseval
  8. document = window.document
  9. except:
  10. print("Emulation mode")
  11. from xml.dom.minidom import parseString
  12. jseval = None
  13. window = None
  14. document = parseString("<html><head /><body /></html>")
  15. def domCreateAttribute(tag, ns=None):
  16. """
  17. Creates a new HTML/SVG/... attribute
  18. :param ns: the namespace. Default: HTML. Possible values: HTML, SVG, XBL, XUL
  19. """
  20. uri = None
  21. if ns == "SVG":
  22. uri = "http://www.w3.org/2000/svg"
  23. elif ns == "XBL":
  24. uri = "http://www.mozilla.org/xbl"
  25. elif ns == "XUL":
  26. uri = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  27. if uri:
  28. return document.createAttribute(uri, tag)
  29. return document.createAttribute(tag)
  30. def domCreateElement(tag, ns=None):
  31. """
  32. Creates a new HTML/SVG/... tag
  33. :param ns: the namespace. Default: HTML. Possible values: HTML, SVG, XBL, XUL
  34. """
  35. uri = None
  36. if ns == "SVG":
  37. uri = "http://www.w3.org/2000/svg"
  38. elif ns == "XBL":
  39. uri = "http://www.mozilla.org/xbl"
  40. elif ns == "XUL":
  41. uri = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  42. if uri:
  43. return document.createElementNS(uri, tag)
  44. return document.createElement(tag)
  45. def domCreateTextNode(txt=""):
  46. return document.createTextNode(txt)
  47. def domGetElementById(idTag):
  48. return document.getElementById(idTag)
  49. def domElementFromPoint(x, y):
  50. return document.elementFromPoint(x, y)
  51. def domGetElementsByTagName(tag):
  52. items = document.getElementsByTagName(tag)
  53. return [items.item(i) for i in range(0, int(items.length))] #pyodide interprets items.length as float, so convert to int
  54. ########################################################################################################################
  55. # HTML Widgets
  56. ########################################################################################################################
  57. # TextNode -------------------------------------------------------------------------------------------------------------
  58. class TextNode(object):
  59. """
  60. Represents a piece of text inside the DOM.
  61. This is the *only* object not deriving from "Widget", as it does
  62. not support any of its properties.
  63. """
  64. def __init__(self, txt=None, *args, **kwargs):
  65. super().__init__()
  66. self._parent = None
  67. self._children = []
  68. self.element = domCreateTextNode(txt or "")
  69. self._isAttached = False
  70. def _setText(self, txt):
  71. self.element.data = txt
  72. def _getText(self):
  73. return self.element.data
  74. def __str__(self):
  75. return self.element.data
  76. def onAttach(self):
  77. self._isAttached = True
  78. def onDetach(self):
  79. self._isAttached = False
  80. def _setDisabled(self, disabled):
  81. return
  82. def _getDisabled(self):
  83. return False
  84. def children(self):
  85. return []
  86. # _WidgetClassWrapper -------------------------------------------------------------------------------------------------
  87. class _WidgetClassWrapper(list):
  88. def __init__(self, targetWidget):
  89. super().__init__()
  90. self.targetWidget = targetWidget
  91. def _updateElem(self):
  92. if len(self) == 0:
  93. self.targetWidget.element.removeAttribute("class")
  94. else:
  95. self.targetWidget.element.setAttribute("class", " ".join(self))
  96. def append(self, p_object):
  97. list.append(self, p_object)
  98. self._updateElem()
  99. def clear(self):
  100. list.clear(self)
  101. self._updateElem()
  102. def remove(self, value):
  103. try:
  104. list.remove(self, value)
  105. except:
  106. pass
  107. self._updateElem()
  108. def extend(self, iterable):
  109. list.extend(self, iterable)
  110. self._updateElem()
  111. def insert(self, index, p_object):
  112. list.insert(self, index, p_object)
  113. self._updateElem()
  114. def pop(self, index=None):
  115. list.pop(self, index)
  116. self._updateElem()
  117. # _WidgetDataWrapper ---------------------------------------------------------------------------------------------------
  118. class _WidgetDataWrapper(dict):
  119. def __init__(self, targetWidget):
  120. super().__init__()
  121. self.targetWidget = targetWidget
  122. alldata = targetWidget.element
  123. for data in dir(alldata.dataset):
  124. dict.__setitem__(self, data, getattr(alldata.dataset, data))
  125. def __setitem__(self, key, value):
  126. dict.__setitem__(self, key, value)
  127. self.targetWidget.element.setAttribute(str("data-" + key), value)
  128. def update(self, E=None, **F):
  129. dict.update(self, E, **F)
  130. if E is not None and "keys" in dir(E):
  131. for key in E:
  132. self.targetWidget.element.setAttribute(str("data-" + key), E["data-" + key])
  133. elif E:
  134. for (key, val) in E:
  135. self.targetWidget.element.setAttribute(str("data-" + key), "data-" + val)
  136. for key in F:
  137. self.targetWidget.element.setAttribute(str("data-" + key), F["data-" + key])
  138. # _WidgetStyleWrapper --------------------------------------------------------------------------------------------------
  139. class _WidgetStyleWrapper(dict):
  140. def __init__(self, targetWidget):
  141. super().__init__()
  142. self.targetWidget = targetWidget
  143. style = targetWidget.element.style
  144. for key in dir(style):
  145. # Convert JS-Style-Syntax to CSS Syntax (ie borderTop -> border-top)
  146. realKey = ""
  147. for currChar in key:
  148. if currChar.isupper():
  149. realKey += "-"
  150. realKey += currChar.lower()
  151. val = style.getPropertyValue(realKey)
  152. if val:
  153. dict.__setitem__(self, realKey, val)
  154. def __setitem__(self, key, value):
  155. dict.__setitem__(self, key, value)
  156. self.targetWidget.element.style.setProperty(key, value)
  157. def update(self, E=None, **F):
  158. dict.update(self, E, **F)
  159. if E is not None and "keys" in dir(E):
  160. for key in E:
  161. self.targetWidget.element.style.setProperty(key, E[key])
  162. elif E:
  163. for (key, val) in E:
  164. self.targetWidget.element.style.setProperty(key, val)
  165. for key in F:
  166. self.targetWidget.element.style.setProperty(key, F[key])
  167. # Widget ---------------------------------------------------------------------------------------------------------------
  168. class Widget(object):
  169. _tagName = None
  170. _namespace = None
  171. _parserTagName = None
  172. style = []
  173. def __init__(self, *args, appendTo=None, style=None, **kwargs):
  174. if "_wrapElem" in kwargs.keys():
  175. self.element = kwargs["_wrapElem"]
  176. del kwargs["_wrapElem"]
  177. else:
  178. assert self._tagName is not None
  179. self.element = domCreateElement(self._tagName, ns=self._namespace)
  180. super().__init__()
  181. self._widgetClassWrapper = _WidgetClassWrapper(self)
  182. self.addClass(self.style)
  183. if style:
  184. self.addClass(style)
  185. self._children = []
  186. self._catchedEvents = {}
  187. self._disabledState = 0
  188. self._isAttached = False
  189. self._parent = None
  190. self._lastDisplayState = None
  191. if args:
  192. self.appendChild(*args, **kwargs)
  193. if appendTo:
  194. appendTo.appendChild(self)
  195. def sinkEvent(self, *args):
  196. for event_attrName in args:
  197. event = event_attrName.lower()
  198. if event_attrName in self._catchedEvents or event in ["onattach", "ondetach"]:
  199. continue
  200. eventFn = getattr(self, event_attrName, None)
  201. assert eventFn and callable(eventFn), "{} must provide a {} method".format(str(self), event_attrName)
  202. self._catchedEvents[event_attrName] = eventFn
  203. if event.startswith("on"):
  204. event = event[2:]
  205. self.element.addEventListener(event, eventFn)
  206. def unsinkEvent(self, *args):
  207. for event_attrName in args:
  208. event = event_attrName.lower()
  209. if event_attrName not in self._catchedEvents:
  210. continue
  211. eventFn = self._catchedEvents[event_attrName]
  212. del self._catchedEvents[event_attrName]
  213. if event.startswith("on"):
  214. event = event[2:]
  215. self.element.removeEventListener(event, eventFn)
  216. def disable(self):
  217. if not self["disabled"]:
  218. self["disabled"] = True
  219. def enable(self):
  220. if self["disabled"]:
  221. self["disabled"] = False
  222. def _getDisabled(self):
  223. return bool(self._disabledState)
  224. def _setDisabled(self, disable):
  225. for child in self._children:
  226. child._setDisabled(disable)
  227. if disable:
  228. self._disabledState += 1
  229. self.addClass("is-disabled")
  230. if isinstance(self, _attrDisabled):
  231. self.element.disabled = True
  232. elif self._disabledState:
  233. self._disabledState -= 1
  234. if not self._disabledState:
  235. self.removeClass("is-disabled")
  236. if isinstance(self, _attrDisabled):
  237. self.element.disabled = False
  238. def _getTargetfuncName(self, key, type):
  239. assert type in ["get", "set"]
  240. return "_{}{}{}".format(type, key[0].upper(), key[1:])
  241. def __getitem__(self, key):
  242. funcName = self._getTargetfuncName(key, "get")
  243. if funcName in dir(self):
  244. return getattr(self, funcName)()
  245. return None
  246. def __setitem__(self, key, value):
  247. funcName = self._getTargetfuncName(key, "set")
  248. if funcName in dir(self):
  249. return getattr(self, funcName)(value)
  250. raise ValueError("{} is no valid attribute for {}".format(key, (self._tagName or str(self))))
  251. def __str__(self):
  252. return str(self.__class__.__name__)
  253. def __iter__(self):
  254. return self._children.__iter__()
  255. def _getData(self):
  256. """
  257. Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
  258. :param name:
  259. :returns:
  260. """
  261. return _WidgetDataWrapper(self)
  262. def _getTranslate(self):
  263. """
  264. Specifies whether an elements attribute values and contents of its children are to be translated when the page is localized, or whether to leave them unchanged.
  265. :returns: True | False
  266. """
  267. return True if self.element.translate == "yes" else False
  268. def _setTranslate(self, val):
  269. """
  270. Specifies whether an elements attribute values and contents of its children are to be translated when the page is localized, or whether to leave them unchanged.
  271. :param val: True | False
  272. """
  273. self.element.translate = "yes" if val == True else "no"
  274. def _getTitle(self):
  275. """
  276. Advisory information associated with the element.
  277. :returns: str
  278. """
  279. return self.element.title
  280. def _setTitle(self, val):
  281. """
  282. Advisory information associated with the element.
  283. :param val: str
  284. """
  285. self.element.title = val
  286. def _getTabindex(self):
  287. """
  288. Specifies whether the element represents an element that is is focusable (that is, an element which is part of the sequence of focusable elements in the document), and the relative order of the element in the sequence of focusable elements in the document.
  289. :returns: number
  290. """
  291. return self.element.getAttribute("tabindex")
  292. def _setTabindex(self, val):
  293. """
  294. Specifies whether the element represents an element that is is focusable (that is, an element which is part of the sequence of focusable elements in the document), and the relative order of the element in the sequence of focusable elements in the document.
  295. :param val: number
  296. """
  297. self.element.setAttribute("tabindex", val)
  298. def _getSpellcheck(self):
  299. """
  300. Specifies whether the element represents an element whose contents are subject to spell checking and grammar checking.
  301. :returns: True | False
  302. """
  303. return True if self.element.spellcheck == "true" else False
  304. def _setSpellcheck(self, val):
  305. """
  306. Specifies whether the element represents an element whose contents are subject to spell checking and grammar checking.
  307. :param val: True | False
  308. """
  309. self.element.spellcheck = str(val).lower()
  310. def _getLang(self):
  311. """
  312. Specifies the primary language for the contents of the element and for any of the elements attributes that contain text.
  313. :returns: language tag e.g. de|en|fr|es|it|ru|
  314. """
  315. return self.element.lang
  316. def _setLang(self, val):
  317. """
  318. Specifies the primary language for the contents of the element and for any of the elements attributes that contain text.
  319. :param val: language tag
  320. """
  321. self.element.lang = val
  322. def _getHidden(self):
  323. """
  324. Specifies that the element represents an element that is not yet, or is no longer, relevant.
  325. :returns: True | False
  326. """
  327. return True if self.element.hasAttribute("hidden") else False
  328. def _setHidden(self, val):
  329. """
  330. Specifies that the element represents an element that is not yet, or is no longer, relevant.
  331. :param val: True | False
  332. """
  333. if val:
  334. self.element.setAttribute("hidden", "")
  335. else:
  336. self.element.removeAttribute("hidden")
  337. def _getDropzone(self):
  338. """
  339. Specifies what types of content can be dropped on the element, and instructs the UA about which actions to take with content when it is dropped on the element.
  340. :returns: "copy" | "move" | "link"
  341. """
  342. return self.element.dropzone
  343. def _setDropzone(self, val):
  344. """
  345. Specifies what types of content can be dropped on the element, and instructs the UA about which actions to take with content when it is dropped on the element.
  346. :param val: "copy" | "move" | "link"
  347. """
  348. self.element.dropzone = val
  349. def _getDraggable(self):
  350. """
  351. Specifies whether the element is draggable.
  352. :returns: True | False | "auto"
  353. """
  354. return (self.element.draggable if str(self.element.draggable) == "auto" else (
  355. True if str(self.element.draggable).lower() == "true" else False))
  356. def _setDraggable(self, val):
  357. """
  358. Specifies whether the element is draggable.
  359. :param val: True | False | "auto"
  360. """
  361. self.element.draggable = str(val).lower()
  362. def _getDir(self):
  363. """
  364. Specifies the elements text directionality.
  365. :returns: ltr | rtl | auto
  366. """
  367. return self.element.dir
  368. def _setDir(self, val):
  369. """
  370. Specifies the elements text directionality.
  371. :param val: ltr | rtl | auto
  372. """
  373. self.element.dir = val
  374. def _getContextmenu(self):
  375. """
  376. The value of the id attribute on the menu with which to associate the element as a context menu.
  377. :returns:
  378. """
  379. return self.element.contextmenu
  380. def _setContextmenu(self, val):
  381. """
  382. The value of the id attribute on the menu with which to associate the element as a context menu.
  383. :param val:
  384. """
  385. self.element.contextmenu = val
  386. def _getContenteditable(self):
  387. """
  388. Specifies whether the contents of the element are editable.
  389. :returns: True | False
  390. """
  391. v = self.element.getAttribute("contenteditable")
  392. return str(v).lower() == "true"
  393. def _setContenteditable(self, val):
  394. """
  395. Specifies whether the contents of the element are editable.
  396. :param val: True | False
  397. """
  398. self.element.setAttribute("contenteditable", str(val).lower())
  399. def _getAccesskey(self):
  400. """
  401. A key label or list of key labels with which to associate the element; each key label represents a keyboard shortcut which UAs can use to activate the element or give focus to the element.
  402. :param self:
  403. :returns:
  404. """
  405. return self.element.accesskey
  406. def _setAccesskey(self, val):
  407. """
  408. A key label or list of key labels with which to associate the element; each key label represents a keyboard shortcut which UAs can use to activate the element or give focus to the element.
  409. :param self:
  410. :param val:
  411. """
  412. self.element.accesskey = val
  413. def _getId(self):
  414. """
  415. Specifies a unique id for an element
  416. :param self:
  417. :returns:
  418. """
  419. return self.element.id
  420. def _setId(self, val):
  421. """
  422. Specifies a unique id for an element
  423. :param self:
  424. :param val:
  425. """
  426. self.element.id = val
  427. def _getClass(self):
  428. """
  429. The class attribute specifies one or more classnames for an element.
  430. :returns:
  431. """
  432. return self._widgetClassWrapper
  433. def _setClass(self, value):
  434. """
  435. The class attribute specifies one or more classnames for an element.
  436. :param self:
  437. :param value:
  438. @raise ValueError:
  439. """
  440. if value is None:
  441. self.element.setAttribute("class", " ")
  442. elif isinstance(value, str):
  443. self.element.setAttribute("class", value)
  444. elif isinstance(value, list):
  445. self.element.setAttribute("class", " ".join(value))
  446. else:
  447. raise ValueError("Class must be a str, a List or None")
  448. def _getStyle(self):
  449. """
  450. The style attribute specifies an inline style for an element.
  451. :param self:
  452. :returns:
  453. """
  454. return _WidgetStyleWrapper(self)
  455. def _getRole(self):
  456. """
  457. Specifies a role for an element
  458. @param self:
  459. @return:
  460. """
  461. return self.element.getAttribute("role")
  462. def _setRole(self, val):
  463. """
  464. Specifies a role for an element
  465. @param self:
  466. @param val:
  467. """
  468. self.element.setAttribute("role", val)
  469. def hide(self):
  470. """
  471. Hide element, if shown.
  472. :return:
  473. """
  474. state = self["style"].get("display", "")
  475. if state != "none":
  476. self._lastDisplayState = state
  477. self["style"]["display"] = "none"
  478. def show(self):
  479. """
  480. Show element, if hidden.
  481. :return:
  482. """
  483. if self._lastDisplayState is not None:
  484. self["style"]["display"] = self._lastDisplayState
  485. self._lastDisplayState = None
  486. def isHidden(self):
  487. """
  488. Checks if a widget is hidden.
  489. :return: True if hidden, False otherwise.
  490. """
  491. return self["style"].get("display", "") == "none"
  492. def isVisible(self):
  493. """
  494. Checks if a widget is visible.
  495. :return: True if visible, False otherwise.
  496. """
  497. return not self.isHidden()
  498. def onBind(self, widget, name):
  499. """
  500. Event function that is called on the widget when it is bound to another widget with a name.
  501. This is only done by the HTML parser, a manual binding by the user is not triggered.
  502. """
  503. return
  504. def onAttach(self):
  505. self._isAttached = True
  506. for c in self._children:
  507. c.onAttach()
  508. def onDetach(self):
  509. self._isAttached = False
  510. for c in self._children:
  511. c.onDetach()
  512. def __collectChildren(self, *args, **kwargs):
  513. assert not isinstance(self, _isVoid), "<%s> can't have children!" % self._tagName
  514. if kwargs.get("bindTo") is None:
  515. kwargs["bindTo"] = self
  516. widgets = []
  517. for arg in args:
  518. if isinstance(arg, (str, HtmlAst)):
  519. widgets.extend(fromHTML(arg, **kwargs))
  520. elif isinstance(arg, (list, tuple)):
  521. for subarg in arg:
  522. widgets.extend(self.__collectChildren(subarg, **kwargs))
  523. elif not isinstance(arg, (Widget, TextNode)):
  524. widgets.append(TextNode(str(arg)))
  525. else:
  526. widgets.append(arg)
  527. return widgets
  528. def insertBefore(self, insert, child, **kwargs):
  529. if not child:
  530. return self.appendChild(insert)
  531. assert child in self._children, "{} is not a child of {}".format(child, self)
  532. toInsert = self.__collectChildren(insert, **kwargs)
  533. for insert in toInsert:
  534. if insert._parent:
  535. insert._parent.removeChild(insert)
  536. self.element.insertBefore(insert.element, child.element)
  537. self._children.insert(self._children.index(child), insert)
  538. insert._parent = self
  539. if self._isAttached:
  540. insert.onAttach()
  541. return toInsert
  542. def prependChild(self, *args, **kwargs):
  543. if kwargs.get("replace", False):
  544. self.removeAllChildren()
  545. del kwargs["replace"]
  546. toPrepend = self.__collectChildren(*args, **kwargs)
  547. for child in toPrepend:
  548. if child._parent:
  549. child._parent._children.remove(child)
  550. child._parent = None
  551. if not self._children:
  552. self.appendChild(child)
  553. else:
  554. self.insertBefore(child, self.children(0))
  555. return toPrepend
  556. def appendChild(self, *args, **kwargs):
  557. if kwargs.get("replace", False):
  558. self.removeAllChildren()
  559. del kwargs["replace"]
  560. toAppend = self.__collectChildren(*args, **kwargs)
  561. for child in toAppend:
  562. if child._parent:
  563. child._parent._children.remove(child)
  564. self._children.append(child)
  565. self.element.appendChild(child.element)
  566. child._parent = self
  567. if self._isAttached:
  568. child.onAttach()
  569. return toAppend
  570. def removeChild(self, child):
  571. assert child in self._children, "{} is not a child of {}".format(child, self)
  572. if child._isAttached:
  573. child.onDetach()
  574. self.element.removeChild(child.element)
  575. self._children.remove(child)
  576. child._parent = None
  577. def removeAllChildren(self):
  578. """
  579. Removes all child widgets of the current widget.
  580. """
  581. for child in self._children[:]:
  582. self.removeChild(child)
  583. def isParentOf(self, widget):
  584. """
  585. Checks if an object is the parent of widget.
  586. :type widget: Widget
  587. :param widget: The widget to check for.
  588. :return: True, if widget is a child of the object, else False.
  589. """
  590. # You cannot be your own child!
  591. if self == widget:
  592. return False
  593. for child in self._children:
  594. if child == widget:
  595. return True
  596. if child.isParentOf(widget):
  597. return True
  598. return False
  599. def isChildOf(self, widget):
  600. """
  601. Checks if an object is the child of widget.
  602. :type widget: Widget
  603. :param widget: The widget to check for.
  604. :return: True, if object is a child of widget, else False.
  605. """
  606. # You cannot be your own parent!
  607. if self == widget:
  608. return False
  609. parent = self.parent()
  610. while parent:
  611. if parent == widget:
  612. return True
  613. parent = widget.parent()
  614. return False
  615. def hasClass(self, className):
  616. """
  617. Determine whether the current widget is assigned the given class
  618. :param className: The class name to search for.
  619. :type className: str
  620. """
  621. if isinstance(className, str) or isinstance(className, unicode):
  622. return className in self["class"]
  623. else:
  624. raise TypeError()
  625. def addClass(self, *args):
  626. """
  627. Adds a class or a list of classes to the current widget.
  628. If the widget already has the class, it is ignored.
  629. :param args: A list of class names. This can also be a list.
  630. :type args: list of str | list of list of str
  631. """
  632. for item in args:
  633. if isinstance(item, list):
  634. self.addClass(*item)
  635. elif isinstance(item, str):
  636. for sitem in item.split(" "):
  637. if not self.hasClass(sitem):
  638. self["class"].append(sitem)
  639. else:
  640. raise TypeError()
  641. def removeClass(self, *args):
  642. """
  643. Removes a class or a list of classes from the current widget.
  644. :param args: A list of class names. This can also be a list.
  645. :type args: list of str | list of list of str
  646. """
  647. for item in args:
  648. if isinstance(item, list):
  649. self.removeClass(item)
  650. elif isinstance(item, str):
  651. for sitem in item.split(" "):
  652. if self.hasClass(sitem):
  653. self["class"].remove(sitem)
  654. else:
  655. raise TypeError()
  656. def toggleClass(self, on, off=None):
  657. """
  658. Toggles the class ``on``.
  659. If the widget contains a class ``on``, it is toggled by ``off``.
  660. ``off`` can either be a class name that is substituted, or nothing.
  661. :param on: Classname to test for. If ``on`` does not exist, but ``off``, ``off`` is replaced by ``on``.
  662. :type on: str
  663. :param off: Classname to replace if ``on`` existed.
  664. :type off: str
  665. :return: Returns True, if ``on`` was switched, else False.
  666. :rtype: bool
  667. """
  668. if self.hasClass(on):
  669. self.removeClass(on)
  670. if off and not self.hasClass(off):
  671. self.addClass(off)
  672. return False
  673. if off and self.hasClass(off):
  674. self.removeClass(off)
  675. self.addClass(on)
  676. return True
  677. def onBlur(self, event):
  678. pass
  679. def onChange(self, event):
  680. pass
  681. def onContextMenu(self, event):
  682. pass
  683. def onFocus(self, event):
  684. pass
  685. def onFocusIn(self, event):
  686. pass
  687. def onFocusOut(self, event):
  688. pass
  689. def onFormChange(self, event):
  690. pass
  691. def onFormInput(self, event):
  692. pass
  693. def onInput(self, event):
  694. pass
  695. def onInvalid(self, event):
  696. pass
  697. def onReset(self, event):
  698. pass
  699. def onSelect(self, event):
  700. pass
  701. def onSubmit(self, event):
  702. pass
  703. def onKeyDown(self, event):
  704. pass
  705. def onKeyPress(self, event):
  706. pass
  707. def onKeyUp(self, event):
  708. pass
  709. def onClick(self, event):
  710. pass
  711. def onDblClick(self, event):
  712. pass
  713. def onDrag(self, event):
  714. pass
  715. def onDragEnd(self, event):
  716. pass
  717. def onDragEnter(self, event):
  718. pass
  719. def onDragLeave(self, event):
  720. pass
  721. def onDragOver(self, event):
  722. pass
  723. def onDragStart(self, event):
  724. pass
  725. def onDrop(self, event):
  726. pass
  727. def onMouseDown(self, event):
  728. pass
  729. def onMouseMove(self, event):
  730. pass
  731. def onMouseOut(self, event):
  732. pass
  733. def onMouseOver(self, event):
  734. pass
  735. def onMouseUp(self, event):
  736. pass
  737. def onMouseWheel(self, event):
  738. pass
  739. def onScroll(self, event):
  740. pass
  741. def onTouchStart(self, event):
  742. pass
  743. def onTouchEnd(self, event):
  744. pass
  745. def onTouchMove(self, event):
  746. pass
  747. def onTouchCancel(self, event):
  748. pass
  749. def focus(self):
  750. self.element.focus()
  751. def blur(self):
  752. self.element.blur()
  753. def parent(self):
  754. return self._parent
  755. def children(self, n=None):
  756. """
  757. Access children of widget.
  758. If ``n`` is ommitted, it returns a list of all child-widgets;
  759. Else, it returns the N'th child, or None if its out of bounds.
  760. :param n: Optional offset of child widget to return.
  761. :type n: int
  762. :return: Returns all children or only the requested one.
  763. :rtype: list | Widget | None
  764. """
  765. if n is None:
  766. return self._children[:]
  767. try:
  768. return self._children[n]
  769. except IndexError:
  770. return None
  771. def sortChildren(self, key):
  772. """
  773. Sorts our direct children. They are rearranged on DOM level.
  774. Key must be a function accepting one widget as parameter and must return
  775. the key used to sort these widgets.
  776. """
  777. self._children.sort(key=key)
  778. tmpl = self._children[:]
  779. tmpl.reverse()
  780. for c in tmpl:
  781. self.element.removeChild(c.element)
  782. self.element.insertBefore(c.element, self.element.children.item(0))
  783. def fromHTML(self, html, appendTo=None, bindTo=None, replace=False, vars=None, **kwargs):
  784. """
  785. Parses html and constructs its elements as part of self.
  786. :param html: HTML code.
  787. :param appendTo: The entity where the HTML code is constructed below. This defaults to self in usual case.
  788. :param bindTo: The entity where the named objects are bound to. This defaults to self in usual case.
  789. :param replace: Clear entire content of appendTo before appending.
  790. :param vars: Deprecated; Same as kwargs.
  791. :param **kwargs: Additional variables provided as a dict for {{placeholders}} inside the HTML
  792. :return:
  793. """
  794. if appendTo is None:
  795. appendTo = self
  796. if bindTo is None:
  797. bindTo = self
  798. if replace:
  799. appendTo.removeAllChildren()
  800. # use of vars is deprecated!
  801. if isinstance(vars, dict):
  802. kwargs.update(vars)
  803. return fromHTML(html, appendTo=appendTo, bindTo=bindTo, **kwargs)
  804. ########################################################################################################################
  805. # Attribute Collectors
  806. ########################################################################################################################
  807. # _attrLabel ---------------------------------------------------------------------------------------------------------------
  808. class _attrLabel(object):
  809. def _getLabel(self):
  810. return self.element.getAttribute("label")
  811. def _setLabel(self, val):
  812. self.element.setAttribute("label", val)
  813. # _attrCharset --------------------------------------------------------------------------------------------------------------
  814. class _attrCharset(object):
  815. def _getCharset(self):
  816. return self.element._attrCharset
  817. def _setCharset(self, val):
  818. self.element._attrCharset = val
  819. # _attrCite -----------------------------------------------------------------------------------------------------------------
  820. class _attrCite(object):
  821. def _getCite(self):
  822. return self.element._attrCite
  823. def _setCite(self, val):
  824. self.element._attrCite = val
  825. class _attrDatetime(object):
  826. def _getDatetime(self):
  827. return self.element.datetime
  828. def _setDatetime(self, val):
  829. self.element.datetime = val
  830. # Form -----------------------------------------------------------------------------------------------------------------
  831. class _attrForm(object):
  832. def _getForm(self):
  833. return self.element.form
  834. def _setForm(self, val):
  835. self.element.form = val
  836. class _attrAlt(object):
  837. def _getAlt(self):
  838. return self.element.alt
  839. def _setAlt(self, val):
  840. self.element.alt = val
  841. class _attrAutofocus(object):
  842. def _getAutofocus(self):
  843. return True if self.element.hasAttribute("autofocus") else False
  844. def _setAutofocus(self, val):
  845. if val:
  846. self.element.setAttribute("autofocus", "")
  847. else:
  848. self.element.removeAttribute("autofocus")
  849. class _attrDisabled(object):
  850. pass
  851. class _attrChecked(object):
  852. def _getChecked(self):
  853. return self.element.checked
  854. def _setChecked(self, val):
  855. self.element.checked = val
  856. class _attrIndeterminate(object):
  857. def _getIndeterminate(self):
  858. return self.element.indeterminate
  859. def _setIndeterminate(self, val):
  860. self.element.indeterminate = val
  861. class _attrName(object):
  862. def _getName(self):
  863. return self.element.getAttribute("name")
  864. def _setName(self, val):
  865. self.element.setAttribute("name", val)
  866. class _attrValue(object):
  867. def _getValue(self):
  868. return self.element.value
  869. def _setValue(self, val):
  870. self.element.value = val
  871. class _attrAutocomplete(object):
  872. def _getAutocomplete(self):
  873. return True if self.element.autocomplete == "on" else False
  874. def _setAutocomplete(self, val):
  875. self.element.autocomplete = "on" if val == True else "off"
  876. class _attrRequired(object):
  877. def _getRequired(self):
  878. return True if self.element.hasAttribute("required") else False
  879. def _setRequired(self, val):
  880. if val:
  881. self.element.setAttribute("required", "")
  882. else:
  883. self.element.removeAttribute("required")
  884. class _attrMultiple(object):
  885. def _getMultiple(self):
  886. return True if self.element.hasAttribute("multiple") else False
  887. def _setMultiple(self, val):
  888. if val:
  889. self.element.setAttribute("multiple", "")
  890. else:
  891. self.element.removeAttribute("multiple")
  892. class _attrSize(object):
  893. def _getSize(self):
  894. return self.element.size
  895. def _setSize(self, val):
  896. self.element.size = val
  897. class _attrFor(object):
  898. def _getFor(self):
  899. return self.element.getAttribute("for")
  900. def _setFor(self, val):
  901. self.element.setAttribute("for", val)
  902. class _attrInputs(_attrRequired):
  903. def _getMaxlength(self):
  904. return self.element.maxlength
  905. def _setMaxlength(self, val):
  906. self.element.maxlength = val
  907. def _getPlaceholder(self):
  908. return self.element.placeholder
  909. def _setPlaceholder(self, val):
  910. self.element.placeholder = val
  911. def _getReadonly(self):
  912. return True if self.element.hasAttribute("readonly") else False
  913. def _setReadonly(self, val):
  914. if val:
  915. self.element.setAttribute("readonly", "")
  916. else:
  917. self.element.removeAttribute("readonly")
  918. class _attrFormhead(object):
  919. def _getFormaction(self):
  920. return self.element.formaction
  921. def _setFormaction(self, val):
  922. self.element.formaction = val
  923. def _getFormenctype(self):
  924. return self.element.formenctype
  925. def _setFormenctype(self, val):
  926. self.element.formenctype = val
  927. def _getFormmethod(self):
  928. return self.element.formmethod
  929. def _setFormmethod(self, val):
  930. self.element.formmethod = val
  931. def _getFormtarget(self):
  932. return self.element.formtarget
  933. def _setFormtarget(self, val):
  934. self.element.formtarget = val
  935. def _getFormnovalidate(self):
  936. return True if self.element.hasAttribute("formnovalidate") else False
  937. def _setFormnovalidate(self, val):
  938. if val:
  939. self.element.setAttribute("formnovalidate", "")
  940. else:
  941. self.element.removeAttribute("formnovalidate")
  942. # _attrHref -----------------------------------------------------------------------------------------------------------------
  943. class _attrHref(object):
  944. def _getHref(self):
  945. """
  946. Url of a Page
  947. :param self:
  948. """
  949. return self.element.href
  950. def _setHref(self, val):
  951. """
  952. Url of a Page
  953. :param val: URL
  954. """
  955. self.element.href = val
  956. def _getHreflang(self):
  957. return self.element.hreflang
  958. def _setHreflang(self, val):
  959. self.element.hreflang = val
  960. class _attrTarget(object):
  961. def _getTarget(self):
  962. return self.element.target
  963. def _setTarget(self, val):
  964. self.element.target = val
  965. # _attrMedia ----------------------------------------------------------------------------------------------------------------
  966. class _attrType(object):
  967. def _getType(self):
  968. return self.element.type
  969. def _setType(self, val):
  970. self.element.type = val
  971. class _attrMedia(_attrType):
  972. def _getMedia(self):
  973. return self.element.media
  974. def _setMedia(self, val):
  975. self.element.media = val
  976. class _attrDimensions(object):
  977. def _getWidth(self):
  978. return self.element.width
  979. def _setWidth(self, val):
  980. self.element.width = val
  981. def _getHeight(self):
  982. return self.element.height
  983. def _setHeight(self, val):
  984. self.element.height = val
  985. class _attrUsemap(object):
  986. def _getUsemap(self):
  987. return self.element.usemap
  988. def _setUsemap(self, val):
  989. self.element.usemap = val
  990. class _attrMultimedia(object):
  991. def _getAutoplay(self):
  992. return True if self.element.hasAttribute("autoplay") else False
  993. def _setAutoplay(self, val):
  994. if val:
  995. self.element.setAttribute("autoplay", "")
  996. else:
  997. self.element.removeAttribute("autoplay")
  998. def _getPlaysinline(self):
  999. return True if self.element.hasAttribute("playsinline") else False
  1000. def _setPlaysinline(self, val):
  1001. if val:
  1002. self.element.setAttribute("playsinline", "")
  1003. else:
  1004. self.element.removeAttribute("playsinline")
  1005. def _getControls(self):
  1006. return True if self.element.hasAttribute("controls") else False
  1007. def _setControls(self, val):
  1008. if val:
  1009. self.element.setAttribute("controls", "")
  1010. else:
  1011. self.element.removeAttribute("controls")
  1012. def _getLoop(self):
  1013. return True if self.element.hasAttribute("loop") else False
  1014. def _setLoop(self, val):
  1015. if val:
  1016. self.element.setAttribute("loop", "")
  1017. else:
  1018. self.element.removeAttribute("loop")
  1019. def _getMuted(self):
  1020. return True if self.element.hasAttribute("muted") else False
  1021. def _setMuted(self, val):
  1022. if val:
  1023. self.element.setAttribute("muted", "")
  1024. else:
  1025. self.element.removeAttribute("muted")
  1026. def _getPreload(self):
  1027. return self.element.preload
  1028. def _setPreload(self, val):
  1029. self.element.preload = val
  1030. # _attrRel ------------------------------------------------------------------------------------------------------------------
  1031. class _attrRel(object):
  1032. def _getRel(self):
  1033. return self.element.rel
  1034. def _setRel(self, val):
  1035. self.element.rel = val
  1036. # _attrSrc ------------------------------------------------------------------------------------------------------------------
  1037. class _attrSrc(object):
  1038. def _getSrc(self):
  1039. return self.element.src
  1040. def _setSrc(self, val):
  1041. self.element.src = val
  1042. # Svg ------------------------------------------------------------------------------------------------------------------
  1043. class _attrSvgViewBox(object):
  1044. def _getViewbox(self):
  1045. viewBox = self.element.viewBox
  1046. try:
  1047. return " ".join([str(x) for x in [viewBox.baseVal.x, viewBox.baseVal.y, viewBox.baseVal.width, viewBox.baseVal.height]])
  1048. except:
  1049. return ""
  1050. def _setViewbox(self, val):
  1051. self.element.setAttribute("viewBox", val)
  1052. def _getPreserveaspectratio(self):
  1053. return self.element.preserveAspectRatio
  1054. def _setPreserveaspectratio(self, val):
  1055. self.element.setAttribute("preserveAspectRatio", val)
  1056. class _attrSvgDimensions(object):
  1057. def _getWidth(self):
  1058. return self.element.width
  1059. def _setWidth(self, val):
  1060. self.element.setAttribute("width", val)
  1061. def _getHeight(self):
  1062. return self.element.height
  1063. def _setHeight(self, val):
  1064. self.element.setAttribute("height", val)
  1065. def _getX(self):
  1066. return self.element.x
  1067. def _setX(self, val):
  1068. self.element.setAttribute("x", val)
  1069. def _getY(self):
  1070. return self.element.y
  1071. def _setY(self, val):
  1072. self.element.setAttribute("y", val)
  1073. def _getR(self):
  1074. return self.element.r
  1075. def _setR(self, val):
  1076. self.element.setAttribute("r", val)
  1077. def _getRx(self):
  1078. return self.element.rx
  1079. def _setRx(self, val):
  1080. self.element.setAttribute("rx", val)
  1081. def _getRy(self):
  1082. return self.element.ry
  1083. def _setRy(self, val):
  1084. self.element.setAttribute("ry", val)
  1085. def _getCx(self):
  1086. return self.element.cx
  1087. def _setCx(self, val):
  1088. self.element.setAttribute("cx", val)
  1089. def _getCy(self):
  1090. return self.element.cy
  1091. def _setCy(self, val):
  1092. self.element.setAttribute("cy", val)
  1093. class _attrSvgPoints(object):
  1094. def _getPoints(self):
  1095. return self.element.points
  1096. def _setPoints(self, val):
  1097. self.element.setAttribute("points", val)
  1098. def _getX1(self):
  1099. return self.element.x1
  1100. def _setX1(self, val):
  1101. self.element.setAttribute("x1", val)
  1102. def _getY1(self):
  1103. return self.element.y1
  1104. def _setY1(self, val):
  1105. self.element.setAttribute("y1", val)
  1106. def _getX2(self):
  1107. return self.element.x2
  1108. def _setX2(self, val):
  1109. self.element.setAttribute("x2", val)
  1110. def _getY2(self):
  1111. return self.element.y2
  1112. def _setY2(self, val):
  1113. self.element.setAttribute("y2", val)
  1114. class _attrSvgTransform(object):
  1115. def _getTransform(self):
  1116. return self.element.transform
  1117. def _setTransform(self, val):
  1118. self.element.setAttribute("transform", val)
  1119. class _attrSvgXlink(object):
  1120. def _getXlinkhref(self):
  1121. return self.element.getAttribute("xlink:href")
  1122. def _setXlinkhref(self, val):
  1123. self.element.setAttribute("xlink:href", val)
  1124. class _attrSvgStyles(object):
  1125. def _getFill(self):
  1126. return self.element.fill
  1127. def _setFill(self, val):
  1128. self.element.setAttribute("fill", val)
  1129. def _getStroke(self):
  1130. return self.element.stroke
  1131. def _setStroke(self, val):
  1132. self.element.setAttribute("stroke", val)
  1133. class _isVoid(object):
  1134. pass
  1135. ########################################################################################################################
  1136. # HTML Elements
  1137. ########################################################################################################################
  1138. # A --------------------------------------------------------------------------------------------------------------------
  1139. class A(Widget, _attrHref, _attrTarget, _attrMedia, _attrRel, _attrName):
  1140. _tagName = "a"
  1141. def _getDownload(self):
  1142. """
  1143. The download attribute specifies the path to a download
  1144. :returns: filename
  1145. """
  1146. return self.element.download
  1147. def _setDownload(self, val):
  1148. """
  1149. The download attribute specifies the path to a download
  1150. :param val: filename
  1151. """
  1152. self.element.download = val
  1153. # Area -----------------------------------------------------------------------------------------------------------------
  1154. class Area(A, _attrAlt, _isVoid):
  1155. _tagName = "area"
  1156. def _getCoords(self):
  1157. return self.element.coords
  1158. def _setCoords(self, val):
  1159. self.element.coords = val
  1160. def _getShape(self):
  1161. return self.element.shape
  1162. def _setShape(self, val):
  1163. self.element.shape = val
  1164. # Audio ----------------------------------------------------------------------------------------------------------------
  1165. class Audio(Widget, _attrSrc, _attrMultimedia):
  1166. _tagName = "audio"
  1167. class Bdo(Widget):
  1168. _tagName = "bdo"
  1169. # Blockquote -----------------------------------------------------------------------------------------------------------
  1170. class Blockquote(Widget):
  1171. _tagName = "blockquote"
  1172. def _getBlockquote(self):
  1173. return self.element.blockquote
  1174. def _setBlockquote(self, val):
  1175. self.element.blockquote = val
  1176. # Body -----------------------------------------------------------------------------------------------------------------
  1177. class BodyCls(Widget):
  1178. def __init__(self, *args, **kwargs):
  1179. super().__init__(_wrapElem=domGetElementsByTagName("body")[0], *args, **kwargs)
  1180. self._isAttached = True
  1181. _body = None
  1182. def Body():
  1183. global _body
  1184. if _body is None:
  1185. _body = BodyCls()
  1186. return _body
  1187. # Canvas ---------------------------------------------------------------------------------------------------------------
  1188. class Canvas(Widget, _attrDimensions):
  1189. _tagName = "canvas"
  1190. # Command --------------------------------------------------------------------------------------------------------------
  1191. class Command(Widget, _attrLabel, _attrType, _attrDisabled, _attrChecked):
  1192. _tagName = "command"
  1193. def _getIcon(self):
  1194. return self.element.icon
  1195. def _setIcon(self, val):
  1196. self.element.icon = val
  1197. def _getRadiogroup(self):
  1198. return self.element.radiogroup
  1199. def _setRadiogroup(self, val):
  1200. self.element.radiogroup = val
  1201. # _Del -----------------------------------------------------------------------------------------------------------------
  1202. class _Del(Widget, _attrCite, _attrDatetime):
  1203. _tagName = "_del"
  1204. # Dialog --------------------------------------------------------------------------------------------------------------
  1205. class Dialog(Widget):
  1206. _tagName = "dialog"
  1207. def _getOpen(self):
  1208. return True if self.element.hasAttribute("open") else False
  1209. def _setOpen(self, val):
  1210. if val:
  1211. self.element.setAttribute("open", "")
  1212. else:
  1213. self.element.removeAttribute("open")
  1214. # Elements -------------------------------------------------------------------------------------------------------------
  1215. class Abbr(Widget):
  1216. _tagName = "abbr"
  1217. class Address(Widget):
  1218. _tagName = "address"
  1219. class Article(Widget):
  1220. _tagName = "article"
  1221. class Aside(Widget):
  1222. _tagName = "aside"
  1223. class B(Widget):
  1224. _tagName = "b"
  1225. class Bdi(Widget):
  1226. _tagName = "bdi"
  1227. class Br(Widget, _isVoid):
  1228. _tagName = "br"
  1229. class Caption(Widget):
  1230. _tagName = "caption"
  1231. class Cite(Widget):
  1232. _tagName = "cite"
  1233. class Code(Widget):
  1234. _tagName = "code"
  1235. class Datalist(Widget):
  1236. _tagName = "datalist"
  1237. class Dfn(Widget):
  1238. _tagName = "dfn"
  1239. class Div(Widget):
  1240. _tagName = "div"
  1241. class Em(Widget):
  1242. _tagName = "em"
  1243. class Embed(Widget, _attrSrc, _attrType, _attrDimensions, _isVoid):
  1244. _tagName = "embed"
  1245. class Figcaption(Widget):
  1246. _tagName = "figcaption"
  1247. class Figure(Widget):
  1248. _tagName = "figure"
  1249. class Footer(Widget):
  1250. _tagName = "footer"
  1251. class Header(Widget):
  1252. _tagName = "header"
  1253. class H1(Widget):
  1254. _tagName = "h1"
  1255. class H2(Widget):
  1256. _tagName = "h2"
  1257. class H3(Widget):
  1258. _tagName = "h3"
  1259. class H4(Widget):
  1260. _tagName = "h4"
  1261. class H5(Widget):
  1262. _tagName = "h5"
  1263. class H6(Widget):
  1264. _tagName = "h6"
  1265. class Hr(Widget, _isVoid):
  1266. _tagName = "hr"
  1267. class I(Widget):
  1268. _tagName = "i"
  1269. class Kdb(Widget):
  1270. _tagName = "kdb"
  1271. class Legend(Widget):
  1272. _tagName = "legend"
  1273. class Mark(Widget):
  1274. _tagName = "mark"
  1275. class Noscript(Widget):
  1276. _tagName = "noscript"
  1277. class P(Widget):
  1278. _tagName = "p"
  1279. class Rq(Widget):
  1280. _tagName = "rq"
  1281. class Rt(Widget):
  1282. _tagName = "rt"
  1283. class Ruby(Widget):
  1284. _tagName = "ruby"
  1285. class S(Widget):
  1286. _tagName = "s"
  1287. class Samp(Widget):
  1288. _tagName = "samp"
  1289. class Section(Widget):
  1290. _tagName = "section"
  1291. class Small(Widget):
  1292. _tagName = "small"
  1293. class Strong(Widget):
  1294. _tagName = "strong"
  1295. class Sub(Widget):
  1296. _tagName = "sub"
  1297. class Summery(Widget):
  1298. _tagName = "summery"
  1299. class Sup(Widget):
  1300. _tagName = "sup"
  1301. class U(Widget):
  1302. _tagName = "u"
  1303. class Var(Widget):
  1304. _tagName = "var"
  1305. class Wbr(Widget):
  1306. _tagName = "wbr"
  1307. # Form -----------------------------------------------------------------------------------------------------------------
  1308. class Button(Widget, _attrDisabled, _attrType, _attrForm, _attrAutofocus, _attrName, _attrValue, _attrFormhead):
  1309. _tagName = "button"
  1310. class Fieldset(Widget, _attrDisabled, _attrForm, _attrName):
  1311. _tagName = "fieldset"
  1312. class Form(Widget, _attrDisabled, _attrName, _attrTarget, _attrAutocomplete):
  1313. _tagName = "form"
  1314. def _getNovalidate(self):
  1315. return True if self.element.hasAttribute("novalidate") else False
  1316. def _setNovalidate(self, val):
  1317. if val:
  1318. self.element.setAttribute("novalidate", "")
  1319. else:
  1320. self.element.removeAttribute("novalidate")
  1321. def _getAction(self):
  1322. return self.element.action
  1323. def _setAction(self, val):
  1324. self.element.action = val
  1325. def _getMethod(self):
  1326. return self.element.method
  1327. def _setMethod(self, val):
  1328. self.element.method = val
  1329. def _getEnctype(self):
  1330. return self.element.enctype
  1331. def _setEnctype(self, val):
  1332. self.element.enctype = val
  1333. def _getAccept_attrCharset(self):
  1334. return getattr(self.element, "accept-charset")
  1335. def _setAccept_attrCharset(self, val):
  1336. self.element.setAttribute("accept-charset", val)
  1337. class Input(Widget, _attrDisabled, _attrType, _attrForm, _attrAlt, _attrAutofocus, _attrChecked,
  1338. _attrIndeterminate, _attrName, _attrDimensions, _attrValue, _attrFormhead,
  1339. _attrAutocomplete, _attrInputs, _attrMultiple, _attrSize, _attrSrc, _isVoid):
  1340. _tagName = "input"
  1341. def _getAccept(self):
  1342. return self.element.accept
  1343. def _setAccept(self, val):
  1344. self.element.accept = val
  1345. def _getList(self):
  1346. return self.element.list
  1347. def _setList(self, val):
  1348. self.element.list = val
  1349. def _getMax(self):
  1350. return self.element.max
  1351. def _setMax(self, val):
  1352. self.element.max = val
  1353. def _getMin(self):
  1354. return self.element.min
  1355. def _setMin(self, val):
  1356. self.element.min = val
  1357. def _getPattern(self):
  1358. return self.element.pattern
  1359. def _setPattern(self, val):
  1360. self.element.pattern = val
  1361. def _getStep(self):
  1362. return self.element.step
  1363. def _setStep(self, val):
  1364. self.element.step = val
  1365. class Label(Widget, _attrForm, _attrFor):
  1366. _tagName = "label"
  1367. autoIdCounter = 0
  1368. def __init__(self, *args, forElem=None, **kwargs):
  1369. super().__init__(*args, **kwargs)
  1370. if forElem:
  1371. if not forElem["id"]:
  1372. idx = Label.autoIdCounter
  1373. Label.autoIdCounter += 1
  1374. forElem["id"] = "label-autoid-for-{}".format(idx)
  1375. self["for"] = forElem["id"]
  1376. class Optgroup(Widget, _attrDisabled, _attrLabel):
  1377. _tagName = "optgroup"
  1378. class Option(Widget, _attrDisabled, _attrLabel, _attrValue):
  1379. _tagName = "option"
  1380. def _getSelected(self):
  1381. return True if self.element.selected else False
  1382. def _setSelected(self, val):
  1383. if val:
  1384. self.element.selected = True
  1385. else:
  1386. self.element.selected = False
  1387. class Output(Widget, _attrForm, _attrName, _attrFor):
  1388. _tagName = "output"
  1389. class Select(Widget, _attrDisabled, _attrForm, _attrAutofocus, _attrName, _attrRequired, _attrMultiple, _attrSize):
  1390. _tagName = "select"
  1391. def _getSelectedIndex(self):
  1392. return self.element.selectedIndex
  1393. def _getOptions(self):
  1394. return self.element.options
  1395. class Textarea(Widget, _attrDisabled, _attrForm, _attrAutofocus, _attrName, _attrInputs, _attrValue):
  1396. _tagName = "textarea"
  1397. def _getCols(self):
  1398. return self.element.cols
  1399. def _setCols(self, val):
  1400. self.element.cols = val
  1401. def _getRows(self):
  1402. return self.element.rows
  1403. def _setRows(self, val):
  1404. self.element.rows = val
  1405. def _getWrap(self):
  1406. return self.element.wrap
  1407. def _setWrap(self, val):
  1408. self.element.wrap = val
  1409. # Head -----------------------------------------------------------------------------------------------------------------
  1410. class HeadCls(Widget):
  1411. def __init__(self, *args, **kwargs):
  1412. super().__init__(_wrapElem=domGetElementsByTagName("head")[0], *args, **kwargs)
  1413. self._isAttached = True
  1414. _head = None
  1415. def Head():
  1416. global _head
  1417. if _head is None:
  1418. _head = HeadCls()
  1419. return _head
  1420. # Iframe ---------------------------------------------------------------------------------------------------------------
  1421. class Iframe(Widget, _attrSrc, _attrName, _attrDimensions):
  1422. _tagName = "iframe"
  1423. def _getSandbox(self):
  1424. return self.element.sandbox
  1425. def _setSandbox(self, val):
  1426. self.element.sandbox = val
  1427. def _getSrcdoc(self):
  1428. return self.element.src
  1429. def _setSrcdoc(self, val):
  1430. self.element.src = val
  1431. def _getSeamless(self):
  1432. return True if self.element.hasAttribute("seamless") else False
  1433. def _setSeamless(self, val):
  1434. if val:
  1435. self.element.setAttribute("seamless", "")
  1436. else:
  1437. self.element.removeAttribute("seamless")
  1438. # Img ------------------------------------------------------------------------------------------------------------------
  1439. class Img(Widget, _attrSrc, _attrDimensions, _attrUsemap, _attrAlt, _isVoid):
  1440. _tagName = "img"
  1441. def __init__(self, src=None, *args, **kwargs):
  1442. super().__init__()
  1443. if src:
  1444. self["src"] = src
  1445. def _getCrossorigin(self):
  1446. return self.element.crossorigin
  1447. def _setCrossorigin(self, val):
  1448. self.element.crossorigin = val
  1449. def _getIsmap(self):
  1450. return self.element.ismap
  1451. def _setIsmap(self, val):
  1452. self.element.ismap = val
  1453. # Ins ------------------------------------------------------------------------------------------------------------------
  1454. class Ins(Widget, _attrCite, _attrDatetime):
  1455. _tagName = "ins"
  1456. # Keygen ---------------------------------------------------------------------------------------------------------------
  1457. class Keygen(Form, _attrAutofocus, _attrDisabled):
  1458. _tagName = "keygen"
  1459. def _getChallenge(self):
  1460. return True if self.element.hasAttribute("challenge") else False
  1461. def _setChallenge(self, val):
  1462. if val:
  1463. self.element.setAttribute("challenge", "")
  1464. else:
  1465. self.element.removeAttribute("challenge")
  1466. def _getKeytype(self):
  1467. return self.element.keytype
  1468. def _setKeytype(self, val):
  1469. self.element.keytype = val
  1470. # Link -----------------------------------------------------------------------------------------------------------------
  1471. class Link(Widget, _attrHref, _attrMedia, _attrRel, _isVoid):
  1472. _tagName = "link"
  1473. def _getSizes(self):
  1474. return self.element.sizes
  1475. def _setSizes(self, val):
  1476. self.element.sizes = val
  1477. # List -----------------------------------------------------------------------------------------------------------------
  1478. class Ul(Widget):
  1479. _tagName = "ul"
  1480. class Ol(Widget):
  1481. _tagName = "ol"
  1482. class Li(Widget):
  1483. _tagName = "li"
  1484. class Dl(Widget):
  1485. _tagName = "dl"
  1486. class Dt(Widget):
  1487. _tagName = "dt"
  1488. class Dd(Widget):
  1489. _tagName = "dd"
  1490. # Map ------------------------------------------------------------------------------------------------------------------
  1491. class Map(Label, _attrType):
  1492. _tagName = "map"
  1493. # Menu -----------------------------------------------------------------------------------------------------------------
  1494. class Menu(Widget):
  1495. _tagName = "menu"
  1496. # Meta -----------------------------------------------------------------------------------------------------------------
  1497. class Meta(Widget, _attrName, _attrCharset, _isVoid):
  1498. _tagName = "meta"
  1499. def _getContent(self):
  1500. return self.element.content
  1501. def _setContent(self, val):
  1502. self.element.content = val
  1503. # Meter ----------------------------------------------------------------------------------------------------------------
  1504. class Meter(Form, _attrValue):
  1505. _tagName = "meter"
  1506. def _getHigh(self):
  1507. return self.element.high
  1508. def _setHigh(self, val):
  1509. self.element.high = val
  1510. def _getLow(self):
  1511. return self.element.low
  1512. def _setLow(self, val):
  1513. self.element.low = val
  1514. def _getMax(self):
  1515. return self.element.max
  1516. def _setMax(self, val):
  1517. self.element.max = val
  1518. def _getMin(self):
  1519. return self.element.min
  1520. def _setMin(self, val):
  1521. self.element.min = val
  1522. def _getOptimum(self):
  1523. return self.element.optimum
  1524. def _setOptimum(self, val):
  1525. self.element.optimum = val
  1526. # Nav ------------------------------------------------------------------------------------------------------------------
  1527. class Nav(Widget):
  1528. _tagName = "nav"
  1529. # Object -----------------------------------------------------------------------------------------------------------------
  1530. class Object(Form, _attrType, _attrName, _attrDimensions, _attrUsemap):
  1531. _tagName = "object"
  1532. # Param -----------------------------------------------------------------------------------------------------------------
  1533. class Param(Widget, _attrName, _attrValue, _isVoid):
  1534. _tagName = "param"
  1535. # Progress -------------------------------------------------------------------------------------------------------------
  1536. class Progress(Widget, _attrValue):
  1537. _tagName = "progress"
  1538. def _getMax(self):
  1539. return self.element.max
  1540. def _setMax(self, val):
  1541. self.element.max = val
  1542. # Q --------------------------------------------------------------------------------------------------------------------
  1543. class Q(Widget, _attrCite):
  1544. _tagName = "q"
  1545. # Script ----------------------------------------------------------------------------------------------------------------
  1546. class Script(Widget, _attrSrc, _attrCharset):
  1547. _tagName = "script"
  1548. def _getAsync(self):
  1549. return True if self.element.hasAttribute("async") else False
  1550. def _setAsync(self, val):
  1551. if val:
  1552. self.element.setAttribute("async", "")
  1553. else:
  1554. self.element.removeAttribute("async")
  1555. def _getDefer(self):
  1556. return True if self.element.hasAttribute("defer") else False
  1557. def _setDefer(self, val):
  1558. if val:
  1559. self.element.setAttribute("defer", "")
  1560. else:
  1561. self.element.removeAttribute("defer")
  1562. # Source ---------------------------------------------------------------------------------------------------------------
  1563. class Source(Widget, _attrMedia, _attrSrc, _isVoid):
  1564. _tagName = "source"
  1565. # Span -----------------------------------------------------------------------------------------------------------------
  1566. class Span(Widget):
  1567. _tagName = "span"
  1568. # Style ----------------------------------------------------------------------------------------------------------------
  1569. class Style(Widget, _attrMedia):
  1570. _tagName = "style"
  1571. def _getScoped(self):
  1572. return True if self.element.hasAttribute("scoped") else False
  1573. def _setScoped(self, val):
  1574. if val:
  1575. self.element.setAttribute("scoped", "")
  1576. else:
  1577. self.element.removeAttribute("scoped")
  1578. # SVG ------------------------------------------------------------------------------------------------------------------
  1579. class Svg(Widget, _attrSvgViewBox, _attrSvgDimensions, _attrSvgTransform):
  1580. _tagName = "svg"
  1581. _namespace = "SVG"
  1582. def _getVersion(self):
  1583. return self.element.version
  1584. def _setVersion(self, val):
  1585. self.element.setAttribute("version", val)
  1586. def _getXmlns(self):
  1587. return self.element.xmlns
  1588. def _setXmlns(self, val):
  1589. self.element.setAttribute("xmlns", val)
  1590. class SvgCircle(Widget, _attrSvgTransform, _attrSvgDimensions):
  1591. _tagName = "circle"
  1592. _namespace = "SVG"
  1593. class SvgEllipse(Widget, _attrSvgTransform, _attrSvgDimensions):
  1594. _tagName = "ellipse"
  1595. _namespace = "SVG"
  1596. class SvgG(Widget, _attrSvgTransform, _attrSvgStyles):
  1597. _tagName = "g"
  1598. _namespace = "SVG"
  1599. def _getSvgTransform(self):
  1600. return self.element.transform
  1601. def _setSvgTransform(self, val):
  1602. self.element.setAttribute("transform", val)
  1603. class SvgImage(Widget, _attrSvgViewBox, _attrSvgDimensions, _attrSvgTransform, _attrSvgXlink):
  1604. _tagName = "image"
  1605. _namespace = "SVG"
  1606. class SvgLine(Widget, _attrSvgTransform, _attrSvgPoints):
  1607. _tagName = "line"
  1608. _namespace = "SVG"
  1609. class SvgPath(Widget, _attrSvgTransform):
  1610. _tagName = "path"
  1611. _namespace = "SVG"
  1612. def _getD(self):
  1613. return self.element.d
  1614. def _setD(self, val):
  1615. self.element.setAttribute("d", val)
  1616. def _getPathLength(self):
  1617. return self.element.pathLength
  1618. def _setPathLength(self, val):
  1619. self.element.setAttribute("pathLength", val)
  1620. class SvgPolygon(Widget, _attrSvgTransform, _attrSvgPoints):
  1621. _tagName = "polygon"
  1622. _namespace = "SVG"
  1623. class SvgPolyline(Widget, _attrSvgTransform, _attrSvgPoints):
  1624. _tagName = "polyline"
  1625. _namespace = "SVG"
  1626. class SvgRect(Widget, _attrSvgDimensions, _attrSvgTransform, _attrSvgStyles):
  1627. _tagName = "rect"
  1628. _namespace = "SVG"
  1629. class SvgText(Widget, _attrSvgDimensions, _attrSvgTransform, _attrSvgStyles):
  1630. _tagName = "text"
  1631. _namespace = "SVG"
  1632. # Table ----------------------------------------------------------------------------------------------------------------
  1633. class Tr(Widget):
  1634. _tagName = "tr"
  1635. def _getRowspan(self):
  1636. span = self.element.getAttribute("rowspan")
  1637. return span if span else 1
  1638. def _setRowspan(self, span):
  1639. assert span >= 1, "span may not be negative"
  1640. self.element.setAttribute("rowspan", span)
  1641. return self
  1642. class Td(Widget):
  1643. _tagName = "td"
  1644. def _getColspan(self):
  1645. span = self.element.getAttribute("colspan")
  1646. return span if span else 1
  1647. def _setColspan(self, span):
  1648. assert span >= 1, "span may not be negative"
  1649. self.element.setAttribute("colspan", span)
  1650. return self
  1651. def _getRowspan(self):
  1652. span = self.element.getAttribute("rowspan")
  1653. return span if span else 1
  1654. def _setRowspan(self, span):
  1655. assert span >= 1, "span may not be negative"
  1656. self.element.setAttribute("rowspan", span)
  1657. return self
  1658. class Th(Td):
  1659. _tagName = "th"
  1660. class Thead(Widget):
  1661. _tagName = "thead"
  1662. class Tbody(Widget):
  1663. _tagName = "tbody"
  1664. class ColWrapper(object):
  1665. def __init__(self, parentElem, *args, **kwargs):
  1666. super().__init__(*args, **kwargs)
  1667. self.parentElem = parentElem
  1668. def __getitem__(self, item):
  1669. assert isinstance(item, int), "Invalid col-number. Expected int, got {}".format(str(type(item)))
  1670. if item < 0 or item > len(self.parentElem._children):
  1671. return None
  1672. return self.parentElem._children[item]
  1673. def __setitem__(self, key, value):
  1674. col = self[key]
  1675. assert col is not None, "Cannot assign widget to invalid column"
  1676. col.removeAllChildren()
  1677. if isinstance(value, list) or isinstance(value, tuple):
  1678. for el in value:
  1679. if isinstance(el, Widget) or isinstance(el, TextNode):
  1680. col.appendChild(value)
  1681. elif isinstance(value, Widget) or isinstance(value, TextNode):
  1682. col.appendChild(value)
  1683. class RowWrapper(object):
  1684. def __init__(self, parentElem, *args, **kwargs):
  1685. super().__init__(*args, **kwargs)
  1686. self.parentElem = parentElem
  1687. def __getitem__(self, item):
  1688. assert isinstance(item, int), "Invalid row-number. Expected int, got {}".format(str(type(item)))
  1689. if item < 0 or item > len(self.parentElem._children):
  1690. return None
  1691. return ColWrapper(self.parentElem._children[item])
  1692. class Table(Widget):
  1693. _tagName = "table"
  1694. def __init__(self, *args, **kwargs):
  1695. super().__init__(*args, **kwargs)
  1696. self.head = Thead()
  1697. self.body = Tbody()
  1698. self.appendChild(self.head)
  1699. self.appendChild(self.body)
  1700. def prepareRow(self, row):
  1701. assert row >= 0, "Cannot create rows with negative index"
  1702. for child in self.body._children:
  1703. row -= child["rowspan"]
  1704. if row < 0:
  1705. return
  1706. while row >= 0:
  1707. self.body.appendChild(Tr())
  1708. row -= 1
  1709. def prepareCol(self, row, col):
  1710. assert col >= 0, "Cannot create cols with negative index"
  1711. self.prepareRow(row)
  1712. for rowChild in self.body._children:
  1713. row -= rowChild["rowspan"]
  1714. if row < 0:
  1715. for colChild in rowChild._children:
  1716. col -= colChild["colspan"]
  1717. if col < 0:
  1718. return
  1719. while col >= 0:
  1720. rowChild.appendChild(Td())
  1721. col -= 1
  1722. return
  1723. def prepareGrid(self, rows, cols):
  1724. for row in range(self.getRowCount(), self.getRowCount() + rows):
  1725. self.prepareCol(row, cols)
  1726. def clear(self):
  1727. for row in self.body._children[:]:
  1728. for col in row._children[:]:
  1729. row.removeChild(col)
  1730. self.body.removeChild(row)
  1731. def _getCell(self):
  1732. return RowWrapper(self.body)
  1733. def getRowCount(self):
  1734. cnt = 0
  1735. for tr in self.body._children:
  1736. cnt += tr["rowspan"]
  1737. return cnt
  1738. # Time -----------------------------------------------------------------------------------------------------------------
  1739. class Time(Widget, _attrDatetime):
  1740. _tagName = "time"
  1741. # Track ----------------------------------------------------------------------------------------------------------------
  1742. class Track(Label, _attrSrc, _isVoid):
  1743. _tagName = "track"
  1744. def _getKind(self):
  1745. return self.element.kind
  1746. def _setKind(self, val):
  1747. self.element.kind = val
  1748. def _getSrclang(self):
  1749. return self.element.srclang
  1750. def _setSrclang(self, val):
  1751. self.element.srclang = val
  1752. def _getDefault(self):
  1753. return True if self.element.hasAttribute("default") else False
  1754. def _setDefault(self, val):
  1755. if val:
  1756. self.element.setAttribute("default", "")
  1757. else:
  1758. self.element.removeAttribute("default")
  1759. # Video ----------------------------------------------------------------------------------------------------------------
  1760. class Video(Widget, _attrSrc, _attrDimensions, _attrMultimedia):
  1761. _tagName = "video"
  1762. def _getPoster(self):
  1763. return self.element.poster
  1764. def _setPoster(self, val):
  1765. self.element.poster = val
  1766. ########################################################################################################################
  1767. # Utilities
  1768. ########################################################################################################################
  1769. def unescape(val, maxLength=0):
  1770. """
  1771. Unquotes several HTML-quoted characters in a string.
  1772. :param val: The value to be unescaped.
  1773. :type val: str
  1774. :param maxLength: Cut-off after maxLength characters.
  1775. A value of 0 means "unlimited". (default)
  1776. :type maxLength: int
  1777. :returns: The unquoted string.
  1778. :rtype: str
  1779. """
  1780. val = val \
  1781. .replace("&lt;", "<") \
  1782. .replace("&gt;", ">") \
  1783. .replace("&quot;", "\"") \
  1784. .replace("&#39;", "'")
  1785. if maxLength > 0:
  1786. return val[0:maxLength]
  1787. return val
  1788. def doesEventHitWidgetOrParents(event, widget):
  1789. """
  1790. Test if event 'event' hits widget 'widget' (or *any* of its parents)
  1791. """
  1792. while widget:
  1793. if event.target == widget.element:
  1794. return True
  1795. widget = widget.parent()
  1796. return False
  1797. def doesEventHitWidgetOrChildren(event, widget):
  1798. """
  1799. Test if event 'event' hits widget 'widget' (or *any* of its children)
  1800. """
  1801. if event.target == widget.element:
  1802. return True
  1803. for child in widget._children:
  1804. if doesEventHitWidgetOrChildren(event, child):
  1805. return True
  1806. return False
  1807. def textToHtml(node, text):
  1808. """
  1809. Generates html nodes from text by splitting text into content and into
  1810. line breaks html5.Br.
  1811. :param node: The node where the nodes are appended to.
  1812. :param text: The text to be inserted.
  1813. """
  1814. for (i, part) in enumerate(text.split("\n")):
  1815. if i > 0:
  1816. node.appendChild(Br())
  1817. node.appendChild(TextNode(part))
  1818. def parseInt(s, ret=0):
  1819. """
  1820. Parses a value as int
  1821. """
  1822. if not isinstance(s, str):
  1823. return int(s)
  1824. elif s:
  1825. if s[0] in "+-":
  1826. ts = s[1:]
  1827. else:
  1828. ts = s
  1829. if ts and all([_ in "0123456789" for _ in ts]):
  1830. return int(s)
  1831. return ret
  1832. def parseFloat(s, ret=0.0):
  1833. """
  1834. Parses a value as float.
  1835. """
  1836. if not isinstance(s, str):
  1837. return float(s)
  1838. elif s:
  1839. if s[0] in "+-":
  1840. ts = s[1:]
  1841. else:
  1842. ts = s
  1843. if ts and ts.count(".") <= 1 and all([_ in ".0123456789" for _ in ts]):
  1844. return float(s)
  1845. return ret
  1846. ########################################################################################################################
  1847. # Keycodes
  1848. ########################################################################################################################
  1849. def getKey(event):
  1850. """
  1851. Returns the Key Identifier of the given event
  1852. Available Codes: https://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/keyset.html#KeySet-Set
  1853. """
  1854. if hasattr(event, "key"):
  1855. return event.key
  1856. elif hasattr(event, "keyIdentifier"):
  1857. if event.keyIdentifier in ["Esc", "U+001B"]:
  1858. return "Escape"
  1859. else:
  1860. return event.keyIdentifier
  1861. return None
  1862. def isArrowLeft(event):
  1863. return getKey(event) in ["ArrowLeft", "Left"]
  1864. def isArrowUp(event):
  1865. return getKey(event) in ["ArrowUp", "Up"]
  1866. def isArrowRight(event):
  1867. return getKey(event) in ["ArrowRight", "Right"]
  1868. def isArrowDown(event):
  1869. return getKey(event) in ["ArrowDown", "Down"]
  1870. def isEscape(event):
  1871. return getKey(event) == "Escape"
  1872. def isReturn(event):
  1873. return getKey(event) == "Enter"
  1874. def isControl(event): # The Control (Ctrl) key.
  1875. return getKey(event) == "Control"
  1876. def isShift(event):
  1877. return getKey(event) == "Shift"
  1878. ########################################################################################################################
  1879. # HTML parser
  1880. ########################################################################################################################
  1881. # Global variables required by HTML parser
  1882. __tags = None
  1883. __domParser = None
  1884. def registerTag(tagName, widgetClass, override=True):
  1885. assert issubclass(widgetClass, Widget), "widgetClass must be a sub-class of Widget!"
  1886. global __tags
  1887. if __tags is None:
  1888. _buildTags()
  1889. if not override and tagName.lower() in __tags:
  1890. return
  1891. attr = []
  1892. for fname in dir(widgetClass):
  1893. if fname.startswith("_set"):
  1894. attr.append(fname[4:].lower())
  1895. __tags[tagName.lower()] = (widgetClass, attr)
  1896. def tag(cls):
  1897. assert issubclass(cls, Widget)
  1898. registerTag(cls._parserTagName or cls.__name__, cls) # do NOT check for cls._tagName here!!!
  1899. return cls
  1900. def _buildTags(debug=False):
  1901. """
  1902. Generates a dictionary of all to the html5-library
  1903. known tags and their associated objects and attributes.
  1904. """
  1905. global __tags
  1906. if __tags is not None:
  1907. return
  1908. if __tags is None:
  1909. __tags = {}
  1910. for cname in globals().keys():
  1911. if cname.startswith("_"):
  1912. continue
  1913. cls = globals()[cname]
  1914. try:
  1915. if not issubclass(cls, Widget):
  1916. continue
  1917. except:
  1918. continue
  1919. registerTag(cls._parserTagName or cls._tagName or cls.__name__, cls, override=False)
  1920. if debug:
  1921. for tag in sorted(__tags.keys()):
  1922. print("{}: {}".format(tag, ", ".join(sorted(__tags[tag][1]))))
  1923. class HtmlAst(list):
  1924. pass
  1925. def parseHTML(html, debug=False):
  1926. """
  1927. Parses the provided HTML-code according to the objects defined in the html5-library.
  1928. """
  1929. def convertEncodedText(txt):
  1930. """
  1931. Convert HTML-encoded text into decoded string.
  1932. The reason for this function is the handling of HTML entities, which is not
  1933. properly supported by native JavaScript.
  1934. We use the browser's DOM parser to to this, according to
  1935. https://stackoverflow.com/questions/3700326/decode-amp-back-to-in-javascript
  1936. :param txt: The encoded text.
  1937. :return: The decoded text.
  1938. """
  1939. global __domParser
  1940. if jseval is None:
  1941. return txt
  1942. if __domParser is None:
  1943. __domParser = jseval("new DOMParser")
  1944. dom = __domParser.parseFromString("<!doctype html><body>" + str(txt), "text/html")
  1945. return dom.body.textContent
  1946. def scanWhite(l):
  1947. """
  1948. Scan and return whitespace.
  1949. """
  1950. ret = ""
  1951. while l and l[0] in " \t\r\n":
  1952. ret += l.pop(0)
  1953. return ret
  1954. def scanWord(l):
  1955. """
  1956. Scan and return a word.
  1957. """
  1958. ret = ""
  1959. while l and l[0] not in " \t\r\n" + "<>=\"'":
  1960. ret += l.pop(0)
  1961. return ret
  1962. stack = []
  1963. # Obtain tag descriptions, if not already done!
  1964. global __tags
  1965. if __tags is None:
  1966. _buildTags(debug=debug)
  1967. # Prepare stack and input
  1968. stack.append((None, None, HtmlAst()))
  1969. html = [ch for ch in html]
  1970. # Parse
  1971. while html:
  1972. tag = None
  1973. text = ""
  1974. # Auto-close void elements (_isVoid), e.g. <hr>, <br>, etc.
  1975. while stack and stack[-1][0] and issubclass(__tags[stack[-1][0]][0], _isVoid):
  1976. stack.pop()
  1977. if not stack:
  1978. break
  1979. parent = stack[-1][2]
  1980. while html:
  1981. ch = html.pop(0)
  1982. # Comment
  1983. if html and ch == "<" and "".join(html[:3]) == "!--":
  1984. html = html[3:]
  1985. while html and "".join(html[:3]) != "-->":
  1986. html.pop(0)
  1987. html = html[3:]
  1988. # Opening tag
  1989. elif html and ch == "<" and html[0] != "/":
  1990. tag = scanWord(html)
  1991. if tag.lower() in __tags:
  1992. break
  1993. text += ch + tag
  1994. # Closing tag
  1995. elif html and stack[-1][0] and ch == "<" and html[0] == "/":
  1996. junk = ch
  1997. junk += html.pop(0)
  1998. tag = scanWord(html)
  1999. junk += tag
  2000. if stack[-1][0] == tag.lower():
  2001. junk += scanWhite(html)
  2002. if html and html[0] == ">":
  2003. html.pop(0)
  2004. stack.pop()
  2005. tag = None
  2006. break
  2007. text += junk
  2008. tag = None
  2009. else:
  2010. text += ch
  2011. # Append plain text (if not only whitespace)
  2012. if (text and ((len(text) == 1 and text in ["\t "])
  2013. or not all([ch in " \t\r\n" for ch in text]))):
  2014. # print("text", text)
  2015. parent.append(convertEncodedText(text))
  2016. # Create tag
  2017. if tag:
  2018. tag = tag.lower()
  2019. # print("tag", tag)
  2020. elem = (tag, {}, HtmlAst())
  2021. stack.append(elem)
  2022. parent.append(elem)
  2023. while html:
  2024. scanWhite(html)
  2025. if not html:
  2026. break
  2027. # End of tag >
  2028. if html[0] == ">":
  2029. html.pop(0)
  2030. break
  2031. # Closing tag at end />
  2032. elif html[0] == "/":
  2033. html.pop(0)
  2034. scanWhite(html)
  2035. if html[0] == ">":
  2036. stack.pop()
  2037. html.pop(0)
  2038. break
  2039. val = att = scanWord(html).lower()
  2040. if not att:
  2041. html.pop(0)
  2042. continue
  2043. if att in __tags[tag][1] or att in ["[name]", "style", "disabled", "hidden"] or att.startswith("data-"):
  2044. scanWhite(html)
  2045. if html[0] == "=":
  2046. html.pop(0)
  2047. scanWhite(html)
  2048. if html[0] in "\"'":
  2049. ch = html.pop(0)
  2050. val = ""
  2051. while html and html[0] != ch:
  2052. val += html.pop(0)
  2053. html.pop(0)
  2054. if att not in elem[1]:
  2055. elem[1][att] = val
  2056. else:
  2057. elem[1][att] += " " + val
  2058. continue
  2059. while stack and stack[-1][0]:
  2060. stack.pop()
  2061. return stack[0][2]
  2062. def fromHTML(html, appendTo=None, bindTo=None, debug=False, vars=None, **kwargs):
  2063. """
  2064. Parses the provided HTML code according to the objects defined in the html5-library.
  2065. html can also be pre-compiled by `parseHTML()` so that it executes faster.
  2066. Constructs all objects as DOM nodes. The first level is chained into appendTo.
  2067. If no appendTo is provided, appendTo will be set to html5.Body().
  2068. If bindTo is provided, objects are bound to this widget.
  2069. ```python
  2070. from vi import html5
  2071. div = html5.Div()
  2072. html5.parse.fromHTML('''
  2073. <div>Yeah!
  2074. <a href="hello world" [name]="myLink" class="trullman bernd" disabled>
  2075. hah ala malla" bababtschga"
  2076. <img src="/static/images/icon_home.svg" style="background-color: red;"/>st
  2077. <em>ah</em>ralla <i>malla tralla</i> da
  2078. </a>lala
  2079. </div>''', div)
  2080. div.myLink.appendChild("appended!")
  2081. ```
  2082. """
  2083. # Handle defaults
  2084. if bindTo is None:
  2085. bindTo = appendTo
  2086. if isinstance(html, str):
  2087. html = parseHTML(html, debug=debug)
  2088. assert isinstance(html, HtmlAst)
  2089. if isinstance(vars, dict):
  2090. kwargs.update(vars)
  2091. def replaceVars(txt):
  2092. for var, val in kwargs.items():
  2093. txt = txt.replace("{{%s}}" % var, str(val) if val is not None else "")
  2094. return txt
  2095. def interpret(parent, items):
  2096. ret = []
  2097. for item in items:
  2098. if isinstance(item, str):
  2099. txt = TextNode(replaceVars(item))
  2100. if parent:
  2101. parent.appendChild(txt)
  2102. ret.append(txt)
  2103. continue
  2104. tag = item[0]
  2105. atts = item[1]
  2106. children = item[2]
  2107. # Special handling for tables: A "thead" and "tbody" are already part of table!
  2108. if tag in ["thead", "tbody"] and isinstance(parent, Table):
  2109. wdg = getattr(parent, tag[1:])
  2110. # Usual way: Construct new element and chain it into the parent.
  2111. else:
  2112. wdg = __tags[tag][0]()
  2113. for att, val in atts.items():
  2114. val = replaceVars(val)
  2115. if att == "[name]":
  2116. # Allow disable binding!
  2117. if not bindTo:
  2118. continue
  2119. if getattr(bindTo, val, None):
  2120. print("Cannot assign name '{}' because it already exists in {}".format(val, bindTo))
  2121. elif not (any([val.startswith(x) for x in
  2122. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "_"])
  2123. and all(
  2124. [x in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789" + "_"
  2125. for x in val[1:]])):
  2126. print("Cannot assign name '{}' because it contains invalid characters".format(val))
  2127. else:
  2128. setattr(bindTo, val, wdg)
  2129. wdg.onBind(bindTo, val)
  2130. if debug:
  2131. print("name '{}' assigned to {}".format(val, bindTo))
  2132. elif att == "class":
  2133. # print(tag, att, val.split())
  2134. wdg.addClass(*val.split())
  2135. elif att == "disabled":
  2136. # print(tag, att, val)
  2137. if val == "disabled":
  2138. wdg.disable()
  2139. elif att == "hidden":
  2140. # print(tag, att, val)
  2141. if val == "hidden":
  2142. wdg.hide()
  2143. elif att == "style":
  2144. for dfn in val.split(";"):
  2145. if ":" not in dfn:
  2146. continue
  2147. att, val = dfn.split(":", 1)
  2148. # print(tag, "style", att.strip(), val.strip())
  2149. wdg["style"][att.strip()] = val.strip()
  2150. elif att.startswith("data-"):
  2151. wdg["data"][att[5:]] = val
  2152. else:
  2153. wdg[att] = parseInt(val, val)
  2154. interpret(wdg, children)
  2155. if parent and not wdg.parent():
  2156. parent.appendChild(wdg)
  2157. ret.append(wdg)
  2158. return ret
  2159. return interpret(appendTo, html)
  2160. if __name__ == '__main__':
  2161. print(globals())