summaryrefslogtreecommitdiffstats
path: root/chrome/common/extensions/docs/server2/sidenav_data_source.py
blob: 679345636d98754b619173e8d0d684c96297dc9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import copy
import json
import logging

import compiled_file_system as compiled_fs
from third_party.json_schema_compiler.model import UnixName

# Increment this if the data model changes for SidenavDataSource.
_VERSION = 1

class SidenavDataSource(object):
  """This class reads in and caches a JSON file representing the side navigation
  menu.
  """
  class Factory(object):
    def __init__(self, compiled_fs_factory, json_path):
      self._cache = compiled_fs_factory.Create(self._CreateSidenavDict,
                                               SidenavDataSource,
                                               version=_VERSION)
      self._json_path = json_path

    def Create(self, path):
      """Create a SidenavDataSource, binding it to |path|. |path| is the url
      of the page that is being rendered. It is used to determine which item
      in the sidenav should be highlighted.
      """
      return SidenavDataSource(self._cache, self._json_path, path)

    def _AddLevels(self, items, level):
      """Levels represent how deeply this item is nested in the sidenav. We
      start at 2 because the top <ul> is the only level 1 element.
      """
      for item in items:
        item['level'] = level
        if 'items' in item:
          self._AddLevels(item['items'], level + 1)

    def _CreateSidenavDict(self, json_path, json_str):
      items = json.loads(json_str)
      self._AddLevels(items, 2);
      return items

  def __init__(self, cache, json_path, path):
    self._cache = cache
    self._json_path = json_path
    self._file_name = path.split('/')[-1]

  def _AddSelected(self, items):
    for item in items:
      if item.get('fileName', '') == self._file_name:
        item['selected'] = True
        return True
      if 'items' in item:
        if self._AddSelected(item['items']):
          item['child_selected'] = True
          return True
    return False

  def get(self, key):
    sidenav = copy.deepcopy(self._cache.GetFromFile(
        '%s/%s_sidenav.json' % (self._json_path, key)))
    self._AddSelected(sidenav)
    return sidenav