Files
kryon/docs/HTML_TO_KRYON.md
T

246 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HTML and CSS to native TSX
Author application screens in `.tsx`, using typed components from
`kryon/tsx/*`. Ziran owns the native widgets, retained tree, rendering and
application logic. Both source languages enter Ziran's common checked IR;
there is no JavaScript engine or generated Ziran screen to maintain.
The [dashboard](../examples/dashboard/README.md) has real navigation, search,
settings, loading and error states. Its [responsive preview](../examples/dashboard/previews/responsive.tsx)
shows the same native layout at several widths.
## 1. HTML concepts
| HTML concept | Native TSX |
| --- | --- |
| Element | An imported typed component, such as `<Button session={session} props={{label: "Save"}}/>` |
| Nested children | JSX children, or a typed synchronous `children` callback; the component closes its native scope |
| Application model | Checked imports of Ziran records and actions; one owner of persistent state |
| Local presentation state | A mounted component instance's typed state; see [component lifetimes](COMPONENTS.md) |
| Stable identity | Parent identity, component location and explicit keys for changing lists |
| Element ID and CSS classes | Native props `id` and `class_name`, using `CSS.StyleId` and `CSS.StyleClass` |
| Media queries | Set the native stylesheet environment from the frame's viewport width |
A `key` remains an explicit native integer. Use `u64(9007199254740993n)` for a
wide identity; converting it through `number` would lose precision. Native
TSX's `number` is binary64. Native integer fields use their checked integer
types and conversions; see [the TSX contract](CHEATSHEET.md).
## 2. Semantic elements
[ui-map.json](ui-map.json) is the versioned, machine-readable TSX catalogue.
`import` and `component` identify the ordinary package export. `props` holds
native prop values; `lists` describes named array attributes. `native_import`
is the source of array and state types, not another composition API.
`children: "scoped"` means the component invokes a synchronous callback and
owns its matching native close. `children_type`, when present, is that
callback's native view parameter. `result_field` describes a reported event.
The existing project-entry check compiles every catalogue component into
checked IR; match the most specific HTML selector first.
| HTML | Component import | Behavior |
| --- | --- | --- |
| `html`, `body`, `main`, `section` | `Page`, `Section` from `kryon/tsx/page` | Scoped semantic containers |
| `article`, card | `Card` or `ResolvedCard` from `kryon/tsx/card` | Children, with a resolved content rectangle when needed |
| `div`, form, list | `Column`, `Row`, `Stack` from `kryon/tsx/layout` | Native layout and stylesheet rules |
| Header, navigation, tabs | `Toolbar`, `NavigationBar`, `TabBar` from their `kryon/tsx/*` modules | Typed action, item and tab arrays |
| Headings, paragraphs, labels | `Heading`, `ParagraphText` from `kryon/tsx/page`; `Text` from `kryon/tsx/text` | Native wrapping, fonts and semantics |
| Link, button | `Link`, `Button` from `kryon/tsx/link`, `kryon/tsx/button` | `Link` reports `open_url`; `Button` returns a boolean activation |
| Text, search, password, number input | `TextField` from `kryon/tsx/text_field` | Bind a stable native `State` reference; `secure` or `numeric` selects editing policy |
| Controlled input | `ControlledTextField` from `kryon/tsx/text_field` | Returns the native result; stage borrowed edits before mutating their backing model |
| Text area | `TextArea` from `kryon/tsx/text_area` | Native multiline editing and composition |
| Checkbox, switch, radio | `Checkbox`, `Toggle`, `Radio` from their `kryon/tsx/*` modules | Inspect the typed result and call a model action |
| Select, multiple select | `Dropdown`, `ListBoxMulti` from `kryon/tsx/dropdown`, `kryon/tsx/list_box` | Typed item arrays, selection and keyboard routing |
| Range, progress, fieldset | `Slider`, `Progress`, `Fieldset` from their `kryon/tsx/*` modules | Native values, labels and styling |
| Table, scrollable content | `Grid` from `kryon/tsx/grid`, inside `Scroll` from `kryon/tsx/scroll` | Shared tracks, horizontal scrolling and reading order |
| Details, dialog | `Collapsible`, `Modal` from `kryon/tsx/collapsible`, `kryon/tsx/modal` | Typed reveal state or scoped modal children |
| Image, SVG icon | `Image`, `SvgIcon` from `kryon/tsx/image`, `kryon/tsx/svg_icon` | Native resources and the same retained paint tree |
| Line, bar, heatmap, waterfall, OHLC chart | `plot/tsx/dashboard`; line/candle views in `plot/tsx/charts`; `BandChart` in `plot/tsx/band_chart` | Optional Plot dependency; native data and drawing |
Import native prop, enum and model types directly from the checked Ziran
modules. Do not duplicate them in TypeScript interfaces or export private
widget `Draw` functions to make old screens compile.
## 3. Layout and responsive screens
A content-sized container places children with unspecified positions and
settles to their combined height. Theme and CSS supply spacing and padding.
Explicit `gap` or `padding` props take precedence when their corresponding
`gap_override` or `padding_override` flag is true, including an explicit zero.
```tsx
import { Session } from "kryon/session";
import { Column, Row } from "kryon/tsx/layout";
import { Button } from "kryon/tsx/button";
import { Text } from "kryon/tsx/text";
export function Actions(session: Session): void {
<Column session={session} props={{padding: s32(16), padding_override: true}}>
<Text session={session} props={{text: "Cluster nodes"}}/>
<Row session={session} props={{gap: s32(12), gap_override: true}}>
<Button session={session} props={{label: "Refresh"}}/>
<Button session={session} props={{label: "Settings"}}/>
</Row>
</Column>;
}
```
Use `ResolvedRow`, `ResolvedColumn`, `ResolvedCard` or `ResolvedModal` when
children need the native content rectangle. Their scoped callback receives
the actual native result; never retain that borrowed view in an event closure.
`MeasuredRow` and `MeasuredColumn` accept native `FlexItem[]` and output
placements. `MeasuredGrid` accepts `GridItem[]` and `Rectangle[]` placements.
These are ordinary typed library components, with no compiler widget catalogue.
Use the same stylesheet and composition across widths. For example:
```css
Grid.metrics {
grid-template-columns: repeat(auto-fit, minmax(min(165px, 100%), 1fr));
gap: 14px;
}
Column.panel { padding: 20px; gap: 8px; }
@media (max-width: 820px) {
Column.panel { padding: 12px; }
}
```
Set the viewport with `CssEnvironmentWithViewportWidth` before installing the
sheet. `CssSheetSameMedia` avoids reinstalling unchanged matching rules.
The responsive dashboard's native
[stylesheet helper](../examples/dashboard/previews/responsive_styles.zi)
and [TSX composition](../examples/dashboard/previews/responsive.tsx) show
measured grids, full-row spans, a horizontal ledger and breakpoint behavior.
Pure geometry, measurement, custom painting and stylesheet policy remain
available from Ziran without reopening native screen composition.
## 4. Kryon CSS Support (`kryonlabs/css`)
Import `CSS :: #import "css/Css";` and install a stylesheet over `Theme.InstallDefaultTheme`:
```zi
CSS :: #import "css/Css";
Theme :: #import "kryon/theme";
sheet: CSS.CssSheet;
ApplyStyles :: (dark: bool, compact: bool, viewport_width: float32) -> bool {
unused Theme.InstallDefaultTheme(dark)
CSS.CssSheetReset(*sheet)
if !CSS.CssSheetParse(*sheet, app_css, "app.css", CSS.CssNoImports) {
return false // inspect CSS.CssSheetDiagnostic(*sheet, buf[:])
}
env := CSS.CssEnvironmentWithNames(
CSS.CssDefaultEnvironment(),
ifx dark then "dark" else "light",
"normal",
ifx compact then "compact" else "comfortable",
"mouse",
"desktop")
return CSS.CssSheetInstall(*sheet, CSS.CssEnvironmentWithViewportWidth(env, viewport_width), null)
}
```
Bind selectors on widgets via `props.class_name = CSS.StyleClass("primary")` and `props.id = CSS.StyleId("save")`.
Parse once per stylesheet in a running app. The example reparses to show the complete setup.
### Supported Selectors
- **Widget types**: `*`, `Any`, `App`, `Button`, `Text`, `TextField`, `TextArea`, `Surface`, `Dropdown`, `Card`, `Slider`, `SliderThumb`, `Toggle`, `ToggleThumb`, `Scroll`, `ScrollThumb`, `Checkbox`, `Radio`, `Progress`, `Separator`, `NavigationBar`, `NavigationBarItem`, `Selectable`, `Fieldset`, `Link`, `TabBar`, `Tab`, `TabClose`, `SegmentedControl`, `Segment`, `Menu`, `MenuItem`, `MenuSeparator`, `ListBox`, `ListBoxItem`, `ListBoxMulti`, `ListBoxMultiItem`, `TreeView`, `TreeViewItem`, `TableView`, `Collapsible`, `Modal`, `Toast`, `Toolbar`, `TitleBar`, `Image`, `Heading`, `ParagraphText`, `Page`, `Section`, `Popup`, `Row`, `Column`, `Grid`.
- **Classes & IDs**: at most one `.class` and one `#id` per compound selector (e.g. `Button.primary#save:hover`).
- **Kryon attributes**: `[tone=Neutral|Accent|Danger|Success|Warning]`, `[emphasis=Filled|Soft|Outline|Ghost|Link]`, `[size=Small|Medium|Large]`, `[role=Label|Panel|Track|Fill|Header|Close|...]`, `[state=any|normal|hover|pressed|focus|disabled|loading|selected]`.
- **State pseudo-classes** (max 1 per selector): `:hover`, `:active`, `:focus`, `:focus-visible`, `:disabled`, `:selected`, `:checked`, `:loading`.
- **Tree context**: one ancestor, matched by its class or id, as a descendant (`.card Text`, `#sidebar .item`) or the parent (`.toolbar > Button`); structural positions `:first-child`, `:last-child`, `:only-child`, `:nth-child()`, `:first-of-type`, `:last-of-type`, `:only-of-type` and `:nth-of-type()`; sibling combinators directly before the styled compound: `.a + .b` (the adjacent previous sibling) or `.a ~ .b` (any previous sibling), whose left side matches by its type, class and id alone (`.item + .detail`, `Text.done ~ Button`); and `:not(.class)` or `:not(:state)` (`Text:not(.muted)`, `Button:not(:disabled)`). Early positions and sibling combinators match while the frame builds — a sibling combinator reads the siblings already submitted, so it is exact; late positions (`:last-child` family) read the previous frame's children, so a tree change converges on the next frame; a sheet without such rules does no tree work.
- **Nesting**: `&:state`, `&.class`, `&#id`, `&[attribute]`, `&:first-child` and `&:not(...)` rules one level deep inside a rule; each adds to the parent selector.
- **Not supported** (parse error): a typed ancestor (`Row Text`) or more than one (`.a .b .c`), a sibling chain (`.a + .b + .c`) or an ancestor plus a sibling combinator (`.card .a + .b`) in one selector, nested combinators (`& .b`), pseudo-elements (`::before`), `!important`, `//` comments, other selector functions. Give the inner widget its own class instead.
### Supported Properties & Values
- **Native StyleData properties**:
- Colors: `color`, `background` (a color, `linear-gradient()` or `radial-gradient()`), `background-image` (`none`, `linear-gradient()` or `radial-gradient()`), `background-color`, `border-color`. A linear gradient takes an angle (`deg`, `turn`, `rad`, `grad`) or `to` a side or corner; a radial gradient takes `[circle | ellipse] [<extent> | <radius> [<radius>]]? [at <position>]` with extent keywords `closest-corner` (default), `closest-side`, `farthest-corner` and `farthest-side` (a circle radius is a `px` length, ellipse radii are `px` or `%`). Both take two to six color stops with optional `%` positions. `Row`, `Column` and `Grid` paint any of them, radial as bands from the computed center and radii; other widgets paint a top-to-bottom gradient of the first and last colors (`css_tool check` says so).
- Focus ring: `outline` (`[width] [solid | auto | none] [color]`), `outline-color`, `outline-width` (`px`, `rem`, `thin`, `medium`, `thick`) and `outline-offset` (signed) size the ring Button, ConfirmButton, Selectable and Radio draw on keyboard focus, from their `:focus-visible` rules. Keyboard focus always keeps a ring, so `outline: none` changes nothing (`css_tool check` says so).
- Borders & shape: `border` (`width` or `thin`/`medium`/`thick`, `solid` or `none`, `color`), `border-width`, `border-style` (`solid` | `none`), `border-radius`, `opacity` (unitless number or clamped `0%`–`100%`).
- Per-side borders on `Row`, `Column` and `Grid`: `border-top|right|bottom|left` and the logical `border-block-start|end` and `border-inline-start|end`, each with `-width`, `-color` and `-style`, for dividers, accent bars and tab underlines. A side without its own width or color takes the uniform `border`, and a uniform border later in the same rule clears earlier sides. The sides paint as square bands inside the box; with a `border-radius` the box paints only its uniform border, and `css_tool check` reports it.
- Spacing & sizing: `padding` (1–4 values; top/bottom and left/right must be equal), `padding-inline`, `padding-block`, `gap` (one value for both axes or two values in `row column` order), `row-gap`, `column-gap` (`Row` reads `column-gap`, `Column` reads `row-gap`, uniform-gap controls read the first `gap` value; accepts `normal` = 0 or nonnegative `px`/`rem`), `min-height`, `min-block-size` (logical alias for `min-height`; a percentage only on `Row`, `Column` and `Grid`).
- Retained `Row`, `Column` and `Grid` also accept `width` and `height` as positive `px` or `rem` lengths, a percentage, or `auto`. Other size expressions pass through to the browser.
- Percentages refer to the parent's content box (a grid child's track for widths), as in CSS: `width: 50%` is half the parent's inner width, and a percent height in a parent that sizes to its content computes to `auto`. `flex-basis` takes `px`, `rem`, `em`, `vw` or `vh` (viewport units bake at the sheet's default viewport) and `%`, which shares a measured flex row's inner width. A percentage mixed with other units in `calc()`, `min()`, `max()` or `clamp()` stays in the browser; write `width: 100%` with a `max-width`, or `flex: 1`, instead.
- Box: `Row`, `Column` and `Grid` read `min-width`/`min-inline-size`, `max-width`/`max-inline-size` and `max-height`/`max-block-size` (`px`, `rem`, `0`, a percentage, or `none` for maxima), `margin` (1–4 values), `margin-top|right|bottom|left`, `margin-inline`, `margin-block`, `margin-inline-start|end` (`px`, `rem`, `0` or `auto`; `auto` inline margins share the free width, so `margin: 0 auto` centers), and `overflow` (`visible`, or `hidden`/`clip` to clip descendants). A container placed at explicit `x`/`y` ignores margins. Negative and percentage margins and `overflow: auto|scroll` stay in the browser; compose `Scroll` from `kryon/tsx/scroll` for native scrolling.
- Transforms: `transform` (`translate()`, `scale()`, `rotate()` and their X and Y forms, in any order that does not shear), `translate` (`x [y]`, which moves the whole box after the others), `scale`, `rotate` and `transform-origin` (the box center unless set). They apply when Kryon paints, on every host, to `Row`, `Column`, `Grid`, `Button`, `Card`, `Text`, `Heading`, `Link` and `Image` nodes and to everything inside them; layout and pointer hit areas keep the untransformed box. `:hover` and `:active` follow the pointer, so `.card:hover { translate: 0 -2px }` works, and `transition: translate 150ms` (or `transform`, or `all`) eases the change. A transform rule matches its node by type, class, id and state; an ancestor or `:first-child` in its selector does not apply. A whole-pixel translation paints exactly as without it. A scale or rotation draws boxes as triangles, text at the nearest whole font size, and images scaled and turned; a widget that rasterizes by itself (a Scene, a custom emitter) ignores it. Transforms are opt-in paint code: an app whose styles set one imports `kryon/paint_transform` and calls `PaintTransformInstall()` once before its first frame, and installing a sheet with a transform without it fails with that instruction. An app that never calls it links none of the code.
- Text: `text-align` (`start`/`left`, `center`, `end`/`right`) on `Text`, `Heading`, `ParagraphText` and `Link`; an explicit `Text.Props.align` wins.
- Use `border-color: var(--line)` and `border-width` for typed border variables.
- Typography: `font-size`, `font-family`; native `Text`, `Heading`, and `ParagraphText` read `font-weight` (`normal` = 400, `bold` = 700, or `1`–`1000`), `font-style` (`normal` | `italic` | `oblique` without angle), and `letter-spacing` (`normal` or signed `px` / `rem`); `Text` and `Button` accept `line-height` (`normal`, nonnegative unitless factor, `%` of font size, or nonnegative `px` / `rem`).
- Kryon extensions: `-kryon-material` (`lightfield` | `flat` | `glass`), `-kryon-icon-size`, `-kryon-content-offset` (`x [y]`: a widget part's offset or metric, such as a NavigationBar panel's width), `-kryon-font-role` (`inherit` | `control` | `body` | `heading` | `code`), `-kryon-elevation` (`none` | `rest` | `raised` | `floating`), `-kryon-motion-duration`, `-kryon-motion-multiplier`, `-kryon-motion-easing` (`inherit` | `standard` | `linear` | `instant`), `-kryon-motion-reduced` (`reduce` | `no-preference`).
- **Units & values**: hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`), CSS named colors, `rgb()`, `rgba()`, `hsl()`, `hsla()`, `hwb(hue white% black% [/ alpha])`, hue angle units (`deg`, `rad`, `grad`, `turn`), `px`, `rem` (`16px`), `s`, `ms`, `em` (the rule's font-size, else 16px), `vw`, `vh`, `calc()`, `min()`, `max()`, `clamp()`, `:root` custom properties (`--token: ...;`) with `var(--token, fallback)` whose fallback may be one more `var()`, and `var(--kryon-surface)`-style theme colors (`background`, `surface`, `text`, `muted`, `border`, `accent`, `success`, `warning`, `danger` and more). `%` sizes as above; other `%` lengths are refused. The full property table is generated from the parser in the CSS package README.
- **At-rules**: `@import` (before rules), `@layer`, `@keyframes`, `@media` (`prefers-color-scheme`, `prefers-contrast`, `prefers-reduced-motion`, `pointer`, `width`, `min-width`, `max-width`, `-kryon-theme`, `-kryon-density`, `-kryon-pointer`, `-kryon-platform`).
- **Browser-only layout and paint** includes grid declarations outside the native track subset, conic and repeating gradients (Kryon backends have no such paint primitive), skew, `matrix()` and 3D transforms, `text-decoration`, `text-transform`, `white-space`, `cursor`, `z-index` and `visibility`. A plain `CssSheetParse` refuses them; read a sheet shared with the browser export through `CssSheetParseWithDiagnostics`, which reports them. CSS `display` maps to an authored native flex or grid container; intrinsic flex basis keywords (`min-content`, `max-content`, `fit-content`) remain browser-only.
Use `color-mix(in srgb, #2076c0 35%, transparent)` in a native color
declaration or custom property to derive a tint from two literal colors.
For native `@media (prefers-reduced-motion: reduce)` rules, set
`env.reduced_motion` from `Theme.CurrentTheme().motion.reduced_motion` and
reinstall the parsed sheet when that preference changes.
### CSS and layout motion
Install motion styles with `css/motion`. Supported native styles animate
through `transition` and `@keyframes`, including duration, delays, easing,
direction, fill modes and repeat counts. For example, a native Button with
`class_name = CSS.StyleClass("save")` uses these rules.
```css
button.save {
background-color: #365bd6;
transition: background-color 180ms ease-out;
}
button.save:hover { background-color: #2443ac; }
```
| UI effect | Kryon API |
| --- | --- |
| Move keyed items when a row, column or grid reflows | `LayoutMotion.Children(session)` from `kryon/layout_motion` in the open layout scope |
| Grow an entering item or ease a size change | `LayoutMotion.Children` with `.enter` or `.resize` |
| Keep drawing an exiting item until it settles | `LayoutMotion.Presence` with caller-owned state |
| Animate a custom shape, number, angle or graph value | `Motion.TweenTo` or `Motion.Sample` from `kryon/motion` |
| Animate a changing line chart | `AnimatedLineChart` from `plot/tsx/charts`, with native chart state |
See the [retained motion API](MOTION.md#retained-style-and-layout-motion) for
supported native widget properties and the [scalar motion API](MOTION.md#timed-motion-and-keyframes)
for application-owned tracks.
---
A complete runnable example with real CSS lives in [HTML_EXAMPLES.md](HTML_EXAMPLES.md).
## 5. Input and accessibility
Give interactive controls meaningful labels and stable identities. Native
pointer, touch, keyboard, focus, clipping and accessibility all observe the
same composed tree. `TextField` binds caller-owned storage through a checked
`NativeRef<State>` and handles selection, clipboard and IME updates. Keep
its backing state alive until unmount. Use `ControlledTextField` only when
handling the input result yourself; borrowed text must expire before the
model's bytes change.
`Modal` owns its child scope and reports dismissal, including Escape. Do not
manually close a TSX container. The native preview and test driver inspect the
same semantic labels and hit bounds as the running application.
## 6. Build and inspect the authored source
From a project with pinned dependencies, use the normal mixed-source workflow:
```sh
ziran check --project
ziran ir --project -o build/ir
ziran build
ziran run
```
Use the project's declared portable or browser profile to build that same
screen for another host. No separate TSX transpiler command is needed.
`ziran api --project --json --imports-only src/app.tsx` resolves authored
imports; query native model and policy declarations through the same package
graph. [HTML_EXAMPLES.md](HTML_EXAMPLES.md) links complete maintained screens
and their build, preview and interaction commands.