Source code for uw.web.html.sorttable
"""Sort table routines.
This module makes it easy to use tables that can be sorted by clicking the
headers. It monkeypatches html.th and html.td. The changes are quite
innocuous and should not affect any other users of those classes.
The main routine provided by this module is :func:`render_sort_table`. In
order for this to work, the header_insert provided to
:func:`uw.local.webtools.web_main` should include the header_insert values
from this module.
"""
from collections import namedtuple
from ll.xist import xsc
from ll.xist.ns import html
from uw.web.html.format import make_table_format
header_insert = [
html.script (src="//odyssey.uwaterloo.ca/static/table-sort.js", type="text/javascript"),
html.link (href="//odyssey.uwaterloo.ca/static/table-sort.css", rel="stylesheet", type="text/css"),
]
[docs]class th (html.th):
"""Monkeypatch html.th to allow use of the data-sort attribute.
This class replaces html.th. It differs only in allowing the HTML 5
data-sort attribute to be specified.
"""
[docs] class Attrs (html.th.Attrs):
[docs] class data_sort (xsc.TextAttr):
xmlname = "data-sort"
html.th = th
[docs]class td (html.td):
"""Monkeypatch html.td to allow use of the data-sort-value attribute.
This class replaces html.td. It differs only in allowing the HTML 5
data-sort-value attribute to be specified.
"""
[docs] class Attrs (html.td.Attrs):
[docs] class data_sort_value (xsc.TextAttr):
xmlname = "data-sort-value"
html.td = td
[docs]class table_column (namedtuple ('table_column',
['col', 'head', 'content', 'attr', 'sort_style'])):
"""A namedtuple class representing the definition of a table column.
The namedtuple elements are col, head, content, attr, and sort_style.
The constructor of this class, however, allows omitting elements, in which
case the natural default will be used in each case. An additional
sort_order element may be provided, which should be a function from a data
row to a sort order value. This is a convenient way of adding the
data-sort-value attribute which could otherwise be provided by the attr
function.
"""
def __new__ (cls, col=None, head=None, content=None, attr=None, sort_order=None, sort_style=None):
if col is None:
col = html.col ()
if content is None:
content = lambda r: None
if attr is None:
attr = lambda r: {}
if sort_order is None:
complete_attr = attr
else:
def complete_attr (value):
result = attr (value)
result["data_sort_value"] = sort_order (value)
return result
if sort_style is None:
sort_style = 'string-ins'
elif sort_style == 'none':
sort_style = None
return super (table_column, cls).__new__ (cls, col, head, content, complete_attr, sort_style)