sidenav_data_source.py revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
1# Copyright (c) 2012 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
5import copy
6import json
7import logging
8
9import compiled_file_system as compiled_fs
10from file_system import FileNotFoundError
11from third_party.json_schema_compiler.model import UnixName
12
13class SidenavDataSource(object):
14  """This class reads in and caches a JSON file representing the side navigation
15  menu.
16  """
17  class Factory(object):
18    def __init__(self, cache_factory, json_path):
19      self._cache = cache_factory.Create(self._CreateSidenavDict,
20                                         compiled_fs.SIDENAV)
21      self._json_path = json_path
22
23    def Create(self, path):
24      """Create a SidenavDataSource, binding it to |path|. |path| is the url
25      of the page that is being rendered. It is used to determine which item
26      in the sidenav should be highlighted.
27      """
28      return SidenavDataSource(self._cache, self._json_path, path)
29
30    def _AddLevels(self, items, level):
31      """Levels represent how deeply this item is nested in the sidenav. We
32      start at 2 because the top <ul> is the only level 1 element.
33      """
34      for item in items:
35        item['level'] = level
36        if 'items' in item:
37          self._AddLevels(item['items'], level + 1)
38
39    def _CreateSidenavDict(self, json_path, json_str):
40      items = json.loads(json_str)
41      self._AddLevels(items, 2);
42      return items
43
44  def __init__(self, cache, json_path, path):
45    self._cache = cache
46    self._json_path = json_path
47    self._file_name = path.split('/')[-1]
48
49  def _AddSelected(self, items):
50    for item in items:
51      if item.get('fileName', '') == self._file_name:
52        item['selected'] = True
53        return True
54      if 'items' in item:
55        if self._AddSelected(item['items']):
56          item['child_selected'] = True
57          return True
58    return False
59
60  def get(self, key):
61    try:
62      sidenav = copy.deepcopy(self._cache.GetFromFile(
63          '%s/%s_sidenav.json' % (self._json_path, key)))
64      self._AddSelected(sidenav)
65      return sidenav
66    except FileNotFoundError as e:
67      logging.error('%s: Error reading sidenav "%s".' % (e, key))
68