jsx.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* eslint-disable @typescript-eslint/no-namespace, import/export */
  2. import { vnode } from "./vnode";
  3. import { h } from "./h";
  4. export function Fragment(data, ...children) {
  5. const flatChildren = flattenAndFilter(children, []);
  6. if (flatChildren.length === 1 &&
  7. !flatChildren[0].sel &&
  8. flatChildren[0].text) {
  9. // only child is a simple text node, pass as text for a simpler vtree
  10. return vnode(undefined, undefined, undefined, flatChildren[0].text, undefined);
  11. }
  12. else {
  13. return vnode(undefined, data !== null && data !== void 0 ? data : {}, flatChildren, undefined, undefined);
  14. }
  15. }
  16. function flattenAndFilter(children, flattened) {
  17. for (const child of children) {
  18. // filter out falsey children, except 0 since zero can be a valid value e.g inside a chart
  19. if (child !== undefined &&
  20. child !== null &&
  21. child !== false &&
  22. child !== "") {
  23. if (Array.isArray(child)) {
  24. flattenAndFilter(child, flattened);
  25. }
  26. else if (typeof child === "string" ||
  27. typeof child === "number" ||
  28. typeof child === "boolean") {
  29. flattened.push(vnode(undefined, undefined, undefined, String(child), undefined));
  30. }
  31. else {
  32. flattened.push(child);
  33. }
  34. }
  35. }
  36. return flattened;
  37. }
  38. /**
  39. * jsx/tsx compatible factory function
  40. * see: https://www.typescriptlang.org/docs/handbook/jsx.html#factory-functions
  41. */
  42. export function jsx(tag, data, ...children) {
  43. const flatChildren = flattenAndFilter(children, []);
  44. if (typeof tag === "function") {
  45. // tag is a function component
  46. return tag(data, flatChildren);
  47. }
  48. else {
  49. if (flatChildren.length === 1 &&
  50. !flatChildren[0].sel &&
  51. flatChildren[0].text) {
  52. // only child is a simple text node, pass as text for a simpler vtree
  53. return h(tag, data, flatChildren[0].text);
  54. }
  55. else {
  56. return h(tag, data, flatChildren);
  57. }
  58. }
  59. }
  60. (function (jsx) {
  61. })(jsx || (jsx = {}));
  62. //# sourceMappingURL=jsx.js.map