Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/swift.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Swift

on:
workflow_dispatch:
push:
branches: [main]
paths: ['Package.swift', 'swift/**']
pull_request:
paths: ['Package.swift', 'swift/**']

jobs:
test:
runs-on: ubuntu-latest
container: swift:latest
steps:
- uses: actions/checkout@v7
- run: swift test
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ node_modules/
meta/
_docs/
_proc/
.build/
.swiftpm/

*.bak
.last_checked
Expand Down
10 changes: 5 additions & 5 deletions DEV.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# AnswerUI source

The notebooks in `nbs/` own the CSS and Python components. The first five derive the palette, typography, layout, controls and interactions. The following notebooks add the FastHTML registry, browser adapter, previews and Python constructors. Read them in sidebar order.
The notebooks in `ship/` own the CSS and Python components. The first five derive the palette, typography, layout, controls and interactions. The following notebooks add the FastHTML registry, browser adapter, previews and Python constructors. Read them in sidebar order.

A `#| asset styles.css` cell contains a CSS string. `nbdev-export` joins these sections in notebook and cell order. The palette notebook writes `nbs/palette.css` after fitting the colour ladders; ordinary exports read that file without repeating the calculations. The authored vanilla modules live in `answerui/assets/`. The HTML auto-initialiser, `browser.js`, is exported from the behaviors notebook to that same directory. FastHTML includes it automatically. Plain HTML apps can import `@answerdotai/answerui/browser.js`; Svelte components mount the individual controllers through their own lifecycle instead.
A `#| asset styles.css` cell contains a CSS string. `ship-export` joins these sections in notebook and cell order. The palette notebook writes `ship/palette.css` after fitting the colour ladders; ordinary exports read that file without repeating the calculations. The authored vanilla modules live in `answerui/assets/`. The HTML auto-initialiser, `browser.js`, is exported from the behaviors notebook to that same directory. FastHTML includes it automatically. Plain HTML apps can import `@answerdotai/answerui/browser.js`; Svelte components mount the individual controllers through their own lifecycle instead.

Run `npm run build` to export the styles and Python modules using nbdev from your Python environment. `answerui/assets/` is the asset directory for both distributions. The npm package `@answerdotai/answerui` contains CSS, optional fonts, dependency-free browser modules and Svelte 5 wrappers in `svelte/` (`@answerdotai/answerui/svelte`). The Python distribution `answerui-py` contains those assets, FastHTML constructors and the app registry. No JavaScript bundler is needed to build the library.
Run `npm run build` to export the styles and Python modules using fastship from your Python environment. `answerui/assets/` is the asset directory for the Python and npm distributions. The npm package `@answerdotai/answerui` contains CSS, optional fonts, dependency-free browser modules and Svelte 5 wrappers in `svelte/` (`@answerdotai/answerui/svelte`). The Python distribution `answerui-py` contains those assets, FastHTML constructors and the app registry. The Swift package in `Package.swift` and `swift/` exposes `FastTags` and `AnswerUI`; `ship-export` also writes `styles.css` and pre-inlined `browser.js` into `swift/Sources/AnswerUI/Resources/` alongside `idiomorph.min.js`. No JavaScript bundler is needed to build the library.

Shared styles use the cascade layers `reset`, `tokens`, `base`, `layout`, `components`, `app` and `utilities`. Python app rules normally use `app`. Direct foundation rules stay inside `@scope (:root, [ui]) to ([unstyle])`; opaque widgets can stop the skin with `[unstyle]`. Components own padding; layout containers own gaps.

The HTML lessons use `answerui.preview.preview` to show a markup string in an isolated frame with the built stylesheet. The Python lessons use `demo(page)` with the registry's current app rules and browser adapter. Both keep readable markup in saved notebook outputs rather than repeated copies of the stylesheet. Run `nbdev-test` on changed notebooks and `nbdev-readme` after updating `nbs/index.ipynb`.
The HTML lessons use `answerui.preview.preview` to show a markup string in an isolated frame with the built stylesheet. The Python lessons use `demo(page)` with the registry's current app rules and browser adapter. Both keep readable markup in saved notebook outputs rather than repeated copies of the stylesheet. Run `ship-test` on changed notebooks and `ship-readme` after updating `ship/index.ipynb`.

In a fastws workspace, include `AnswerDotAI/answerui[dev]` in the repo list. `ws-sync` installs the Python development dependencies, links the npm package and exports its assets before building dependent apps. Consumers declare an ordinary `@answerdotai/answerui` dependency without sibling paths or aliases. Outside the workspace, use the published package or a built package artifact.

## Release

The Python version in `answerui/__init__.py` and the npm version in `package.json` are kept together by Fastship. `ship-release` tags the current version. The tag workflow exports the assets, publishes `@answerdotai/answerui` to npm and `answerui-py` to PyPI, and creates the GitHub release. Fastship advances both version files for the next release.
The Python version in `answerui/__init__.py` and the npm version in `package.json` are kept together by Fastship. `ship-release` tags the current version. The tag workflow exports the assets, publishes `@answerdotai/answerui` to npm and `answerui-py` to PyPI, and creates the GitHub release; SwiftPM resolves the Swift package directly from those same `v*` GitHub tags. Fastship advances both version files for the next release.

Before the first npm release, publish the reviewed package once with normal authenticated `npm publish`, then configure npm's trusted publisher for owner `AnswerDotAI`, repository `answerui` and workflow `ci.yml`, with **Allow npm publish** selected. Configure PyPI trusted publishing for `answerui-py` with the same repository and workflow. The workflow uses no registry tokens or GitHub environment. Advance both version files with `ship-bump` before the first tag-driven release when that bootstrap npm version already exists.
29 changes: 29 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// swift-tools-version:6.0
import PackageDescription

let package = Package(
name: "AnswerUI",
platforms: [.macOS(.v14)],
products: [
.library(name: "FastTags", targets: ["FastTags"]),
.library(name: "AnswerUI", targets: ["AnswerUI"]),
],
targets: [
.target(name: "FastTags", path: "swift/Sources/FastTags"),
.target(
name: "AnswerUI",
dependencies: ["FastTags"],
path: "swift/Sources/AnswerUI",
resources: [
.copy("Resources/styles.css"),
.copy("Resources/browser.js"),
.copy("Resources/idiomorph.min.js"),
]
),
.testTarget(
name: "AnswerUITests",
dependencies: ["FastTags", "AnswerUI"],
path: "swift/Tests/AnswerUITests"
),
]
)
16 changes: 16 additions & 0 deletions answerui/_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@
from ast import literal_eval, parse
from collections import defaultdict
from textwrap import dedent, indent
from fastcore.utils import Path, to_data_url


def inline_browser(assets_dir=None):
"Return `browser.js` with its relative module imports inlined as base64 `data:` URLs."
d = Path(__file__).parent / 'assets' if assets_dir is None else Path(assets_dir)
body = (d / 'browser.js').read_text(encoding='utf-8')
for name in ('floating.js', 'interactions.js', 'fit.js', 'copy.js'):
url = to_data_url((d / name).read_bytes(), 'text/javascript')
body = body.replace(f"'./{name}'", repr(url))
return body


class _Assets:
Expand Down Expand Up @@ -126,3 +137,8 @@ def build_assets_(cell):
body = _merge_css(sections) if name.endswith('.css') else '\n\n'.join(sections)
css = '/* Generated by ship-export. Edit the source notebooks. */\n\n' + body + '\n'
if not out.exists() or out.read_text(encoding='utf-8') != css: out.write_text(css, encoding='utf-8')
swift_res = cfg.root / 'swift' / 'Sources' / 'AnswerUI' / 'Resources'
if swift_res.exists():
for name, txt in (('styles.css', (dest / 'styles.css').read_text(encoding='utf-8')), ('browser.js', inline_browser(dest))):
out = swift_res / name
if not out.exists() or out.read_text(encoding='utf-8') != txt: out.write_text(txt, encoding='utf-8')
2 changes: 1 addition & 1 deletion answerui/_modidx.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
'answerui.demo.Hyperelement.demo': ('python_components/demo.html#hyperelement.demo', 'answerui/demo.py')},
'answerui.hdrs': { 'answerui.hdrs.Registry.assets': ('python_components/hdrs.html#registry.assets', 'answerui/hdrs.py'),
'answerui.hdrs._Lazy': ('python_components/hdrs.html#_lazy', 'answerui/hdrs.py'),
'answerui.hdrs._inline_browser': ('python_components/hdrs.html#_inline_browser', 'answerui/hdrs.py'),
'answerui.hdrs.inline_browser': ('python_components/hdrs.html#inline_browser', 'answerui/hdrs.py'),
'answerui.hdrs.Registry.hdrs': ('python_components/hdrs.html#registry.hdrs', 'answerui/hdrs.py'),
'answerui.hdrs._Lazy.__init__': ('python_components/hdrs.html#_lazy.__init__', 'answerui/hdrs.py'),
'answerui.hdrs._Lazy.__ft__': ('python_components/hdrs.html#_lazy.__ft__', 'answerui/hdrs.py'),
Expand Down
15 changes: 6 additions & 9 deletions answerui/hdrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# AUTOGENERATED! DO NOT EDIT! File to edit: ../ship/python_components/13_hdrs.ipynb.

# %% auto #0
__all__ = []
__all__ = ['inline_browser']

# %% #cfc40afc
from fastcore.utils import *
Expand All @@ -19,6 +19,7 @@
from starlette.responses import Response
from functools import cache
from . import assets as shared_assets
from ._build import inline_browser as _inline_browser_js

# %% #89f8f25a
@patch
Expand All @@ -36,19 +37,15 @@ def __init__(self, f): self.f = f
def __ft__(self): return self.f()

@cache
def _inline_browser():
body = (shared_assets/'browser.js').read_text()
for name in ('floating.js', 'interactions.js', 'fit.js', 'copy.js'):
url = to_data_url((shared_assets/name).read_bytes(), 'text/javascript')
body = body.replace(f"'./{name}'", repr(url))
return body
def inline_browser():
"Return `browser.js` with its relative module imports inlined as base64 `data:` URLs"
return _inline_browser_js(shared_assets)

@patch
def hdrs(self:Registry):
"Inline foundation, application rules and browser behavior, rendered from this registry per response"
return (_Lazy(lambda: Style(self.assets()['css'])), _Lazy(lambda: Script(self.assets()['js'])),
_Lazy(lambda: Script(_inline_browser(), type='module')))

_Lazy(lambda: Script(inline_browser(), type='module')))

# %% #0a31b42e
@patch
Expand Down
2 changes: 1 addition & 1 deletion answerui/skill.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
- declarative browser behaviors (mounted across htmx swaps via `browser.js`): `Btn(..., disabled=True, enable='changed valid')` (form dirty/validity gating), `Checkbox(..., reveals='id')` (show/hide), `Copy(copy=...)` / `Copy(copyfor=...)` (clipboard + feedback), `[btn]` auto-spinner on `aria-busy='true'` or `.htmx-request` (delayed by `--busy-delay`), `Dialog(..., side='start' or 'end')` (slide-over drawers via native `command='show-modal'`/`commandfor`), `Tooltip` (CSS anchor positioning, no JS), `setup_toasts(app)` + `add_toast(sess, ...)` (`Toast(..., partial=True)` or queued `<hx-partial>` toasts on htmx fragments)
- app event handlers: `reg.rule(..., on={(sel, ev): js})` installs delegated document listeners surviving htmx swaps (`&` = component selector; `init`/`cleanup` = element lifetime; leading `:` = htmx event; see `doc(answerui.behaviors)`)
- escape hatches & prose sizing: `[unstyle]` stops `@scope` inheritance for third-party embeds; `[prose-size]` (`sm`, `lg`, `xl`, `2xl`) scales prose; `@layer base` provides `:focus-visible` ring globally
- inspect & preview: `reg.elements`, `Btn.rules`, `Btn.variants`, `Btn.example()`, `demo(markup, width='24rem')` (isolated iframe with current assets/app rules; `nbdev-clean` strips iframe bloat); `reg` describes registrations, not computed layout — browser check only when layout or rendering is genuinely uncertain, not routine edits
- inspect & preview: `reg.elements`, `Btn.rules`, `Btn.variants`, `Btn.example()`, `demo(markup, width='24rem')` (isolated iframe with current assets/app rules; `ship-clean` strips iframe bloat); `reg` describes registrations, not computed layout — browser check only when layout or rendering is genuinely uncertain, not routine edits
"""
from .all import *

Expand Down
16 changes: 7 additions & 9 deletions ship/python_components/13_hdrs.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"import hashlib, mimetypes\n",
"from starlette.responses import Response\n",
"from functools import cache\n",
"from answerui import assets as shared_assets"
"from answerui import assets as shared_assets\n",
"from answerui._build import inline_browser as _inline_browser_js"
]
},
{
Expand Down Expand Up @@ -136,7 +137,7 @@
"id": "d05ac8c7",
"metadata": {},
"source": [
"FastHTML calls `__ft__` on each object that defines it. `_Lazy` uses that hook to render the registry's current CSS and event script on each response. For inline pages and notebook previews, `_inline_browser` rewrites `browser.js` so its imports of `floating.js`, `interactions.js`, `fit.js`, and `copy.js` use base64 `data:` URLs rather than relative paths. On served pages, the browser loads those same files over HTTP. If your app uses its own `Registry`, pass its `hdrs()` instead of `reg.hdrs()`."
"FastHTML calls `__ft__` on each object that defines it. `_Lazy` uses that hook to render the registry's current CSS and event script on each response. For inline pages and notebook previews, `inline_browser` rewrites `browser.js` so its imports of `floating.js`, `interactions.js`, `fit.js`, and `copy.js` use base64 `data:` URLs rather than relative paths. On served pages, the browser loads those same files over HTTP. If your app uses its own `Registry`, pass its `hdrs()` instead of `reg.hdrs()`."
]
},
{
Expand All @@ -155,18 +156,15 @@
" def __ft__(self): return self.f()\n",
"\n",
"@cache\n",
"def _inline_browser():\n",
" body = (shared_assets/'browser.js').read_text()\n",
" for name in ('floating.js', 'interactions.js', 'fit.js', 'copy.js'):\n",
" url = to_data_url((shared_assets/name).read_bytes(), 'text/javascript')\n",
" body = body.replace(f\"'./{name}'\", repr(url))\n",
" return body\n",
"def inline_browser():\n",
" \"Return `browser.js` with its relative module imports inlined as base64 `data:` URLs\"\n",
" return _inline_browser_js(shared_assets)\n",
"\n",
"@patch\n",
"def hdrs(self:Registry):\n",
" \"Inline foundation, application rules and browser behavior, rendered from this registry per response\"\n",
" return (_Lazy(lambda: Style(self.assets()['css'])), _Lazy(lambda: Script(self.assets()['js'])),\n",
" _Lazy(lambda: Script(_inline_browser(), type='module')))\n"
" _Lazy(lambda: Script(inline_browser(), type='module')))"
]
},
{
Expand Down
46 changes: 46 additions & 0 deletions swift/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# AnswerUI for Swift

Swift 6 packages for composable HTML (`FastTags`) and AnswerUI components (`AnswerUI`), sharing the stylesheet and browser behavior in `answerui/assets/`. Both targets import only `Foundation` and run on macOS and Linux.

## Installation

Add `AnswerUI` to `Package.swift`:

```swift
dependencies: [
.package(url: "https://github.com/AnswerDotAI/answerui.git", from: "0.0.12"),
],
targets: [
.executableTarget(name: "MyApp", dependencies: [
.product(name: "AnswerUI", package: "answerui"),
]),
]
```

`AnswerUI` re-exports `FastTags`. Depend on the `FastTags` product alone if you only want HTML builders without AnswerUI components or assets.

## Usage

Build HTML trees with `@HTMLBuilder` closures and AnswerUI components:

```swift
import AnswerUI

let page = AnswerUIPage(title: "Settings", bridgeHandler: "app") {
Theme(space: "0.5rem") {
Card(gap: "0.6rem") {
Cluster(justify: .between) {
Strong("Plugins")
Badge("Ready", tone: .success)
}
Btn("Refresh", variant: .secondary, size: .sm).action("refresh")
}
}
}.render()
```

`AnswerUIAssets` loads the bundled `styles.css`, pre-inlined `browser.js`, and `idiomorph.min.js` from `Bundle.main.resourceURL/AnswerUI_AnswerUI.bundle` when packaged inside a macOS `.app` bundle, falling back to `Bundle.module` for `swift run` and `swift test`. `AnswerUIPage` uses those bundled assets by default. Call `morphCall(body)` to diff live DOM updates inside a `WKWebView` with `Idiomorph.morph` while preserving input focus and values.

## Development

`ship-export` syncs `styles.css` and pre-inlined `browser.js` into `swift/Sources/AnswerUI/Resources/` whenever notebook assets change. Run `swift test` from the repository root to verify `FastTags`, `AnswerUI`, and bundled asset loading.
Loading
Loading