_properties.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. from collections import UserDict
  12. from taipy.common.config.common._template_handler import _TemplateHandler as _tpl
  13. from ..common._utils import _normalize_path
  14. from ..notification import EventOperation, Notifier, _make_event
  15. class _Properties(UserDict):
  16. __PROPERTIES_ATTRIBUTE_NAME = "properties"
  17. def __init__(self, entity_owner, **kwargs):
  18. super().__init__(**kwargs)
  19. self._entity_owner = entity_owner
  20. self._pending_changes = {}
  21. self._pending_deletions = set()
  22. def __setitem__(self, key, value):
  23. if key == "path":
  24. value = _normalize_path(value)
  25. super(_Properties, self).__setitem__(key, value)
  26. if hasattr(self, "_entity_owner"):
  27. event = _make_event(
  28. self._entity_owner,
  29. EventOperation.UPDATE,
  30. attribute_name=self.__PROPERTIES_ATTRIBUTE_NAME,
  31. attribute_value=value,
  32. )
  33. if not self._entity_owner._is_in_context:
  34. self._set_entity_owner(self._entity_owner)
  35. Notifier.publish(event)
  36. else:
  37. if key in self._pending_deletions:
  38. self._pending_deletions.remove(key)
  39. self._pending_changes[key] = value
  40. self._entity_owner._in_context_attributes_changed_collector.append(event)
  41. def __getitem__(self, key):
  42. return _tpl._replace_templates(super(_Properties, self).__getitem__(key))
  43. def __delitem__(self, key):
  44. super(_Properties, self).__delitem__(key)
  45. if hasattr(self, "_entity_owner"):
  46. event = _make_event(
  47. self._entity_owner,
  48. EventOperation.UPDATE,
  49. attribute_name=self.__PROPERTIES_ATTRIBUTE_NAME,
  50. attribute_value=None,
  51. )
  52. if not self._entity_owner._is_in_context:
  53. self._set_entity_owner(self._entity_owner)
  54. Notifier.publish(event)
  55. else:
  56. self._pending_changes.pop(key, None)
  57. self._pending_deletions.add(key)
  58. self._entity_owner._in_context_attributes_changed_collector.append(event)
  59. def _set_entity_owner(self, entity_owner):
  60. from ... import core as tp
  61. tp.set(entity_owner)