django-components 0.87__tar.gz → 0.89__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. {django_components-0.87/src/django_components.egg-info → django_components-0.89}/PKG-INFO +124 -2
  2. {django_components-0.87 → django_components-0.89}/README.md +123 -1
  3. {django_components-0.87 → django_components-0.89}/pyproject.toml +1 -1
  4. {django_components-0.87 → django_components-0.89}/src/django_components/component.py +8 -10
  5. django_components-0.89/src/django_components/component_registry.py +338 -0
  6. {django_components-0.87 → django_components-0.89/src/django_components.egg-info}/PKG-INFO +124 -2
  7. {django_components-0.87 → django_components-0.89}/tests/test_attributes.py +5 -8
  8. {django_components-0.87 → django_components-0.89}/tests/test_component.py +46 -2
  9. {django_components-0.87 → django_components-0.89}/tests/test_context.py +0 -4
  10. {django_components-0.87 → django_components-0.89}/tests/test_dependency_rendering.py +0 -4
  11. {django_components-0.87 → django_components-0.89}/tests/test_registry.py +58 -0
  12. {django_components-0.87 → django_components-0.89}/tests/test_templatetags.py +1 -8
  13. {django_components-0.87 → django_components-0.89}/tests/test_templatetags_component.py +12 -22
  14. {django_components-0.87 → django_components-0.89}/tests/test_templatetags_slot_fill.py +0 -17
  15. {django_components-0.87 → django_components-0.89}/tests/test_templatetags_templating.py +0 -12
  16. django_components-0.87/src/django_components/component_registry.py +0 -63
  17. {django_components-0.87 → django_components-0.89}/LICENSE +0 -0
  18. {django_components-0.87 → django_components-0.89}/setup.cfg +0 -0
  19. {django_components-0.87 → django_components-0.89}/src/django_components/__init__.py +0 -0
  20. {django_components-0.87 → django_components-0.89}/src/django_components/app_settings.py +0 -0
  21. {django_components-0.87 → django_components-0.89}/src/django_components/apps.py +0 -0
  22. {django_components-0.87 → django_components-0.89}/src/django_components/attributes.py +0 -0
  23. {django_components-0.87 → django_components-0.89}/src/django_components/autodiscover.py +0 -0
  24. {django_components-0.87 → django_components-0.89}/src/django_components/component_media.py +0 -0
  25. {django_components-0.87 → django_components-0.89}/src/django_components/context.py +0 -0
  26. {django_components-0.87 → django_components-0.89}/src/django_components/expression.py +0 -0
  27. {django_components-0.87 → django_components-0.89}/src/django_components/logger.py +0 -0
  28. {django_components-0.87 → django_components-0.89}/src/django_components/management/__init__.py +0 -0
  29. {django_components-0.87 → django_components-0.89}/src/django_components/management/commands/__init__.py +0 -0
  30. {django_components-0.87 → django_components-0.89}/src/django_components/management/commands/startcomponent.py +0 -0
  31. {django_components-0.87 → django_components-0.89}/src/django_components/management/commands/upgradecomponent.py +0 -0
  32. {django_components-0.87 → django_components-0.89}/src/django_components/middleware.py +0 -0
  33. {django_components-0.87 → django_components-0.89}/src/django_components/node.py +0 -0
  34. {django_components-0.87 → django_components-0.89}/src/django_components/provide.py +0 -0
  35. {django_components-0.87 → django_components-0.89}/src/django_components/py.typed +0 -0
  36. {django_components-0.87 → django_components-0.89}/src/django_components/safer_staticfiles/__init__.py +0 -0
  37. {django_components-0.87 → django_components-0.89}/src/django_components/safer_staticfiles/apps.py +0 -0
  38. {django_components-0.87 → django_components-0.89}/src/django_components/slots.py +0 -0
  39. {django_components-0.87 → django_components-0.89}/src/django_components/template_loader.py +0 -0
  40. {django_components-0.87 → django_components-0.89}/src/django_components/template_parser.py +0 -0
  41. {django_components-0.87 → django_components-0.89}/src/django_components/templatetags/__init__.py +0 -0
  42. {django_components-0.87 → django_components-0.89}/src/django_components/templatetags/component_tags.py +0 -0
  43. {django_components-0.87 → django_components-0.89}/src/django_components/types.py +0 -0
  44. {django_components-0.87 → django_components-0.89}/src/django_components/utils.py +0 -0
  45. {django_components-0.87 → django_components-0.89}/src/django_components.egg-info/SOURCES.txt +0 -0
  46. {django_components-0.87 → django_components-0.89}/src/django_components.egg-info/dependency_links.txt +0 -0
  47. {django_components-0.87 → django_components-0.89}/src/django_components.egg-info/requires.txt +0 -0
  48. {django_components-0.87 → django_components-0.89}/src/django_components.egg-info/top_level.txt +0 -0
  49. {django_components-0.87 → django_components-0.89}/tests/test_autodiscover.py +0 -0
  50. {django_components-0.87 → django_components-0.89}/tests/test_command_startcomponent.py +0 -0
  51. {django_components-0.87 → django_components-0.89}/tests/test_component_as_view.py +0 -0
  52. {django_components-0.87 → django_components-0.89}/tests/test_component_media.py +0 -0
  53. {django_components-0.87 → django_components-0.89}/tests/test_safer_staticfiles.py +0 -0
  54. {django_components-0.87 → django_components-0.89}/tests/test_settings.py +0 -0
  55. {django_components-0.87 → django_components-0.89}/tests/test_template_loader.py +0 -0
  56. {django_components-0.87 → django_components-0.89}/tests/test_template_parser.py +0 -0
  57. {django_components-0.87 → django_components-0.89}/tests/test_templatetags_provide.py +0 -0
  58. {django_components-0.87 → django_components-0.89}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.87
3
+ Version: 0.89
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Author-email: Emil Stenström <emil@emilstenstrom.se>
6
6
  License: MIT
@@ -53,6 +53,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
53
53
  - [Using single-file components](#using-single-file-components)
54
54
  - [Use components in templates](#use-components-in-templates)
55
55
  - [Use components outside of templates](#use-components-outside-of-templates)
56
+ - [Registering components](#registering-components)
56
57
  - [Use components as views](#use-components-as-views)
57
58
  - [Autodiscovery](#autodiscovery)
58
59
  - [Using slots in templates](#using-slots-in-templates)
@@ -139,7 +140,7 @@ You probably don't want this, as parts of your backend logic will be exposed, po
139
140
  As of _v0.27_, django-components ships with an additional installable app _django_components.**safer_staticfiles**_.
140
141
  It is a drop-in replacement for _django.contrib.staticfiles_.
141
142
  Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
142
- To use it, add it to INSTALLED*APPS and remove \_django.contrib.staticfiles*.
143
+ To use it, add it to INSTALLED_APPS and remove _django.contrib.staticfiles_.
143
144
 
144
145
  ```python
145
146
  INSTALLED_APPS = [
@@ -667,6 +668,127 @@ Note: slots content are automatically escaped by default to prevent XSS attacks.
667
668
 
668
669
  If you're planning on passing an HTML string, check Django's use of [`format_html`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.html.format_html) and [`mark_safe`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.safestring.mark_safe).
669
670
 
671
+ ## Registering components
672
+
673
+ In previous examples you could repeatedly see us using `@register()` to "register"
674
+ the components. In this section we dive deeper into what it actually means and how you can
675
+ manage (add or remove) components.
676
+
677
+ As a reminder, we may have a component like this:
678
+
679
+ ```python
680
+ from django_components import Component, register
681
+
682
+ @register("calendar")
683
+ class Calendar(Component):
684
+ template_name = "template.html"
685
+
686
+ # This component takes one parameter, a date string to show in the template
687
+ def get_context_data(self, date):
688
+ return {
689
+ "date": date,
690
+ }
691
+ ```
692
+
693
+ which we then render in the template as:
694
+
695
+ ```django
696
+ {% component "calendar" date="1970-01-01" %}
697
+ {% endcomponent %}
698
+ ```
699
+
700
+ As you can see, `@register` links up the component class
701
+ with the `{% component %}` template tag. So when the template tag comes across
702
+ a component called `"calendar"`, it can look up it's class and instantiate it.
703
+
704
+ ### What is ComponentRegistry
705
+
706
+ The `@register` decorator is a shortcut for working with the `ComponentRegistry`.
707
+
708
+ `ComponentRegistry` manages which components can be used in the template tags.
709
+
710
+ Each `ComponentRegistry` instance is associated with an instance
711
+ of Django's `Library`. And Libraries are inserted into Django template
712
+ using the `{% load %}` tags.
713
+
714
+ The `@register` decorator accepts an optional kwarg `registry`, which specifies, the `ComponentRegistry` to register components into.
715
+ If omitted, the default `ComponentRegistry` instance defined in django_components is used.
716
+
717
+ ```py
718
+ my_registry = ComponentRegistry()
719
+
720
+ @register(registry=my_registry)
721
+ class MyComponent(Component):
722
+ ...
723
+ ```
724
+
725
+ The default `ComponentRegistry` is associated with the `Library` that
726
+ you load when you call `{% load component_tags %}` inside your template, or when you
727
+ add `django_components.templatetags.component_tags` to the template builtins.
728
+
729
+ So when you register or unregister a component to/from a component registry,
730
+ then behind the scenes the registry automatically adds/removes the component's
731
+ template tags to/from the Library, so you can call the component from within the templates
732
+ such as `{% component "my_comp" %}`.
733
+
734
+ ### Working with ComponentRegistry
735
+
736
+ The default `ComponentRegistry` instance can be imported as:
737
+
738
+ ```py
739
+ from django_components import registry
740
+ ```
741
+
742
+ You can use the registry to manually add/remove/get components:
743
+
744
+ ```py
745
+ from django_components import registry
746
+
747
+ # Register components
748
+ registry.register("button", ButtonComponent)
749
+ registry.register("card", CardComponent)
750
+
751
+ # Get all or single
752
+ registry.all() # {"button": ButtonComponent, "card": CardComponent}
753
+ registry.get("card") # CardComponent
754
+
755
+ # Unregister single component
756
+ registry.unregister("card")
757
+
758
+ # Unregister all components
759
+ registry.clear()
760
+ ```
761
+
762
+ ### Registering components to custom ComponentRegistry
763
+
764
+ In rare cases, you may want to manage your own instance of `ComponentRegistry`,
765
+ or register components onto a different `Library` instance than the default one.
766
+
767
+ The `Library` instance can be set at instantiation of `ComponentRegistry`. If omitted,
768
+ then the default Library instance from django_components is used.
769
+
770
+ ```py
771
+ from django.template import Library
772
+ from django_components import ComponentRegistry
773
+
774
+ my_library = Library(...)
775
+ my_registry = ComponentRegistry(library=my_library)
776
+ ```
777
+
778
+ When you have defined your own `ComponentRegistry`, you can either register the components
779
+ with `my_registry.register()`, or pass the registry to the `@component.register()` decorator
780
+ via the `registry` kwarg:
781
+
782
+ ```py
783
+ from path.to.my.registry import my_registry
784
+
785
+ @register("my_component", registry=my_registry)
786
+ class MyComponent(Component):
787
+ ...
788
+ ```
789
+
790
+ NOTE: The Library instance can be accessed under `library` attribute of `ComponentRegistry`.
791
+
670
792
  ## Autodiscovery
671
793
 
672
794
  Every component that you want to use in the template with the `{% component %}` tag needs to be registered with the ComponentRegistry. Normally, we use the `@register` decorator for that:
@@ -29,6 +29,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
29
29
  - [Using single-file components](#using-single-file-components)
30
30
  - [Use components in templates](#use-components-in-templates)
31
31
  - [Use components outside of templates](#use-components-outside-of-templates)
32
+ - [Registering components](#registering-components)
32
33
  - [Use components as views](#use-components-as-views)
33
34
  - [Autodiscovery](#autodiscovery)
34
35
  - [Using slots in templates](#using-slots-in-templates)
@@ -115,7 +116,7 @@ You probably don't want this, as parts of your backend logic will be exposed, po
115
116
  As of _v0.27_, django-components ships with an additional installable app _django_components.**safer_staticfiles**_.
116
117
  It is a drop-in replacement for _django.contrib.staticfiles_.
117
118
  Its behavior is 100% identical except it ignores .py and .html files, meaning these will not end up on your static files server.
118
- To use it, add it to INSTALLED*APPS and remove \_django.contrib.staticfiles*.
119
+ To use it, add it to INSTALLED_APPS and remove _django.contrib.staticfiles_.
119
120
 
120
121
  ```python
121
122
  INSTALLED_APPS = [
@@ -643,6 +644,127 @@ Note: slots content are automatically escaped by default to prevent XSS attacks.
643
644
 
644
645
  If you're planning on passing an HTML string, check Django's use of [`format_html`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.html.format_html) and [`mark_safe`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.safestring.mark_safe).
645
646
 
647
+ ## Registering components
648
+
649
+ In previous examples you could repeatedly see us using `@register()` to "register"
650
+ the components. In this section we dive deeper into what it actually means and how you can
651
+ manage (add or remove) components.
652
+
653
+ As a reminder, we may have a component like this:
654
+
655
+ ```python
656
+ from django_components import Component, register
657
+
658
+ @register("calendar")
659
+ class Calendar(Component):
660
+ template_name = "template.html"
661
+
662
+ # This component takes one parameter, a date string to show in the template
663
+ def get_context_data(self, date):
664
+ return {
665
+ "date": date,
666
+ }
667
+ ```
668
+
669
+ which we then render in the template as:
670
+
671
+ ```django
672
+ {% component "calendar" date="1970-01-01" %}
673
+ {% endcomponent %}
674
+ ```
675
+
676
+ As you can see, `@register` links up the component class
677
+ with the `{% component %}` template tag. So when the template tag comes across
678
+ a component called `"calendar"`, it can look up it's class and instantiate it.
679
+
680
+ ### What is ComponentRegistry
681
+
682
+ The `@register` decorator is a shortcut for working with the `ComponentRegistry`.
683
+
684
+ `ComponentRegistry` manages which components can be used in the template tags.
685
+
686
+ Each `ComponentRegistry` instance is associated with an instance
687
+ of Django's `Library`. And Libraries are inserted into Django template
688
+ using the `{% load %}` tags.
689
+
690
+ The `@register` decorator accepts an optional kwarg `registry`, which specifies, the `ComponentRegistry` to register components into.
691
+ If omitted, the default `ComponentRegistry` instance defined in django_components is used.
692
+
693
+ ```py
694
+ my_registry = ComponentRegistry()
695
+
696
+ @register(registry=my_registry)
697
+ class MyComponent(Component):
698
+ ...
699
+ ```
700
+
701
+ The default `ComponentRegistry` is associated with the `Library` that
702
+ you load when you call `{% load component_tags %}` inside your template, or when you
703
+ add `django_components.templatetags.component_tags` to the template builtins.
704
+
705
+ So when you register or unregister a component to/from a component registry,
706
+ then behind the scenes the registry automatically adds/removes the component's
707
+ template tags to/from the Library, so you can call the component from within the templates
708
+ such as `{% component "my_comp" %}`.
709
+
710
+ ### Working with ComponentRegistry
711
+
712
+ The default `ComponentRegistry` instance can be imported as:
713
+
714
+ ```py
715
+ from django_components import registry
716
+ ```
717
+
718
+ You can use the registry to manually add/remove/get components:
719
+
720
+ ```py
721
+ from django_components import registry
722
+
723
+ # Register components
724
+ registry.register("button", ButtonComponent)
725
+ registry.register("card", CardComponent)
726
+
727
+ # Get all or single
728
+ registry.all() # {"button": ButtonComponent, "card": CardComponent}
729
+ registry.get("card") # CardComponent
730
+
731
+ # Unregister single component
732
+ registry.unregister("card")
733
+
734
+ # Unregister all components
735
+ registry.clear()
736
+ ```
737
+
738
+ ### Registering components to custom ComponentRegistry
739
+
740
+ In rare cases, you may want to manage your own instance of `ComponentRegistry`,
741
+ or register components onto a different `Library` instance than the default one.
742
+
743
+ The `Library` instance can be set at instantiation of `ComponentRegistry`. If omitted,
744
+ then the default Library instance from django_components is used.
745
+
746
+ ```py
747
+ from django.template import Library
748
+ from django_components import ComponentRegistry
749
+
750
+ my_library = Library(...)
751
+ my_registry = ComponentRegistry(library=my_library)
752
+ ```
753
+
754
+ When you have defined your own `ComponentRegistry`, you can either register the components
755
+ with `my_registry.register()`, or pass the registry to the `@component.register()` decorator
756
+ via the `registry` kwarg:
757
+
758
+ ```py
759
+ from path.to.my.registry import my_registry
760
+
761
+ @register("my_component", registry=my_registry)
762
+ class MyComponent(Component):
763
+ ...
764
+ ```
765
+
766
+ NOTE: The Library instance can be accessed under `library` attribute of `ComponentRegistry`.
767
+
646
768
  ## Autodiscovery
647
769
 
648
770
  Every component that you want to use in the template with the `{% component %}` tag needs to be registered with the ComponentRegistry. Normally, we use the `@register` decorator for that:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.87"
7
+ version = "0.89"
8
8
  requires-python = ">=3.8, <4.0"
9
9
  description = "A way to create simple reusable template components in Django."
10
10
  keywords = ["django", "components", "css", "js", "html"]
@@ -362,15 +362,11 @@ class Component(View, metaclass=ComponentMeta):
362
362
  slots: Optional[Mapping[SlotName, SlotContent]] = None,
363
363
  escape_slots_content: bool = True,
364
364
  ) -> str:
365
- # Allow to provide no args/kwargs
366
- args = args or []
367
- kwargs = kwargs or {}
368
-
369
- # Allow to provide no Context, so we can render component just with args + kwargs
370
- context_was_given = True
371
- if context is None:
372
- context = Context()
373
- context_was_given = False
365
+ # Allow to provide no args/kwargs/slots/context
366
+ args = args or [] # type: ignore[assignment]
367
+ kwargs = kwargs or {} # type: ignore[assignment]
368
+ slots = slots or {} # type: ignore[assignment]
369
+ context = context or Context()
374
370
 
375
371
  # Allow to provide a dict instead of Context
376
372
  # NOTE: This if/else is important to avoid nested Contexts,
@@ -387,9 +383,11 @@ class Component(View, metaclass=ComponentMeta):
387
383
  with context.update(context_data):
388
384
  template = self.get_template(context)
389
385
  _monkeypatch_template(template)
390
- if not context_was_given:
386
+
387
+ if context.template is None:
391
388
  # Associate the newly-created Context with a Template, otherwise we get
392
389
  # an error when we try to use `{% include %}` tag inside the template?
390
+ # See https://github.com/EmilStenstrom/django-components/issues/580
393
391
  context.template = template
394
392
  context.template_name = template.name
395
393
 
@@ -0,0 +1,338 @@
1
+ from typing import TYPE_CHECKING, Callable, Dict, List, NamedTuple, Optional, Set, Type, TypeVar
2
+
3
+ from django.template import Library
4
+
5
+ if TYPE_CHECKING:
6
+ from django_components.component import Component
7
+
8
+ _TComp = TypeVar("_TComp", bound=Type["Component"])
9
+
10
+
11
+ PROTECTED_TAGS = [
12
+ "component",
13
+ "component_dependencies",
14
+ "component_css_dependencies",
15
+ "component_js_dependencies",
16
+ "fill",
17
+ "html_attrs",
18
+ "provide",
19
+ "slot",
20
+ ]
21
+
22
+
23
+ class AlreadyRegistered(Exception):
24
+ pass
25
+
26
+
27
+ class NotRegistered(Exception):
28
+ pass
29
+
30
+
31
+ # Why do we store the tags with the component?
32
+ #
33
+ # Each component may be associated with two template tags - One for "block"
34
+ # and one for "inline" usage. E.g. in the following snippets, the template
35
+ # tags are `component` and `#component`:
36
+ #
37
+ # `{% component "abc" %}{% endcomponent %}`
38
+ # `{% #component "abc" %}`
39
+ #
40
+ # (NOTE: While `endcomponent` also looks like a template tag, we don't have to register
41
+ # it, because it simply marks the end of body.)
42
+ #
43
+ # With the component tag formatter (configurable tags per component class),
44
+ # each component may have a unique set of template tags.
45
+ #
46
+ # For user's convenience, we automatically add/remove the tags from Django's tag Library,
47
+ # when a component is (un)registered.
48
+ #
49
+ # Thus we need to remember which component used which template tags.
50
+ class ComponentRegistryEntry(NamedTuple):
51
+ cls: Type["Component"]
52
+ block_tag: str
53
+ inline_tag: str
54
+
55
+ @property
56
+ def tags(self) -> List[str]:
57
+ return [self.block_tag, self.inline_tag]
58
+
59
+
60
+ class ComponentRegistry:
61
+ """
62
+ Manages which components can be used in the template tags.
63
+
64
+ Each ComponentRegistry instance is associated with an instance
65
+ of Django's Library. So when you register or unregister a component
66
+ to/from a component registry, behind the scenes the registry
67
+ automatically adds/removes the component's template tag to/from
68
+ the Library.
69
+
70
+ The Library instance can be set at instantiation. If omitted, then
71
+ the default Library instance from django_components is used. The
72
+ Library instance can be accessed under `library` attribute.
73
+
74
+ Example:
75
+
76
+ ```py
77
+ # Use with default Library
78
+ registry = ComponentRegistry()
79
+
80
+ # Or a custom one
81
+ my_lib = Library()
82
+ registry = ComponentRegistry(library=my_lib)
83
+
84
+ # Usage
85
+ registry.register("button", ButtonComponent)
86
+ registry.register("card", CardComponent)
87
+ registry.all()
88
+ registry.clear()
89
+ registry.get()
90
+ ```
91
+ """
92
+
93
+ def __init__(self, library: Optional[Library] = None) -> None:
94
+ self._registry: Dict[str, ComponentRegistryEntry] = {} # component name -> component_entry mapping
95
+ self._tags: Dict[str, Set[str]] = {} # tag -> list[component names]
96
+ self._library = library
97
+
98
+ @property
99
+ def library(self) -> Library:
100
+ """
101
+ The template tag library with which the component registry is associated.
102
+ """
103
+ # Lazily use the default library if none was passed
104
+ if self._library is not None:
105
+ lib = self._library
106
+ else:
107
+ from django_components.templatetags.component_tags import register as tag_library
108
+
109
+ # For the default library, we want to protect our template tags from
110
+ # being overriden.
111
+ # On the other hand, if user provided their own Library instance,
112
+ # it is up to the user to use `mark_protected_tags` if they want
113
+ # to protect any tags.
114
+ mark_protected_tags(tag_library, PROTECTED_TAGS)
115
+ lib = self._library = tag_library
116
+ return lib
117
+
118
+ def register(self, name: str, component: Type["Component"]) -> None:
119
+ """
120
+ Register a component with this registry under the given name.
121
+
122
+ A component MUST be registered before it can be used in a template such as:
123
+ ```django
124
+ {% component "my_comp" %}{% endcomponent %}
125
+ ```
126
+
127
+ Raises `AlreadyRegistered` if a different component was already registered
128
+ under the same name.
129
+
130
+ Example:
131
+
132
+ ```py
133
+ registry.register("button", ButtonComponent)
134
+ ```
135
+ """
136
+ existing_component = self._registry.get(name)
137
+ if existing_component and existing_component.cls._class_hash != component._class_hash:
138
+ raise AlreadyRegistered('The component "%s" has already been registered' % name)
139
+
140
+ block_tag = "component"
141
+ inline_tag = "#component"
142
+
143
+ entry = ComponentRegistryEntry(
144
+ cls=component,
145
+ block_tag=block_tag,
146
+ inline_tag=inline_tag,
147
+ )
148
+
149
+ # Keep track of which components use which tags, because multiple components may
150
+ # use the same tag.
151
+ for tag in entry.tags:
152
+ if tag not in self._tags:
153
+ self._tags[tag] = set()
154
+ self._tags[tag].add(name)
155
+
156
+ self._registry[name] = entry
157
+
158
+ def unregister(self, name: str) -> None:
159
+ """
160
+ Unlinks a previously-registered component from the registry under the given name.
161
+
162
+ Once a component is unregistered, it CANNOT be used in a template anymore.
163
+ Following would raise an error:
164
+ ```django
165
+ {% component "my_comp" %}{% endcomponent %}
166
+ ```
167
+
168
+ Raises `NotRegistered` if the given name is not registered.
169
+
170
+ Example:
171
+
172
+ ```py
173
+ # First register component
174
+ registry.register("button", ButtonComponent)
175
+ # Then unregister
176
+ registry.unregister("button")
177
+ ```
178
+ """
179
+ # Validate
180
+ self.get(name)
181
+
182
+ entry = self._registry[name]
183
+
184
+ # Unregister the tag from library if this was the last component using this tag
185
+ for tag in entry.tags:
186
+ # Unlink component from tag
187
+ self._tags[tag].remove(name)
188
+
189
+ # Cleanup
190
+ is_tag_empty = not len(self._tags[tag])
191
+ if is_tag_empty:
192
+ del self._tags[tag]
193
+
194
+ # Do NOT unregister tag if it's protected
195
+ is_protected = is_tag_protected(self.library, tag)
196
+ if is_protected:
197
+ continue
198
+
199
+ # Unregister the tag from library if this was the last component using this tag
200
+ if is_tag_empty and tag in self.library.tags:
201
+ del self.library.tags[tag]
202
+
203
+ del self._registry[name]
204
+
205
+ def get(self, name: str) -> Type["Component"]:
206
+ """
207
+ Retrieve a component class registered under the given name.
208
+
209
+ Raises `NotRegistered` if the given name is not registered.
210
+
211
+ Example:
212
+
213
+ ```py
214
+ # First register component
215
+ registry.register("button", ButtonComponent)
216
+ # Then get
217
+ registry.get("button")
218
+ # > ButtonComponent
219
+ ```
220
+ """
221
+ if name not in self._registry:
222
+ raise NotRegistered('The component "%s" is not registered' % name)
223
+
224
+ return self._registry[name].cls
225
+
226
+ def all(self) -> Dict[str, Type["Component"]]:
227
+ """
228
+ Retrieve all registered component classes.
229
+
230
+ Example:
231
+
232
+ ```py
233
+ # First register components
234
+ registry.register("button", ButtonComponent)
235
+ registry.register("card", CardComponent)
236
+ # Then get all
237
+ registry.all()
238
+ # > {
239
+ # > "button": ButtonComponent,
240
+ # > "card": CardComponent,
241
+ # > }
242
+ ```
243
+ """
244
+ comps = {key: entry.cls for key, entry in self._registry.items()}
245
+ return comps
246
+
247
+ def clear(self) -> None:
248
+ """
249
+ Clears the registry, unregistering all components.
250
+
251
+ Example:
252
+
253
+ ```py
254
+ # First register components
255
+ registry.register("button", ButtonComponent)
256
+ registry.register("card", CardComponent)
257
+ # Then clear
258
+ registry.clear()
259
+ # Then get all
260
+ registry.all()
261
+ # > {}
262
+ ```
263
+ """
264
+ all_comp_names = list(self._registry.keys())
265
+ for comp_name in all_comp_names:
266
+ self.unregister(comp_name)
267
+
268
+ self._registry = {}
269
+ self._tags = {}
270
+
271
+
272
+ # This variable represents the global component registry
273
+ registry: ComponentRegistry = ComponentRegistry()
274
+ """
275
+ The default and global component registry. Use this instance to directly
276
+ register or remove components:
277
+
278
+ ```py
279
+ # Register components
280
+ registry.register("button", ButtonComponent)
281
+ registry.register("card", CardComponent)
282
+ # Get single
283
+ registry.get("button")
284
+ # Get all
285
+ registry.all()
286
+ # Unregister single
287
+ registry.unregister("button")
288
+ # Unregister all
289
+ registry.clear()
290
+ ```
291
+ """
292
+
293
+ # NOTE: Aliased so that the arg to `@register` can also be called `registry`
294
+ _the_registry = registry
295
+
296
+
297
+ def register(name: str, registry: Optional[ComponentRegistry] = None) -> Callable[[_TComp], _TComp]:
298
+ """
299
+ Class decorator to register a component.
300
+
301
+ Usage:
302
+
303
+ ```py
304
+ @register("my_component")
305
+ class MyComponent(Component):
306
+ ...
307
+ ```
308
+
309
+ Optionally specify which `ComponentRegistry` the component should be registered to by
310
+ setting the `registry` kwarg:
311
+
312
+ ```py
313
+ my_lib = django.template.Library()
314
+ my_reg = ComponentRegistry(library=my_lib)
315
+
316
+ @register("my_component", registry=my_reg)
317
+ class MyComponent(Component):
318
+ ...
319
+ ```
320
+ """
321
+ if registry is None:
322
+ registry = _the_registry
323
+
324
+ def decorator(component: _TComp) -> _TComp:
325
+ registry.register(name=name, component=component)
326
+ return component
327
+
328
+ return decorator
329
+
330
+
331
+ def mark_protected_tags(lib: Library, tags: List[str]) -> None:
332
+ # By marking the library as default,
333
+ lib._protected_tags = [*tags]
334
+
335
+
336
+ def is_tag_protected(lib: Library, tag: str) -> bool:
337
+ protected_tags = getattr(lib, "_protected_tags", [])
338
+ return tag in protected_tags