forked from reactive-python/reactpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.py
More file actions
267 lines (234 loc) · 8.93 KB
/
module.py
File metadata and controls
267 lines (234 loc) · 8.93 KB
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
from __future__ import annotations
import logging
from pathlib import Path, PurePosixPath
from typing import Any, Literal
from reactpy.config import REACTPY_DEBUG, REACTPY_WEB_MODULES_DIR
from reactpy.core.vdom import Vdom
from reactpy.reactjs.types import NAME_SOURCE, URL_SOURCE
from reactpy.reactjs.utils import (
are_files_identical,
copy_file,
file_lock,
resolve_names_from_file,
resolve_names_from_url,
)
from reactpy.types import ImportSourceDict, JavaScriptModule, VdomConstructor, VdomDict
logger = logging.getLogger(__name__)
def url_to_module(
url: str,
fallback: Any | None = None,
resolve_imports: bool = True,
resolve_imports_depth: int = 5,
unmount_before_update: bool = False,
) -> JavaScriptModule:
return JavaScriptModule(
source=url,
source_type=URL_SOURCE,
default_fallback=fallback,
file=None,
import_names=(
resolve_names_from_url(url, resolve_imports_depth)
if resolve_imports
else None
),
unmount_before_update=unmount_before_update,
)
def file_to_module(
name: str,
file: str | Path,
fallback: Any | None = None,
resolve_imports: bool = True,
resolve_imports_depth: int = 5,
unmount_before_update: bool = False,
symlink: bool = False,
) -> JavaScriptModule:
name += module_name_suffix(name)
source_file = Path(file).resolve()
target_file = get_module_path(name)
with file_lock(target_file.with_name(f"{target_file.name}.lock")):
if not source_file.exists():
msg = f"Source file does not exist: {source_file}"
raise FileNotFoundError(msg)
if not target_file.exists():
copy_file(target_file, source_file, symlink)
elif not are_files_identical(source_file, target_file):
logger.info(
f"Existing web module {name!r} will "
f"be replaced with {target_file.resolve()}"
)
copy_file(target_file, source_file, symlink)
return JavaScriptModule(
source=name,
source_type=NAME_SOURCE,
default_fallback=fallback,
file=target_file,
import_names=(
resolve_names_from_file(source_file, resolve_imports_depth)
if resolve_imports
else None
),
unmount_before_update=unmount_before_update,
)
def string_to_module(
name: str,
content: str,
fallback: Any | None = None,
resolve_imports: bool = True,
resolve_imports_depth: int = 5,
unmount_before_update: bool = False,
) -> JavaScriptModule:
name += module_name_suffix(name)
target_file = get_module_path(name)
if target_file.exists() and target_file.read_text(encoding="utf-8") != content:
logger.info(
f"Existing web module {name!r} will "
f"be replaced with {target_file.resolve()}"
)
target_file.unlink()
target_file.parent.mkdir(parents=True, exist_ok=True)
target_file.write_text(content)
return JavaScriptModule(
source=name,
source_type=NAME_SOURCE,
default_fallback=fallback,
file=target_file,
import_names=(
resolve_names_from_file(target_file, resolve_imports_depth)
if resolve_imports
else None
),
unmount_before_update=unmount_before_update,
)
def module_to_vdom(
web_module: JavaScriptModule,
import_names: str | list[str] | tuple[str, ...],
fallback: Any | None = None,
allow_children: bool = True,
) -> VdomConstructor | list[VdomConstructor]:
"""Return one or more VDOM constructors from a :class:`JavaScriptModule`
Parameters:
import_names:
One or more names to import. If given as a string, a single component
will be returned. If a list is given, then a list of components will be
returned.
fallback:
What to temporarily display while the module is being loaded.
allow_children:
Whether or not these components can have children.
"""
if isinstance(import_names, str):
if (
web_module.import_names is not None
and import_names.split(".")[0] not in web_module.import_names
):
msg = f"{web_module.source!r} does not contain {import_names!r}"
raise ValueError(msg)
return make_module(web_module, import_names, fallback, allow_children)
else:
if web_module.import_names is not None:
missing = sorted(
{e.split(".")[0] for e in import_names}.difference(
web_module.import_names
)
)
if missing:
msg = f"{web_module.source!r} does not contain {missing!r}"
raise ValueError(msg)
return [
make_module(web_module, name, fallback, allow_children)
for name in import_names
]
def make_module(
web_module: JavaScriptModule,
name: str,
fallback: Any | None,
allow_children: bool,
) -> VdomConstructor:
return Vdom(
name,
allow_children=allow_children,
import_source=ImportSourceDict(
source=web_module.source,
sourceType=web_module.source_type,
fallback=(fallback or web_module.default_fallback),
unmountBeforeUpdate=web_module.unmount_before_update,
),
)
def import_reactjs(
framework: Literal["preact", "react"] | None = None,
version: str | None = None,
use_local: bool = False,
) -> VdomDict:
"""
Return an import map script tag for ReactJS or Preact.
Parameters:
framework:
The framework to use, either "preact" or "react". Defaults to "preact" for
performance reasons. Set this to `react` if you are experiencing compatibility
issues with your component library.
version:
The version of the framework to use. Example values include "18", "10.2.4",
or "latest". If left as `None`, a default version will be used depending on the
selected framework.
use_local:
Whether to use the local framework ReactPy is bundled with (Preact).
Raises:
ValueError:
If both `framework` and `react_url_prefix` are provided, or if
`framework` is not one of "preact" or "react".
Returns:
A VDOM script tag containing the import map.
"""
from reactpy import html
from reactpy.executors.utils import default_import_map
if use_local and (framework or version): # nocov
raise ValueError("use_local cannot be used with framework or version")
framework = framework or "preact"
if framework and framework not in {"preact", "react"}: # nocov
raise ValueError("framework must be 'preact' or 'react'")
# Import map for ReactPy's local framework (re-exported/bundled/minified version of Preact)
if use_local:
return html.script(
{"type": "importmap", "id": "reactpy-importmap"},
default_import_map(),
)
# Import map for ReactJS from esm.sh
if framework == "react":
version = version or "19"
postfix = "?dev" if REACTPY_DEBUG.current else ""
return html.script(
{"type": "importmap", "id": "reactpy-importmap"},
f"""{{
"imports": {{
"react": "https://esm.sh/react@{version}{postfix}",
"react-dom": "https://esm.sh/react-dom@{version}{postfix}",
"react-dom/client": "https://esm.sh/react-dom@{version}/client{postfix}",
"react/jsx-runtime": "https://esm.sh/react@{version}/jsx-runtime{postfix}"
}}
}}""".replace("\n", "").replace(" ", ""),
)
# Import map for Preact from esm.sh
if framework == "preact":
version = version or "10"
postfix = "?dev" if REACTPY_DEBUG.current else ""
return html.script(
{"type": "importmap", "id": "reactpy-importmap"},
f"""{{
"imports": {{
"react": "https://esm.sh/preact@{version}/compat{postfix}",
"react-dom": "https://esm.sh/preact@{version}/compat{postfix}",
"react-dom/client": "https://esm.sh/preact@{version}/compat/client{postfix}",
"react/jsx-runtime": "https://esm.sh/preact@{version}/compat/jsx-runtime{postfix}"
}}
}}""".replace("\n", "").replace(" ", ""),
)
def module_name_suffix(name: str) -> str:
if name.startswith("@"):
name = name[1:]
head, _, tail = name.partition("@") # handle version identifier
_, _, tail = tail.partition("/") # get section after version
return PurePosixPath(tail or head).suffix or ".js"
def get_module_path(name: str) -> Path:
directory = REACTPY_WEB_MODULES_DIR.current
path = directory.joinpath(*name.split("/"))
return path.with_suffix(path.suffix)