UNPKG

preact-render-to-string

Version:

Render JSX to an HTML string, with support for Preact components.

3 lines (2 loc) 9.6 kB
import{options as e,h as t,Fragment as r}from"preact";var n="__s",o="__c",i="__d",a="__s",s=/[\s\n\\/='"\0<>]/,c=/^(xlink|xmlns|xml)([A-Z])/,l=/^(?:accessK|auto[A-Z]|cell|ch|col|cont|cross|dateT|encT|form[A-Z]|frame|hrefL|inputM|maxL|minL|noV|playsI|popoverT|readO|rowS|src[A-Z]|tabI|useM|item[A-Z])/,u=/^ac|^ali|arabic|basel|cap|clipPath$|clipRule$|color|dominant|enable|fill|flood|font|glyph[^R]|horiz|image|letter|lighting|marker[^WUH]|overline|panose|pointe|paint|rendering|shape|stop|strikethrough|stroke|text[^L]|transform|underline|unicode|units|^v[^i]|^w|^xH/,p=new Set(["draggable","spellcheck"]);function f(e){void 0!==e.__g?e.__g|=8:e[i]=!0}function d(e){void 0!==e.__g?e.__g&=-9:e[i]=!1}function h(e){return void 0!==e.__g?!!(8&e.__g):!0===e[i]}var v=/["&<]/;function m(e){if(0===e.length||!1===v.test(e))return e;for(var t=0,r=0,n="",o="";r<e.length;r++){switch(e.charCodeAt(r)){case 34:o="&quot;";break;case 38:o="&amp;";break;case 60:o="&lt;";break;default:continue}r!==t&&(n+=e.slice(t,r)),n+=o,t=r+1}return r!==t&&(n+=e.slice(t,r)),n}var g={},_=new Set(["animation-iteration-count","border-image-outset","border-image-slice","border-image-width","box-flex","box-flex-group","box-ordinal-group","column-count","fill-opacity","flex","flex-grow","flex-negative","flex-order","flex-positive","flex-shrink","flood-opacity","font-weight","grid-column","grid-row","line-clamp","line-height","opacity","order","orphans","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","widows","z-index","zoom"]),y=/[A-Z]/g;function b(e){var t="";for(var r in e){var n=e[r];if(null!=n&&""!==n){var o="-"==r[0]?r:g[r]||(g[r]=r.replace(y,"-$&").toLowerCase()),i=";";"number"!=typeof n||o.startsWith("--")||_.has(o)||(i="px;"),t=t+o+":"+n+i}}return t||void 0}function x(){this.__d=!0}function k(e,t){return{__v:e,context:t,props:e.props,setState:x,forceUpdate:x,__d:!0,__h:new Array(0)}}var w,C,S,E,A=function(){var e=this;this.promise=new Promise(function(t,r){e.resolve=t,e.reject=r})},L={},P=[],j=Array.isArray,T=Object.assign,W="",D="\x3c!--$s--\x3e",N="\x3c!--/$s--\x3e";function $(e){return"string"==typeof e?D+e+N:j(e)?(e.unshift(D),e.push(N),e):e&&"function"==typeof e.then?e.then($):D+e+N}function F(o,i,a){var s=e[n];e[n]=!0,w=e.__b,C=e.diffed,S=e.__r,E=e.unmount;var c=t(r,null);c.__k=[o];try{var l=U(o,i||L,!1,void 0,c,!1,a);return j(l)?l.join(W):l}catch(e){if(e.then)throw new Error('Use "renderToStringAsync" for suspenseful rendering.');throw e}finally{e.__c&&e.__c(o,P),e[n]=s,P.length=0}}function M(e,t){var r,n=e.type,i=!0;return e[o]?(i=!1,(r=e[o]).state=r[a]):r=new n(e.props,t),e[o]=r,r.__v=e,r.props=e.props,r.context=t,f(r),null==r.state&&(r.state=L),null==r[a]&&(r[a]=r.state),n.getDerivedStateFromProps?r.state=T({},r.state,n.getDerivedStateFromProps(r.props,r.state)):i&&r.componentWillMount?(r.componentWillMount(),r.state=r[a]!==r.state?r[a]:r.state):!i&&r.componentWillUpdate&&r.componentWillUpdate(),S&&S(e),r.render(r.props,r.state,t)}function U(t,n,i,v,g,_,y){if(null==t||!0===t||!1===t||t===W)return W;var x=typeof t;if("object"!=x)return"function"==x?W:"string"==x?m(t):t+W;if(j(t)){var A,P=W;g.__k=t;for(var D=t.length,N=0;N<D;N++){var F=t[N];if(null!=F&&"boolean"!=typeof F){var H,I=U(F,n,i,v,g,_,y);"string"==typeof I?P+=I:(A||(A=new Array(D)),P&&A.push(P),P=W,j(I)?(H=A).push.apply(H,I):A.push(I))}}return A?(P&&A.push(P),A):P}if(void 0!==t.constructor)return W;t.__=g,w&&w(t);var O=t.type,z=t.props;if("function"==typeof O){var R,B,V,K=n;if(O===r){if("tpl"in z){for(var Y=W,G=0;G<z.tpl.length;G++)if(Y+=z.tpl[G],z.exprs&&G<z.exprs.length){var J=z.exprs[G];if(null==J)continue;"object"!=typeof J||void 0!==J.constructor&&!j(J)?Y+=J:Y+=U(J,n,i,v,t,_,y)}return Y}if("UNSTABLE_comment"in z)return"\x3c!--"+m(z.UNSTABLE_comment)+"--\x3e";B=z.children}else{if(null!=(R=O.contextType)){var Q=n[R.__c];K=Q?Q.props.value:R.__}var X=O.prototype&&"function"==typeof O.prototype.render;if(X)B=/**#__NOINLINE__**/M(t,K),V=t[o];else{t[o]=V=/**#__NOINLINE__**/k(t,K);for(var ee=0;h(V)&&ee++<25;){d(V),S&&S(t);try{B=O.call(V,z,K)}catch(e){throw _&&e&&"function"==typeof e.then&&(t._suspended=!0),e}}f(V)}if(null!=V.getChildContext&&(n=T({},n,V.getChildContext())),X&&e.errorBoundaries&&(O.getDerivedStateFromError||V.componentDidCatch)){B=null!=B&&B.type===r&&null==B.key&&null==B.props.tpl?B.props.children:B;try{return U(B,n,i,v,t,_,!1)}catch(e){return O.getDerivedStateFromError&&(V[a]=O.getDerivedStateFromError(e)),V.componentDidCatch&&V.componentDidCatch(e,L),h(V)?(B=M(t,n),null!=(V=t[o]).getChildContext&&(n=T({},n,V.getChildContext())),U(B=null!=B&&B.type===r&&null==B.key&&null==B.props.tpl?B.props.children:B,n,i,v,t,_,y)):W}finally{C&&C(t),E&&E(t)}}}B=null!=B&&B.type===r&&null==B.key&&null==B.props.tpl?B.props.children:B;try{var te=U(B,n,i,v,t,_,y);return C&&C(t),e.unmount&&e.unmount(t),t._suspended?$(te):te}catch(r){if(!_&&y&&y.onError){var re=function e(r){return y.onError(r,t,function(t,r){try{return U(t,n,i,v,r,_,y)}catch(t){return e(t)}})}(r);if(void 0!==re)return re;var ne=e.__e;return ne&&ne(r,t),W}if(!_)throw r;if(!r||"function"!=typeof r.then)throw r;return r.then(function e(){try{var r=U(B,n,i,v,t,_,y);return t._suspended?$(r):r}catch(t){if(!t||"function"!=typeof t.then)throw t;return t.then(e)}})}}var oe,ie="<"+O,ae=W;for(var se in z){var ce=z[se];if("function"!=typeof(ce=q(ce)?ce.value:ce)||"class"===se||"className"===se){switch(se){case"children":oe=ce;continue;case"key":case"ref":case"__self":case"__source":continue;case"htmlFor":if("for"in z)continue;se="for";break;case"className":if("class"in z)continue;se="class";break;case"defaultChecked":se="checked";break;case"defaultSelected":se="selected";break;case"defaultValue":case"value":switch(se="value",O){case"textarea":oe=ce;continue;case"select":v=ce;continue;case"option":v!=ce||"selected"in z||(ie+=" selected")}break;case"dangerouslySetInnerHTML":ae=ce&&ce.__html;continue;case"style":"object"==typeof ce&&(ce=b(ce));break;case"acceptCharset":se="accept-charset";break;case"httpEquiv":se="http-equiv";break;default:if(c.test(se))se=se.replace(c,"$1:$2").toLowerCase();else{if(s.test(se))continue;"-"!==se[4]&&!p.has(se)||null==ce?i?u.test(se)&&(se="panose1"===se?"panose-1":se.replace(/([A-Z])/g,"-$1").toLowerCase()):l.test(se)&&(se=se.toLowerCase()):ce+=W}}null!=ce&&!1!==ce&&(ie=!0===ce||ce===W?ie+" "+se:ie+" "+se+'="'+("string"==typeof ce?m(ce):ce+W)+'"')}}if(s.test(O))throw new Error(O+" is not a valid HTML tag name in "+ie+">");if(ae||("string"==typeof oe?ae=m(oe):null!=oe&&!1!==oe&&!0!==oe&&(ae=U(oe,n,"svg"===O||"foreignObject"!==O&&i,v,t,_,y))),C&&C(t),E&&E(t),!ae&&Z.has(O))return ie+"/>";var le="</"+O+">",ue=ie+">";return j(ae)?[ue].concat(ae,[le]):"string"!=typeof ae?[ue,ae,le]:ue+ae+le}var Z=new Set(["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"]);function q(e){return null!==e&&"object"==typeof e&&"function"==typeof e.peek&&"value"in e}function H(e,t){return'<preact-island hidden data-target="'+e+'">'+t+"</preact-island>"}var I=function e(t){try{var r=function(){if(t.suspended.length>0){var r=[].concat(t.suspended);return Promise.resolve(Promise.all(t.suspended.map(function(e){return e.promise}))).then(function(){return t.suspended=t.suspended.filter(function(e){return!r.includes(e)}),Promise.resolve(e(t)).then(function(){})})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},O=function(e,t){var r=t.context,n=t.onWrite,o=t.abortSignal;try{r=r||{};var i={start:Date.now(),abortSignal:o,onWrite:n,onError:z,suspended:[]},a=F(e,r,i),s=i.suspended.length,c=function(){if(s>0){var e=a.lastIndexOf("</body>"),t=a.trimStart().startsWith("<html"),r=-1!==e?a.slice(0,e):a;return n((t?"<!DOCTYPE html>":"")+r),n("<div hidden>"),n('<script>(function(){class e extends HTMLElement{connectedCallback(){var e=this;if(!e.isConnected)return;let t=this.getAttribute("data-target");if(t){for(var r,a,i=document.createNodeIterator(document,128);i.nextNode();){let e=i.referenceNode;if(e.data=="preact-island:"+t?r=e:e.data=="/preact-island:"+t&&(a=e),r&&a)break}r&&a&&r.parentNode!==document&&requestAnimationFrame((()=>{for(var t=a.previousSibling;t!=r&&t&&t!=r;)a.parentNode.removeChild(t),t=a.previousSibling;for(i=r;e.firstChild;)r=e.firstChild,e.removeChild(r),i.after(r),i=r;e.parentNode.removeChild(e)}))}}}customElements.define("preact-island",e);}())<\/script>'),Promise.resolve(I(i)).then(function(){n("</div>"),-1!==e&&n(a.slice(e))})}n(a)}();return Promise.resolve(c&&c.then?c.then(function(){}):void 0)}catch(e){return Promise.reject(e)}};function z(e,t,r){var n=this;if(e&&e.then){for(;t=t.__;){var i=t[o];if(i&&i.__c)break}if(t){var a=t.__v,s=this.suspended.find(function(e){return e.id===a}),c=new A,l=this.abortSignal;l&&(l.aborted?c.resolve():l.addEventListener("abort",c.resolve));var u=e.then(function(){if(!l||!l.aborted){var e=r(t.props.children,t);e&&n.onWrite(H(a,e))}},this.onError);this.suspended.push({id:a,vnode:t,promise:Promise.race([u,c.promise])});var p=r(t.props.fallback);return s?"":"\x3c!--preact-island:"+a+"--\x3e"+p+"\x3c!--/preact-island:"+a+"--\x3e"}}}function R(e,t){var r=new A,n=new TextEncoder("utf-8"),o=new ReadableStream({start:function(o){O(e,{context:t,onError:function(e){r.reject(e),o.abort(e)},onWrite:function(e){o.enqueue(n.encode(e))}}).then(function(){o.close(),r.resolve()}).catch(function(e){o.error(e),r.reject(e)})}});return o.allReady=r.promise,o}export{R as renderToReadableStream}; //# sourceMappingURL=index.module.js.map