django-components 0.134__tar.gz → 0.136__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 (85) hide show
  1. {django_components-0.134/src/django_components.egg-info → django_components-0.136}/PKG-INFO +54 -4
  2. {django_components-0.134 → django_components-0.136}/README.md +53 -3
  3. {django_components-0.134 → django_components-0.136}/pyproject.toml +1 -1
  4. {django_components-0.134 → django_components-0.136}/src/django_components/__init__.py +5 -0
  5. {django_components-0.134 → django_components-0.136}/src/django_components/app_settings.py +2 -1
  6. django_components-0.136/src/django_components/attributes.py +441 -0
  7. {django_components-0.134 → django_components-0.136}/src/django_components/component.py +12 -102
  8. {django_components-0.134 → django_components-0.136}/src/django_components/component_media.py +10 -4
  9. {django_components-0.134 → django_components-0.136}/src/django_components/extension.py +6 -1
  10. django_components-0.136/src/django_components/extensions/defaults.py +157 -0
  11. {django_components-0.134 → django_components-0.136}/src/django_components/util/tag_parser.py +0 -7
  12. {django_components-0.134 → django_components-0.136}/src/django_components/util/testing.py +0 -10
  13. {django_components-0.134 → django_components-0.136/src/django_components.egg-info}/PKG-INFO +54 -4
  14. {django_components-0.134 → django_components-0.136}/src/django_components.egg-info/SOURCES.txt +1 -1
  15. django_components-0.134/src/django_components/attributes.py +0 -118
  16. django_components-0.134/src/django_components/util/validation.py +0 -130
  17. {django_components-0.134 → django_components-0.136}/LICENSE +0 -0
  18. {django_components-0.134 → django_components-0.136}/MANIFEST.in +0 -0
  19. {django_components-0.134 → django_components-0.136}/setup.cfg +0 -0
  20. {django_components-0.134 → django_components-0.136}/src/django_components/apps.py +0 -0
  21. {django_components-0.134 → django_components-0.136}/src/django_components/autodiscovery.py +0 -0
  22. {django_components-0.134 → django_components-0.136}/src/django_components/cache.py +0 -0
  23. {django_components-0.134 → django_components-0.136}/src/django_components/commands/__init__.py +0 -0
  24. {django_components-0.134 → django_components-0.136}/src/django_components/commands/components.py +0 -0
  25. {django_components-0.134 → django_components-0.136}/src/django_components/commands/create.py +0 -0
  26. {django_components-0.134 → django_components-0.136}/src/django_components/commands/ext.py +0 -0
  27. {django_components-0.134 → django_components-0.136}/src/django_components/commands/ext_list.py +0 -0
  28. {django_components-0.134 → django_components-0.136}/src/django_components/commands/ext_run.py +0 -0
  29. {django_components-0.134 → django_components-0.136}/src/django_components/commands/list.py +0 -0
  30. {django_components-0.134 → django_components-0.136}/src/django_components/commands/startcomponent.py +0 -0
  31. {django_components-0.134 → django_components-0.136}/src/django_components/commands/upgrade.py +0 -0
  32. {django_components-0.134 → django_components-0.136}/src/django_components/commands/upgradecomponent.py +0 -0
  33. {django_components-0.134 → django_components-0.136}/src/django_components/compat/__init__.py +0 -0
  34. {django_components-0.134 → django_components-0.136}/src/django_components/compat/django.py +0 -0
  35. {django_components-0.134 → django_components-0.136}/src/django_components/component_registry.py +0 -0
  36. {django_components-0.134 → django_components-0.136}/src/django_components/components/__init__.py +0 -0
  37. {django_components-0.134 → django_components-0.136}/src/django_components/components/dynamic.py +0 -0
  38. {django_components-0.134 → django_components-0.136}/src/django_components/context.py +0 -0
  39. {django_components-0.134 → django_components-0.136}/src/django_components/dependencies.py +0 -0
  40. {django_components-0.134 → django_components-0.136}/src/django_components/expression.py +0 -0
  41. {django_components-0.134 → django_components-0.136}/src/django_components/extensions/__init__.py +0 -0
  42. {django_components-0.134 → django_components-0.136}/src/django_components/extensions/view.py +0 -0
  43. {django_components-0.134 → django_components-0.136}/src/django_components/finders.py +0 -0
  44. {django_components-0.134 → django_components-0.136}/src/django_components/library.py +0 -0
  45. {django_components-0.134 → django_components-0.136}/src/django_components/management/__init__.py +0 -0
  46. {django_components-0.134 → django_components-0.136}/src/django_components/management/commands/__init__.py +0 -0
  47. {django_components-0.134 → django_components-0.136}/src/django_components/management/commands/components.py +0 -0
  48. {django_components-0.134 → django_components-0.136}/src/django_components/management/commands/startcomponent.py +0 -0
  49. {django_components-0.134 → django_components-0.136}/src/django_components/management/commands/upgradecomponent.py +0 -0
  50. {django_components-0.134 → django_components-0.136}/src/django_components/middleware.py +0 -0
  51. {django_components-0.134 → django_components-0.136}/src/django_components/node.py +0 -0
  52. {django_components-0.134 → django_components-0.136}/src/django_components/perfutil/__init__.py +0 -0
  53. {django_components-0.134 → django_components-0.136}/src/django_components/perfutil/component.py +0 -0
  54. {django_components-0.134 → django_components-0.136}/src/django_components/perfutil/provide.py +0 -0
  55. {django_components-0.134 → django_components-0.136}/src/django_components/provide.py +0 -0
  56. {django_components-0.134 → django_components-0.136}/src/django_components/py.typed +0 -0
  57. {django_components-0.134 → django_components-0.136}/src/django_components/slots.py +0 -0
  58. {django_components-0.134 → django_components-0.136}/src/django_components/static/django_components/django_components.min.js +0 -0
  59. {django_components-0.134 → django_components-0.136}/src/django_components/tag_formatter.py +0 -0
  60. {django_components-0.134 → django_components-0.136}/src/django_components/template.py +0 -0
  61. {django_components-0.134 → django_components-0.136}/src/django_components/template_loader.py +0 -0
  62. {django_components-0.134 → django_components-0.136}/src/django_components/templatetags/__init__.py +0 -0
  63. {django_components-0.134 → django_components-0.136}/src/django_components/templatetags/component_tags.py +0 -0
  64. {django_components-0.134 → django_components-0.136}/src/django_components/testing.py +0 -0
  65. {django_components-0.134 → django_components-0.136}/src/django_components/types.py +0 -0
  66. {django_components-0.134 → django_components-0.136}/src/django_components/urls.py +0 -0
  67. {django_components-0.134 → django_components-0.136}/src/django_components/util/__init__.py +0 -0
  68. {django_components-0.134 → django_components-0.136}/src/django_components/util/cache.py +0 -0
  69. {django_components-0.134 → django_components-0.136}/src/django_components/util/command.py +0 -0
  70. {django_components-0.134 → django_components-0.136}/src/django_components/util/component_highlight.py +0 -0
  71. {django_components-0.134 → django_components-0.136}/src/django_components/util/context.py +0 -0
  72. {django_components-0.134 → django_components-0.136}/src/django_components/util/django_monkeypatch.py +0 -0
  73. {django_components-0.134 → django_components-0.136}/src/django_components/util/exception.py +0 -0
  74. {django_components-0.134 → django_components-0.136}/src/django_components/util/loader.py +0 -0
  75. {django_components-0.134 → django_components-0.136}/src/django_components/util/logger.py +0 -0
  76. {django_components-0.134 → django_components-0.136}/src/django_components/util/misc.py +0 -0
  77. {django_components-0.134 → django_components-0.136}/src/django_components/util/nanoid.py +0 -0
  78. {django_components-0.134 → django_components-0.136}/src/django_components/util/routing.py +0 -0
  79. {django_components-0.134 → django_components-0.136}/src/django_components/util/template_parser.py +0 -0
  80. {django_components-0.134 → django_components-0.136}/src/django_components/util/template_tag.py +0 -0
  81. {django_components-0.134 → django_components-0.136}/src/django_components/util/types.py +0 -0
  82. {django_components-0.134 → django_components-0.136}/src/django_components/util/weakref.py +0 -0
  83. {django_components-0.134 → django_components-0.136}/src/django_components.egg-info/dependency_links.txt +0 -0
  84. {django_components-0.134 → django_components-0.136}/src/django_components.egg-info/requires.txt +0 -0
  85. {django_components-0.134 → django_components-0.136}/src/django_components.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django_components
3
- Version: 0.134
3
+ Version: 0.136
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
@@ -233,9 +233,53 @@ class Calendar(Component):
233
233
  / %}
234
234
  ```
235
235
 
236
+ ### Granular HTML attributes
237
+
238
+ Use the [`{% html_attrs %}`](https://django-components.github.io/django-components/latest/concepts/fundamentals/html_attributes/) template tag to render HTML attributes.
239
+ It supports:
240
+
241
+ - Defining attributes as dictionaries
242
+ - Defining attributes as keyword arguments
243
+ - Merging attributes from multiple sources
244
+ - Boolean attributes
245
+ - Appending attributes
246
+ - Removing attributes
247
+ - Defining default attributes
248
+
249
+ ```django
250
+ <div
251
+ {% html_attrs
252
+ attrs
253
+ defaults:class="default-class"
254
+ class="extra-class"
255
+ %}
256
+ >
257
+ ```
258
+
259
+ `{% html_attrs %}` offers a Vue-like granular control over `class` and `style` HTML attributes,
260
+ where you can use a dictionary to manage each class name or style property separately.
261
+
262
+ ```django
263
+ {% html_attrs
264
+ class="foo bar"
265
+ class={"baz": True, "foo": False}
266
+ class="extra"
267
+ %}
268
+ ```
269
+
270
+ ```django
271
+ {% html_attrs
272
+ style="text-align: center; background-color: blue;"
273
+ style={"background-color": "green", "color": None, "width": False}
274
+ style="position: absolute; height: 12px;"
275
+ %}
276
+ ```
277
+
278
+ Read more about [HTML attributes](https://django-components.github.io/django-components/latest/concepts/fundamentals/html_attributes/).
279
+
236
280
  ### HTML fragment support
237
281
 
238
- `django-components` makes intergration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:
282
+ `django-components` makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:
239
283
 
240
284
  - Components's JS and CSS is loaded automatically when the fragment is inserted into the DOM.
241
285
 
@@ -315,13 +359,20 @@ Django-components functionality can be extended with "extensions". Extensions al
315
359
 
316
360
  - Tap into lifecycle events, such as when a component is created, deleted, or registered.
317
361
  - Add new attributes and methods to the components under an extension-specific nested class.
362
+ - Add custom CLI commands.
363
+ - Add custom URLs.
364
+
365
+ Some of the extensions include:
366
+
367
+ - [Django View integration](https://github.com/django-components/django-components/blob/master/src/django_components/extensions/view.py)
368
+ - [Component defaults](https://github.com/django-components/django-components/blob/master/src/django_components/extensions/defaults.py)
369
+ - [Pydantic integration (input validation)](https://github.com/django-components/djc-ext-pydantic)
318
370
 
319
371
  Some of the planned extensions include:
320
372
 
321
373
  - Caching
322
374
  - AlpineJS integration
323
375
  - Storybook integration
324
- - Pydantic validation
325
376
  - Component-level benchmarking with asv
326
377
 
327
378
  ### Simple testing
@@ -377,7 +428,6 @@ def test_my_table():
377
428
  ### Other features
378
429
 
379
430
  - Vue-like provide / inject system
380
- - Format HTML attributes with `{% html_attrs %}`
381
431
 
382
432
  ## Documentation
383
433
 
@@ -201,9 +201,53 @@ class Calendar(Component):
201
201
  / %}
202
202
  ```
203
203
 
204
+ ### Granular HTML attributes
205
+
206
+ Use the [`{% html_attrs %}`](https://django-components.github.io/django-components/latest/concepts/fundamentals/html_attributes/) template tag to render HTML attributes.
207
+ It supports:
208
+
209
+ - Defining attributes as dictionaries
210
+ - Defining attributes as keyword arguments
211
+ - Merging attributes from multiple sources
212
+ - Boolean attributes
213
+ - Appending attributes
214
+ - Removing attributes
215
+ - Defining default attributes
216
+
217
+ ```django
218
+ <div
219
+ {% html_attrs
220
+ attrs
221
+ defaults:class="default-class"
222
+ class="extra-class"
223
+ %}
224
+ >
225
+ ```
226
+
227
+ `{% html_attrs %}` offers a Vue-like granular control over `class` and `style` HTML attributes,
228
+ where you can use a dictionary to manage each class name or style property separately.
229
+
230
+ ```django
231
+ {% html_attrs
232
+ class="foo bar"
233
+ class={"baz": True, "foo": False}
234
+ class="extra"
235
+ %}
236
+ ```
237
+
238
+ ```django
239
+ {% html_attrs
240
+ style="text-align: center; background-color: blue;"
241
+ style={"background-color": "green", "color": None, "width": False}
242
+ style="position: absolute; height: 12px;"
243
+ %}
244
+ ```
245
+
246
+ Read more about [HTML attributes](https://django-components.github.io/django-components/latest/concepts/fundamentals/html_attributes/).
247
+
204
248
  ### HTML fragment support
205
249
 
206
- `django-components` makes intergration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:
250
+ `django-components` makes integration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:
207
251
 
208
252
  - Components's JS and CSS is loaded automatically when the fragment is inserted into the DOM.
209
253
 
@@ -283,13 +327,20 @@ Django-components functionality can be extended with "extensions". Extensions al
283
327
 
284
328
  - Tap into lifecycle events, such as when a component is created, deleted, or registered.
285
329
  - Add new attributes and methods to the components under an extension-specific nested class.
330
+ - Add custom CLI commands.
331
+ - Add custom URLs.
332
+
333
+ Some of the extensions include:
334
+
335
+ - [Django View integration](https://github.com/django-components/django-components/blob/master/src/django_components/extensions/view.py)
336
+ - [Component defaults](https://github.com/django-components/django-components/blob/master/src/django_components/extensions/defaults.py)
337
+ - [Pydantic integration (input validation)](https://github.com/django-components/djc-ext-pydantic)
286
338
 
287
339
  Some of the planned extensions include:
288
340
 
289
341
  - Caching
290
342
  - AlpineJS integration
291
343
  - Storybook integration
292
- - Pydantic validation
293
344
  - Component-level benchmarking with asv
294
345
 
295
346
  ### Simple testing
@@ -345,7 +396,6 @@ def test_my_table():
345
396
  ### Other features
346
397
 
347
398
  - Vue-like provide / inject system
348
- - Format HTML attributes with `{% html_attrs %}`
349
399
 
350
400
  ## Documentation
351
401
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.134"
7
+ version = "0.136"
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"]
@@ -5,6 +5,7 @@
5
5
  # NOTE: Some of the documentation is generated based on these exports
6
6
  # isort: off
7
7
  from django_components.app_settings import ContextBehavior, ComponentsSettings
8
+ from django_components.attributes import format_attributes, merge_attributes
8
9
  from django_components.autodiscovery import autodiscover, import_libraries
9
10
  from django_components.util.command import (
10
11
  CommandArg,
@@ -39,6 +40,7 @@ from django_components.extension import (
39
40
  OnComponentInputContext,
40
41
  OnComponentDataContext,
41
42
  )
43
+ from django_components.extensions.defaults import Default
42
44
  from django_components.extensions.view import ComponentView
43
45
  from django_components.library import TagProtectedError
44
46
  from django_components.node import BaseNode, template_tag
@@ -87,12 +89,15 @@ __all__ = [
87
89
  "component_formatter",
88
90
  "component_shorthand_formatter",
89
91
  "ContextBehavior",
92
+ "Default",
90
93
  "DynamicComponent",
91
94
  "EmptyTuple",
92
95
  "EmptyDict",
96
+ "format_attributes",
93
97
  "get_component_dirs",
94
98
  "get_component_files",
95
99
  "import_libraries",
100
+ "merge_attributes",
96
101
  "NotRegistered",
97
102
  "OnComponentClassCreatedContext",
98
103
  "OnComponentClassDeletedContext",
@@ -750,9 +750,10 @@ class InternalSettings:
750
750
  )
751
751
 
752
752
  # Prepend built-in extensions
753
+ from django_components.extensions.defaults import DefaultsExtension
753
754
  from django_components.extensions.view import ViewExtension
754
755
 
755
- extensions = [ViewExtension] + list(extensions)
756
+ extensions = [DefaultsExtension, ViewExtension] + list(extensions)
756
757
 
757
758
  # Extensions may be passed in either as classes or import strings.
758
759
  extension_instances: List["ComponentExtension"] = []
@@ -0,0 +1,441 @@
1
+ # Initial implementation based on attributes.py from django-web-components
2
+ # See https://github.com/Xzya/django-web-components/blob/b43eb0c832837db939a6f8c1980334b0adfdd6e4/django_web_components/templatetags/components.py # noqa: E501
3
+ # And https://github.com/Xzya/django-web-components/blob/b43eb0c832837db939a6f8c1980334b0adfdd6e4/django_web_components/attributes.py # noqa: E501
4
+
5
+ import re
6
+ from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence, Union
7
+
8
+ from django.template import Context
9
+ from django.utils.html import conditional_escape, format_html
10
+ from django.utils.safestring import SafeString, mark_safe
11
+
12
+ from django_components.node import BaseNode
13
+
14
+ ClassValue = Union[Sequence["ClassValue"], str, Dict[str, bool]]
15
+ StyleDict = Dict[str, Union[str, int, Literal[False], None]]
16
+ StyleValue = Union[Sequence["StyleValue"], str, StyleDict]
17
+
18
+
19
+ class HtmlAttrsNode(BaseNode):
20
+ """
21
+ Generate HTML attributes (`key="value"`), combining data from multiple sources,
22
+ whether its template variables or static text.
23
+
24
+ It is designed to easily merge HTML attributes passed from outside with the internal.
25
+ See how to in [Passing HTML attributes to components](../../guides/howto/passing_html_attrs/).
26
+
27
+ **Args:**
28
+
29
+ - `attrs` (dict, optional): Optional dictionary that holds HTML attributes. On conflict, overrides
30
+ values in the `default` dictionary.
31
+ - `default` (str, optional): Optional dictionary that holds HTML attributes. On conflict, is overriden
32
+ with values in the `attrs` dictionary.
33
+ - Any extra kwargs will be appended to the corresponding keys
34
+
35
+ The attributes in `attrs` and `defaults` are merged and resulting dict is rendered as HTML attributes
36
+ (`key="value"`).
37
+
38
+ Extra kwargs (`key=value`) are concatenated to existing keys. So if we have
39
+
40
+ ```python
41
+ attrs = {"class": "my-class"}
42
+ ```
43
+
44
+ Then
45
+
46
+ ```django
47
+ {% html_attrs attrs class="extra-class" %}
48
+ ```
49
+
50
+ will result in `class="my-class extra-class"`.
51
+
52
+ **Example:**
53
+ ```django
54
+ <div {% html_attrs
55
+ attrs
56
+ defaults:class="default-class"
57
+ class="extra-class"
58
+ data-id="123"
59
+ %}>
60
+ ```
61
+
62
+ renders
63
+
64
+ ```html
65
+ <div class="my-class extra-class" data-id="123">
66
+ ```
67
+
68
+ **See more usage examples in
69
+ [HTML attributes](../../concepts/fundamentals/html_attributes#examples-for-html_attrs).**
70
+ """
71
+
72
+ tag = "html_attrs"
73
+ end_tag = None # inline-only
74
+ allowed_flags = []
75
+
76
+ def render(
77
+ self,
78
+ context: Context,
79
+ attrs: Optional[Dict] = None,
80
+ defaults: Optional[Dict] = None,
81
+ **kwargs: Any,
82
+ ) -> SafeString:
83
+ # Merge
84
+ final_attrs = {}
85
+ final_attrs.update(defaults or {})
86
+ final_attrs.update(attrs or {})
87
+ final_attrs = merge_attributes(final_attrs, kwargs)
88
+
89
+ # Render to HTML attributes
90
+ return format_attributes(final_attrs)
91
+
92
+
93
+ def format_attributes(attributes: Mapping[str, Any]) -> str:
94
+ """
95
+ Format a dict of attributes into an HTML attributes string.
96
+
97
+ Read more about [HTML attributes](../../concepts/fundamentals/html_attributes).
98
+
99
+ **Example:**
100
+
101
+ ```python
102
+ format_attributes({"class": "my-class", "data-id": "123"})
103
+ ```
104
+
105
+ will return
106
+
107
+ ```py
108
+ 'class="my-class" data-id="123"'
109
+ ```
110
+ """
111
+ attr_list = []
112
+
113
+ for key, value in attributes.items():
114
+ if value is None or value is False:
115
+ continue
116
+ if value is True:
117
+ attr_list.append(conditional_escape(key))
118
+ else:
119
+ attr_list.append(format_html('{}="{}"', key, value))
120
+
121
+ return mark_safe(SafeString(" ").join(attr_list))
122
+
123
+
124
+ # TODO_V1 - Remove in v1, keep only `format_attributes` going forward
125
+ attributes_to_string = format_attributes
126
+ """
127
+ Deprecated. Use [`format_attributes`](../api#django_components.format_attributes) instead.
128
+ """
129
+
130
+
131
+ def merge_attributes(*attrs: Dict) -> Dict:
132
+ """
133
+ Merge a list of dictionaries into a single dictionary.
134
+
135
+ The dictionaries are treated as HTML attributes and are merged accordingly:
136
+
137
+ - If a same key is present in multiple dictionaries, the values are joined with a space
138
+ character.
139
+ - The `class` and `style` keys are handled specially, similar to
140
+ [how Vue does it](https://vuejs.org/api/render-function#mergeprops).
141
+
142
+ Read more about [HTML attributes](../../concepts/fundamentals/html_attributes).
143
+
144
+ **Example:**
145
+
146
+ ```python
147
+ merge_attributes(
148
+ {"my-attr": "my-value", "class": "my-class"},
149
+ {"my-attr": "extra-value", "data-id": "123"},
150
+ )
151
+ ```
152
+
153
+ will result in
154
+
155
+ ```python
156
+ {
157
+ "my-attr": "my-value extra-value",
158
+ "class": "my-class",
159
+ "data-id": "123",
160
+ }
161
+ ```
162
+
163
+ **The `class` attribute**
164
+
165
+ The `class` attribute can be given as a string, or a dictionary.
166
+
167
+ - If given as a string, it is used as is.
168
+ - If given as a dictionary, only the keys with a truthy value are used.
169
+
170
+ **Example:**
171
+
172
+ ```python
173
+ merge_attributes(
174
+ {"class": "my-class extra-class"},
175
+ {"class": {"truthy": True, "falsy": False}},
176
+ )
177
+ ```
178
+
179
+ will result in
180
+
181
+ ```python
182
+ {
183
+ "class": "my-class extra-class truthy",
184
+ }
185
+ ```
186
+
187
+ **The `style` attribute**
188
+
189
+ The `style` attribute can be given as a string, a list, or a dictionary.
190
+
191
+ - If given as a string, it is used as is.
192
+ - If given as a dictionary, it is converted to a style attribute string.
193
+
194
+ **Example:**
195
+
196
+ ```python
197
+ merge_attributes(
198
+ {"style": "color: red; background-color: blue;"},
199
+ {"style": {"background-color": "green", "color": False}},
200
+ )
201
+ ```
202
+
203
+ will result in
204
+
205
+ ```python
206
+ {
207
+ "style": "color: red; background-color: blue; background-color: green;",
208
+ }
209
+ ```
210
+ """
211
+ result: Dict = {}
212
+
213
+ classes: List[ClassValue] = []
214
+ styles: List[StyleValue] = []
215
+ for attrs_dict in attrs:
216
+ for key, value in attrs_dict.items():
217
+ if key == "class":
218
+ classes.append(value)
219
+ elif key == "style":
220
+ styles.append(value)
221
+ elif key in result:
222
+ # Other keys are concatenated with a space character as separator
223
+ # if given multiple times.
224
+ result[key] = str(result[key]) + " " + str(value)
225
+ else:
226
+ result[key] = value
227
+
228
+ # Style and class have special handling based on how Vue does it.
229
+ if classes:
230
+ result["class"] = normalize_class(classes)
231
+ if styles:
232
+ result["style"] = normalize_style(styles)
233
+
234
+ return result
235
+
236
+
237
+ def normalize_class(value: ClassValue) -> str:
238
+ """
239
+ Normalize a class value.
240
+
241
+ Class may be given as a string, a list, or a dictionary:
242
+
243
+ - If given as a string, it is used as is.
244
+ - If given as a dictionary, only the keys with a truthy value are used.
245
+ - If given as a list, each item is converted to a dict, the dicts are merged, and resolved as above.
246
+
247
+ If a class is given multiple times, the last value is used.
248
+
249
+ This is based on Vue's [`mergeProps` function](https://vuejs.org/api/render-function#mergeprops).
250
+
251
+ **Example:**
252
+
253
+ ```python
254
+ normalize_class([
255
+ "my-class other-class",
256
+ {"extra-class": True, "other-class": False}
257
+ ])
258
+ ```
259
+
260
+ will result in
261
+ ```python
262
+ "my-class extra-class"
263
+ ```
264
+
265
+ Where:
266
+ - `my-class` is used as is
267
+ - `extra-class` is used because it has a truthy value
268
+ - `other-class` is ignored because it's last value is falsy
269
+ """
270
+ res: Dict[str, bool] = {}
271
+ if isinstance(value, str):
272
+ return value.strip()
273
+ elif isinstance(value, (list, tuple)):
274
+ # List items may be strings, dicts, or other lists/tuples
275
+ for item in value:
276
+ # NOTE: One difference from Vue is that if a class is given multiple times,
277
+ # and the last value is falsy, then it will be removed.
278
+ # E.g.
279
+ # `{"class": ["my-class", "extra-class", {"extra-class": False}]}`
280
+ # will result in `class="my-class"`
281
+ # while in Vue it will result in `class="my-class extra-class"`
282
+ normalized = _normalize_class(item)
283
+ res.update(normalized)
284
+ elif isinstance(value, dict):
285
+ # Take only those keys whose value is truthy. So
286
+ # `{"class": True, "extra": False}` will result in `class="extra"`
287
+ # while
288
+ # `{"class": True, "extra": True}` will result in `class="class extra"`
289
+ res = value
290
+ else:
291
+ raise ValueError(f"Invalid class value: {value}")
292
+
293
+ res_str = ""
294
+ for key, val in res.items():
295
+ if val:
296
+ res_str += key + " "
297
+ return res_str.strip()
298
+
299
+
300
+ whitespace_re = re.compile(r"\s+")
301
+
302
+
303
+ # Similar to `normalize_class`, but returns a dict instead of a string.
304
+ def _normalize_class(value: ClassValue) -> Dict[str, bool]:
305
+ res: Dict[str, bool] = {}
306
+ if isinstance(value, str):
307
+ class_parts = whitespace_re.split(value)
308
+ res.update({part: True for part in class_parts if part})
309
+ elif isinstance(value, (list, tuple)):
310
+ # List items may be strings, dicts, or other lists/tuples
311
+ for item in value:
312
+ normalized = _normalize_class(item)
313
+ res.update(normalized)
314
+ elif isinstance(value, dict):
315
+ res = value
316
+ else:
317
+ raise ValueError(f"Invalid class value: {value}")
318
+ return res
319
+
320
+
321
+ def normalize_style(value: StyleValue) -> str:
322
+ """
323
+ Normalize a style value.
324
+
325
+ Style may be given as a string, a list, or a dictionary:
326
+
327
+ - If given as a string, it is parsed as an inline CSS style,
328
+ e.g. `"color: red; background-color: blue;"`.
329
+ - If given as a dictionary, it is assumed to be a dict of style properties,
330
+ e.g. `{"color": "red", "background-color": "blue"}`.
331
+ - If given as a list, each item may itself be a list, string, or a dict.
332
+ The items are converted to dicts and merged.
333
+
334
+ If a style property is given multiple times, the last value is used.
335
+
336
+ If, after merging, a style property has a literal `False` value, it is removed.
337
+
338
+ Properties with a value of `None` are ignored.
339
+
340
+ This is based on Vue's [`mergeProps` function](https://vuejs.org/api/render-function#mergeprops).
341
+
342
+ **Example:**
343
+
344
+ ```python
345
+ normalize_style([
346
+ "color: red; background-color: blue; width: 100px;",
347
+ {"color": "green", "background-color": None, "width": False},
348
+ ])
349
+ ```
350
+
351
+ will result in
352
+ ```python
353
+ "color: green; background-color: blue;"
354
+ ```
355
+
356
+ Where:
357
+ - `color: green` overwrites `color: red`
358
+ - `background-color": None` is ignored, so `background-color: blue` is used
359
+ - `width` is omitted because it is given with a `False` value
360
+ """
361
+ res: StyleDict = {}
362
+ if isinstance(value, str):
363
+ return value.strip()
364
+ elif isinstance(value, (list, tuple)):
365
+ # List items may be strings, dicts, or other lists/tuples
366
+ for item in value:
367
+ normalized = _normalize_style(item)
368
+ res.update(normalized)
369
+ elif isinstance(value, dict):
370
+ # Remove entries with `None` value
371
+ res = _normalize_style(value)
372
+ else:
373
+ raise ValueError(f"Invalid style value: {value}")
374
+
375
+ # By the time we get here, all `None` values have been removed.
376
+ # If the final dict has `None` or `False` values, they are removed, so those
377
+ # properties are not rendered.
378
+ res_parts = []
379
+ for key, val in res.items():
380
+ if val is not None and val is not False:
381
+ res_parts.append(f"{key}: {val};")
382
+ return " ".join(res_parts).strip()
383
+
384
+
385
+ def _normalize_style(value: StyleValue) -> StyleDict:
386
+ res: StyleDict = {}
387
+ if isinstance(value, str):
388
+ # Generate a dict of style properties from a string
389
+ normalized = parse_string_style(value)
390
+ res.update(normalized)
391
+ elif isinstance(value, (list, tuple)):
392
+ # List items may be strings, dicts, or other lists/tuples
393
+ for item in value:
394
+ normalized = _normalize_style(item)
395
+ res.update(normalized)
396
+ elif isinstance(value, dict):
397
+ # Skip assigning entries with `None` value
398
+ for key, val in value.items():
399
+ if val is not None:
400
+ res[key] = val
401
+ else:
402
+ raise ValueError(f"Invalid style value: {value}")
403
+ return res
404
+
405
+
406
+ # Match CSS comments `/* ... */`
407
+ style_comment_re = re.compile(r"/\*.*?\*/", re.DOTALL)
408
+ # Split CSS properties by semicolon, but not inside parentheses
409
+ list_delimiter_re = re.compile(r";(?![^(]*\))", re.DOTALL)
410
+ # Split CSS property name and value
411
+ property_delimiter_re = re.compile(r":(.+)", re.DOTALL)
412
+
413
+
414
+ def parse_string_style(css_text: str) -> StyleDict:
415
+ """
416
+ Parse a string of CSS style properties into a dictionary.
417
+
418
+ **Example:**
419
+
420
+ ```python
421
+ parse_string_style("color: red; background-color: blue; /* comment */")
422
+ ```
423
+
424
+ will result in
425
+
426
+ ```python
427
+ {"color": "red", "background-color": "blue"}
428
+ ```
429
+ """
430
+ # Remove comments
431
+ css_text = style_comment_re.sub("", css_text)
432
+
433
+ ret: StyleDict = {}
434
+
435
+ # Split by semicolon, but not inside parentheses
436
+ for item in list_delimiter_re.split(css_text):
437
+ if item:
438
+ parts = property_delimiter_re.split(item)
439
+ if len(parts) > 1:
440
+ ret[parts[0].strip()] = parts[1].strip()
441
+ return ret