pax_global_header00006660000000000000000000000064145217711020014512gustar00rootroot0000000000000052 comment=4a667566c053efb143bf4938d9568ba6f17552df dominate-2.9.0/000077500000000000000000000000001452177110200133225ustar00rootroot00000000000000dominate-2.9.0/.github/000077500000000000000000000000001452177110200146625ustar00rootroot00000000000000dominate-2.9.0/.github/workflows/000077500000000000000000000000001452177110200167175ustar00rootroot00000000000000dominate-2.9.0/.github/workflows/.coveragerc000066400000000000000000000000341452177110200210350ustar00rootroot00000000000000[run] relative_files = True dominate-2.9.0/.github/workflows/ci.yml000066400000000000000000000040451452177110200200400ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python name: Dominate on: push: branches: ["master"] pull_request: branches: ["master"] jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: python: ["3"] os: ["ubuntu-latest"] include: - {python: "3.7", os: "ubuntu-22.04"} - {python: "3.8", os: "ubuntu-22.04"} - {python: "3.9", os: "ubuntu-22.04"} - {python: "3.10", os: "ubuntu-22.04"} - {python: "3.11", os: "ubuntu-22.04"} - {python: "3.12", os: "ubuntu-22.04"} steps: - uses: actions/checkout@v3 - name: "Set up Python ${{ matrix.python }}" uses: actions/setup-python@v3 with: python-version: ${{ matrix.python }} - name: "Install dependencies" run: | # python -m pip install --upgrade pip python -m pip install pytest python -m pip install mock python -m pip install flake8 python -m pip install importlib_metadata python -m pip install "setuptools>=62" python -m pip install wheel python -m pip install build - name: "Lint with flake8" run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics flake8 . --count --exit-zero --max-complexity=10 --max-line-length=80 --statistics - name: "Build and test" run: | python -m build --no-isolation pip install dist/dominate*.tar.gz pytest - name: Coveralls env: COVERAGE_RCFILE: ".github/workflows/.coveragerc" GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | python -m pip install coverage python -m pip install coveralls coverage run --source=dominate -m pytest python -m coveralls --service=github || true dominate-2.9.0/.gitignore000066400000000000000000000005571452177110200153210ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 __pycache__ # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject *.sublime-workspace *.sublime-project .idea .idea/ dominate-2.9.0/LICENSE.txt000066400000000000000000000167251452177110200151600ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. dominate-2.9.0/MANIFEST.in000066400000000000000000000002361452177110200150610ustar00rootroot00000000000000include README.md include LICENSE.txt include pyproject.toml include setup/setup.py recursive-include tests * global-exclude __pycache__ global-exclude *.pyc dominate-2.9.0/Makefile000066400000000000000000000004731452177110200147660ustar00rootroot00000000000000test: -python2 -m pytest . python3 -m pytest . publish_old: clean test python3 setup/setup.py sdist python3 setup/setup.py bdist_wheel python3 -m twine upload dist/* publish: clean test python3 -m build --no-isolation python3 -m twine upload dist/* clean: -rm dist/ -r -rm build/ -r -rm *.egg-info/ -r dominate-2.9.0/README.md000066400000000000000000000300531452177110200146020ustar00rootroot00000000000000Dominate ======== `Dominate` is a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminates the need to learn another template language, and lets you take advantage of the more powerful features of Python. ![Python version](https://img.shields.io/pypi/pyversions/dominate.svg?style=flat) [![Build status](https://github.com/Knio/dominate/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/Knio/dominate/actions/workflows/ci.yml?query=branch%3Amaster+) [![Coverage status](https://img.shields.io/coveralls/github/Knio/dominate/master.svg?style=flat)](https://coveralls.io/r/Knio/dominate?branch=master) Python: ```python import dominate from dominate.tags import * doc = dominate.document(title='Dominate your HTML') with doc.head: link(rel='stylesheet', href='style.css') script(type='text/javascript', src='script.js') with doc: with div(id='header').add(ol()): for i in ['home', 'about', 'contact']: li(a(i.title(), href='/%s.html' % i)) with div(): attr(cls='body') p('Lorem ipsum..') print(doc) ``` Output: ```html Dominate your HTML

Lorem ipsum..

``` Installation ------------ The recommended way to install `dominate` is with [`pip`](http://pypi.python.org/pypi/pip/): pip install dominate [![PyPI version](https://img.shields.io/pypi/v/dominate.svg?style=flat)](https://pypi.org/project/dominate/) [![PyPI downloads](https://img.shields.io/pypi/dm/dominate.svg?style=flat)](https://pypi.org/project/dominate/) Developed By ------------ * Tom Flanagan - * Jake Wharton - * [Brad Janke](//github.com/bradj) Git repository located at [github.com/Knio/dominate](//github.com/Knio/dominate) Examples ======== All examples assume you have imported the appropriate tags or entire tag set: ```python from dominate.tags import * ``` Hello, World! ------------- The most basic feature of `dominate` exposes a class for each HTML element, where the constructor accepts child elements, text, or keyword attributes. `dominate` nodes return their HTML representation from the `__str__`, `__unicode__`, and `render()` methods. ```python print(html(body(h1('Hello, World!')))) ``` ```html

Hello, World!

``` Attributes ---------- `Dominate` can also use keyword arguments to append attributes onto your tags. Most of the attributes are a direct copy from the HTML spec with a few variations. For attributes `class` and `for` which conflict with Python's [reserved keywords](http://docs.python.org/2/reference/lexical_analysis.html#keywords "Reserved Keywords"), you can use the following aliases: | class | for | |-------|-----| |_class | _for | |cls | fr | |className|htmlFor| |class_name|html_for| ```python test = label(cls='classname anothername', fr='someinput') print(test) ``` ```html ``` Use `data_*` for [custom HTML5 data attributes](http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes "HTML5 Data Attributes"). ```python test = div(data_employee='101011') print(test) ``` ```html
``` You can also modify the attributes of tags through a dictionary-like interface: ```python header = div() header['id'] = 'header' print(header) ``` ```html ``` Complex Structures ------------------ Through the use of the `+=` operator and the `.add()` method you can easily create more advanced structures. Create a simple list: ```python list = ul() for item in range(4): list += li('Item #', item) print(list) ``` ```html
  • Item #0
  • Item #1
  • Item #2
  • Item #3
``` `dominate` supports iterables to help streamline your code: ```python print(ul(li(a(name, href=link), __pretty=False) for name, link in menu_items)) ``` ```html ``` A simple document tree: ```python _html = html() _body = _html.add(body()) header = _body.add(div(id='header')) content = _body.add(div(id='content')) footer = _body.add(div(id='footer')) print(_html) ``` ```html
``` For clean code, the `.add()` method returns children in tuples. The above example can be cleaned up and expanded like this: ```python _html = html() _head, _body = _html.add(head(title('Simple Document Tree')), body()) names = ['header', 'content', 'footer'] header, content, footer = _body.add([div(id=name) for name in names]) print(_html) ``` ```html Simple Document Tree
``` You can modify the attributes of tags through a dictionary-like interface: ```python header = div() header['id'] = 'header' print(header) ``` ```html ``` Or the children of a tag though an array-line interface: ```python header = div('Test') header[0] = 'Hello World' print(header) ``` ```html
Hello World
``` Comments can be created using objects too! ```python print(comment('BEGIN HEADER')) ``` ```html ``` ```python print(comment(p('Upgrade to newer IE!'), condition='lt IE9')) ``` ```html ``` Rendering --------- By default, `render()` tries to make all output human readable, with one HTML element per line and two spaces of indentation. This behavior can be controlled by the `__pretty` (default: `True` except for certain element types like `pre`) attribute when creating an element, and by the `pretty` (default: `True`), `indent` (default: ` `) and `xhtml` (default: `False`) arguments to `render()`. Rendering options propagate to all descendant nodes. ```python a = div(span('Hello World')) print(a.render()) ``` ```html
Hello World
``` ```python print(a.render(pretty=False)) ``` ```html
Hello World
``` ```python print(a.render(indent='\t')) ``` ```html
Hello World
``` ```python a = div(span('Hello World'), __pretty=False) print(a.render()) ``` ```html
Hello World
``` ```python d = div() with d: hr() p("Test") br() print(d.render()) print(d.render(xhtml=True)) ``` ```html

Test



Test


``` Context Managers ---------------- You can also add child elements using Python's `with` statement: ```python h = ul() with h: li('One') li('Two') li('Three') print(h) ``` ```html
  • One
  • Two
  • Three
``` You can use this along with the other mechanisms of adding children elements, including nesting `with` statements, and it works as expected: ```python h = html() with h.add(body()).add(div(id='content')): h1('Hello World!') p('Lorem ipsum ...') with table().add(tbody()): l = tr() l += td('One') l.add(td('Two')) with l: td('Three') print(h) ``` ```html

Hello World!

Lorem ipsum ...

One Two Three
``` When the context is closed, any nodes that were not already added to something get added to the current context. Attributes can be added to the current context with the `attr` function: ```python d = div() with d: attr(id='header') print(d) ``` ```html ``` And text nodes can be added with the `dominate.util.text` function: ```python from dominate.util import text para = p(__pretty=False) with para: text('Have a look at our ') a('other products', href='/products') print(para) ``` ```html

Have a look at our other products

``` Decorators ---------- `Dominate` is great for creating reusable widgets for parts of your page. Consider this example: ```python def greeting(name): with div() as d: p('Hello, %s' % name) return d print(greeting('Bob')) ``` ```html

Hello, Bob

``` You can see the following pattern being repeated here: ```python def widget(parameters): with tag() as t: ... return t ``` This boilerplate can be avoided by using tags (objects and instances) as decorators ```python @div def greeting(name): p('Hello %s' % name) print(greeting('Bob')) ``` ```html

Hello Bob

``` The decorated function will return a new instance of the tag used to decorate it, and execute in a `with` context which will collect all the nodes created inside it. You can also use instances of tags as decorators, if you need to add attributes or other data to the root node of the widget. Each call to the decorated function will return a copy of the node used to decorate it. ```python @div(h2('Welcome'), cls='greeting') def greeting(name): p('Hello %s' % name) print(greeting('Bob')) ``` ```html

Welcome

Hello Bob

``` Creating Documents ------------------ Since creating the common structure of an HTML document everytime would be excessively tedious dominate provides a class to create and manage them for you: `document`. When you create a new document, the basic HTML tag structure is created for you. ```python d = document() print(d) ``` ```html Dominate ``` The `document` class accepts `title`, `doctype`, and `request` keyword arguments. The default values for these arguments are `Dominate`, ``, and `None` respectively. The `document` class also provides helpers to allow you to access the `title`, `head`, and `body` nodes directly. ```python d = document() ``` ```python >>> d.head >>> d.body >>> d.title u'Dominate' ``` The `document` class also provides helpers to allow you to directly add nodes to the `body` tag. ```python d = document() d += h1('Hello, World!') d += p('This is a paragraph.') print(d) ``` ```html Dominate

Hello, World!

This is a paragraph.

``` Embedding HTML -------------- If you need to embed a node of pre-formed HTML coming from a library such as markdown or the like, you can avoid escaped HTML by using the raw method from the dominate.util package: ``` from dominate.util import raw ... td(raw('Example')) ``` Without the raw call, this code would render escaped HTML with lt, etc. SVG --- The `dominate.svg` module contains SVG tags similar to how `dominate.tags` contains HTML tags. SVG elements will automatically convert `_` to `-` for dashed elements. For example: ```python from dominate.svg import * print(circle(stroke_width=5)) ``` ```html ``` dominate-2.9.0/conftest.py000066400000000000000000000001571452177110200155240ustar00rootroot00000000000000# used by pytest to test against the local copy of dominate # (this file is important even though it is empty) dominate-2.9.0/dominate/000077500000000000000000000000001452177110200151225ustar00rootroot00000000000000dominate-2.9.0/dominate/__init__.py000066400000000000000000000001301452177110200172250ustar00rootroot00000000000000from ._version import __version__ version = __version__ from .document import document dominate-2.9.0/dominate/_version.py000066400000000000000000000000261452177110200173160ustar00rootroot00000000000000__version__ = '2.9.0' dominate-2.9.0/dominate/document.py000066400000000000000000000043031452177110200173120ustar00rootroot00000000000000__license__ = ''' This file is part of Dominate. Dominate is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dominate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Dominate. If not, see . ''' from . import tags from . import util try: basestring = basestring except NameError: # py3 basestring = str unicode = str class document(tags.html): tagname = 'html' def __init__(self, title='Dominate', doctype='', *a, **kw): ''' Creates a new document instance. Accepts `title` and `doctype` ''' super(document, self).__init__(*a, **kw) self.doctype = doctype self.head = super(document, self).add(tags.head()) self.body = super(document, self).add(tags.body()) if title is not None: self.title_node = self.head.add(tags.title(title)) with self.body: self.header = util.container() self.main = util.container() self.footer = util.container() self._entry = self.main def get_title(self): return self.title_node.text def set_title(self, title): if isinstance(title, basestring): self.title_node.text = title else: self.head.remove(self.title_node) self.head.add(title) self.title_node = title title = property(get_title, set_title) def add(self, *args): ''' Adding tags to a document appends them to the . ''' return self._entry.add(*args) def _render(self, sb, *args, **kwargs): ''' Renders the DOCTYPE and tag tree. ''' # adds the doctype if one was set if self.doctype: sb.append(self.doctype) sb.append('\n') return super(document, self)._render(sb, *args, **kwargs) def __repr__(self): return '' % self.title dominate-2.9.0/dominate/dom1core.py000066400000000000000000000033061452177110200172070ustar00rootroot00000000000000__license__ = ''' This file is part of Dominate. Dominate is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dominate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Dominate. If not, see . ''' try: basestring = basestring except NameError: # py3 basestring = str unicode = str class dom1core(object): ''' Implements the Document Object Model (Core) Level 1 http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/ http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html ''' @property def parentNode(self): ''' DOM API: Returns the parent tag of the current element. ''' return self.parent def getElementById(self, id): ''' DOM API: Returns single element with matching id value. ''' results = self.get(id=id) if len(results) > 1: raise ValueError('Multiple tags with id "%s".' % id) elif results: return results[0] return None def getElementsByTagName(self, name): ''' DOM API: Returns all tags that match name. ''' if isinstance(name, basestring): return self.get(name.lower()) return None def appendChild(self, obj): ''' DOM API: Add an item to the end of the children list. ''' self.add(obj) return self dominate-2.9.0/dominate/dom_tag.py000066400000000000000000000306401452177110200171110ustar00rootroot00000000000000__license__ = ''' This file is part of Dominate. Dominate is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dominate is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Dominate. If not, see . ''' # pylint: disable=bad-indentation, bad-whitespace, missing-docstring import copy import numbers from collections import defaultdict, namedtuple from functools import wraps import threading try: # Python 3 from collections.abc import Callable except ImportError: # pragma: no cover # Python 2.7 from collections import Callable try: basestring = basestring except NameError: # py3 # pragma: no cover basestring = str unicode = str try: import greenlet except ImportError: greenlet = None def _get_thread_context(): context = [threading.current_thread()] if greenlet: context.append(greenlet.getcurrent()) return hash(tuple(context)) class dom_tag(object): is_single = False # Tag does not require matching end tag (ex.
) is_pretty = True # Text inside the tag should be left as-is (ex.
)
                     # otherwise, text will be escaped() and whitespace may be
                     # modified
  is_inline = False


  def __new__(_cls, *args, **kwargs):
    '''
    Check if bare tag is being used a a decorator
    (called with a single function arg).
    decorate the function and return
    '''
    if len(args) == 1 and isinstance(args[0], Callable) \
        and not isinstance(args[0], dom_tag) and not kwargs:
      wrapped = args[0]

      @wraps(wrapped)
      def f(*args, **kwargs):
        with _cls() as _tag:
          return wrapped(*args, **kwargs) or _tag
      return f
    return object.__new__(_cls)


  def __init__(self, *args, **kwargs):
    '''
    Creates a new tag. Child tags should be passed as arguments and attributes
    should be passed as keyword arguments.

    There is a non-rendering attribute which controls how the tag renders:

    * `__inline` - Boolean value. If True renders all children tags on the same
                   line.
    '''

    self.attributes = {}
    self.children   = []
    self.parent     = None

    # Does not insert newlines on all children if True (recursive attribute)
    self.is_inline = kwargs.pop('__inline', self.is_inline)
    self.is_pretty = kwargs.pop('__pretty', self.is_pretty)

    #Add child elements
    if args:
      self.add(*args)

    for attr, value in kwargs.items():
      self.set_attribute(*type(self).clean_pair(attr, value))

    self._ctx = None
    self._add_to_ctx()


  # context manager
  frame = namedtuple('frame', ['tag', 'items', 'used'])
  # stack of frames
  _with_contexts = defaultdict(list)

  def _add_to_ctx(self):
    stack = dom_tag._with_contexts.get(_get_thread_context())
    if stack:
      self._ctx = stack[-1]
      stack[-1].items.append(self)


  def __enter__(self):
    stack = dom_tag._with_contexts[_get_thread_context()]
    stack.append(dom_tag.frame(self, [], set()))
    return self


  def __exit__(self, type, value, traceback):
    thread_id = _get_thread_context()
    stack = dom_tag._with_contexts[thread_id]
    frame = stack.pop()
    for item in frame.items:
      if item in frame.used: continue
      self.add(item)
    if not stack:
      del dom_tag._with_contexts[thread_id]


  def __call__(self, func):
    '''
    tag instance is being used as a decorator.
    wrap func to make a copy of this tag
    '''
    # remove decorator from its context so it doesn't
    # get added in where it was defined
    if self._ctx:
      self._ctx.used.add(self)

    @wraps(func)
    def f(*args, **kwargs):
      tag = copy.deepcopy(self)
      tag._add_to_ctx()
      with tag:
        return func(*args, **kwargs) or tag
    return f


  def set_attribute(self, key, value):
    '''
    Add or update the value of an attribute.
    '''
    if isinstance(key, int):
      self.children[key] = value
    elif isinstance(key, basestring):
      self.attributes[key] = value
    else:
      raise TypeError('Only integer and string types are valid for assigning '
          'child tags and attributes, respectively.')
  __setitem__ = set_attribute


  def delete_attribute(self, key):
    if isinstance(key, int):
      del self.children[key:key+1]
    else:
      del self.attributes[key]
  __delitem__ = delete_attribute


  def add(self, *args):
    '''
    Add new child tags.
    '''
    for obj in args:
      if isinstance(obj, numbers.Number):
        # Convert to string so we fall into next if block
        obj = str(obj)

      if isinstance(obj, basestring):
        obj = util.escape(obj)
        self.children.append(obj)

      elif isinstance(obj, dom_tag):
        stack = dom_tag._with_contexts.get(_get_thread_context(), [])
        for s in stack:
          s.used.add(obj)
        self.children.append(obj)
        obj.parent = self

      elif isinstance(obj, dict):
        for attr, value in obj.items():
          self.set_attribute(*dom_tag.clean_pair(attr, value))

      elif hasattr(obj, '__iter__'):
        for subobj in obj:
          self.add(subobj)

      else:  # wtf is it?
        raise ValueError('%r not a tag or string.' % obj)

    if len(args) == 1:
      return args[0]

    return args


  def add_raw_string(self, s):
    self.children.append(s)


  def remove(self, obj):
    self.children.remove(obj)


  def clear(self):
    for i in self.children:
      if isinstance(i, dom_tag) and i.parent is self:
        i.parent = None
    self.children = []


  def get(self, tag=None, **kwargs):
    '''
    Recursively searches children for tags of a certain
    type with matching attributes.
    '''
    # Stupid workaround since we can not use dom_tag in the method declaration
    if tag is None: tag = dom_tag

    attrs = [(dom_tag.clean_attribute(attr), value)
        for attr, value in kwargs.items()]

    results = []
    for child in self.children:
      if (isinstance(tag, basestring) and type(child).__name__ == tag) or \
        (not isinstance(tag, basestring) and isinstance(child, tag)):

        if all(child.attributes.get(attribute) == value
            for attribute, value in attrs):
          # If the child is of correct type and has all attributes and values
          # in kwargs add as a result
          results.append(child)
      if isinstance(child, dom_tag):
        # If the child is a dom_tag extend the search down through its children
        results.extend(child.get(tag, **kwargs))
    return results


  def __getitem__(self, key):
    '''
    Returns the stored value of the specified attribute or child
    (if it exists).
    '''
    if isinstance(key, int):
      # Children are accessed using integers
      try:
        return object.__getattribute__(self, 'children')[key]
      except IndexError:
        raise IndexError('Child with index "%s" does not exist.' % key)
    elif isinstance(key, basestring):
      # Attributes are accessed using strings
      try:
        return object.__getattribute__(self, 'attributes')[key]
      except KeyError:
        raise AttributeError('Attribute "%s" does not exist.' % key)
    else:
      raise TypeError('Only integer and string types are valid for accessing '
          'child tags and attributes, respectively.')
  __getattr__ = __getitem__


  def __len__(self):
    '''
    Number of child elements.
    '''
    return len(self.children)


  def __bool__(self):
    '''
    Hack for "if x" and __len__
    '''
    return True
  __nonzero__ = __bool__


  def __iter__(self):
    '''
    Iterates over child elements.
    '''
    return self.children.__iter__()


  def __contains__(self, item):
    '''
    Checks recursively if item is in children tree.
    Accepts both a string and a class.
    '''
    return bool(self.get(item))


  def __iadd__(self, obj):
    '''
    Reflexive binary addition simply adds tag as a child.
    '''
    self.add(obj)
    return self

  # String and unicode representations are the same as render()
  def __unicode__(self):
    return self.render()
  __str__ = __unicode__


  def render(self, indent='  ', pretty=True, xhtml=False):
    data = self._render([], 0, indent, pretty, xhtml)
    return u''.join(data)


  def _render(self, sb, indent_level, indent_str, pretty, xhtml):
    pretty = pretty and self.is_pretty

    name = getattr(self, 'tagname', type(self).__name__)

    # Workaround for python keywords and standard classes/methods
    # (del, object, input)
    if name[-1] == '_':
      name = name[:-1]

    # open tag
    sb.append('<')
    sb.append(name)

    for attribute, value in sorted(self.attributes.items()):
      if value in (False, None):
        continue
      val = unicode(value) if isinstance(value, util.text) and not value.escape else util.escape(unicode(value), True)
      sb.append(' %s="%s"' % (attribute, val))

    sb.append(' />' if self.is_single and xhtml else '>')

    if self.is_single:
      return sb

    inline = self._render_children(sb, indent_level + 1, indent_str, pretty, xhtml)
    if pretty and not inline:
      sb.append('\n')
      sb.append(indent_str * indent_level)

    # close tag
    sb.append('')

    return sb

  def _render_children(self, sb, indent_level, indent_str, pretty, xhtml):
    inline = True
    for child in self.children:
      if isinstance(child, dom_tag):
        if pretty and not child.is_inline:
          inline = False
          sb.append('\n')
          sb.append(indent_str * indent_level)
        child._render(sb, indent_level, indent_str, pretty, xhtml)
      else:
        sb.append(unicode(child))

    return inline


  def __repr__(self):
    name = '%s.%s' % (self.__module__, type(self).__name__)

    attributes_len = len(self.attributes)
    attributes = '%s attribute' % attributes_len
    if attributes_len != 1: attributes += 's'

    children_len = len(self.children)
    children = '%s child' % children_len
    if children_len != 1: children += 'ren'

    return '<%s at %x: %s, %s>' % (name, id(self), attributes, children)


  @staticmethod
  def clean_attribute(attribute):
    '''
    Normalize attribute names for shorthand and work arounds for limitations
    in Python's syntax
    '''

    # Shorthand
    attribute = {
      'cls': 'class',
      'className': 'class',
      'class_name': 'class',
      'klass': 'class',
      'fr': 'for',
      'html_for': 'for',
      'htmlFor': 'for',
      'phor': 'for',
    }.get(attribute, attribute)

    # Workaround for Python's reserved words
    if attribute[0] == '_':
      attribute = attribute[1:]

    # Workaround for dash
    special_prefix = any([attribute.startswith(x) for x in ('data_', 'aria_')])
    if attribute in set(['http_equiv']) or special_prefix:
      attribute = attribute.replace('_', '-').lower()

    # Workaround for colon
    if attribute.split('_')[0] in ('xlink', 'xml', 'xmlns'):
      attribute = attribute.replace('_', ':', 1).lower()

    return attribute


  @classmethod
  def clean_pair(cls, attribute, value):
    '''
    This will call `clean_attribute` on the attribute and also allows for the
    creation of boolean attributes.

    Ex. input(selected=True) is equivalent to input(selected="selected")
    '''
    attribute = cls.clean_attribute(attribute)

    # Check for boolean attributes
    # (i.e. selected=True becomes selected="selected")
    if value is True:
      value = attribute

    # Ignore `if value is False`: this is filtered out in render()

    return (attribute, value)


_get_current_none = object()
def get_current(default=_get_current_none):
  '''
  get the current tag being used as a with context or decorated function.
  if no context is active, raises ValueError, or returns the default, if provided
  '''
  h = _get_thread_context()
  ctx = dom_tag._with_contexts.get(h, None)
  if ctx:
    return ctx[-1].tag
  if default is _get_current_none:
    raise ValueError('no current context')
  return default


def attr(*args, **kwargs):
  '''
  Set attributes on the current active tag context
  '''
  c = get_current()
  dicts = args + (kwargs,)
  for d in dicts:
    for attr, value in d.items():
      c.set_attribute(*dom_tag.clean_pair(attr, value))


from . import util
dominate-2.9.0/dominate/svg.py000066400000000000000000000216411452177110200162770ustar00rootroot00000000000000'''
This module consists of classes specific to HTML5-SVG Elements. In general this module does not include
- Elements that are not specific to SVG (eg. )
- Elements that are deprecated
'''
from dominate.tags import html_tag
from dominate.dom_tag import dom_tag
import numbers


__license__ = '''
This file is part of Dominate.

Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

Dominate is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General
Public License along with Dominate.  If not, see
.
'''

# Tag attributes
_ATTR_GLOBAL = set([
  'accesskey', 'class', 'class', 'contenteditable', 'contextmenu', 'dir',
  'draggable', 'id', 'item', 'hidden', 'lang', 'itemprop', 'spellcheck',
  'style', 'subject', 'tabindex', 'title'
])

# https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Events#Attributes
_ATTR_EVENTS = set([
  'onbegin', 'onend', 'onrepeat',
  'onabort', 'onerror', 'onresize', 'onscroll', 'onunload',
  'oncopy', 'oncut', 'onpaste',
  'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncuechange', 'ondblclick',
  'ondrag', 'ondragend', 'ondragenter', 'ondragexit', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
  'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress',
  'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata','onloadstart', 'onmousedown', 'onmouseenter',
  'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onpause', 'onplay',
  'onplaying', 'onprogress', 'onratechange', 'onreset', 'onresize', 'onscroll', 'onseeked', 'onseeking', 'onselect',
  'onshow', 'onstalled', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'onvolumechange', 'onwaiting'
])

DASHED_ATTRIBUTES = set([
  'accent', 'alignment', 'arabic', 'baseline', 'cap', 'clip', 'color', 'dominant', 'enable', 'fill', 'flood', 
  'font', 'glyph', 'horiz', 'image', 'letter', 'lighting', 'marker', 'overline', 'paint', 'panose', 'pointer', 
  'rendering', 'shape', 'stop', 'strikethrough', 'stroke', 'text', 'underline', 'unicode', 'units', 'v', 'vector', 
  'vert', 'word', 'writing', 'x'
])


# https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg
class svg_tag(html_tag):
  @staticmethod
  def clean_attribute(attribute):
    attribute = html_tag.clean_attribute(attribute)
    words = attribute.split('_')
    if words[0] in DASHED_ATTRIBUTES:
      return attribute.replace('_', '-')
    return attribute


class svg(svg_tag):
  pass


class animate(svg_tag):
  '''
  The  animate SVG element is used to animate an attribute or property of an element over time.
  It's normally inserted inside the element or referenced by the href attribute of the target element.
  '''
  pass


class animateMotion(svg_tag):
  '''
  The  element causes a referenced element to move along a motion path.
  '''
  pass


class animateTransform(svg_tag):
  '''
  The animateTransform element animates a transformation attribute on its target element, thereby allowing
  animations to control translation, scaling, rotation, and/or skewing.
  '''
  is_single = True


class circle(svg_tag):
  '''
  The  SVG element is an SVG basic shape, used to draw circles based on a center point and a radius.
  '''
  pass


class clipPath(svg_tag):
  '''
  The  SVG element defines a clipping path, to be used used by the clip-path property.
  '''
  pass


class defs(svg_tag):
  '''
  The  element is used to store graphical objects that will be used at a later time. Objects created inside a
   element are not rendered directly. To display them you have to reference them
  (with a  element for example).
  '''
  pass


class desc(svg_tag):
  '''
  The  element provides an accessible, long-text description of any SVG container element or graphics element.
  '''
  pass


class ellipse(svg_tag):
  '''
  An ellipse element for svg containers
  '''
  pass

# (Note, filters are at the bottom of this file)

class g(svg_tag):
  '''
  The  SVG element is a container used to group other SVG elements.
  '''
  pass


class image(svg_tag):
  '''
  The  SVG element includes images inside SVG documents. It can display raster image files or other SVG files.
  '''
  pass


class line(svg_tag):
  '''
  The  element is an SVG basic shape used to create a line connecting two points.
  '''
  pass


class linearGradient(svg_tag):
  '''
  The  element lets authors define linear gradients that can be applied to fill or
  stroke of graphical elements.
  '''
  pass


class marker(svg_tag):
  '''
  The  element defines the graphic that is to be used for drawing arrowheads or polymarkers on a given , ,  or  element.
  '''
  pass


class mask(svg_tag):
  '''
  The  element defines an alpha mask for compositing the current object into the background.
  A mask is used/referenced using the mask property.
  '''
  pass


class mpath(svg_tag):
  '''
  The  sub-element for the  element provides the ability to reference an
  external  element as the definition of a motion path.
  '''
  pass


class pattern(svg_tag):
  '''
  The  element defines a graphics object which can be redrawn at repeated x and y-coordinate
  intervals ("tiled") to cover an area.
  '''
  pass


class polygon(svg_tag):
  '''
  A polygon element for svg containers
  '''
  pass


class polyline(svg_tag):
  '''
  A polyline element for svg containers
  '''
  pass


class radialGradient(svg_tag):
  '''
  The  element lets authors define radial gradients that can be applied to fill
  or stroke of graphical elements.
  '''
  pass


class path(svg_tag):
  '''
  A path element for svg containers
  '''
  pass


class rect(svg_tag):
  '''
  A rectangle element for svg containers
  '''
  pass


class stop(svg_tag):
  '''
  The SVG  element defines a color and its position to use on a gradient.
  This element is always a child of a  or  element.
  '''
  pass


class switch(svg_tag):
  '''
  The  SVG element evaluates any requiredFeatures, requiredExtensions and systemLanguage attributes
  on its direct child elements in order, and then renders the first child where these attributes evaluate to true.
  Other direct children will be bypassed and therefore not rendered. If a child element is a container element,
  like , then its subtree is also processed/rendered or bypassed/not rendered.
  '''
  pass


class symbol(svg_tag):
  '''
  The use of symbol elements for graphics that are used multiple times in the same document adds structure and
   semantics. Documents that are rich in structure may be rendered graphically, as speech, or as Braille,
   and thus promote accessibility.
  '''
  pass


class text(svg_tag):
  '''
  The SVG  element draws a graphics element consisting of text. It's possible to apply a gradient,
   pattern, clipping path, mask, or filter to , like any other SVG graphics element.
  '''
  pass


class textPath(svg_tag):
  '''
  To render text along the shape of a , enclose the text in a  element that has an href
  attribute with a reference to the  element.
  '''
  pass


class title(svg_tag):
  '''
  The  element provides an accessible, short-text description of any SVG container
  element or graphics element.
  '''
  pass


class tspan(svg_tag):
  '''
  The SVG <tspan> element define a subtext within a <text> element or another <tspan> element.
  It allows to adjust the style and/or position of that subtext as needed.
  '''
  pass


class use(svg_tag):
  '''
  The <use> element takes nodes from within the SVG document, and duplicates them somewhere else.
  '''
  pass


class view(svg_tag):
  '''
  A view is a defined way to view the image, like a zoom level or a detail view.
  '''
  pass


# FILTERS
class filter(svg_tag):
  pass

class feBlend(svg_tag):
  pass

class feColorMatrix(svg_tag):
  pass

class feComponentTransfer(svg_tag):
  pass

class feComposite(svg_tag):
  pass

class feConvolveMatrix(svg_tag):
  pass

class feDiffuseLighting(svg_tag):
  pass

class feDisplacementMap(svg_tag):
  pass

class feFlood(svg_tag):
  pass

class feGaussianBlur(svg_tag):
  pass

class feImage(svg_tag):
  pass

class feMerge(svg_tag):
  pass

class feMorphology(svg_tag):
  pass

class feOffset(svg_tag):
  pass

class feSpecularLighting(svg_tag):
  pass

class feTile(svg_tag):
  pass

class feTurbulence(svg_tag):
  pass

class feDistantLight(svg_tag):
  pass

class fePointLight(svg_tag):
  pass

class feSpotLight(svg_tag):
  pass
�����������������������������������������������������������������������������������������������dominate-2.9.0/dominate/tags.py���������������������������������������������������������������������0000664�0000000�0000000�00000067743�14521771102�0016453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'''
HTML tag classes.
'''
__license__ = '''
This file is part of Dominate.

Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

Dominate is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General
Public License along with Dominate.  If not, see
<http://www.gnu.org/licenses/>.
'''
from .dom_tag  import dom_tag, attr, get_current
from .dom1core import dom1core

try:
  basestring = basestring
except NameError: # py3
  basestring = str
  unicode = str

underscored_classes = set(['del', 'input', 'map', 'object'])

# Tag attributes
_ATTR_GLOBAL = set([
  'accesskey', 'class', 'class', 'contenteditable', 'contextmenu', 'dir',
  'draggable', 'id', 'item', 'hidden', 'lang', 'itemprop', 'spellcheck',
  'style', 'subject', 'tabindex', 'title'
])
_ATTR_EVENTS = set([
  'onabort', 'onblur', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick',
  'oncontextmenu', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter',
  'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange',
  'onemptied', 'onended', 'onerror', 'onfocus', 'onformchange', 'onforminput',
  'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onload',
  'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmousedown',
  'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel',
  'onpause', 'onplay', 'onplaying', 'onprogress', 'onratechange',
  'onreadystatechange', 'onscroll', 'onseeked', 'onseeking', 'onselect',
  'onshow', 'onstalled', 'onsubmit', 'onsuspend', 'ontimeupdate',
  'onvolumechange', 'onwaiting'
])


ERR_ATTRIBUTE = 'attributes'
ERR_CONTEXT = 'context'
ERR_CONTENT = 'content'


class html_tag(dom_tag, dom1core):
  def __init__(self, *args, **kwargs):
    '''
    Creates a new html tag instance.
    '''
    super(html_tag, self).__init__(*args, **kwargs)


  # def validate(self):
  #   '''
  #   Validate the tag. This will check the attributes, context, and contents and
  #   emit tuples in the form of: element, message.
  #   '''
  #   errors = []

  #   errors.extend(self.validate_attributes())
  #   errors.extend(self.validate_context())
  #   errors.extend(self.validate_content())

  #   return errors

  # def validate_attributes(self):
  #   '''
  #   Validate the tag attributes.
  #   '''
  #   return []

  # def validate_context(self):
  #   '''
  #   Validate the tag context.
  #   '''
  #   return []

  # def validate_content(self):
  #   '''
  #   Validate the content of the tag.
  #   '''
  #   return []

  # def _check_attributes(self, *attrs):
  #   valid = set([])
  #   for attr in attrs:
  #     if hasattr(attr, '__iter__'):
  #       valid |= set(attr)
  #     else:
  #       valid.add(attr)
  #   return set(list(self.attributes.iterkeys())) - valid



################################################################################
############################### Html Tag Classes ###############################
################################################################################

# Root element

class html(html_tag):
  '''
  The html element represents the root of an HTML document.
  '''
  pass
  # def validate_attributes(self):
  #   errors = []
  #   for invalid in self._check_attributes(_ATTR_GLOBAL, 'manifest'):
  #     errors.append( (self, ERR_ATTRIBUTE, 'Invalid attribute: "%s"' % invalid) )
  #   return errors

  # def validate_context(self):
  #   if self.parent is not None and not isinstance(self.parent, iframe):
  #     return [(self, ERR_CONTEXT, 'Must be root element or child of an <iframe>')]
  #   return []

  # def validate_content(self):
  #   if len(self) != 2 or not isinstance(self[0], head) or not isinstance(self[1], body):
  #     return [(self, ERR_CONTENT, 'Children must be <head> and then <body>.')]
  #   return []


# Document metadata
class head(html_tag):
  '''
  The head element represents a collection of metadata for the document.
  '''
  pass


class title(html_tag):
  '''
  The title element represents the document's title or name. Authors should use
  titles that identify their documents even when they are used out of context,
  for example in a user's history or bookmarks, or in search results. The
  document's title is often different from its first heading, since the first
  heading does not have to stand alone when taken out of context.
  '''
  def _get_text(self):
    return u''.join(self.get(basestring))
  def _set_text(self, text):
    self.clear()
    self.add(text)
  text = property(_get_text, _set_text)


class base(html_tag):
  '''
  The base element allows authors to specify the document base URL for the
  purposes of resolving relative URLs, and the name of the default browsing
  context for the purposes of following hyperlinks. The element does not
  represent any content beyond this information.
  '''
  is_single = True


class link(html_tag):
  '''
  The link element allows authors to link their document to other resources.
  '''
  is_single = True


class meta(html_tag):
  '''
  The meta element represents various kinds of metadata that cannot be
  expressed using the title, base, link, style, and script elements.
  '''
  is_single = True


class style(html_tag):
  '''
  The style element allows authors to embed style information in their
  documents. The style element is one of several inputs to the styling
  processing model. The element does not represent content for the user.
  '''
  is_pretty = False


# Scripting
class script(html_tag):
  '''
  The script element allows authors to include dynamic script and data blocks
  in their documents. The element does not represent content for the user.
  '''
  is_pretty = False


class noscript(html_tag):
  '''
  The noscript element represents nothing if scripting is enabled, and
  represents its children if scripting is disabled. It is used to present
  different markup to user agents that support scripting and those that don't
  support scripting, by affecting how the document is parsed.
  '''
  pass


# Sections
class body(html_tag):
  '''
  The body element represents the main content of the document.
  '''
  pass

class main(html_tag):
  '''
  The main content area of a document includes content that is unique to that
  document and excludes content that is repeated across a set of documents such
  as site navigation links, copyright information, site logos and banners and
  search forms (unless the document or application's main function is that of a
  search form).
  '''

class section(html_tag):
  '''
  The section element represents a generic section of a document or
  application. A section, in this context, is a thematic grouping of content,
  typically with a heading.
  '''
  pass


class nav(html_tag):
  '''
  The nav element represents a section of a page that links to other pages or
  to parts within the page: a section with navigation links.
  '''
  pass


class article(html_tag):
  '''
  The article element represents a self-contained composition in a document,
  page, application, or site and that is, in principle, independently
  distributable or reusable, e.g. in syndication. This could be a forum post, a
  magazine or newspaper article, a blog entry, a user-submitted comment, an
  interactive widget or gadget, or any other independent item of content.
  '''
  pass


class aside(html_tag):
  '''
  The aside element represents a section of a page that consists of content
  that is tangentially related to the content around the aside element, and
  which could be considered separate from that content. Such sections are
  often represented as sidebars in printed typography.
  '''
  pass


class h1(html_tag):
  '''
  Represents the highest ranking heading.
  '''
  pass


class h2(html_tag):
  '''
  Represents the second-highest ranking heading.
  '''
  pass


class h3(html_tag):
  '''
  Represents the third-highest ranking heading.
  '''
  pass


class h4(html_tag):
  '''
  Represents the fourth-highest ranking heading.
  '''
  pass


class h5(html_tag):
  '''
  Represents the fifth-highest ranking heading.
  '''
  pass


class h6(html_tag):
  '''
  Represents the sixth-highest ranking heading.
  '''
  pass


class hgroup(html_tag):
  '''
  The hgroup element represents the heading of a section. The element is used
  to group a set of h1-h6 elements when the heading has multiple levels, such
  as subheadings, alternative titles, or taglines.
  '''
  pass


class header(html_tag):
  '''
  The header element represents a group of introductory or navigational aids.
  '''
  pass


class footer(html_tag):
  '''
  The footer element represents a footer for its nearest ancestor sectioning
  content or sectioning root element. A footer typically contains information
  about its section such as who wrote it, links to related documents,
  copyright data, and the like.
  '''
  pass


class address(html_tag):
  '''
  The address element represents the contact information for its nearest
  article or body element ancestor. If that is the body element, then the
  contact information applies to the document as a whole.
  '''
  pass


# Grouping content
class p(html_tag):
  '''
  The p element represents a paragraph.
  '''
  pass


class hr(html_tag):
  '''
  The hr element represents a paragraph-level thematic break, e.g. a scene
  change in a story, or a transition to another topic within a section of a
  reference book.
  '''
  is_single = True


class pre(html_tag):
  '''
  The pre element represents a block of preformatted text, in which structure
  is represented by typographic conventions rather than by elements.
  '''
  is_pretty = False


class blockquote(html_tag):
  '''
  The blockquote element represents a section that is quoted from another
  source.
  '''
  pass


class ol(html_tag):
  '''
  The ol element represents a list of items, where the items have been
  intentionally ordered, such that changing the order would change the
  meaning of the document.
  '''
  pass


class ul(html_tag):
  '''
  The ul element represents a list of items, where the order of the items is
  not important - that is, where changing the order would not materially change
  the meaning of the document.
  '''
  pass


class li(html_tag):
  '''
  The li element represents a list item. If its parent element is an ol, ul, or
  menu element, then the element is an item of the parent element's list, as
  defined for those elements. Otherwise, the list item has no defined
  list-related relationship to any other li element.
  '''
  pass


class dl(html_tag):
  '''
  The dl element represents an association list consisting of zero or more
  name-value groups (a description list). Each group must consist of one or
  more names (dt elements) followed by one or more values (dd elements).
  Within a single dl element, there should not be more than one dt element for
  each name.
  '''
  pass


class dt(html_tag):
  '''
  The dt element represents the term, or name, part of a term-description group
  in a description list (dl element).
  '''
  pass


class dd(html_tag):
  '''
  The dd element represents the description, definition, or value, part of a
  term-description group in a description list (dl element).
  '''
  pass


class figure(html_tag):
  '''
  The figure element represents some flow content, optionally with a caption,
  that is self-contained and is typically referenced as a single unit from the
  main flow of the document.
  '''
  pass


class figcaption(html_tag):
  '''
  The figcaption element represents a caption or legend for the rest of the
  contents of the figcaption element's parent figure element, if any.
  '''
  pass


class div(html_tag):
  '''
  The div element has no special meaning at all. It represents its children. It
  can be used with the class, lang, and title attributes to mark up semantics
  common to a group of consecutive elements.
  '''
  pass


# Text semantics
class a(html_tag):
  '''
  If the a element has an href attribute, then it represents a hyperlink (a
  hypertext anchor).

  If the a element has no href attribute, then the element represents a
  placeholder for where a link might otherwise have been placed, if it had been
  relevant.
  '''
  pass


class em(html_tag):
  '''
  The em element represents stress emphasis of its contents.
  '''
  pass


class strong(html_tag):
  '''
  The strong element represents strong importance for its contents.
  '''
  pass


class small(html_tag):
  '''
  The small element represents side comments such as small print.
  '''
  pass


class s(html_tag):
  '''
  The s element represents contents that are no longer accurate or no longer
  relevant.
  '''
  pass


class cite(html_tag):
  '''
  The cite element represents the title of a work (e.g. a book, a paper, an
  essay, a poem, a score, a song, a script, a film, a TV show, a game, a
  sculpture, a painting, a theatre production, a play, an opera, a musical, an
  exhibition, a legal case report, etc). This can be a work that is being
  quoted or referenced in detail (i.e. a citation), or it can just be a work
  that is mentioned in passing.
  '''
  pass


class q(html_tag):
  '''
  The q element represents some phrasing content quoted from another source.
  '''
  pass


class dfn(html_tag):
  '''
  The dfn element represents the defining instance of a term. The paragraph,
  description list group, or section that is the nearest ancestor of the dfn
  element must also contain the definition(s) for the term given by the dfn
  element.
  '''
  pass


class abbr(html_tag):
  '''
  The abbr element represents an abbreviation or acronym, optionally with its
  expansion. The title attribute may be used to provide an expansion of the
  abbreviation. The attribute, if specified, must contain an expansion of the
  abbreviation, and nothing else.
  '''
  pass


class time_(html_tag):
  '''
  The time element represents either a time on a 24 hour clock, or a precise
  date in the proleptic Gregorian calendar, optionally with a time and a
  time-zone offset.
  '''
  pass
_time = time_


class code(html_tag):
  '''
  The code element represents a fragment of computer code. This could be an XML
  element name, a filename, a computer program, or any other string that a
  computer would recognize.
  '''
  pass


class var(html_tag):
  '''
  The var element represents a variable. This could be an actual variable in a
  mathematical expression or programming context, an identifier representing a
  constant, a function parameter, or just be a term used as a placeholder in
  prose.
  '''
  pass


class samp(html_tag):
  '''
  The samp element represents (sample) output from a program or computing
  system.
  '''
  pass


class kbd(html_tag):
  '''
  The kbd element represents user input (typically keyboard input, although it
  may also be used to represent other input, such as voice commands).
  '''
  pass


class sub(html_tag):
  '''
  The sub element represents a subscript.
  '''
  pass


class sup(html_tag):
  '''
  The sup element represents a superscript.
  '''
  pass


class i(html_tag):
  is_inline = True
  '''
  The i element represents a span of text in an alternate voice or mood, or
  otherwise offset from the normal prose in a manner indicating a different
  quality of text, such as a taxonomic designation, a technical term, an
  idiomatic phrase from another language, a thought, or a ship name in Western
  texts.
  '''
  pass


class b(html_tag):
  '''
  The b element represents a span of text to which attention is being drawn for
  utilitarian purposes without conveying any extra importance and with no
  implication of an alternate voice or mood, such as key words in a document
  abstract, product names in a review, actionable words in interactive
  text-driven software, or an article lede.
  '''
  pass


class u(html_tag):
  '''
  The u element represents a span of text with an unarticulated, though
  explicitly rendered, non-textual annotation, such as labeling the text as
  being a proper name in Chinese text (a Chinese proper name mark), or
  labeling the text as being misspelt.
  '''
  pass


class mark(html_tag):
  '''
  The mark element represents a run of text in one document marked or
  highlighted for reference purposes, due to its relevance in another context.
  When used in a quotation or other block of text referred to from the prose,
  it indicates a highlight that was not originally present but which has been
  added to bring the reader's attention to a part of the text that might not
  have been considered important by the original author when the block was
  originally written, but which is now under previously unexpected scrutiny.
  When used in the main prose of a document, it indicates a part of the
  document that has been highlighted due to its likely relevance to the user's
  current activity.
  '''
  pass


class ruby(html_tag):
  '''
  The ruby element allows one or more spans of phrasing content to be marked
  with ruby annotations. Ruby annotations are short runs of text presented
  alongside base text, primarily used in East Asian typography as a guide for
  pronunciation or to include other annotations. In Japanese, this form of
  typography is also known as furigana.
  '''
  pass


class rt(html_tag):
  '''
  The rt element marks the ruby text component of a ruby annotation.
  '''
  pass


class rp(html_tag):
  '''
  The rp element can be used to provide parentheses around a ruby text
  component of a ruby annotation, to be shown by user agents that don't support
  ruby annotations.
  '''
  pass


class bdi(html_tag):
  '''
  The bdi element represents a span of text that is to be isolated from its
  surroundings for the purposes of bidirectional text formatting.
  '''
  pass


class bdo(html_tag):
  '''
  The bdo element represents explicit text directionality formatting control
  for its children. It allows authors to override the Unicode bidirectional
  algorithm by explicitly specifying a direction override.
  '''
  pass


class span(html_tag):
  '''
  The span element doesn't mean anything on its own, but can be useful when
  used together with the global attributes, e.g. class, lang, or dir. It
  represents its children.
  '''
  pass


class br(html_tag):
  '''
  The br element represents a line break.
  '''
  is_single = True
  is_inline = True


class wbr(html_tag):
  '''
  The wbr element represents a line break opportunity.
  '''
  is_single = True
  is_inline = True


# Edits
class ins(html_tag):
  '''
  The ins element represents an addition to the document.
  '''
  pass


class del_(html_tag):
  '''
  The del element represents a removal from the document.
  '''
  pass
_del = del_

# Embedded content
class img(html_tag):
  '''
  An img element represents an image.
  '''
  is_single = True


class iframe(html_tag):
  '''
  The iframe element represents a nested browsing context.
  '''
  pass


class embed(html_tag):
  '''
  The embed element represents an integration point for an external (typically
  non-HTML) application or interactive content.
  '''
  is_single = True


class object_(html_tag):
  '''
  The object element can represent an external resource, which, depending on
  the type of the resource, will either be treated as an image, as a nested
  browsing context, or as an external resource to be processed by a plugin.
  '''
  pass
_object = object_


class param(html_tag):
  '''
  The param element defines parameters for plugins invoked by object elements.
  It does not represent anything on its own.
  '''
  is_single = True


class video(html_tag):
  '''
  A video element is used for playing videos or movies, and audio files with
  captions.
  '''
  pass


class audio(html_tag):
  '''
  An audio element represents a sound or audio stream.
  '''
  pass


class source(html_tag):
  '''
  The source element allows authors to specify multiple alternative media
  resources for media elements. It does not represent anything on its own.
  '''
  is_single = True


class track(html_tag):
  '''
  The track element allows authors to specify explicit external timed text
  tracks for media elements. It does not represent anything on its own.
  '''
  is_single = True


class canvas(html_tag):
  '''
  The canvas element provides scripts with a resolution-dependent bitmap
  canvas, which can be used for rendering graphs, game graphics, or other
  visual images on the fly.
  '''
  pass


class map_(html_tag):
  '''
  The map element, in conjunction with any area element descendants, defines an
  image map. The element represents its children.
  '''
  pass
_map = map_

class area(html_tag):
  '''
  The area element represents either a hyperlink with some text and a
  corresponding area on an image map, or a dead area on an image map.
  '''
  is_single = True


# Tabular data
class table(html_tag):
  '''
  The table element represents data with more than one dimension, in the form
  of a table.
  '''
  pass


class caption(html_tag):
  '''
  The caption element represents the title of the table that is its parent, if
  it has a parent and that is a table element.
  '''
  pass


class colgroup(html_tag):
  '''
  The colgroup element represents a group of one or more columns in the table
  that is its parent, if it has a parent and that is a table element.
  '''
  pass


class col(html_tag):
  '''
  If a col element has a parent and that is a colgroup element that itself has
  a parent that is a table element, then the col element represents one or more
  columns in the column group represented by that colgroup.
  '''
  is_single = True


class tbody(html_tag):
  '''
  The tbody element represents a block of rows that consist of a body of data
  for the parent table element, if the tbody element has a parent and it is a
  table.
  '''
  pass


class thead(html_tag):
  '''
  The thead element represents the block of rows that consist of the column
  labels (headers) for the parent table element, if the thead element has a
  parent and it is a table.
  '''
  pass


class tfoot(html_tag):
  '''
  The tfoot element represents the block of rows that consist of the column
  summaries (footers) for the parent table element, if the tfoot element has a
  parent and it is a table.
  '''
  pass


class tr(html_tag):
  '''
  The tr element represents a row of cells in a table.
  '''
  pass


class td(html_tag):
  '''
  The td element represents a data cell in a table.
  '''
  pass


class th(html_tag):
  '''
  The th element represents a header cell in a table.
  '''
  pass


# Forms
class form(html_tag):
  '''
  The form element represents a collection of form-associated elements, some of
  which can represent editable values that can be submitted to a server for
  processing.
  '''
  pass


class fieldset(html_tag):
  '''
  The fieldset element represents a set of form controls optionally grouped
  under a common name.
  '''
  pass


class legend(html_tag):
  '''
  The legend element represents a caption for the rest of the contents of the
  legend element's parent fieldset element, if any.
  '''
  pass


class label(html_tag):
  '''
  The label represents a caption in a user interface. The caption can be
  associated with a specific form control, known as the label element's labeled
  control, either using for attribute, or by putting the form control inside
  the label element itself.
  '''
  pass


class input_(html_tag):
  '''
  The input element represents a typed data field, usually with a form control
  to allow the user to edit the data.
  '''
  is_single = True
_input = input_


class button(html_tag):
  '''
  The button element represents a button. If the element is not disabled, then
  the user agent should allow the user to activate the button.
  '''
  pass


class select(html_tag):
  '''
  The select element represents a control for selecting amongst a set of
  options.
  '''
  pass


class datalist(html_tag):
  '''
  The datalist element represents a set of option elements that represent
  predefined options for other controls. The contents of the element represents
  fallback content for legacy user agents, intermixed with option elements that
  represent the predefined options. In the rendering, the datalist element
  represents nothing and it, along with its children, should be hidden.
  '''
  pass


class optgroup(html_tag):
  '''
  The optgroup element represents a group of option elements with a common
  label.
  '''
  pass


class option(html_tag):
  '''
  The option element represents an option in a select element or as part of a
  list of suggestions in a datalist element.
  '''
  pass


class textarea(html_tag):
  '''
  The textarea element represents a multiline plain text edit control for the
  element's raw value. The contents of the control represent the control's
  default value.
  '''
  pass


class keygen(html_tag):
  '''
  The keygen element represents a key pair generator control. When the
  control's form is submitted, the private key is stored in the local keystore,
  and the public key is packaged and sent to the server.
  '''
  is_single = True


class output(html_tag):
  '''
  The output element represents the result of a calculation.
  '''
  pass


class progress(html_tag):
  '''
  The progress element represents the completion progress of a task. The
  progress is either indeterminate, indicating that progress is being made but
  that it is not clear how much more work remains to be done before the task is
  complete (e.g. because the task is waiting for a remote host to respond), or
  the progress is a number in the range zero to a maximum, giving the fraction
  of work that has so far been completed.
  '''
  pass


class meter(html_tag):
  '''
  The meter element represents a scalar measurement within a known range, or a
  fractional value; for example disk usage, the relevance of a query result, or
  the fraction of a voting population to have selected a particular candidate.
  '''
  pass


# Interactive elements
class details(html_tag):
  '''
  The details element represents a disclosure widget from which the user can
  obtain additional information or controls.
  '''
  pass


class summary(html_tag):
  '''
  The summary element represents a summary, caption, or legend for the rest of
  the contents of the summary element's parent details element, if any.
  '''
  pass


class command(html_tag):
  '''
  The command element represents a command that the user can invoke.
  '''
  is_single = True


class menu(html_tag):
  '''
  The menu element represents a list of commands.
  '''
  pass


class font(html_tag):
  '''
  The font element represents the font in a html .
  '''
  pass


# Additional markup
class comment(html_tag):
  '''
  Normal, one-line comment:
    >>> print comment("Hello, comments!")
    <!--Hello, comments!-->

  For IE's "if" statement comments:
    >>> print comment(p("Upgrade your browser."), condition='lt IE6')
    <!--[if lt IE6]><p>Upgrade your browser.</p><![endif]-->

  Downlevel conditional comments:
    >>> print comment(p("You are using a ", em("downlevel"), " browser."),
            condition='false', downlevel='revealed')
    <![if false]><p>You are using a <em>downlevel</em> browser.</p><![endif]>

  For more on conditional comments see:
    http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx
  '''

  ATTRIBUTE_CONDITION = 'condition'

  # Valid values are 'hidden', 'downlevel' or 'revealed'
  ATTRIBUTE_DOWNLEVEL = 'downlevel'

  def _render(self, sb, indent_level=1, indent_str='  ', pretty=True, xhtml=False):
    has_condition = comment.ATTRIBUTE_CONDITION in self.attributes
    is_revealed   = comment.ATTRIBUTE_DOWNLEVEL in self.attributes and \
        self.attributes[comment.ATTRIBUTE_DOWNLEVEL] == 'revealed'

    sb.append('<!')
    if not is_revealed:
      sb.append('--')
    if has_condition:
      sb.append('[if %s]>' % self.attributes[comment.ATTRIBUTE_CONDITION])

    pretty = self._render_children(sb, indent_level - 1, indent_str, pretty, xhtml)

    # if len(self.children) > 1:
    if any(isinstance(child, dom_tag) for child in self):
      sb.append('\n')
      sb.append(indent_str * (indent_level - 1))

    if has_condition:
      sb.append('<![endif]')
    if not is_revealed:
      sb.append('--')
    sb.append('>')

    return sb
�����������������������������dominate-2.9.0/dominate/util.py���������������������������������������������������������������������0000664�0000000�0000000�00000010327�14521771102�0016454�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������'''
Utility classes for creating dynamic html documents
'''

__license__ = '''
This file is part of Dominate.

Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

Dominate is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General
Public License along with Dominate.  If not, see
<http://www.gnu.org/licenses/>.
'''

import re

from .dom_tag import dom_tag

try:
  basestring = basestring
except NameError:
  basestring = str
  unichr = chr


def include(f):
  '''
  includes the contents of a file on disk.
  takes a filename
  '''
  fl = open(f, 'r')
  data = fl.read()
  fl.close()
  return raw(data)


def system(cmd, data=None):
  '''
  pipes the output of a program
  '''
  import subprocess
  s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  out, err = s.communicate(data)
  return out.decode('utf8')


def escape(data, quote=True):  # stolen from std lib cgi
  '''
  Escapes special characters into their html entities
  Replace special characters "&", "<" and ">" to HTML-safe sequences.
  If the optional flag quote is true, the quotation mark character (")
  is also translated.

  This is used to escape content that appears in the body of an HTML document
  '''
  data = data.replace("&", "&")  # Must be done first!
  data = data.replace("<", "<")
  data = data.replace(">", ">")
  if quote:
    data = data.replace('"', """)
  return data


_unescape = {
  'quot': 34,
  'amp':  38,
  'lt':   60,
  'gt':   62,
  'nbsp': 32,
  # more here
  # http://www.w3.org/TR/html4/sgml/entities.html
  'yuml': 255,
}
str_escape = escape


def unescape(data):
  '''
  unescapes html entities. the opposite of escape.
  '''
  cc = re.compile(r'&(?:(?:#(\d+))|([^;]+));')

  result = []
  m = cc.search(data)
  while m:
    result.append(data[0:m.start()])
    d = m.group(1)
    if d:
      d = int(d)
      result.append(unichr(d))
    else:
      d = _unescape.get(m.group(2), ord('?'))
      result.append(unichr(d))

    data = data[m.end():]
    m = cc.search(data)

  result.append(data)
  return ''.join(result)


_reserved = ";/?:@&=+$, "
_replace_map = dict((c, '%%%2X' % ord(c)) for c in _reserved)


def url_escape(data):
  return ''.join(_replace_map.get(c, c) for c in data)


def url_unescape(data):
  return re.sub('%([0-9a-fA-F]{2})',
    lambda m: unichr(int(m.group(1), 16)), data)


class container(dom_tag):
  '''
  Contains multiple elements, but does not add a level
  '''
  is_inline = True
  def _render(self, sb, indent_level, indent_str, pretty, xhtml):
    inline = self._render_children(sb, indent_level, indent_str, pretty, xhtml)
    if pretty and not inline:
      sb.append('\n')
      sb.append(indent_str * (indent_level - 1))
    return sb


class lazy(dom_tag):
  '''
  delays function execution until rendered
  '''
  def __new__(_cls, *args, **kwargs):
    '''
    Need to reset this special method or else
    dom_tag will think it's being used as a dectorator.

    This means lazy() can't be used as a dectorator, but
    thinking about when you might want that just confuses me.
    '''
    return object.__new__(_cls)

  def __init__(self, func, *args, **kwargs):
    super(lazy, self).__init__()
    self.func   = func
    self.args   = args
    self.kwargs = kwargs


  def _render(self, sb, *a, **kw):
    r = self.func(*self.args, **self.kwargs)
    sb.append(str(r))


class text(dom_tag):
  '''
  Just a string. Useful for inside context managers
  '''
  is_pretty = False
  is_inline = True

  def __init__(self, _text, escape=True):
    super(text, self).__init__()
    self.escape = escape
    if escape:
      self.text = str_escape(_text)
    else:
      self.text = _text

  def _render(self, sb, *a, **kw):
    sb.append(self.text)
    return sb


def raw(s):
  '''
  Inserts a raw string into the DOM. Unsafe. Alias for text(x, escape=False)
  '''
  return text(s, escape=False)
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/pyproject.toml�����������������������������������������������������������������������0000664�0000000�0000000�00000003027�14521771102�0016240�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[build-system]
requires = ["setuptools>=62"]
build-backend = "setuptools.build_meta"

[project]
name = "dominate"
description = "Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API."
readme = {file = "README.md", content-type = "text/markdown"}
authors = [
    {name = "Tom Flanagan", email = "tom@zkpq.ca"},
    {name = "Jake Wharton"},
]
requires-python = ">=3.4"
keywords = ["framework", "templating", "template", "html", "xhtml", "python", "html5"]
license = {text = "LGPL-3.0-or-newer"}
classifiers = [
    "Intended Audience :: Developers",
    "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.7",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
    "Programming Language :: Python :: Implementation :: PyPy",
    "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Topic :: Text Processing :: Markup :: HTML",
]
dynamic = ["version"]

[project.urls]
Homepage = "https://github.com/Knio/dominate"
Source = "https://github.com/Knio/dominate"

[tool.setuptools]
packages = ["dominate"]

[tool.setuptools.dynamic]
version = {attr = "dominate._version.__version__"}
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/setup.cfg����������������������������������������������������������������������������0000664�0000000�0000000�00000000106�14521771102�0015140�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������[metadata]
license_files = ["LICENSE.txt"]

[bdist_wheel]
universal=1
����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/setup/�������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14521771102�0014462�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/setup/setup.py�����������������������������������������������������������������������0000664�0000000�0000000�00000004503�14521771102�0016176�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������__license__ = '''
This file is part of Dominate.

Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

Dominate is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General
Public License along with dominate.  If not, see
<http://www.gnu.org/licenses/>.
'''
# pylint: disable=bad-whitespace

from setuptools import setup

import imp
_version = imp.load_source("dominate._version", "dominate/_version.py")

long_description = open('README.md').read()

setup(
  name    = 'dominate',
  version = _version.__version__,
  author  = 'Tom Flanagan and Jake Wharton',
  author_email = 'tom@zkpq.ca',
  license = 'LGPLv3',
  url     = 'https://github.com/Knio/dominate/',
  description      = 'Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API.',
  long_description = long_description,
  long_description_content_type='text/markdown',
  keywords         = 'framework templating template html xhtml python html5',

  python_requires='>=2.7, <3',
  classifiers = [
    'Intended Audience :: Developers',
    'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3.7',
    'Programming Language :: Python :: 3.8',
    'Programming Language :: Python :: 3.9',
    'Programming Language :: Python :: 3.10',
    'Programming Language :: Python :: Implementation :: PyPy',
    'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    'Topic :: Software Development :: Libraries :: Python Modules',
    'Topic :: Text Processing :: Markup :: HTML',
  ],

  packages = ['dominate'],
  include_package_data = True,
)
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/tests/�������������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14521771102�0014464�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������dominate-2.9.0/tests/test_document.py���������������������������������������������������������������0000664�0000000�0000000�00000003501�14521771102�0017712�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from dominate import document
from dominate.tags import *

def test_doc():
  d = document()
  assert d.render() == \
'''<!DOCTYPE html>
<html>
  <head>
    <title>Dominate
  
  
'''


def test_decorator():
  @document()
  def foo():
    p('Hello World')

  f = foo()
  assert f.render() == \
'''

  
    Dominate
  
  
    

Hello World

''' def test_bare_decorator(): @document def foo(): p('Hello World') assert foo().render() == \ ''' Dominate

Hello World

''' def test_title(): d = document() assert d.title == 'Dominate' d = document(title='foobar') assert d.title == 'foobar' d.title = 'baz' assert d.title == 'baz' d.title = title('bar') assert d.title == 'bar' assert d.render() == \ ''' bar ''' def test_containers(): d = document() with d.footer: div('footer') with d: div('main1') with d.main: div('main2') print(d.header) print(d) print(d.body.children) with d.header: div('header1') div('header2') assert d.render() == \ ''' Dominate
header1
header2
''''''
main1
main2
''''''
footer
''' def test_attributes(): d = document(title=None, doctype=None, lang='en') assert d.render() == \ ''' ''' def test_repr(): d = document(title='foo') assert d.__repr__() == '' if __name__ == '__main__': # test_doc() test_decorator() dominate-2.9.0/tests/test_dom1core.py000066400000000000000000000016021452177110200176050ustar00rootroot00000000000000import pytest from dominate.tags import * def test_dom(): container = div() with container.add(div(id='base')) as dom: s1 = span('Hello', id='span1') s2 = span('World', id='span2') s3 = span('foobar', id='span3') dom.appendChild(s3) assert container.getElementById('base') is dom assert container.getElementById('span1') is s1 assert container.getElementById('span3') is s3 assert container.getElementById('foo') is None assert container.getElementsByTagName('span') == [s1, s2, s3] assert container.getElementsByTagName('SPAN') == [s1, s2, s3] assert container.getElementsByTagName(1234) is None def test_element(): d = div( span(id='a'), span(id='a'), ) with pytest.raises(ValueError): d.getElementById('a') def test_parent_node(): parent = div(id='parent') child = div(id='child') parent.add(child) assert child.parentNode is parent dominate-2.9.0/tests/test_dom_tag.py000066400000000000000000000034251452177110200175130ustar00rootroot00000000000000import pytest try: import mock except ImportError: import unittest.mock as mock from dominate.tags import * def test___get_thread_context(monkeypatch): from dominate import dom_tag as sut greenlet = mock.Mock() greenlet.getcurrent.return_value = 100 monkeypatch.setattr(sut, 'greenlet', greenlet) threading = mock.Mock() threading.current_thread.return_value = 200 monkeypatch.setattr(sut, 'threading', threading) assert sut._get_thread_context() is not None def test_add_raw_string(): container = div() container.add_raw_string('foo') assert container.children == ['foo'] def test_clear(): container = div() child = div() container.add(child) assert container.children == [child] assert child.parent == container container.clear() assert container.children == [] assert child.parent is None def test_set_attribute(): container = div() container.add_raw_string('foo') container.set_attribute(0, 'bar') assert container.children == ['bar'] def test_set_attribute_error(): container = div() with pytest.raises(TypeError, match=( 'Only integer and string types are valid for assigning ' 'child tags and attributes, respectively.' )): container.set_attribute(1.0, 'foo') def test___get_item___child_index_error(): d = div() with pytest.raises(IndexError, match='Child with index "10" does not exist.'): d[10] def test___contains__(): container = div() container.add(div()) assert 'div' in container def test_nested_context(): def sub(*args): with div('B') as B: B.add(*args) with div('A') as A: sub(div('C')) assert str(A) == \ '''
A
B
C
''' dominate-2.9.0/tests/test_dominate.py000066400000000000000000000002111452177110200176670ustar00rootroot00000000000000 def test_version(): import dominate version = '2.9.0' assert dominate.version == version assert dominate.__version__ == version dominate-2.9.0/tests/test_html.py000066400000000000000000000157511452177110200170520ustar00rootroot00000000000000import dominate from dominate.tags import * import pytest from dominate.util import raw try: xrange = xrange except NameError: xrange = range def test_arguments(): assert html(body(h1('Hello, pyy!'))).render() == \ '''

Hello, pyy!

''' def test_kwargs(): assert div( id=4, checked=True, cls="mydiv", data_name='foo', onclick='alert(1);').render() == \ '''
''' def test_repr(): import re d = div() assert repr(d).startswith('') d += [1, {'id':'foo'}] assert repr(d).startswith('') def test_add(): d = div() with pytest.raises(ValueError): d += None d += 1 d += xrange(2,3) d += {'id': 'foo'} assert d.render() == '
12
' assert len(d) == 2 assert d with pytest.raises(IndexError): d[2] with pytest.raises(TypeError): d[None] del d[0] assert len(d) == 1 def test_iadd(): list = ul() for item in range(4): list += li('Item #', item) # 2 children so doesn't render inline assert list.render() == \ '''
  • Item #0
  • Item #1
  • Item #2
  • Item #3
''' def test_context_manager(): other = div() h = ul() with h: li('One') li('Two') li('Three') # added to other, so not added to h other += li('Four') assert h.render() == \ '''
  • One
  • Two
  • Three
''' def test_decorator(): @div def f(): p('Hello') assert f().render() == \ '''

Hello

''' d = div() @d def f2(): p('Hello') assert f2().render() == \ '''

Hello

''' @div(cls='three') def f3(): p('Hello') assert f3().render() == \ '''

Hello

''' def test_nested_decorator(): @div def f1(): p('hello') d = div() with d: f1() assert d.render() == \ '''

hello

''' @div() def f2(): p('hello') d = div() with d: f2() assert d.render() == \ '''

hello

''' def test_text(): from dominate.util import text d = div() with d: text('Hello World') assert d.render() == \ '''
Hello World
''' assert div(text('<>', escape=False)).render() == \ '''
<>
''' assert div(text('<>')).render() == \ '''
<>
''' def test_raw(): from dominate.util import raw d = div() with d: raw('Hello World
') assert d.render() == '''
Hello World
''' def test_escape(): assert pre('<>').render() == '''\
<>
''' def test_get_context(): with pytest.raises(ValueError): d = get_current() d = get_current(None) assert d is None with div() as d1: d2 = span() with d2: d2p = get_current() d1p = get_current() assert d1 is d1p assert d2 is d2p def test_attributes(): d = div() d['id'] = 'foo' assert d['id'] == 'foo' del d['id'] with pytest.raises(KeyError): del d['id'] with pytest.raises(AttributeError): x = d['id'] with div() as d: attr(data_test=False) assert d['data-test'] is False with div() as d: attr(data_test=True) assert d['data-test'] with pytest.raises(ValueError): # not in a tag context attr(id='moo') def test_attribute_none(): d = div(foo=1, bar=None) assert d.render() == '
' def test_attribute_dashes(): # fix issue #118 (https://github.com/Knio/dominate/issues/118) expected = '
' assert div(data_a_b_c='foo', data_page_size='123', aria_foo='bar').render() == expected def test_lazy(): from dominate import util executed = [False] def _lazy(): executed[0] = True return span('Hi') d = div() s = util.lazy(_lazy) d += s assert executed[0] == False assert d.render() == '
\n Hi\n
' assert executed[0] == True def test_keyword_attributes(): expected = '
' assert div(cls='foo', fr='bar').render() == expected assert div(_class='foo', _for='bar').render() == expected assert div(className='foo', htmlFor='bar').render() == expected assert div(class_name='foo', html_for='bar').render() == expected def test_namespaced_attributes(): assert div(foo_bar='one').render() == '
' assert div(xlink_href='one').render() == '
' def test_comment(): d = comment('Hi there') assert d.render() == '' assert div(d).render() == '
\n \n
' d = comment('Hi ie user', condition='IE 6') assert d.render() == '' d = comment(div('Hi non-ie user'), condition='!IE', downlevel='revealed') assert d.render() == '''
Hi non-ie user
''' def test_boolean_attributes(): assert input_(type="checkbox", checked=True).render() == \ '' assert input_(type="checkbox", checked=False).render() == \ '' def test_nested_decorator_2(): @span def foo(): @div(cls='bar') def bar(x): p(x) bar('a') bar('b') assert foo().render() == '''

a

b

''' def test_pretty(): assert head(script('foo'), style('bar')).render() == ''' ''' assert div(pre('test')).render() == '''
test
''' assert div(pre('test')).render(indent='\t') == '''
\t
test
''' assert div(pre('test')).render(pretty=False) == \ '''
test
''' assert div(span('hi'), span('there'), __pretty=False).render() == \ '''
hithere
''' assert span('hi', br(), 'there').render() == \ '''hi
there
''' assert span('hi', br(__inline=False), 'there').render() == \ '''hi\n
there\n
''' assert p('goodbye ', i('cruel'), ' world').render() == \ '''

goodbye cruel world

''' def test_xhtml(): assert head(script('foo'), style('bar')).render(xhtml=True) == ''' ''' assert span('hi', br(), 'there').render(xhtml=True) == \ '''hi
there
''' assert span('hi', br(), 'there').render() == \ '''hi
there
''' assert span('hi', br(), 'there').render(xhtml=False) == \ '''hi
there
''' def test_verbatim_attributes(): assert div(attr = '{
}').render() == \ '''
''' assert div(attr = raw('{
}')).render() == \ '''
''' dominate-2.9.0/tests/test_svg.py000066400000000000000000000234201452177110200166750ustar00rootroot00000000000000import dominate.svg from dominate.tags import * from dominate.svg import * import pytest def base(): return svg( width=120, height=120, viewBox="0 0 120 120", version="1.1", xmlns="http://www.w3.org/2000/svg", xmlns_xlink="http://www.w3.org/1999/xlink" ) def get_expected(func): return func.__doc__.replace('\n ', '\n').strip() def output_test(func): def wrapper(): with base() as result: func() assert result.render() == get_expected(func) return wrapper # Note, all tests produce working examples. The expected results can be pasted into https://jsfiddle.net/api/mdn/ @output_test def test_animate(): ''' ''' with rect(x="10", y="10", width="100", height="100"): animate(attributeType="XML", attributeName="x", _from="-100", to="120", dur="10s", repeatCount="indefinite") @output_test def test_animate_motion(): ''' ''' path(d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110", stroke="lightgrey", stroke_width="2", fill="none", id="theMotionPath") circle(cx=10, cy=110, r=3, fill="lightgrey") circle(cx=110, cy=10, r=3, fill="lightgrey") with circle(cx="", cy="", r="5", fill="red"): with animateMotion(dur="6s", repeatCount="indefinite"): mpath(xlink_href="#theMotionPath") @output_test def test_animate_transform(): ''' ''' with polygon(points="60,30 90,90, 30,90"): animateTransform(attributeName="transform", attributeType="XML", type="rotate", _from="0 60 70", to="360 60 70", dur="10s", repeatCount="indefinite") @output_test def test_circle(): ''' I am a circle ''' with circle(cx=50, cy=60, r=30, fill="black"): desc("I am a circle") @output_test def test_clip_path(): ''' ''' with clipPath(id="MyClip"): circle(cx="20", cy="30", r="40") path(id="heart", d="M10,30 A20,20,0,0,1,50,30 A20,20,0,0,1,90,30 Q90,60,50,90 Q10,60,10,30 Z") use(clip_path="url(#MyClip)", xlink_href="#heart", fill="red") @output_test def test_defs(): ''' ''' with defs(): circle(cx=50, cy=60, r=30, fill="black") use(x="5", y="5", xlink_href="#myCircle") @output_test def test_ellipse(): ''' ''' ellipse(cx="100", cy="50", rx="100", ry="50" ) filter_names = ['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feFlood', 'feGaussianBlur', 'feImage', 'feMerge', 'feMorphology', 'feOffset', 'feSpecularLighting', 'feTile', 'feTurbulence', 'feDistantLight', 'fePointLight', 'feSpotLight'] def test_filters(): for name in filter_names: attr = getattr(dominate.svg, name) with filter() as f: attr() expected = '''\n <{0}>\n'''.format(name) assert f.render() == expected @output_test def test_g(): ''' ''' with g(fill="white", stroke="green", stroke_width="5"): circle(rx=40, ry=40, r=25) circle(rx=60, ry=60, r=25) @output_test def test_line(): ''' ''' line(x0='0', x1='50', y0='0', y1='50', stroke='red') @output_test def test_linear_gradient(): ''' ''' with defs(): with linearGradient(id="myGradient", gradientTransform="rotate(90)"): stop(offset="5%", stop_color="gold") stop(offset="95%", stop_color="red") circle(rx=50, ry=50, r=40, fill="url('#myGradient')") @output_test def test_marker(): ''' ''' with defs(): with marker(id="arrow", viewBox="0 0 10 10", refX="5", refY="5", markerWidth="6", markerHeight="6", orient="auto-start-reverse"): path(d="M 0 0 L 10 5 L 0 10 z") polyline(points="10,10 10,90 90,90", fill="none", stroke="black", marker_start="url(#arrow)", marker_end="url(#arrow)") @output_test def test_mask(): ''' ''' with mask(id="myMask"): rect(x="0", y="0", width="100", height="100", fill="white") path(d="M10,35 A20,20,0,0,1,50,35 A20,20,0,0,1,90,35 Q90,65,50,95 Q10,65,10,35 Z", fill="black" ) polygon(points="-10,110 110,110 110,-10", fill="orange") circle(cx=50, cy=50, r=50, mask="url(#myMask)") def test_pattern(): ''' ''' with svg(viewBox="0 0 230 100") as result: with defs(): with pattern(id="star", viewBox="0 0 10 10", width="10%", height="10%"): polygon(points="0,0 2,5 0,10 5,8 10,10 8,5 10,0 5,2") circle(cx=50, cy=50, r=50, fill="url(#star)") circle(cx=180, cy=50, r=50, fill="none", stroke_width=20, stroke="url(#star)") assert result.render() == get_expected(test_pattern) @output_test def test_radial_gradient(): ''' ''' with defs(): with radialGradient(id="myGradient"): stop(offset="10%", stop_color="gold") stop(offset="95%", stop_color="red") circle(cx=50, cy=5, r=50, fill="url(#myGradient)") dominate-2.9.0/tests/test_utils.py000066400000000000000000000021511452177110200172340ustar00rootroot00000000000000import dominate from dominate.tags import * from dominate import util def test_context(): id1 = dominate.dom_tag._get_thread_context() id2 = dominate.dom_tag._get_thread_context() assert id1 == id2 def test_include(): import os try: f = open('_test_include.deleteme', 'w') f.write('Hello World') f.close() d = div() d += util.include('_test_include.deleteme') assert d.render() == '
Hello World
' finally: try: os.remove('_test_include.deleteme') except: pass def test_system(): d = div() d += util.system('echo Hello World') assert d.render().replace('\r\n', '\n') == '
Hello World\n
' def test_unescape(): assert util.unescape('&<> ') == '&<> ' def test_url(): assert util.url_escape('hi there?') == 'hi%20there%3F' assert util.url_unescape('hi%20there%3f') == 'hi there?' def test_container(): d = div() with d: with util.container(): pass assert d.render() == '
' d = div() with d: with util.container(): h1('a') assert d.render() == \ '''

a

'''