11from __future__ import annotations
22
3- from collections .abc import Callable
43from dataclasses import dataclass
5- from enum import IntEnum
4+ from enum import Enum
65from pathlib import Path
76
8- from django .templatetags .static import static
9- from django .utils .html import format_html
10- from django .utils .html import format_html_join
11- from django .utils .safestring import SafeString
7+ from django .template .backends .django import Template
128
139from ._typing import override
1410
1511
16- class AssetType (IntEnum ):
17- CSS = 1
18- JS = 2
12+ class AssetType (Enum ):
13+ CSS = "css"
14+ JS = "js"
1915
16+ @property
17+ def ext (self ):
18+ return f".{ self .value } "
2019
21- @dataclass (frozen = True )
20+
21+ @dataclass (frozen = True , slots = True )
2222class Asset :
2323 path : Path
2424 type : AssetType
@@ -42,52 +42,12 @@ def from_path(cls, path: Path) -> Asset:
4242 return cls (path = path , type = asset_type )
4343
4444
45- class Registry :
46- def __init__ (self ) -> None :
47- self .assets : set [Asset ] = set ()
48-
49- def register (self , asset : Asset | Path ) -> None :
50- if isinstance (asset , Path ):
51- asset = Asset .from_path (asset )
52-
53- if not asset .exists ():
54- raise FileNotFoundError (f"Asset file not found: { asset .path } " )
55-
56- self .assets .add (asset )
57-
58- def clear (self ) -> None :
59- self .assets .clear ()
60-
61- def get_assets (self , asset_type : AssetType ) -> list [Asset ]:
62- assets = [asset for asset in self .assets if asset .type == asset_type ]
63- return self .sort_assets (assets )
64-
65- def sort_assets (
66- self ,
67- assets : list [Asset ],
68- * ,
69- key : Callable [[Asset ], str ] = lambda a : str (a .path ),
70- ) -> list [Asset ]:
71- return sorted (assets , key = key )
72-
73- def get_format_string (self , asset_type : AssetType ) -> str :
74- match asset_type :
75- case AssetType .CSS :
76- return '<link rel="stylesheet" href="{}" type="text/css">'
77- case AssetType .JS :
78- return '<script src="{}" type="text/javascript">'
79-
80- def render (self , asset_type : AssetType ) -> SafeString :
81- assets = self .get_assets (asset_type )
82-
83- if not assets :
84- return format_html ("" )
85-
86- return format_html_join (
87- "\n " ,
88- self .get_format_string (asset_type ),
89- ((static (str (asset .path )),) for asset in assets ),
90- )
91-
92-
93- registry = Registry ()
45+ def get_template_assets (template : Template ):
46+ assets : set [Asset ] = set ()
47+ template_path = Path (template .template .origin .name )
48+ for asset_type in AssetType :
49+ asset_path = template_path .with_suffix (asset_type .ext )
50+ if asset_path .exists ():
51+ asset = Asset .from_path (asset_path )
52+ assets .add (asset )
53+ return assets
0 commit comments