3
3
from __future__ import annotations
4
4
5
5
import json
6
+ from pathlib import Path
6
7
from typing import TYPE_CHECKING , Any , Callable , Union , cast
7
8
from urllib .parse import urlencode
8
9
9
10
from django .http import HttpRequest
11
+ from django .templatetags .static import static
10
12
from django .urls import reverse
11
- from reactpy import component , hooks , html , utils
13
+ from reactpy import component , hooks , html , utils , web
12
14
from reactpy .types import ComponentType , Key , VdomDict
13
15
14
16
from reactpy_django .exceptions import ViewNotRegisteredError
25
27
from reactpy_django .types import AsyncFormEvent , SyncFormEvent , ViewToComponentConstructor , ViewToIframeConstructor
26
28
27
29
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
+
28
36
def view_to_component (
29
37
view : Callable | View | str ,
30
38
transforms : Sequence [Callable [[VdomDict ], Any ]] = (),
@@ -97,7 +105,9 @@ def django_css(static_path: str, key: Key | None = None) -> ComponentType:
97
105
return _django_css (static_path = static_path , key = key )
98
106
99
107
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 :
101
111
"""Fetches a JS static file for use within ReactPy. This allows for deferred JS loading.
102
112
103
113
Args:
@@ -107,7 +117,9 @@ def django_js(static_path: str, key: Key | None = None) -> ComponentType:
107
117
immediate siblings
108
118
"""
109
119
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
+ )
111
123
112
124
113
125
def django_form (
@@ -278,5 +290,8 @@ def _django_css(static_path: str):
278
290
279
291
280
292
@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
+
282
297
return html .script (cached_static_file (static_path ))
0 commit comments