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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/generics/lib.generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4447,3 +4447,57 @@ class DisposableStack<X = int> {
}
}
}

// JSX's default factory: a .tsx file's `<div class="a">{x}</div>` is `h("div", { class: "a" }, x)`, and
// where the program declares no `h` of its own the compiler calls this one (JsxElement and the fragment:
// see lib.ts). It is not named `h` here: a program's own `h` would merge with it. A tag that is a function
// is a component, called with the attributes and the children, `Item(props, children)`, as its parameters
// take them: `() => ...`,
// `(props: { name: string }) => ...` and `(props, children: any[]) => ...` are all components. What it
// returns is the element; anything else (a string, a number, an array) becomes a fragment of it.
// Generic, so that a component is called as it is typed and each child keeps its type until it is
// put among the element's children. Not under -mm=own: the element keeps its children.
function __jsx_h<T, P, C extends any[]>(tag: T, props: P, ...children: C) {
const items: any[] = [];
for (const child of children) {
__jsxAddChild(items, child);
}

if (typeof tag == "function") {
const component = tag as (props: P, children: any[]) => ReturnType<T>;
return __jsxAsElement(component(props, items));
}

if (typeof tag == "string") {
return new JsxElement(tag, props, items);
}

return new JsxElement("", null, items);
}

// what a component returned, as an element
function __jsxAsElement<R>(result: R) {
// an instance's `typeof` is "class" here
if (typeof result == "class") {
if (result instanceof JsxElement) {
return result;
}
}

const items: any[] = [];
__jsxAddChild(items, result);
return new JsxElement("", null, items);
}

// a child among `items`: an array's items each, nothing of null, undefined and a boolean
function __jsxAddChild<V>(items: any[], child: V) {
if (Array.isArray(child)) {
for (const item of child) {
__jsxAddChild(items, item);
}
} else if (child === null || child === undefined || typeof child == "boolean") {
// React leaves them out: `{cond && <b />}`
} else {
items.push(child);
}
}
15 changes: 15 additions & 0 deletions src/lib.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1053,3 +1053,18 @@ declare namespace Temporal {
declare function plainTimeISO(): Temporal.PlainTime;
}
}

// JSX: see lib.ts. The default factory, __jsx_h, is in generics/lib.generics.ts.
@owned
declare class JsxElement {
public tag: string;
public props: any;
public children: any[];
@keeps("tag", "props", "children")
constructor(tag: string, props: any, children: any[]);
public toString(): string;
}

@owned
@keeps("children")
declare function __jsx_Fragment(props: null, children: any[]): JsxElement;
112 changes: 112 additions & 0 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4645,3 +4645,115 @@ export namespace Temporal {
}
}
}

// JSX. A .tsx file's elements are calls of `h`, the default JSX factory, unless the file names another one
// (`/** @jsx f */`, "jsxFactory", --jsx-factory); where the program declares no `h` of its own the compiler
// calls the library's, __jsx_h (lib.generics.ts), and `<>...</>` is __jsx_Fragment. An element is a JsxElement:
// its tag, its attributes as written (`props`, null when it has none) and its children, flattened
// (an array is its items) and without null, undefined and booleans (`{cond && <b />}`), as React
// leaves them out. `toString()` (so print(e), String(e), `${e}`) is the element as HTML.
export class JsxElement {
// `tag` "" is a fragment (`<>...</>`): its children alone
@keeps("tag", "props", "children")
public constructor(public tag: string, public props: any, public children: any[]) {
}

public toString(): string {
let html = "";
const tag = this.tag;
if (tag != "") {
html += "<" + tag;
// -mm=own reads no keys of an `any` (and the compiler refuses the library's factory there)
const props = this.props;
if (props != null) {
if (__MEMORY_MODEL__ == "own") {
throw new TypeError("the attributes of a JSX element can't be read under -mm=own");
} else {
for (const name in props) {
html += __jsxAttribute(name, props[name]);
}
}
}

html += ">";
if (__jsxIsVoid(tag)) {
return html;
}
}

for (const child of this.children) {
html += typeof child == "string" ? __jsxEscape(<string>child, false) : String(child);
}

if (tag != "") {
html += "</" + tag + ">";
}

return html;
}
}

// `<>...</>`'s tag where the program declares no `Fragment`: its children alone (a fragment has no
// attributes: `props` is null)
@keeps("children")
export function __jsx_Fragment(props: null, children: any[]): JsxElement {
return new JsxElement("", null, children);
}

// ` name="value"`; nothing for null, undefined and false, the name alone for true. React's className
// and htmlFor are HTML's class and for.
function __jsxAttribute(name: string, value: any): string {
if (value == null || value === false) {
return "";
}

const html = name == "className" ? "class" : name == "htmlFor" ? "for" : name;
if (value === true) {
return " " + html;
}

return " " + html + "=\"" + __jsxEscape(String(value), true) + "\"";
}

// the elements HTML writes without an end tag
function __jsxIsVoid(tag: string): boolean {
switch (tag) {
case "area":
case "base":
case "br":
case "col":
case "embed":
case "hr":
case "img":
case "input":
case "link":
case "meta":
case "source":
case "track":
case "wbr":
return true;
}

return false;
}

// text as HTML: & < > escaped, and " too in an attribute's value
function __jsxEscape(text: string, attribute: boolean): string {
let html = "";
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (c == 38 /* & */) {
html += "&amp;";
} else if (c == 60 /* < */) {
html += "&lt;";
} else if (c == 62 /* > */) {
html += "&gt;";
} else if (attribute && c == 34 /* " */) {
html += "&quot;";
} else {
html += text[i];
}
}

return html;
}
49 changes: 49 additions & 0 deletions tests/jsx_default_factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// not own: -mm=own refuses the default JSX factory (an element keeps its children)
// The default JSX factory, __jsx_h, as a .tsx element calls it where the program declares no `h` of its own
// (`<p class="x">a</p>` is `h("p", { class: "x" }, "a")`): a JsxElement that prints as HTML. A tag that is a
// function is a component, called with what its parameters take; arrays among the children are flattened,
// null, undefined and booleans left out, text and attribute values escaped. `<>...</>` is __jsx_Fragment.

function check(condition: boolean, message: string) {
if (!condition) {
console.log("fail:", message);
assert(false, message);
}
}

function Item(props: { name: string }) {
return __jsx_h("li", { class: "item" }, props.name);
}

function Card(props: { title: string }, children: any[]) {
return __jsx_h("section", null, __jsx_h("h2", null, props.title), children);
}

function Rule() {
return __jsx_h("hr", null);
}

function Count(props: { n: int }) {
return "n=" + props.n;
}

function main() {
check(`${__jsx_h("div", null)}` == "<div></div>", "an empty element");

const names = ["a", "b<c"];
const shown = false;
const page = __jsx_h(Card, { title: "T & U" },
__jsx_h("ul", { id: "list", hidden: false, disabled: true }, names.map(n => __jsx_h(Item, { name: n }))),
shown && __jsx_h("b", null, "never"), null,
__jsx_h(Rule, null), __jsx_h(Count, { n: 7 }),
__jsx_h(__jsx_Fragment, null, "x", 1, "y"),
__jsx_h("input", { value: "q\"r", className: "c" }));

const html = `${page}`;
print(html);
check(html == "<section><h2>T &amp; U</h2><ul id=\"list\" disabled><li class=\"item\">a</li>"
+ "<li class=\"item\">b&lt;c</li></ul><hr>n=7x1y<input value=\"q&quot;r\" class=\"c\"></section>", "the page");
check(String(page) == html, "String() as the template");
check(page.tag == "section" && page.children.length == 6, "the component's element, its children as given");
console.log("ALL DONE");
}
Loading