diff --git a/.changeset/html-plugin-sap-html.md b/.changeset/html-plugin-sap-html.md new file mode 100644 index 0000000..3bbeb42 --- /dev/null +++ b/.changeset/html-plugin-sap-html.md @@ -0,0 +1,15 @@ +--- +"@ui5-community/jsx-runtime": minor +--- + +Add `plugins/html` opt-in plugin for native HTML tags via `sap.html` (OpenUI5 ≥ 1.154.0). + +Lowercase HTML tags (`
`, ``, ``, …) now map to the corresponding `sap.html.*` UI5 control classes when wrapped in `withScope(htmlScope, () => …)`. Because these are real `ManagedObject` controls, the full UI5 programming model applies: data binding, events, dot-handler strings, `class=`, `ref=`, and auto-prefix-id all work identically to any other control — no per-tag imports needed. + +New exports from `ui5/community/jsx/runtime/plugins/html`: + +- `htmlScope` — partial scope to pass to `withScope` +- `preloadSapHtml()` — async bootstrap call that loads `sap.html` and all its controls via library metadata discovery +- `sapHtmlIntrinsic`, `tagToModulePath`, `resolveHtmlControl`, `normaliseHtmlProps` — lower-level exports for testing and custom composition + +Also replaces the permissive `HTMLAttributes` fallback in `JSX.IntrinsicElements` with per-tag TypeScript interfaces (`AnchorAttributes`, `InputAttributes`, `ButtonHtmlAttributes`, `FormAttributes`, and more). diff --git a/.gitignore b/.gitignore index ad9967a..edb842c 100644 --- a/.gitignore +++ b/.gitignore @@ -17,12 +17,6 @@ report/ .ui5-tooling-modules/ .ui5-middleware-serveframework/ ui5-workspace.yaml -# Keep the showcase's workspace file tracked — it wires the -# workspace-linked runtime dependency for `pnpm dev` and is the -# same for every developer. Per-developer overrides can live in -# a sibling ui5-workspace.yaml under a different name via the -# `--workspace` CLI flag. -!packages/jsx-runtime-showcase/ui5-workspace.yaml # TypeScript *.tsbuildinfo @@ -35,6 +29,9 @@ ui5-workspace.yaml .idea/ Thumbs.db +# Playwright MCP browser-session snapshots +.playwright-mcp/ + # Logs npm-debug.log* pnpm-debug.log* diff --git a/docs/gotchas.md b/docs/gotchas.md index 3eaeaed..e0bab0c 100644 --- a/docs/gotchas.md +++ b/docs/gotchas.md @@ -28,16 +28,46 @@ Documented at [src/runtime/scope.ts](../packages/jsx-runtime/src/runtime/scope.t --- -## HTML intrinsic tags are typed but not runtime-supported (yet) +## HTML intrinsic tags — use the `plugins/html` opt-in -`JSX.IntrinsicElements` permissively types `
`, ``, ``, etc. The **default** renderer throws on lowercase tags — it constructs UI5 controls, and a literal `div` cannot become a control. +Lowercase HTML tags (`
`, ``, ``, …) are typed in +`JSX.IntrinsicElements` but are **not enabled by default**. The default +scope throws on them — it constructs UI5 controls, and a bare string tag +has no UI5 metadata to construct from. + +To use HTML tags, opt in to the `plugins/html` package (requires +**OpenUI5 ≥ 1.154.0**, which ships the `sap.html` library): ```tsx -// ❌ Typechecks, throws at runtime -
hi
+import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; +import { htmlScope, preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; + +// At bootstrap (once, before any HTML-tag view renders): +await preloadSapHtml(); + +// In createContent(): +return withScope(htmlScope, () => ( +
Hi
+)); ``` -An HTML-aware renderer plugin is planned that installs an `htmlIntrinsic` in the scope; until then, treat lowercase tags as unusable in JSX. The error message from `jsx()` names the missing `htmlIntrinsic` explicitly. +Each lowercase tag maps to the corresponding `sap.html.*` control class +(`
` → `sap/html/Div`, `` → `sap/html/Input`, etc.). Because +these are real `ManagedObject` controls, data binding, events, `class=`, +and `ref=` all work identically to any other UI5 control. + +Outside `withScope(htmlScope, …)`, lowercase tags still throw a clear +error naming the missing `htmlIntrinsic`. The scope boundary is explicit +and reversible. + +See [docs: Native HTML via sap.html](../packages/jsx-runtime-showcase/webapp/docs/native-html.md) +and the [plugins/html README](../packages/jsx-runtime/src/plugins/html/README.md) +for full details. + +SVG tags (``, ``, ``, …) remain unimplemented; there is +no `sap.svg` library equivalent. They are typed permissively in +`JSX.IntrinsicElements` as `HTMLAttributes` (fallback) but will still +throw at runtime if used without a custom `htmlIntrinsic` that handles them. --- diff --git a/packages/jsx-runtime-showcase/samples.json b/packages/jsx-runtime-showcase/samples.json index c51f510..04361d9 100644 --- a/packages/jsx-runtime-showcase/samples.json +++ b/packages/jsx-runtime-showcase/samples.json @@ -163,6 +163,15 @@ "viewName": "ui5.community.jsx.showcase.view.showcases.ForwardedMenu", "sourcePath": "webapp/view/showcases/ForwardedMenu.tsx", "docPath": "webapp/docs/samples/forwarded-menu.md" + }, + { + "id": "native-html", + "title": "Native HTML via sap.html", + "chapter": 19, + "concepts": ["sap.html controls", "html plugin", "withScope(htmlScope)", "text children", "mixed content", "native events", "import-free HTML tags"], + "viewName": "ui5.community.jsx.showcase.view.showcases.NativeHtml", + "sourcePath": "webapp/view/showcases/NativeHtml.tsx", + "docPath": "webapp/docs/native-html.md" } ] } diff --git a/packages/jsx-runtime-showcase/ui5-workspace.yaml b/packages/jsx-runtime-showcase/ui5-workspace.yaml deleted file mode 100644 index f39a351..0000000 --- a/packages/jsx-runtime-showcase/ui5-workspace.yaml +++ /dev/null @@ -1,6 +0,0 @@ -specVersion: "workspace/1.0" -metadata: - name: default -dependencyManagement: - resolutions: - - path: ../jsx-runtime diff --git a/packages/jsx-runtime-showcase/ui5.yaml b/packages/jsx-runtime-showcase/ui5.yaml index 6c93de2..14f3a35 100644 --- a/packages/jsx-runtime-showcase/ui5.yaml +++ b/packages/jsx-runtime-showcase/ui5.yaml @@ -4,10 +4,11 @@ metadata: type: application framework: name: OpenUI5 - version: "1.148.2" + version: "1.154.0" libraries: - name: sap.m - name: sap.f + - name: sap.html - name: sap.tnt - name: sap.ui.core - name: sap.ui.layout diff --git a/packages/jsx-runtime-showcase/webapp/Component.ts b/packages/jsx-runtime-showcase/webapp/Component.ts index ab58e4a..8ed8ac6 100644 --- a/packages/jsx-runtime-showcase/webapp/Component.ts +++ b/packages/jsx-runtime-showcase/webapp/Component.ts @@ -1,6 +1,8 @@ import UIComponent from "sap/ui/core/UIComponent"; +import Log from "sap/base/Log"; import { getMode, setMode } from "./util/theme"; +import { preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; /** * Root component of the showcase. @@ -8,6 +10,11 @@ import { getMode, setMode } from "./util/theme"; * The manifest declares `ui5.community.jsx.runtime` as a `libs` * dependency, so UI5 auto-loads the library before `init()` runs. * + * `preloadSapHtml()` fetches the `sap.html` library and the + * `sap/ui/core/html/TextContent` module (required for mixed + * text+control children in native HTML JSX tags) before the + * router opens any view. + * * @namespace ui5.community.jsx.showcase */ export default class Component extends UIComponent { @@ -15,7 +22,7 @@ export default class Component extends UIComponent { manifest: "json" }; - public init(): void { + public async init(): Promise { super.init(); // Reconcile UI5's runtime theme with the persisted (or // OS-derived) mode. The pre-paint resolver in @@ -24,6 +31,22 @@ export default class Component extends UIComponent { // Mermaid + the CodeBlock have a consistent view of "the // theme has arrived" on first render. setMode(getMode()); + // Preload sap.html (and sap/ui/core/html/TextContent) so the + // html plugin can resolve
//… synchronously at JSX + // construction time in the NativeHtml sample view. + // A failure (wrong framework version, network error) is non-fatal: + // the app still works, but HTML-tag views will throw at construction + // time with a clear "module not loaded" message instead of silently. + try { + await preloadSapHtml(); + } catch (err) { + Log.error( + "ui5/community/jsx/runtime/plugins/html: preloadSapHtml() failed — " + + "native HTML tags (
, , …) will not work in this session.", + err instanceof Error ? err.message : String(err), + "ui5.community.jsx.showcase.Component" + ); + } this.getRouter().initialize(); } } diff --git a/packages/jsx-runtime-showcase/webapp/controller/Explorer.controller.ts b/packages/jsx-runtime-showcase/webapp/controller/Explorer.controller.ts index 41ec6bd..f1ef276 100644 --- a/packages/jsx-runtime-showcase/webapp/controller/Explorer.controller.ts +++ b/packages/jsx-runtime-showcase/webapp/controller/Explorer.controller.ts @@ -85,7 +85,8 @@ export default class Explorer extends Controller { { key: "learn.runtime-anatomy", title: "Runtime anatomy", icon: "sap-icon://process", route: "learnDoc", arg: "runtime-anatomy" }, { key: "learn.auto-prefix", title: "Auto id prefix", icon: "sap-icon://text", route: "learnDoc", arg: "auto-prefix" }, { key: "learn.plugin-spi", title: "The Plugin SPI", icon: "sap-icon://puzzle", route: "learnDoc", arg: "plugin-spi" }, - { key: "learn.switch-plugin", title: "Case study: ", icon: "sap-icon://switch-classes", route: "learnDoc", arg: "switch-plugin" } + { key: "learn.switch-plugin", title: "Case study: ", icon: "sap-icon://switch-classes", route: "learnDoc", arg: "switch-plugin" }, + { key: "learn.native-html", title: "Native HTML (sap.html)", icon: "sap-icon://html5", route: "learnDoc", arg: "native-html" } ]} ]; @@ -118,7 +119,8 @@ export default class Explorer extends Controller { { key: "explore.forwarded-menu", title: "Forwarded aggregation (Menu)", icon: "sap-icon://menu2", route: "exploreSample", arg: "forwarded-menu" } ]}, { key: "explore.g.plugins", title: "Plugins / Extend", icon: "sap-icon://puzzle", children: [ - { key: "explore.switch-plugin", title: "Plugin ", icon: "sap-icon://switch-classes", route: "exploreSample", arg: "switch-plugin" } + { key: "explore.switch-plugin", title: "Plugin ", icon: "sap-icon://switch-classes", route: "exploreSample", arg: "switch-plugin" }, + { key: "explore.native-html", title: "Native HTML via sap.html", icon: "sap-icon://html5", route: "exploreSample", arg: "native-html" } ]} ]; @@ -284,6 +286,15 @@ export default class Explorer extends Controller { toolPage?.removeStyleClass("jsx-welcome-no-sidenav"); sideNav?.setVisible(true); toolPage?.setSideExpanded?.(true); + // Scroll the selected nav item into view after the binding + // has updated the DOM (sapTntNLISelected class lands async). + setTimeout(() => { + const view = this.getView(); + if (!view) return; + const navListDom = view.byId("explorerNavList")?.getDomRef(); + const selected = navListDom?.querySelector(".sapTntNLISelected"); + selected?.scrollIntoView({ block: "nearest" }); + }, 0); } } diff --git a/packages/jsx-runtime-showcase/webapp/css/style.css b/packages/jsx-runtime-showcase/webapp/css/style.css index 3f6d477..fc64092 100644 --- a/packages/jsx-runtime-showcase/webapp/css/style.css +++ b/packages/jsx-runtime-showcase/webapp/css/style.css @@ -124,6 +124,18 @@ margin-left: 0.5rem; } +/* + * The ToolPage aside content area needs a scrollbar when the nav list + * is taller than the viewport. UI5's `sapTntNL` already has + * `overflow-y: auto` on the inner UL, but the parent `sapTntToolPage` + * has `overflow: hidden` which clips the scrollbar track. Giving the + * aside content its own `overflow-y: auto` surfaces the scrollbar so + * users can reach nav items below the fold. + */ +.sapTntToolPageAsideContent { + overflow-y: auto; +} + /* * Welcome view uses the same shared `sap.tnt.ToolPage` shell as * Learn and Explore. On the welcome route we hide the side diff --git a/packages/jsx-runtime-showcase/webapp/docs/native-html.md b/packages/jsx-runtime-showcase/webapp/docs/native-html.md new file mode 100644 index 0000000..7997b61 --- /dev/null +++ b/packages/jsx-runtime-showcase/webapp/docs/native-html.md @@ -0,0 +1,175 @@ +# Native HTML via `sap.html` (plugin) + +The runtime ships a `plugins/html` package that maps lowercase HTML +tags in TSX views to real `sap.html.*` UI5 control classes, available +from **OpenUI5 1.154.0**. No per-tag imports needed. + +## What it looks like + +```tsx +import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; +import { htmlScope } from "ui5/community/jsx/runtime/plugins/html/index"; + +return withScope(htmlScope, () => ( +
+

Hello, JSX!

+

Mix HTML and UI5 controls freely.

+ + +
+)); +``` + +Because `
`, ``, etc. are mapped to real `sap.html.Div` / +`sap.html.Input` controls, the full UI5 programming model works: + +- **Data binding** — `value="{/name}"`, `text="{/title}"`, object-form + `{ path, formatter }` — all work as on any UI5 control. +- **Dot-handler events** — `click=".onSave"` resolves at fire time. +- **Inline function events** — `click={() => …}` is a normal UI5 listener. +- **`class=`** → `addStyleClass(...)`. +- **`ref=`** callback ref, receives the `sap.html.*` instance. +- **Auto-prefix-id** — `id="foo"` is expanded by the view bridge. + +## Preloading + +The `sap.html` library is not part of the default UI5 preload. Load it +once at bootstrap before any HTML-tag view renders: + +```ts +// Component.ts +import { preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; + +public async init(): Promise { + super.init(); + await preloadSapHtml(); // ← before router.initialize() + this.getRouter().initialize(); +} +``` + +`preloadSapHtml()` is idempotent — safe to call multiple times. + +## Opt-in: `withScope(htmlScope, fn)` + +HTML support is not global. Wrap the subtree where you want it: + +```tsx +// ✅ HTML works inside the scope +return withScope(htmlScope, () =>
); + +// ❌ HTML outside the scope — throws "no htmlIntrinsic" +return
; +``` + +The boundary is explicit so a typo like `` in a non-HTML +context produces a clear error rather than a silent rendering quirk. + +## Tag resolution + +| JSX tag | UI5 module | +|---|---| +| `
` | `sap/html/Div` | +| `` | `sap/html/Span` | +| `

` – `

` | `sap/html/H1` – `sap/html/H6` | +| `` | `sap/html/Input` | +| ` // dot-handler + …} /> // inline arrow +
// method reference +``` + +## Two-way binding: write-back is explicit + +`sap.html` property bindings are **read-only**: they sync the model +value into the control, but user edits are **not** automatically +written back. To keep the model up to date you must call +`model.setProperty()` inside the `input` or `change` event handler: + +```tsx + { + // getValue() returns the stale model value — the binding pushes + // the model into the property, but DOM changes don't flow back. + // Read the current text from the DOM directly. + const inputEl = (event.getSource() as unknown as { + getDomRef(): HTMLInputElement | null; + }).getDomRef(); + model.setProperty("/name", inputEl?.value ?? ""); + }} +/> +``` + +### `input` vs `change` + +| Event | Fires | Typical use | +|---|---|---| +| `input` | every keystroke | live filter, live preview | +| `change` | blur or Enter | commit-on-leave, server call | + +Use `input` when the bound output (another `sap.html` element, a +``, an aggregation) needs to reflect every keypress. +Use `change` when you only need to react once the user is done. + +> **Contrast with `sap.m.Input`:** `sap.m.Input` with a `JSONModel` +> binding and default `TwoWay` mode writes back automatically on +> `change`. That implicit write-back does not apply to `sap.html` +> controls. + +## `enabled` vs `disabled` + +Interactive controls use `enabled` (default `true`); the framework +maps it to the native `disabled` attribute: + +```tsx + // renders: +``` + +## TypeScript types + +Per-tag prop types are in `JSX.IntrinsicElements` (part of the runtime +typings, no separate package needed). Common attributes are on +`JSX.HtmlBaseAttributes`; element-specific ones have their own +interfaces (`JSX.AnchorAttributes`, `JSX.InputAttributes`, …). + +See the running demo in [native-html](#/explore/native-html). diff --git a/packages/jsx-runtime-showcase/webapp/docs/samples/binding-string.md b/packages/jsx-runtime-showcase/webapp/docs/samples/binding-string.md index 2791b97..5bf9e32 100644 --- a/packages/jsx-runtime-showcase/webapp/docs/samples/binding-string.md +++ b/packages/jsx-runtime-showcase/webapp/docs/samples/binding-string.md @@ -1,8 +1,14 @@ A view-local `JSONModel` registered under the named scope `"form"`. The ``'s `value` and a sibling ``'s -`text` both bind to `"{form>/name}"`. UI5's binding system -keeps them in sync as the user types. No `liveChange` handler, -no `byId(...).setText(...)` round-trips. +`text` both bind to `"{form>/name}"`. Because `JSONModel` defaults +to `TwoWay` mode, UI5 writes the ``'s value back to the +model automatically when the `change` event fires (blur or Enter). +No explicit `change` handler, no `byId(...).setText(...)`. + +> **Note — `change`, not `liveChange`:** The `` mirror +> updates when the model updates, which happens on blur or Enter, +> not on every keystroke. For per-keystroke updates (live search, +> character count) you need an explicit `liveChange` handler. Compare to the `no-bindings` foil: the entire mirroring infrastructure collapses into two binding strings. That's the @@ -17,5 +23,6 @@ Concept reference: [Data binding](#/learn/data-binding). See also: [no-bindings](#/explore/no-bindings) — the foil, same mirroring done imperatively via `byId` + `setText`; [binding-object](#/explore/binding-object) — when the binding needs -more than a `path`; [structural](#/explore/structural) — the same -binding syntax powering bound aggregations. +more than a `path`; +[structural](#/explore/structural) — the same binding syntax +powering bound aggregations. diff --git a/packages/jsx-runtime-showcase/webapp/docs/samples/native-html.md b/packages/jsx-runtime-showcase/webapp/docs/samples/native-html.md new file mode 100644 index 0000000..94e3cb8 --- /dev/null +++ b/packages/jsx-runtime-showcase/webapp/docs/samples/native-html.md @@ -0,0 +1,35 @@ +An **opt-in plugin** that maps every lowercase HTML tag to its +corresponding `sap.html.*` control class (available from OpenUI5 1.154.0). +Because these are ordinary `ManagedObject` controls, the full UI5 +programming model applies — data binding, events, `class=`, `ref=`, +and dot-handler strings all work exactly as on any other control. + +Opt in by wrapping the JSX subtree in +`withScope(htmlScope, () => …)`. +Outside that scope, lowercase tags still throw a clear +"no htmlIntrinsic" error — the boundary is explicit and reversible. + +**Tag resolution** — first character uppercased, rest as-is: +`
` → `sap/html/Div`, `

` → `sap/html/H1`, +`
` → `sap/html/Blockquote`. + +**Text children** — two modes: + +- **Sole text child.** A single string/number (no sibling controls) + becomes the control's `text` property. +- **Mixed content.** Text interleaved with child controls is wrapped in + `sap.ui.core.html.TextContent` controls placed at the correct + position in the `children` aggregation. + +**Void elements** (`
`, ``, ``, …) reject children or a +`text` property — providing either throws a clear error at construction time. + +**Preload once** at bootstrap before any HTML-tag view renders: + +```ts +// Component.ts +await preloadSapHtml(); // loads sap.html + all sap/html/* controls +this.getRouter().initialize(); +``` + +Concept reference: [Native HTML via sap.html](#/learn/native-html). diff --git a/packages/jsx-runtime-showcase/webapp/view/ExploreSample.tsx b/packages/jsx-runtime-showcase/webapp/view/ExploreSample.tsx index 356bc54..923edfc 100644 --- a/packages/jsx-runtime-showcase/webapp/view/ExploreSample.tsx +++ b/packages/jsx-runtime-showcase/webapp/view/ExploreSample.tsx @@ -161,6 +161,12 @@ const REGISTRY: Record`'s `value` and a sibling ``'s `text` both bind - * to `"{form>/name}"`. UI5's binding system keeps them in sync as - * the user types. No `liveChange` handler, no `byId(...).setText(...)` - * round-trips. + * to `"{form>/name}"`. Because `JSONModel` defaults to `TwoWay` mode, + * UI5 writes the new value back to the model when the `change` event + * fires (blur or Enter). The `` updates as soon as the model + * changes — no `change` handler, no `byId(...).setText(...)`. + * + * > **`change`, not `liveChange`:** The mirror updates on blur / Enter, + * > not on every keystroke. For per-keystroke updates you need an + * > explicit `liveChange` handler. * * Compare to Chapter 5 (the foil): the entire mirroring infrastructure * collapses into two binding strings. That is the whole pitch. diff --git a/packages/jsx-runtime-showcase/webapp/view/showcases/NativeHtml.tsx b/packages/jsx-runtime-showcase/webapp/view/showcases/NativeHtml.tsx new file mode 100644 index 0000000..b64f299 --- /dev/null +++ b/packages/jsx-runtime-showcase/webapp/view/showcases/NativeHtml.tsx @@ -0,0 +1,185 @@ +import View from "sap/ui/core/mvc/View"; +import type Control from "sap/ui/core/Control"; +import type UI5Event from "sap/ui/base/Event"; +import VBox from "sap/m/VBox"; +import Title from "sap/m/Title"; +import Text from "sap/m/Text"; +import JSONModel from "sap/ui/model/json/JSONModel"; +import MessageToast from "sap/m/MessageToast"; +import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; +import { htmlScope } from "ui5/community/jsx/runtime/plugins/html/index"; + +/** + * # Chapter 19. Native HTML via `sap.html` (opt-in plugin) + * + * The `ui5.community.jsx.runtime/plugins/html` plugin maps every + * lowercase HTML tag to its corresponding `sap.html.*` control class + * (available from OpenUI5 1.154.0). Because these are real UI5 + * `ManagedObject` controls, the full runtime pipeline applies: + * data binding, events, dot-handler strings, `class=`, and `ref=` + * all work identically to any other control. + * + * ## Opt-in + * + * Wrap `createContent()` (or any subtree) in `withScope(htmlScope, fn)`. + * Outside that scope, lowercase tags still throw the "no htmlIntrinsic" + * error — the scope boundary is explicit and reversible. + * + * ## Text children + * + * `sap.html` controls handle text content in two ways: + * + * - **Sole text child** — a single string/number child (no sibling + * controls) is forwarded as the control's `text` property. + * - **Mixed content** — text interleaved with child controls; the + * plugin wraps each text segment in a `sap.ui.core.html.TextContent` + * placed at the correct position in the `children` aggregation. + * + * ## Two-way write-back + * + * `sap.html` property bindings are **read-only by default**: they read + * from the model into the control, but user edits are not automatically + * written back. Call `model.setProperty()` explicitly inside the + * `input` (or `change`) event handler: + * + * ```tsx + * { + * // getValue() returns the stale model value, not what the user typed. + * // Read from the DOM directly via getDomRef(). + * const inputEl = (event.getSource() as unknown as { + * getDomRef(): HTMLInputElement | null; + * }).getDomRef(); + * model.setProperty("/name", inputEl?.value ?? ""); + * }} + * /> + * ``` + * + * ## Try it + * + * Type in the input below; the `` and `

` elements reflect + * the model value via string binding. Toggle the details panel. + * + * @namespace ui5.community.jsx.showcase.view.showcases + */ +interface ViewState { + name: string; + lastKey: string; +} + +export default class NativeHtml extends View { + private readonly state: JSONModel = new JSONModel({ + name: "World", + lastKey: "(none)" + } satisfies ViewState); + + getAutoPrefixId(): boolean { + return true; + } + + createContent(): Control { + this.setModel(this.state); + + return withScope(htmlScope, () => ( + + + {/* ------ Plain HTML with text children ---------------------- */} + + <Text text="These elements are real sap.html controls — not raw DOM strings." /> + + {/* Sole text child → forwarded as `text` property */} + <p class="sapUiSmallMarginTop"> + Hello from a native <strong>paragraph</strong> with mixed text and a bold element. + </p> + + {/* Heading tags */} + <h4 class="sapUiSmallMarginTop">Data binding</h4> + + {/* ------ Bound <input> --------------------------------------- */} + <p> + Enter your name: + <input + id="nameInput" + type="text" + value="{/name}" + class="sapUiSmallMarginBegin" + input={(event: UI5Event): void => { + // sap.html property bindings are model-driven: getValue() + // returns the last value pushed FROM the model, not the + // current DOM text the user typed. Read from the DOM directly. + const inputEl = (event.getSource() as unknown as { + getDomRef(): HTMLInputElement | null; + }).getDomRef(); + const name = inputEl?.value ?? ""; + this.state.setProperty("/name", name); + this.state.setProperty("/lastKey", name.slice(-1) || "(backspace)"); + }} + /> + </p> + + {/* Bound <output> and <p> reflect the model value */} + <p class="sapUiTinyMarginTop"> + Bound output: + <output text="{/name}" class="sapUiSmallMarginBegin" /> + </p> + <p> + Hello, <strong text="{/name}" />! (last key: <em text="{/lastKey}" />) + </p> + + {/* ------ Mixed text + controls ------------------------------- */} + <h4 class="sapUiSmallMarginTop">Mixed content</h4> + <p> + This paragraph mixes plain text with a UI5{" "} + <Text text="Text control" class="sapThemeHighlightText sapUiSmallMarginBegin sapUiSmallMarginEnd" /> + {" "}embedded inline. + </p> + + {/* ------ Semantic structure ---------------------------------- */} + <h4 class="sapUiSmallMarginTop">Semantic structure</h4> + <section class="sapUiSmallMarginTop"> + <header> + <h5>Feature list</h5> + </header> + <ul> + <li>Data binding on any attribute</li> + <li>Dot-handler events (<code>click=".onSomething"</code>)</li> + <li>Inline function events</li> + <li> + <code>class=</code> → <code>addStyleClass</code> + </li> + <li>Mixed text + child controls (TextContent)</li> + </ul> + </section> + + {/* ------ <details> / <summary> ------------------------------- */} + <h4 class="sapUiSmallMarginTop">Disclosure widget</h4> + <details class="sapUiSmallMarginTop"> + <summary>Click to expand</summary> + <p> + The <code>sap.html.Details</code> control is a real UI5 control + with a native browser disclosure mechanism. + </p> + </details> + + {/* ------ Event: click on a native <button> ------------------- */} + <h4 class="sapUiSmallMarginTop">Native events</h4> + <p class="sapUiTinyMarginTop"> + <button + class="sapUiSmallMarginEnd" + click={(): void => { + const name = this.state.getProperty("/name") as string; + MessageToast.show(`Hello, ${name}!`); + }} + > + Say hello (native button) + </button> + <a href="#native-html" click={(_e: UI5Event): void => { MessageToast.show("Link clicked"); }}> + Native link + </a> + </p> + + </VBox> + )); + } +} diff --git a/packages/jsx-runtime/package.json b/packages/jsx-runtime/package.json index 24685ff..65f9b3e 100644 --- a/packages/jsx-runtime/package.json +++ b/packages/jsx-runtime/package.json @@ -49,6 +49,10 @@ "types": "./dist/resources/ui5/community/jsx/runtime/plugins/switch/index.d.ts", "default": "./dist/resources/ui5/community/jsx/runtime/plugins/switch/index.js" }, + "./plugins/html": { + "types": "./dist/resources/ui5/community/jsx/runtime/plugins/html/index.d.ts", + "default": "./dist/resources/ui5/community/jsx/runtime/plugins/html/index.js" + }, "./src/*": "./src/*", "./dist/*": "./dist/*", "./package.json": "./package.json" diff --git a/packages/jsx-runtime/scripts/jsx-runtime-aug.d.ts b/packages/jsx-runtime/scripts/jsx-runtime-aug.d.ts index 01ebbda..38cbba0 100644 --- a/packages/jsx-runtime/scripts/jsx-runtime-aug.d.ts +++ b/packages/jsx-runtime/scripts/jsx-runtime-aug.d.ts @@ -73,6 +73,31 @@ declare module "ui5/community/jsx/runtime/jsx-runtime" { export type ElementAttributesProperty = DeepJSX.ElementAttributesProperty; export type ElementChildrenAttribute = DeepJSX.ElementChildrenAttribute; export type HTMLAttributes = DeepJSX.HTMLAttributes; + export type HtmlBaseAttributes = DeepJSX.HtmlBaseAttributes; + export type AnchorAttributes = DeepJSX.AnchorAttributes; + export type ButtonHtmlAttributes = DeepJSX.ButtonHtmlAttributes; + export type ImgAttributes = DeepJSX.ImgAttributes; + export type InputAttributes = DeepJSX.InputAttributes; + export type LabelHtmlAttributes = DeepJSX.LabelHtmlAttributes; + export type SelectAttributes = DeepJSX.SelectAttributes; + export type TextareaAttributes = DeepJSX.TextareaAttributes; + export type FormAttributes = DeepJSX.FormAttributes; + export type TableHtmlAttributes = DeepJSX.TableHtmlAttributes; + export type TableCellAttributes = DeepJSX.TableCellAttributes; + export type ColAttributes = DeepJSX.ColAttributes; + export type LiAttributes = DeepJSX.LiAttributes; + export type OlAttributes = DeepJSX.OlAttributes; + export type DetailsAttributes = DeepJSX.DetailsAttributes; + export type MeterAttributes = DeepJSX.MeterAttributes; + export type ProgressAttributes = DeepJSX.ProgressAttributes; + export type TimeAttributes = DeepJSX.TimeAttributes; + export type DataAttributes = DeepJSX.DataAttributes; + export type OptionAttributes = DeepJSX.OptionAttributes; + export type OptgroupAttributes = DeepJSX.OptgroupAttributes; + export type FieldsetAttributes = DeepJSX.FieldsetAttributes; + export type MapAttributes = DeepJSX.MapAttributes; + export type AreaAttributes = DeepJSX.AreaAttributes; + export type CanvasAttributes = DeepJSX.CanvasAttributes; export type IntrinsicElements = DeepJSX.IntrinsicElements; export type IntrinsicAttributes = DeepJSX.IntrinsicAttributes; export type LibraryManagedAttributes<C, P> = DeepJSX.LibraryManagedAttributes<C, P>; diff --git a/packages/jsx-runtime/src/plugins/html/README.md b/packages/jsx-runtime/src/plugins/html/README.md new file mode 100644 index 0000000..670956d --- /dev/null +++ b/packages/jsx-runtime/src/plugins/html/README.md @@ -0,0 +1,187 @@ +# `@ui5-community/jsx-runtime/plugins/html` + +> **Requires OpenUI5 ≥ 1.154.0** — the `sap.html` library was introduced in 1.154.0. + +An opt-in plugin that maps lowercase HTML tags in TSX views to the corresponding `sap.html.*` UI5 control classes, letting you write native HTML without importing each class individually. + +```tsx +import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; +import { htmlScope, preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; + +// Once at bootstrap (Component.init / app entry): +await preloadSapHtml(); + +// In a view's createContent(): +return withScope(htmlScope, () => ( + <div class="myCard"> + <h3>Hello, {name}!</h3> + <input type="text" value="{/name}" input={this.onNameChanged} /> + <button click={(): void => MessageToast.show("Hi!")}>Click me</button> + </div> +)); +``` + +Because `sap.html` controls are ordinary UI5 `ManagedObject` subclasses, the full runtime pipeline applies: + +- **Data binding** — `value="{/name}"`, `text="{/title}"`, object-form `{ path, formatter }` — all work as on any UI5 control. +- **Dot-handler events** — `click=".onSave"` resolves against the view's controller at fire time. +- **Inline function events** — `click={() => …}` wraps in a normal UI5 event listener. +- **`class=`** — forwarded through the `classIntrinsic` to `addStyleClass(...)`. +- **`ref=`** — callback ref, receives the constructed `sap.html.*` instance. +- **Auto-prefix-id** — `id="foo"` in a view with `getAutoPrefixId() === true` is expanded to `view.createId("foo")` automatically. + +--- + +## Installation / opt-in + +The plugin is bundled in `@ui5-community/jsx-runtime`. Import it from the subpath: + +```ts +import { htmlScope, preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; +``` + +Wrap the JSX subtree you want HTML support in: + +```tsx +return withScope(htmlScope, () => <div>…</div>); +``` + +`withScope` is synchronous, so you can scope individual subtrees rather than entire views. + +--- + +## Preloading + +`sap.html` is loaded lazily; the sync `sap.ui.require` call inside the plugin only works if the library is already in the require cache. Call `preloadSapHtml()` once at bootstrap: + +```ts +// Component.ts +public async init(): Promise<void> { + super.init(); + await preloadSapHtml(); // ← before router.initialize() + this.getRouter().initialize(); +} +``` + +`preloadSapHtml()` calls `Lib.load({ name: "sap.html" })`, reads the library metadata's `controls` list to discover every `sap/html/*` module, then async-requires them all in one batch — plus `sap/ui/core/html/TextContent` for mixed-content support. After the promise resolves, every `sap/html/*` control is in the synchronous require cache. Safe to call multiple times. + +--- + +## Tag resolution + +A lowercase JSX tag maps to `sap/html/<ClassName>` where `<ClassName>` is the tag with its first character uppercased: + +| JSX tag | UI5 module | UI5 class | +|---|---|---| +| `<div>` | `sap/html/Div` | `sap.html.Div` | +| `<span>` | `sap/html/Span` | `sap.html.Span` | +| `<h1>` | `sap/html/H1` | `sap.html.H1` | +| `<blockquote>` | `sap/html/Blockquote` | `sap.html.Blockquote` | +| `<selectedcontent>` | `sap/html/Selectedcontent` | `sap.html.Selectedcontent` | + +A tag not present in the `sap.html` library (e.g. `<script>`, `<video>`) or a tag whose module is not yet loaded throws a clear error at JSX construction time. + +--- + +## Text children + +HTML elements contain text. The plugin normalises JSX children before delegating to the core runtime: + +### Sole text child → `text` property + +```tsx +<span>Hello, world</span> +// ↓ normalised to: +// <sap.html.Span text="Hello, world" /> +``` + +Whitespace-only children (Babel's JSX indentation) are ignored. + +### Mixed content → `TextContent` controls + +Text interleaved with child controls is wrapped in `sap.ui.core.html.TextContent` (a private core control) inserted at the correct position in the `children` aggregation, preserving source order: + +```tsx +<p> + Visit <a href="https://openui5.org">OpenUI5</a> for docs. +</p> +// ↓ normalised to children: [TextContent("Visit "), Anchor, TextContent(" for docs.")] +``` + +### All-control children → unchanged + +Children that are all UI5 controls (no string segments) are forwarded to the `children` default aggregation as-is. + +--- + +## Void elements + +Void elements (`<br>`, `<hr>`, `<img>`, `<input>`, `<area>`, `<col>`, `<wbr>`, …) cannot have children or a `text` property. Providing either throws at construction time: + +```tsx +<br>oops</br> // ← Error: <br> is a void element and cannot have children +``` + +--- + +## Events + +`sap.html` controls declare UI5 events for native DOM events — `click`, `input`, `change`, `keydown`, `focus`, `blur`, `submit`, `scroll`, and more. Use them the same way as any UI5 event: + +```tsx +// Inline arrow: +<button click={(): void => MessageToast.show("Hi!")}>Click</button> + +// Dot-handler (resolved against view controller at fire time): +<button click=".onSave">Save</button> + +// Method reference (with bind): +<input input={this.onInput.bind(this)} /> +``` + +Event names are the **UI5 event names** (`click`, `input`, `change`, …), not the DOM `onclick` / `oninput` attribute syntax. + +--- + +## `enabled` vs `disabled` + +Interactive controls (`<button>`, `<input>`, `<select>`, `<textarea>`) expose an `enabled` property (default `true`) that maps to the native `disabled` attribute: + +```tsx +<input enabled={false} /> // renders: <input disabled> +``` + +--- + +## TypeScript types + +Per-tag TypeScript prop types are shipped in the runtime's `JSX.IntrinsicElements` declaration. Common attributes are typed on `HtmlBaseAttributes` (available as `JSX.HtmlBaseAttributes`); element-specific attributes are on dedicated interfaces (e.g. `JSX.AnchorAttributes`, `JSX.InputAttributes`, `JSX.FormAttributes`, …). + +No `@openui5/types` update is required — the interfaces are defined directly in the runtime. + +--- + +## Scope isolation + +`withScope(htmlScope, fn)` is the explicit opt-in. Any JSX outside the scope still throws a clear error if it encounters a lowercase tag. This is deliberate: HTML tags and UI5 control tags do not mix accidentally. + +```tsx +// ✅ HTML inside the scope +return withScope(htmlScope, () => <div><VBox /></div>); + +// ❌ HTML outside the scope — throws "no htmlIntrinsic" +return <div />; +``` + +--- + +## Exports + +| Export | Type | Description | +|---|---|---| +| `htmlScope` | `Partial<Scope>` | Spread into `withScope(htmlScope, fn)` to enable HTML tags. | +| `sapHtmlIntrinsic` | `Scope["htmlIntrinsic"]` | The raw handler — spread manually if you need to compose scopes. | +| `preloadSapHtml` | `() => Promise<void>` | Load the `sap.html` library. Call once at bootstrap. | +| `tagToModulePath` | `(tag: string) => string` | Map `"div"` → `"sap/html/Div"`. Useful for testing. | +| `resolveHtmlControl` | `(tag: string) => ControlClass` | Sync-resolve the control class (requires preload). | +| `normaliseHtmlProps` | `(tag, props) => props` | Text-child normalisation (exported for testing). | diff --git a/packages/jsx-runtime/src/plugins/html/index.ts b/packages/jsx-runtime/src/plugins/html/index.ts new file mode 100644 index 0000000..aca8fbf --- /dev/null +++ b/packages/jsx-runtime/src/plugins/html/index.ts @@ -0,0 +1,370 @@ +/** + * `ui5.community.jsx.runtime/plugins/html` — opt-in `sap.html` integration. + * + * Makes lowercase HTML tags (`<div>`, `<span>`, `<input>`, …) work in TSX + * views by mapping them to the real `sap.html.*` control classes introduced + * in OpenUI5 1.154.0. Because these are ordinary UI5 `ManagedObject` controls + * the full runtime pipeline is reused without change: data binding, events, + * associations, dot-handler strings, `class=`, `ref=`, and auto-prefix-id + * all work exactly as they do for any other control. + * + * ## Usage + * + * ```tsx + * import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; + * import { htmlScope, preloadSapHtml } from "ui5/community/jsx/runtime/plugins/html/index"; + * + * // Once, at component init (async OK here): + * await preloadSapHtml(); + * + * // In a view's createContent(): + * createContent() { + * return withScope(htmlScope, () => ( + * <div class="myCard"> + * <h3>Hello</h3> + * <input value="{/name}" input={this.onNameChanged} /> + * </div> + * )); + * } + * ``` + * + * ## Tag resolution + * + * A lowercase tag `"div"` becomes module path `"sap/html/Div"` by + * capitalising the first character. The only exception is `"selectedcontent"` + * which maps to `"sap/html/Selectedcontent"` (the class name that mirrors + * the HTML spec's lowercase `<selectedcontent>` element). All other elements + * follow the simple capitalisation rule (e.g. `"h1"` → `"sap/html/H1"` … + * wait — `"h1"` → `"H1"`: only the *first* character is uppercased, the rest + * stay as-is so `"h1"` → `"H1"`, `"blockquote"` → `"Blockquote"`). + * + * The runtime is **synchronous** by design, so resolution uses + * `sap.ui.require(modulePath)` which returns the already-loaded module + * synchronously. Call `preloadSapHtml()` first to ensure the library (and + * therefore every `sap/html/*` module) is loaded before any HTML-tag JSX + * runs. A clear error is thrown if the module is not yet loaded. + * + * ## Text children + * + * HTML elements can hold text. `sap.html` exposes two mechanisms: + * + * - **Sole text child** — one string child with no sibling controls → + * the string is forwarded as the `text` property of the control. + * - **Mixed content** — text interleaved with child controls → each text + * segment is wrapped in `sap.ui.core.html.TextContent` (a private core + * control), preserving source order in the `children` aggregation. + * + * ## Void elements + * + * Void elements (`br`, `hr`, `img`, `input`, `area`, `col`, `wbr`) cannot + * have children or a `text` property. Providing either throws a clear error + * at JSX construction time. + * + * @namespace ui5.community.jsx.runtime.plugins.html + */ + +import Lib from "sap/ui/core/Lib"; +import type ManagedObject from "sap/ui/base/ManagedObject"; +import { jsx } from "../../runtime/runtime"; +import type { ControlClass } from "../../runtime/runtime"; +import type { Scope } from "../../runtime/scope"; + +// --------------------------------------------------------------------------- +// Ambient shims for sap.html + sap/ui/core/html types not in @openui5/types +// --------------------------------------------------------------------------- + +/** + * Minimal surface of the `sap.html.*` control constructors we need: every + * sap/html/* class is constructable with a settings object, and has the + * standard ManagedObject API. The actual settings shapes are typed via the + * JSX.IntrinsicElements augmentation in runtime.ts; here we only need to + * construct them. + */ +type SapHtmlControlClass = ControlClass<ManagedObject>; + +// --------------------------------------------------------------------------- +// Void elements +// --------------------------------------------------------------------------- + +/** + * HTML void elements — they render no closing tag, must have no children, and + * the `sap.html` controls for these elements reject `text` / `children`. + */ +const VOID_ELEMENTS = new Set([ + "area", "base", "br", "col", "embed", "hr", "img", "input", + "link", "meta", "param", "source", "track", "wbr" +]); + +// --------------------------------------------------------------------------- +// Tag → sap/html/* module path +// --------------------------------------------------------------------------- + +/** + * Map a lowercase HTML tag name to its `sap/html/*` AMD module path. + * Rule: capitalise the first character only. + * e.g. `"div"` → `"sap/html/Div"`, `"h1"` → `"sap/html/H1"`, + * `"blockquote"` → `"sap/html/Blockquote"`. + * + * The only special case is `"selectedcontent"` → `"sap/html/Selectedcontent"`, + * which matches the actual class name in the library. + */ +export function tagToModulePath(tag: string): string { + // Capitalise first letter only; everything else stays as-is. + // "selectedcontent" → "Selectedcontent" (handled naturally by this rule). + const className = tag.charAt(0).toUpperCase() + tag.slice(1); + return `sap/html/${className}`; +} + +/** + * Synchronously resolve the `sap/html/*` control class for `tag`. + * + * Requires that `preloadSapHtml()` has been called and awaited beforehand + * so the AMD module is already in the require cache. Throws a descriptive + * error when the module is not loaded (typically because `preloadSapHtml()` + * was skipped or awaited after JSX began constructing the tree). + * + * @throws {Error} when the tag is not a known sap.html element or the + * library was not preloaded before this JSX call. + */ +export function resolveHtmlControl(tag: string): SapHtmlControlClass { + const modulePath = tagToModulePath(tag); + // sap.ui.require with a single string argument (no callback) returns the + // already-loaded module synchronously, or undefined if not yet loaded. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const ctor = (globalThis as Record<string, any>)["sap"]?.["ui"]?.require(modulePath) as + | SapHtmlControlClass + | undefined; + + if (typeof ctor !== "function") { + throw new Error( + `ui5/community/jsx/runtime/plugins/html: <${tag}> maps to module ` + + `"${modulePath}", but the module is not loaded. ` + + `Did you call and await preloadSapHtml() before this JSX view rendered? ` + + `Add \`await preloadSapHtml()\` to your Component.init() (or equivalent ` + + `bootstrap point) before initialising the router / creating the first view.` + ); + } + return ctor; +} + +// --------------------------------------------------------------------------- +// Text-child normalisation +// --------------------------------------------------------------------------- + +/** + * Normalise the `children` and `text` fields in the props bag for an + * `sap.html` control *before* delegating to the main `jsx()` factory. + * + * Rules (matching `XMLTemplateProcessor.handleChild` / sap.html semantics): + * + * 1. Void element with any `text` or `children` → throw. + * 2. Sole text child (string or number, no other siblings) → forward as the + * `text` property; remove from `children`. + * 3. Mixed content (text interleaved with control children) → wrap each + * text segment in a `sap/ui/core/html/TextContent` control inserted at + * the right position in `children`. + * 4. All-control children → `children` unchanged; no `text` property added. + * + * Returns a new props object (shallow clone) with `children` and `text` + * adjusted. The original props object is not mutated. + */ +export function normaliseHtmlProps( + tag: string, + props: Record<string, unknown> & { children?: unknown } +): Record<string, unknown> & { children?: unknown } { + const isVoid = VOID_ELEMENTS.has(tag); + const rawChildren = props.children; + + // For void elements: reject any children (or text property). + if (isVoid) { + const hasText = "text" in props && props.text !== undefined && props.text !== null && props.text !== ""; + const hasChildren = rawChildren !== null && rawChildren !== undefined; + if (hasText || hasChildren) { + throw new Error( + `ui5/community/jsx/runtime/plugins/html: <${tag}> is a void element ` + + `and cannot have children or a text property. ` + + `Found: ${hasChildren ? "children" : "text property"}.` + ); + } + return props; + } + + if (rawChildren === undefined || rawChildren === null) { + return props; + } + + // Flatten children into a simple array for analysis. We do a shallow + // flatten here (no fragment expansion) because the core's jsx() will + // run flattenChildren on the final children value — we only need to + // inspect the top-level children to distinguish "sole text" vs "mixed". + const childArray: unknown[] = Array.isArray(rawChildren) + ? (rawChildren as unknown[]) + : [rawChildren]; + + // Filter out JSX indentation artefacts — strings that are purely + // whitespace AND contain at least one newline, which is the signature + // of JSX-emitted indentation between elements (e.g. "\n\t\t\t\t"). + // Lone spaces such as {" "} or {" "} are intentional text content and + // must NOT be filtered here. + const meaningful = childArray.filter( + (c) => !(typeof c === "string" && c.trim() === "" && /[\n\r]/.test(c)) + ); + + if (meaningful.length === 0) { + // Only whitespace children — treat as no content, let core drop them. + const { children: _children, ...rest } = props; + return rest as Record<string, unknown> & { children?: unknown }; + } + + const allStrings = meaningful.every((c) => typeof c === "string" || typeof c === "number"); + const anyString = meaningful.some((c) => typeof c === "string" || typeof c === "number"); + + if (allStrings) { + // Sole text child path: combine all text segments (there may be more + // than one if JSX emitted ["Hello ", " world"] from interpolation), + // forward as `text` property. Removing `children` prevents the core + // from trying to place them into the default aggregation. + const textValue = meaningful.map(String).join(""); + const { children: _children, ...rest } = props; + return { ...rest, text: textValue }; + } + + if (anyString) { + // Mixed content: wrap each string in TextContent, keep controls as-is. + const TextContent = resolveTextContent(); + const normalized = meaningful.map((c) => { + if (typeof c === "string" || typeof c === "number") { + return new TextContent({ text: String(c) }); + } + return c; + }); + const { children: _children, ...rest } = props; + return { ...rest, children: normalized }; + } + + // All-control children — no normalisation needed. + return props; +} + +/** + * Synchronously resolve `sap/ui/core/html/TextContent` — the private core + * control used to carry inline text in mixed-content sap.html aggregations. + * Same preload requirement as the sap/html/* controls (it is in sap.ui.core + * which must be loaded; it is loaded by preloadSapHtml() via the core + * library dependency chain). + */ +function resolveTextContent(): new (settings?: { text?: string }) => ManagedObject { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const ctor = (globalThis as Record<string, any>)["sap"]?.["ui"]?.require( + "sap/ui/core/html/TextContent" + ) as (new (settings?: { text?: string }) => ManagedObject) | undefined; + if (typeof ctor !== "function") { + throw new Error( + `ui5/community/jsx/runtime/plugins/html: mixed text+control content ` + + `requires "sap/ui/core/html/TextContent" (part of sap.ui.core), ` + + `but the module is not loaded. ` + + `Ensure preloadSapHtml() was awaited before this view rendered.` + ); + } + return ctor; +} + +// --------------------------------------------------------------------------- +// The htmlIntrinsic handler +// --------------------------------------------------------------------------- + +/** + * The `htmlIntrinsic` implementation for the `sap.html` library. + * + * Installed via `withScope(htmlScope, fn)`. When `jsx()` encounters a + * string-typed element (e.g. `<div>`) it delegates here. This handler: + * + * 1. Validates the tag and resolves it to the `sap/html/*` control class. + * 2. Normalises text children to `text`/`TextContent` per sap.html semantics. + * 3. Re-enters the normal `jsx(Class, props)` path so all core intrinsics + * (`class=`, dot-handlers, `ref=`, binding, prop-type coercion) apply. + */ +export const sapHtmlIntrinsic: NonNullable<Scope["htmlIntrinsic"]> = ( + tag: string, + props: Record<string, unknown> & { children?: unknown } +): unknown => { + const controlClass = resolveHtmlControl(tag); + const normalised = normaliseHtmlProps(tag, props); + // Re-enter the normal control-instance pipeline. The cast to + // SapHtmlControlClass is safe: every sap/html/* class is a + // ManagedObject subclass with standard metadata. + return jsx(controlClass as SapHtmlControlClass, normalised); +}; + +// --------------------------------------------------------------------------- +// Scope entry point — spread into withScope +// --------------------------------------------------------------------------- + +/** + * Partial scope that installs the `sap.html` HTML intrinsic handler. + * + * Spread into `withScope` to enable HTML tags within that scope: + * + * ```tsx + * import { withScope } from "ui5/community/jsx/runtime/jsx-runtime"; + * import { htmlScope } from "ui5/community/jsx/runtime/plugins/html/index"; + * + * return withScope(htmlScope, () => ( + * <div class="wrapper">…</div> + * )); + * ``` + */ +export const htmlScope: Partial<Scope> = { + htmlIntrinsic: sapHtmlIntrinsic +}; + +// --------------------------------------------------------------------------- +// Library preload +// --------------------------------------------------------------------------- + +/** + * Load the `sap.html` library and async-require every control it declares + * (discovered from the library metadata's `controls` list) plus + * `sap/ui/core/html/TextContent`, so that all `sap/html/*` modules are in + * the synchronous require cache before any HTML-tag JSX view renders. + * + * Call **once** at application bootstrap — e.g. from `Component.init()` or + * from the root view's `onBeforeRendering`. Await the returned promise before + * initialising the router or opening any view that uses HTML tags. + * + * ```ts + * // In Component.init(): + * super.init(); + * await preloadSapHtml(); + * this.getRouter().initialize(); + * ``` + * + * Safe to call multiple times — UI5's `Lib.load` is idempotent. + */ +export async function preloadSapHtml(): Promise<void> { + // Load the library and discover all its controls/elements from the + // library metadata, then async-require all of them in one batch so + // resolveHtmlControl() can use the sync single-arg sap.ui.require form. + const lib = await Lib.load({ name: "sap.html" }); + + // The Lib instance exposes the "controls" array declared in library.js. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const libAny = lib as unknown as Record<string, any>; + const controls: string[] = Array.isArray(libAny["controls"]) ? libAny["controls"] : []; + + // Convert "sap.html.Div" → "sap/html/Div" (dot → slash). + const modulePaths = controls.map((fqn: string) => fqn.replace(/\./g, "/")); + + // Ensure sap/ui/core/html/TextContent is also fetched — it is needed for + // mixed text+control children but lives in sap.ui.core, not sap.html. + modulePaths.push("sap/ui/core/html/TextContent"); + + await new Promise<void>((resolve, reject) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (globalThis as Record<string, any>)["sap"]?.["ui"]?.require( + modulePaths, + () => resolve(), + reject + ); + }); +} diff --git a/packages/jsx-runtime/src/runtime/runtime.ts b/packages/jsx-runtime/src/runtime/runtime.ts index 39e183b..6211056 100644 --- a/packages/jsx-runtime/src/runtime/runtime.ts +++ b/packages/jsx-runtime/src/runtime/runtime.ts @@ -4,7 +4,7 @@ import DataType from "sap/ui/base/DataType"; import BindingParser from "sap/ui/base/BindingParser"; import View from "sap/ui/core/mvc/View"; import type Element from "sap/ui/core/Element"; -import type Event from "sap/ui/base/Event"; +import type UI5Event from "sap/ui/base/Event"; import type { ChildrenProcessor, ControlClass, @@ -167,19 +167,19 @@ function findController(start: Element): ControllerLike | undefined { * who need "capture now" semantics anyway (e.g. dialogs opened from * a shared controller that mount under different views). */ -function makeHandler(handlerName: string): (this: Element, event: Event) => void { +function makeHandler(handlerName: string): (this: Element, event: UI5Event) => void { // Capture any pinned controller at JSX-construction time, this // is the F2 improvement: authors can pin a specific controller // via `withScope({ controller }, …)` and the handler resolves // against it regardless of where the control ultimately mounts. const pinned = pinnedController(); - return function (this: Element, event: Event): void { + return function (this: Element, event: UI5Event): void { const controller = pinned ?? findController(this); const fn = controller?.[handlerName]; if (typeof fn !== "function") { throw new Error(`Event handler '${handlerName}' not found on controller`); } - (fn as (event: Event) => void).call(controller, event); + (fn as (event: UI5Event) => void).call(controller, event); }; } @@ -1027,7 +1027,7 @@ const fnHandlerIntrinsic: IntrinsicHandler = { return typeof ctx.value === "function" && ctx.metadata.hasEvent(propName); }, apply(_propName, value) { - const fn = value as (this: unknown, event: Event) => unknown; + const fn = value as (this: unknown, event: UI5Event) => unknown; const pinned = pinnedController(); if (pinned) { // Fast path: hand UI5 the same `[fn, listener]` shape XMLView @@ -1039,7 +1039,7 @@ const fnHandlerIntrinsic: IntrinsicHandler = { // inside the handler is resolved via the ancestor walk at fire // time. Bound functions ignore the reassigned receiver, so // `press={this.onTap.bind(this)}` still works transparently. - return function (this: Element, event: Event): unknown { + return function (this: Element, event: UI5Event): unknown { const owner = findController(this); return fn.call(owner ?? this, event); }; @@ -1458,29 +1458,12 @@ export namespace JSX { export interface ElementChildrenAttribute { children: object } /** - * Common HTML / SVG attribute bag, deliberately permissive. + * Permissive fallback for SVG, custom-element, and unknown tags. * - * String-typed JSX (`<div>`, `<svg>`, `<polyline>`) is the hook - * point for a future HTML-aware RenderManager plugin. Outside that - * plugin, the runtime throws a clear error at construction time, - * see the `htmlIntrinsic` dispatch in `jsx()`. - * - * The typing here is intentionally minimal: - * - * - The standard HTML attributes that *every* tag accepts - * (`id`, `class`, `style`, `title`, `data-*`, etc.) are typed. - * - `[attr: string]: unknown` covers the long tail (SVG-specific - * attributes, ARIA, custom-element props) without forcing us - * to mirror `lib.dom.d.ts`. - * - Event handlers are typed loosely as `(e: Event) => void`; - * the RM plugin's typed renderer can narrow them per-element - * via a more specific `IntrinsicElements` map if it wants. - * - * A future iteration can replace this with per-tag types pulled from - * `lib.dom.d.ts` (the same approach `solid-js` and `preact` use). - * For the sketch the permissive bag is enough to make - * `<div class="x"><polyline points="..."/></div>` typecheck cleanly - * without any cast. + * Used as the value type of the `[tag: string]` index signature in + * `IntrinsicElements` so that any tag not listed explicitly still + * compiles without a cast. Named `sap.html` tags get richer types + * via the specific interfaces below. */ export interface HTMLAttributes { id?: string; @@ -1495,34 +1478,492 @@ export namespace JSX { } /** - * `IntrinsicElements` is the type-checker's table of "what props - * does each string-typed tag accept". A non-empty map makes - * `<div>` legal in TSX; the value type defines the prop schema. + * Global attributes shared by every `sap.html` control (maps to the + * properties declared on `sap.html.HTMLElementBase`, available from + * OpenUI5 1.154.0). All props are optional; unset props emit no DOM + * attribute (UI5's "initial property" semantics). JSX-specific extras + * (`class`, `id`, `ref`, `children`) are added on top via + * `LibraryManagedAttributes`. + * + * Event handlers — listed explicitly for the most common DOM events — + * accept an inline function **or** a `".dotHandler"` controller-method + * string (resolved at fire-time against the surrounding view's controller + * by the core `dotHandlerIntrinsic`). Additional events can always be + * passed via the permissive `[prop: string]: any` index. + */ + export interface HtmlBaseAttributes { + // ---- Text content (text-only child shorthand) ---------------------- + /** Sole text child — rendered as text content inside the element. */ + text?: string; + // ---- Global HTML attributes (sap.html.HTMLElementBase) ------------- + accesskey?: string; + autocapitalize?: string; + autocorrect?: string; + autofocus?: boolean; + contenteditable?: string | boolean; + dir?: string; + draggable?: boolean; + enterkeyhint?: string; + hidden?: boolean; + inert?: boolean; + inputmode?: string; + lang?: string; + popover?: string; + role?: string; + spellcheck?: boolean; + style?: string; + tabindex?: string | number; + title?: string; + translate?: string; + // ---- ARIA attributes (subset of HTMLElementBase aria* properties) -- + ariaActiveDescendant?: string; + ariaAtomic?: string; + ariaAutoComplete?: string; + ariaBrailleLabel?: string; + ariaBrailleRoleDescription?: string; + ariaBusy?: string; + ariaChecked?: string; + ariaColCount?: string; + ariaColIndex?: string; + ariaColIndexText?: string; + ariaColSpan?: string; + ariaControls?: string; + ariaCurrent?: string; + ariaDescribedBy?: string; + ariaDescription?: string; + ariaDetails?: string; + ariaDisabled?: string; + ariaDropEffect?: string; + ariaErrorMessage?: string; + ariaExpanded?: string; + ariaFlowTo?: string; + ariaGrabbed?: string; + ariaHasPopup?: string; + ariaHidden?: string; + ariaInvalid?: string; + ariaKeyShortcuts?: string; + ariaLabel?: string; + ariaLabelledBy?: string; + ariaLevel?: string; + ariaLive?: string; + ariaModal?: string; + ariaMultiLine?: string; + ariaMultiSelectable?: string; + ariaOrientation?: string; + ariaOwns?: string; + ariaPlaceholder?: string; + ariaPosInSet?: string; + ariaPressed?: string; + ariaReadOnly?: string; + ariaRelevant?: string; + ariaRequired?: string; + ariaRoleDescription?: string; + ariaRowCount?: string; + ariaRowIndex?: string; + ariaRowIndexText?: string; + ariaRowSpan?: string; + ariaSelected?: string; + ariaSetSize?: string; + ariaSort?: string; + ariaValueMax?: string; + ariaValueMin?: string; + ariaValueNow?: string; + ariaValueText?: string; + // ---- Common DOM events (sap.html.HTMLElementBase events) ----------- + click?: ((e: UI5Event) => void) | `.${string}`; + auxclick?: ((e: UI5Event) => void) | `.${string}`; + dblclick?: ((e: UI5Event) => void) | `.${string}`; + keydown?: ((e: UI5Event) => void) | `.${string}`; + keyup?: ((e: UI5Event) => void) | `.${string}`; + keypress?: ((e: UI5Event) => void) | `.${string}`; + mousedown?: ((e: UI5Event) => void) | `.${string}`; + mouseup?: ((e: UI5Event) => void) | `.${string}`; + mousemove?: ((e: UI5Event) => void) | `.${string}`; + mouseenter?: ((e: UI5Event) => void) | `.${string}`; + mouseleave?: ((e: UI5Event) => void) | `.${string}`; + mouseover?: ((e: UI5Event) => void) | `.${string}`; + mouseout?: ((e: UI5Event) => void) | `.${string}`; + focus?: ((e: UI5Event) => void) | `.${string}`; + blur?: ((e: UI5Event) => void) | `.${string}`; + input?: ((e: UI5Event) => void) | `.${string}`; + change?: ((e: UI5Event) => void) | `.${string}`; + submit?: ((e: UI5Event) => void) | `.${string}`; + reset?: ((e: UI5Event) => void) | `.${string}`; + scroll?: ((e: UI5Event) => void) | `.${string}`; + toggle?: ((e: UI5Event) => void) | `.${string}`; + beforetoggle?: ((e: UI5Event) => void) | `.${string}`; + load?: ((e: UI5Event) => void) | `.${string}`; + error?: ((e: UI5Event) => void) | `.${string}`; + // JSX extras (class, id, ref, children, key handled by LibraryManagedAttributes) + /** @internal resolved by classIntrinsic */ + class?: string; + children?: unknown; + [prop: string]: any; + } + + /** Props for `<a>` — `sap.html.A` (since 1.154.0). */ + export interface AnchorAttributes extends HtmlBaseAttributes { + href?: string; + target?: string; + rel?: string; + download?: string | boolean; + hreflang?: string; + type?: string; + ping?: string; + referrerpolicy?: string; + } + + /** Props for `<button>` — `sap.html.Button` (since 1.154.0). */ + export interface ButtonHtmlAttributes extends HtmlBaseAttributes { + /** Use `enabled={false}` — the control maps it to the `disabled` attribute. */ + enabled?: boolean; + name?: string; + /** `"button" | "submit" | "reset"` */ + type?: string; + value?: string; + form?: string; + popovertarget?: string; + popovertargetaction?: string; + formaction?: string; + formenctype?: string; + formmethod?: string; + formnovalidate?: boolean; + formtarget?: string; + commandfor?: string; + command?: string; + } + + /** Props for `<img>` — `sap.html.Img` (since 1.154.0). */ + export interface ImgAttributes extends HtmlBaseAttributes { + src?: string; + alt?: string; + width?: number | string; + height?: number | string; + loading?: string; + decoding?: string; + fetchpriority?: string; + crossorigin?: string; + ismap?: boolean; + usemap?: string; + referrerpolicy?: string; + srcset?: string; + sizes?: string; + } + + /** Props for `<input>` — `sap.html.Input` (since 1.154.0). */ + export interface InputAttributes extends HtmlBaseAttributes { + /** Use `enabled={false}` — the control maps it to the `disabled` attribute. */ + enabled?: boolean; + name?: string; + /** `"text" | "email" | "number" | "password" | "checkbox" | "radio" | …` */ + type?: string; + value?: string; + checked?: boolean; + placeholder?: string; + readonly?: boolean; + required?: boolean; + multiple?: boolean; + min?: string | number; + max?: string | number; + step?: string | number; + minlength?: number; + maxlength?: number; + pattern?: string; + size?: number; + accept?: string; + autocomplete?: string; + list?: string; + form?: string; + formaction?: string; + formenctype?: string; + formmethod?: string; + formnovalidate?: boolean; + formtarget?: string; + popovertarget?: string; + popovertargetaction?: string; + } + + /** Props for `<label>` — `sap.html.Label` (since 1.154.0). */ + export interface LabelHtmlAttributes extends HtmlBaseAttributes { + /** ID of the labelled control. */ + for?: string; + form?: string; + } + + /** Props for `<select>` — `sap.html.Select` (since 1.154.0). */ + export interface SelectAttributes extends HtmlBaseAttributes { + /** Use `enabled={false}` — the control maps it to the `disabled` attribute. */ + enabled?: boolean; + name?: string; + multiple?: boolean; + required?: boolean; + size?: number; + autocomplete?: string; + form?: string; + } + + /** Props for `<textarea>` — `sap.html.Textarea` (since 1.154.0). */ + export interface TextareaAttributes extends HtmlBaseAttributes { + /** Use `enabled={false}` — the control maps it to the `disabled` attribute. */ + enabled?: boolean; + name?: string; + rows?: number; + cols?: number; + placeholder?: string; + readonly?: boolean; + required?: boolean; + minlength?: number; + maxlength?: number; + autocomplete?: string; + form?: string; + wrap?: string; + } + + /** Props for `<form>` — `sap.html.Form` (since 1.154.0). */ + export interface FormAttributes extends HtmlBaseAttributes { + action?: string; + method?: string; + enctype?: string; + target?: string; + novalidate?: boolean; + autocomplete?: string; + name?: string; + rel?: string; + } + + /** Props for `<table>` — `sap.html.Table` (since 1.154.0). */ + export interface TableHtmlAttributes extends HtmlBaseAttributes { + border?: string | number; + cellpadding?: string | number; + cellspacing?: string | number; + summary?: string; + } + + /** Props for `<td>` and `<th>` — `sap.html.Td` / `sap.html.Th` (since 1.154.0). */ + export interface TableCellAttributes extends HtmlBaseAttributes { + colspan?: number | string; + rowspan?: number | string; + headers?: string; + scope?: string; + abbr?: string; + } + + /** Props for `<col>` and `<colgroup>` — void / structural (since 1.154.0). */ + export interface ColAttributes extends HtmlBaseAttributes { + span?: number | string; + } + + /** Props for `<li>` — `sap.html.Li` (since 1.154.0). */ + export interface LiAttributes extends HtmlBaseAttributes { + value?: number | string; + } + + /** Props for `<ol>` — `sap.html.Ol` (since 1.154.0). */ + export interface OlAttributes extends HtmlBaseAttributes { + reversed?: boolean; + start?: number; + type?: string; + } + + /** Props for `<details>` — `sap.html.Details` (since 1.154.0). */ + export interface DetailsAttributes extends HtmlBaseAttributes { + open?: boolean; + name?: string; + } + + /** Props for `<dialog>` — if present in sap.html (since 1.154.0). */ + export interface DialogHtmlAttributes extends HtmlBaseAttributes { + open?: boolean; + } + + /** Props for `<meter>` — `sap.html.Meter` (since 1.154.0). */ + export interface MeterAttributes extends HtmlBaseAttributes { + value?: number | string; + min?: number | string; + max?: number | string; + low?: number | string; + high?: number | string; + optimum?: number | string; + form?: string; + } + + /** Props for `<progress>` — `sap.html.Progress` (since 1.154.0). */ + export interface ProgressAttributes extends HtmlBaseAttributes { + value?: number | string; + max?: number | string; + } + + /** Props for `<time>` — `sap.html.Time` (since 1.154.0). */ + export interface TimeAttributes extends HtmlBaseAttributes { + datetime?: string; + } + + /** Props for `<data>` — `sap.html.Data` (since 1.154.0). */ + export interface DataAttributes extends HtmlBaseAttributes { + value?: string; + } + + /** Props for `<option>` — `sap.html.Option` (since 1.154.0). */ + export interface OptionAttributes extends HtmlBaseAttributes { + value?: string; + selected?: boolean; + disabled?: boolean; + label?: string; + } + + /** Props for `<optgroup>` — `sap.html.Optgroup` (since 1.154.0). */ + export interface OptgroupAttributes extends HtmlBaseAttributes { + label?: string; + disabled?: boolean; + } + + /** Props for `<fieldset>` — `sap.html.Fieldset` (since 1.154.0). */ + export interface FieldsetAttributes extends HtmlBaseAttributes { + disabled?: boolean; + name?: string; + form?: string; + } + + /** Props for `<map>` — `sap.html.Map` (since 1.154.0). */ + export interface MapAttributes extends HtmlBaseAttributes { + name?: string; + } + + /** Props for `<area>` — `sap.html.Area` (void, since 1.154.0). */ + export interface AreaAttributes extends HtmlBaseAttributes { + alt?: string; + href?: string; + target?: string; + rel?: string; + download?: string | boolean; + referrerpolicy?: string; + coords?: string; + shape?: string; + ping?: string; + } + + /** Props for `<canvas>` — `sap.html.Canvas` (since 1.154.0). */ + export interface CanvasAttributes extends HtmlBaseAttributes { + width?: number | string; + height?: number | string; + } + + /** + * `IntrinsicElements` maps each lowercase HTML tag to the prop type of the + * corresponding `sap.html` control (available from OpenUI5 1.154.0 with + * the `ui5/community/jsx/runtime/plugins/html` opt-in plugin). Tags listed + * explicitly get per-element types derived from the `sap.html.*` settings + * interfaces; the `[tag: string]: HTMLAttributes` index is a permissive + * fallback for SVG, custom elements, and sap.html tags not listed here. * - * The string-indexer entry is what actually matters here, it - * makes *every* HTML/SVG/custom-element tag legal with the - * permissive `HTMLAttributes` shape. The named entries are listed - * for IDE-completion friendliness on the most common tags; they - * resolve to the same shape. + * Note: use the `enabled` prop (not `disabled`) for interactive controls + * (`<button>`, `<input>`, `<select>`, `<textarea>`) — `sap.html` controls + * map `enabled={false}` to the native `disabled` attribute. */ export interface IntrinsicElements { + // Permissive fallback — SVG, custom elements, unlisted sap.html tags: [tag: string]: HTMLAttributes; - // Common HTML - div: HTMLAttributes; - span: HTMLAttributes; - p: HTMLAttributes; - a: HTMLAttributes; - button: HTMLAttributes; - input: HTMLAttributes; - label: HTMLAttributes; - ul: HTMLAttributes; - ol: HTMLAttributes; - li: HTMLAttributes; - table: HTMLAttributes; - tr: HTMLAttributes; - td: HTMLAttributes; - th: HTMLAttributes; - // Common SVG + // ---- sap.html block-level / grouping elements ---------------------- + div: HtmlBaseAttributes; + p: HtmlBaseAttributes; + section: HtmlBaseAttributes; + article: HtmlBaseAttributes; + aside: HtmlBaseAttributes; + header: HtmlBaseAttributes; + footer: HtmlBaseAttributes; + main: HtmlBaseAttributes; + nav: HtmlBaseAttributes; + hgroup: HtmlBaseAttributes; + blockquote: HtmlBaseAttributes; + pre: HtmlBaseAttributes; + figure: HtmlBaseAttributes; + figcaption: HtmlBaseAttributes; + address: HtmlBaseAttributes; + search: HtmlBaseAttributes; + // ---- sap.html inline elements -------------------------------------- + span: HtmlBaseAttributes; + a: AnchorAttributes; + abbr: HtmlBaseAttributes; + b: HtmlBaseAttributes; + bdi: HtmlBaseAttributes; + bdo: HtmlBaseAttributes; + cite: HtmlBaseAttributes; + code: HtmlBaseAttributes; + data: DataAttributes; + dfn: HtmlBaseAttributes; + em: HtmlBaseAttributes; + i: HtmlBaseAttributes; + ins: HtmlBaseAttributes; + del: HtmlBaseAttributes; + kbd: HtmlBaseAttributes; + mark: HtmlBaseAttributes; + q: HtmlBaseAttributes; + rp: HtmlBaseAttributes; + rt: HtmlBaseAttributes; + ruby: HtmlBaseAttributes; + s: HtmlBaseAttributes; + samp: HtmlBaseAttributes; + small: HtmlBaseAttributes; + strong: HtmlBaseAttributes; + sub: HtmlBaseAttributes; + sup: HtmlBaseAttributes; + time: TimeAttributes; + u: HtmlBaseAttributes; + "var": HtmlBaseAttributes; + wbr: HtmlBaseAttributes; + // ---- sap.html heading elements ------------------------------------- + h1: HtmlBaseAttributes; + h2: HtmlBaseAttributes; + h3: HtmlBaseAttributes; + h4: HtmlBaseAttributes; + h5: HtmlBaseAttributes; + h6: HtmlBaseAttributes; + // ---- sap.html list elements ---------------------------------------- + ul: HtmlBaseAttributes; + ol: OlAttributes; + li: LiAttributes; + dl: HtmlBaseAttributes; + dt: HtmlBaseAttributes; + dd: HtmlBaseAttributes; + menu: HtmlBaseAttributes; + // ---- sap.html table elements --------------------------------------- + table: TableHtmlAttributes; + caption: HtmlBaseAttributes; + colgroup: ColAttributes; + col: ColAttributes; + thead: HtmlBaseAttributes; + tbody: HtmlBaseAttributes; + tfoot: HtmlBaseAttributes; + tr: HtmlBaseAttributes; + td: TableCellAttributes; + th: TableCellAttributes; + // ---- sap.html form elements ---------------------------------------- + form: FormAttributes; + input: InputAttributes; + button: ButtonHtmlAttributes; + select: SelectAttributes; + textarea: TextareaAttributes; + label: LabelHtmlAttributes; + fieldset: FieldsetAttributes; + legend: HtmlBaseAttributes; + datalist: HtmlBaseAttributes; + optgroup: OptgroupAttributes; + option: OptionAttributes; + output: HtmlBaseAttributes; + // ---- sap.html interactive / sectioning elements -------------------- + details: DetailsAttributes; + summary: HtmlBaseAttributes; + meter: MeterAttributes; + progress: ProgressAttributes; + // ---- sap.html media/embedded elements (void or structural) ---------- + img: ImgAttributes; + area: AreaAttributes; + map: MapAttributes; + canvas: CanvasAttributes; + // ---- sap.html void / self-closing elements -------------------------- + br: HtmlBaseAttributes; + hr: HtmlBaseAttributes; + // ---- SVG (permissive — not sap.html; use HTMLAttributes fallback) -- svg: HTMLAttributes; g: HTMLAttributes; path: HTMLAttributes; diff --git a/packages/jsx-runtime/test/qunit/plugins/html.qunit.ts b/packages/jsx-runtime/test/qunit/plugins/html.qunit.ts new file mode 100644 index 0000000..3098a41 --- /dev/null +++ b/packages/jsx-runtime/test/qunit/plugins/html.qunit.ts @@ -0,0 +1,351 @@ +/** + * QUnit tests for the `plugins/html` (sap.html) opt-in plugin. + * + * Strategy: since `sap.html` ships in OpenUI5 1.154.0 and the test + * environment runs on 1.148.2, the tests fake the `sap/html/*` and + * `sap/ui/core/html/TextContent` modules by wrapping `sap.ui.require` + * with a function that returns stub `ManagedObject.extend` subclasses + * for the known fake paths, and falls through to the real require for + * everything else. + * + * Tests cover: + * - tag-to-module-path resolution (pure function) + * - `resolveHtmlControl` sync require + error case + * - `normaliseHtmlProps`: void-element guard, sole text child, + * mixed content (TextContent wrappers), all-control children + * - `sapHtmlIntrinsic` end-to-end via `withScope(htmlScope, …)` + * - control children inside an HTML control + * - `class=` and `ref=` forwarding + * - string tag inside `withScope(htmlScope)` dispatches to the handler + */ +import { jsx, withScope } from "ui5/community/jsx/runtime/jsx-runtime"; +import { + tagToModulePath, + resolveHtmlControl, + normaliseHtmlProps, + sapHtmlIntrinsic, + htmlScope +} from "ui5/community/jsx/runtime/plugins/html/index"; +import ManagedObject from "sap/ui/base/ManagedObject"; +import Control from "sap/ui/core/Control"; +import Text from "sap/m/Text"; +import VBox from "sap/m/VBox"; + +// --------------------------------------------------------------------------- +// Fake sap.html.* and TextContent classes +// --------------------------------------------------------------------------- + +// Minimal fake that mimics a sap.html element control. +// Extends Control (not ManagedObject) so that `addStyleClass`/`hasStyleClass` +// work, and so the control can be placed in sap.m.VBox.items which is typed +// for sap.ui.core.Control. +const FakeBase = Control.extend("ui5.community.jsx.runtime.test.html.FakeBase", { + metadata: { + defaultAggregation: "children", + properties: { + text: { type: "string", defaultValue: "" } + }, + aggregations: { + children: { type: "sap.ui.core.Control", multiple: true } + } + }, + renderer: { apiVersion: 2, render: () => {/* no-op for tests */ } } +}); + +// FakeBase is inferred as `Function` by TS (Control.extend returns `Function`); +// cast to `typeof Control` so .extend() is available for subclassing. +const FakeBaseClass = FakeBase as unknown as typeof Control; +const FakeDiv = FakeBaseClass.extend("ui5.community.jsx.runtime.test.html.FakeDiv", {}); +const FakeSpan = FakeBaseClass.extend("ui5.community.jsx.runtime.test.html.FakeSpan", {}); +const FakeH1 = FakeBaseClass.extend("ui5.community.jsx.runtime.test.html.FakeH1", {}); +const FakeInput = FakeBaseClass.extend("ui5.community.jsx.runtime.test.html.FakeInput", {}); +const FakeSelectedcontent = FakeBaseClass.extend( + "ui5.community.jsx.runtime.test.html.FakeSelectedcontent", + {} +); + +// Minimal fake for sap/ui/core/html/TextContent (text-only control used in +// mixed content). Extends Control so it can be placed in children aggregations +// typed as sap.ui.core.Control. +const FakeTextContent = Control.extend( + "ui5.community.jsx.runtime.test.html.FakeTextContent", + { + metadata: { + properties: { + text: { type: "string", defaultValue: "" } + } + }, + renderer: { apiVersion: 2, render: () => {/* no-op for tests */ } } + } +); + +// --------------------------------------------------------------------------- +// Fake require registry +// --------------------------------------------------------------------------- + +// Map of module path → fake constructor. This is the lookup table that the +// patched sap.ui.require will consult for the single-string (sync) form. +const FAKE_MODULES: Record<string, unknown> = { + "sap/html/Div": FakeDiv, + "sap/html/Span": FakeSpan, + "sap/html/H1": FakeH1, + "sap/html/Input": FakeInput, + "sap/html/Selectedcontent": FakeSelectedcontent, + "sap/ui/core/html/TextContent": FakeTextContent +}; + +// Keep a reference to the original sap.ui.require for tear-down. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const sapUI = (globalThis as Record<string, any>)["sap"]?.["ui"] as + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Record<string, any> | undefined; +const originalRequire = sapUI?.["require"] as ((...args: unknown[]) => unknown) | undefined; + +/** + * Install the patched sap.ui.require that returns fake sap.html classes + * for the module paths listed in FAKE_MODULES. All other single-string + * calls fall through to the real require; multi-arg (async) calls are + * passed through unchanged. + */ +function installFakeRequire(): void { + if (!sapUI || !originalRequire) return; + + const patched = function patchedRequire(...args: unknown[]): unknown { + // Single-string synchronous form: check fake registry first. + if (args.length === 1 && typeof args[0] === "string") { + const path = args[0]; + if (Object.prototype.hasOwnProperty.call(FAKE_MODULES, path)) { + return FAKE_MODULES[path]; + } + } + // Everything else: delegate to original. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return originalRequire.apply(sapUI, args as Parameters<any>); + }; + // Copy over any own properties (e.g. sap.ui.require.toUrl). + Object.assign(patched, originalRequire); + sapUI["require"] = patched; +} + +function uninstallFakeRequire(): void { + if (sapUI && originalRequire) { + sapUI["require"] = originalRequire; + } +} + +// Install once for the entire test file before any modules run. +installFakeRequire(); + +// --------------------------------------------------------------------------- +// tagToModulePath — pure function, no require involved +// --------------------------------------------------------------------------- + +QUnit.module("plugins/html — tagToModulePath"); + +QUnit.test("div → sap/html/Div", (assert) => { + assert.strictEqual(tagToModulePath("div"), "sap/html/Div"); +}); +QUnit.test("span → sap/html/Span", (assert) => { + assert.strictEqual(tagToModulePath("span"), "sap/html/Span"); +}); +QUnit.test("h1 → sap/html/H1 (only first char uppercased)", (assert) => { + assert.strictEqual(tagToModulePath("h1"), "sap/html/H1"); +}); +QUnit.test("h6 → sap/html/H6", (assert) => { + assert.strictEqual(tagToModulePath("h6"), "sap/html/H6"); +}); +QUnit.test("blockquote → sap/html/Blockquote", (assert) => { + assert.strictEqual(tagToModulePath("blockquote"), "sap/html/Blockquote"); +}); +QUnit.test("selectedcontent → sap/html/Selectedcontent", (assert) => { + assert.strictEqual(tagToModulePath("selectedcontent"), "sap/html/Selectedcontent"); +}); + +// --------------------------------------------------------------------------- +// resolveHtmlControl — sync require via patched sap.ui.require +// --------------------------------------------------------------------------- + +QUnit.module("plugins/html — resolveHtmlControl"); + +QUnit.test("resolves 'div' to FakeDiv", (assert) => { + assert.strictEqual(resolveHtmlControl("div"), FakeDiv); +}); +QUnit.test("resolves 'h1' to FakeH1", (assert) => { + assert.strictEqual(resolveHtmlControl("h1"), FakeH1); +}); +QUnit.test("resolves 'selectedcontent' to FakeSelectedcontent", (assert) => { + assert.strictEqual(resolveHtmlControl("selectedcontent"), FakeSelectedcontent); +}); +QUnit.test("throws a clear error for an unknown / not-preloaded tag", (assert) => { + assert.throws( + () => resolveHtmlControl("thisdoesnotexist"), + /preloadSapHtml|not loaded/i, + "error mentions preloadSapHtml" + ); +}); + +// --------------------------------------------------------------------------- +// normaliseHtmlProps — text-child normalisation +// --------------------------------------------------------------------------- + +QUnit.module("plugins/html — normaliseHtmlProps"); + +QUnit.test("sole text child → `text` property, children removed", (assert) => { + const result = normaliseHtmlProps("span", { children: "Hello" }); + assert.strictEqual((result as Record<string, unknown>).text, "Hello", "text set"); + assert.notOk("children" in result, "children removed"); +}); + +QUnit.test("sole number child → `text` property (stringified)", (assert) => { + const result = normaliseHtmlProps("span", { children: 42 }); + assert.strictEqual((result as Record<string, unknown>).text, "42"); +}); + +QUnit.test("whitespace-only children treated as empty (no text, no children)", (assert) => { + // JSX indentation artefacts always contain newlines ("\n\t\t\t\t"); pure- + // space strings like {" "} are intentional content and must be preserved. + const result = normaliseHtmlProps("span", { children: ["\n\t", "\n\t\t"] }); + assert.notOk("children" in result, "no children"); + assert.notOk("text" in result, "no text property for whitespace-only content"); +}); + +QUnit.test("lone space {' '} preserved as text content", (assert) => { + const result = normaliseHtmlProps("span", { children: " " }); + assert.strictEqual((result as Record<string, unknown>).text, " ", "single space kept as text"); +}); + +QUnit.test("multiple text segments concatenated into `text`", (assert) => { + const result = normaliseHtmlProps("span", { children: ["Hello, ", "World"] }); + assert.strictEqual((result as Record<string, unknown>).text, "Hello, World"); +}); + +QUnit.test("mixed text + control → TextContent wrappers in children", (assert) => { + const inner = new Text({ text: "ctrl" }); + const result = normaliseHtmlProps("p", { children: ["Before ", inner, " after"] }); + const children = (result as Record<string, unknown>).children as unknown[]; + assert.strictEqual(children.length, 3, "three children: TextContent, control, TextContent"); + assert.ok(children[0] instanceof FakeTextContent, "first child is FakeTextContent"); + assert.strictEqual( + (children[0] as ManagedObject).getProperty("text") as string, + "Before ", + "first text segment preserved" + ); + assert.strictEqual(children[1], inner, "control preserved in position"); + assert.ok(children[2] instanceof FakeTextContent, "third child is FakeTextContent"); + assert.strictEqual( + (children[2] as ManagedObject).getProperty("text") as string, + " after", + "last text segment preserved" + ); + inner.destroy(); + (children[0] as ManagedObject).destroy(); + (children[2] as ManagedObject).destroy(); +}); + +QUnit.test("all-control children unchanged, no text property added", (assert) => { + const a = new Text({ text: "a" }); + const b = new Text({ text: "b" }); + const result = normaliseHtmlProps("div", { children: [a, b] }); + const children = (result as Record<string, unknown>).children as unknown[]; + assert.deepEqual(children, [a, b], "children passed through as-is"); + assert.notOk("text" in result, "no text property added"); + a.destroy(); + b.destroy(); +}); + +QUnit.test("void element with text child throws with 'void element' in message", (assert) => { + assert.throws( + () => normaliseHtmlProps("br", { children: "oops" }), + /void element/i + ); +}); + +QUnit.test("void element with text property throws", (assert) => { + assert.throws( + () => normaliseHtmlProps("input", { text: "oops" }), + /void element/i + ); +}); + +QUnit.test("non-void element with no children returns props unchanged", (assert) => { + const result = normaliseHtmlProps("div", { text: "hello" }); + assert.deepEqual(result, { text: "hello" }); +}); + +// --------------------------------------------------------------------------- +// sapHtmlIntrinsic + withScope(htmlScope, …) — integration +// --------------------------------------------------------------------------- + +QUnit.module("plugins/html — sapHtmlIntrinsic / withScope(htmlScope)"); + +QUnit.test("constructs the resolved control class via jsx()", (assert) => { + const inst = withScope(htmlScope, () => sapHtmlIntrinsic("div", {})); + assert.ok(inst instanceof FakeDiv, "instance of FakeDiv"); + (inst as ManagedObject).destroy(); +}); + +QUnit.test("sole text child lands as `text` property on the control", (assert) => { + const inst = withScope(htmlScope, () => + sapHtmlIntrinsic("span", { children: "Hello" }) + ) as ManagedObject; + assert.strictEqual(inst.getProperty("text") as string, "Hello"); + inst.destroy(); +}); + +QUnit.test("UI5 control child lands in default aggregation 'children'", (assert) => { + const textCtrl = jsx(Text, { text: "inner" }) as Text; + const inst = withScope(htmlScope, () => + sapHtmlIntrinsic("div", { children: textCtrl }) + ) as ManagedObject; + const agg = inst.getAggregation("children") as unknown[]; + assert.ok(Array.isArray(agg) && agg.includes(textCtrl), "control in children aggregation"); + inst.destroy(); +}); + +QUnit.test("class= is applied via addStyleClass", (assert) => { + const inst = withScope(htmlScope, () => + sapHtmlIntrinsic("div", { class: "myClass" }) + ) as ManagedObject; + assert.ok( + (inst as unknown as { hasStyleClass(c: string): boolean }).hasStyleClass("myClass"), + "style class added" + ); + inst.destroy(); +}); + +QUnit.test("HTML control as child of sap.m.VBox works", (assert) => { + const htmlChild = withScope(htmlScope, () => + sapHtmlIntrinsic("span", { children: "text" }) + ) as ManagedObject; + const vbox = jsx(VBox as unknown as Parameters<typeof jsx>[0], { + children: htmlChild + }) as VBox; + const items = vbox.getItems(); + assert.ok(items.includes(htmlChild as never), "html control in VBox items"); + vbox.destroy(); +}); + +QUnit.test("ref= callback receives the constructed instance", (assert) => { + let received: unknown; + const inst = withScope(htmlScope, () => + sapHtmlIntrinsic("div", { ref: (i: unknown) => { received = i; } }) + ) as ManagedObject; + assert.strictEqual(received, inst, "ref called with instance"); + inst.destroy(); +}); + +QUnit.test("jsx('span') inside withScope(htmlScope) dispatches to htmlIntrinsic", (assert) => { + const inst = withScope(htmlScope, () => + jsx("span" as never, { children: "ok" }) + ) as ManagedObject; + assert.ok(inst instanceof FakeSpan, "resolved to FakeSpan via htmlIntrinsic"); + inst.destroy(); +}); + +// --------------------------------------------------------------------------- +// Tear-down: restore original sap.ui.require after all tests +// --------------------------------------------------------------------------- + +QUnit.done(() => { + uninstallFakeRequire(); +}); diff --git a/packages/jsx-runtime/test/qunit/testsuite.qunit.ts b/packages/jsx-runtime/test/qunit/testsuite.qunit.ts index e1cfbbb..92c8e7d 100644 --- a/packages/jsx-runtime/test/qunit/testsuite.qunit.ts +++ b/packages/jsx-runtime/test/qunit/testsuite.qunit.ts @@ -36,6 +36,7 @@ export default { "runtime/string-aggregation-binding": { title: "runtime: string aggregation binding + template" }, "runtime/forwarded-aggregation": { title: "runtime: forwarded default aggregation (Menu#items)" }, "runtime/view-error-logging": { title: "runtime: view createContent() errors logged via Log.error" }, - "plugins/switch": { title: "plugins: <Switch> / <Case> / <Default>" } + "plugins/switch": { title: "plugins: <Switch> / <Case> / <Default>" }, + "plugins/html": { title: "plugins: html sap.html intrinsic" } } };