forked from reactive-python/reactpy-django
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponents.py
311 lines (258 loc) · 10.9 KB
/
components.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""This file contains Django related components. Most of these components utilize wrappers to fix type hints."""
from __future__ import annotations
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Union, cast
from urllib.parse import urlencode
from django.http import HttpRequest
from django.templatetags.static import static
from django.urls import reverse
from reactpy import component, hooks, html, utils, web
from reactpy.types import ComponentType, Key, VdomDict
from reactpy_django.exceptions import ViewNotRegisteredError
from reactpy_django.forms.components import _django_form
from reactpy_django.pyscript.components import _pyscript_component
from reactpy_django.utils import cached_static_file, generate_obj_name, import_module, render_view
if TYPE_CHECKING:
from collections.abc import Sequence
from django.forms import Form, ModelForm
from django.views import View
from reactpy_django.types import AsyncFormEvent, SyncFormEvent, ViewToComponentConstructor, ViewToIframeConstructor
def view_to_component(
view: Callable | View | str,
transforms: Sequence[Callable[[VdomDict], Any]] = (),
strict_parsing: bool = True,
) -> ViewToComponentConstructor:
"""Converts a Django view to a ReactPy component.
Keyword Args:
view: The view to convert, or the view's dotted path as a string.
transforms: A list of functions that transforms the newly generated VDOM. \
The functions will be called on each VDOM node.
strict_parsing: If True, an exception will be generated if the HTML does not \
perfectly adhere to HTML5.
Returns:
A function that takes `request, *args, key, **kwargs` and returns a ReactPy component.
"""
def constructor(
request: HttpRequest | None = None,
*args,
key: Key | None = None,
**kwargs,
) -> ComponentType:
return _view_to_component(
view=view,
transforms=transforms,
strict_parsing=strict_parsing,
request=request,
args=args,
kwargs=kwargs,
key=key,
)
return constructor
def view_to_iframe(view: Callable | View | str, extra_props: dict[str, Any] | None = None) -> ViewToIframeConstructor:
"""
Args:
view: The view function or class to convert, or the dotted path to the view.
Keyword Args:
extra_props: Additional properties to add to the `iframe` element.
Returns:
A function that takes `*args, key, **kwargs` and returns a ReactPy component.
"""
def constructor(
*args,
key: Key | None = None,
**kwargs,
) -> ComponentType:
return _view_to_iframe(view=view, extra_props=extra_props, args=args, kwargs=kwargs, key=key)
return constructor
def django_css(
static_path: str, only_once: bool = False, auto_remove: bool = False, key: Key | None = None
) -> ComponentType:
"""Fetches a CSS static file for use within ReactPy. This allows for deferred CSS loading.
Args:
static_path: The path to the static file. This path is identical to what you would \
use on Django's `{% static %}` template tag
key: A key to uniquely identify this component which is unique amongst a component's \
immediate siblings
"""
return _django_css(static_path=static_path, only_once=only_once, auto_remove=auto_remove, key=key)
def django_js(
static_path: str, only_once: bool = False, auto_remove: bool = False, key: Key | None = None
) -> ComponentType:
"""Fetches a JS static file for use within ReactPy. This allows for deferred JS loading.
Args:
static_path: The path to the static file. This path is identical to what you would \
use on Django's `{% static %}` template tag.
key: A key to uniquely identify this component which is unique amongst a component's \
immediate siblings
"""
return _django_js(static_path=static_path, only_once=only_once, auto_remove=auto_remove, key=key)
def django_form(
form: type[Form | ModelForm],
*,
on_success: AsyncFormEvent | SyncFormEvent | None = None,
on_error: AsyncFormEvent | SyncFormEvent | None = None,
on_receive_data: AsyncFormEvent | SyncFormEvent | None = None,
on_change: AsyncFormEvent | SyncFormEvent | None = None,
auto_save: bool = True,
extra_props: dict[str, Any] | None = None,
extra_transforms: Sequence[Callable[[VdomDict], Any]] | None = None,
form_template: str | None = None,
thread_sensitive: bool = True,
top_children: Sequence[Any] = (),
bottom_children: Sequence[Any] = (),
key: Key | None = None,
) -> ComponentType:
"""Converts a Django form to a ReactPy component.
Args:
form: The form to convert.
Keyword Args:
on_success: A callback function that is called when the form is successfully submitted.
on_error: A callback function that is called when the form submission fails.
on_receive_data: A callback function that is called before newly submitted form data is rendered.
on_change: A callback function that is called when a form field is modified by the user.
auto_save: If `True`, the form will automatically call `save` on successful submission of \
a `ModelForm`. This has no effect on regular `Form` instances.
extra_props: Additional properties to add to the `html.form` element.
extra_transforms: A list of functions that transforms the newly generated VDOM. \
The functions will be repeatedly called on each VDOM node.
form_template: The template to use for the form. If `None`, Django's default template is used.
thread_sensitive: Whether to run event callback functions in thread sensitive mode. \
This mode only applies to sync functions, and is turned on by default due to Django \
ORM limitations.
top_children: Additional elements to add to the top of the form.
bottom_children: Additional elements to add to the bottom of the form.
key: A key to uniquely identify this component which is unique amongst a component's \
immediate siblings.
"""
return _django_form(
form=form,
on_success=on_success,
on_error=on_error,
on_receive_data=on_receive_data,
on_change=on_change,
auto_save=auto_save,
extra_props=extra_props or {},
extra_transforms=extra_transforms or [],
form_template=form_template,
thread_sensitive=thread_sensitive,
top_children=top_children,
bottom_children=bottom_children,
key=key,
)
def pyscript_component(
*file_paths: str,
initial: str | VdomDict | ComponentType = "",
root: str = "root",
) -> ComponentType:
"""
Args:
file_paths: File path to your client-side component. If multiple paths are \
provided, the contents are automatically merged.
Kwargs:
initial: The initial HTML that is displayed prior to the PyScript component \
loads. This can either be a string containing raw HTML, a \
`#!python reactpy.html` snippet, or a non-interactive component.
root: The name of the root component function.
"""
return _pyscript_component(
*file_paths,
initial=initial,
root=root,
)
@component
def _view_to_component(
view: Callable | View | str,
transforms: Sequence[Callable[[VdomDict], Any]],
strict_parsing: bool,
request: HttpRequest | None,
args: Sequence | None,
kwargs: dict | None,
):
converted_view, set_converted_view = hooks.use_state(cast(Union[VdomDict, None], None))
_args: Sequence = args or ()
_kwargs: dict = kwargs or {}
if request:
_request: HttpRequest = request
else:
_request = HttpRequest()
_request.method = "GET"
resolved_view: Callable = import_module(view) if isinstance(view, str) else view # type: ignore
# Render the view render within a hook
@hooks.use_effect(
dependencies=[
json.dumps(vars(_request), default=generate_obj_name),
json.dumps([_args, _kwargs], default=generate_obj_name),
]
)
async def _render_view():
"""Render the view in an async hook to avoid blocking the main thread."""
# Render the view
response = await render_view(resolved_view, _request, _args, _kwargs)
set_converted_view(
utils.html_to_vdom(
response.content.decode("utf-8").strip(),
utils.del_html_head_body_transform,
*transforms,
strict=strict_parsing,
)
)
# Return the view if it's been rendered via the `async_render` hook
return converted_view
@component
def _view_to_iframe(
view: Callable | View | str,
extra_props: dict[str, Any] | None,
args: Sequence,
kwargs: dict,
):
from reactpy_django.config import REACTPY_REGISTERED_IFRAME_VIEWS
if hasattr(view, "view_class"):
view = view.view_class # type: ignore
dotted_path = view if isinstance(view, str) else generate_obj_name(view)
registered_view = REACTPY_REGISTERED_IFRAME_VIEWS.get(dotted_path)
if not registered_view:
msg = (
f"'{dotted_path}' has not been registered as an iframe! "
"Are you sure you called `register_iframe` within a Django `AppConfig.ready` method?"
)
raise ViewNotRegisteredError(msg)
query = kwargs.copy()
if args:
query["_args"] = args
query_string = f"?{urlencode(query, doseq=True)}" if args or kwargs else ""
extra_props = extra_props or {}
extra_props.pop("src", None)
return html.iframe(
{
"src": reverse("reactpy:view_to_iframe", args=[dotted_path]) + query_string,
"style": {"border": "none"},
"loading": "lazy",
}
| extra_props
)
# TODO: Consider on_load callback. Store whether something is loaded in the scope.
# TODO: Consider a boolean to change load behavior between text content and file loading
# TODO: Consider doing server side CSS de-duplication to allow for instant loading
@component
def _django_css(static_path: str, only_once: bool, auto_remove: bool):
if only_once:
return LoadOnlyOnce({
"path": static(static_path),
"nodeName": "link",
"autoRemove": auto_remove,
})
return html.style(cached_static_file(static_path))
@component
def _django_js(static_path: str, only_once: bool, auto_remove: bool):
if only_once:
return LoadOnlyOnce({
"path": static(static_path),
"nodeName": "script",
"autoRemove": auto_remove,
})
return html.script(cached_static_file(static_path))
LoadOnlyOnce = web.export(
web.module_from_file("reactpy-django", file=Path(__file__).parent / "static" / "reactpy_django" / "client.js"),
("LoadOnlyOnce"),
)