kite-ui 0.2.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.
Files changed (48) hide show
  1. kite/LICENSE +21 -0
  2. kite/THIRD_PARTY_NOTICES.md +190 -0
  3. kite/__init__.py +8 -0
  4. kite/__main__.py +51 -0
  5. kite/app.py +145 -0
  6. kite/components/__init__.py +10 -0
  7. kite/components/charts.py +103 -0
  8. kite/components/chrome.py +27 -0
  9. kite/components/code.py +49 -0
  10. kite/components/data.py +82 -0
  11. kite/components/display.py +300 -0
  12. kite/components/dock.py +68 -0
  13. kite/components/inputs.py +185 -0
  14. kite/components/islands.py +103 -0
  15. kite/components/layout.py +408 -0
  16. kite/components/nav.py +75 -0
  17. kite/core.py +168 -0
  18. kite/docsite.py +467 -0
  19. kite/export.py +378 -0
  20. kite/fonts.py +91 -0
  21. kite/icons.py +39 -0
  22. kite/presets.py +286 -0
  23. kite/react/components/charts.jsx +243 -0
  24. kite/react/components/codeblock.jsx +31 -0
  25. kite/react/components/core.jsx +341 -0
  26. kite/react/components/debug.js +34 -0
  27. kite/react/components/dock.js +75 -0
  28. kite/react/components/helpers.jsx +48 -0
  29. kite/react/components/index.js +8 -0
  30. kite/react/components/layout.jsx +185 -0
  31. kite/react/components/overlays.jsx +109 -0
  32. kite/react/docs/Playground.jsx +172 -0
  33. kite/react/icons.json +1 -0
  34. kite/react/layout.json +12 -0
  35. kite/static/fonts/Inter-Variable.woff2 +0 -0
  36. kite/static/fonts/JetBrainsMono-Variable.woff2 +0 -0
  37. kite/static/fonts/OFL-Inter.txt +93 -0
  38. kite/static/fonts/OFL-JetBrainsMono.txt +93 -0
  39. kite/static/kite.css +631 -0
  40. kite/static/kite.docs.js +45 -0
  41. kite/static/kite.islands.js +106 -0
  42. kite/theme.py +303 -0
  43. kite_ui-0.2.0.dist-info/METADATA +146 -0
  44. kite_ui-0.2.0.dist-info/RECORD +48 -0
  45. kite_ui-0.2.0.dist-info/WHEEL +4 -0
  46. kite_ui-0.2.0.dist-info/entry_points.txt +2 -0
  47. kite_ui-0.2.0.dist-info/licenses/LICENSE +21 -0
  48. kite_ui-0.2.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +190 -0
kite/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ruhan Ahuja
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,190 @@
1
+ # Third-party notices
2
+
3
+ kite-ui itself is licensed as stated in its LICENSE. It bundles the following third-party software; each keeps its own license, reproduced below.
4
+
5
+ ## Icons: Lucide (ISC)
6
+ `kite/react/icons.json` is derived from [Lucide](https://lucide.dev) (lucide-static 1.83.0). Lucide is ISC licensed; portions derive from Feather (MIT). See https://github.com/lucide-icons/lucide/blob/main/LICENSE.
7
+
8
+ ## Fonts (SIL Open Font License 1.1)
9
+ Inter and JetBrains Mono (`kite/static/fonts/`); their license texts ship next to the font files (OFL-Inter.txt, OFL-JetBrainsMono.txt).
10
+ SF Pro is NOT included (Apple license).
11
+
12
+ ## JavaScript bundled into kite/static/kite.islands.js and kite.docs.js
13
+
14
+ ### @floating-ui/core@1.8.0, @floating-ui/dom@1.8.0, @floating-ui/react-dom@2.1.9, @floating-ui/utils@0.2.12
15
+
16
+ ```
17
+ MIT License
18
+
19
+ Copyright (c) 2021-present Floating UI contributors
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
22
+ this software and associated documentation files (the "Software"), to deal in
23
+ the Software without restriction, including without limitation the rights to
24
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
25
+ the Software, and to permit persons to whom the Software is furnished to do so,
26
+ subject to the following conditions:
27
+
28
+ The above copyright notice and this permission notice shall be included in all
29
+ copies or substantial portions of the Software.
30
+
31
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
33
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
34
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
35
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
36
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37
+ ```
38
+
39
+ ### @radix-ui/primitive@1.2.0, @radix-ui/react-accordion@1.3.1, @radix-ui/react-arrow@1.1.17, @radix-ui/react-collapsible@1.2.1, @radix-ui/react-collection@1.2.0, @radix-ui/react-compose-refs@1.1.5, @radix-ui/react-context@1.3.0, @radix-ui/react-dialog@1.3.1, @radix-ui/react-direction@1.2.0, @radix-ui/react-dismissable-layer@1.2.1, @radix-ui/react-dropdown-menu@2.2.1, @radix-ui/react-focus-guards@1.2.0, @radix-ui/react-focus-scope@1.3.1, @radix-ui/react-id@1.1.4, @radix-ui/react-menu@2.2.1, @radix-ui/react-popover@1.3.1, @radix-ui/react-popper@1.4.0, @radix-ui/react-portal@1.2.0, @radix-ui/react-presence@1.1.11, @radix-ui/react-primitive@2.2.0, @radix-ui/react-roving-focus@1.2.1, @radix-ui/react-slot@1.5.0, @radix-ui/react-tabs@1.2.1, @radix-ui/react-tooltip@1.4.1, @radix-ui/react-use-callback-ref@1.1.5, @radix-ui/react-use-controllable-state@1.3.0, @radix-ui/react-use-effect-event@0.0.5, @radix-ui/react-use-is-hydrated@0.1.3, @radix-ui/react-use-layout-effect@1.1.4, @radix-ui/react-use-size@1.1.5, @radix-ui/react-visually-hidden@1.2.13
40
+
41
+ ```
42
+ MIT License
43
+
44
+ Copyright (c) 2022 WorkOS
45
+
46
+ Permission is hereby granted, free of charge, to any person obtaining a copy
47
+ of this software and associated documentation files (the "Software"), to deal
48
+ in the Software without restriction, including without limitation the rights
49
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
50
+ copies of the Software, and to permit persons to whom the Software is
51
+ furnished to do so, subject to the following conditions:
52
+
53
+ The above copyright notice and this permission notice shall be included in all
54
+ copies or substantial portions of the Software.
55
+
56
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
57
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
58
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
59
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
60
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
61
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
62
+ SOFTWARE.
63
+ ```
64
+
65
+ ### aria-hidden@1.2.6, react-remove-scroll@2.7.2, react-style-singleton@2.2.3, use-callback-ref@1.3.3, use-sidecar@1.1.3
66
+
67
+ ```
68
+ MIT License
69
+
70
+ Copyright (c) 2017 Anton Korzunov
71
+
72
+ Permission is hereby granted, free of charge, to any person obtaining a copy
73
+ of this software and associated documentation files (the "Software"), to deal
74
+ in the Software without restriction, including without limitation the rights
75
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
76
+ copies of the Software, and to permit persons to whom the Software is
77
+ furnished to do so, subject to the following conditions:
78
+
79
+ The above copyright notice and this permission notice shall be included in all
80
+ copies or substantial portions of the Software.
81
+
82
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
83
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
84
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
85
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
86
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
87
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
88
+ SOFTWARE.
89
+ ```
90
+
91
+ ### detect-node-es@1.1.0
92
+
93
+ ```
94
+ MIT License
95
+
96
+ Copyright (c) 2017 Ilya Kantor
97
+
98
+ Permission is hereby granted, free of charge, to any person obtaining a copy
99
+ of this software and associated documentation files (the "Software"), to deal
100
+ in the Software without restriction, including without limitation the rights
101
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
102
+ copies of the Software, and to permit persons to whom the Software is
103
+ furnished to do so, subject to the following conditions:
104
+
105
+ The above copyright notice and this permission notice shall be included in all
106
+ copies or substantial portions of the Software.
107
+
108
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
109
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
110
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
111
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
112
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
113
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
114
+ SOFTWARE.
115
+ ```
116
+
117
+ ### get-nonce@1.0.1
118
+
119
+ ```
120
+ MIT License
121
+
122
+ Copyright (c) 2020 Anton Korzunov
123
+
124
+ Permission is hereby granted, free of charge, to any person obtaining a copy
125
+ of this software and associated documentation files (the "Software"), to deal
126
+ in the Software without restriction, including without limitation the rights
127
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
128
+ copies of the Software, and to permit persons to whom the Software is
129
+ furnished to do so, subject to the following conditions:
130
+
131
+ The above copyright notice and this permission notice shall be included in all
132
+ copies or substantial portions of the Software.
133
+
134
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
135
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
136
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
137
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
138
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
139
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
140
+ SOFTWARE.
141
+ ```
142
+
143
+ ### react@19.3.1, react-dom@19.3.1, scheduler@0.28.0
144
+
145
+ ```
146
+ MIT License
147
+
148
+ Copyright (c) Meta Platforms, Inc. and affiliates.
149
+
150
+ Permission is hereby granted, free of charge, to any person obtaining a copy
151
+ of this software and associated documentation files (the "Software"), to deal
152
+ in the Software without restriction, including without limitation the rights
153
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
154
+ copies of the Software, and to permit persons to whom the Software is
155
+ furnished to do so, subject to the following conditions:
156
+
157
+ The above copyright notice and this permission notice shall be included in all
158
+ copies or substantial portions of the Software.
159
+
160
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
161
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
162
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
163
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
164
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
165
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
166
+ SOFTWARE.
167
+ ```
168
+
169
+ ### react-remove-scroll-bar@2.3.8
170
+
171
+ ```
172
+ (MIT: see the package)
173
+ ```
174
+
175
+ ### tslib@2.9.1
176
+
177
+ ```
178
+ Copyright (c) Microsoft Corporation.
179
+
180
+ Permission to use, copy, modify, and/or distribute this software for any
181
+ purpose with or without fee is hereby granted.
182
+
183
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
184
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
185
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
186
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
187
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
188
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
189
+ PERFORMANCE OF THIS SOFTWARE.
190
+ ```
kite/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """kite: Python-first UI components. `from kite import Button, Theme, assets`"""
2
+ from .core import Component, Island, Raw, render
3
+ from .app import App
4
+ from .icons import Icon, icon
5
+ from .theme import Theme, assets
6
+ from .components import * # noqa: F401,F403
7
+
8
+ __version__ = "0.2.0"
kite/__main__.py ADDED
@@ -0,0 +1,51 @@
1
+ """kite-ui: the command line.
2
+
3
+ kite-ui --docs [--port 8001] [--no-open] open the interactive docs
4
+ kite-ui run app.py serve an app.py that defines `app = App(...)`
5
+ kite-ui export app.py out_dir [web|windows|mac|linux]
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import runpy
11
+ import sys
12
+
13
+ from . import __version__
14
+
15
+
16
+ def _load(path: str):
17
+ app = runpy.run_path(path, run_name="kite_app").get("app")
18
+ if app is None:
19
+ sys.exit(f"{path} must define `app = App(...)`")
20
+ return app
21
+
22
+
23
+ def cli(argv=None) -> int:
24
+ ap = argparse.ArgumentParser(prog="kite-ui", description="kite: Python UI with a real design language.")
25
+ ap.add_argument("--docs", action="store_true", help="open the interactive docs (learn it, try every component)")
26
+ ap.add_argument("--port", type=int, default=None, help="port for --docs / run (default 8001 / 8000)")
27
+ ap.add_argument("--no-open", action="store_true", help="don't open a browser window")
28
+ ap.add_argument("--version", action="version", version=f"kite-ui {__version__}")
29
+ sub = ap.add_subparsers(dest="cmd")
30
+ r = sub.add_parser("run", help="serve an app.py")
31
+ r.add_argument("file")
32
+ e = sub.add_parser("export", help="export an app.py as a React / Electron project")
33
+ e.add_argument("file")
34
+ e.add_argument("directory", nargs="?", default="web")
35
+ e.add_argument("type", nargs="?", default="web", choices=["web", "windows", "mac", "linux"])
36
+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)
37
+ if a.docs:
38
+ from .docsite import main
39
+ main(port=a.port or 8001, openBrowser=not a.no_open)
40
+ elif a.cmd == "run":
41
+ _load(a.file).run(port=a.port or 8000, openBrowser=not a.no_open)
42
+ elif a.cmd == "export":
43
+ print("exported to", _load(a.file).export(a.directory, a.type))
44
+ else:
45
+ ap.print_help()
46
+ print("\nNew here? Run: kite-ui --docs")
47
+ return 0
48
+
49
+
50
+ if __name__ == "__main__":
51
+ sys.exit(cli())
kite/app.py ADDED
@@ -0,0 +1,145 @@
1
+ """App: routes + theme(s) in one object. Run it, save it as one offline file, or export a React/Electron project.
2
+
3
+ app = App("My site", theme=Theme.apple())
4
+
5
+ @app.page("/")
6
+ def home():
7
+ return Container(H1("Hello"), Button("Click", color="primary"))
8
+
9
+ app.run() # http://127.0.0.1:8000 (stdlib server, no dependencies, no network)
10
+ app.save("site.html") # ONE self-contained file (CSS, JS, fonts inlined): double-click to open offline
11
+ app.export("web") # a real Vite + React project (type="windows" | "mac" | "linux" adds Electron)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import mimetypes
17
+ import re
18
+ import warnings
19
+ import webbrowser
20
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
21
+ from pathlib import Path
22
+ from urllib.parse import unquote, urlparse
23
+
24
+ from . import fonts
25
+ from .core import Raw, render
26
+ from .theme import Theme, assets, static_dir
27
+
28
+ STATIC = Path(static_dir())
29
+
30
+
31
+ def _data_uri(path: Path) -> str:
32
+ mime = mimetypes.guess_type(path.name)[0] or "font/woff2"
33
+ return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode()}"
34
+
35
+
36
+ class App:
37
+ def __init__(self, title: str = "Kite app", theme: Theme | None = None, themes: dict | None = None, defaultTheme: str | None = None,
38
+ lang: str = "en", base: str = "/kite", fonts: str = "fonts", debug: bool = False):
39
+ """theme=Theme.apple() for one look; themes={"apple": Theme.apple(), "bloomberg": Theme.bloomberg()} to switch at runtime
40
+ (see ThemeSwitcher). fonts = folder with your own font files, bundled automatically."""
41
+ self.title, self.theme, self.themes, self.defaultTheme, self.lang, self.base, self.fontsDir, self.debug = title, theme, themes, defaultTheme, lang, base, fonts, debug
42
+ self._pages: dict = {}
43
+ self._warned = False
44
+
45
+ def page(self, path: str = "/", title: str | None = None):
46
+ """Decorator: register a function that returns a component (or list/str) for `path`."""
47
+
48
+ def deco(fn):
49
+ self._pages[path] = (fn, title)
50
+ return fn
51
+
52
+ return deco
53
+
54
+ def routes(self):
55
+ return [(p, fn, t) for p, (fn, t) in self._pages.items()]
56
+
57
+ def allThemes(self) -> list:
58
+ return [*([self.theme] if self.theme else []), *(self.themes or {}).values()]
59
+
60
+ def _warnMissingFonts(self):
61
+ if self._warned:
62
+ return
63
+ self._warned = True
64
+ names = [n for t in self.allThemes() for n in t.families()]
65
+ for n in fonts.missing(names, self.fontsDir):
66
+ warnings.warn(f"kite: font {n!r} is not bundled. Add its files to ./{self.fontsDir}/ (e.g. {n.replace(' ', '-')}-Regular.woff2) "
67
+ f"or run kite.fonts.download({n!r}) once. Falling back to the next font in the stack.", stacklevel=3)
68
+
69
+ def _head(self, inline: bool) -> str:
70
+ self._warnMissingFonts()
71
+ urlFor = (lambda n: _data_uri(Path(self.fontsDir) / n)) if inline else (lambda n: f"{self.base}/user-fonts/{n}")
72
+ fontCss = fonts.faceCss(urlFor, self.fontsDir)
73
+ head = str(assets(self.base, self.theme, self.themes, self.defaultTheme, islands=not inline, fontCss=fontCss))
74
+ if self.debug: # outline every placement component on load (Ctrl+Shift+L toggles it any time)
75
+ head += "<script>addEventListener('load',function(){window.kite&&kite.debug&&kite.debug(true)})</script>"
76
+ if not inline:
77
+ return head
78
+ css = (STATIC / "kite.css").read_text()
79
+ css = re.sub(r'url\("fonts/([^"]+)"\)', lambda m: f'url("{_data_uri(STATIC / "fonts" / m.group(1))}")', css)
80
+ js = (STATIC / "kite.islands.js").read_text().replace("</script", "<\\/script")
81
+ return head.replace(f'<link rel="stylesheet" href="{self.base}/kite.css">', f"<style>{css}</style>") + f'<script type="module">{js}</script>'
82
+
83
+ def html(self, path: str = "/", inline: bool = False) -> str:
84
+ """The full HTML document for one route. inline=True embeds CSS, JS and fonts (no external files at all)."""
85
+ fn, title = self._pages[path]
86
+ return (f'<!doctype html><html lang="{self.lang}"><head><meta charset="utf-8">'
87
+ f'<meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="data:,"><title>{render(title or self.title)}</title>'
88
+ f"{self._head(inline)}</head><body>{render(fn())}</body></html>")
89
+
90
+ def save(self, file: str = "site.html", route: str = "/") -> Path:
91
+ """Write ONE self-contained HTML file for `route` (open it offline, email it, drop it on any static host)."""
92
+ out = Path(file)
93
+ out.write_text(self.html(route, inline=True), encoding="utf-8")
94
+ return out
95
+
96
+ def export(self, directory, type: str = "web"):
97
+ """Write a Vite + React project (real components, editable src/theme.css) and return its Path.
98
+ type="web" (default) | "windows" | "mac" | "linux": desktop types add an Electron shell + preload."""
99
+ from .export import export
100
+
101
+ return export(self, directory, type)
102
+
103
+ def run(self, host: str = "127.0.0.1", port: int = 8000, openBrowser: bool = False):
104
+ app = self
105
+ fontsDir = Path(self.fontsDir).resolve()
106
+
107
+ class Handler(BaseHTTPRequestHandler):
108
+ def _send(self, code, body: bytes, ctype="text/html; charset=utf-8"):
109
+ self.send_response(code)
110
+ self.send_header("Content-Type", ctype)
111
+ self.send_header("Content-Length", str(len(body)))
112
+ self.end_headers()
113
+ self.wfile.write(body)
114
+
115
+ def _file(self, root: Path, rel: str):
116
+ f = (root / rel).resolve()
117
+ if f.is_file() and f.is_relative_to(root): # no path traversal
118
+ return self._send(200, f.read_bytes(), mimetypes.guess_type(f.name)[0] or "application/octet-stream")
119
+ return self._send(404, b"not found", "text/plain")
120
+
121
+ def do_GET(self):
122
+ path = unquote(urlparse(self.path).path)
123
+ if path.startswith(app.base + "/user-fonts/"):
124
+ return self._file(fontsDir, path[len(app.base) + len("/user-fonts/"):])
125
+ if path.startswith(app.base + "/"):
126
+ return self._file(STATIC.resolve(), path[len(app.base) + 1:])
127
+ key = path if path in app._pages else path.rstrip("/") or "/"
128
+ if key in app._pages:
129
+ return self._send(200, app.html(key).encode())
130
+ self._send(404, b"<h1>404</h1>")
131
+
132
+ def log_message(self, *a):
133
+ pass
134
+
135
+ server = ThreadingHTTPServer((host, port), Handler)
136
+ url = f"http://{host}:{port}"
137
+ print(f"kite: serving {len(self._pages)} page(s) at {url} (Ctrl+C to stop)")
138
+ if openBrowser:
139
+ webbrowser.open(url)
140
+ try:
141
+ server.serve_forever()
142
+ except KeyboardInterrupt:
143
+ pass
144
+ finally:
145
+ server.server_close()
@@ -0,0 +1,10 @@
1
+ from .layout import * # noqa: F401,F403
2
+ from .inputs import * # noqa: F401,F403
3
+ from .display import * # noqa: F401,F403
4
+ from .nav import * # noqa: F401,F403
5
+ from .islands import * # noqa: F401,F403
6
+ from .dock import * # noqa: F401,F403
7
+ from .charts import * # noqa: F401,F403
8
+ from .data import * # noqa: F401,F403
9
+ from .chrome import * # noqa: F401,F403
10
+ from .code import * # noqa: F401,F403
@@ -0,0 +1,103 @@
1
+ """Interactive charts. Python describes the data; the browser draws it (kite/react/components/charts.jsx): hover crosshair
2
+ + tooltip card, click-legend to hide a series, draw-in animation, arrow-key inspection, and live updates:
3
+
4
+ LineChart(rows, x="month", y=["revenue", "costs"], id="rev") # id enables live data
5
+ Script("kite.charts.push('rev', {month: 'Jul', revenue: 9800, costs: 4400}, {max: 24})")
6
+
7
+ AreaChart / BarChart(..., stacked=True) CandlestickChart(rows, x="t", open="o", high="h", low="l", close="c", volume="v")
8
+ DonutChart(rows, label="plan", value="users") Sparkline([3, 5, 2, 8], color="auto")
9
+ rows = list of dicts. prefix="$" / suffix="%" format the axis and tooltip.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import math
14
+
15
+ from ..core import Component, Island, render
16
+
17
+ PALETTE = ["primary", "secondary", "success", "warning", "danger"]
18
+
19
+
20
+ class _Chart(Island):
21
+ island = ""
22
+ kite = "kite-island"
23
+
24
+ def __init__(self, data=(), height=260, **props):
25
+ self.height = height
26
+ super().__init__()
27
+ self.p = {"data": list(data), "height": height, **{k: v for k, v in props.items() if v is not None}}
28
+
29
+ def island_props(self):
30
+ return self.p
31
+
32
+ def inner(self): # shown until the island hydrates
33
+ return f'<div class="kite-skeleton" style="height:{self.height}px"></div>'
34
+
35
+
36
+ class LineChart(_Chart):
37
+ island = "LineChart"
38
+
39
+ def __init__(self, data=(), x="x", y="y", height=260, colors=None, legend=True, grid=True, smooth=True, prefix=None, suffix=None, animate=True, id=None):
40
+ super().__init__(data, height, x=x, y=y, colors=colors, legend=legend, grid=grid, smooth=smooth, prefix=prefix, suffix=suffix, animate=animate, id=id)
41
+
42
+
43
+ class AreaChart(_Chart):
44
+ island = "AreaChart"
45
+
46
+ def __init__(self, data=(), x="x", y="y", height=260, colors=None, legend=True, grid=True, smooth=True, stacked=False, prefix=None, suffix=None, animate=True, id=None):
47
+ super().__init__(data, height, x=x, y=y, colors=colors, legend=legend, grid=grid, smooth=smooth, stacked=stacked, prefix=prefix, suffix=suffix, animate=animate, id=id)
48
+
49
+
50
+ class BarChart(_Chart):
51
+ island = "BarChart"
52
+
53
+ def __init__(self, data=(), x="x", y="y", height=260, colors=None, legend=True, grid=True, stacked=False, prefix=None, suffix=None, animate=True, id=None):
54
+ super().__init__(data, height, x=x, y=y, colors=colors, legend=legend, grid=grid, stacked=stacked, prefix=prefix, suffix=suffix, animate=animate, id=id)
55
+
56
+
57
+ class CandlestickChart(_Chart):
58
+ """OHLC candles + volume. Up candles use --kite-up, down use --kite-down."""
59
+
60
+ island = "CandlestickChart"
61
+
62
+ def __init__(self, data=(), x="x", open="open", high="high", low="low", close="close", volume="volume", height=300, grid=True, prefix=None, suffix=None, animate=True, id=None):
63
+ super().__init__(data, height, x=x, open=open, high=high, low=low, close=close, volume=volume, grid=grid, prefix=prefix, suffix=suffix, animate=animate, id=id)
64
+
65
+
66
+ class DonutChart(_Chart):
67
+ island = "DonutChart"
68
+
69
+ def __init__(self, data=(), label="label", value="value", colors=None, center=None, legend=True, prefix=None, suffix=None, height=190):
70
+ super().__init__(data, height, label=label, value=value, colors=colors, center=center, legend=legend, prefix=prefix, suffix=suffix)
71
+
72
+
73
+ # ---- Sparkline: tiny, static, rendered on the server ----
74
+ def _smooth(pts):
75
+ d = f"M{pts[0][0]:.1f},{pts[0][1]:.1f}"
76
+ for i in range(len(pts) - 1):
77
+ p0, p1, p2, p3 = pts[max(i - 1, 0)], pts[i], pts[i + 1], pts[min(i + 2, len(pts) - 1)]
78
+ d += f"C{p1[0] + (p2[0] - p0[0]) / 6:.1f},{p1[1] + (p2[1] - p0[1]) / 6:.1f} {p2[0] - (p3[0] - p1[0]) / 6:.1f},{p2[1] - (p3[1] - p1[1]) / 6:.1f} {p2[0]:.1f},{p2[1]:.1f}"
79
+ return d
80
+
81
+
82
+ class Sparkline(Component):
83
+ """Sparkline([3, 5, 2, 8], color="primary" | "auto" (green up / red down) | any CSS color, width=120, height=36, area=True)"""
84
+
85
+ kite = "kite-spark"
86
+
87
+ def __init__(self, values=(), color="primary", width=120, height=36, area=True, **kw):
88
+ super().__init__(**kw)
89
+ self.values, self.w, self.h, self.area = list(values), width, height, area
90
+ if color == "auto":
91
+ color = "up" if self.values and self.values[-1] >= self.values[0] else "down"
92
+ self.color = f"var(--kite-{color})" if color in PALETTE + ["up", "down"] else color
93
+
94
+ def inner(self) -> str:
95
+ v, w, h = self.values, self.w, self.h
96
+ if len(v) < 2:
97
+ return ""
98
+ lo = min(v)
99
+ span = (max(v) - lo) or 1
100
+ pts = [(2 + (w - 4) * i / (len(v) - 1), h - 3 - (x - lo) / span * (h - 6)) for i, x in enumerate(v)]
101
+ d = _smooth(pts)
102
+ fill = f'<path d="{d}L{pts[-1][0]:.1f},{h}L{pts[0][0]:.1f},{h}Z" fill="{self.color}" opacity=".15"/>' if self.area else ""
103
+ return f'<svg viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="Trend">{fill}<path d="{d}" fill="none" stroke="{self.color}" stroke-width="2" stroke-linecap="round"/></svg>'
@@ -0,0 +1,27 @@
1
+ """Sidebar: a vertical nav list (sections, icons, badges)."""
2
+ from __future__ import annotations
3
+
4
+ from ..core import Component, render, render_attrs
5
+ from ..icons import icon
6
+
7
+
8
+ class Sidebar(Component):
9
+ """Sidebar(["Favorites", ("Wi-Fi", "wifi", "#", 2), ("Bluetooth", "bluetooth")], current="Wi-Fi"): plain strings are section headers."""
10
+
11
+ tag = "nav"
12
+ kite = "kite-sidebar"
13
+
14
+ def __init__(self, items=(), current=None, **kw):
15
+ super().__init__(**kw)
16
+ self.items, self.current = list(items), current
17
+
18
+ def inner(self):
19
+ out = []
20
+ for it in self.items:
21
+ if isinstance(it, str):
22
+ out.append(f"<h6>{render(it)}</h6>")
23
+ continue
24
+ label, ic, href, n = (*it, None, None, None)[:4]
25
+ a = render_attrs({"href": href or "#", "aria-current": "page" if label == self.current else None})
26
+ out.append(f'<a{a}>{icon(ic)}{render(label)}{f"<span class=n>{render(n)}</span>" if n is not None else ""}</a>')
27
+ return "".join(out)
@@ -0,0 +1,49 @@
1
+ """CodeBlock: syntax-highlighted code with a copy button. The tokenizer is mirrored in react/components/codeblock.jsx."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from html import escape
6
+
7
+ from ..core import Component, Raw, render_attrs
8
+ from ..icons import icon
9
+
10
+ KEYWORDS = "from|import|def|class|return|if|else|elif|for|in|and|or|not|None|True|False|lambda|with|as|while|try|except|pass|const|let|var|function|null|true|false"
11
+ TOKEN = re.compile(
12
+ r"(#[^\n]*|//[^\n]*)" # 1 comment
13
+ r"|(\"\"\"[\s\S]*?\"\"\"|\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*')" # 2 string
14
+ r"|\b(" + KEYWORDS + r")\b" # 3 keyword
15
+ r"|\b(\d+(?:\.\d+)?)\b" # 4 number
16
+ r"|\b([A-Z][A-Za-z0-9_]*)(?=\()" # 5 Component( call
17
+ )
18
+ CLASSES = {1: "c", 2: "s", 3: "k", 4: "n", 5: "f"}
19
+
20
+
21
+ def tokenize(code: str):
22
+ """[(cls, text)]: cls is c (comment) s (string) k (keyword) n (number) f (Component call) or '' (plain)."""
23
+ out, pos = [], 0
24
+ for m in TOKEN.finditer(code):
25
+ if m.start() > pos:
26
+ out.append(("", code[pos:m.start()]))
27
+ out.append((CLASSES[m.lastindex], m.group(0)))
28
+ pos = m.end()
29
+ if pos < len(code):
30
+ out.append(("", code[pos:]))
31
+ return out
32
+
33
+
34
+ def highlight(code: str) -> Raw:
35
+ return Raw("".join(f'<span class="{c}">{escape(t)}</span>' if c else escape(t) for c, t in tokenize(code)))
36
+
37
+
38
+ class CodeBlock(Component):
39
+ """CodeBlock('Button("Save", color="primary")'): highlighted, themed, with a copy button. lang is only a label."""
40
+
41
+ kite = "kite-codeblock"
42
+
43
+ def __init__(self, code="", lang="python", **kw):
44
+ super().__init__(**kw)
45
+ self.code, self.lang = code.strip("\n"), lang
46
+
47
+ def inner(self):
48
+ return (f'<pre><code>{highlight(self.code)}</code></pre>'
49
+ f'<button type="button" class="kite-codeblock-copy" aria-label="Copy code" {render_attrs({"data-kite-copy": self.code})[1:]}>{icon("copy")}</button>')