table_of_contents_renderer.py revision f2477e01787aa58f445919b809d89e252beef54f
1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5from extensions_paths import PRIVATE_TEMPLATES
6
7
8class TableOfContentsRenderer(object):
9  '''Renders a table of contents pulled from a list of DocumentSections
10  returned from document_parser.ParseDocument.
11
12  This performs key functionality of DocumentRenderer, pulled into its own
13  class for testability.
14  '''
15
16  def __init__(self, host_file_system, compiled_fs_factory):
17    self._templates = compiled_fs_factory.ForTemplates(host_file_system)
18
19  def Render(self, sections):
20    '''Renders a list of DocumentSections |sections| and returns a tuple
21    (text, warnings).
22    '''
23    table_of_contents_template = self._templates.GetFromFile(
24        '%s/table_of_contents.html' % PRIVATE_TEMPLATES).Get()
25
26    def make_toc_items(entries):
27      return [{
28        'attributes':  [(key, val) for key, val in entry.attributes.iteritems()
29                        if key != 'id'],
30        'link':        entry.attributes.get('id', ''),
31        'subheadings': make_toc_items(entry.entries),
32        'title':       entry.name,
33      } for entry in entries]
34
35    toc_items = []
36    for section in sections:
37      items_for_section = make_toc_items(section.structure)
38      if toc_items and items_for_section:
39        items_for_section[0]['separator'] = True
40      toc_items.extend(items_for_section)
41
42    table_of_contents = table_of_contents_template.Render({
43      'items': toc_items
44    })
45    return table_of_contents.text, table_of_contents.errors
46