pyjs 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. pyjs/__init__.py +6 -0
  2. pyjs/__main__.py +6 -0
  3. pyjs/cli.py +816 -0
  4. pyjs/decorators.py +170 -0
  5. pyjs/docs/__init__.py +6 -0
  6. pyjs/docs/builder.py +351 -0
  7. pyjs/docs/cli.py +55 -0
  8. pyjs/docs/config.py +45 -0
  9. pyjs/docs/favicon.svg +18 -0
  10. pyjs/docs/markdown.py +61 -0
  11. pyjs/docs/models.py +38 -0
  12. pyjs/docs/navigation.py +61 -0
  13. pyjs/docs/style.css +901 -0
  14. pyjs/docs/ui.py +349 -0
  15. pyjs/nativescript/__init__.py +77 -0
  16. pyjs/scaffolding/__init__.py +418 -0
  17. pyjs/scaffolding/templates/app/README.md.template +33 -0
  18. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__PYJS_PACKAGE__.py.template +81 -0
  19. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__init__.py.template +0 -0
  20. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__main__.py.template +5 -0
  21. pyjs/scaffolding/templates/app/tests/test_app.py.template +22 -0
  22. pyjs/scaffolding/templates/app/tests/test_browser_app.py.template +19 -0
  23. pyjs/scaffolding/templates/app_test.py.template +8 -0
  24. pyjs/server.py +468 -0
  25. pyjs/skills/pyjs/SKILL.md +161 -0
  26. pyjs/state.py +101 -0
  27. pyjs/testing/__init__.py +3 -0
  28. pyjs/testing/android.py +248 -0
  29. pyjs/testing/artifacts.py +37 -0
  30. pyjs/testing/assertion_rewriter.py +125 -0
  31. pyjs/testing/builder.py +191 -0
  32. pyjs/testing/capture.py +133 -0
  33. pyjs/testing/client/__init__.py +1 -0
  34. pyjs/testing/client/app.py +718 -0
  35. pyjs/testing/client/assertions.py +49 -0
  36. pyjs/testing/client/runtime.py +123 -0
  37. pyjs/testing/client/sidebar.py +377 -0
  38. pyjs/testing/client/state.py +107 -0
  39. pyjs/testing/client/viewer.py +361 -0
  40. pyjs/testing/daemon.py +641 -0
  41. pyjs/testing/helpers.py +155 -0
  42. pyjs/testing/protocol.py +56 -0
  43. pyjs/testing/pytest_plugin.py +797 -0
  44. pyjs/testing/web.py +97 -0
  45. pyjs/testing/webgpu.py +27 -0
  46. pyjs/tooling/__init__.py +4 -0
  47. pyjs/tooling/android.py +138 -0
  48. pyjs/tooling/browser.py +676 -0
  49. pyjs/tooling/command.py +75 -0
  50. pyjs/tooling/nativescript.py +156 -0
  51. pyjs/tooling/node.py +170 -0
  52. pyjs/tooling/perf.py +163 -0
  53. pyjs/transpiler/__init__.py +23 -0
  54. pyjs/transpiler/_builtins.py +485 -0
  55. pyjs/transpiler/analyzer.py +1495 -0
  56. pyjs/transpiler/objects.py +1015 -0
  57. pyjs/transpiler/source.py +189 -0
  58. pyjs/transpiler/transpiler.py +748 -0
  59. pyjs/transpiler/utils.py +150 -0
  60. pyjs/web/__init__.py +5 -0
  61. pyjs/web/console.py +16 -0
  62. pyjs/web/dom.py +1529 -0
  63. pyjs/web/domx.py +474 -0
  64. pyjs/web/dragdrop.py +102 -0
  65. pyjs/web/events.py +1306 -0
  66. pyjs/web/files.py +203 -0
  67. pyjs/web/geometry.py +475 -0
  68. pyjs/web/html.py +927 -0
  69. pyjs/web/indexeddb.py +410 -0
  70. pyjs/web/javascript.py +112 -0
  71. pyjs/web/network.py +193 -0
  72. pyjs/web/ssr.py +70 -0
  73. pyjs/web/streams.py +17 -0
  74. pyjs/web/svg.py +684 -0
  75. pyjs/web/timers.py +29 -0
  76. pyjs/web/ui/__init__.py +18 -0
  77. pyjs/web/ui/accordion.py +166 -0
  78. pyjs/web/ui/alert.py +52 -0
  79. pyjs/web/ui/alert_dialog.py +102 -0
  80. pyjs/web/ui/aspect_ratio.py +12 -0
  81. pyjs/web/ui/attachment.py +80 -0
  82. pyjs/web/ui/avatar.py +105 -0
  83. pyjs/web/ui/badge.py +48 -0
  84. pyjs/web/ui/breadcrumb.py +85 -0
  85. pyjs/web/ui/bubble.py +38 -0
  86. pyjs/web/ui/button.py +86 -0
  87. pyjs/web/ui/calendar.py +124 -0
  88. pyjs/web/ui/card.py +58 -0
  89. pyjs/web/ui/carousel.py +99 -0
  90. pyjs/web/ui/chart.py +56 -0
  91. pyjs/web/ui/checkbox.py +31 -0
  92. pyjs/web/ui/collapsible.py +71 -0
  93. pyjs/web/ui/combobox.py +36 -0
  94. pyjs/web/ui/command.py +118 -0
  95. pyjs/web/ui/context_menu.py +65 -0
  96. pyjs/web/ui/date_picker.py +24 -0
  97. pyjs/web/ui/dialog.py +289 -0
  98. pyjs/web/ui/direction.py +9 -0
  99. pyjs/web/ui/drawer.py +72 -0
  100. pyjs/web/ui/dropdown_menu.py +239 -0
  101. pyjs/web/ui/empty.py +69 -0
  102. pyjs/web/ui/field.py +96 -0
  103. pyjs/web/ui/floating.py +90 -0
  104. pyjs/web/ui/hover_card.py +128 -0
  105. pyjs/web/ui/input.py +48 -0
  106. pyjs/web/ui/input_group.py +77 -0
  107. pyjs/web/ui/input_otp.py +76 -0
  108. pyjs/web/ui/item.py +78 -0
  109. pyjs/web/ui/kbd.py +26 -0
  110. pyjs/web/ui/label.py +14 -0
  111. pyjs/web/ui/marker.py +29 -0
  112. pyjs/web/ui/menubar.py +52 -0
  113. pyjs/web/ui/message.py +57 -0
  114. pyjs/web/ui/message_scroller.py +45 -0
  115. pyjs/web/ui/native_select.py +47 -0
  116. pyjs/web/ui/navigation_menu.py +110 -0
  117. pyjs/web/ui/pagination.py +63 -0
  118. pyjs/web/ui/popover.py +217 -0
  119. pyjs/web/ui/progress.py +44 -0
  120. pyjs/web/ui/radio_group.py +129 -0
  121. pyjs/web/ui/resizable.py +194 -0
  122. pyjs/web/ui/scroll_area.py +29 -0
  123. pyjs/web/ui/select.py +83 -0
  124. pyjs/web/ui/separator.py +24 -0
  125. pyjs/web/ui/sheet.py +77 -0
  126. pyjs/web/ui/sidebar.py +162 -0
  127. pyjs/web/ui/skeleton.py +15 -0
  128. pyjs/web/ui/slider.py +46 -0
  129. pyjs/web/ui/sonner.py +70 -0
  130. pyjs/web/ui/spinner.py +14 -0
  131. pyjs/web/ui/switch.py +35 -0
  132. pyjs/web/ui/table.py +84 -0
  133. pyjs/web/ui/tabs.py +167 -0
  134. pyjs/web/ui/text.py +15 -0
  135. pyjs/web/ui/textarea.py +28 -0
  136. pyjs/web/ui/toggle.py +109 -0
  137. pyjs/web/ui/tooltip.py +164 -0
  138. pyjs/web/ui/typography.py +79 -0
  139. pyjs/web/url.py +76 -0
  140. pyjs/web/webgpu.py +496 -0
  141. pyjs-0.0.1.dist-info/METADATA +441 -0
  142. pyjs-0.0.1.dist-info/RECORD +146 -0
  143. pyjs-0.0.1.dist-info/WHEEL +5 -0
  144. pyjs-0.0.1.dist-info/entry_points.txt +5 -0
  145. pyjs-0.0.1.dist-info/licenses/LICENSE +28 -0
  146. pyjs-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,418 @@
1
+ import importlib
2
+ import importlib.metadata
3
+ import inspect
4
+ import json
5
+ import keyword
6
+ import re
7
+ import shutil
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from importlib import resources
11
+ from pathlib import Path, PurePosixPath
12
+
13
+ from pyjs import __version__
14
+
15
+ TEMPLATE_ENTRY_POINT_GROUP = "pyjs.templates"
16
+ IGNORED_NAMES = {
17
+ "__pycache__",
18
+ ".pytest_cache",
19
+ ".ruff_cache",
20
+ }
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Template:
25
+ name: str
26
+ title: str
27
+ description: str
28
+ kind: str
29
+ modules: tuple[str, ...]
30
+
31
+ @property
32
+ def primary_module(self) -> str:
33
+ name = self.name.rsplit(".", 1)[-1]
34
+ return name if name in self.modules else self.modules[0]
35
+
36
+
37
+ def version_string() -> str:
38
+ return ".".join(str(part) for part in __version__)
39
+
40
+
41
+ def templates() -> tuple[Template, ...]:
42
+ discovered = []
43
+ seen = set()
44
+ entry_points = importlib.metadata.entry_points(group=TEMPLATE_ENTRY_POINT_GROUP)
45
+ for entry_point in sorted(entry_points, key=lambda entry_point: entry_point.name):
46
+ source = entry_point.load()
47
+ name = source.__name__
48
+ if name in seen:
49
+ raise ValueError(f"duplicate PyJS template: {name!r}")
50
+ seen.add(name)
51
+ if hasattr(source, "__path__"):
52
+ kind = "directory"
53
+ modules = tuple(
54
+ sorted(
55
+ child.name.removesuffix(".py")
56
+ for child in resources.files(source).iterdir()
57
+ if child.name.endswith(".py") and not child.name.startswith("__")
58
+ )
59
+ )
60
+ if not modules:
61
+ raise ValueError(
62
+ f"directory template {name!r} must contain at least one Python module"
63
+ )
64
+ else:
65
+ kind = "file"
66
+ modules = (Path(source.__file__).stem,)
67
+ discovered.append(
68
+ Template(
69
+ name=name,
70
+ title=name.rsplit(".", 1)[-1].replace("_", " ").replace("-", " ").title(),
71
+ description=inspect.getdoc(source) or f"An application created from {name}.",
72
+ kind=kind,
73
+ modules=modules,
74
+ )
75
+ )
76
+ return tuple(sorted(discovered, key=lambda template: template.name))
77
+
78
+
79
+ def find_template(name: str) -> Template:
80
+ catalog = templates()
81
+ if not catalog:
82
+ raise ValueError(
83
+ "no PyJS templates are installed; "
84
+ "install the official templates with 'python -m pip install pyjs-examples'"
85
+ )
86
+ for template in catalog:
87
+ if template.name == name:
88
+ return template
89
+ choices = ", ".join(template.name for template in catalog)
90
+ raise ValueError(f"unknown template {name!r}; choose from: {choices}")
91
+
92
+
93
+ def _ignored_source(name: str) -> bool:
94
+ return name in IGNORED_NAMES or name.endswith((".pyc", ".main.js", ".main.css", ".main.html"))
95
+
96
+
97
+ def _source_files(source, parent: PurePosixPath | None = None):
98
+ if parent is None:
99
+ parent = PurePosixPath()
100
+ for child in sorted(source.iterdir(), key=lambda child: child.name):
101
+ if _ignored_source(child.name):
102
+ continue
103
+ if not parent.parts and child.name in {"__init__.py", "__main__.py"}:
104
+ continue
105
+ relative_path = parent / child.name
106
+ if child.is_dir():
107
+ yield from _source_files(child, relative_path)
108
+ else:
109
+ yield relative_path.as_posix(), child.read_bytes()
110
+
111
+
112
+ def _normalize_source(
113
+ name: str,
114
+ content: bytes,
115
+ template: Template,
116
+ ) -> bytes:
117
+ try:
118
+ value = content.decode("utf-8")
119
+ except UnicodeDecodeError:
120
+ return content
121
+
122
+ if name == "README.md":
123
+ value = value.replace(".venv/bin/python", "python")
124
+ value = value.replace(
125
+ f"python -m {template.name}",
126
+ f"python {template.primary_module}.py",
127
+ )
128
+ package_path = template.name.split(".", 1)[-1].replace(".", "/")
129
+ value = value.replace(f"examples/{package_path}/", "")
130
+ value = value.replace("From the repository root", "From the project root")
131
+
132
+ if name.endswith(".py"):
133
+ for module in template.modules:
134
+ value = value.replace(
135
+ f"from {template.name}.{module} import",
136
+ f"from {module} import",
137
+ )
138
+ value = value.replace(f"from .{module} import", f"from {module} import")
139
+
140
+ return value.encode("utf-8")
141
+
142
+
143
+ def _materialized_sources(template: Template) -> tuple[tuple[str, bytes], ...]:
144
+ if template.kind == "file":
145
+ source = Path(importlib.import_module(template.name).__file__)
146
+ return ((source.name, source.read_bytes()),)
147
+
148
+ return tuple(
149
+ (name, _normalize_source(name, content, template))
150
+ for name, content in _source_files(resources.files(template.name))
151
+ )
152
+
153
+
154
+ def template_sources(template: Template) -> tuple[tuple[str, str | None], ...]:
155
+ sources = []
156
+ for name, content in _materialized_sources(template):
157
+ try:
158
+ value = content.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n")
159
+ except UnicodeDecodeError:
160
+ value = None
161
+ sources.append((name, value))
162
+ return tuple(sources)
163
+
164
+
165
+ def _distribution_name(name: str) -> str:
166
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name):
167
+ raise ValueError(
168
+ "project names must start with a letter or number and contain only "
169
+ "letters, numbers, dots, underscores, or hyphens"
170
+ )
171
+ return re.sub(r"[-_.]+", "-", name).lower()
172
+
173
+
174
+ def _package_name(name: str) -> str:
175
+ if not name.isidentifier() or keyword.iskeyword(name):
176
+ raise ValueError(
177
+ "application names must be valid Python identifiers because they are also "
178
+ "used as package names"
179
+ )
180
+ return name
181
+
182
+
183
+ def _render(value: str, context: dict[str, str]) -> str:
184
+ for name, replacement in context.items():
185
+ value = value.replace(f"__PYJS_{name}__", replacement)
186
+ return value
187
+
188
+
189
+ def _copy_template(source, destination: Path, context: dict[str, str]):
190
+ destination.mkdir(parents=True, exist_ok=True)
191
+ for child in sorted(source.iterdir(), key=lambda child: child.name):
192
+ output_name = ".gitignore" if child.name == "gitignore.template" else child.name
193
+ if output_name.endswith(".template"):
194
+ output_name = output_name.removesuffix(".template")
195
+ output_name = _render(output_name, context)
196
+ output = destination / output_name
197
+ if child.is_dir():
198
+ _copy_template(child, output, context)
199
+ elif child.name.endswith(".template"):
200
+ output.write_text(
201
+ _render(child.read_text(encoding="utf-8"), context),
202
+ encoding="utf-8",
203
+ )
204
+ else:
205
+ output.write_bytes(child.read_bytes())
206
+
207
+
208
+ def _copy_source(template: Template, destination: Path):
209
+ for name, content in _materialized_sources(template):
210
+ output = destination / name
211
+ output.parent.mkdir(parents=True, exist_ok=True)
212
+ output.write_bytes(content)
213
+
214
+
215
+ def _project_toml(
216
+ name: str,
217
+ description: str,
218
+ modules: tuple[str, ...],
219
+ package: str | None = None,
220
+ src_layout: bool = False,
221
+ ) -> str:
222
+ version = version_string()
223
+ description_value = json.dumps(description)
224
+ if package is None:
225
+ module_list = ", ".join(f'"{module}"' for module in modules)
226
+ setuptools = f"[tool.setuptools]\npy-modules = [{module_list}]"
227
+ else:
228
+ source = 'where = ["src"]\n' if src_layout else ""
229
+ setuptools = (
230
+ "[tool.setuptools.packages.find]\n"
231
+ f"{source}"
232
+ f'include = ["{package}", "{package}.*"]'
233
+ )
234
+ return f"""\
235
+ [build-system]
236
+ requires = ["setuptools>=82.0.1"]
237
+ build-backend = "setuptools.build_meta"
238
+
239
+ [project]
240
+ name = "{_distribution_name(name)}"
241
+ version = "0.1.0"
242
+ description = {description_value}
243
+ readme = "README.md"
244
+ requires-python = ">=3.14"
245
+ dependencies = ["pyjs~={version}"]
246
+
247
+ [project.optional-dependencies]
248
+ test = ["pytest>=9.0"]
249
+
250
+ {setuptools}
251
+
252
+ [tool.pytest.ini_options]
253
+ testpaths = ["tests"]
254
+
255
+ [tool.ruff]
256
+ target-version = "py314"
257
+ line-length = 100
258
+
259
+ [tool.ruff.lint]
260
+ extend-select = ["B", "I", "UP"]
261
+ """
262
+
263
+
264
+ def _write_project_files(
265
+ destination: Path,
266
+ name: str,
267
+ description: str,
268
+ modules: tuple[str, ...],
269
+ package: str | None = None,
270
+ src_layout: bool = False,
271
+ ):
272
+ (destination / "pyproject.toml").write_text(
273
+ _project_toml(name, description, modules, package, src_layout),
274
+ encoding="utf-8",
275
+ )
276
+ (destination / ".gitignore").write_text(
277
+ ".venv/\n__pycache__/\n.pytest_cache/\n.ruff_cache/\n*.py[cod]\n"
278
+ "*.main.js\n*.main.css\n*.main.html\n",
279
+ encoding="utf-8",
280
+ )
281
+
282
+
283
+ def _populate(
284
+ destination: Path,
285
+ project_name: str,
286
+ template: Template | None,
287
+ src_layout: bool = False,
288
+ ):
289
+ title = project_name.replace("-", " ").replace("_", " ").title()
290
+ description = "A browser application built with PyJS."
291
+ context = {
292
+ "INLINE_TEST": "",
293
+ "PACKAGE": _package_name(project_name),
294
+ "PROJECT_NAME": _distribution_name(project_name),
295
+ "PROJECT_TITLE": title,
296
+ "SOURCE_ROOT": "src" if src_layout else "",
297
+ "VERSION": version_string(),
298
+ }
299
+
300
+ starter = resources.files(__package__).joinpath("templates", "app")
301
+ if template is None:
302
+ _copy_template(starter, destination, context)
303
+ modules = ()
304
+ package = context["PACKAGE"]
305
+ else:
306
+ description = template.description
307
+ _copy_source(template, destination)
308
+ if template.kind == "file":
309
+ (destination / "README.md").write_text(
310
+ f"# {title}\n\n{description}\n\n"
311
+ "## Run\n\n"
312
+ f"```bash\npython {template.modules[0]}.py\n```\n",
313
+ encoding="utf-8",
314
+ )
315
+ modules = template.modules
316
+ package = None
317
+
318
+ _write_project_files(
319
+ destination,
320
+ project_name,
321
+ description,
322
+ modules,
323
+ package,
324
+ src_layout,
325
+ )
326
+
327
+
328
+ def _populate_file(destination: Path, project_name: str, template: Template | None):
329
+ if template is None:
330
+ inline_test = resources.files(__package__).joinpath("templates", "app_test.py.template")
331
+ context = {
332
+ "INLINE_TEST": inline_test.read_text(encoding="utf-8").rstrip() + "\n\n\n",
333
+ "PACKAGE": _package_name(project_name),
334
+ "PROJECT_NAME": _distribution_name(project_name),
335
+ "PROJECT_TITLE": project_name.replace("-", " ").replace("_", " ").title(),
336
+ "VERSION": version_string(),
337
+ }
338
+ source = resources.files(__package__).joinpath(
339
+ "templates",
340
+ "app",
341
+ "__PYJS_SOURCE_ROOT__",
342
+ "__PYJS_PACKAGE__",
343
+ "__PYJS_PACKAGE__.py.template",
344
+ )
345
+ destination.write_text(
346
+ _render(source.read_text(encoding="utf-8"), context), encoding="utf-8"
347
+ )
348
+ return
349
+
350
+ _, content = _materialized_sources(template)[0]
351
+ destination.write_bytes(content)
352
+
353
+
354
+ def create(
355
+ name: str,
356
+ destination: str | Path | None = None,
357
+ *,
358
+ template: str | None = None,
359
+ single_file: bool = False,
360
+ src_layout: bool = False,
361
+ ) -> Path:
362
+ project_name = _package_name(name)
363
+ if destination is None:
364
+ destination = Path.cwd() if single_file else Path(project_name)
365
+ destination = Path(destination).resolve()
366
+ selected_template = find_template(template) if template is not None else None
367
+ if src_layout and single_file:
368
+ raise ValueError("--src-layout cannot be combined with --single-file")
369
+ if src_layout and selected_template is not None:
370
+ raise ValueError("--src-layout cannot be combined with --template")
371
+ if single_file:
372
+ if selected_template is not None and selected_template.kind != "file":
373
+ raise ValueError(
374
+ f"template {selected_template.name!r} is a directory template "
375
+ "and cannot create a single file"
376
+ )
377
+ if destination.exists() and not destination.is_dir():
378
+ raise FileExistsError(f"destination is not a directory: {destination}")
379
+ destination.mkdir(parents=True, exist_ok=True)
380
+ application = destination / f"{project_name}.py"
381
+ if application.exists():
382
+ raise FileExistsError(f"destination already exists: {application}")
383
+
384
+ temporary = Path(tempfile.mkdtemp(prefix=f".{project_name}-", dir=destination))
385
+ try:
386
+ temporary_file = temporary / application.name
387
+ _populate_file(temporary_file, project_name, selected_template)
388
+ temporary_file.replace(application)
389
+ finally:
390
+ shutil.rmtree(temporary, ignore_errors=True)
391
+ return application
392
+
393
+ if destination.exists() and (not destination.is_dir() or any(destination.iterdir())):
394
+ raise FileExistsError(f"destination is not empty: {destination}")
395
+
396
+ destination.parent.mkdir(parents=True, exist_ok=True)
397
+ temporary = Path(tempfile.mkdtemp(prefix=f".{project_name}-", dir=destination.parent))
398
+ try:
399
+ _populate(temporary, project_name, selected_template, src_layout)
400
+ if destination.exists():
401
+ shutil.copytree(temporary, destination, dirs_exist_ok=True)
402
+ else:
403
+ temporary.replace(destination)
404
+ temporary = None
405
+ finally:
406
+ if temporary is not None:
407
+ shutil.rmtree(temporary, ignore_errors=True)
408
+ return destination
409
+
410
+
411
+ __all__ = [
412
+ "Template",
413
+ "create",
414
+ "find_template",
415
+ "template_sources",
416
+ "templates",
417
+ "version_string",
418
+ ]
@@ -0,0 +1,33 @@
1
+ # __PYJS_PROJECT_TITLE__
2
+
3
+ A small browser application built with PyJS.
4
+
5
+ ## Install
6
+
7
+ Create and activate a virtual environment, then install the application:
8
+
9
+ ```bash
10
+ python -m pip install -e ".[test]"
11
+ ```
12
+
13
+ ## Run
14
+
15
+ ```bash
16
+ python -m __PYJS_PACKAGE__
17
+ ```
18
+
19
+ Open <http://127.0.0.1:8000/>.
20
+
21
+ ## Test
22
+
23
+ Run the Python target:
24
+
25
+ ```bash
26
+ python -m pytest -q
27
+ ```
28
+
29
+ Run the web target:
30
+
31
+ ```bash
32
+ python -m pytest -q --pyjs-target=web
33
+ ```
@@ -0,0 +1,81 @@
1
+ from pyjs import effect, js, state
2
+ from pyjs.web.domx import CustomElement, button, ref, tag
3
+ from pyjs.web.events import Event
4
+
5
+
6
+ @js
7
+ class App(CustomElement):
8
+ status = state("Ready")
9
+
10
+ def __init__(self):
11
+ super().__init__()
12
+ self.status_text = ref(tag("strong", "Ready"))
13
+ self.action_button = ref(
14
+ button(
15
+ {
16
+ "style": (
17
+ "border:0;border-radius:8px;background:#111827;color:white;"
18
+ "padding:10px 16px;font:inherit;cursor:pointer"
19
+ ),
20
+ "type": "button",
21
+ },
22
+ "Test interaction",
23
+ )
24
+ )
25
+ self.action_button.addEventListener("click", self.activate)
26
+ tag(
27
+ self,
28
+ tag(
29
+ "main",
30
+ {
31
+ "style": (
32
+ "min-height:100vh;display:grid;place-items:center;background:#f8fafc;"
33
+ "color:#111827;font:16px system-ui,sans-serif"
34
+ )
35
+ },
36
+ tag(
37
+ "section",
38
+ {
39
+ "style": (
40
+ "width:min(28rem,calc(100% - 3rem));padding:2rem;border:1px solid "
41
+ "#e2e8f0;border-radius:16px;background:white;box-shadow:"
42
+ "0 20px 50px rgb(15 23 42 / 10%)"
43
+ )
44
+ },
45
+ tag("p", {"style": "margin:0;color:#6366f1;font-weight:700"}, "PYJS"),
46
+ tag(
47
+ "h1",
48
+ {"style": "margin:.5rem 0;font-size:2rem"},
49
+ "__PYJS_PROJECT_TITLE__",
50
+ ),
51
+ tag(
52
+ "p",
53
+ {"style": "margin:0 0 1.5rem;color:#475569"},
54
+ "Server-rendered HTML, hydrated with browser-native Python.",
55
+ ),
56
+ tag(
57
+ "div",
58
+ {"style": "display:flex;align-items:center;gap:1rem"},
59
+ self.action_button,
60
+ self.status_text,
61
+ ),
62
+ ),
63
+ ),
64
+ )
65
+
66
+ @effect(status)
67
+ def render_status(self):
68
+ self.status_text.textContent = self.status
69
+
70
+ def activate(self, event: Event):
71
+ self.status = "Browser connected"
72
+
73
+
74
+ def main():
75
+ return App()
76
+
77
+
78
+ __PYJS_INLINE_TEST__if __name__ == "__main__":
79
+ from pyjs.server import serve
80
+
81
+ serve(__file__)
@@ -0,0 +1,5 @@
1
+ from pyjs.server import serve
2
+
3
+ from . import __PYJS_PACKAGE__ as application
4
+
5
+ serve(application.__file__)
@@ -0,0 +1,22 @@
1
+ import pytest
2
+ from pyjs import js
3
+ from pyjs.web.events import Event
4
+
5
+ from __PYJS_PACKAGE__.__PYJS_PACKAGE__ import App, main
6
+
7
+
8
+ @pytest.mark.pyjs_python
9
+ @js
10
+ def test_app_state_updates_the_rendered_status():
11
+ app = App()
12
+
13
+ assert app.status == "Ready"
14
+ app.activate(Event("click"))
15
+
16
+ assert app.status == "Browser connected"
17
+ assert app.status_text.textContent == "Browser connected"
18
+
19
+
20
+ @pytest.mark.pyjs_python
21
+ def test_main_returns_the_application():
22
+ assert isinstance(main(), App)
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from pyjs import js
3
+ from pyjs.web.dom import document
4
+ from pyjs.web.events import Event
5
+
6
+ from __PYJS_PACKAGE__.__PYJS_PACKAGE__ import App
7
+
8
+ pytestmark = pytest.mark.pyjs_web
9
+
10
+
11
+ @js
12
+ def test_action_button_updates_the_mounted_application():
13
+ document.body.replaceChildren()
14
+ app = App()
15
+ document.body.append(app)
16
+
17
+ app.action_button.dispatchEvent(Event("click"))
18
+
19
+ assert app.status_text.textContent == "Browser connected"
@@ -0,0 +1,8 @@
1
+ @js
2
+ def test_app_updates_its_status():
3
+ app = App()
4
+
5
+ app.activate(Event("click"))
6
+
7
+ assert app.status == "Browser connected"
8
+ assert app.status_text.textContent == "Browser connected"