Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/js_asset/js.py: 53%
30 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1import json
2import warnings
4from django import VERSION
5from django.forms.utils import flatatt
6from django.templatetags.static import static
7from django.utils.html import format_html, html_safe, mark_safe
10__all__ = ("JS", "static")
13_sentinel = object()
16class JS:
17 """
18 Use this to insert a script tag via ``forms.Media`` containing additional
19 attributes (such as ``id`` and ``data-*`` for CSP-compatible data
20 injection.)::
22 forms.Media(js=[
23 JS('asset.js', {
24 'id': 'asset-script',
25 'data-answer': '"42"',
26 }),
27 ])
29 The rendered media tag (via ``{{ media.js }}`` or ``{{ media }}`` will
30 now contain a script tag as follows, without line breaks::
32 <script type="text/javascript" src="/static/asset.js"
33 data-answer=""42"" id="asset-script"></script>
35 The attributes are automatically escaped. The data attributes may now be
36 accessed inside ``asset.js``::
38 var answer = document.querySelector('#asset-script').dataset.answer;
39 """
41 def __init__(self, js, attrs=None, static=_sentinel):
42 self.js = js
43 self.attrs = attrs or {}
44 if static is not _sentinel:
45 warnings.warn(
46 "JS automatically determines whether it received an absolute"
47 " path or not. Stop passing the 'static' argument please.",
48 DeprecationWarning,
49 stacklevel=2,
50 )
52 def startswith(self, _):
53 # Masquerade as absolute path so that we are returned as-is.
54 return True
56 def __repr__(self):
57 return f"JS({self.js}, {json.dumps(self.attrs, sort_keys=True)})"
59 if VERSION >= (4, 1):
61 def __str__(self):
62 return format_html(
63 '<script src="{}"{}></script>',
64 self.js
65 if self.js.startswith(("http://", "https://", "/"))
66 else static(self.js),
67 mark_safe(flatatt(self.attrs)),
68 )
70 else:
72 def __html__(self):
73 js = (
74 self.js
75 if self.js.startswith(("http://", "https://", "/"))
76 else static(self.js)
77 )
78 return (
79 format_html('{}"{}', js, mark_safe(flatatt(self.attrs)))[:-1]
80 if self.attrs
81 else js
82 )
84 def __eq__(self, other):
85 if isinstance(other, JS):
86 return self.js == other.js and self.attrs == other.attrs
87 return self.js == other and not self.attrs
89 def __hash__(self):
90 return hash((self.js, json.dumps(self.attrs, sort_keys=True)))
93if VERSION >= (4, 1): 93 ↛ 94line 93 didn't jump to line 94, because the condition on line 93 was never true
94 JS = html_safe(JS)