mockitdown 0.1.0__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.
- mockitdown/__init__.py +32 -0
- mockitdown/api.py +96 -0
- mockitdown/assets.py +84 -0
- mockitdown/cli.py +194 -0
- mockitdown/diagnostics.py +95 -0
- mockitdown/evaluate.py +687 -0
- mockitdown/extension.py +147 -0
- mockitdown/fence.py +69 -0
- mockitdown/icons.py +358 -0
- mockitdown/model.py +129 -0
- mockitdown/options.py +93 -0
- mockitdown/packs/__init__.py +214 -0
- mockitdown/packs/android/pack.css +691 -0
- mockitdown/packs/android/pack.json +310 -0
- mockitdown/packs/angular-material/pack.css +725 -0
- mockitdown/packs/angular-material/pack.json +237 -0
- mockitdown/packs/base/pack.css +963 -0
- mockitdown/packs/base/pack.json +1037 -0
- mockitdown/packs/bootstrap/pack.css +969 -0
- mockitdown/packs/bootstrap/pack.json +320 -0
- mockitdown/packs/cde/pack.css +234 -0
- mockitdown/packs/cde/pack.json +716 -0
- mockitdown/packs/fluent/pack.css +710 -0
- mockitdown/packs/fluent/pack.json +288 -0
- mockitdown/packs/gsos/pack.css +490 -0
- mockitdown/packs/gsos/pack.json +567 -0
- mockitdown/packs/gtk/pack.css +583 -0
- mockitdown/packs/gtk/pack.json +357 -0
- mockitdown/packs/hologram/pack.css +494 -0
- mockitdown/packs/hologram/pack.json +436 -0
- mockitdown/packs/kde-plasma/pack.css +508 -0
- mockitdown/packs/kde-plasma/pack.json +347 -0
- mockitdown/packs/lcars/pack.css +627 -0
- mockitdown/packs/lcars/pack.json +236 -0
- mockitdown/packs/lisa/pack.css +1030 -0
- mockitdown/packs/lisa/pack.json +615 -0
- mockitdown/packs/mac-classic/pack.css +930 -0
- mockitdown/packs/mac-classic/pack.json +697 -0
- mockitdown/packs/macos9/pack.css +738 -0
- mockitdown/packs/macos9/pack.json +783 -0
- mockitdown/packs/mui/pack.css +866 -0
- mockitdown/packs/mui/pack.json +292 -0
- mockitdown/packs/phosphor/pack.css +413 -0
- mockitdown/packs/phosphor/pack.json +468 -0
- mockitdown/packs/qt/pack.css +604 -0
- mockitdown/packs/qt/pack.json +341 -0
- mockitdown/packs/sapui5/pack.css +819 -0
- mockitdown/packs/sapui5/pack.json +1395 -0
- mockitdown/packs/shadcn/pack.css +707 -0
- mockitdown/packs/shadcn/pack.json +325 -0
- mockitdown/packs/swiftui/pack.css +1441 -0
- mockitdown/packs/swiftui/pack.json +277 -0
- mockitdown/packs/vista/pack.css +899 -0
- mockitdown/packs/vista/pack.json +938 -0
- mockitdown/packs/win2/pack.css +187 -0
- mockitdown/packs/win2/pack.json +235 -0
- mockitdown/packs/win31/pack.css +706 -0
- mockitdown/packs/win31/pack.json +1164 -0
- mockitdown/packs/winxp/pack.css +894 -0
- mockitdown/packs/winxp/pack.json +886 -0
- mockitdown/packs/xerox-star/pack.css +137 -0
- mockitdown/packs/xerox-star/pack.json +209 -0
- mockitdown/page.css +138 -0
- mockitdown/render/__init__.py +108 -0
- mockitdown/render/charts.py +507 -0
- mockitdown/render/chrome.py +80 -0
- mockitdown/render/html.py +2370 -0
- mockitdown/render/style.py +439 -0
- mockitdown/styles.py +98 -0
- mockitdown/syntax/__init__.py +7 -0
- mockitdown/syntax/ast.py +217 -0
- mockitdown/syntax/lexer.py +245 -0
- mockitdown/syntax/parser.py +573 -0
- mockitdown/vocabulary.py +53 -0
- mockitdown-0.1.0.dist-info/METADATA +126 -0
- mockitdown-0.1.0.dist-info/RECORD +80 -0
- mockitdown-0.1.0.dist-info/WHEEL +5 -0
- mockitdown-0.1.0.dist-info/entry_points.txt +2 -0
- mockitdown-0.1.0.dist-info/licenses/LICENSE +21 -0
- mockitdown-0.1.0.dist-info/top_level.txt +1 -0
mockitdown/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""mockitdown — UI mockups written in SwiftUI syntax inside Markdown, rendered as HTML styled
|
|
2
|
+
after a real UI framework (SwiftUI, Fluent, Material UI, Angular Material, SAPUI5, Bootstrap, …).
|
|
3
|
+
|
|
4
|
+
Library use::
|
|
5
|
+
|
|
6
|
+
from mockitdown import render, stylesheet
|
|
7
|
+
result = render('import SwiftUI\\nText("Hello")', device="phone")
|
|
8
|
+
page = f"<style>{stylesheet(result.packs)}</style>{result.html}"
|
|
9
|
+
|
|
10
|
+
In a MkDocs or Zensical site, add the ``mockitdown`` Markdown extension and the superfences fence
|
|
11
|
+
(``mockitdown.fence.format`` / ``mockitdown.fence.validate``); see the documentation.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from .api import RenderResult, check, evaluate, render, stylesheet
|
|
17
|
+
from .diagnostics import Diagnostic, MockitdownError, MockitdownSyntaxError, Severity
|
|
18
|
+
from .options import RenderOptions
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"render", "check", "evaluate", "stylesheet", "RenderOptions", "RenderResult", "Diagnostic", "Severity",
|
|
24
|
+
"MockitdownError", "MockitdownSyntaxError", "makeExtension", "__version__",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def makeExtension(**kwargs): # noqa: N802 - Python-Markdown's required name
|
|
29
|
+
"""Python-Markdown entry point, so ``markdown_extensions: [mockitdown]`` works."""
|
|
30
|
+
from .extension import MockitdownExtension
|
|
31
|
+
|
|
32
|
+
return MockitdownExtension(**kwargs)
|
mockitdown/api.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Public entry points: render, check, stylesheet."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .assets import AssetResolver
|
|
9
|
+
from .diagnostics import Diagnostic, Diagnostics, MockitdownSyntaxError, Severity
|
|
10
|
+
from .evaluate import Evaluator, ImportContext
|
|
11
|
+
from .model import Screen
|
|
12
|
+
from .options import RenderOptions
|
|
13
|
+
from .packs import registry as _registry
|
|
14
|
+
from .render import Renderer, render_screen
|
|
15
|
+
from .render.html import esc
|
|
16
|
+
from .styles import stylesheet as _stylesheet
|
|
17
|
+
from .syntax import parse
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class RenderResult:
|
|
22
|
+
html: str
|
|
23
|
+
diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
24
|
+
#: Ids of the packs the output needs CSS for (empty when nothing rendered).
|
|
25
|
+
packs: list[str] = field(default_factory=list)
|
|
26
|
+
screen: Screen | None = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def errors(self) -> list[Diagnostic]:
|
|
30
|
+
return [d for d in self.diagnostics if d.severity is Severity.ERROR]
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def ok(self) -> bool:
|
|
34
|
+
return not self.errors
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _search_paths(paths: tuple[Path, ...]) -> list[Path]:
|
|
38
|
+
return [Path(p) for p in paths]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def evaluate(source: str, options: RenderOptions | None = None,
|
|
42
|
+
diagnostics: Diagnostics | None = None) -> tuple[Screen | None, Diagnostics]:
|
|
43
|
+
"""Parse and evaluate ``source``. Returns ``(None, diags)`` on a syntax error."""
|
|
44
|
+
opts = options or RenderOptions()
|
|
45
|
+
diags = diagnostics or Diagnostics()
|
|
46
|
+
src_name = str(opts.source_path) if opts.source_path else ""
|
|
47
|
+
try:
|
|
48
|
+
module = parse(source, source=src_name)
|
|
49
|
+
except MockitdownSyntaxError as e:
|
|
50
|
+
diags.extend([e.diagnostic])
|
|
51
|
+
return None, diags
|
|
52
|
+
reg = _registry(tuple(str(p) for p in opts.pack_paths))
|
|
53
|
+
base_dir = opts.source_path.parent if opts.source_path else None
|
|
54
|
+
ev = Evaluator(reg, diags, default_pack=opts.default_pack, pack_override=opts.pack,
|
|
55
|
+
imports=ImportContext(_search_paths(opts.import_paths), base_dir))
|
|
56
|
+
return ev.evaluate(module), diags
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def render(source: str, options: RenderOptions | None = None, **overrides: object) -> RenderResult:
|
|
60
|
+
"""Render one mockup to an HTML fragment (no CSS; see :func:`stylesheet`)."""
|
|
61
|
+
opts = (options or RenderOptions()).with_overrides(**overrides)
|
|
62
|
+
screen, diags = evaluate(source, opts)
|
|
63
|
+
if screen is None:
|
|
64
|
+
return RenderResult(error_html(diags.items), diags.items)
|
|
65
|
+
base_dir = opts.source_path.parent if opts.source_path else None
|
|
66
|
+
assets = AssetResolver(_search_paths(opts.asset_paths), base_dir, diags, embed=opts.embed_assets,
|
|
67
|
+
max_bytes=opts.max_embed_bytes)
|
|
68
|
+
renderer = Renderer(screen.pack, diags, assets)
|
|
69
|
+
body = render_screen(screen, renderer, opts, diags)
|
|
70
|
+
errors = diags.errors
|
|
71
|
+
shown = errors + (diags.warnings if opts.show_warnings else [])
|
|
72
|
+
prefix = error_html(shown) if shown else ""
|
|
73
|
+
packs = [p.id for p in screen.pack.lineage()]
|
|
74
|
+
if opts.source:
|
|
75
|
+
body += (f'<details class="mkd-source"><summary>Source</summary><pre><code class="language-swift">'
|
|
76
|
+
f"{esc(source.strip())}</code></pre></details>")
|
|
77
|
+
return RenderResult(prefix + body, diags.items, packs, screen)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def check(source: str, options: RenderOptions | None = None, **overrides: object) -> list[Diagnostic]:
|
|
81
|
+
"""All diagnostics for ``source`` (rendering included, so asset and icon problems are found)."""
|
|
82
|
+
return render(source, options, **overrides).diagnostics
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def stylesheet(packs: list[str] | None = None, *, pack_paths: tuple[Path, ...] = (), minify: bool = True) -> str:
|
|
86
|
+
"""CSS for the given pack ids (all known packs when None)."""
|
|
87
|
+
reg = _registry(tuple(str(p) for p in pack_paths))
|
|
88
|
+
return _stylesheet(packs if packs is not None else reg.ids(), reg, minify=minify)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def error_html(items: list[Diagnostic]) -> str:
|
|
92
|
+
errors = [d for d in items if d.severity is Severity.ERROR]
|
|
93
|
+
title = "mockitdown: " + (f"{len(errors)} error{'s' if len(errors) != 1 else ''}" if errors else "warnings")
|
|
94
|
+
lis = "".join(f"<li>{esc(str(d))}</li>" for d in items)
|
|
95
|
+
return (f'<div class="mkd-error" role="alert"><div class="mkd-error__title">{esc(title)}</div>'
|
|
96
|
+
f"<ul>{lis}</ul></div>")
|
mockitdown/assets.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""External assets (images) referenced from a mockup.
|
|
2
|
+
|
|
3
|
+
``Image("assets/team.jpg")`` is resolved at build time:
|
|
4
|
+
|
|
5
|
+
* ``http(s)://``, protocol-relative ``//`` and ``data:image/…`` references pass through unchanged;
|
|
6
|
+
* a local path is looked up relative to the block's own file (when known), then each asset path;
|
|
7
|
+
* with ``embed`` on (the default) a found file is inlined as a ``data:`` URI, so the rendered page is
|
|
8
|
+
self-contained and the reference works at any page URL; files over ``max_bytes`` are linked instead;
|
|
9
|
+
* with ``embed`` off the reference is emitted as written, for the browser to resolve.
|
|
10
|
+
|
|
11
|
+
A local path is only read when it resolves inside one of the search roots.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import base64
|
|
17
|
+
import mimetypes
|
|
18
|
+
import re
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from .diagnostics import Diagnostics, Location
|
|
22
|
+
|
|
23
|
+
_MIME = {
|
|
24
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
25
|
+
".webp": "image/webp", ".svg": "image/svg+xml", ".avif": "image/avif", ".ico": "image/x-icon",
|
|
26
|
+
".bmp": "image/bmp",
|
|
27
|
+
}
|
|
28
|
+
_REMOTE = re.compile(r"^(https?:)?//", re.I)
|
|
29
|
+
_DATA = re.compile(r"^data:image/[a-z0-9.+-]+(;[a-z0-9=.+-]+)*,", re.I)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AssetResolver:
|
|
33
|
+
def __init__(self, search_paths: list[Path], base_dir: Path | None, diags: Diagnostics, *, embed: bool = True,
|
|
34
|
+
max_bytes: int = 2_000_000) -> None:
|
|
35
|
+
self.roots = [p.resolve() for p in ([base_dir] if base_dir else []) + list(search_paths)]
|
|
36
|
+
self.embed = embed
|
|
37
|
+
self.max_bytes = max_bytes
|
|
38
|
+
self.diags = diags
|
|
39
|
+
self._cache: dict[Path, str] = {}
|
|
40
|
+
|
|
41
|
+
def _find(self, ref: str) -> Path | None:
|
|
42
|
+
rel = Path(ref.split("?", 1)[0].split("#", 1)[0])
|
|
43
|
+
for root in self.roots:
|
|
44
|
+
cand = (root / rel).resolve() if not rel.is_absolute() else rel.resolve()
|
|
45
|
+
if cand.is_file() and any(cand.is_relative_to(r) for r in self.roots):
|
|
46
|
+
return cand
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
def resolve(self, ref: str, loc: Location | None = None) -> str | None:
|
|
50
|
+
"""A URL for ``ref`` to put in ``src``, or None when a local file cannot be found."""
|
|
51
|
+
ref = ref.strip()
|
|
52
|
+
if not ref:
|
|
53
|
+
return None
|
|
54
|
+
if _REMOTE.match(ref):
|
|
55
|
+
return ref
|
|
56
|
+
if ref.lower().startswith("data:"):
|
|
57
|
+
if _DATA.match(ref):
|
|
58
|
+
return ref
|
|
59
|
+
self.diags.warning("only data:image/… URIs are accepted", loc, "asset")
|
|
60
|
+
return None
|
|
61
|
+
if re.match(r"^[a-z][a-z0-9+.-]*:", ref, re.I): # javascript:, file:, …
|
|
62
|
+
self.diags.warning(f"unsupported asset scheme in {ref!r}", loc, "asset")
|
|
63
|
+
return None
|
|
64
|
+
if not self.embed:
|
|
65
|
+
return ref
|
|
66
|
+
path = self._find(ref)
|
|
67
|
+
if path is None:
|
|
68
|
+
searched = ", ".join(str(r) for r in self.roots) or "(no asset paths)"
|
|
69
|
+
self.diags.warning(f"asset {ref!r} not found (searched {searched})", loc, "asset")
|
|
70
|
+
return None
|
|
71
|
+
if path in self._cache:
|
|
72
|
+
return self._cache[path]
|
|
73
|
+
size = path.stat().st_size
|
|
74
|
+
if size > self.max_bytes:
|
|
75
|
+
self.diags.warning(f"asset {ref!r} is {size} bytes, over the {self.max_bytes}-byte embed limit; "
|
|
76
|
+
"it is linked instead", loc, "asset")
|
|
77
|
+
return ref
|
|
78
|
+
mime = _MIME.get(path.suffix.lower()) or mimetypes.guess_type(path.name)[0]
|
|
79
|
+
if not mime or not mime.startswith("image/"):
|
|
80
|
+
self.diags.warning(f"asset {ref!r} is not a recognised image type", loc, "asset")
|
|
81
|
+
return None
|
|
82
|
+
uri = f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}"
|
|
83
|
+
self._cache[path] = uri
|
|
84
|
+
return uri
|
mockitdown/cli.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""``mockitdown`` command line.
|
|
2
|
+
|
|
3
|
+
mockitdown render FILE [options] [--standalone] [-o OUT] HTML fragment, or a full page
|
|
4
|
+
mockitdown check FILE… [options] diagnostics; exit 1 on any error
|
|
5
|
+
mockitdown css [--pack ID …] [-o OUT] the stylesheet (for css: none sites)
|
|
6
|
+
mockitdown packs [--json] the packs and their element names
|
|
7
|
+
mockitdown elements PACK [--markdown] one pack's element catalogue
|
|
8
|
+
|
|
9
|
+
FILE may be ``-`` for stdin. Diagnostics go to stderr; ``check --json`` prints them as JSON.
|
|
10
|
+
Exit codes: 0 ok, 1 diagnostics with errors, 2 usage error.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
from .api import render, stylesheet
|
|
22
|
+
from .diagnostics import MockitdownError, Severity
|
|
23
|
+
from .options import APPEARANCES, RenderOptions
|
|
24
|
+
from .packs import registry
|
|
25
|
+
from .render.html import esc
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _read(path: str) -> tuple[str, Path | None]:
|
|
29
|
+
if path == "-":
|
|
30
|
+
return sys.stdin.read(), None
|
|
31
|
+
p = Path(path)
|
|
32
|
+
return p.read_text(encoding="utf-8"), p.resolve()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _options(a: argparse.Namespace, source_path: Path | None) -> RenderOptions:
|
|
36
|
+
return RenderOptions(
|
|
37
|
+
pack=a.pack, default_pack=a.default_pack, device=a.device, appearance=a.appearance,
|
|
38
|
+
width=a.width, height=a.height, chrome=a.chrome or "auto", title=a.title,
|
|
39
|
+
elements=a.elements, import_paths=tuple(Path(p) for p in a.import_path),
|
|
40
|
+
asset_paths=tuple(Path(p) for p in a.asset_path), pack_paths=tuple(Path(p) for p in a.pack_path),
|
|
41
|
+
embed_assets=not a.no_embed, source_path=source_path,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _common(p: argparse.ArgumentParser) -> None:
|
|
46
|
+
p.add_argument("--pack", help="pack id (overrides the source's import)")
|
|
47
|
+
p.add_argument("--default-pack", default="base", help="pack when the source names none")
|
|
48
|
+
p.add_argument("--device", help="phone | tablet | desktop | wide | fit | …")
|
|
49
|
+
p.add_argument("--appearance", choices=APPEARANCES)
|
|
50
|
+
p.add_argument("--width", type=int)
|
|
51
|
+
p.add_argument("--height", type=int)
|
|
52
|
+
p.add_argument("--chrome", help="auto | none | ios | ipados | macos | windows | android | browser")
|
|
53
|
+
p.add_argument("--title")
|
|
54
|
+
p.add_argument("--elements", action="store_true", help="append the Elements table")
|
|
55
|
+
p.add_argument("-I", "--import-path", action="append", default=[], help="directory for import \"…\"")
|
|
56
|
+
p.add_argument("-A", "--asset-path", action="append", default=[], help="directory for Image(\"…\")")
|
|
57
|
+
p.add_argument("-P", "--pack-path", action="append", default=[], help="directory of site packs")
|
|
58
|
+
p.add_argument("--no-embed", action="store_true", help="link local images instead of inlining them")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _print_diags(diags, file=sys.stderr) -> None:
|
|
62
|
+
for d in diags:
|
|
63
|
+
print(str(d), file=file)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def cmd_render(a: argparse.Namespace) -> int:
|
|
67
|
+
src, path = _read(a.file)
|
|
68
|
+
result = render(src, _options(a, path))
|
|
69
|
+
_print_diags(result.diagnostics)
|
|
70
|
+
out = result.html
|
|
71
|
+
if a.standalone:
|
|
72
|
+
css = stylesheet(result.packs or ["base"], pack_paths=tuple(Path(p) for p in a.pack_path))
|
|
73
|
+
title = esc(a.title or (path.stem if path else "mockitdown"))
|
|
74
|
+
out = (f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" '
|
|
75
|
+
f'content="width=device-width,initial-scale=1"><title>{title}</title><style>body{{margin:0;'
|
|
76
|
+
f'padding:24px;font-family:system-ui,sans-serif;background:#f3f4f6}}@media (prefers-color-scheme:'
|
|
77
|
+
f'dark){{body{{background:#111;color:#eee}}}}</style><style>{css}</style></head><body>{out}</body></html>')
|
|
78
|
+
if a.output:
|
|
79
|
+
Path(a.output).write_text(out + "\n", encoding="utf-8")
|
|
80
|
+
else:
|
|
81
|
+
sys.stdout.write(out + "\n")
|
|
82
|
+
return 1 if result.errors else 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_check(a: argparse.Namespace) -> int:
|
|
86
|
+
failed = False
|
|
87
|
+
report = []
|
|
88
|
+
for f in a.files:
|
|
89
|
+
src, path = _read(f)
|
|
90
|
+
result = render(src, _options(a, path))
|
|
91
|
+
failed |= bool(result.errors)
|
|
92
|
+
if a.json:
|
|
93
|
+
report.append({"file": f, "ok": result.ok, "diagnostics": [
|
|
94
|
+
{"severity": d.severity.value, "code": d.code, "message": d.message,
|
|
95
|
+
"line": d.location.line, "col": d.location.col, "source": d.location.source}
|
|
96
|
+
for d in result.diagnostics]})
|
|
97
|
+
else:
|
|
98
|
+
_print_diags(result.diagnostics, sys.stdout)
|
|
99
|
+
errors = len(result.errors)
|
|
100
|
+
warnings = sum(1 for d in result.diagnostics if d.severity is Severity.WARNING)
|
|
101
|
+
print(f"{f}: {'ok' if not errors else 'FAILED'} ({errors} errors, {warnings} warnings)")
|
|
102
|
+
if a.json:
|
|
103
|
+
print(json.dumps(report, indent=2))
|
|
104
|
+
return 1 if failed else 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def cmd_css(a: argparse.Namespace) -> int:
|
|
108
|
+
css = stylesheet(a.pack or None, pack_paths=tuple(Path(p) for p in a.pack_path), minify=not a.pretty)
|
|
109
|
+
if a.output:
|
|
110
|
+
Path(a.output).parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
Path(a.output).write_text(css + "\n", encoding="utf-8")
|
|
112
|
+
else:
|
|
113
|
+
sys.stdout.write(css + "\n")
|
|
114
|
+
return 0
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cmd_packs(a: argparse.Namespace) -> int:
|
|
118
|
+
reg = registry(tuple(a.pack_path))
|
|
119
|
+
rows = []
|
|
120
|
+
for pid in reg.ids():
|
|
121
|
+
p = reg.get(pid)
|
|
122
|
+
if p.hidden and not a.all:
|
|
123
|
+
continue
|
|
124
|
+
rows.append({"id": p.id, "name": p.name, "framework": p.framework, "version": p.version,
|
|
125
|
+
"modules": list(p.modules), "device": p.device, "elements": len(p.elements),
|
|
126
|
+
"own_elements": list(p.own_elements)})
|
|
127
|
+
if a.json:
|
|
128
|
+
print(json.dumps(rows, indent=2))
|
|
129
|
+
else:
|
|
130
|
+
for r in rows:
|
|
131
|
+
mods = ", ".join(r["modules"])
|
|
132
|
+
print(f"{r['id']:<18} {r['name']:<22} {r['elements']:>4} elements import {mods}")
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_elements(a: argparse.Namespace) -> int:
|
|
137
|
+
pack = registry(tuple(a.pack_path)).get(a.pack)
|
|
138
|
+
names = sorted(pack.own_elements if a.own else pack.elements)
|
|
139
|
+
if a.markdown:
|
|
140
|
+
print(f"| Element | Role | Arguments | Defaults | Notes |\n|---|---|---|---|---|")
|
|
141
|
+
for n in names:
|
|
142
|
+
e = pack.elements[n]
|
|
143
|
+
defaults = ", ".join(f"{k}: {json.dumps(v)}" for k, v in e.defaults)
|
|
144
|
+
own = "" if n in pack.own_elements or pack.parent is None else " *(core)*"
|
|
145
|
+
print(f"| `{n}`{own} | {e.role} | {', '.join(e.params)} | {defaults} | {e.doc.replace('|', '/')} |")
|
|
146
|
+
else:
|
|
147
|
+
for n in names:
|
|
148
|
+
e = pack.elements[n]
|
|
149
|
+
print(f"{n:<28} {e.role:<12} {', '.join(e.params)}")
|
|
150
|
+
return 0
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def main(argv: list[str] | None = None) -> int:
|
|
154
|
+
ap = argparse.ArgumentParser(prog="mockitdown", description="Render SwiftUI-syntax UI mockups to HTML.")
|
|
155
|
+
ap.add_argument("--version", action="version", version=f"mockitdown {__version__}")
|
|
156
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
157
|
+
p = sub.add_parser("render", help="render a mockup file to HTML")
|
|
158
|
+
p.add_argument("file")
|
|
159
|
+
_common(p)
|
|
160
|
+
p.add_argument("--standalone", action="store_true", help="a full HTML page with the CSS inlined")
|
|
161
|
+
p.add_argument("-o", "--output")
|
|
162
|
+
p.set_defaults(func=cmd_render)
|
|
163
|
+
p = sub.add_parser("check", help="report diagnostics for mockup files")
|
|
164
|
+
p.add_argument("files", nargs="+")
|
|
165
|
+
_common(p)
|
|
166
|
+
p.add_argument("--json", action="store_true")
|
|
167
|
+
p.set_defaults(func=cmd_check)
|
|
168
|
+
p = sub.add_parser("css", help="write the stylesheet")
|
|
169
|
+
p.add_argument("--pack", action="append", help="pack id (repeatable; default: all)")
|
|
170
|
+
p.add_argument("-P", "--pack-path", action="append", default=[])
|
|
171
|
+
p.add_argument("--pretty", action="store_true", help="do not minify")
|
|
172
|
+
p.add_argument("-o", "--output")
|
|
173
|
+
p.set_defaults(func=cmd_css)
|
|
174
|
+
p = sub.add_parser("packs", help="list packs")
|
|
175
|
+
p.add_argument("-P", "--pack-path", action="append", default=[])
|
|
176
|
+
p.add_argument("--all", action="store_true", help=argparse.SUPPRESS)
|
|
177
|
+
p.add_argument("--json", action="store_true")
|
|
178
|
+
p.set_defaults(func=cmd_packs)
|
|
179
|
+
p = sub.add_parser("elements", help="list a pack's elements")
|
|
180
|
+
p.add_argument("pack")
|
|
181
|
+
p.add_argument("-P", "--pack-path", action="append", default=[])
|
|
182
|
+
p.add_argument("--markdown", action="store_true")
|
|
183
|
+
p.add_argument("--own", action="store_true", help="only the pack's own elements, not inherited ones")
|
|
184
|
+
p.set_defaults(func=cmd_elements)
|
|
185
|
+
a = ap.parse_args(argv)
|
|
186
|
+
try:
|
|
187
|
+
return int(a.func(a))
|
|
188
|
+
except (MockitdownError, OSError) as e:
|
|
189
|
+
print(f"mockitdown: {e}", file=sys.stderr)
|
|
190
|
+
return 1
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
sys.exit(main())
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Diagnostics: located errors and warnings produced while parsing, expanding and rendering.
|
|
2
|
+
|
|
3
|
+
Every stage reports problems through a :class:`Diagnostics` collector instead of printing or
|
|
4
|
+
raising, so one bad element never hides the others. Only a syntax error stops processing; it is
|
|
5
|
+
raised as :class:`MockitdownSyntaxError` and carries the same :class:`Diagnostic`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from enum import Enum
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Severity(str, Enum):
|
|
15
|
+
ERROR = "error"
|
|
16
|
+
WARNING = "warning"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Location:
|
|
21
|
+
"""A 1-based position in a mockup source. ``source`` names the file for imported code."""
|
|
22
|
+
|
|
23
|
+
line: int = 0
|
|
24
|
+
col: int = 0
|
|
25
|
+
source: str = ""
|
|
26
|
+
|
|
27
|
+
def __str__(self) -> str:
|
|
28
|
+
where = f"{self.source}:" if self.source else "line "
|
|
29
|
+
return f"{where}{self.line}:{self.col}" if self.line else (self.source or "?")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Diagnostic:
|
|
34
|
+
severity: Severity
|
|
35
|
+
message: str
|
|
36
|
+
location: Location = field(default_factory=Location)
|
|
37
|
+
code: str = ""
|
|
38
|
+
|
|
39
|
+
def __str__(self) -> str:
|
|
40
|
+
code = f" [{self.code}]" if self.code else ""
|
|
41
|
+
return f"{self.severity.value}{code} at {self.location}: {self.message}"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class MockitdownError(Exception):
|
|
45
|
+
"""Base class for errors raised by mockitdown."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, diagnostic: Diagnostic | str):
|
|
48
|
+
if isinstance(diagnostic, str):
|
|
49
|
+
diagnostic = Diagnostic(Severity.ERROR, diagnostic)
|
|
50
|
+
self.diagnostic = diagnostic
|
|
51
|
+
super().__init__(str(diagnostic))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class MockitdownSyntaxError(MockitdownError):
|
|
55
|
+
"""The source could not be tokenized or parsed."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Diagnostics:
|
|
59
|
+
"""An ordered collector of diagnostics, de-duplicated by (severity, message, location)."""
|
|
60
|
+
|
|
61
|
+
def __init__(self) -> None:
|
|
62
|
+
self._items: list[Diagnostic] = []
|
|
63
|
+
self._seen: set[tuple] = set()
|
|
64
|
+
|
|
65
|
+
def add(self, severity: Severity, message: str, location: Location | None = None, code: str = "") -> None:
|
|
66
|
+
d = Diagnostic(severity, message, location or Location(), code)
|
|
67
|
+
key = (d.severity, d.message, d.location)
|
|
68
|
+
if key not in self._seen:
|
|
69
|
+
self._seen.add(key)
|
|
70
|
+
self._items.append(d)
|
|
71
|
+
|
|
72
|
+
def error(self, message: str, location: Location | None = None, code: str = "") -> None:
|
|
73
|
+
self.add(Severity.ERROR, message, location, code)
|
|
74
|
+
|
|
75
|
+
def warning(self, message: str, location: Location | None = None, code: str = "") -> None:
|
|
76
|
+
self.add(Severity.WARNING, message, location, code)
|
|
77
|
+
|
|
78
|
+
def extend(self, items: list[Diagnostic]) -> None:
|
|
79
|
+
for d in items:
|
|
80
|
+
self.add(d.severity, d.message, d.location, d.code)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def items(self) -> list[Diagnostic]:
|
|
84
|
+
return list(self._items)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def errors(self) -> list[Diagnostic]:
|
|
88
|
+
return [d for d in self._items if d.severity is Severity.ERROR]
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def warnings(self) -> list[Diagnostic]:
|
|
92
|
+
return [d for d in self._items if d.severity is Severity.WARNING]
|
|
93
|
+
|
|
94
|
+
def __len__(self) -> int:
|
|
95
|
+
return len(self._items)
|