Merge branch 'master' into python3
[wrw.git] / wrw / sp / xhtml.py
CommitLineData
62551769
FT
1import xml.dom.minidom, io
2from . import cons as _cons
3from . import util
ff79cdbf
FT
4dom = xml.dom.minidom.getDOMImplementation()
5
62551769
FT
6ns = "http://www.w3.org/1999/xhtml"
7doctype = "-//W3C//DTD XHTML 1.1//EN"
8dtd = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
ff79cdbf
FT
9
10class htmlelement(_cons.element):
11 def __todoc__(self):
12 doc = dom.createDocument(None, None, None)
13 doc.appendChild(dom.createDocumentType("html", doctype, dtd))
14 doc.appendChild(self.__todom__(doc))
15 return doc
16
a573465e 17class xhtmlcontext(_cons.context):
26648796 18 attrmap = {"klass": "class"}
a573465e
FT
19
20 def addattr(self, node, k, v):
26648796
FT
21 k = str(k)
22 node.attrs[self.attrmap.get(k, k)] = str(v)
a573465e 23
ff79cdbf 24def cons(ctx=None):
a573465e 25 if ctx is None: ctx = xhtmlcontext()
ff79cdbf
FT
26 return _cons.constructor(ns, htmlelement, ctx)
27
28def head(title=None, css=None):
29 h = cons()
30 head = h.head
31 if title:
32 head(h.title(title))
62551769 33 if isinstance(css, str) or isinstance(css, bytes):
ff79cdbf
FT
34 head(h.link(rel="stylesheet", type="text/css", href=css))
35 elif css:
36 for ss in css:
37 head(h.link(rel="stylesheet", type="text/css", href=ss))
38 return head
39
40class htmlformatter(util.formatter):
3e91bb19 41 allowshort = set(["br", "hr", "img", "input", "meta", "link"])
ff79cdbf
FT
42 def element(self, el, **extra):
43 if el.name in self.allowshort:
44 super(htmlformatter, self).element(el, **extra)
45 else:
46 self.longtag(el, **extra)
47
48class htmlindenter(util.indenter, htmlformatter):
49 pass
50
51def forreq(req, tree):
52 # XXX: Use proper Content-Type for clients accepting it.
53 req.ohead["Content-Type"] = "text/html; charset=utf-8"
dc437c45 54 buf = io.BytesIO()
ff79cdbf
FT
55 htmlindenter.output(buf, tree, doctype=(doctype, dtd), charset="utf-8")
56 return [buf.getvalue()]
57
58def xhtmlresp(callable):
59 def wrapper(req):
60 return forreq(req, callable(req))
61 return wrapper