django-components 0.66__tar.gz → 0.67__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 (44) hide show
  1. {django_components-0.66/src/django_components.egg-info → django_components-0.67}/PKG-INFO +24 -1
  2. {django_components-0.66 → django_components-0.67}/README.md +23 -0
  3. {django_components-0.66 → django_components-0.67}/pyproject.toml +1 -1
  4. django_components-0.67/src/django_components/app_settings.py +146 -0
  5. {django_components-0.66 → django_components-0.67}/src/django_components/component.py +70 -31
  6. django_components-0.67/src/django_components/context.py +122 -0
  7. django_components-0.67/src/django_components/logger.py +93 -0
  8. django_components-0.67/src/django_components/node.py +38 -0
  9. {django_components-0.66 → django_components-0.67}/src/django_components/slots.py +177 -152
  10. {django_components-0.66 → django_components-0.67}/src/django_components/templatetags/component_tags.py +39 -4
  11. {django_components-0.66 → django_components-0.67}/src/django_components/utils.py +14 -0
  12. {django_components-0.66 → django_components-0.67/src/django_components.egg-info}/PKG-INFO +24 -1
  13. {django_components-0.66 → django_components-0.67}/src/django_components.egg-info/SOURCES.txt +2 -0
  14. {django_components-0.66 → django_components-0.67}/tests/test_component.py +205 -0
  15. {django_components-0.66 → django_components-0.67}/tests/test_context.py +17 -2
  16. {django_components-0.66 → django_components-0.67}/tests/test_templatetags.py +24 -24
  17. django_components-0.66/src/django_components/app_settings.py +0 -41
  18. django_components-0.66/src/django_components/logger.py +0 -3
  19. {django_components-0.66 → django_components-0.67}/LICENSE +0 -0
  20. {django_components-0.66 → django_components-0.67}/setup.cfg +0 -0
  21. {django_components-0.66 → django_components-0.67}/src/django_components/__init__.py +0 -0
  22. {django_components-0.66 → django_components-0.67}/src/django_components/apps.py +0 -0
  23. {django_components-0.66 → django_components-0.67}/src/django_components/component_registry.py +0 -0
  24. {django_components-0.66 → django_components-0.67}/src/django_components/management/__init__.py +0 -0
  25. {django_components-0.66 → django_components-0.67}/src/django_components/management/commands/__init__.py +0 -0
  26. {django_components-0.66 → django_components-0.67}/src/django_components/management/commands/startcomponent.py +0 -0
  27. {django_components-0.66 → django_components-0.67}/src/django_components/management/commands/upgradecomponent.py +0 -0
  28. {django_components-0.66 → django_components-0.67}/src/django_components/middleware.py +0 -0
  29. {django_components-0.66 → django_components-0.67}/src/django_components/py.typed +0 -0
  30. {django_components-0.66 → django_components-0.67}/src/django_components/safer_staticfiles/__init__.py +0 -0
  31. {django_components-0.66 → django_components-0.67}/src/django_components/safer_staticfiles/apps.py +0 -0
  32. {django_components-0.66 → django_components-0.67}/src/django_components/template_loader.py +0 -0
  33. {django_components-0.66 → django_components-0.67}/src/django_components/templatetags/__init__.py +0 -0
  34. {django_components-0.66 → django_components-0.67}/src/django_components/types.py +0 -0
  35. {django_components-0.66 → django_components-0.67}/src/django_components.egg-info/dependency_links.txt +0 -0
  36. {django_components-0.66 → django_components-0.67}/src/django_components.egg-info/requires.txt +0 -0
  37. {django_components-0.66 → django_components-0.67}/src/django_components.egg-info/top_level.txt +0 -0
  38. {django_components-0.66 → django_components-0.67}/tests/test_autodiscover.py +0 -0
  39. {django_components-0.66 → django_components-0.67}/tests/test_component_as_view.py +0 -0
  40. {django_components-0.66 → django_components-0.67}/tests/test_dependency_rendering.py +0 -0
  41. {django_components-0.66 → django_components-0.67}/tests/test_registry.py +0 -0
  42. {django_components-0.66 → django_components-0.67}/tests/test_settings.py +0 -0
  43. {django_components-0.66 → django_components-0.67}/tests/test_startcomponent_command.py +0 -0
  44. {django_components-0.66 → django_components-0.67}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.66
3
+ Version: 0.67
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
@@ -47,6 +47,8 @@ Read on to learn about the details!
47
47
 
48
48
  ## Release notes
49
49
 
50
+ **Version 0.67** CHANGED the default way how context variables are resolved in slots. See the [documentation](#isolate-components-slots) for more details.
51
+
50
52
  🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of components to the new syntax automatically.
51
53
 
52
54
  This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
@@ -731,6 +733,27 @@ COMPONENTS = {
731
733
  }
732
734
  ```
733
735
 
736
+ ### Isolate components' slots
737
+
738
+ What variables should be available from inside a component slot?
739
+
740
+ By default, variables inside component slots are preferentially taken from the root context.
741
+ This is similar to [how Vue renders slots](https://vuejs.org/guide/components/slots.html#render-scope),
742
+ except that, if variable is not found in the root, then the surrounding context is searched too.
743
+
744
+ You can change this with the `slot_contet_behavior` setting. Options are:
745
+ - `"prefer_root"` - Default - as described above
746
+ - `"isolated"` - Same behavior as Vue - variables are taken ONLY from the root context
747
+ - `"allow_override"` - slot context variables are taken from its surroundings (default before v0.67)
748
+
749
+ ```python
750
+ COMPONENTS = {
751
+ "slot_context_behavior": "isolated",
752
+ }
753
+ ```
754
+
755
+ For further details and examples, see [SlotContextBehavior](https://github.com/EmilStenstrom/django-components/blob/master/src/django_components/app_settings.py#L12).
756
+
734
757
  ## Logging and debugging
735
758
 
736
759
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -20,6 +20,8 @@ Read on to learn about the details!
20
20
 
21
21
  ## Release notes
22
22
 
23
+ **Version 0.67** CHANGED the default way how context variables are resolved in slots. See the [documentation](#isolate-components-slots) for more details.
24
+
23
25
  🚨📢 **Version 0.5** CHANGES THE SYNTAX for components. `component_block` is now `component`, and `component` blocks need an ending `endcomponent` tag. The new `python manage.py upgradecomponent` command can be used to upgrade a directory (use --path argument to point to each dir) of components to the new syntax automatically.
24
26
 
25
27
  This change is done to simplify the API in anticipation of a 1.0 release of django_components. After 1.0 we intend to be stricter with big changes like this in point releases.
@@ -704,6 +706,27 @@ COMPONENTS = {
704
706
  }
705
707
  ```
706
708
 
709
+ ### Isolate components' slots
710
+
711
+ What variables should be available from inside a component slot?
712
+
713
+ By default, variables inside component slots are preferentially taken from the root context.
714
+ This is similar to [how Vue renders slots](https://vuejs.org/guide/components/slots.html#render-scope),
715
+ except that, if variable is not found in the root, then the surrounding context is searched too.
716
+
717
+ You can change this with the `slot_contet_behavior` setting. Options are:
718
+ - `"prefer_root"` - Default - as described above
719
+ - `"isolated"` - Same behavior as Vue - variables are taken ONLY from the root context
720
+ - `"allow_override"` - slot context variables are taken from its surroundings (default before v0.67)
721
+
722
+ ```python
723
+ COMPONENTS = {
724
+ "slot_context_behavior": "isolated",
725
+ }
726
+ ```
727
+
728
+ For further details and examples, see [SlotContextBehavior](https://github.com/EmilStenstrom/django-components/blob/master/src/django_components/app_settings.py#L12).
729
+
707
730
  ## Logging and debugging
708
731
 
709
732
  Django components supports [logging with Django](https://docs.djangoproject.com/en/5.0/howto/logging/#logging-how-to). This can help with troubleshooting.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.66"
7
+ version = "0.67"
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"]
@@ -0,0 +1,146 @@
1
+ from enum import Enum
2
+ from typing import Dict, List
3
+
4
+ from django.conf import settings
5
+
6
+
7
+ class ContextBehavior(str, Enum):
8
+ GLOBAL = "global"
9
+ ISOLATED = "isolated"
10
+
11
+
12
+ class SlotContextBehavior(str, Enum):
13
+ ALLOW_OVERRIDE = "allow_override"
14
+ """
15
+ Components CAN override the slot context variables passed from the outer scopes.
16
+ Contexts of deeper components take precedence over shallower ones.
17
+
18
+ Example:
19
+
20
+ Given this template
21
+
22
+ ```txt
23
+ {% component 'my_comp' %}
24
+ {{ my_var }}
25
+ {% endcomponent %}
26
+ ```
27
+
28
+ and this context passed to the render function (AKA root context)
29
+ ```py
30
+ { "my_var": 123 }
31
+ ```
32
+
33
+ Then if component "my_comp" defines context
34
+ ```py
35
+ { "my_var": 456 }
36
+ ```
37
+
38
+ Then since "my_comp" overrides the varialbe "my_var", so `{{ my_var }}` will equal `456`.
39
+ """
40
+
41
+ PREFER_ROOT = "prefer_root"
42
+ """
43
+ This is the same as "allow_override", except any variables defined in the root context
44
+ take precedence over anything else.
45
+
46
+ So if a variable is found in the root context, then root context is used.
47
+ Otherwise, the context of the component where the slot fill is located is used.
48
+
49
+ Example:
50
+
51
+ Given this template
52
+
53
+ ```txt
54
+ {% component 'my_comp' %}
55
+ {{ my_var_one }}
56
+ {{ my_var_two }}
57
+ {% endcomponent %}
58
+ ```
59
+
60
+ and this context passed to the render function (AKA root context)
61
+ ```py
62
+ { "my_var_one": 123 }
63
+ ```
64
+
65
+ Then if component "my_comp" defines context
66
+ ```py
67
+ { "my_var": 456, "my_var_two": "abc" }
68
+ ```
69
+
70
+ Then the rendered `{{ my_var_one }}` will equal to `123`, and `{{ my_var_two }}`
71
+ will equal to "abc".
72
+ """
73
+
74
+ ISOLATED = "isolated"
75
+ """
76
+ This setting makes the slots behave similar to Vue or React, where
77
+ the slot uses EXCLUSIVELY the root context, and nested components CANNOT
78
+ override context variables inside the slots.
79
+
80
+ Example:
81
+
82
+ Given this template
83
+
84
+ ```txt
85
+ {% component 'my_comp' %}
86
+ {{ my_var }}
87
+ {% endcomponent %}
88
+ ```
89
+
90
+ and this context passed to the render function (AKA root context)
91
+ ```py
92
+ { "my_var": 123 }
93
+ ```
94
+
95
+ Then if component "my_comp" defines context
96
+ ```py
97
+ { "my_var": 456 }
98
+ ```
99
+
100
+ Then the rendered `{{ my_var }}` will equal `123`.
101
+ """
102
+
103
+
104
+ class AppSettings:
105
+ @property
106
+ def settings(self) -> Dict:
107
+ return getattr(settings, "COMPONENTS", {})
108
+
109
+ @property
110
+ def AUTODISCOVER(self) -> bool:
111
+ return self.settings.get("autodiscover", True)
112
+
113
+ @property
114
+ def LIBRARIES(self) -> List:
115
+ return self.settings.get("libraries", [])
116
+
117
+ @property
118
+ def TEMPLATE_CACHE_SIZE(self) -> int:
119
+ return self.settings.get("template_cache_size", 128)
120
+
121
+ @property
122
+ def CONTEXT_BEHAVIOR(self) -> ContextBehavior:
123
+ raw_value = self.settings.get("context_behavior", ContextBehavior.GLOBAL.value)
124
+ return self._validate_context_behavior(raw_value)
125
+
126
+ def _validate_context_behavior(self, raw_value: ContextBehavior) -> ContextBehavior:
127
+ try:
128
+ return ContextBehavior(raw_value)
129
+ except ValueError:
130
+ valid_values = [behavior.value for behavior in ContextBehavior]
131
+ raise ValueError(f"Invalid context behavior: {raw_value}. Valid options are {valid_values}")
132
+
133
+ @property
134
+ def SLOT_CONTEXT_BEHAVIOR(self) -> SlotContextBehavior:
135
+ raw_value = self.settings.get("slot_context_behavior", SlotContextBehavior.PREFER_ROOT.value)
136
+ return self._validate_slot_context_behavior(raw_value)
137
+
138
+ def _validate_slot_context_behavior(self, raw_value: SlotContextBehavior) -> SlotContextBehavior:
139
+ try:
140
+ return SlotContextBehavior(raw_value)
141
+ except ValueError:
142
+ valid_values = [behavior.value for behavior in SlotContextBehavior]
143
+ raise ValueError(f"Invalid slot context behavior: {raw_value}. Valid options are {valid_values}")
144
+
145
+
146
+ app_settings = AppSettings()
@@ -2,7 +2,7 @@ import inspect
2
2
  import os
3
3
  import sys
4
4
  from pathlib import Path
5
- from typing import Any, ClassVar, Dict, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
5
+ from typing import Any, ClassVar, Dict, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
6
6
 
7
7
  from django.core.exceptions import ImproperlyConfigured
8
8
  from django.forms.widgets import Media, MediaDefiningClass
@@ -20,17 +20,24 @@ from django.views import View
20
20
  # way the two modules depend on one another.
21
21
  from django_components.component_registry import registry # NOQA
22
22
  from django_components.component_registry import AlreadyRegistered, ComponentRegistry, NotRegistered, register # NOQA
23
- from django_components.logger import logger
23
+ from django_components.context import (
24
+ capture_root_context,
25
+ get_root_context,
26
+ set_root_context,
27
+ set_slot_component_association,
28
+ )
29
+ from django_components.logger import logger, trace_msg
24
30
  from django_components.middleware import is_dependency_middleware_active
31
+ from django_components.node import walk_nodelist
25
32
  from django_components.slots import (
26
- DefaultFillContent,
27
- ImplicitFillNode,
28
- NamedFillContent,
29
- NamedFillNode,
33
+ DEFAULT_SLOT_KEY,
34
+ FillContent,
35
+ FillNode,
30
36
  SlotName,
37
+ SlotNode,
31
38
  render_component_template_with_slots,
32
39
  )
33
- from django_components.utils import search
40
+ from django_components.utils import gen_id, search
34
41
 
35
42
  RENDERED_COMMENT_TEMPLATE = "<!-- _RENDERED {name} -->"
36
43
 
@@ -185,12 +192,14 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
185
192
  def __init__(
186
193
  self,
187
194
  registered_name: Optional[str] = None,
195
+ component_id: Optional[str] = None,
188
196
  outer_context: Optional[Context] = None,
189
- fill_content: Union[DefaultFillContent, Iterable[NamedFillContent]] = (), # type: ignore
197
+ fill_content: Dict[str, FillContent] = {},
190
198
  ):
191
199
  self.registered_name: Optional[str] = registered_name
192
200
  self.outer_context: Context = outer_context or Context()
193
201
  self.fill_content = fill_content
202
+ self.component_id = component_id or gen_id()
194
203
 
195
204
  def __init_subclass__(cls, **kwargs: Any) -> None:
196
205
  cls.class_hash = hash(inspect.getfile(cls) + cls.__name__)
@@ -230,6 +239,12 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
230
239
  return mark_safe(f"<script>{self.js}</script>")
231
240
  return mark_safe("\n".join(self.media.render_js()))
232
241
 
242
+ # NOTE: When the template is taken from a file (AKA
243
+ # specified via `template_name`), then we leverage
244
+ # Django's template caching. This means that the same
245
+ # instance of Template is reused. This is important to keep
246
+ # in mind, because the implication is that we should
247
+ # treat Templates AND their nodelists as IMMUTABLE.
233
248
  def get_template(self, context: Mapping) -> Template:
234
249
  template_string = self.get_template_string(context)
235
250
  if template_string is not None:
@@ -246,7 +261,7 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
246
261
 
247
262
  def render(
248
263
  self,
249
- context_data: Dict[str, Any],
264
+ context_data: Union[Dict[str, Any], Context],
250
265
  slots_data: Optional[Dict[SlotName, str]] = None,
251
266
  escape_slots_content: bool = True,
252
267
  ) -> str:
@@ -255,14 +270,25 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
255
270
  context = context_data if isinstance(context_data, Context) else Context(context_data)
256
271
  template = self.get_template(context)
257
272
 
273
+ # Associate the slots with this component for this context
274
+ # This allows us to look up component-specific slot fills.
275
+ def on_node(node: Node) -> None:
276
+ if isinstance(node, SlotNode):
277
+ trace_msg("ASSOC", "SLOT", node.name, node.node_id, component_id=self.component_id)
278
+ set_slot_component_association(context, node.node_id, self.component_id)
279
+
280
+ walk_nodelist(template.nodelist, on_node)
281
+
258
282
  if slots_data:
259
283
  self._fill_slots(slots_data, escape_slots_content)
260
284
 
261
- return render_component_template_with_slots(template, context, self.fill_content, self.registered_name)
285
+ return render_component_template_with_slots(
286
+ self.component_id, template, context, self.fill_content, self.registered_name
287
+ )
262
288
 
263
289
  def render_to_response(
264
290
  self,
265
- context_data: Dict[str, Any],
291
+ context_data: Union[Dict[str, Any], Context],
266
292
  slots_data: Optional[Dict[SlotName, str]] = None,
267
293
  escape_slots_content: bool = True,
268
294
  *args: Any,
@@ -280,14 +306,13 @@ class Component(View, metaclass=SimplifiedInterfaceMediaDefiningClass):
280
306
  escape_content: bool = True,
281
307
  ) -> None:
282
308
  """Fill component slots outside of template rendering."""
283
- self.fill_content = [
284
- (
285
- slot_name,
309
+ self.fill_content = {
310
+ slot_name: FillContent(
286
311
  TextNode(escape(content) if escape_content else content),
287
312
  None,
288
313
  )
289
314
  for (slot_name, content) in slots_data.items()
290
- ]
315
+ }
291
316
 
292
317
 
293
318
  class ComponentNode(Node):
@@ -299,20 +324,16 @@ class ComponentNode(Node):
299
324
  context_args: List[FilterExpression],
300
325
  context_kwargs: Mapping[str, FilterExpression],
301
326
  isolated_context: bool = False,
302
- fill_nodes: Union[ImplicitFillNode, Iterable[NamedFillNode]] = (),
327
+ fill_nodes: Optional[List[FillNode]] = None,
328
+ component_id: Optional[str] = None,
303
329
  ) -> None:
330
+ self.component_id = component_id or gen_id()
304
331
  self.name_fexp = name_fexp
305
332
  self.context_args = context_args or []
306
333
  self.context_kwargs = context_kwargs or {}
307
334
  self.isolated_context = isolated_context
308
- self.fill_nodes = fill_nodes
309
- self.nodelist = self._create_nodelist(fill_nodes)
310
-
311
- def _create_nodelist(self, fill_nodes: Union[Iterable[Node], ImplicitFillNode]) -> NodeList:
312
- if isinstance(fill_nodes, ImplicitFillNode):
313
- return NodeList([fill_nodes])
314
- else:
315
- return NodeList(fill_nodes)
335
+ self.fill_nodes = fill_nodes or []
336
+ self.nodelist = NodeList(fill_nodes)
316
337
 
317
338
  def __repr__(self) -> str:
318
339
  return "<ComponentNode: {}. Contents: {!r}>".format(
@@ -321,46 +342,64 @@ class ComponentNode(Node):
321
342
  )
322
343
 
323
344
  def render(self, context: Context) -> str:
345
+ trace_msg("RENDR", "COMP", self.name_fexp, self.component_id)
346
+
324
347
  resolved_component_name = self.name_fexp.resolve(context)
325
348
  component_cls: Type[Component] = registry.get(resolved_component_name)
326
349
 
350
+ # If this is the outer-/top-most component node, then save the outer context,
351
+ # so it can be used by nested Slots.
352
+ capture_root_context(context)
353
+
327
354
  # Resolve FilterExpressions and Variables that were passed as args to the
328
355
  # component, then call component's context method
329
356
  # to get values to insert into the context
330
357
  resolved_context_args = [safe_resolve(arg, context) for arg in self.context_args]
331
358
  resolved_context_kwargs = {key: safe_resolve(kwarg, context) for key, kwarg in self.context_kwargs.items()}
332
359
 
333
- if isinstance(self.fill_nodes, ImplicitFillNode):
334
- fill_content = self.fill_nodes.nodelist
360
+ is_default_slot = len(self.fill_nodes) == 1 and self.fill_nodes[0].is_implicit
361
+ if is_default_slot:
362
+ fill_content: Dict[str, FillContent] = {DEFAULT_SLOT_KEY: FillContent(self.fill_nodes[0].nodelist, None)}
335
363
  else:
336
- fill_content = []
364
+ fill_content = {}
337
365
  for fill_node in self.fill_nodes:
338
366
  # Note that outer component context is used to resolve variables in
339
367
  # fill tag.
340
368
  resolved_name = fill_node.name_fexp.resolve(context)
341
369
  resolved_fill_alias = fill_node.resolve_alias(context, resolved_component_name)
342
- fill_content.append((resolved_name, fill_node.nodelist, resolved_fill_alias))
370
+ fill_content[resolved_name] = FillContent(fill_node.nodelist, resolved_fill_alias)
343
371
 
344
372
  component: Component = component_cls(
345
373
  registered_name=resolved_component_name,
346
374
  outer_context=context,
347
375
  fill_content=fill_content,
376
+ component_id=self.component_id,
348
377
  )
349
378
 
350
379
  component_context: dict = component.get_context_data(*resolved_context_args, **resolved_context_kwargs)
351
380
 
381
+ # Prevent outer context from leaking into the template of the component
352
382
  if self.isolated_context:
383
+ # Even if contexts are isolated, we still need to pass down the
384
+ # original context so variables in slots can be rendered using
385
+ # the original context.
386
+ root_ctx = get_root_context(context)
353
387
  context = context.new()
388
+ set_root_context(context, root_ctx)
389
+
354
390
  with context.update(component_context):
355
391
  rendered_component = component.render(context)
356
392
 
357
393
  if is_dependency_middleware_active():
358
- return RENDERED_COMMENT_TEMPLATE.format(name=resolved_component_name) + rendered_component
394
+ output = RENDERED_COMMENT_TEMPLATE.format(name=resolved_component_name) + rendered_component
359
395
  else:
360
- return rendered_component
396
+ output = rendered_component
397
+
398
+ trace_msg("RENDR", "COMP", self.name_fexp, self.component_id, "...Done!")
399
+ return output
361
400
 
362
401
 
363
402
  def safe_resolve(context_item: FilterExpression, context: Context) -> Any:
364
- """Resolve FilterExpressions and Variables in context if possible. Return other items unchanged."""
403
+ """Resolve FilterExpressions and Variables in context if possible. Return other items unchanged."""
365
404
 
366
405
  return context_item.resolve(context) if hasattr(context_item, "resolve") else context_item
@@ -0,0 +1,122 @@
1
+ """
2
+ This file centralizes various ways we use Django's Context class
3
+ pass data across components, nodes, slots, and contexts.
4
+
5
+ You can think of the Context as our storage system.
6
+ """
7
+
8
+ from copy import copy
9
+ from typing import TYPE_CHECKING, Optional
10
+
11
+ from django.template import Context
12
+
13
+ from django_components.logger import trace_msg
14
+
15
+ if TYPE_CHECKING:
16
+ from django_components.slots import FillContent
17
+
18
+
19
+ _FILLED_SLOTS_CONTENT_CONTEXT_KEY = "_DJANGO_COMPONENTS_FILLED_SLOTS"
20
+ _OUTER_CONTEXT_CONTEXT_KEY = "_DJANGO_COMPONENTS_OUTER_CONTEXT"
21
+ _SLOT_COMPONENT_ASSOC_KEY = "_DJANGO_COMPONENTS_SLOT_COMP_ASSOC"
22
+
23
+
24
+ def get_slot_fill(context: Context, component_id: str, slot_name: str) -> Optional["FillContent"]:
25
+ """
26
+ Use this function to obtain a slot fill from the current context.
27
+
28
+ See `set_slot_fill` for more details.
29
+ """
30
+ trace_msg("GET", "FILL", slot_name, component_id)
31
+ slot_key = (_FILLED_SLOTS_CONTENT_CONTEXT_KEY, component_id, slot_name)
32
+ return context.get(slot_key, None)
33
+
34
+
35
+ def set_slot_fill(context: Context, component_id: str, slot_name: str, value: "FillContent") -> None:
36
+ """
37
+ Use this function to set a slot fill for the current context.
38
+
39
+ Note that we make use of the fact that Django's Context is a stack - we can push and pop
40
+ extra contexts on top others.
41
+
42
+ For the slot fills to be pushed/popped wth stack layer, they need to have keys defined
43
+ directly on the Context object.
44
+ """
45
+ trace_msg("SET", "FILL", slot_name, component_id)
46
+ slot_key = (_FILLED_SLOTS_CONTENT_CONTEXT_KEY, component_id, slot_name)
47
+ context[slot_key] = value
48
+
49
+
50
+ def get_root_context(context: Context) -> Optional[Context]:
51
+ """
52
+ Use this function to get the root context.
53
+
54
+ Root context is the top-most context, AKA the context that was passed to
55
+ the initial `Template.render()`.
56
+ We pass through the root context to allow configure how slot fills should be rendered.
57
+
58
+ See the `SLOT_CONTEXT_BEHAVIOR` setting.
59
+ """
60
+ return context.get(_OUTER_CONTEXT_CONTEXT_KEY)
61
+
62
+
63
+ def set_root_context(context: Context, root_ctx: Context) -> None:
64
+ """
65
+ Use this function to set the root context.
66
+
67
+ Root context is the top-most context, AKA the context that was passed to
68
+ the initial `Template.render()`.
69
+ We pass through the root context to allow configure how slot fills should be rendered.
70
+
71
+ See the `SLOT_CONTEXT_BEHAVIOR` setting.
72
+ """
73
+ context.push({_OUTER_CONTEXT_CONTEXT_KEY: root_ctx})
74
+
75
+
76
+ def capture_root_context(context: Context) -> None:
77
+ """
78
+ Set the root context if it was not set before.
79
+
80
+ Root context is the top-most context, AKA the context that was passed to
81
+ the initial `Template.render()`.
82
+ We pass through the root context to allow configure how slot fills should be rendered.
83
+
84
+ See the `SLOT_CONTEXT_BEHAVIOR` setting.
85
+ """
86
+ root_ctx_already_defined = _OUTER_CONTEXT_CONTEXT_KEY in context
87
+ if not root_ctx_already_defined:
88
+ set_root_context(context, copy(context))
89
+
90
+
91
+ def set_slot_component_association(context: Context, slot_id: str, component_id: str) -> None:
92
+ """
93
+ Set association between a Slot and a Component in the current context.
94
+
95
+ We use SlotNodes to render slot fills. SlotNodes are created only at Template parse time.
96
+ However, when we are using components with slots in (another) template, we can render
97
+ the same component multiple time. So we can have multiple FillNodes intended to be used
98
+ with the same SlotNode.
99
+
100
+ So how do we tell the SlotNode which FillNode to render? We do so by tagging the ComponentNode
101
+ and FillNodes with a unique component_id, which ties them together. And then we tell SlotNode
102
+ which component_id to use to be able to find the correct Component/Fill.
103
+
104
+ We don't want to store this info on the Nodes themselves, as we need to treat them as
105
+ immutable due to caching of Templates by Django.
106
+
107
+ Hence, we use the Context to store the associations of SlotNode <-> Component for
108
+ the current context stack.
109
+ """
110
+ key = (_SLOT_COMPONENT_ASSOC_KEY, slot_id)
111
+ context[key] = component_id
112
+
113
+
114
+ def get_slot_component_association(context: Context, slot_id: str) -> str:
115
+ """
116
+ Given a slot ID, get the component ID that this slot is associated with
117
+ in this context.
118
+
119
+ See `set_slot_component_association` for more details.
120
+ """
121
+ key = (_SLOT_COMPONENT_ASSOC_KEY, slot_id)
122
+ return context[key]
@@ -0,0 +1,93 @@
1
+ import logging
2
+ import sys
3
+ from typing import Any, Dict, Literal, Optional
4
+
5
+ DEFAULT_TRACE_LEVEL_NUM = 5 # NOTE: MUST be lower than DEBUG which is 10
6
+
7
+ logger = logging.getLogger("django_components")
8
+ actual_trace_level_num = -1
9
+
10
+
11
+ def setup_logging() -> None:
12
+ # Check if "TRACE" level was already defined. And if so, use its log level.
13
+ # See https://docs.python.org/3/howto/logging.html#custom-levels
14
+ global actual_trace_level_num
15
+ log_levels = _get_log_levels()
16
+
17
+ if "TRACE" in log_levels:
18
+ actual_trace_level_num = log_levels["TRACE"]
19
+ else:
20
+ actual_trace_level_num = DEFAULT_TRACE_LEVEL_NUM
21
+ logging.addLevelName(actual_trace_level_num, "TRACE")
22
+
23
+
24
+ def _get_log_levels() -> Dict[str, int]:
25
+ # Use official API if possible
26
+ if sys.version_info >= (3, 11):
27
+ return logging.getLevelNamesMapping()
28
+ else:
29
+ return logging._nameToLevel.copy()
30
+
31
+
32
+ def trace(logger: logging.Logger, message: str, *args: Any, **kwargs: Any) -> None:
33
+ """
34
+ TRACE level logger.
35
+
36
+ To display TRACE logs, set the logging level to 5.
37
+
38
+ Example:
39
+ ```py
40
+ LOGGING = {
41
+ "version": 1,
42
+ "disable_existing_loggers": False,
43
+ "handlers": {
44
+ "console": {
45
+ "class": "logging.StreamHandler",
46
+ "stream": sys.stdout,
47
+ },
48
+ },
49
+ "loggers": {
50
+ "django_components": {
51
+ "level": 5,
52
+ "handlers": ["console"],
53
+ },
54
+ },
55
+ }
56
+ ```
57
+ """
58
+ if actual_trace_level_num == -1:
59
+ setup_logging()
60
+ if logger.isEnabledFor(actual_trace_level_num):
61
+ logger.log(actual_trace_level_num, message, *args, **kwargs)
62
+
63
+
64
+ def trace_msg(
65
+ action: Literal["PARSE", "ASSOC", "RENDR", "GET", "SET"],
66
+ node_type: Literal["COMP", "FILL", "SLOT", "IFSB", "N/A"],
67
+ node_name: str,
68
+ node_id: str,
69
+ msg: str = "",
70
+ component_id: Optional[str] = None,
71
+ ) -> None:
72
+ """
73
+ TRACE level logger with opinionated format for tracing interaction of components,
74
+ nodes, and slots. Formats messages like so:
75
+
76
+ `"ASSOC SLOT test_slot ID 0088 TO COMP 0087"`
77
+ """
78
+ msg_prefix = ""
79
+ if action == "ASSOC":
80
+ if not component_id:
81
+ raise ValueError("component_id must be set for the ASSOC action")
82
+ msg_prefix = f"TO COMP {component_id}"
83
+ elif action == "RENDR" and node_type != "COMP":
84
+ if not component_id:
85
+ raise ValueError("component_id must be set for the RENDER action")
86
+ msg_prefix = f"FOR COMP {component_id}"
87
+
88
+ msg_parts = [f"{action} {node_type} {node_name} ID {node_id}", *([msg_prefix] if msg_prefix else []), msg]
89
+ full_msg = " ".join(msg_parts)
90
+
91
+ # NOTE: When debugging tests during development, it may be easier to change
92
+ # this to `print()`
93
+ trace(logger, full_msg)