Home | History | Annotate | Download | only in server2
      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 
      5 from extensions_paths import PRIVATE_TEMPLATES
      6 from file_system import FileNotFoundError
      7 
      8 
      9 class TableOfContentsRenderer(object):
     10   '''Renders a table of contents pulled from a list of DocumentSections
     11   returned from document_parser.ParseDocument.
     12 
     13   This performs key functionality of DocumentRenderer, pulled into its own
     14   class for testability.
     15   '''
     16 
     17   def __init__(self,
     18                host_file_system,
     19                compiled_fs_factory,
     20                template_renderer):
     21     self._templates = compiled_fs_factory.ForTemplates(host_file_system)
     22     self._template_renderer = template_renderer
     23 
     24   def Render(self, sections):
     25     '''Renders a list of DocumentSections |sections| and returns a tuple
     26     (text, warnings).
     27     '''
     28     path = '%stable_of_contents.html' % PRIVATE_TEMPLATES
     29     try:
     30       table_of_contents_template = self._templates.GetFromFile(path).Get()
     31     except FileNotFoundError:
     32       return '', ['%s not found' % path]
     33 
     34     def make_toc_items(entries):
     35       return [{
     36         'attributes':  [{'key': key, 'value': val}
     37                         for key, val in entry.attributes.iteritems()
     38                         if key != 'id'],
     39         'link':        entry.attributes.get('id', ''),
     40         'subheadings': make_toc_items(entry.entries),
     41         'title':       entry.name,
     42       } for entry in entries]
     43 
     44     toc_items = []
     45     for section in sections:
     46       items_for_section = make_toc_items(section.structure)
     47       if toc_items and items_for_section:
     48         items_for_section[0]['separator'] = True
     49       toc_items.extend(items_for_section)
     50 
     51     return self._template_renderer.Render(
     52         self._templates.GetFromFile(
     53             '%stable_of_contents.html' % PRIVATE_TEMPLATES).Get(),
     54         None,  # no request
     55         data_sources=('partials'),
     56         additional_context={'items': toc_items})
     57