33from __future__ import annotations
44
55import json
6+ from pathlib import Path
67from typing import TYPE_CHECKING , Any , Callable , Union , cast
78from urllib .parse import urlencode
89
910from django .http import HttpRequest
11+ from django .templatetags .static import static
1012from django .urls import reverse
11- from reactpy import component , hooks , html , utils
13+ from reactpy import component , hooks , html , utils , web
1214from reactpy .types import ComponentType , Key , VdomDict
1315
1416from reactpy_django .exceptions import ViewNotRegisteredError
2527 from reactpy_django .types import AsyncFormEvent , SyncFormEvent , ViewToComponentConstructor , ViewToIframeConstructor
2628
2729
30+ DjangoJS = web .export (
31+ web .module_from_file ("reactpy-django" , file = Path (__file__ ).parent / "static" / "reactpy_django" / "client.js" ),
32+ ("OnlyOnceJS" ),
33+ )
34+
35+
2836def view_to_component (
2937 view : Callable | View | str ,
3038 transforms : Sequence [Callable [[VdomDict ], Any ]] = (),
@@ -97,7 +105,9 @@ def django_css(static_path: str, key: Key | None = None) -> ComponentType:
97105 return _django_css (static_path = static_path , key = key )
98106
99107
100- def django_js (static_path : str , key : Key | None = None ) -> ComponentType :
108+ def django_js (
109+ static_path : str , only_once : bool = False , only_once_auto_remove : bool = False , key : Key | None = None
110+ ) -> ComponentType :
101111 """Fetches a JS static file for use within ReactPy. This allows for deferred JS loading.
102112
103113 Args:
@@ -107,7 +117,9 @@ def django_js(static_path: str, key: Key | None = None) -> ComponentType:
107117 immediate siblings
108118 """
109119
110- return _django_js (static_path = static_path , key = key )
120+ return _django_js (
121+ static_path = static_path , only_once = only_once , only_once_auto_remove = only_once_auto_remove , key = key
122+ )
111123
112124
113125def django_form (
@@ -278,5 +290,8 @@ def _django_css(static_path: str):
278290
279291
280292@component
281- def _django_js (static_path : str ):
293+ def _django_js (static_path : str , only_once : bool , only_once_auto_remove : bool ):
294+ if only_once :
295+ return DjangoJS ({"jsPath" : static (static_path ), "autoRemove" : only_once_auto_remove })
296+
282297 return html .script (cached_static_file (static_path ))
0 commit comments