|
| 1 | +try: |
| 2 | + from django.forms import Script |
| 3 | +except ImportError: # pragma: no cover |
| 4 | + # Django < 5.2 backport |
| 5 | + from django.forms.utils import flatatt |
| 6 | + from django.templatetags.static import static |
| 7 | + from django.utils.html import format_html, html_safe |
| 8 | + |
| 9 | + @html_safe |
| 10 | + class MediaAsset: |
| 11 | + element_template = "{path}" |
| 12 | + |
| 13 | + def __init__(self, path, **attributes): |
| 14 | + self._path = path |
| 15 | + self.attributes = attributes |
| 16 | + |
| 17 | + def __eq__(self, other): |
| 18 | + # Compare the path only, to ensure performant comparison in Media.merge. |
| 19 | + return (self.__class__ is other.__class__ and self.path == other.path) or ( |
| 20 | + isinstance(other, str) and self._path == other |
| 21 | + ) |
| 22 | + |
| 23 | + def __hash__(self): |
| 24 | + # Hash the path only, to ensure performant comparison in Media.merge. |
| 25 | + return hash(self._path) |
| 26 | + |
| 27 | + def __str__(self): |
| 28 | + return format_html( |
| 29 | + self.element_template, |
| 30 | + path=self.path, |
| 31 | + attributes=flatatt(self.attributes), |
| 32 | + ) |
| 33 | + |
| 34 | + def __repr__(self): |
| 35 | + return f"{type(self).__qualname__}({self._path!r})" |
| 36 | + |
| 37 | + @property |
| 38 | + def path(self): |
| 39 | + if self._path.startswith(("http://", "https://", "/")): |
| 40 | + return self._path |
| 41 | + return static(self._path) |
| 42 | + |
| 43 | + class Script(MediaAsset): |
| 44 | + element_template = '<script src="{path}"{attributes}></script>' |
| 45 | + |
| 46 | + def __init__(self, src, **attributes): |
| 47 | + # Alter the signature to allow src to be passed as a keyword argument. |
| 48 | + super().__init__(src, **attributes) |
| 49 | + |
| 50 | + |
| 51 | +__all__ = ["ImportESModule"] |
| 52 | + |
| 53 | + |
| 54 | +class ImportESModule(Script): |
| 55 | + """ |
| 56 | + Import ES module inline via an importmap. |
| 57 | +
|
| 58 | + Usage: |
| 59 | + class MyForm(forms.Form): |
| 60 | + class Media: |
| 61 | + js = [ImportESModule("@sentry/browser")] |
| 62 | + """ |
| 63 | + |
| 64 | + # https://code.djangoproject.com/ticket/36353 |
| 65 | + element_template = "<script{attributes}>import '{path}'</script>" |
| 66 | + |
| 67 | + def __init__(self, src, **attributes): |
| 68 | + super().__init__(src, **attributes | {"type": "module"}) |
| 69 | + |
| 70 | + @property |
| 71 | + def path(self): |
| 72 | + return self._path |
0 commit comments