domwidget.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright (c) Jupyter Development Team.
  2. # Distributed under the terms of the Modified BSD License.
  3. """Contains the DOMWidget class"""
  4. from traitlets import Unicode
  5. from .widget import Widget, widget_serialization
  6. from .trait_types import InstanceDict, TypedTuple
  7. from .widget_layout import Layout
  8. from .widget_style import Style
  9. class DOMWidget(Widget):
  10. """Widget that can be inserted into the DOM"""
  11. _model_name = Unicode('DOMWidgetModel').tag(sync=True)
  12. _dom_classes = TypedTuple(trait=Unicode(), help="CSS classes applied to widget DOM element").tag(sync=True)
  13. layout = InstanceDict(Layout).tag(sync=True, **widget_serialization)
  14. def add_class(self, className):
  15. """
  16. Adds a class to the top level element of the widget.
  17. Doesn't add the class if it already exists.
  18. """
  19. if className not in self._dom_classes:
  20. self._dom_classes = list(self._dom_classes) + [className]
  21. return self
  22. def remove_class(self, className):
  23. """
  24. Removes a class from the top level element of the widget.
  25. Doesn't remove the class if it doesn't exist.
  26. """
  27. if className in self._dom_classes:
  28. self._dom_classes = [c for c in self._dom_classes if c != className]
  29. return self
  30. def _repr_keys(self):
  31. for key in super(DOMWidget, self)._repr_keys():
  32. # Exclude layout if it had the default value
  33. if key == 'layout':
  34. value = getattr(self, key)
  35. if repr(value) == '%s()' % value.__class__.__name__:
  36. continue
  37. yield key
  38. # We also need to include _dom_classes in repr for reproducibility
  39. if self._dom_classes:
  40. yield '_dom_classes'