widget_selectioncontainer.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright (c) Jupyter Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. """SelectionContainer class.
  4. Represents a multipage container that can be used to group other widgets into
  5. pages.
  6. """
  7. from .widget_box import Box
  8. from .widget import register
  9. from .widget_core import CoreWidget
  10. from traitlets import Unicode, Dict, CInt, TraitError, validate
  11. from ipython_genutils.py3compat import unicode_type
  12. class _SelectionContainer(Box, CoreWidget):
  13. """Base class used to display multiple child widgets."""
  14. _titles = Dict(help="Titles of the pages").tag(sync=True)
  15. selected_index = CInt(
  16. help="""The index of the selected page. This is either an integer selecting a particular sub-widget, or None to have no widgets selected.""",
  17. allow_none=True
  18. ).tag(sync=True)
  19. @validate('selected_index')
  20. def _validated_index(self, proposal):
  21. if proposal.value is None or 0 <= proposal.value < len(self.children):
  22. return proposal.value
  23. else:
  24. raise TraitError('Invalid selection: index out of bounds')
  25. # Public methods
  26. def set_title(self, index, title):
  27. """Sets the title of a container page.
  28. Parameters
  29. ----------
  30. index : int
  31. Index of the container page
  32. title : unicode
  33. New title
  34. """
  35. # JSON dictionaries have string keys, so we convert index to a string
  36. index = unicode_type(int(index))
  37. self._titles[index] = title
  38. self.send_state('_titles')
  39. def get_title(self, index):
  40. """Gets the title of a container pages.
  41. Parameters
  42. ----------
  43. index : int
  44. Index of the container page
  45. """
  46. # JSON dictionaries have string keys, so we convert index to a string
  47. index = unicode_type(int(index))
  48. if index in self._titles:
  49. return self._titles[index]
  50. else:
  51. return None
  52. def _repr_keys(self):
  53. # We also need to include _titles in repr for reproducibility
  54. for key in super(_SelectionContainer, self)._repr_keys():
  55. yield key
  56. if self._titles:
  57. yield '_titles'
  58. @register
  59. class Accordion(_SelectionContainer):
  60. """Displays children each on a separate accordion page."""
  61. _view_name = Unicode('AccordionView').tag(sync=True)
  62. _model_name = Unicode('AccordionModel').tag(sync=True)
  63. @register
  64. class Tab(_SelectionContainer):
  65. """Displays children each on a separate accordion tab."""
  66. _view_name = Unicode('TabView').tag(sync=True)
  67. _model_name = Unicode('TabModel').tag(sync=True)