UNPKG

springtype

Version:

1k TypeScript/TSX nano-framework for the web

63 lines (62 loc) 2.43 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; exports.__esModule = true; exports.tsx = void 0; // If a JSX comment is written, it looks like: { /* this */ } // Therefore, it turns into: {}, which is detected here var isJSXComment = function (node) { // istanbul ignore next return node && typeof node === 'object' && !node.attributes && !node.type && !node.children; }; // Filters comments and undefines like: ['a', 'b', false, {}] to: ['a', 'b', false] var filterComments = function (children) { return children.filter(function (child) { return !isJSXComment(child); }); }; var onUpdateFn = function (callback) { this.update = callback; }; var tsx = function ( // if it is a function, it is a component type, attributes) { var children = []; for (var _i = 2; _i < arguments.length; _i++) { children[_i - 2] = arguments[_i]; } children = filterComments( // Implementation to flatten virtual node children structures like: // [<p>1</p>, [<p>2</p>,<p>3</p>]] to: [<p>1</p>,<p>2</p>,<p>3</p>] [].concat.apply([], children)); // clone attributes as well attributes = __assign({}, attributes); // effectively unwrap by directly returning the children if (type === 'fragment') { return filterComments(children); } // it's a component, divide and conquer children if (typeof type === 'function') { if (attributes.ref) { // references an onUpdate assignment function to be called inside of the functional component // to register an "update" function that can be called from the outside (ref.current.update(state?)) attributes.ref.onUpdate = onUpdateFn.bind(attributes.ref); } return type(__assign({ children: children }, attributes)); } // @ts-ignore as type allows for Function here, but internally we wouldn't // want to deal with Function, only "string". However, in this method it is indeed possible return { type: type, attributes: attributes, children: children }; }; exports.tsx = tsx;