/chromium-webcl/src/chrome/common/extensions/docs/server2/sidenav_data_source.py

https://bitbucket.org/peixuan/chromium_r197479_base
Python | 63 lines | 41 code | 9 blank | 13 comment | 6 complexity | b7d1d8472c40492abc87969abdee4e46 MD5 | raw file
  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. import copy
  5. import json
  6. import logging
  7. import compiled_file_system as compiled_fs
  8. from third_party.json_schema_compiler.model import UnixName
  9. class SidenavDataSource(object):
  10. """This class reads in and caches a JSON file representing the side navigation
  11. menu.
  12. """
  13. class Factory(object):
  14. def __init__(self, compiled_fs_factory, json_path):
  15. self._cache = compiled_fs_factory.Create(self._CreateSidenavDict,
  16. SidenavDataSource)
  17. self._json_path = json_path
  18. def Create(self, path):
  19. """Create a SidenavDataSource, binding it to |path|. |path| is the url
  20. of the page that is being rendered. It is used to determine which item
  21. in the sidenav should be highlighted.
  22. """
  23. return SidenavDataSource(self._cache, self._json_path, path)
  24. def _AddLevels(self, items, level):
  25. """Levels represent how deeply this item is nested in the sidenav. We
  26. start at 2 because the top <ul> is the only level 1 element.
  27. """
  28. for item in items:
  29. item['level'] = level
  30. if 'items' in item:
  31. self._AddLevels(item['items'], level + 1)
  32. def _CreateSidenavDict(self, json_path, json_str):
  33. items = json.loads(json_str)
  34. self._AddLevels(items, 2);
  35. return items
  36. def __init__(self, cache, json_path, path):
  37. self._cache = cache
  38. self._json_path = json_path
  39. self._file_name = path.split('/')[-1]
  40. def _AddSelected(self, items):
  41. for item in items:
  42. if item.get('fileName', '') == self._file_name:
  43. item['selected'] = True
  44. return True
  45. if 'items' in item:
  46. if self._AddSelected(item['items']):
  47. item['child_selected'] = True
  48. return True
  49. return False
  50. def get(self, key):
  51. sidenav = copy.deepcopy(self._cache.GetFromFile(
  52. '%s/%s_sidenav.json' % (self._json_path, key)))
  53. self._AddSelected(sidenav)
  54. return sidenav