| 1 |
#!/usr/bin/env python |
| 2 |
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai |
| 3 |
|
| 4 |
from itertools import count |
| 5 |
|
| 6 |
from docutils import nodes |
| 7 |
from sphinx.environment.adapters.toctree import TocTree |
| 8 |
|
| 9 |
id_counter = count() |
| 10 |
ID = 'sidebar-collapsible-toc' |
| 11 |
|
| 12 |
CSS = r''' |
| 13 |
ID li { |
| 14 |
list-style: none; |
| 15 |
margin-left: 0; |
| 16 |
padding-left: 0.2em; |
| 17 |
text-indent: -0.7em; |
| 18 |
} |
| 19 |
|
| 20 |
ID li.leaf-node { |
| 21 |
text-indent: 0; |
| 22 |
} |
| 23 |
|
| 24 |
ID li input[type=checkbox] { |
| 25 |
display: none; |
| 26 |
} |
| 27 |
|
| 28 |
ID li > label { |
| 29 |
cursor: pointer; |
| 30 |
} |
| 31 |
|
| 32 |
ID li > input[type=checkbox] ~ ul > li { |
| 33 |
display: none; |
| 34 |
} |
| 35 |
|
| 36 |
ID li > input[type=checkbox]:checked ~ ul > li { |
| 37 |
display: block; |
| 38 |
} |
| 39 |
|
| 40 |
ID li > input[type=checkbox]:checked + label:before { |
| 41 |
content: "\025bf"; |
| 42 |
} |
| 43 |
|
| 44 |
ID li > input[type=checkbox]:not(:checked) + label:before { |
| 45 |
content: "\025b8"; |
| 46 |
} |
| 47 |
'''.replace('ID', 'ul#' + ID) |
| 48 |
|
| 49 |
|
| 50 |
class checkbox(nodes.Element): |
| 51 |
pass |
| 52 |
|
| 53 |
|
| 54 |
def visit_checkbox(self, node): |
| 55 |
cid = node['ids'][0] |
| 56 |
node['classes'] = [] |
| 57 |
self.body.append(f'<input id="{cid}" type="checkbox" /><label for="{cid}"> </label>') |
| 58 |
|
| 59 |
|
| 60 |
def modify_li(li): |
| 61 |
sublist = li.first_child_matching_class(nodes.bullet_list) |
| 62 |
if sublist is None or li[sublist].first_child_matching_class(nodes.list_item) is None: |
| 63 |
if not li.get('classes'): |
| 64 |
li['classes'] = [] |
| 65 |
li['classes'].append('leaf-node') |
| 66 |
else: |
| 67 |
c = checkbox() |
| 68 |
c['ids'] = [f'collapse-checkbox-{next(id_counter)}'] |
| 69 |
li.insert(0, c) |
| 70 |
|
| 71 |
|
| 72 |
def create_toc(app, pagename): |
| 73 |
tt = TocTree(app.env) |
| 74 |
toctree = tt.get_toc_for(pagename, app.builder) |
| 75 |
if toctree is not None: |
| 76 |
subtree = toctree[toctree.first_child_matching_class(nodes.list_item)] |
| 77 |
bl = subtree.first_child_matching_class(nodes.bullet_list) |
| 78 |
if bl is None: |
| 79 |
return # Empty ToC |
| 80 |
subtree = subtree[bl] |
| 81 |
for li in subtree.traverse(nodes.list_item): |
| 82 |
modify_li(li) |
| 83 |
subtree['ids'] = [ID] |
| 84 |
return '<style>' + CSS + '</style>' + app.builder.render_partial(subtree)['fragment'] |
| 85 |
|
| 86 |
|
| 87 |
def add_html_context(app, pagename, templatename, context, *args): |
| 88 |
if 'toc' in context: |
| 89 |
context['toc'] = create_toc(app, pagename) or context['toc'] |
| 90 |
|
| 91 |
|
| 92 |
def setup(app): |
| 93 |
app.add_node(checkbox, html=(visit_checkbox, lambda *x: None)) |
| 94 |
app.connect('html-page-context', add_html_context) |