├── .gitignore ├── LICENSE ├── README.md ├── assets └── header.png ├── celx ├── __about__.py ├── __init__.py ├── __main__.py ├── application.py ├── callbacks.py ├── default_chrome.xml ├── lua.py └── parsing.py ├── pyproject.toml ├── server ├── counters.xml ├── htmx.js ├── index.php ├── lua.php ├── lua_compiler.php └── zml.lua └── tests └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | TX-02-Retina-SemiCondensed.woff2 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Shade 40 ~ 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![celx](https://github.com/shade40/celx/blob/main/assets/header.png?raw=true) 2 | 3 | ## celx 4 | 5 | A modern terminal UI framework powered by hypermedia served over HTTP. 6 | 7 | ``` 8 | pip install sh40-celx 9 | ``` 10 | 11 | See [/server](https://github.com/shade40/celx/tree/main/server/) for an example server & app. 12 | 13 | ### Quickstart 14 | 15 | `celx` is a TUI application framework inspired by [htmx](htmx.org). It emphasizes the usage of hypermedia 16 | as the engine of application state (HATEOAS) as an alternative to reactive client-side frameworks. `celx` apps are 17 | written as XML fragments, and communicated through the Hypertext Transfer Protocol (HTTP). 18 | 19 | Let's start with a basic application index (running on `/`): 20 | 21 | ```xml 22 | 23 | 24 | 25 | 26 | Hello World 27 | 28 | 29 | This is the app's body 30 | 31 | 32 | 33 | 34 | 35 | ``` 36 | 37 | At the moment, both the header and body will take equal amounts of space on the page. You probably don't want this, 38 | so let's modify `header` to only take 1 cell of height: 39 | 40 | ```xml 41 | 42 | 43 | 44 | ``` 45 | 46 | You can insert a ` 66 | 67 | ``` 68 | 69 | Alternatively, you can use a pre-defined group to do the same: 70 | 71 | ```xml 72 | 75 | ``` 76 | 77 | #### Adding interactivity 78 | 79 | You can press our button already, but you might notice it doesn't do anything. Let's fix that. 80 | 81 | First, add an on-submit event to the button: 82 | 83 | ```xml 84 | 87 | ``` 88 | 89 | And let's add the corresponding endpoint to the server (running on `/content`): 90 | 91 | ```xml 92 | This is some cool content 93 | ``` 94 | 95 | After this, our button will: 96 | 97 | - Send an HTTP `GET` request to `/content`, keeping its result 98 | - Parse the result as a widget, and swap `#body`'s children with it 99 | 100 | The syntax used here is quite simple: 101 | 102 | ` ...` 103 | 104 | ...where command is one of: 105 | 106 | - `GET` 107 | - `POST` 108 | - `insert` 109 | - `swap` 110 | - `append` 111 | 112 | `POST` optionally takes a selector for its first arg (`POST #parent /content`), which controls the 113 | widget whos serialized result will be sent in the request. It defaults to the parent of the widget 114 | executing the request (our button, in this case). 115 | 116 | `insert`, `swap` and `append` take a location as their first argument, similar to `hx-swap`. Its 117 | value must be one of: 118 | 119 | - `in`: Add result into the targets children 120 | - `before`: Add result _before_ the target (by essentially executing the command on the target's parent, offset 121 | by the target's offset) 122 | - `after`: Add result _after_ the target (the same way) 123 | - `None`: (only for `swap`) Replaces the target widget completely, deleting it from its parent and putting 124 | result in its place. 125 | 126 | While `swap` replaces the target's (or its parent's) children completely (deleting previous content), `insert` 127 | and `append` add onto the current list 128 | 129 | So in effect, our text and button will disappear and get replaced by whatever our server returns. 130 | 131 | ![rule](https://singlecolorimage.com/get/707E8C/1600x3) 132 | 133 | ### Features 134 | 135 | #### Hypermedia as the Engine of Application State 136 | 137 | Since applications are served over HTTP, you don't have to write _any_ client side code. So why is that 138 | a good thing? 139 | 140 | - No client-side state duplication (your client doesn't even have to be _aware_ of state) 141 | 142 | You cannot (and should never) trust client side code. If your application state mutates on the 143 | client side, you must be able to validate it on the server, as the client could do _anything_ 144 | with that state. This essentially means you have to have duplicated state, and validation on both 145 | sides. 146 | 147 | Since all of your state is on the server, you avoid most of these issues. 148 | 149 | - You're free to choose your own server 150 | 151 | Don't like Python? You can use any HTTP server, in ANY language. Python is more than fast enough 152 | for our runtime, and this way all custom logic & slow operations happen on the server side in the 153 | language of your choosing. 154 | 155 | - Instant usability, no need to install potentially dangerous application code 156 | 157 | Your users only need the celx runtime to run your application. From that point on, trying out a new 158 | app takes as much as writing in the URL its served at, and pressing enter. No further installation, 159 | no 'clone my repo, download my build tool and execute these commands', not even a `pip install`. 160 | 161 | - Running a celx & html of the same backend on the same server 162 | 163 | Since every bit of state is handled on the backend, you can simply send out different formats to represent 164 | the same interfaces based on who is listening. In the (near) future celx will send a specific header 165 | to tell the server to send celx' XML instead of HTML. 166 | 167 | #### A sophisticated styling engine 168 | 169 | As shown above, each ``. 222 | - [Slate](https://github.com/shade40/slate): The engine powering every interaction we make to the terminal and 223 | its APIs, providing us with intelligent per-changed-character drawing and a way to color text (quite a useful 224 | feature!) 225 | -------------------------------------------------------------------------------- /assets/header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shade40/celx/431faba190e9068a778cf31b620d2fb3938cff30/assets/header.png -------------------------------------------------------------------------------- /celx/__about__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.8.1" 2 | -------------------------------------------------------------------------------- /celx/__init__.py: -------------------------------------------------------------------------------- 1 | from .application import Browser 2 | -------------------------------------------------------------------------------- /celx/__main__.py: -------------------------------------------------------------------------------- 1 | from argparse import ArgumentParser 2 | 3 | from . import Browser 4 | from slate import feed 5 | 6 | 7 | def run(endpoint: str): 8 | """Runs the application at the given endpoint.""" 9 | 10 | with open("debug.lua", "w") as f: 11 | ... 12 | 13 | with Browser(endpoint, title="celx") as app: 14 | ... 15 | 16 | root = app.find("#root") 17 | print(root.children[0].content) 18 | print(app.dump_rules_applied_to(root.children[0].content)) 19 | 20 | def main() -> None: 21 | """The main entrypoint.""" 22 | 23 | parser = ArgumentParser("A prototype browser for celx applications.") 24 | 25 | subs = parser.add_subparsers(required=True) 26 | 27 | run_command = subs.add_parser("run") 28 | run_command.set_defaults(func=run) 29 | run_command.add_argument("endpoint", help="The endpoint to connect to.") 30 | 31 | args = parser.parse_args() 32 | command = args.func 33 | 34 | opts = vars(args) 35 | del opts["func"] 36 | 37 | command(**vars(args)) 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | -------------------------------------------------------------------------------- /celx/application.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from pathlib import Path 3 | from threading import Thread 4 | from time import time 5 | from typing import Any, Callable 6 | from urllib.parse import urlparse 7 | 8 | from lxml.etree import fromstring as ElementTree, Element 9 | from xml.dom.minidom import parseString 10 | from xml.parsers.expat import ExpatError 11 | 12 | from celadon import Application, Page, Widget, Container, Tower, Row, Text, Field, Button 13 | from requests import Session 14 | from zenith import zml_escape 15 | 16 | from .parsing import parse_widget, parse_page 17 | from .callbacks import ( 18 | HTTPMethod, 19 | Instruction, 20 | Verb, 21 | TreeMethod, 22 | ) 23 | from .lua import lua, init_runtime 24 | 25 | 26 | __all__ = ["Browser"] 27 | 28 | 29 | def threaded(func: Callable[..., None]) -> Callable[..., None]: 30 | """Returns a callable that runs the given function in a thread.""" 31 | 32 | @wraps(func) 33 | def _inner(*args, **kwargs) -> None: 34 | Thread(target=func, args=args, kwargs=kwargs).start() 35 | 36 | return _inner 37 | 38 | 39 | class Browser(Application): 40 | """An application class for HTTP pages.""" 41 | 42 | def __init__(self, domain: str, **app_args: Any) -> None: 43 | super().__init__(**app_args) 44 | 45 | init_runtime(lua, self) 46 | 47 | self._registered_components = {} 48 | self._page = Page() 49 | self._url = urlparse(domain) 50 | self.url = self._url.geturl() 51 | self.history = [] 52 | self.history_offset = 0 53 | self._session = Session() 54 | self._session.headers = { 55 | "Accepts": "text/celx", 56 | "CELX_Request": "true", 57 | } 58 | 59 | self._current_instructions: list[list[Instruction]] = [] 60 | 61 | 62 | self.content = Tower( 63 | self._build_chrome(), 64 | Tower(eid="root"), 65 | ) 66 | 67 | def _clear_instructions(_: Page) -> bool: 68 | for instructions in self._current_instructions: 69 | instructions.clear() 70 | 71 | return True 72 | 73 | self.on_page_changed += _clear_instructions 74 | 75 | self.route(self._url.geturl()) 76 | 77 | def _build_chrome(self) -> Widget: 78 | with open(Path(__file__).parents[0] / "default_chrome.xml", "r") as f: 79 | xml = ElementTree(f.read()) 80 | default_chrome, scripts = parse_page(xml, self._registered_components, self) 81 | 82 | for script in scripts: 83 | lua.execute(script) 84 | 85 | user_chrome = None 86 | user_chrome_path = (Path.home() / ".config" / "celx" / "chrome.xml") 87 | 88 | if user_chrome_path.exists(): 89 | with open(user_chrome_path, "r") as f: 90 | xml = ElementTree(f.read()) 91 | 92 | if "disabled" not in xml.attrib: 93 | user_chrome, scripts = parse_page(xml, self._registered_components, self) 94 | 95 | for script in scripts: 96 | lua.execute(script) 97 | 98 | return user_chrome or default_chrome 99 | 100 | 101 | @property 102 | def session(self) -> Session: 103 | """Returns the current requests session.""" 104 | 105 | return self._session 106 | 107 | def __getitem__(self, item: Any) -> Any: 108 | """Implement `__getitem__` for Lua attribute access.""" 109 | 110 | return getattr(self, item) 111 | 112 | def _error(self, error: Exception) -> None: 113 | self.stop() 114 | 115 | self._raised = error 116 | 117 | def _prefix_endpoint(self, endpoint: str) -> str: 118 | """Prefixes hierarchy-only endpoints with the current url and its scheme.""" 119 | 120 | if endpoint.startswith("/"): 121 | return self._url.scheme + "://" + self._url.netloc + endpoint 122 | 123 | return endpoint 124 | 125 | def _http( 126 | self, 127 | method: HTTPMethod, 128 | endpoint: str, 129 | data: dict[str, Any], 130 | handler: Callable[[Element], None], 131 | ) -> Thread: 132 | endpoint = self._prefix_endpoint(endpoint) 133 | 134 | if method is HTTPMethod.GET: 135 | request_data = {"params": data} 136 | else: 137 | request_data = {"data": data} 138 | 139 | if not isinstance(method, HTTPMethod): 140 | self._error(TypeError(f"Invalid method {method!r}.")) 141 | 142 | request = getattr(self._session, method.value.lower()) 143 | 144 | def _execute() -> None: 145 | resp = request(endpoint, **request_data) 146 | 147 | if not 200 <= resp.status_code < 300: 148 | self.stop() 149 | resp.raise_for_status() 150 | 151 | self._url = urlparse(endpoint) 152 | self.url = self._url.geturl() 153 | 154 | # Wrap invalid XML as text 155 | # TODO: Treat response differently based on Content-Type 156 | xml = resp.text 157 | 158 | try: 159 | _ = parseString(xml) 160 | except ExpatError: 161 | xml = zml_escape(xml) 162 | xml = f"{xml}" 163 | 164 | tree = ElementTree(xml) 165 | 166 | for sourceable in ["style", "script", "complib"]: 167 | for node in tree.findall(f".//{sourceable}[@src]"): 168 | resp = self._session.get(self._prefix_endpoint(node.attrib["src"])) 169 | 170 | if not 200 <= resp.status_code < 300: 171 | self.stop() 172 | resp.raise_for_status() 173 | 174 | if sourceable == "complib": 175 | sourced = ElementTree(resp.text) 176 | for child in sourced: 177 | node.append(child) 178 | 179 | for key, value in sourced.attrib.items(): 180 | node.attrib[key] = value 181 | 182 | else: 183 | node.text = resp.text 184 | 185 | del node.attrib["src"] 186 | 187 | return handler(tree) 188 | 189 | thread = Thread(target=_execute) 190 | thread.start() 191 | 192 | return thread 193 | 194 | def _xml_page_route(self, node: Element) -> None: 195 | """Routes to a page loaded from the given XML.""" 196 | 197 | try: 198 | page_node = node.find("page") 199 | 200 | if page_node is None: 201 | raise ValueError("no node found.") 202 | 203 | page = Page(**page_node.attrib) 204 | 205 | widget, scripts = parse_page(page_node, self._registered_components, page) 206 | 207 | for script in scripts: 208 | lua.execute(script) 209 | 210 | self.content = Tower( 211 | self._build_chrome(), 212 | Tower(widget, eid="root"), 213 | ) 214 | 215 | page.append(self.content) 216 | 217 | except Exception as exc: # pylint: disable=broad-exception-caught 218 | self._error(exc) 219 | return 220 | 221 | page.route_name = self._url.geturl() 222 | 223 | # TODO: We don't have to request the page every time we go to it 224 | self.append(page) 225 | 226 | self._page = page 227 | self._mouse_target = self._page[0] 228 | self.on_page_changed(page) 229 | 230 | if page.route_name == "/": 231 | self._terminal.set_title(self.title) 232 | 233 | else: 234 | self._terminal.set_title(page.title) 235 | 236 | self.apply_rules() 237 | self.page._rules_changed = True 238 | 239 | @threaded 240 | def run_instructions( # pylint: disable=too-many-locals,too-many-branches,too-many-statements 241 | self, instructions: list[Instruction], caller: Widget 242 | ) -> None: 243 | """Runs through a list of instructions.""" 244 | 245 | result = None 246 | 247 | def _set_result(xml: Element) -> None: 248 | nonlocal result 249 | 250 | # Drill down to find the first widget, pass that on instead. 251 | if xml.tag == "celx": 252 | for node in xml.findall("./page//"): 253 | if node.tag not in ["style", "script"]: 254 | xml = node 255 | break 256 | 257 | else: 258 | self._error(ValueError("no widget in response")) 259 | return 260 | 261 | result, rules = parse_widget(xml, self._registered_components) 262 | 263 | if self.page is None: 264 | return 265 | 266 | # TODO: There might be cases where we don't want to apply styles immediately, 267 | # like when a future "DELETE" instruction is added. 268 | for selector, rule in rules.items(): 269 | self.page.rule(selector, **rule) 270 | 271 | with open("log", "a") as f: 272 | f.write(str(rules) + "\n") 273 | 274 | self._current_instructions.append(instructions) 275 | 276 | try: # pylint: disable=too-many-nested-blocks 277 | for instr in instructions: 278 | if instr.verb.value in HTTPMethod.__members__: 279 | endpoint, container = instr.args 280 | assert endpoint is not None 281 | 282 | body: Widget | Page | None = caller.parent 283 | 284 | if container is not None: 285 | body = self.find(container) 286 | 287 | if body is None: 288 | raise ValueError(f"nothing matched selector {container!r}") 289 | 290 | if not isinstance(body, Widget): 291 | raise ValueError(f"request body {body!r} is not serializable") 292 | 293 | content = body.serialize() 294 | 295 | self._http( 296 | HTTPMethod(instr.verb.value), endpoint, content, _set_result 297 | ).join() 298 | 299 | continue 300 | 301 | if instr.verb.value in TreeMethod.__members__: 302 | if result is None: 303 | raise ValueError("no result to update tree with") 304 | 305 | selector, modifier = instr.args 306 | assert selector is not None 307 | 308 | target = self.find(selector) 309 | 310 | if target is None: 311 | raise ValueError(f"nothing matched selector {selector!r}") 312 | 313 | if not isinstance(target, Container): 314 | raise ValueError( 315 | f"cannot modify tree of non-container {target!r}" 316 | ) 317 | 318 | if instr.verb is Verb.SWAP: 319 | offsets = {"before": -1, None: 0, "after": 1} 320 | 321 | if modifier == "IN": 322 | target.update_children([result]) 323 | 324 | elif modifier in offsets: 325 | if not isinstance(target.parent, Container): 326 | raise ValueError( 327 | "cannot modify tree of non-container parent of" 328 | + repr(target) 329 | ) 330 | 331 | target.parent.replace( 332 | target, result, offset=offsets[modifier] 333 | ) 334 | 335 | else: 336 | raise ValueError( 337 | f"unknown modifier {modifier!r} for verb {instr.verb!r}" 338 | ) 339 | 340 | elif instr.verb is Verb.INSERT: 341 | if modifier == "IN": 342 | target.insert(0, result) 343 | 344 | else: 345 | if not isinstance(target.parent, Container): 346 | raise ValueError( 347 | "cannot modify tree of non-container parent of" 348 | + repr(target) 349 | ) 350 | 351 | index = target.parent.children.index(target) 352 | offsets = {"before": index, "after": index + 1} 353 | 354 | if modifier not in offsets: 355 | raise ValueError( 356 | f"unknown modifier {modifier!r}" 357 | + f" for verb {instr.verb!r}" 358 | ) 359 | 360 | target.parent.insert(offsets[modifier], result) 361 | 362 | elif instr.verb is Verb.APPEND: 363 | if modifier != "IN": 364 | raise ValueError( 365 | f"unknown modifier {modifier!r} for verb {instr.verb!r}" 366 | ) 367 | 368 | target.append(result) 369 | 370 | # TODO: This is hacky as hell, but we need it for widgets to load in 371 | # .styles 372 | parent = result.parent 373 | self._init_widget(result) 374 | result.parent = parent 375 | 376 | continue 377 | 378 | if instr.verb is Verb.SELECT: 379 | if result is None: 380 | raise ValueError("no result to select from") 381 | 382 | if not isinstance(result, Container): 383 | raise ValueError( 384 | f"cannot select from non container ({result!r})" 385 | ) 386 | 387 | assert instr.args[0] is not None 388 | 389 | result = self.find(instr.args[0], scope=result) 390 | continue 391 | 392 | except Exception as exc: # pylint: disable=broad-exception-caught 393 | self._error(exc) 394 | return 395 | 396 | self._current_instructions.remove(instructions) 397 | 398 | def route(self, destination: str, no_history: bool = False) -> None: 399 | """Routes to the given URL.""" 400 | 401 | if not no_history: 402 | self.history.append(destination) 403 | self.history_offset = 0 404 | 405 | destination = self._prefix_endpoint(destination) 406 | 407 | self._http(HTTPMethod.GET, destination, {}, self._xml_page_route) 408 | 409 | def refresh(self) -> None: 410 | """Reloads the current URL.""" 411 | 412 | self._http(HTTPMethod.GET, self.url, {}, self._xml_page_route) 413 | 414 | def back(self) -> None: 415 | self.history_offset = min(self.history_offset + 1, len(self.history) - 1) 416 | self.route(self.history[-self.history_offset-1], no_history=True) 417 | 418 | def forward(self) -> None: 419 | self.history_offset = max(self.history_offset - 1, 0) 420 | self.route(self.history[-self.history_offset-1], no_history=True) 421 | -------------------------------------------------------------------------------- /celx/callbacks.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from dataclasses import dataclass 4 | from enum import Enum 5 | from typing import Callable 6 | 7 | from celadon import Widget 8 | 9 | 10 | class HTTPMethod(Enum): 11 | """An enumeration of supported HTTP methods.""" 12 | 13 | GET = "GET" 14 | POST = "POST" 15 | DELETE = "DELETE" 16 | PUT = "PUT" 17 | PATCH = "PATCH" 18 | 19 | 20 | class TreeMethod(Enum): 21 | """An enumeration of supported tree-manipulation methods.""" 22 | 23 | INSERT = "INSERT" 24 | SWAP = "SWAP" 25 | APPEND = "APPEND" 26 | 27 | 28 | class Verb(Enum): 29 | """An enumeration of supported verbs in Chocl.""" 30 | 31 | GET = HTTPMethod.GET.value 32 | POST = HTTPMethod.POST.value 33 | DELETE = HTTPMethod.DELETE.value 34 | PUT = HTTPMethod.PUT.value 35 | PATCH = HTTPMethod.PATCH.value 36 | 37 | INSERT = TreeMethod.INSERT.value 38 | SWAP = TreeMethod.SWAP.value 39 | APPEND = TreeMethod.APPEND.value 40 | 41 | SELECT = "SELECT" 42 | 43 | 44 | @dataclass 45 | class Instruction: 46 | """A single Chocl instruction.""" 47 | 48 | verb: Verb 49 | args: list[str | None] 50 | 51 | 52 | def _instruction_runner(instructions: list[Instruction]) -> Callable[[Widget], bool]: 53 | """Creates a function to runs the given instructions on the calller widget's app.""" 54 | 55 | def _interpret(self: Widget) -> bool: 56 | # self.app must be `HttpApplication` by this point. 57 | self.app.run_instructions(instructions, self) # type: ignore 58 | 59 | return True 60 | 61 | return _interpret 62 | 63 | 64 | def parse_callback(text: str) -> Callable[[Widget], bool]: 65 | """Parses a callback descriptor into a list of Instructions.""" 66 | 67 | lines = re.split("[;\n]", text) 68 | 69 | instructions = [] 70 | first = True 71 | 72 | for line in lines: 73 | verb_str, *args = line.strip().split() 74 | verb = Verb(verb_str.upper().lstrip(":")) 75 | 76 | if first and verb.value not in HTTPMethod.__members__: 77 | raise ValueError(f"first verb must be an HTTP method, got {verb!r}") 78 | 79 | first = False 80 | 81 | if verb is Verb.SELECT: 82 | if len(args) > 1: 83 | raise ValueError(f"too many arguments for verb {verb!r}") 84 | 85 | instructions.append(Instruction(verb, [args[0]])) 86 | 87 | else: 88 | if len(args) > 2: 89 | raise ValueError(f"too many arguments for verb {verb!r}") 90 | 91 | modifier = None 92 | arg = args[0] 93 | 94 | if len(args) == 2: 95 | modifier, arg = args 96 | modifier = modifier.upper() 97 | 98 | instructions.append(Instruction(verb, [arg, modifier])) 99 | 100 | return _instruction_runner(instructions) 101 | -------------------------------------------------------------------------------- /celx/default_chrome.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 12 | 16 | 22 | 23 | 24 | 25 | 40 | 47 | 48 | 55 | celx v1.0 - $offset 56 | 57 | 58 | 62 | 63 | 64 | 69 | ⟳ 70 | 71 | 72 | 81 | < 82 | 83 | 84 | 93 | > 94 | 95 | 96 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /celx/lua.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | from functools import partial 4 | from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar 5 | from textwrap import dedent 6 | 7 | from lupa import LuaRuntime # type: ignore # pylint: disable=no-name-in-module 8 | from celadon import Widget, widgets 9 | from zenith import zml_alias, zml_macro, MacroType, zml_escape, zml_expand_aliases 10 | 11 | from .callbacks import parse_callback 12 | 13 | if TYPE_CHECKING: 14 | from .application import HttpApplication 15 | 16 | WIDGET_TYPES = { 17 | key.lower(): value 18 | for key, value in vars(widgets).items() 19 | if isinstance(value, type) and issubclass(value, Widget) 20 | } 21 | 22 | LuaTable = TypeVar("LuaTable") 23 | 24 | LUA_SCOPE_SETUP = """ 25 | builtins = { 26 | ipairs = ipairs, 27 | next = next, 28 | pairs = pairs, 29 | pcall = pcall, 30 | tonumber = tonumber, 31 | tostring = tostring, 32 | type = type, 33 | coroutine = { create = coroutine.create, resume = coroutine.resume, 34 | running = coroutine.running, status = coroutine.status, 35 | wrap = coroutine.wrap }, 36 | string = { byte = string.byte, char = string.char, find = string.find, 37 | format = string.format, gmatch = string.gmatch, gsub = string.gsub, 38 | len = string.len, lower = string.lower, match = string.match, 39 | rep = string.rep, reverse = string.reverse, sub = string.sub, 40 | upper = string.upper }, 41 | table = { insert = table.insert, maxn = table.maxn, remove = table.remove, 42 | sort = table.sort, unpack = table.unpack }, 43 | math = { abs = math.abs, acos = math.acos, asin = math.asin, 44 | atan = math.atan, atan2 = math.atan2, ceil = math.ceil, cos = math.cos, 45 | cosh = math.cosh, deg = math.deg, exp = math.exp, floor = math.floor, 46 | fmod = math.fmod, frexp = math.frexp, huge = math.huge, 47 | ldexp = math.ldexp, log = math.log, log10 = math.log10, max = math.max, 48 | min = math.min, modf = math.modf, pi = math.pi, pow = math.pow, 49 | rad = math.rad, random = math.random, sin = math.sin, sinh = math.sinh, 50 | sqrt = math.sqrt, tan = math.tan, tanh = math.tanh }, 51 | os = { clock = os.clock, difftime = os.difftime, time = os.time }, 52 | copy = copy, 53 | setmetatable = setmetatable, 54 | print = print, 55 | error = error, 56 | debug = { getupvalue = debug.getupvalue, upvaluejoin = debug.upvaluejoin }, 57 | dump_keys = function(t) 58 | local result = "" 59 | 60 | for k, _ in pairs(t) do 61 | result = result .. tostring(k) .. ", " 62 | end 63 | 64 | return result 65 | end, 66 | dump_values = function(t) 67 | local result = "" 68 | 69 | for _, v in pairs(t) do 70 | result = result .. tostring(v) .. ", " 71 | end 72 | 73 | return result 74 | end, 75 | setfenv = function(fn, env) 76 | local i = 1 77 | while true do 78 | local name = debug.getupvalue(fn, i) 79 | if name == "_ENV" then 80 | debug.upvaluejoin(fn, i, (function() 81 | return env 82 | end), 1) 83 | break 84 | elseif not name then 85 | break 86 | end 87 | 88 | i = i + 1 89 | end 90 | 91 | return fn 92 | end, 93 | } 94 | 95 | sandbox = { 96 | builtins = builtins, 97 | app = nil, 98 | stack = {}, 99 | envs = {}, 100 | 101 | alert = function(text) 102 | local text = tostring(text) 103 | 104 | app.pin(w.Dialogue{ 105 | w.Text{text, group="body"}, 106 | w.Row{ 107 | w.Button{"Close", on_submit={ 108 | function() app.unpin_last() end 109 | }}, 110 | group="input", 111 | } 112 | }) 113 | end, 114 | 115 | confirm = function(title, body, callback) 116 | app.pin(w.Dialogue{ 117 | w.Text{title, group="title"}, 118 | w.Text{body, group="body"}, 119 | w.Row{ 120 | w.Button{ 121 | "Confirm", 122 | on_submit={function() 123 | app.unpin_last() 124 | callback(true) 125 | end} 126 | }, 127 | w.Button{ 128 | "Deny", 129 | on_submit={function() 130 | app.unpin_last() 131 | callback(false) 132 | end} 133 | }, 134 | group="input" 135 | } 136 | }) 137 | end, 138 | 139 | prompt = function(title, body, callback) 140 | app.pin(w.Dialogue{ 141 | w.Text{tostring(title)}, 142 | w.Tower{group="body", table.unpack(body)}, 143 | w.Row{ 144 | w.Button{"Submit", on_submit={function() 145 | callback(app.unpin_last()) 146 | end}}, 147 | group="input" 148 | } 149 | }) 150 | end, 151 | 152 | find = function(selector, multiple) 153 | if multiple then 154 | return table.from_py(app.find_all(selector)) 155 | end 156 | 157 | return app.find(selector) 158 | end, 159 | 160 | initScope = function(hiddenScope) 161 | local innerScope = {} 162 | 163 | local _listeners = {} 164 | local _children = {} 165 | 166 | return setmetatable({ 167 | on_change = function(field, callback) 168 | if _listeners[field] == nil then 169 | _listeners[field] = {} 170 | end 171 | 172 | table.insert(_listeners[field], callback) 173 | end, 174 | 175 | hasOwn = function(k) 176 | return innerScope[k] ~= nil 177 | end, 178 | 179 | builtins = builtins, 180 | 181 | _children = _children, 182 | _listeners = _listeners, 183 | }, { 184 | __index = function(t, k) 185 | local value = innerScope[k] 186 | 187 | if value == nil then 188 | value = hiddenScope[k] 189 | end 190 | 191 | if value == nil then 192 | value = builtins[k] 193 | end 194 | 195 | if builtins.type(value) == "function" then 196 | builtins.setfenv(value, t) 197 | end 198 | 199 | return value 200 | end, 201 | 202 | __pairs = function(t) 203 | local merged = {{}} 204 | 205 | for k, v in pairs(hiddenScope) do 206 | merged[k] = v 207 | end 208 | 209 | for k, v in pairs(innerScope) do 210 | merged[k] = v 211 | end 212 | 213 | return pairs(merged) 214 | end, 215 | 216 | __newindex = function(t, k, v) 217 | local current = hiddenScope[k] 218 | 219 | if current == nil or builtins.type(current) == "function" then 220 | innerScope[k] = v 221 | else 222 | hiddenScope[k] = v 223 | end 224 | 225 | if current ~= v and _listeners[k] ~= nil then 226 | for _, callback in ipairs(_listeners[k]) do 227 | builtins.setfenv(callback, t)(v) 228 | end 229 | 230 | for _, subenv in ipairs(_children) do 231 | local listeners = subenv._listeners[k] 232 | 233 | if listeners ~= nil then 234 | for _, callback in pairs(listeners) do 235 | builtins.setfenv(callback, subenv)(v) 236 | end 237 | end 238 | end 239 | end 240 | end, 241 | }) 242 | end 243 | } 244 | """ 245 | 246 | 247 | def _attr_filter(_, attr, __): 248 | """Removes access to sunder and dunder attributes in Lua code.""" 249 | 250 | if not isinstance(attr, str): 251 | return attr 252 | 253 | if attr.startswith("_"): 254 | raise AttributeError("access denied") 255 | 256 | return attr 257 | 258 | 259 | class LuaStyleWrapper: 260 | """Wraps a widget's style object for nice Lua syntax. 261 | 262 | ``` 263 | styles.content = 'red' 264 | styles(some_widget).content = 'blue' 265 | ``` 266 | """ 267 | 268 | def __init__(self, widget: Widget) -> None: 269 | self._widget = widget 270 | 271 | def __setattr__(self, attr: str, value: Any) -> None: 272 | if attr == "_widget": 273 | super().__setattr__(attr, value) 274 | 275 | return 276 | 277 | self._widget.app.rule( 278 | self._widget.as_query(), score=9999, **{f"{attr}_style": value} 279 | ) 280 | 281 | def __call__(self, widget: Widget) -> LuaStyleWrapper: 282 | return self.__class__(widget) 283 | 284 | 285 | def _multi_find( 286 | app: "HttpApplication", selector: str, multiple: bool = False 287 | ) -> Widget | list[Widget] | None: 288 | """Finds widgets from the application.""" 289 | 290 | """ 291 | """ 292 | 293 | if multiple: 294 | return lua.table_from([*app.find_all(selector)]) 295 | 296 | return app.find(selector) 297 | 298 | 299 | def _zml_define(name: str, macro: MacroType) -> None: 300 | """Defines a macro in Lua.""" 301 | 302 | def _inner(*args) -> str: 303 | return macro(*args) 304 | 305 | _inner.__name__ = name.replace(" ", "_") 306 | zml_macro(_inner) 307 | 308 | 309 | def _chocl(descriptor: str) -> Callable[[Widget], bool]: 310 | """Provides Lua access to the celx hypermedia-oriented callback language.""" 311 | 312 | return parse_callback(descriptor) 313 | 314 | 315 | def _remove_and_callback_with( 316 | dialogue: widgets.Dialogue, callback: Callable, value: Any 317 | ) -> bool: 318 | dialogue.remove_from_parent() 319 | callback(value) 320 | 321 | return False 322 | 323 | 324 | def _widget_factory(envs: LuaTable, typ: Type[Widget]) -> Callable[[LuaTable], Widget]: 325 | """Lets Lua instantiate widgets. 326 | 327 | ``` 328 | Button{"label", on_submit={function() alert("hey") end }} 329 | ``` 330 | """ 331 | 332 | setfenv = lua.globals().builtins.setfenv 333 | getenv = lua.globals().sandbox.env 334 | 335 | widget = None 336 | 337 | def _create(options: LuaTable) -> Widget: 338 | nonlocal widget 339 | 340 | args = [] 341 | kwargs = {} 342 | 343 | for key, value in options.items(): 344 | if isinstance(key, int): 345 | args.append(value) 346 | continue 347 | 348 | if key == "groups": 349 | value = tuple(value.values()) 350 | 351 | # Likely a Lua table 352 | elif hasattr(value, "values"): 353 | if all(isinstance(val, int) for val in list(value)): 354 | value = [*value.values()] 355 | else: 356 | value = dict(value.items()) 357 | 358 | if callable(value): 359 | value = _scope_func(value) 360 | 361 | kwargs[key] = value 362 | 363 | widget = typ(*args, **kwargs) 364 | return widget 365 | 366 | return _create 367 | 368 | 369 | def _env_getter(envs: LuaTable) -> Callable[[Widget], LuaTable]: 370 | def _inner(widget: Widget) -> LuaTable: 371 | return envs[id(widget)] 372 | 373 | return _inner 374 | 375 | 376 | def init_runtime(runtime: LuaRuntime, app: "HttpApplication") -> None: 377 | """Sets up the global namespace for the given runtime.""" 378 | 379 | runtime.execute(LUA_SCOPE_SETUP) 380 | 381 | sandbox = runtime.globals().sandbox 382 | runtime.globals().builtins.table.from_py = runtime.table_from 383 | 384 | sandbox.app = app 385 | sandbox.timeout = app.timeout 386 | 387 | sandbox.env = _env_getter(sandbox.envs) 388 | sandbox.styles = LuaStyleWrapper 389 | sandbox.chocl = parse_callback 390 | sandbox.len = len 391 | 392 | sandbox.zml = { 393 | "alias": zml_alias, 394 | "define": _zml_define, 395 | "escape": zml_escape, 396 | "expand_aliases": zml_expand_aliases, 397 | } 398 | sandbox.w = { 399 | key.title(): _widget_factory(sandbox.envs, value) 400 | for key, value in WIDGET_TYPES.items() 401 | } 402 | 403 | runtime.execute( 404 | dedent( 405 | """ 406 | do table.insert(sandbox.stack, _ENV) 407 | scope = {} 408 | for k, v in pairs(sandbox) do 409 | scope[k] = v 410 | end 411 | 412 | sandbox.envs[0] = sandbox.initScope(scope) 413 | end 414 | """ 415 | ) 416 | ) 417 | 418 | 419 | class LoggedLuaRuntime(LuaRuntime): 420 | FILE = "debug.lua" 421 | 422 | def execute(self, code: str, **kwargs) -> Any: 423 | if self.FILE: 424 | with open(self.FILE, "a") as f: 425 | f.write(code + "\n") 426 | 427 | return super().execute(code, **kwargs) 428 | 429 | 430 | lua = LoggedLuaRuntime( 431 | register_eval=False, 432 | register_builtins=False, 433 | unpack_returned_tuples=True, 434 | attribute_filter=_attr_filter, 435 | ) 436 | -------------------------------------------------------------------------------- /celx/parsing.py: -------------------------------------------------------------------------------- 1 | import re 2 | from lxml.etree import Element, fromstring, tostring 3 | 4 | import lupa 5 | from copy import deepcopy 6 | from dataclasses import dataclass 7 | from typing import Any, Callable 8 | from textwrap import indent, dedent 9 | 10 | from celadon import Widget, load_rules, Page 11 | 12 | from .lua import lua, LuaTable, WIDGET_TYPES 13 | from .callbacks import parse_callback 14 | 15 | STYLE_TEMPLATE = """\ 16 | {query}: 17 | {indented_content}\ 18 | """ 19 | 20 | LUA_SCRIPT_BEGIN = """\ 21 | do table.insert(stack, _ENV) 22 | _ENV = initScope(_ENV) 23 | env_id = {script_id} 24 | 25 | -- USER CODE BEGIN 26 | """ 27 | 28 | LUA_SCRIPT_END = """ 29 | -- USER CODE END 30 | 31 | envs[{script_id}] = _ENV 32 | end _ENV = table.remove(stack) 33 | if _children then table.insert(_children, envs[{script_id}]) end 34 | 35 | """ 36 | 37 | EVENT_PREFIXES = ("on", "pre") 38 | 39 | RE_ERROR_LINENO = re.compile('\[string ""\]:(\d+):') 40 | 41 | @dataclass 42 | class RuntimeError(Exception): 43 | funcname: str 44 | widget: Widget 45 | code: str 46 | exc: lupa.LuaError 47 | 48 | lineno: int = -1 49 | 50 | def __post_init__(self): 51 | if (match := RE_ERROR_LINENO.search(str(self.exc))) is None: 52 | return 53 | 54 | self.lineno = int(match[1]) - 1 55 | 56 | def __str__(self): 57 | dedented = dedent("\n".join(self.code.splitlines()[self.lineno - 4 : self.lineno + 5])) 58 | lines = indent(dedented, 2 * " ").splitlines() 59 | 60 | lines[4] = "> " + dedented.splitlines()[4] 61 | 62 | start = None 63 | end = None 64 | 65 | for i, line in enumerate(lines): 66 | if "-- USER CODE BEGIN" in line: 67 | start = i 68 | continue 69 | 70 | if "-- USER CODE END" in line: 71 | end = i 72 | 73 | snippet = "\n".join(lines[start:end]) 74 | 75 | return f"error in '{self.funcname}'\n\n{self.widget.as_query()}:\n\n" + dedent(snippet) 76 | 77 | # TODO: This breaks `width: shrink` for text 78 | def lua_formatted_get_content(scope: dict[str, Any]) -> Callable[[Widget], list[str]]: 79 | """Returns a `get_content` method that formats Lua variables. 80 | 81 | You can use any variable available in the current scope using a $ prefix, like 82 | `$count`. 83 | """ 84 | 85 | def _get_content(self: Widget) -> list[str]: 86 | lines = [] 87 | 88 | for line in self.__class__.get_content(self): 89 | in_var = False 90 | parts = [] 91 | word = "" 92 | 93 | for word in re.split(r"([^a-zA-Z0-9_\.])", line): 94 | if word == "$": 95 | in_var = True 96 | continue 97 | 98 | if in_var: 99 | in_var = False 100 | 101 | value = scope[word] 102 | 103 | if value is None: 104 | raise ValueError( 105 | f"unknown variable '{word}' for {self.as_query()}" 106 | ) 107 | 108 | word = str(value) 109 | 110 | parts.append(word) 111 | 112 | lines.append("".join(parts)) 113 | 114 | return lines 115 | 116 | return _get_content 117 | 118 | 119 | def parse_rules(text: str, query: str | None = None) -> dict[str, Any]: 120 | """Parses a block of YAML rules into a dictionary.""" 121 | 122 | if query is None: 123 | style = dedent(text) 124 | else: 125 | style = STYLE_TEMPLATE.format( 126 | query=query, indented_content=indent(dedent(text), 4 * " ") 127 | ) 128 | 129 | return load_rules(style) 130 | 131 | 132 | def _extract_script( 133 | node: Element, node_to_id: dict[Element, int], outer: bool = False, level: int = 0 134 | ) -> str: 135 | """Recursively extracts scripts starting from the given node.""" 136 | 137 | code = "" 138 | 139 | if outer: 140 | code += "_ENV = sandbox.envs[0]\n\n" 141 | 142 | code += indent( 143 | LUA_SCRIPT_BEGIN.format(script_id=node_to_id[node]), 144 | level * 4 * " ", 145 | ) 146 | 147 | for child in node: 148 | if child.tag == "style": 149 | continue 150 | 151 | if child.tag == "script": 152 | code += indent(dedent(child.text), (level + 1) * 4 * " ") 153 | continue 154 | 155 | code += _extract_script(child, node_to_id, level=level + 1) 156 | 157 | code += indent(LUA_SCRIPT_END.format(script_id=node_to_id[node]), level * 4 * " ") 158 | 159 | return code 160 | 161 | 162 | def _get_pairs(table: LuaTable) -> list[str]: 163 | """Iterates through the `__pairs` of a Lua table.""" 164 | 165 | iterator, state, first_key = lua.globals().pairs(table) 166 | 167 | while True: 168 | item = iterator(state, first_key) 169 | 170 | if item is None: 171 | break 172 | 173 | key, value = item 174 | 175 | yield (key, value) 176 | first_key = key 177 | 178 | 179 | # TODO: Technically rules is more like a `dict[str, dict[str, ]]`! 180 | def parse_widget( 181 | node: Element, 182 | components: dict[str, tuple[dict[str, Any], str]], 183 | parse_script: bool = True, 184 | result: dict[str, list[Widget, Element]] | None = None, 185 | ) -> tuple[Widget, dict[str, Any]]: 186 | """Parses a widget, its scripts & its styling from an XML node.""" 187 | 188 | result = result or {} 189 | 190 | init: dict[str, str | tuple[str, ...] | list[Callable[[Widget], bool]]] = {} 191 | 192 | if node.tag in components: 193 | params, replacement = components[node.tag] 194 | replacement = deepcopy(replacement) 195 | 196 | script = replacement.find("script") 197 | 198 | if script is None: 199 | script = Element("script") 200 | script.text = " " 201 | 202 | node.append(script) 203 | 204 | slot = replacement.find("_slot") 205 | 206 | if slot is not None: 207 | slot_idx = [*replacement].index(slot) 208 | replacement.remove(slot) 209 | 210 | content = [*node] 211 | 212 | for i, child in enumerate(content): 213 | replacement[max(slot_idx - 1 + i, 0)].addnext(child) 214 | 215 | parent = node.getparent() 216 | idx = [*parent].index(node) 217 | 218 | text = tostring(replacement).decode() 219 | 220 | for key, value in params.items(): 221 | text = text.replace(f"${key}", node.get(key, default=value)) 222 | 223 | replacement = fromstring(text.encode()) 224 | 225 | node = replacement 226 | parent[idx] = replacement 227 | 228 | for key, value in node.attrib.items(): 229 | if key == "groups": 230 | init["groups"] = tuple(value.split(" ")) 231 | continue 232 | 233 | if key.startswith(EVENT_PREFIXES): 234 | key = key.replace("-", "_") 235 | 236 | if value.startswith(":"): 237 | init[key] = [parse_callback(value)] 238 | 239 | else: 240 | script_node = node.find("script") 241 | 242 | if script_node is None: 243 | script_node = Element("script") 244 | script_node.text = "" 245 | 246 | script_node.text += f"function {key}() {value} end\n\n" 247 | node.append(script_node) 248 | 249 | continue 250 | 251 | key = key.replace("-", "_") 252 | 253 | if value.isdigit(): 254 | value = int(value) 255 | 256 | elif value.lstrip("-+").replace(".", "", 1).isdigit(): 257 | value = float(value) 258 | 259 | init[key] = value 260 | 261 | text = node.text 262 | 263 | if text is None or text.strip() == "": 264 | text = "" 265 | skipped = 0 266 | total = 0 267 | 268 | for total, child in enumerate(node): 269 | if child.tail is None: 270 | skipped += 1 271 | continue 272 | 273 | text = text + child.tail 274 | 275 | if skipped == total + 1: 276 | text = None 277 | 278 | cls = WIDGET_TYPES[node.tag] 279 | 280 | if text is not None and text.strip() != "": 281 | # The init args aren't strongly typed. 282 | widget = cls(dedent(text).strip("\n"), **init) # type: ignore 283 | else: 284 | widget = cls(**init) # type: ignore 285 | 286 | query = widget.as_query() 287 | scope = None 288 | 289 | rules: dict[str, Any] = {} 290 | 291 | script_id = id(widget) 292 | result[script_id] = widget, node 293 | 294 | for child in node: 295 | if child.tag == "style": 296 | rules.update(**parse_rules(child.text or "", query)) 297 | continue 298 | 299 | if child.tag == "script": 300 | continue 301 | 302 | parsed, parsed_rules = parse_widget( 303 | child, components, parse_script=False, result=result 304 | ) 305 | rules.update(**parsed_rules) 306 | widget += parsed # type: ignore 307 | 308 | if child.tag in WIDGET_TYPES: 309 | result[id(parsed)] = parsed, child 310 | 311 | if parse_script: 312 | code = _extract_script( 313 | node, {node: s_id for s_id, [_, node] in result.items()}, outer=True 314 | ) 315 | 316 | if not parse_script: 317 | return widget, rules 318 | 319 | sandbox = lua.eval("sandbox") 320 | envs = lua.eval("sandbox.envs") 321 | setfenv = lua.eval("builtins.setfenv") 322 | 323 | try: 324 | lua.execute(code) 325 | except lupa.LuaSyntaxError as exc: 326 | # TODO: This could alert() instead and abort exec 327 | raise exc 328 | 329 | for s_id, [widget, _] in reversed(result.items()): 330 | env = envs[s_id] 331 | 332 | if env is None: 333 | continue 334 | 335 | env.self = widget 336 | 337 | for key, value in _get_pairs(env): 338 | if sandbox[key] is not None: 339 | continue 340 | 341 | if callable(value): 342 | if not env.hasOwn(key): 343 | continue 344 | 345 | value = setfenv(value, env) 346 | 347 | if key == "init": 348 | value() 349 | continue 350 | 351 | if isinstance(key, str) and key.startswith(EVENT_PREFIXES): 352 | event = getattr(widget, key, None) 353 | 354 | if event is None: 355 | raise ValueError(f"invalid event handler {key!r}") 356 | 357 | assert callable(value) 358 | 359 | event += _report_env_id(value, s_id, code, widget, key) 360 | 361 | # Set formatted get content for the widget 362 | get_content = lua_formatted_get_content(env) 363 | widget.get_content = get_content.__get__(widget, widget.__class__) # type: ignore 364 | 365 | return widget, rules 366 | 367 | def _report_env_id(callback, env_id, code, widget, key): 368 | """Wraps a function and reports its environment id with exceptions it raises.""" 369 | 370 | def _inner(*args, **kwargs): 371 | try: 372 | return callback(*args, **kwargs) 373 | 374 | except Exception as e: 375 | raise RuntimeError(key, widget, code, e) 376 | 377 | return _inner 378 | 379 | 380 | def _register_component( 381 | node: Element, components: dict[str, str], namespace: str | None = None 382 | ) -> None: 383 | name = None 384 | params = {} 385 | 386 | for key, value in node.attrib.items(): 387 | if key == "name": 388 | name = value 389 | continue 390 | 391 | params[key] = value 392 | 393 | if name is None: 394 | raise ValueError("components must have a name.") 395 | 396 | if namespace is not None: 397 | name = namespace + "." + name 398 | 399 | components[name] = params, node[0] 400 | 401 | 402 | def parse_page(page_node: Element, components: dict[str, str], page: Page) -> tuple[Widget | None, list[str]]: 403 | """Parses a page, its scripts & its children from XML node.""" 404 | 405 | content_nodes = [node for node in page_node if node.tag not in ["component", "complib", "style", "script"]] 406 | 407 | if len(content_nodes) > 1: 408 | raise ValueError("pages must have exactly one content node.", content_nodes) 409 | 410 | root = None 411 | scripts = []; 412 | 413 | for child in page_node: 414 | if child.tag == "complib": 415 | namespace = child.get("namespace") 416 | 417 | for inner in child: 418 | _register_component(inner, components, namespace) 419 | 420 | continue 421 | 422 | if child.tag == "component": 423 | _register_component(child, components) 424 | continue 425 | 426 | if child.tag == "style": 427 | for selector, rule in parse_rules(child.text or "").items(): 428 | page.rule(selector, **rule) 429 | 430 | continue 431 | 432 | if child.tag == "script": 433 | scripts.append("_ENV = sandbox.envs[0]\n" + dedent(child.text)) 434 | continue 435 | 436 | if child.tag in WIDGET_TYPES or child.tag in components: 437 | root, rules = parse_widget(child, components) 438 | 439 | for selector, rule in rules.items(): 440 | page.rule(selector, **rule) 441 | 442 | else: 443 | raise ValueError(child.tag) 444 | 445 | return root, scripts 446 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling>=1.26.1"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "sh40-celx" 7 | description = "A modern terminal UI framework powered by hypermedia served over HTTP." 8 | readme = "README.md" 9 | requires-python = ">=3.8" 10 | license = "MIT" 11 | keywords = [] 12 | authors = [ 13 | { name = "bczsalba", email = "bczsalba@gmail.com" }, 14 | ] 15 | classifiers = [ 16 | "Environment :: Console", 17 | "Intended Audience :: Developers", 18 | "License :: OSI Approved :: MIT License", 19 | "Operating System :: MacOS", 20 | "Operating System :: POSIX :: Linux", 21 | "Development Status :: 4 - Beta", 22 | "Programming Language :: Python", 23 | "Programming Language :: Python :: 3.8", 24 | "Programming Language :: Python :: 3.9", 25 | "Programming Language :: Python :: 3.10", 26 | "Programming Language :: Python :: 3.11", 27 | "Programming Language :: Python :: Implementation :: CPython", 28 | "Programming Language :: Python :: Implementation :: PyPy", 29 | "Typing :: Typed", 30 | "Topic :: Software Development :: Libraries", 31 | "Topic :: Terminals", 32 | "Topic :: Text Processing :: Markup", 33 | ] 34 | dependencies = ["sh40-celadon", "requests", "lxml", "lupa"] 35 | dynamic = ["version"] 36 | 37 | [project.urls] 38 | Documentation = "https://github.com/shade40/celx#readme" 39 | Issues = "https://github.com/shade40/celx/issues" 40 | Source = "https://github.com/shade40/celx" 41 | 42 | [project.scripts] 43 | celx = "celx.__main__:main" 44 | 45 | [tool.hatch.version] 46 | path = "celx/__about__.py" 47 | 48 | [tool.hatch.build] 49 | include = [ 50 | "celx/*.py", 51 | "celx/py.typed", 52 | "/tests", 53 | ] 54 | 55 | [tool.hatch.envs.default] 56 | dependencies = [ 57 | "mypy", 58 | "pylint", 59 | "pytest", 60 | "pytest-cov", 61 | ] 62 | 63 | [tool.hatch.envs.test] 64 | dependencies = [ 65 | "mypy", 66 | "pylint", 67 | "pytest", 68 | "pytest-cov", 69 | ] 70 | 71 | [tool.hatch.envs.default.scripts] 72 | test = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=celx --cov=tests && coverage html" 73 | lint = "pylint celx" 74 | type = "mypy celx" 75 | upload = "hatch build && twine upload dist/* && hatch clean" 76 | 77 | [[tool.hatch.envs.test.matrix]] 78 | python = ["38", "39", "310", "311"] 79 | 80 | [tool.pylint] 81 | fail-under = 9.9 82 | disable = "fixme, missing-module-docstring, no-member" 83 | good-names = ["i", "j", "k", "ex", "Run", "_", "x" ,"y", "fd"] 84 | 85 | [tool.coverage.run] 86 | branch = true 87 | parallel = true 88 | omit = [ 89 | "celx/__about__.py", 90 | ] 91 | 92 | [tool.coverage.report] 93 | exclude_lines = [ 94 | "no cov", 95 | "def __repr__", 96 | "if __name__ == .__main__.:", 97 | "if TYPE_CHECKING:", 98 | ] 99 | -------------------------------------------------------------------------------- /server/counters.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 8 | 19 | <_slot /> 20 | 21 | $value 22 | 23 | 24 | 25 | 26 | 27 | 31 | <_slot /> 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /server/htmx.js: -------------------------------------------------------------------------------- 1 | var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.1"};Q.onLoad=$;Q.process=kt;Q.on=be;Q.off=we;Q.trigger=he;Q.ajax=Hn;Q.find=r;Q.findAll=p;Q.closest=g;Q.remove=K;Q.addClass=Y;Q.removeClass=o;Q.toggleClass=W;Q.takeClass=ge;Q.swap=ze;Q.defineExtension=Un;Q.removeExtension=Bn;Q.logAll=z;Q.logNone=J;Q.parseInterval=d;Q._=_;const n={addTriggerHandler:Et,bodyContains:le,canAccessLocalStorage:j,findThisElement:Ee,filterValues:dn,swap:ze,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:T,getExpressionVars:Cn,getHeaders:hn,getInputValues:cn,getInternalData:ie,getSwapSpecification:pn,getTriggerSpecs:lt,getTarget:Ce,makeFragment:k,mergeObjects:ue,makeSettleInfo:xn,oobSwap:Te,querySelectorExt:fe,settleImmediately:Gt,shouldCancel:dt,triggerEvent:he,triggerErrorEvent:ae,withExtensions:Ut};const v=["get","post","put","delete","patch"];const R=v.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");const O=e("head");function e(e,t=false){return new RegExp(`<${e}(\\s[^>]*>|>)([\\s\\S]*?)<\\/${e}>`,t?"gim":"im")}function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function H(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function T(e,t){while(e&&!t(e)){e=u(e)}return e||null}function q(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;T(t,function(e){return!!(r=q(t,ce(e),n))});if(r!=="unset"){return r}}function a(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function L(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function N(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function A(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function I(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function P(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function D(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(P(e)){const t=I(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){w(e)}finally{e.remove()}}})}function k(e){const t=e.replace(O,"");const n=L(t);let r;if(n==="html"){r=new DocumentFragment;const i=N(e);A(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=N(t);A(r,i.body);r.title=i.title}else{const i=N('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){D(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function M(e){return typeof e==="function"}function X(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function le(e){const t=e.getRootNode&&e.getRootNode();if(t&&t instanceof window.ShadowRoot){return ne().body.contains(t.host)}else{return ne().body.contains(e)}}function B(e){return e.trim().split(/\s+/)}function ue(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){w(e);return null}}function j(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function V(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function _(e){return vn(ne().body,function(){return eval(e)})}function $(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function z(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function J(){Q.logger=null}function r(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return r(ne(),e)}}function p(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return p(ne(),e)}}function E(){return window}function K(e,t){e=y(e);if(t){E().setTimeout(function(){K(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function G(e){return e instanceof HTMLElement?e:null}function Z(e){return typeof e==="string"?e:null}function h(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function Y(e,t,n){e=ce(y(e));if(!e){return}if(n){E().setTimeout(function(){Y(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function o(e,t,n){let r=ce(y(e));if(!r){return}if(n){E().setTimeout(function(){o(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function ge(e,t){e=y(e);se(e.parentElement.children,function(e){o(e,t)});Y(ce(e),t)}function g(e,t){e=ce(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||a(e,t)){return e}}while(e=e&&ce(u(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function pe(e,t){return e.substring(e.length-t.length)===t}function i(e){const t=e.trim();if(l(t,"<")&&pe(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(e,t,n){e=y(e);if(t.indexOf("closest ")===0){return[g(ce(e),i(t.substr(8)))]}else if(t.indexOf("find ")===0){return[r(h(e),i(t.substr(5)))]}else if(t==="next"){return[ce(e).nextElementSibling]}else if(t.indexOf("next ")===0){return[me(e,i(t.substr(5)),!!n)]}else if(t==="previous"){return[ce(e).previousElementSibling]}else if(t.indexOf("previous ")===0){return[ye(e,i(t.substr(9)),!!n)]}else if(t==="document"){return[document]}else if(t==="window"){return[window]}else if(t==="body"){return[document.body]}else if(t==="root"){return[H(e,!!n)]}else if(t.indexOf("global ")===0){return m(e,t.slice(7),true)}else{return F(h(H(e,!!n)).querySelectorAll(i(t)))}}var me=function(t,e,n){const r=h(H(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function fe(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return r(h(t)||document,e)}else{return e}}function xe(e,t,n){if(M(t)){return{target:ne().body,event:Z(e),listener:t}}else{return{target:y(e),event:Z(t),listener:n}}}function be(t,n,r){_n(function(){const e=xe(t,n,r);e.target.addEventListener(e.event,e.listener)});const e=M(n);return e?n:r}function we(t,n,r){_n(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return M(n)?n:r}const ve=ne().createElement("output");function Se(e,t){const n=re(e,t);if(n){if(n==="this"){return[Ee(e,t)]}else{const r=m(e,n);if(r.length===0){w('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Ee(e,t){return ce(T(e,function(e){return te(ce(e),t)!=null}))}function Ce(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Ee(e,"hx-target")}else{return fe(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Re(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substr(0,e.indexOf(":"));t=e.substr(e.indexOf(":")+1,e.length)}else{s=e}const n=ne().querySelectorAll(t);if(n){se(n,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=h(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){_e(s,e,e,t,i)}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);ae(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function qe(e){se(p(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){e.parentNode.replaceChild(n,e)}})}function Le(l,e,u){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=h(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);u.tasks.push(function(){Oe(t,s)})}}})}function Ne(e){return function(){o(e,Q.config.addedClass);kt(ce(e));Ae(h(e));he(e,"htmx:load")}}function Ae(e){const t="[autofocus]";const n=G(a(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;Y(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ne(o))}}}function Ie(e,t){let n=0;while(n0){E().setTimeout(l,r.settleDelay)}else{l()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(!X(e)){e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){ae(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(nt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function b(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function ot(e){let t;if(e.length>0&&Qe.test(e[0])){e.shift();t=b(e,et).trim();e.shift()}else{t=b(e,x)}return t}const it="input, textarea, select";function st(e,t,n){const r=[];const o=tt(t);do{b(o,We);const l=o.length;const u=b(o,/[,\[\s]/);if(u!==""){if(u==="every"){const c={trigger:"every"};b(o,We);c.pollInterval=d(b(o,/[,\[\s]/));b(o,We);var i=rt(e,o,"event");if(i){c.eventFilter=i}r.push(c)}else{const f={trigger:u};var i=rt(e,o,"event");if(i){f.eventFilter=i}while(o.length>0&&o[0]!==","){b(o,We);const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(b(o,x))}else if(a==="from"&&o[0]===":"){o.shift();if(Qe.test(o[0])){var s=ot(o)}else{var s=b(o,x);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=ot(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=ot(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(b(o,x))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=b(o,x)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=ot(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=b(o,x)}else{ae(e,"htmx:syntax:error",{token:o.shift()})}}r.push(f)}}if(o.length===l){ae(e,"htmx:syntax:error",{token:o.shift()})}b(o,We)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function lt(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||st(e,t,r)}if(n.length>0){return n}else if(a(e,"form")){return[{trigger:"submit"}]}else if(a(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(a(e,it)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function ut(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ft(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ht(t,n,e){if(t instanceof HTMLAnchorElement&&ft(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";if(r==="get"){}o=ee(t,"action")}e.forEach(function(e){mt(t,function(e,t){const n=ce(e);if(at(n)){f(n);return}de(r,o,n,t)},n,e,true)})}}function dt(e,t){const n=ce(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(a(n,'input[type="submit"], button')&&g(n,"form")!==null){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function gt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;ae(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function mt(s,l,e,u,c){const f=ie(s);let t;if(u.from){t=m(s,u.from)}else{t=[s]}if(u.changed){t.forEach(function(e){const t=ie(e);t.lastValue=e.value})}se(t,function(o){const i=function(e){if(!le(s)){o.removeEventListener(u.trigger,i);return}if(gt(s,e)){return}if(c||dt(e,s)){e.preventDefault()}if(pt(u,s,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(s)<0){t.handledFor.push(s);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!a(ce(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=ie(o);const r=o.value;if(n.lastValue===r){return}n.lastValue=r}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){l(s,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){l(s,e)},u.delay)}else{he(s,"htmx:trigger");l(s,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:i,on:o});o.addEventListener(u.trigger,i)})}let yt=false;let xt=null;function bt(){if(!xt){xt=function(){yt=true};window.addEventListener("scroll",xt);setInterval(function(){if(yt){yt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){wt(e)})}},200)}}function wt(e){if(!s(e,"data-hx-revealed")&&U(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function St(t,n,e){let i=false;se(v,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){Et(t,e,n,function(e,t){const n=ce(e);if(g(n,Q.config.disableSelector)){f(n);return}de(r,o,n,t)})})}});return i}function Et(r,e,t,n){if(e.trigger==="revealed"){bt();mt(r,n,t,e);wt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=fe(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{mt(r,n,t,e)}}function Ct(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function qt(e){const t=g(ce(e.target),"button, input[type='submit']");const n=Nt(e);if(n){n.lastButtonClicked=t}}function Lt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function Nt(e){const t=g(ce(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",qt);e.addEventListener("focusin",qt);e.addEventListener("focusout",Lt)}function It(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){De(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){ae(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function _t(t){if(!j()){return null}t=V(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=k(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=jt();const r=xn(n);kn(e.title);Ve(n,t,r);Gt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{ae(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Yt(e){zt();e=e||location.pathname+location.search;const t=_t(e);if(t){const n=k(t.content);const r=jt();const o=xn(r);kn(n.title);Ve(r,n,o);Gt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Zt(e)}}}function Wt(e){let t=Se(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Qt(e){let t=Se(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","")});return t}function en(e,t){se(e,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)-1;if(t.requestCount===0){e.removeAttribute("disabled")}})}function tn(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function sn(t,n,r,o,i){if(o==null||tn(t,o)){return}else{t.push(o)}if(nn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=F(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=F(o.files)}rn(s,e,n);if(i){ln(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){on(e.name,e.value,n)}else{t.push(e)}if(i){ln(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}rn(t,e,n)})}}function ln(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function un(t,e){for(const n of e.keys()){t.delete(n);e.getAll(n).forEach(function(e){t.append(n,e)})}return t}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){sn(n,o,i,g(e,"form"),l)}sn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const c=s.lastButtonClicked||e;const f=ee(c,"name");rn(f,c.value,o)}const u=Se(e,"hx-include");se(u,function(e){sn(n,r,i,ce(e),l);if(!a(e,"form")){se(h(e).querySelectorAll(it),function(e){sn(n,r,i,e,l)})}});un(r,o);return{errors:i,formData:r,values:An(r)}}function fn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=Ln(e);let n="";e.forEach(function(e,t){n=fn(n,t,e)});return n}function hn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};wn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function dn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.substr(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function gn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function pn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!gn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=c;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.substr(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.substr("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{w("Unknown modifier in hx-swap: "+l)}}}}return r}function mn(e){return re(e,"hx-encoding")==="multipart/form-data"||a(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function yn(t,n,r){let o=null;Ut(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(mn(n)){return un(new FormData,Ln(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function bn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(fe(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(fe(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function wn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.substr(11);t=true}else if(e.indexOf("js:")===0){e=e.substr(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return wn(ce(u(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{ae(e,"htmx:evalDisallowedError");return n}}function Sn(e,t){return wn(e,"hx-vars",true,t)}function En(e,t){return wn(e,"hx-vals",false,t)}function Cn(e){return ue(Sn(e),En(e))}function Rn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){ae(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function C(e,t){return t.test(e.getAllResponseHeaders())}function Hn(e,t,n){e=e.toLowerCase();if(n){if(n instanceof Element||typeof n==="string"){return de(e,t,null,null,{targetOverride:y(n),returnPromise:true})}else{return de(e,t,y(n.source),n.event,{handler:n.handler,headers:n.headers,values:n.values,targetOverride:y(n.target),swapOverride:n.swap,select:n.select,returnPromise:true})}}else{return de(e,t,null,null,{returnPromise:true})}}function Tn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function qn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ue({url:o,sameHost:r},n))}function Ln(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Nn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(r){return new Proxy(r,{get:function(e,t){if(typeof t==="symbol"){return Reflect.get(e,t)}if(t==="toJSON"){return()=>Object.fromEntries(r)}if(t in e){if(typeof e[t]==="function"){return function(){return r[t].apply(r,arguments)}}else{return e[t]}}const n=r.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Nn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Mn;const X=i.select||null;if(!le(r)){oe(s);return e}const u=i.targetOverride||ce(Ce(r));if(u==null||u==ve){ae(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let c=ie(r);const f=c.lastButtonClicked;if(f){const L=ee(f,"formaction");if(L!=null){n=L}const N=ee(f,"formmethod");if(N!=null){if(N.toLowerCase()!=="dialog"){t=N}}}const a=re(r,"hx-confirm");if(k===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:u,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const A=d.split(":");const I=A[0].trim();if(I==="this"){h=Ee(r,"hx-sync")}else{h=ce(fe(r,I))}d=(A[1]||"drop").trim();c=ie(h);if(d==="drop"&&c.xhr&&c.abortable!==true){oe(s);return e}else if(d==="abort"){if(c.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const Z=d.split(" ");g=(Z[1]||"last").trim()}}if(c.xhr){if(c.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(c.queuedRequests==null){c.queuedRequests=[]}if(g==="first"&&c.queuedRequests.length===0){c.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){c.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){c.queuedRequests=[];c.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;c.xhr=p;c.abortable=F;const m=function(){c.xhr=null;c.abortable=false;if(c.queuedRequests!=null&&c.queuedRequests.length>0){const e=c.queuedRequests.shift();e()}};const U=re(r,"hx-prompt");if(U){var y=prompt(U);if(y===null||!he(r,"htmx:prompt",{prompt:y,target:u})){oe(s);m();return e}}if(a&&!k){if(!confirm(a)){oe(s);m();return e}}let x=hn(r,u,y);if(t!=="get"&&!mn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=ue(x,i.headers)}const B=cn(r,t);let b=B.errors;const j=B.formData;if(i.values){un(j,Ln(i.values))}const V=Ln(Cn(r));const w=un(j,V);let v=dn(w,r);if(Q.config.getCacheBusterParam&&t==="get"){v.set("org.htmx.cache-buster",ee(u,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=wn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:v,parameters:An(v),unfilteredFormData:w,unfilteredParameters:An(w),headers:x,target:u,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;x=C.headers;v=Ln(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const $=n.split("#");const z=$[0];const R=$[1];let O=n;if(E){O=z;const Y=!v.keys().next().done;if(Y){if(O.indexOf("?")<0){O+="?"}else{O+="&"}O+=an(v);if(R){O+="#"+R}}}if(!qn(r,O,C)){ae(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),O,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const D in x){if(x.hasOwnProperty(D)){const W=x[D];Rn(p,D,W)}}}const H={xhr:p,target:u,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:O,responsePath:null,anchor:R}};p.onload=function(){try{const t=Tn(r);H.pathInfo.responsePath=On(p);M(r,H);en(T,q);he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){ae(r,"htmx:onLoadError",ue({error:e},H));throw e}};p.onerror=function(){en(T,q);ae(r,"htmx:afterRequest",H);ae(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){en(T,q);ae(r,"htmx:afterRequest",H);ae(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){en(T,q);ae(r,"htmx:afterRequest",H);ae(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Wt(r);var q=Qt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:yn(p,r,v);p.send(J);return e}function In(e,t){const n=t.xhr;let r=null;let o=null;if(C(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(C(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(C(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const u=re(e,"hx-replace-url");const c=ie(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(u){f="replace";a=u}else if(c){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Pn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Dn(e){for(var t=0;t0){E().setTimeout(e,y.swapDelay)}else{e()}}if(a){ae(o,"htmx:responseError",ue({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Xn={};function Fn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Un(e,t){if(t.init){t.init(n)}Xn[e]=ue(Fn(),t)}function Bn(e){delete Xn[e]}function jn(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Xn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return jn(ce(u(e)),n,r)}var Vn=false;ne().addEventListener("DOMContentLoaded",function(){Vn=true});function _n(e){if(Vn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function $n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function Jn(){const e=zn();if(e){Q.config=ue(Q.config,e)}}_n(function(){Jn();$n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Yt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); -------------------------------------------------------------------------------- /server/index.php: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 18 | 25 | 26 | 31 | 57 | 58 | 59 | 63 | 77 | 78 | 83 | Main 84 | Test 85 | 89 | 90 | 91 | [bold red]TEST PAGE 92 | 93 | 94 | [bold]Primary color: [/fg @main.primary][/] 95 | 96 | Global count: [!threshold(g_count,main.success,10,main.error)]$g_count[/] 97 | [!random(0,100)]Random number: %i[/] 98 | 99 | 100 | 104 | Before forecasts, studies were only forks. A hen is a japan from the right perspective. A pint is a scorpio from the right perspective. Those coffees are nothing more than sciences. The zeitgeist contends that the first pelting donna is, in its own way, a rod. 105 | 106 | 107 | 108 | 112 | Unfortunately, that is wrong; on the contrary, a turn of the larch is assumed to be a boughten refund. The fancied ruth reveals itself as a spacial team to those who look. A history of the menu is assumed to be a halest backbone. The stylized boy comes from a stickit sleep. 113 | 114 | 115 | 119 | Their fly was, in this moment, a claustral indonesia. Mouths are hurried beams. The chastest donkey reveals itself as a rooky sturgeon to those who look. A broccoli of the reward is assumed to be a foggy lace. 120 | 121 | [bold]Counter component instance 122 | 123 | 124 | 128 | [bold]Confirmation dialogue 129 | 144 | 145 | 146 | 147 | 151 | 152 | 153 | 156 | <text> 157 | [bold]Primary color: [/fg @main.primary][/] 158 | 159 | GCount: [!threshold(g_count,main.success,10,main.error)]0[/] 160 | [!random(0,100)]Random: %i[/] 161 | </text> 162 | 163 | 164 | 165 | 171 | 174 | <complib namespace="form"> 175 | <component name="counter" initial="0" min="0" max="10"> 176 | <row eid="friend"> 177 | <style> 178 | gap: 1 179 | height: shrink 180 | </style> 181 | <script> 182 | value = $initial 183 | 184 | function add(num) 185 | value = math.min(math.max(value + num, $min), $max) 186 | end 187 | 188 | function init() 189 | on_change("value", function() count = count + 1 end) 190 | end 191 | </script> 192 | <_slot /> 193 | <button on-submit="add(-1)"> - </button> 194 | <text>$value</text> 195 | <button on-submit="add(1)"> + </button> 196 | </row> 197 | </component> 198 | </complib> 199 | 200 | <form.counter initial="2" max="20"/> 201 | 202 | 203 | 204 | 205 | 206 | 207 | -------------------------------------------------------------------------------- /server/lua.php: -------------------------------------------------------------------------------- 1 | &1"); 6 | -------------------------------------------------------------------------------- /server/lua_compiler.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 48 |
49 | 50 |
51 | 52 |
53 |             
54 |
55 |
56 | 57 | 58 | -------------------------------------------------------------------------------- /server/zml.lua: -------------------------------------------------------------------------------- 1 | zml.define("random", function(fmt, minval, maxval) 2 | return string.format( 3 | fmt, 4 | math.random(tonumber(minval), tonumber(maxval)) 5 | ) 6 | end) 7 | 8 | zml.define("eid", function(fmt) 9 | return string.format(fmt, self.eid) 10 | end) 11 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shade40/celx/431faba190e9068a778cf31b620d2fb3938cff30/tests/__init__.py --------------------------------------------------------------------------------