Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created March 22, 2020 07:41
Show Gist options
  • Save kayac-chang/348010d96738d3f6dcc2815b8d3339a9 to your computer and use it in GitHub Desktop.
Save kayac-chang/348010d96738d3f6dcc2815b8d3339a9 to your computer and use it in GitHub Desktop.
Simple JSX
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple JSX</title>
</head>
<body>
<script src="./jsx.js"></script>
</body>
</html>
function jsx(tempStr, ...args) {
tempStr = tempStr.map(token => token.trim());
let result = tempStr[0];
for (let i = 0; i < args.length; ++i) {
const token = args[i];
if (Array.isArray(token) && token.length) {
//
for (let j = 0; j < token.length; ++j) {
const key = `${i},${j}`;
if (token[j] instanceof HTMLTableCellElement) {
result += `<td id=${key} ></td>`;
}
if (token[j] instanceof HTMLTableRowElement) {
result += `<tr id=${key} ></tr>`;
}
}
//
result += tempStr[i + 1];
continue;
}
if (token instanceof HTMLTableSectionElement) {
//
result += `<tbody id=${i} ></tbody>`;
result += tempStr[i + 1];
continue;
}
if (token instanceof HTMLElement) {
//
result += `<slot id=${i} ></slot>`;
result += tempStr[i + 1];
continue;
}
result += args[i];
result += tempStr[i + 1];
}
const temp = document.createElement("template");
temp.innerHTML = result;
Array.from(temp.content.querySelectorAll("slot, tbody"))
.filter(el => el.hasAttribute("id"))
.forEach(el => el.replaceWith(args[el.id]));
Array.from(temp.content.querySelectorAll("td, tr"))
.filter(el => el.hasAttribute("id"))
.forEach(el => {
const [i, j] = el.id.split(",");
el.parentNode.append(args[i][j]);
el.remove();
});
return temp.content.firstChild;
}
function Record(Company = "", Contact = "", Country = "") {
return { Company, Contact, Country };
}
function main() {
const rows = [
Record("Alfreds Futterkiste", "Maria Anders", "Germany"),
Record("Centro comercial Moctezuma", "Francisco Chang", "Mexico"),
Record("Ernst Handel", "Roland Mendel", "Austria"),
Record("Island Trading", "Helen Bennett", "UK"),
Record("Laughing Bacchus Winecellars", "Yoshi Tannamuri", "Canada"),
Record("Magazzini Alimentari Riuniti", "Giovanni Rovelli", "Italy")
];
const thead = jsx`
<thead>
<tr>
${Object.keys(Record()).map(key => jsx`<th>${key}</th>`)}
</tr>
</thead>
`;
const tbody = jsx`
<tbody>
${rows.map(
({ Company, Contact, Country }) => jsx`
<tr>
<td>${Company}</td>
<td>${Contact}</td>
<td>${Country}</td>
</tr>
`
)}
</tbody>
`;
const res = jsx`
<table>
${thead}
${tbody}
</table>
`;
document.body.append(res);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment