@fluixi/compiler 1.0.0-alpha.73 → 1.0.0-alpha.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -16
- package/dist/analyze/expr-shape.cjs +1 -0
- package/dist/analyze/expr-shape.d.ts +15 -0
- package/dist/analyze/expr-shape.d.ts.map +1 -0
- package/dist/analyze/expr-shape.js +37 -0
- package/dist/analyze/expr-shape.mjs +1 -0
- package/dist/analyze/reactive-expr.cjs +1 -0
- package/dist/analyze/reactive-expr.d.ts +39 -0
- package/dist/analyze/reactive-expr.d.ts.map +1 -0
- package/dist/analyze/reactive-expr.js +31 -0
- package/dist/analyze/reactive-expr.mjs +1 -0
- package/dist/babel-GXO3KAVI.mjs +1 -0
- package/dist/chunk-3SAEGOMQ.mjs +1 -0
- package/dist/chunk-E2PW2OZU.mjs +1 -0
- package/dist/chunk-IBRM4W7I.mjs +10 -0
- package/dist/chunk-OHHZCYIQ.mjs +1 -0
- package/dist/chunk-TIE4XNAM.mjs +1 -0
- package/dist/frontend/babel/build-ir-lit.cjs +1 -1
- package/dist/frontend/babel/build-ir-lit.d.ts +1 -0
- package/dist/frontend/babel/build-ir-lit.d.ts.map +1 -1
- package/dist/frontend/babel/build-ir-lit.mjs +1 -1
- package/dist/frontend/babel/build-ir.cjs +1 -1
- package/dist/frontend/babel/build-ir.d.ts +13 -11
- package/dist/frontend/babel/build-ir.d.ts.map +1 -1
- package/dist/frontend/babel/build-ir.js +27 -217
- package/dist/frontend/babel/build-ir.mjs +1 -1
- package/dist/frontend/babel/index.cjs +1 -2
- package/dist/frontend/babel/index.mjs +1 -2
- package/dist/frontend/babel/lower-template.cjs +1 -1
- package/dist/frontend/babel/lower-template.d.ts +12 -9
- package/dist/frontend/babel/lower-template.d.ts.map +1 -1
- package/dist/frontend/babel/lower-template.js +33 -445
- package/dist/frontend/babel/lower-template.mjs +1 -1
- package/dist/frontend/babel/plugin.cjs +1 -2
- package/dist/frontend/babel/plugin.d.ts +24 -85
- package/dist/frontend/babel/plugin.d.ts.map +1 -1
- package/dist/frontend/babel/plugin.js +52 -1285
- package/dist/frontend/babel/plugin.mjs +1 -2
- package/dist/frontend/babel/server-functions.cjs +1 -1
- package/dist/frontend/babel/server-functions.d.ts.map +1 -1
- package/dist/frontend/babel/server-functions.js +2 -9
- package/dist/frontend/babel/server-functions.mjs +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -0
- package/dist/index.mjs +9 -9
- package/dist/integrations.cjs +15 -19
- package/dist/integrations.d.ts +39 -151
- package/dist/integrations.d.ts.map +1 -1
- package/dist/integrations.js +79 -491
- package/dist/integrations.mjs +11 -17
- package/dist/lower/compile-template.cjs +1 -0
- package/dist/lower/compile-template.d.ts +57 -0
- package/dist/lower/compile-template.d.ts.map +1 -0
- package/dist/lower/compile-template.js +72 -0
- package/dist/lower/compile-template.mjs +1 -0
- package/dist/lower/jsx.cjs +1 -0
- package/dist/lower/jsx.d.ts +24 -0
- package/dist/lower/jsx.d.ts.map +1 -0
- package/dist/lower/jsx.js +193 -0
- package/dist/lower/jsx.mjs +1 -0
- package/dist/lower/template.cjs +1 -0
- package/dist/lower/template.d.ts +41 -0
- package/dist/lower/template.d.ts.map +1 -0
- package/dist/lower/template.js +445 -0
- package/dist/lower/template.mjs +1 -0
- package/dist/lower/text.cjs +1 -0
- package/dist/lower/text.d.ts +11 -0
- package/dist/lower/text.d.ts.map +1 -0
- package/dist/lower/text.js +31 -0
- package/dist/lower/text.mjs +1 -0
- package/dist/options.cjs +1 -1
- package/dist/options.d.ts +0 -2
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +0 -1
- package/dist/options.mjs +1 -1
- package/dist/server-fns-6QM243HC.mjs +2 -0
- package/dist/server-functions-E3LKCZ4R.mjs +1 -0
- package/dist/transform/bindings.cjs +1 -0
- package/dist/transform/bindings.d.ts +17 -0
- package/dist/transform/bindings.d.ts.map +1 -0
- package/dist/transform/bindings.js +69 -0
- package/dist/transform/bindings.mjs +1 -0
- package/dist/transform/index.cjs +3 -0
- package/dist/transform/index.d.ts +12 -0
- package/dist/transform/index.d.ts.map +1 -0
- package/dist/transform/index.js +10 -0
- package/dist/transform/index.mjs +12 -0
- package/dist/transform/server-fn-id.cjs +1 -0
- package/dist/transform/server-fn-id.d.ts +10 -0
- package/dist/transform/server-fn-id.d.ts.map +1 -0
- package/dist/transform/server-fn-id.js +18 -0
- package/dist/transform/server-fn-id.mjs +1 -0
- package/dist/transform/server-fns.cjs +2 -0
- package/dist/transform/server-fns.d.ts +13 -0
- package/dist/transform/server-fns.d.ts.map +1 -0
- package/dist/transform/server-fns.js +94 -0
- package/dist/transform/server-fns.mjs +11 -0
- package/dist/transform/templates.cjs +3 -0
- package/dist/transform/templates.d.ts +26 -0
- package/dist/transform/templates.d.ts.map +1 -0
- package/dist/transform/templates.js +347 -0
- package/dist/transform/templates.mjs +12 -0
- package/dist/transform-PJX2GNSV.mjs +3 -0
- package/dist/tsconfig.lib.tsbuildinfo +1 -1
- package/package.json +30 -8
- package/dist/babel-E7EQLX36.mjs +0 -2
- package/dist/chunk-EF6V4GTD.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{types as w}from"@babel/core";import te from"@babel/generator";import{parseTemplate as _e}from"@fluixi/template-parser";var se={kind:"eager"},oe=["pointerdown","focusin","keydown"],O=new Set(["eager","idle","visible","interaction","media","never"]),f=class extends Error{};function T(t){return t.startsWith("load:")}function S(t,e){let n=t.slice(5);if(!O.has(n))throw new f(`Unknown load strategy 'load:${n}'. Expected one of ${[...O].join(", ")}.`);switch(n){case"eager":return se;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return e?{kind:"visible",rootMargin:e}:{kind:"visible"};case"interaction":return{kind:"interaction",events:e?ae(e):[...oe]};case"media":if(!e)throw new f(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:e};default:throw new f(`Unhandled load strategy '${n}'.`)}}function ae(t){let e=t.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new f("'load:interaction' was given no event names.");return e}var le=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),_={className:"class",htmlFor:"for"},ce=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),pe=new Set(["script","style","textarea","title"]);function C(t){return pe.has(t)}function M(t){return _[t]??t}function v(t){return t.kind!=="attr"||t.expr!==void 0||t.name.includes(":")?!1:!ce.has(t.name)}function A(t){if(!t.static||C(t.tag))return!1;for(let e of t.props)if(!v(e))return!1;for(let e of t.children)if(e.kind!=="text"&&!(e.kind==="element"&&A(e)))return!1;return!0}function x(t){let e=t.props.map(de).filter(Boolean).join(""),n=`<${t.tag}${e}>`;return le.has(t.tag)?n:`${n}${t.children.map(ue).join("")}</${t.tag}>`}function ue(t){if(t.kind==="text")return fe(t.value);if(t.kind!=="element")throw new Error(`serializeStatic: unexpected ${t.kind}`);return x(t)}function de(t){let e=_[t.name]??t.name,n=t.literal;return n===!0||n===void 0?` ${e}`:n===!1||n===null?"":` ${e}="${me(String(n))}"`}function me(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function fe(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var he="<!--fx-->",ge="<!--fx/-->";function y(t){return t.kind==="expr"||t.kind==="component"||t.kind==="control"}function ve(t){return t.kind==="text"||t.kind==="element"&&B(t)}function B(t){return t.svg||C(t.tag)||!t.props.every(e=>v(e))?!1:t.children.every(e=>ve(e)||y(e))}function b(t){if(y(t))return!0;let e=t.children;return e?e.some(b):!1}function H(t){for(let e=0;e<t.children.length;e++){let n=t.children[e];if(n.kind==="text"&&(n.value===""||t.children[e+1]?.kind==="text"))return!1}return t.children.every(e=>e.kind!=="element"||H(e))}function F(t){if(!B(t)||!H(t)||!t.children.some(b))return null;let e=[],n=[],r=0,i=a=>{let s=`_n$${r++}`;return e.push({ref:s,expr:a}),s};return o(t,"_el$"),{html:xe(t),tag:t.tag,steps:e,holes:n};function o(a,s){let l=-1;a.children.forEach((u,d)=>{b(u)&&(l=d)});let c=null;for(let u=0;u<=l;u++){let d=a.children[u],g=c?`${c}.nextSibling`:`${s}.firstChild`;if(y(d)){let D=i(g),j=i(`holeEnd(${D})`);n.push({parentRef:s,startRef:D,endRef:j,node:d}),c=j;continue}let N=i(g);d.kind==="element"&&b(d)&&o(d,N),c=N}}}function xe(t){return x(z(t)).split(V).join(he+ge)}function z(t){return{...t,children:t.children.map(e=>y(e)?{kind:"text",value:V}:e.kind==="element"?z(e):e)}}var V="\0fx-hole\0";var P={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},Ge={version:2,module:"@fluixi/dom",symbols:[...P.symbols,"template","cloneTemplate","walk"]};var ke={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function Ee(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function U(t){return Ee(t)?t:JSON.stringify(t)}function Re(t){return t.expr!==void 0?t.reactive?`() => (${t.expr})`:`(${t.expr})`:JSON.stringify(t.literal??!0)}function Ne(t){return t.expr!==void 0?`(${t.expr})`:JSON.stringify(t.literal??!0)}function Se(t,e,n){let r=t.filter(s=>s.kind==="spread"),o=t.filter(s=>s.kind!=="spread").map(s=>`${U(s.name)}: ${Re(s)}`);e!=null&&o.push(`children: ${e}`);let a=`{ ${o.join(", ")} }`;return r.length>0?(n.add("mergeProps"),`mergeProps(${r.map(s=>s.expr).join(", ")}, ${a})`):a}function G(t,e,n){return t.length===1?k(t[0],e,n):`[${t.map(r=>k(r,e,n)).join(", ")}]`}function W(t,e,n,r,i){r.add("createMemo"),r.add("createComponent");let o=e.filter(c=>c.kind==="spread"),s=e.filter(c=>c.kind!=="spread").map(c=>`get ${U(c.name)}() { return ${Ne(c)}; }`);n.length>0&&s.push(`get children() { return ${G(n,r,i)}; }`);let l=`{ ${s.join(", ")} }`;return o.length>0&&(r.add("mergeProps"),l=`mergeProps(${o.map(c=>c.expr).join(", ")}, ${l})`),`createMemo(() => createComponent(${t}, ${l}))`}function be(t,e){let n=M(e.name),r=e.literal;return r===!0||r===void 0?`${t}.setAttribute(${JSON.stringify(n)}, "");`:r===!1||r===null?"":`${t}.setAttribute(${JSON.stringify(n)}, ${JSON.stringify(String(r))});`}var K=!1;function k(t,e,n){switch(t.kind){case"text":return JSON.stringify(t.value);case"expr":return t.reactive?`() => (${t.code})`:`(${t.code})`;case"fragment":return t.children.length===0?"null":G(t.children,e,n);case"component":return W(t.name,t.props,t.children,e,n);case"control":{let r=ke[t.control]??t.control;return e.add(r),W(r,t.props,t.children,e,n)}case"element":{if(n&&t.static&&!t.svg&&A(t)){e.add("templateNode");let s=`_tmpl$${n.length}`;return n.push({id:s,html:x(t),tag:t.tag,svg:!1}),`templateNode(${s}, ${JSON.stringify(t.tag)})`}if(n&&K){let s=F(t);if(s){e.add("templateNode"),e.add("insert"),e.add("holeEnd"),e.add("holeContent"),e.add("holeScope");let l=`_tmpl$${n.length}`;n.push({id:l,html:s.html,tag:s.tag,svg:!1});let c=[`const _el$ = templateNode(${l}, ${JSON.stringify(s.tag)}, true);`];for(let u of s.steps)c.push(`const ${u.ref} = ${u.expr};`);for(let u of s.holes)c.push(`insert(${u.parentRef}, holeScope(${u.startRef}, () => (${k(u.node,e,n)})), ${u.endRef}, holeContent(${u.startRef}, ${u.endRef}));`);return c.push("return _el$;"),`(() => { ${c.join(" ")} })()`}}e.add("createNativeElement");let r=JSON.stringify(t.tag),i="_el$",o=[],a=t.svg?`${r}, true`:r;if(o.push(`const ${i} = createNativeElement(${a});`),t.props.length>0)if(!t.svg&&t.props.every(v))for(let s of t.props)o.push(be(i,s));else{e.add("spread");let s=t.svg?", isSVG: true":"";o.push(`spread({ element: ${i}, props: ${Se(t.props,null,e)}${s} });`)}for(let s of t.children){e.add("insert");let l=k(s,e,n),c=s.kind==="expr"&&s.reactive||s.kind==="component"||s.kind==="control";o.push(c?`insert(${i}, ${l}, null);`:`insert(${i}, ${l});`)}return o.push(`return ${i};`),`(() => { ${o.join(" ")} })()`}}}function E(t,e){if(!e||e.length===0)return t;let n=new Map(e.map(r=>[r.id,JSON.stringify(r.html)]));return t.replace(/_tmpl\$\d+/g,r=>n.get(r)??r)}var R={name:"imperative",contract:P,emit(t,e){let n=new Set,r=e?.templateClone!==!1?[]:void 0;return K=e?.partialTemplates===!0,{code:k(t,n,r),imports:Array.from(n),templates:r}}};import{types as p,traverse as $e,template as we}from"@babel/core";import q from"@babel/generator";function ye(t){switch(t.kind){case"event":return"event";case"ref":return"ref";case"spread":return"spread";case"class":case"style":return"class-or-style-directive";case"attr":case"prop":return t.reactive?"reactive-prop":t.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function I(t){let e=[],n=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let o of i.children)r(o);return!1;case"fragment":for(let o of i.children)r(o);return!1;case"element":{let o=!0;for(let s of i.children)r(s)||(o=!1);let a;for(let s of i.props)if(a=ye(s),a)break;return!a&&!o&&(a=Ie(i)),i.static=!a,a?n.set(i,a):e.push(i),i.static}default:return!1}};for(let i of Array.isArray(t)?t:[t])r(i);return{staticElements:e,reasons:n}}function Ie(t){for(let e of t.children){if(e.kind==="expr")return"expression-child";if(e.kind==="component")return"component-child";if(e.kind==="control")return"control-child";if(e.kind==="element"&&!e.static||e.kind==="fragment")return"expression-child"}return"expression-child"}var Te=q.default??q;function Q(t){return Te(t,{concise:!0}).code}function Ce(t,e){let n=p.cloneNode(t,!0),r=p.file(p.program([p.expressionStatement(n)])),i=!1,o=(a,s,l)=>{for(let c of l)e.add(c);a.replaceWith(we.expression(s,{placeholderPattern:!1,plugins:["typescript"]})()),a.skip(),i=!0};return $e(r,{"JSXElement|JSXFragment"(a){let s=a.node,{code:l,imports:c,templates:u}=R.emit(je(s,e),{});o(a,E(l,u),c)},TaggedTemplateExpression(a){let s=a.node.tag;if(!p.isIdentifier(s)||s.name!=="html"&&s.name!=="svg")return;let l=ee(a.node,e,{svg:s.name==="svg"}),{code:c,imports:u,templates:d}=R.emit(l,{});o(a,E(c,d),u)}}),i?r.program.body[0].expression:t}function h(t,e){return Q(Ce(t,e))}var Ae=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),Pe=/^on[A-Z]/,Je=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Le(t){if(p.isJSXIdentifier(t)){let e=t.name[0]!==t.name[0].toLowerCase();return{tag:t.name,component:e}}return p.isJSXMemberExpression(t)?{tag:Q(t),component:!0}:p.isJSXNamespacedName(t)?{tag:`${t.namespace.name}:${t.name.name}`,component:!1}:{tag:"div",component:!1}}function L(t){return p.isJSXIdentifier(t)?t.name==="class"?"className":t.name:p.isJSXNamespacedName(t)?`${t.namespace.name}:${t.name.name}`:"unknown"}function m(t){return p.isCallExpression(t)||p.isOptionalCallExpression(t)?!0:p.isMemberExpression(t)||p.isOptionalMemberExpression(t)?!(!t.computed&&p.isIdentifier(t.property,{name:"children"})):p.isConditionalExpression(t)?m(t.test)||m(t.consequent)||m(t.alternate):p.isLogicalExpression(t)||p.isBinaryExpression(t)?m(t.left)||m(t.right):p.isTemplateLiteral(t)?t.expressions.some(e=>m(e)):p.isObjectExpression(t)?t.properties.some(e=>p.isObjectProperty(e)&&!e.computed&&m(e.value)):p.isArrayExpression(t)?t.elements.some(e=>e!=null&&!p.isSpreadElement(e)&&m(e)):!1}function Xe(t,e){let n=L(t.name),r=Pe.test(n),i=r||n.startsWith("on:")||n==="ref",a={name:n,kind:r?"event":"attr"};r&&(a.event={name:n.slice(2).toLowerCase(),delegated:Je.has(n.slice(2).toLowerCase())});let s=t.value;if(s==null)return a.literal=!0,a;if(p.isStringLiteral(s))return a.literal=s.value,a;if(p.isJSXExpressionContainer(s)&&!p.isJSXEmptyExpression(s.expression)){let l=s.expression;return p.isStringLiteral(l)||p.isNumericLiteral(l)||p.isBooleanLiteral(l)?(a.literal=l.value,a):(a.expr=h(l,e),a.reactive=i?!1:m(l),(p.isJSXElement(l)||p.isJSXFragment(l))&&(a.jsxElement=!0),a)}return a.literal=!0,a}function Z(t,e){let n=t.value;return n==null?null:p.isStringLiteral(n)?JSON.stringify(n.value):p.isJSXExpressionContainer(n)&&!p.isJSXEmptyExpression(n.expression)?h(n.expression,e):null}function De(t,e){let n=[],r=[];for(let i of t){if(p.isJSXSpreadAttribute(i)){n.push({name:"",kind:"spread",expr:h(i.argument,e)});continue}if(!p.isJSXAttribute(i)||T(L(i.name)))continue;let o=p.isJSXNamespacedName(i.name)?i.name.namespace.name:null;if(o==="use"){let a=i.name.name.name;e.add(a);let s=Z(i,e);r.push(s!=null?`[${a}, () => (${s})]`:`[${a}]`);continue}if(o==="oncapture"){let a=i.name.name.name.toLowerCase(),s=Z(i,e)??"undefined";n.push({name:"on:"+a,kind:"attr",expr:`[${s}, { capture: true }]`});continue}n.push(Xe(i,e))}return r.length>0&&n.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),n}function $(t){let e=t.split(/\r\n|\n|\r/),n=0;for(let i=0;i<e.length;i++)/[^ \t]/.test(e[i])&&(n=i);let r="";for(let i=0;i<e.length;i++){let o=e[i].replace(/\t/g," ");i!==0&&(o=o.replace(/^ +/,"")),i!==e.length-1&&(o=o.replace(/ +$/,"")),o&&(i!==n&&(o+=" "),r+=o)}return r}function Y(t,e){let n=[];for(let r of t)if(p.isJSXText(r)){let i=$(r.value);i&&n.push({kind:"text",value:i})}else if(p.isJSXExpressionContainer(r)){if(!p.isJSXEmptyExpression(r.expression)){let i=r.expression;n.push({kind:"expr",code:h(i,e),reactive:m(i)})}}else p.isJSXElement(r)||p.isJSXFragment(r)?n.push(J(r,e)):p.isJSXSpreadChild(r)&&n.push({kind:"expr",code:h(r.expression,e),reactive:!1});return n}function je(t,e=new Set){let n=J(t,e);return I(n),n}function J(t,e){if(p.isJSXFragment(t))return{kind:"fragment",children:Y(t.children,e)};let{tag:n,component:r}=Le(t.openingElement.name),i=De(t.openingElement.attributes,e),o=Y(t.children,e);if(r){let a=Oe(t.openingElement.attributes);return{kind:"component",name:n,props:i,children:o,...a?{load:a}:{}}}return{kind:"element",tag:n,svg:Ae.has(n),props:i,children:o,static:!1}}function Oe(t){for(let e of t){if(!p.isJSXAttribute(e))continue;let n=L(e.name);if(T(n)){if(e.value&&!p.isStringLiteral(e.value))throw new f(`'${n}' needs a literal value, not an expression — the strategy is compile-time.`);return S(n,e.value?e.value.value:null)}}}var Me=te.default??te;function Be(t){return Me(t,{concise:!0}).code}var ne=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function He(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function re(t){return t.charAt(0).toUpperCase()+t.slice(1)}var X=class{constructor(e,n){this.holes=e;this.used=n}hole(e){return this.holes[e]??{node:w.identifier("undefined"),code:"undefined",reactive:!1}}emit(e){let{code:n,imports:r,templates:i}=R.emit(e,{});for(let o of r)this.used.add(o);return E(n,i)}lowerRoot(e){let n=this.lowerChildren(e);return n.length===1?n[0]:{kind:"fragment",children:n}}lowerChildren(e){let n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.kind==="Element"||i.kind==="Component"){let a=i.attributes.find(s=>s.kind==="IfDirective");if(a&&a.kind==="IfDirective"){let s=r+1;s<e.length&&this.isBlankText(e[s])&&s++;let l=e[s],c=l&&(l.kind==="Element"||l.kind==="Component")&&l.attributes.some(u=>u.kind==="ElseDirective");n.push(this.lowerIf(i,a.hole,c?l:null)),c&&(r=s);continue}if(i.attributes.some(s=>s.kind==="EachDirective")){n.push(this.lowerEach(i));continue}}let o=this.lowerNode(i);o&&n.push(o)}return n}isBlankText(e){return e.kind==="Text"&&!e.raw&&$(e.value)===""}lowerNode(e){switch(e.kind){case"Text":{if(e.raw)return{kind:"text",value:e.value};let n=$(e.value);return n?{kind:"text",value:n}:null}case"Comment":return null;case"Expression":{let n=this.hole(e.hole);return{kind:"expr",code:n.code,reactive:n.reactive}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(e.children)};case"Element":return this.lowerElement(e);case"Component":return this.lowerComponent(e);default:return null}}lowerElement(e){let n=e.attributes.find(r=>r.kind==="Attribute"&&r.name==="is");if(e.tag==="component"&&n&&n.value&&n.value.kind==="hole"){let r=e.attributes.filter(o=>o!==n),i=this.lowerComponent({...e,kind:"Component",tag:"Dynamic",tagHole:null,attributes:r});return i.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(n.value.hole).code})`}),i}return{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:this.lowerAttributes(e.attributes),children:this.lowerChildren(e.children),static:!1}}lowerComponent(e){let n=e.tagHole!=null?this.hole(e.tagHole).code:e.tag,r=this.lowerAttributes(e.attributes),{slots:i,rest:o}=this.partitionSlots(e.children);for(let[l,c]of i){let u=c.length===1?c[0]:{kind:"fragment",children:c},d={name:l,kind:"attr",expr:this.emit(u),jsxElement:!0},g=r.findIndex(N=>N.name===l);g>=0?r[g]=d:r.push(d)}let a=e.attributes.find(l=>l.kind==="LoadDirective"),s=a?S(`load:${a.strategy}`,a.modifier):void 0;return{kind:"component",name:n,props:r,children:this.lowerChildren(o),...s?{load:s}:{}}}partitionSlots(e){let n=new Map,r=[];for(let i of e){if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(a=>a.kind==="Attribute"&&a.name==="slot");if(o&&o.value&&o.value.kind==="static"){let a={...i,attributes:i.attributes.filter(c=>c!==o)},s=a.kind==="Element"?this.lowerElement(a):this.lowerComponent(a),l=n.get(o.value.value)??[];l.push(s),n.set(o.value.value,l);continue}}r.push(i)}return{slots:n,rest:r}}lowerIf(e,n,r){let i=this.hole(n),o=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive}];if(r){let s=this.stripAndLower(r,l=>l.kind==="ElseDirective");o.push({name:"fallback",kind:"attr",expr:this.emit(s),jsxElement:!0})}let a=this.stripAndLower(e,s=>s.kind==="IfDirective");return{kind:"component",name:"Show",props:o,children:[a]}}lowerEach(e){let n=e.attributes.find(l=>l.kind==="EachDirective");if(!n||n.kind!=="EachDirective")return this.lowerNode(e);let r=this.hole(n.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive}];if(n.key){let l="static"in n.key?`(item) => item[${JSON.stringify(n.key.static)}]`:this.hole(n.key.hole).code;i.push({name:"by",kind:"attr",expr:l})}let o=this.itemArrow(e),a;if(o){let l=o.body,c={kind:"expr",code:h(l,this.used),reactive:m(l)},u=this.rebuildWithChildren(e,[c]);a=`(${o.params.map(d=>Be(d)).join(", ")}) => (${this.emit(u)})`}else{let l=this.stripAndLower(e,c=>c.kind==="EachDirective");a=`() => (${this.emit(l)})`}return{kind:"component",name:"For",props:i,children:[{kind:"expr",code:a,reactive:!1}]}}itemArrow(e){let n=e.children.filter(i=>!this.isBlankText(i));if(n.length!==1||n[0].kind!=="Expression")return null;let r=this.hole(n[0].hole).node;return w.isArrowFunctionExpression(r)&&!w.isBlockStatement(r.body)?r:null}stripAndLower(e,n){let r={...e,attributes:e.attributes.filter(i=>!n(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(e,n){let r=this.lowerAttributes(e.attributes.filter(i=>i.kind!=="EachDirective"));return e.kind==="Element"?{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:r,children:n,static:!1}:{kind:"component",name:e.tag,props:r,children:n}}lowerAttributes(e){let n=[],r=[],i=!1,o=[],a=!1,s=[];for(let l of e)switch(l.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":n.push(this.plainAttr(l));break;case"PropertyBinding":n.push({name:l.name,kind:"prop",expr:this.hole(l.hole).code,reactive:this.hole(l.hole).reactive});break;case"EventBinding":n.push(this.eventProp(l));break;case"RefBinding":n.push({name:"ref",kind:"ref",expr:this.hole(l.hole).code,reactive:this.hole(l.hole).reactive});break;case"Spread":n.push({name:"",kind:"spread",expr:this.hole(l.hole).code});break;case"ClassDirective":{let c=this.hole(l.hole);r.push(`${JSON.stringify(l.name)}: ${c.code}`),i=i||c.reactive;break}case"StyleDirective":{let c=this.hole(l.hole);o.push(`${JSON.stringify(l.name)}: ${c.code}`),a=a||c.reactive;break}case"BindDirective":n.push(...this.bindProps(l.name,this.hole(l.hole).code));break;case"UseDirective":{let c=l.name??(l.hole!=null?this.hole(l.hole).code:null);if(!c)break;s.push(l.name!=null&&l.hole!=null?`[${c}, () => (${this.hole(l.hole).code})]`:`[${c}]`);break}}return r.length>0&&n.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i}),o.length>0&&n.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:a}),s.length>0&&n.push({name:"use",kind:"attr",expr:`[${s.join(", ")}]`}),n}eventProp(e){let n=e.name.toLowerCase(),r=this.hole(e.hole).code;if(!(e.syntax==="colon"||e.modifiers.length>0))return{name:"on"+re(e.name),kind:"event",event:{name:n,delegated:ne.has(n)},expr:r};let o=this.wrapHandler(r,e.modifiers),a=this.eventOptions(e.modifiers),s=a?`[${o}, ${a}]`:o;return{name:"on:"+n,kind:"attr",expr:s}}wrapHandler(e,n){let r=n.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return n.includes("prevent")&&i.push("e.preventDefault();"),n.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?e:`(e) => { ${r}${i.join(" ")} return (${e})(e); }`}eventOptions(e){let n=[];return e.includes("capture")&&n.push("capture: true"),e.includes("once")&&n.push("once: true"),e.includes("passive")&&n.push("passive: true"),n.length?`{ ${n.join(", ")} }`:null}bindProps(e,n){let r=e==="checked",i=r?"change":"input",o=r?"checked":"value",a=`(${n})`;return[{name:e,kind:"attr",expr:`${a}[0]()`,reactive:!0},{name:"on"+re(i),kind:"event",event:{name:i,delegated:ne.has(i)},expr:`(e) => ${a}[1](e.target.${o})`}]}plainAttr(e){let n=e.value,r=e.name;e.name==="class"?r=n&&n.kind==="hole"&&w.isObjectExpression(this.hole(n.hole).node)?"classList":"className":e.name==="html"&&(r="innerHTML");let o={name:r,kind:"attr"};if(n==null)return o.literal=!0,o;if(n.kind==="static")return o.literal=n.value,o;if(n.kind==="hole"){let l=this.hole(n.hole);return o.expr=l.code,o.reactive=l.reactive,o}let a=!1,s=n.parts.map(l=>{if("text"in l)return He(l.text);let c=this.hole(l.hole);return a=a||c.reactive,"${"+c.code+"}"}).join("");return o.expr="`"+s+"`",o.reactive=a,o}};function ie(t,e,n={}){let r=t.quasi,i=r.expressions.map(s=>{let l=s;return{node:l,code:h(l,e),reactive:m(l)}}),o=Fe(r),{root:a}=_e(o,{svg:n.svg});return new X(i,e).lowerRoot(a.children)}function Fe(t){let e=[];return t.quasis.forEach((n,r)=>{let i=n.value.cooked??n.value.raw;if(e.push({kind:"static",text:i,start:n.start??0}),r<t.expressions.length){let o=t.expressions[r];e.push({kind:"hole",index:r,start:o.start??0,end:o.end??0})}}),e}function ee(t,e=new Set,n={}){let r=ie(t,e,n);return I(r),r}export{ee as buildIRFromLit};
|
|
1
|
+
import{types as M}from"@babel/core";import de from"@babel/generator";import{parseTemplate as Je}from"@fluixi/template-parser";var me={kind:"eager"},fe=["pointerdown","focusin","keydown"],B=new Set(["eager","idle","visible","interaction","media","never"]),m=class extends Error{};function P(e){return e.startsWith("load:")}function I(e,t){let n=e.slice(5);if(!B.has(n))throw new m(`Unknown load strategy 'load:${n}'. Expected one of ${[...B].join(", ")}.`);switch(n){case"eager":return me;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return t?{kind:"visible",rootMargin:t}:{kind:"visible"};case"interaction":return{kind:"interaction",events:t?he(t):[...fe]};case"media":if(!t)throw new m(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:t};default:throw new m(`Unhandled load strategy '${n}'.`)}}function he(e){let t=e.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new m("'load:interaction' was given no event names.");return t}var ge=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),F={className:"class",htmlFor:"for"},ve=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),ke=new Set(["script","style","textarea","title"]);function A(e){return ke.has(e)}function z(e){return F[e]??e}function f(e){return e.kind!=="attr"||e.expr!==void 0||e.name.includes(":")?!1:!ve.has(e.name)}function J(e){if(!e.static||A(e.tag))return!1;for(let t of e.props)if(!f(t))return!1;for(let t of e.children)if(t.kind!=="text"&&!(t.kind==="element"&&J(t)))return!1;return!0}function h(e){let t=e.props.map(ye).filter(Boolean).join(""),n=`<${e.tag}${t}>`;return ge.has(e.tag)?n:`${n}${e.children.map(xe).join("")}</${e.tag}>`}function xe(e){if(e.kind==="text")return Ee(e.value);if(e.kind!=="element")throw new Error(`serializeStatic: unexpected ${e.kind}`);return h(e)}function ye(e){let t=F[e.name]??e.name,n=e.literal;return n===!0||n===void 0?` ${t}`:n===!1||n===null?"":` ${t}="${Ne(String(n))}"`}function Ne(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ee(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var Re="<!--fx-->",be="<!--fx/-->";function w(e){return e.kind==="expr"||e.kind==="component"||e.kind==="control"}function Se(e){return e.kind==="text"||e.kind==="element"&&V(e)}function V(e){return e.svg||A(e.tag)||!e.props.every(t=>f(t))?!1:e.children.every(t=>Se(t)||w(t))}function $(e){if(w(e))return!0;let t=e.children;return t?t.some($):!1}function G(e){for(let t=0;t<e.children.length;t++){let n=e.children[t];if(n.kind==="text"&&(n.value===""||e.children[t+1]?.kind==="text"))return!1}return e.children.every(t=>t.kind!=="element"||G(t))}function W(e){if(!V(e)||!G(e)||!e.children.some($))return null;let t=[],n=[],r=0,i=l=>{let s=`_n$${r++}`;return t.push({ref:s,expr:l}),s};return o(e,"_el$"),{html:Ie(e),tag:e.tag,steps:t,holes:n};function o(l,s){let a=-1;l.children.forEach((p,d)=>{$(p)&&(a=d)});let c=null;for(let p=0;p<=a;p++){let d=l.children[p],u=c?`${c}.nextSibling`:`${s}.firstChild`;if(w(d)){let H=i(u),_=i(`holeEnd(${H})`);n.push({parentRef:s,startRef:H,endRef:_,node:d}),c=_;continue}let S=i(u);d.kind==="element"&&$(d)&&o(d,S),c=S}}}function Ie(e){return h(q(e)).split(U).join(Re+be)}function q(e){return{...e,children:e.children.map(t=>w(t)?{kind:"text",value:U}:t.kind==="element"?q(t):t)}}var U="\0fx-hole\0";var L={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},st={version:2,module:"@fluixi/dom",symbols:[...L.symbols,"template","cloneTemplate","walk"]};var $e={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function we(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function Z(e){return we(e)?e:JSON.stringify(e)}function Te(e){return e.expr!==void 0?e.reactive?`() => (${e.expr})`:`(${e.expr})`:JSON.stringify(e.literal??!0)}function Ce(e){return e.expr!==void 0?`(${e.expr})`:JSON.stringify(e.literal??!0)}function Pe(e,t,n){let r=e.filter(s=>s.kind==="spread"),o=e.filter(s=>s.kind!=="spread").map(s=>`${Z(s.name)}: ${Te(s)}`);t!=null&&o.push(`children: ${t}`);let l=`{ ${o.join(", ")} }`;return r.length>0?(n.add("mergeProps"),`mergeProps(${r.map(s=>s.expr).join(", ")}, ${l})`):l}function Y(e,t,n){return e.length===1?g(e[0],t,n):`[${e.map(r=>g(r,t,n)).join(", ")}]`}function K(e,t,n,r,i){r.add("createMemo"),r.add("createComponent");let o=t.filter(c=>c.kind==="spread"),s=t.filter(c=>c.kind!=="spread").map(c=>`get ${Z(c.name)}() { return ${Ce(c)}; }`);n.length>0&&s.push(`get children() { return ${Y(n,r,i)}; }`);let a=`{ ${s.join(", ")} }`;return o.length>0&&(r.add("mergeProps"),a=`mergeProps(${o.map(c=>c.expr).join(", ")}, ${a})`),`createMemo(() => createComponent(${e}, ${a}))`}function Ae(e,t){let n=z(t.name),r=t.literal;return r===!0||r===void 0?`${e}.setAttribute(${JSON.stringify(n)}, "");`:r===!1||r===null?"":`${e}.setAttribute(${JSON.stringify(n)}, ${JSON.stringify(String(r))});`}var Q=!1;function g(e,t,n){switch(e.kind){case"text":return JSON.stringify(e.value);case"expr":return e.reactive?`() => (${e.code})`:`(${e.code})`;case"fragment":return e.children.length===0?"null":Y(e.children,t,n);case"component":return K(e.name,e.props,e.children,t,n);case"control":{let r=$e[e.control]??e.control;return t.add(r),K(r,e.props,e.children,t,n)}case"element":{if(n&&e.static&&!e.svg&&J(e)){t.add("templateNode");let s=`_tmpl$${n.length}`;return n.push({id:s,html:h(e),tag:e.tag,svg:!1}),`templateNode(${s}, ${JSON.stringify(e.tag)})`}if(n&&Q){let s=W(e);if(s){t.add("templateNode"),t.add("insert"),t.add("holeEnd"),t.add("holeContent"),t.add("holeScope");let a=`_tmpl$${n.length}`;n.push({id:a,html:s.html,tag:s.tag,svg:!1});let c=[`const _el$ = templateNode(${a}, ${JSON.stringify(s.tag)}, true);`];for(let p of s.steps)c.push(`const ${p.ref} = ${p.expr};`);for(let p of s.holes)c.push(`insert(${p.parentRef}, holeScope(${p.startRef}, () => (${g(p.node,t,n)})), ${p.endRef}, holeContent(${p.startRef}, ${p.endRef}));`);return c.push("return _el$;"),`(() => { ${c.join(" ")} })()`}}t.add("createNativeElement");let r=JSON.stringify(e.tag),i="_el$",o=[],l=e.svg?`${r}, true`:r;if(o.push(`const ${i} = createNativeElement(${l});`),e.props.length>0)if(!e.svg&&e.props.every(f))for(let s of e.props)o.push(Ae(i,s));else{t.add("spread");let s=e.svg?", isSVG: true":"";o.push(`spread({ element: ${i}, props: ${Pe(e.props,null,t)}${s} });`)}for(let s of e.children){t.add("insert");let a=g(s,t,n),c=s.kind==="expr"&&s.reactive||s.kind==="component"||s.kind==="control";o.push(c?`insert(${i}, ${a}, null);`:`insert(${i}, ${a});`)}return o.push(`return ${i};`),`(() => { ${o.join(" ")} })()`}}}function v(e,t){if(!t||t.length===0)return e;let n=new Map(t.map(r=>[r.id,JSON.stringify(r.html)]));return e.replace(/_tmpl\$\d+/g,r=>n.get(r)??r)}var k={name:"imperative",contract:L,emit(e,t){let n=new Set,r=t?.templateClone!==!1?[]:void 0;return Q=t?.partialTemplates===!0,{code:g(e,n,r),imports:Array.from(n),templates:r}}};function x(e){let t=e.split(/\r\n|\n|\r/),n=0;for(let i=0;i<t.length;i++)/[^ \t]/.test(t[i])&&(n=i);let r="";for(let i=0;i<t.length;i++){let o=t[i].replace(/\t/g," ");i!==0&&(o=o.replace(/^ +/,"")),i!==t.length-1&&(o=o.replace(/ +$/,"")),o&&(i!==n&&(o+=" "),r+=o)}return r}var ee=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Le(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function te(e){return e.charAt(0).toUpperCase()+e.slice(1)}var D=class{constructor(t,n){this.holes=t;this.used=n}hole(t){return this.holes[t]??{code:"undefined",reactive:!1}}emit(t){let{code:n,imports:r,templates:i}=k.emit(t,{});for(let o of r)this.used.add(o);return v(n,i)}lowerRoot(t){let n=this.lowerChildren(t);return n.length===1?n[0]:{kind:"fragment",children:n}}lowerChildren(t){let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(i.kind==="Element"||i.kind==="Component"){let l=i.attributes.find(s=>s.kind==="IfDirective");if(l&&l.kind==="IfDirective"){let s=r+1;s<t.length&&this.isBlankText(t[s])&&s++;let a=t[s],c=a&&(a.kind==="Element"||a.kind==="Component")&&a.attributes.some(p=>p.kind==="ElseDirective");n.push(this.lowerIf(i,l.hole,c?a:null)),c&&(r=s);continue}if(i.attributes.some(s=>s.kind==="EachDirective")){n.push(this.lowerEach(i));continue}}let o=this.lowerNode(i);o&&n.push(o)}return n}isBlankText(t){return t.kind==="Text"&&!t.raw&&x(t.value)===""}lowerNode(t){switch(t.kind){case"Text":{if(t.raw)return{kind:"text",value:t.value};let n=x(t.value);return n?{kind:"text",value:n}:null}case"Comment":return null;case"Expression":{let n=this.hole(t.hole);return{kind:"expr",code:n.code,reactive:n.reactive}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(t.children)};case"Element":return this.lowerElement(t);case"Component":return this.lowerComponent(t);default:return null}}lowerElement(t){let n=t.attributes.find(r=>r.kind==="Attribute"&&r.name==="is");if(t.tag==="component"&&n&&n.value&&n.value.kind==="hole"){let r=t.attributes.filter(o=>o!==n),i=this.lowerComponent({...t,kind:"Component",tag:"Dynamic",tagHole:null,attributes:r});return i.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(n.value.hole).code})`}),i}return{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:this.lowerAttributes(t.attributes),children:this.lowerChildren(t.children),static:!1}}lowerComponent(t){let n=t.tagHole!=null?this.hole(t.tagHole).code:t.tag,r=this.lowerAttributes(t.attributes),{slots:i,rest:o}=this.partitionSlots(t.children);for(let[a,c]of i){let p=c.length===1?c[0]:{kind:"fragment",children:c},d={name:a,kind:"attr",expr:this.emit(p),jsxElement:!0},u=r.findIndex(S=>S.name===a);u>=0?r[u]=d:r.push(d)}let l=t.attributes.find(a=>a.kind==="LoadDirective"),s=l?I(`load:${l.strategy}`,l.modifier):void 0;return{kind:"component",name:n,props:r,children:this.lowerChildren(o),...s?{load:s}:{}}}partitionSlots(t){let n=new Map,r=[];for(let i of t){if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(l=>l.kind==="Attribute"&&l.name==="slot");if(o&&o.value&&o.value.kind==="static"){let l={...i,attributes:i.attributes.filter(c=>c!==o)},s=l.kind==="Element"?this.lowerElement(l):this.lowerComponent(l),a=n.get(o.value.value)??[];a.push(s),n.set(o.value.value,a);continue}}r.push(i)}return{slots:n,rest:r}}lowerIf(t,n,r){let i=this.hole(n),o=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive}];if(r){let s=this.stripAndLower(r,a=>a.kind==="ElseDirective");o.push({name:"fallback",kind:"attr",expr:this.emit(s),jsxElement:!0})}let l=this.stripAndLower(t,s=>s.kind==="IfDirective");return{kind:"component",name:"Show",props:o,children:[l]}}lowerEach(t){let n=t.attributes.find(a=>a.kind==="EachDirective");if(!n||n.kind!=="EachDirective")return this.lowerNode(t);let r=this.hole(n.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive}];if(n.key){let a="static"in n.key?`(item) => item[${JSON.stringify(n.key.static)}]`:this.hole(n.key.hole).code;i.push({name:"by",kind:"attr",expr:a})}let o=this.itemArrow(t),l;if(o){let a={kind:"expr",code:o.body,reactive:o.bodyReactive},c=this.rebuildWithChildren(t,[a]);l=`(${o.params.join(", ")}) => (${this.emit(c)})`}else{let a=this.stripAndLower(t,c=>c.kind==="EachDirective");l=`() => (${this.emit(a)})`}return{kind:"component",name:"For",props:i,children:[{kind:"expr",code:l,reactive:!1}]}}itemArrow(t){let n=t.children.filter(r=>!this.isBlankText(r));return n.length!==1||n[0].kind!=="Expression"?null:this.hole(n[0].hole).arrow??null}stripAndLower(t,n){let r={...t,attributes:t.attributes.filter(i=>!n(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(t,n){let r=this.lowerAttributes(t.attributes.filter(i=>i.kind!=="EachDirective"));return t.kind==="Element"?{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:r,children:n,static:!1}:{kind:"component",name:t.tag,props:r,children:n}}lowerAttributes(t){let n=[],r=[],i=!1,o=[],l=!1,s=[];for(let a of t)switch(a.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":n.push(this.plainAttr(a));break;case"PropertyBinding":n.push({name:a.name,kind:"prop",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"EventBinding":n.push(this.eventProp(a));break;case"RefBinding":n.push({name:"ref",kind:"ref",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"Spread":n.push({name:"",kind:"spread",expr:this.hole(a.hole).code});break;case"ClassDirective":{let c=this.hole(a.hole);r.push(`${JSON.stringify(a.name)}: ${c.code}`),i=i||c.reactive;break}case"StyleDirective":{let c=this.hole(a.hole);o.push(`${JSON.stringify(a.name)}: ${c.code}`),l=l||c.reactive;break}case"BindDirective":n.push(...this.bindProps(a.name,this.hole(a.hole).code));break;case"UseDirective":{let c=a.name??(a.hole!=null?this.hole(a.hole).code:null);if(!c)break;s.push(a.name!=null&&a.hole!=null?`[${c}, () => (${this.hole(a.hole).code})]`:`[${c}]`);break}}return r.length>0&&n.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i}),o.length>0&&n.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:l}),s.length>0&&n.push({name:"use",kind:"attr",expr:`[${s.join(", ")}]`}),n}eventProp(t){let n=t.name.toLowerCase(),r=this.hole(t.hole).code;if(!(t.syntax==="colon"||t.modifiers.length>0))return{name:"on"+te(t.name),kind:"event",event:{name:n,delegated:ee.has(n)},expr:r};let o=this.wrapHandler(r,t.modifiers),l=this.eventOptions(t.modifiers),s=l?`[${o}, ${l}]`:o;return{name:"on:"+n,kind:"attr",expr:s}}wrapHandler(t,n){let r=n.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return n.includes("prevent")&&i.push("e.preventDefault();"),n.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?t:`(e) => { ${r}${i.join(" ")} return (${t})(e); }`}eventOptions(t){let n=[];return t.includes("capture")&&n.push("capture: true"),t.includes("once")&&n.push("once: true"),t.includes("passive")&&n.push("passive: true"),n.length?`{ ${n.join(", ")} }`:null}bindProps(t,n){let r=t==="checked",i=r?"change":"input",o=r?"checked":"value",l=`(${n})`;return[{name:t,kind:"attr",expr:`${l}[0]()`,reactive:!0},{name:"on"+te(i),kind:"event",event:{name:i,delegated:ee.has(i)},expr:`(e) => ${l}[1](e.target.${o})`}]}plainAttr(t){let n=t.value,r=t.name;t.name==="class"?r=n&&n.kind==="hole"&&this.hole(n.hole).object?"classList":"className":t.name==="html"&&(r="innerHTML");let o={name:r,kind:"attr"};if(n==null)return o.literal=!0,o;if(n.kind==="static")return o.literal=n.value,o;if(n.kind==="hole"){let a=this.hole(n.hole);return o.expr=a.code,o.reactive=a.reactive,o}let l=!1,s=n.parts.map(a=>{if("text"in a)return Le(a.text);let c=this.hole(a.hole);return l=l||c.reactive,"${"+c.code+"}"}).join("");return o.expr="`"+s+"`",o.reactive=l,o}};function ne(e,t,n,r={}){let{root:i}=Je(e,{svg:r.svg});return new D(t,n).lowerRoot(i.children)}import{types as b,traverse as We,template as qe}from"@babel/core";import le from"@babel/generator";var De="children";function y(e){switch(e.kind){case"call":return!0;case"member":return e.property!==De;case"compound":return e.parts.some(y);case"opaque":return!1}}var je=new Set(["CallExpression","OptionalCallExpression"]),Oe=new Set(["MemberExpression","OptionalMemberExpression"]);function E(e){if(!e)return{kind:"opaque"};if(je.has(e.type))return{kind:"call"};if(Oe.has(e.type)){let t=e.property;return{kind:"member",property:!(e.computed===!0)&&t?.type==="Identifier"?t.name:null}}return e.type==="ConditionalExpression"?{kind:"compound",parts:[e.test,e.consequent,e.alternate].map(N)}:e.type==="LogicalExpression"||e.type==="BinaryExpression"?{kind:"compound",parts:[e.left,e.right].map(N)}:e.type==="TemplateLiteral"?{kind:"compound",parts:e.expressions.map(N)}:e.type==="ObjectExpression"?{kind:"compound",parts:e.properties.filter(n=>(n.type==="ObjectProperty"||n.type==="Property")&&n.computed!==!0).map(n=>N(n.value))}:e.type==="ArrayExpression"?{kind:"compound",parts:e.elements.filter(n=>n!=null&&n.type!=="SpreadElement").map(N)}:{kind:"opaque"}}var N=e=>E(e);function Xe(e){switch(e.kind){case"event":return"event";case"ref":return"ref";case"spread":return"spread";case"class":case"style":return"class-or-style-directive";case"attr":case"prop":return e.reactive?"reactive-prop":e.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function T(e){let t=[],n=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let o of i.children)r(o);return!1;case"fragment":for(let o of i.children)r(o);return!1;case"element":{let o=!0;for(let s of i.children)r(s)||(o=!1);let l;for(let s of i.props)if(l=Xe(s),l)break;return!l&&!o&&(l=Me(i)),i.static=!l,l?n.set(i,l):t.push(i),i.static}default:return!1}};for(let i of Array.isArray(e)?e:[e])r(i);return{staticElements:t,reasons:n}}function Me(e){for(let t of e.children){if(t.kind==="expr")return"expression-child";if(t.kind==="component")return"component-child";if(t.kind==="control")return"control-child";if(t.kind==="element"&&!t.static||t.kind==="fragment")return"expression-child"}return"expression-child"}var He=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),_e=/^on[A-Z]/,Be=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]),oe=e=>y(E(e));function R(e){if(e.type==="StringLiteral"||e.type==="NumericLiteral"||e.type==="BooleanLiteral"||e.type==="Literal"&&(typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"))return e.value}var j=e=>!!e&&typeof R(e)=="string";function Fe(e,t){return e.type==="JSXIdentifier"?{tag:e.name,component:e.name[0]!==e.name[0].toLowerCase()}:e.type==="JSXMemberExpression"?{tag:t.code(e),component:!0}:e.type==="JSXNamespacedName"?{tag:`${e.namespace.name}:${e.name.name}`,component:!1}:{tag:"div",component:!1}}function O(e){return e.type==="JSXIdentifier"?e.name==="class"?"className":e.name:e.type==="JSXNamespacedName"?`${e.namespace.name}:${e.name.name}`:"unknown"}function ze(e,t){let n=O(e.name),r=_e.test(n),i=r||n.startsWith("on:")||n==="ref",l={name:n,kind:r?"event":"attr"};if(r){let a=n.slice(2).toLowerCase();l.event={name:a,delegated:Be.has(a)}}let s=e.value;if(s==null)return l.literal=!0,l;if(j(s))return l.literal=R(s),l;if(s.type==="JSXExpressionContainer"&&s.expression?.type!=="JSXEmptyExpression"){let a=s.expression,c=R(a);return c!==void 0?(l.literal=c,l):(l.expr=t.code(a),l.reactive=i?!1:oe(a),(a.type==="JSXElement"||a.type==="JSXFragment")&&(l.jsxElement=!0),l)}return l.literal=!0,l}function re(e,t){let n=e.value;return n==null?null:j(n)?JSON.stringify(R(n)):n.type==="JSXExpressionContainer"&&n.expression?.type!=="JSXEmptyExpression"?t.code(n.expression):null}function Ve(e,t){let n=[],r=[];for(let i of e){if(i.type==="JSXSpreadAttribute"){n.push({name:"",kind:"spread",expr:t.code(i.argument)});continue}if(i.type!=="JSXAttribute"||P(O(i.name)))continue;let o=i.name.type==="JSXNamespacedName"?i.name.namespace.name:null;if(o==="use"){let l=i.name.name.name;t.used.add(l);let s=re(i,t);r.push(s!=null?`[${l}, () => (${s})]`:`[${l}]`);continue}if(o==="oncapture"){let l=i.name.name.name.toLowerCase(),s=re(i,t)??"undefined";n.push({name:"on:"+l,kind:"attr",expr:`[${s}, { capture: true }]`});continue}n.push(ze(i,t))}return r.length>0&&n.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),n}function ie(e,t){let n=[];for(let r of e)if(r.type==="JSXText"){let i=x(r.value);i&&n.push({kind:"text",value:i})}else if(r.type==="JSXExpressionContainer"){if(r.expression?.type!=="JSXEmptyExpression"){let i=r.expression;n.push({kind:"expr",code:t.code(i),reactive:oe(i)})}}else r.type==="JSXElement"||r.type==="JSXFragment"?n.push(se(r,t)):r.type==="JSXSpreadChild"&&n.push({kind:"expr",code:t.code(r.expression),reactive:!1});return n}function Ge(e){for(let t of e){if(t.type!=="JSXAttribute")continue;let n=O(t.name);if(P(n)){if(t.value&&!j(t.value))throw new m(`'${n}' needs a literal value, not an expression — the strategy is compile-time.`);return I(n,t.value?R(t.value):null)}}}function se(e,t){if(e.type==="JSXFragment")return{kind:"fragment",children:ie(e.children,t)};let{tag:n,component:r}=Fe(e.openingElement.name,t),i=Ve(e.openingElement.attributes,t),o=ie(e.children,t);if(r){let l=Ge(e.openingElement.attributes);return{kind:"component",name:n,props:i,children:o,...l?{load:l}:{}}}return{kind:"element",tag:n,svg:He.has(n),props:i,children:o,static:!1}}function ae(e,t){let n=se(e,t);return T(n),n}var Ue=le.default??le;function ce(e){return Ue(e,{concise:!0}).code}function Ke(e,t,n){let r=b.cloneNode(e,!0),i=b.file(b.program([b.expressionStatement(r)])),o=!1,l=(s,a,c)=>{for(let p of c)t.add(p);s.replaceWith(qe.expression(a,{placeholderPattern:!1,plugins:["typescript"]})()),s.skip(),o=!0};return We(i,{"JSXElement|JSXFragment"(s){let a=s.node,c=Ze(a,t,n);n?.(c);let{code:p,imports:d,templates:u}=k.emit(c,{});l(s,v(p,u),d)},TaggedTemplateExpression(s){let a=s.node.tag;if(!b.isIdentifier(a)||a.name!=="html"&&a.name!=="svg")return;let c=pe(s.node,t,{svg:a.name==="svg",onNested:n});n?.(c);let{code:p,imports:d,templates:u}=k.emit(c,{});l(s,v(p,u),d)}}),o?i.program.body[0].expression:e}function C(e,t,n){return ce(Ke(e,t,n))}function X(e){return y(E(e))}function Ze(e,t=new Set,n){return ae(e,{code:i=>i.type==="JSXMemberExpression"?ce(i):C(i,t,n),used:t})}var Ye=de.default??de;function Qe(e){return Ye(e,{concise:!0}).code}function et(e,t,n){let r={code:C(e,t,n),reactive:X(e)};if(M.isArrowFunctionExpression(e)&&!M.isBlockStatement(e.body)){let i=e.body;r.arrow={params:e.params.map(o=>Qe(o)),body:C(i,t,n),bodyReactive:X(i)}}return M.isObjectExpression(e)&&(r.object=!0),r}function ue(e,t,n={}){let r=e.quasi,i=r.expressions.map(o=>et(o,t,n.onNested));return ne(tt(r),i,t,n)}function tt(e){let t=[];return e.quasis.forEach((n,r)=>{let i=n.value.cooked??n.value.raw;if(t.push({kind:"static",text:i,start:n.start??0}),r<e.expressions.length){let o=e.expressions[r];t.push({kind:"hole",index:r,start:o.start??0,end:o.end??0})}}),t}function pe(e,t=new Set,n={}){let r=ue(e,t,n);return T(r),r}export{pe as buildIRFromLit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ue=Object.create;var y=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var ge=(t,e)=>{for(var n in e)y(t,n,{get:e[n],enumerable:!0})},B=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of me(e))!he.call(t,i)&&i!==n&&y(t,i,{get:()=>e[i],enumerable:!(r=de(e,i))||r.enumerable});return t};var H=(t,e,n)=>(n=t!=null?ue(fe(t)):{},B(e||!t||!t.__esModule?y(n,"default",{value:t,enumerable:!0}):n,t)),ve=t=>B(y({},"__esModule",{value:!0}),t);var Ye={};ge(Ye,{SVG_TAGS:()=>ce,buildIR:()=>pe,cleanJSXText:()=>S,genExpr:()=>f,isReactiveExpr:()=>m});module.exports=ve(Ye);var p=require("@babel/core"),D=H(require("@babel/generator"),1);var xe=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),F={className:"class",htmlFor:"for"},ke=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),Ee=new Set(["script","style","textarea","title"]);function C(t){return Ee.has(t)}function z(t){return F[t]??t}function v(t){return t.kind!=="attr"||t.expr!==void 0||t.name.includes(":")?!1:!ke.has(t.name)}function A(t){if(!t.static||C(t.tag))return!1;for(let e of t.props)if(!v(e))return!1;for(let e of t.children)if(e.kind!=="text"&&!(e.kind==="element"&&A(e)))return!1;return!0}function x(t){let e=t.props.map(Ne).filter(Boolean).join(""),n=`<${t.tag}${e}>`;return xe.has(t.tag)?n:`${n}${t.children.map(Re).join("")}</${t.tag}>`}function Re(t){if(t.kind==="text")return be(t.value);if(t.kind!=="element")throw new Error(`serializeStatic: unexpected ${t.kind}`);return x(t)}function Ne(t){let e=F[t.name]??t.name,n=t.literal;return n===!0||n===void 0?` ${e}`:n===!1||n===null?"":` ${e}="${Se(String(n))}"`}function Se(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function be(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var ye="<!--fx-->",Ie="<!--fx/-->";function $(t){return t.kind==="expr"||t.kind==="component"||t.kind==="control"}function $e(t){return t.kind==="text"||t.kind==="element"&&V(t)}function V(t){return t.svg||C(t.tag)||!t.props.every(e=>v(e))?!1:t.children.every(e=>$e(e)||$(e))}function I(t){if($(t))return!0;let e=t.children;return e?e.some(I):!1}function W(t){for(let e=0;e<t.children.length;e++){let n=t.children[e];if(n.kind==="text"&&(n.value===""||t.children[e+1]?.kind==="text"))return!1}return t.children.every(e=>e.kind!=="element"||W(e))}function U(t){if(!V(t)||!W(t)||!t.children.some(I))return null;let e=[],n=[],r=0,i=a=>{let s=`_n$${r++}`;return e.push({ref:s,expr:a}),s};return o(t,"_el$"),{html:we(t),tag:t.tag,steps:e,holes:n};function o(a,s){let l=-1;a.children.forEach((u,d)=>{I(u)&&(l=d)});let c=null;for(let u=0;u<=l;u++){let d=a.children[u],g=c?`${c}.nextSibling`:`${s}.firstChild`;if($(d)){let _=i(g),M=i(`holeEnd(${_})`);n.push({parentRef:s,startRef:_,endRef:M,node:d}),c=M;continue}let b=i(g);d.kind==="element"&&I(d)&&o(d,b),c=b}}}function we(t){return x(G(t)).split(K).join(ye+Ie)}function G(t){return{...t,children:t.children.map(e=>$(e)?{kind:"text",value:K}:e.kind==="element"?G(e):e)}}var K="\0fx-hole\0";var P={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},rt={version:2,module:"@fluixi/dom",symbols:[...P.symbols,"template","cloneTemplate","walk"]};var Te={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function Ce(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)}function Z(t){return Ce(t)?t:JSON.stringify(t)}function Ae(t){return t.expr!==void 0?t.reactive?`() => (${t.expr})`:`(${t.expr})`:JSON.stringify(t.literal??!0)}function Pe(t){return t.expr!==void 0?`(${t.expr})`:JSON.stringify(t.literal??!0)}function Je(t,e,n){let r=t.filter(s=>s.kind==="spread"),o=t.filter(s=>s.kind!=="spread").map(s=>`${Z(s.name)}: ${Ae(s)}`);e!=null&&o.push(`children: ${e}`);let a=`{ ${o.join(", ")} }`;return r.length>0?(n.add("mergeProps"),`mergeProps(${r.map(s=>s.expr).join(", ")}, ${a})`):a}function Y(t,e,n){return t.length===1?k(t[0],e,n):`[${t.map(r=>k(r,e,n)).join(", ")}]`}function q(t,e,n,r,i){r.add("createMemo"),r.add("createComponent");let o=e.filter(c=>c.kind==="spread"),s=e.filter(c=>c.kind!=="spread").map(c=>`get ${Z(c.name)}() { return ${Pe(c)}; }`);n.length>0&&s.push(`get children() { return ${Y(n,r,i)}; }`);let l=`{ ${s.join(", ")} }`;return o.length>0&&(r.add("mergeProps"),l=`mergeProps(${o.map(c=>c.expr).join(", ")}, ${l})`),`createMemo(() => createComponent(${t}, ${l}))`}function Le(t,e){let n=z(e.name),r=e.literal;return r===!0||r===void 0?`${t}.setAttribute(${JSON.stringify(n)}, "");`:r===!1||r===null?"":`${t}.setAttribute(${JSON.stringify(n)}, ${JSON.stringify(String(r))});`}var Q=!1;function k(t,e,n){switch(t.kind){case"text":return JSON.stringify(t.value);case"expr":return t.reactive?`() => (${t.code})`:`(${t.code})`;case"fragment":return t.children.length===0?"null":Y(t.children,e,n);case"component":return q(t.name,t.props,t.children,e,n);case"control":{let r=Te[t.control]??t.control;return e.add(r),q(r,t.props,t.children,e,n)}case"element":{if(n&&t.static&&!t.svg&&A(t)){e.add("templateNode");let s=`_tmpl$${n.length}`;return n.push({id:s,html:x(t),tag:t.tag,svg:!1}),`templateNode(${s}, ${JSON.stringify(t.tag)})`}if(n&&Q){let s=U(t);if(s){e.add("templateNode"),e.add("insert"),e.add("holeEnd"),e.add("holeContent"),e.add("holeScope");let l=`_tmpl$${n.length}`;n.push({id:l,html:s.html,tag:s.tag,svg:!1});let c=[`const _el$ = templateNode(${l}, ${JSON.stringify(s.tag)}, true);`];for(let u of s.steps)c.push(`const ${u.ref} = ${u.expr};`);for(let u of s.holes)c.push(`insert(${u.parentRef}, holeScope(${u.startRef}, () => (${k(u.node,e,n)})), ${u.endRef}, holeContent(${u.startRef}, ${u.endRef}));`);return c.push("return _el$;"),`(() => { ${c.join(" ")} })()`}}e.add("createNativeElement");let r=JSON.stringify(t.tag),i="_el$",o=[],a=t.svg?`${r}, true`:r;if(o.push(`const ${i} = createNativeElement(${a});`),t.props.length>0)if(!t.svg&&t.props.every(v))for(let s of t.props)o.push(Le(i,s));else{e.add("spread");let s=t.svg?", isSVG: true":"";o.push(`spread({ element: ${i}, props: ${Je(t.props,null,e)}${s} });`)}for(let s of t.children){e.add("insert");let l=k(s,e,n),c=s.kind==="expr"&&s.reactive||s.kind==="component"||s.kind==="control";o.push(c?`insert(${i}, ${l}, null);`:`insert(${i}, ${l});`)}return o.push(`return ${i};`),`(() => { ${o.join(" ")} })()`}}}function E(t,e){if(!e||e.length===0)return t;let n=new Map(e.map(r=>[r.id,JSON.stringify(r.html)]));return t.replace(/_tmpl\$\d+/g,r=>n.get(r)??r)}var R={name:"imperative",contract:P,emit(t,e){let n=new Set,r=e?.templateClone!==!1?[]:void 0;return Q=e?.partialTemplates===!0,{code:k(t,n,r),imports:Array.from(n),templates:r}}};var N=require("@babel/core"),L=H(require("@babel/generator"),1),re=require("@fluixi/template-parser");var Xe={kind:"eager"},De=["pointerdown","focusin","keydown"],ee=new Set(["eager","idle","visible","interaction","media","never"]),h=class extends Error{};function J(t){return t.startsWith("load:")}function w(t,e){let n=t.slice(5);if(!ee.has(n))throw new h(`Unknown load strategy 'load:${n}'. Expected one of ${[...ee].join(", ")}.`);switch(n){case"eager":return Xe;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return e?{kind:"visible",rootMargin:e}:{kind:"visible"};case"interaction":return{kind:"interaction",events:e?je(e):[...De]};case"media":if(!e)throw new h(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:e};default:throw new h(`Unhandled load strategy '${n}'.`)}}function je(t){let e=t.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean);if(e.length===0)throw new h("'load:interaction' was given no event names.");return e}var Oe=L.default.default??L.default;function _e(t){return Oe(t,{concise:!0}).code}var te=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Me(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function ne(t){return t.charAt(0).toUpperCase()+t.slice(1)}var X=class{constructor(e,n){this.holes=e;this.used=n}hole(e){return this.holes[e]??{node:N.types.identifier("undefined"),code:"undefined",reactive:!1}}emit(e){let{code:n,imports:r,templates:i}=R.emit(e,{});for(let o of r)this.used.add(o);return E(n,i)}lowerRoot(e){let n=this.lowerChildren(e);return n.length===1?n[0]:{kind:"fragment",children:n}}lowerChildren(e){let n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i.kind==="Element"||i.kind==="Component"){let a=i.attributes.find(s=>s.kind==="IfDirective");if(a&&a.kind==="IfDirective"){let s=r+1;s<e.length&&this.isBlankText(e[s])&&s++;let l=e[s],c=l&&(l.kind==="Element"||l.kind==="Component")&&l.attributes.some(u=>u.kind==="ElseDirective");n.push(this.lowerIf(i,a.hole,c?l:null)),c&&(r=s);continue}if(i.attributes.some(s=>s.kind==="EachDirective")){n.push(this.lowerEach(i));continue}}let o=this.lowerNode(i);o&&n.push(o)}return n}isBlankText(e){return e.kind==="Text"&&!e.raw&&S(e.value)===""}lowerNode(e){switch(e.kind){case"Text":{if(e.raw)return{kind:"text",value:e.value};let n=S(e.value);return n?{kind:"text",value:n}:null}case"Comment":return null;case"Expression":{let n=this.hole(e.hole);return{kind:"expr",code:n.code,reactive:n.reactive}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(e.children)};case"Element":return this.lowerElement(e);case"Component":return this.lowerComponent(e);default:return null}}lowerElement(e){let n=e.attributes.find(r=>r.kind==="Attribute"&&r.name==="is");if(e.tag==="component"&&n&&n.value&&n.value.kind==="hole"){let r=e.attributes.filter(o=>o!==n),i=this.lowerComponent({...e,kind:"Component",tag:"Dynamic",tagHole:null,attributes:r});return i.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(n.value.hole).code})`}),i}return{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:this.lowerAttributes(e.attributes),children:this.lowerChildren(e.children),static:!1}}lowerComponent(e){let n=e.tagHole!=null?this.hole(e.tagHole).code:e.tag,r=this.lowerAttributes(e.attributes),{slots:i,rest:o}=this.partitionSlots(e.children);for(let[l,c]of i){let u=c.length===1?c[0]:{kind:"fragment",children:c},d={name:l,kind:"attr",expr:this.emit(u),jsxElement:!0},g=r.findIndex(b=>b.name===l);g>=0?r[g]=d:r.push(d)}let a=e.attributes.find(l=>l.kind==="LoadDirective"),s=a?w(`load:${a.strategy}`,a.modifier):void 0;return{kind:"component",name:n,props:r,children:this.lowerChildren(o),...s?{load:s}:{}}}partitionSlots(e){let n=new Map,r=[];for(let i of e){if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(a=>a.kind==="Attribute"&&a.name==="slot");if(o&&o.value&&o.value.kind==="static"){let a={...i,attributes:i.attributes.filter(c=>c!==o)},s=a.kind==="Element"?this.lowerElement(a):this.lowerComponent(a),l=n.get(o.value.value)??[];l.push(s),n.set(o.value.value,l);continue}}r.push(i)}return{slots:n,rest:r}}lowerIf(e,n,r){let i=this.hole(n),o=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive}];if(r){let s=this.stripAndLower(r,l=>l.kind==="ElseDirective");o.push({name:"fallback",kind:"attr",expr:this.emit(s),jsxElement:!0})}let a=this.stripAndLower(e,s=>s.kind==="IfDirective");return{kind:"component",name:"Show",props:o,children:[a]}}lowerEach(e){let n=e.attributes.find(l=>l.kind==="EachDirective");if(!n||n.kind!=="EachDirective")return this.lowerNode(e);let r=this.hole(n.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive}];if(n.key){let l="static"in n.key?`(item) => item[${JSON.stringify(n.key.static)}]`:this.hole(n.key.hole).code;i.push({name:"by",kind:"attr",expr:l})}let o=this.itemArrow(e),a;if(o){let l=o.body,c={kind:"expr",code:f(l,this.used),reactive:m(l)},u=this.rebuildWithChildren(e,[c]);a=`(${o.params.map(d=>_e(d)).join(", ")}) => (${this.emit(u)})`}else{let l=this.stripAndLower(e,c=>c.kind==="EachDirective");a=`() => (${this.emit(l)})`}return{kind:"component",name:"For",props:i,children:[{kind:"expr",code:a,reactive:!1}]}}itemArrow(e){let n=e.children.filter(i=>!this.isBlankText(i));if(n.length!==1||n[0].kind!=="Expression")return null;let r=this.hole(n[0].hole).node;return N.types.isArrowFunctionExpression(r)&&!N.types.isBlockStatement(r.body)?r:null}stripAndLower(e,n){let r={...e,attributes:e.attributes.filter(i=>!n(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(e,n){let r=this.lowerAttributes(e.attributes.filter(i=>i.kind!=="EachDirective"));return e.kind==="Element"?{kind:"element",tag:e.tag,svg:e.namespace==="svg",props:r,children:n,static:!1}:{kind:"component",name:e.tag,props:r,children:n}}lowerAttributes(e){let n=[],r=[],i=!1,o=[],a=!1,s=[];for(let l of e)switch(l.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":n.push(this.plainAttr(l));break;case"PropertyBinding":n.push({name:l.name,kind:"prop",expr:this.hole(l.hole).code,reactive:this.hole(l.hole).reactive});break;case"EventBinding":n.push(this.eventProp(l));break;case"RefBinding":n.push({name:"ref",kind:"ref",expr:this.hole(l.hole).code,reactive:this.hole(l.hole).reactive});break;case"Spread":n.push({name:"",kind:"spread",expr:this.hole(l.hole).code});break;case"ClassDirective":{let c=this.hole(l.hole);r.push(`${JSON.stringify(l.name)}: ${c.code}`),i=i||c.reactive;break}case"StyleDirective":{let c=this.hole(l.hole);o.push(`${JSON.stringify(l.name)}: ${c.code}`),a=a||c.reactive;break}case"BindDirective":n.push(...this.bindProps(l.name,this.hole(l.hole).code));break;case"UseDirective":{let c=l.name??(l.hole!=null?this.hole(l.hole).code:null);if(!c)break;s.push(l.name!=null&&l.hole!=null?`[${c}, () => (${this.hole(l.hole).code})]`:`[${c}]`);break}}return r.length>0&&n.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i}),o.length>0&&n.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:a}),s.length>0&&n.push({name:"use",kind:"attr",expr:`[${s.join(", ")}]`}),n}eventProp(e){let n=e.name.toLowerCase(),r=this.hole(e.hole).code;if(!(e.syntax==="colon"||e.modifiers.length>0))return{name:"on"+ne(e.name),kind:"event",event:{name:n,delegated:te.has(n)},expr:r};let o=this.wrapHandler(r,e.modifiers),a=this.eventOptions(e.modifiers),s=a?`[${o}, ${a}]`:o;return{name:"on:"+n,kind:"attr",expr:s}}wrapHandler(e,n){let r=n.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return n.includes("prevent")&&i.push("e.preventDefault();"),n.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?e:`(e) => { ${r}${i.join(" ")} return (${e})(e); }`}eventOptions(e){let n=[];return e.includes("capture")&&n.push("capture: true"),e.includes("once")&&n.push("once: true"),e.includes("passive")&&n.push("passive: true"),n.length?`{ ${n.join(", ")} }`:null}bindProps(e,n){let r=e==="checked",i=r?"change":"input",o=r?"checked":"value",a=`(${n})`;return[{name:e,kind:"attr",expr:`${a}[0]()`,reactive:!0},{name:"on"+ne(i),kind:"event",event:{name:i,delegated:te.has(i)},expr:`(e) => ${a}[1](e.target.${o})`}]}plainAttr(e){let n=e.value,r=e.name;e.name==="class"?r=n&&n.kind==="hole"&&N.types.isObjectExpression(this.hole(n.hole).node)?"classList":"className":e.name==="html"&&(r="innerHTML");let o={name:r,kind:"attr"};if(n==null)return o.literal=!0,o;if(n.kind==="static")return o.literal=n.value,o;if(n.kind==="hole"){let l=this.hole(n.hole);return o.expr=l.code,o.reactive=l.reactive,o}let a=!1,s=n.parts.map(l=>{if("text"in l)return Me(l.text);let c=this.hole(l.hole);return a=a||c.reactive,"${"+c.code+"}"}).join("");return o.expr="`"+s+"`",o.reactive=a,o}};function ie(t,e,n={}){let r=t.quasi,i=r.expressions.map(s=>{let l=s;return{node:l,code:f(l,e),reactive:m(l)}}),o=Be(r),{root:a}=(0,re.parseTemplate)(o,{svg:n.svg});return new X(i,e).lowerRoot(a.children)}function Be(t){let e=[];return t.quasis.forEach((n,r)=>{let i=n.value.cooked??n.value.raw;if(e.push({kind:"static",text:i,start:n.start??0}),r<t.expressions.length){let o=t.expressions[r];e.push({kind:"hole",index:r,start:o.start??0,end:o.end??0})}}),e}function He(t){switch(t.kind){case"event":return"event";case"ref":return"ref";case"spread":return"spread";case"class":case"style":return"class-or-style-directive";case"attr":case"prop":return t.reactive?"reactive-prop":t.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function T(t){let e=[],n=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let o of i.children)r(o);return!1;case"fragment":for(let o of i.children)r(o);return!1;case"element":{let o=!0;for(let s of i.children)r(s)||(o=!1);let a;for(let s of i.props)if(a=He(s),a)break;return!a&&!o&&(a=Fe(i)),i.static=!a,a?n.set(i,a):e.push(i),i.static}default:return!1}};for(let i of Array.isArray(t)?t:[t])r(i);return{staticElements:e,reasons:n}}function Fe(t){for(let e of t.children){if(e.kind==="expr")return"expression-child";if(e.kind==="component")return"component-child";if(e.kind==="control")return"control-child";if(e.kind==="element"&&!e.static||e.kind==="fragment")return"expression-child"}return"expression-child"}function se(t,e=new Set,n={}){let r=ie(t,e,n);return T(r),r}var ze=D.default.default??D.default;function le(t){return ze(t,{concise:!0}).code}function Ve(t,e){let n=p.types.cloneNode(t,!0),r=p.types.file(p.types.program([p.types.expressionStatement(n)])),i=!1,o=(a,s,l)=>{for(let c of l)e.add(c);a.replaceWith(p.template.expression(s,{placeholderPattern:!1,plugins:["typescript"]})()),a.skip(),i=!0};return(0,p.traverse)(r,{"JSXElement|JSXFragment"(a){let s=a.node,{code:l,imports:c,templates:u}=R.emit(pe(s,e),{});o(a,E(l,u),c)},TaggedTemplateExpression(a){let s=a.node.tag;if(!p.types.isIdentifier(s)||s.name!=="html"&&s.name!=="svg")return;let l=se(a.node,e,{svg:s.name==="svg"}),{code:c,imports:u,templates:d}=R.emit(l,{});o(a,E(c,d),u)}}),i?r.program.body[0].expression:t}function f(t,e){return le(Ve(t,e))}var ce=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),We=/^on[A-Z]/,Ue=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Ge(t){if(p.types.isJSXIdentifier(t)){let e=t.name[0]!==t.name[0].toLowerCase();return{tag:t.name,component:e}}return p.types.isJSXMemberExpression(t)?{tag:le(t),component:!0}:p.types.isJSXNamespacedName(t)?{tag:`${t.namespace.name}:${t.name.name}`,component:!1}:{tag:"div",component:!1}}function O(t){return p.types.isJSXIdentifier(t)?t.name==="class"?"className":t.name:p.types.isJSXNamespacedName(t)?`${t.namespace.name}:${t.name.name}`:"unknown"}function m(t){return p.types.isCallExpression(t)||p.types.isOptionalCallExpression(t)?!0:p.types.isMemberExpression(t)||p.types.isOptionalMemberExpression(t)?!(!t.computed&&p.types.isIdentifier(t.property,{name:"children"})):p.types.isConditionalExpression(t)?m(t.test)||m(t.consequent)||m(t.alternate):p.types.isLogicalExpression(t)||p.types.isBinaryExpression(t)?m(t.left)||m(t.right):p.types.isTemplateLiteral(t)?t.expressions.some(e=>m(e)):p.types.isObjectExpression(t)?t.properties.some(e=>p.types.isObjectProperty(e)&&!e.computed&&m(e.value)):p.types.isArrayExpression(t)?t.elements.some(e=>e!=null&&!p.types.isSpreadElement(e)&&m(e)):!1}function Ke(t,e){let n=O(t.name),r=We.test(n),i=r||n.startsWith("on:")||n==="ref",a={name:n,kind:r?"event":"attr"};r&&(a.event={name:n.slice(2).toLowerCase(),delegated:Ue.has(n.slice(2).toLowerCase())});let s=t.value;if(s==null)return a.literal=!0,a;if(p.types.isStringLiteral(s))return a.literal=s.value,a;if(p.types.isJSXExpressionContainer(s)&&!p.types.isJSXEmptyExpression(s.expression)){let l=s.expression;return p.types.isStringLiteral(l)||p.types.isNumericLiteral(l)||p.types.isBooleanLiteral(l)?(a.literal=l.value,a):(a.expr=f(l,e),a.reactive=i?!1:m(l),(p.types.isJSXElement(l)||p.types.isJSXFragment(l))&&(a.jsxElement=!0),a)}return a.literal=!0,a}function oe(t,e){let n=t.value;return n==null?null:p.types.isStringLiteral(n)?JSON.stringify(n.value):p.types.isJSXExpressionContainer(n)&&!p.types.isJSXEmptyExpression(n.expression)?f(n.expression,e):null}function qe(t,e){let n=[],r=[];for(let i of t){if(p.types.isJSXSpreadAttribute(i)){n.push({name:"",kind:"spread",expr:f(i.argument,e)});continue}if(!p.types.isJSXAttribute(i)||J(O(i.name)))continue;let o=p.types.isJSXNamespacedName(i.name)?i.name.namespace.name:null;if(o==="use"){let a=i.name.name.name;e.add(a);let s=oe(i,e);r.push(s!=null?`[${a}, () => (${s})]`:`[${a}]`);continue}if(o==="oncapture"){let a=i.name.name.name.toLowerCase(),s=oe(i,e)??"undefined";n.push({name:"on:"+a,kind:"attr",expr:`[${s}, { capture: true }]`});continue}n.push(Ke(i,e))}return r.length>0&&n.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),n}function S(t){let e=t.split(/\r\n|\n|\r/),n=0;for(let i=0;i<e.length;i++)/[^ \t]/.test(e[i])&&(n=i);let r="";for(let i=0;i<e.length;i++){let o=e[i].replace(/\t/g," ");i!==0&&(o=o.replace(/^ +/,"")),i!==e.length-1&&(o=o.replace(/ +$/,"")),o&&(i!==n&&(o+=" "),r+=o)}return r}function ae(t,e){let n=[];for(let r of t)if(p.types.isJSXText(r)){let i=S(r.value);i&&n.push({kind:"text",value:i})}else if(p.types.isJSXExpressionContainer(r)){if(!p.types.isJSXEmptyExpression(r.expression)){let i=r.expression;n.push({kind:"expr",code:f(i,e),reactive:m(i)})}}else p.types.isJSXElement(r)||p.types.isJSXFragment(r)?n.push(j(r,e)):p.types.isJSXSpreadChild(r)&&n.push({kind:"expr",code:f(r.expression,e),reactive:!1});return n}function pe(t,e=new Set){let n=j(t,e);return T(n),n}function j(t,e){if(p.types.isJSXFragment(t))return{kind:"fragment",children:ae(t.children,e)};let{tag:n,component:r}=Ge(t.openingElement.name),i=qe(t.openingElement.attributes,e),o=ae(t.children,e);if(r){let a=Ze(t.openingElement.attributes);return{kind:"component",name:n,props:i,children:o,...a?{load:a}:{}}}return{kind:"element",tag:n,svg:ce.has(n),props:i,children:o,static:!1}}function Ze(t){for(let e of t){if(!p.types.isJSXAttribute(e))continue;let n=O(e.name);if(J(n)){if(e.value&&!p.types.isStringLiteral(e.value))throw new h(`'${n}' needs a literal value, not an expression — the strategy is compile-time.`);return w(n,e.value?e.value.value:null)}}}
|
|
1
|
+
"use strict";var ke=Object.create;var $=Object.defineProperty;var xe=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Re=(e,t)=>{for(var n in t)$(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ye(t))!Ee.call(e,i)&&i!==n&&$(e,i,{get:()=>t[i],enumerable:!(r=xe(t,i))||r.enumerable});return e};var G=(e,t,n)=>(n=e!=null?ke(Ne(e)):{},V(t||!e||!e.__esModule?$(n,"default",{value:e,enumerable:!0}):n,e)),be=e=>V($({},"__esModule",{value:!0}),e);var dt={};Re(dt,{SVG_TAGS:()=>pt,buildIR:()=>ve,genExpr:()=>N,isReactiveExpr:()=>A});module.exports=be(dt);var u=require("@babel/core"),B=G(require("@babel/generator"),1);var Se=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),W={className:"class",htmlFor:"for"},Ie=new Set(["innerHTML","outerHTML","innerText","textContent","value","checked","selected","muted","defaultValue","defaultChecked","children","ref"]),$e=new Set(["script","style","textarea","title"]);function L(e){return $e.has(e)}function q(e){return W[e]??e}function h(e){return e.kind!=="attr"||e.expr!==void 0||e.name.includes(":")?!1:!Ie.has(e.name)}function D(e){if(!e.static||L(e.tag))return!1;for(let t of e.props)if(!h(t))return!1;for(let t of e.children)if(t.kind!=="text"&&!(t.kind==="element"&&D(t)))return!1;return!0}function g(e){let t=e.props.map(Te).filter(Boolean).join(""),n=`<${e.tag}${t}>`;return Se.has(e.tag)?n:`${n}${e.children.map(we).join("")}</${e.tag}>`}function we(e){if(e.kind==="text")return Pe(e.value);if(e.kind!=="element")throw new Error(`serializeStatic: unexpected ${e.kind}`);return g(e)}function Te(e){let t=W[e.name]??e.name,n=e.literal;return n===!0||n===void 0?` ${t}`:n===!1||n===null?"":` ${t}="${Ce(String(n))}"`}function Ce(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Pe(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var Ae="<!--fx-->",Je="<!--fx/-->";function T(e){return e.kind==="expr"||e.kind==="component"||e.kind==="control"}function Le(e){return e.kind==="text"||e.kind==="element"&&U(e)}function U(e){return e.svg||L(e.tag)||!e.props.every(t=>h(t))?!1:e.children.every(t=>Le(t)||T(t))}function w(e){if(T(e))return!0;let t=e.children;return t?t.some(w):!1}function K(e){for(let t=0;t<e.children.length;t++){let n=e.children[t];if(n.kind==="text"&&(n.value===""||e.children[t+1]?.kind==="text"))return!1}return e.children.every(t=>t.kind!=="element"||K(t))}function Z(e){if(!U(e)||!K(e)||!e.children.some(w))return null;let t=[],n=[],r=0,i=l=>{let s=`_n$${r++}`;return t.push({ref:s,expr:l}),s};return o(e,"_el$"),{html:De(e),tag:e.tag,steps:t,holes:n};function o(l,s){let a=-1;l.children.forEach((p,d)=>{w(p)&&(a=d)});let c=null;for(let p=0;p<=a;p++){let d=l.children[p],m=c?`${c}.nextSibling`:`${s}.firstChild`;if(T(d)){let F=i(m),z=i(`holeEnd(${F})`);n.push({parentRef:s,startRef:F,endRef:z,node:d}),c=z;continue}let I=i(m);d.kind==="element"&&w(d)&&o(d,I),c=I}}}function De(e){return g(Y(e)).split(Q).join(Ae+Je)}function Y(e){return{...e,children:e.children.map(t=>T(t)?{kind:"text",value:Q}:t.kind==="element"?Y(t):t)}}var Q="\0fx-hole\0";var j={version:1,module:"@fluixi/dom",symbols:["createNativeElement","insert","spread","setAttribute","delegateEvents","createComponent","createMemo","untrack","Show","For","Index","Switch","Match","Dynamic","ErrorBoundary"]},gt={version:2,module:"@fluixi/dom",symbols:[...j.symbols,"template","cloneTemplate","walk"]};var je={show:"Show",for:"For",index:"Index",switch:"Switch",match:"Match",dynamic:"Dynamic",errorBoundary:"ErrorBoundary",suspense:"Suspense"};function Oe(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function te(e){return Oe(e)?e:JSON.stringify(e)}function Xe(e){return e.expr!==void 0?e.reactive?`() => (${e.expr})`:`(${e.expr})`:JSON.stringify(e.literal??!0)}function Me(e){return e.expr!==void 0?`(${e.expr})`:JSON.stringify(e.literal??!0)}function He(e,t,n){let r=e.filter(s=>s.kind==="spread"),o=e.filter(s=>s.kind!=="spread").map(s=>`${te(s.name)}: ${Xe(s)}`);t!=null&&o.push(`children: ${t}`);let l=`{ ${o.join(", ")} }`;return r.length>0?(n.add("mergeProps"),`mergeProps(${r.map(s=>s.expr).join(", ")}, ${l})`):l}function ne(e,t,n){return e.length===1?v(e[0],t,n):`[${e.map(r=>v(r,t,n)).join(", ")}]`}function ee(e,t,n,r,i){r.add("createMemo"),r.add("createComponent");let o=t.filter(c=>c.kind==="spread"),s=t.filter(c=>c.kind!=="spread").map(c=>`get ${te(c.name)}() { return ${Me(c)}; }`);n.length>0&&s.push(`get children() { return ${ne(n,r,i)}; }`);let a=`{ ${s.join(", ")} }`;return o.length>0&&(r.add("mergeProps"),a=`mergeProps(${o.map(c=>c.expr).join(", ")}, ${a})`),`createMemo(() => createComponent(${e}, ${a}))`}function _e(e,t){let n=q(t.name),r=t.literal;return r===!0||r===void 0?`${e}.setAttribute(${JSON.stringify(n)}, "");`:r===!1||r===null?"":`${e}.setAttribute(${JSON.stringify(n)}, ${JSON.stringify(String(r))});`}var re=!1;function v(e,t,n){switch(e.kind){case"text":return JSON.stringify(e.value);case"expr":return e.reactive?`() => (${e.code})`:`(${e.code})`;case"fragment":return e.children.length===0?"null":ne(e.children,t,n);case"component":return ee(e.name,e.props,e.children,t,n);case"control":{let r=je[e.control]??e.control;return t.add(r),ee(r,e.props,e.children,t,n)}case"element":{if(n&&e.static&&!e.svg&&D(e)){t.add("templateNode");let s=`_tmpl$${n.length}`;return n.push({id:s,html:g(e),tag:e.tag,svg:!1}),`templateNode(${s}, ${JSON.stringify(e.tag)})`}if(n&&re){let s=Z(e);if(s){t.add("templateNode"),t.add("insert"),t.add("holeEnd"),t.add("holeContent"),t.add("holeScope");let a=`_tmpl$${n.length}`;n.push({id:a,html:s.html,tag:s.tag,svg:!1});let c=[`const _el$ = templateNode(${a}, ${JSON.stringify(s.tag)}, true);`];for(let p of s.steps)c.push(`const ${p.ref} = ${p.expr};`);for(let p of s.holes)c.push(`insert(${p.parentRef}, holeScope(${p.startRef}, () => (${v(p.node,t,n)})), ${p.endRef}, holeContent(${p.startRef}, ${p.endRef}));`);return c.push("return _el$;"),`(() => { ${c.join(" ")} })()`}}t.add("createNativeElement");let r=JSON.stringify(e.tag),i="_el$",o=[],l=e.svg?`${r}, true`:r;if(o.push(`const ${i} = createNativeElement(${l});`),e.props.length>0)if(!e.svg&&e.props.every(h))for(let s of e.props)o.push(_e(i,s));else{t.add("spread");let s=e.svg?", isSVG: true":"";o.push(`spread({ element: ${i}, props: ${He(e.props,null,t)}${s} });`)}for(let s of e.children){t.add("insert");let a=v(s,t,n),c=s.kind==="expr"&&s.reactive||s.kind==="component"||s.kind==="control";o.push(c?`insert(${i}, ${a}, null);`:`insert(${i}, ${a});`)}return o.push(`return ${i};`),`(() => { ${o.join(" ")} })()`}}}function k(e,t){if(!t||t.length===0)return e;let n=new Map(t.map(r=>[r.id,JSON.stringify(r.html)]));return e.replace(/_tmpl\$\d+/g,r=>n.get(r)??r)}var x={name:"imperative",contract:j,emit(e,t){let n=new Set,r=t?.templateClone!==!1?[]:void 0;return re=t?.partialTemplates===!0,{code:v(e,n,r),imports:Array.from(n),templates:r}}};var P=require("@babel/core"),M=G(require("@babel/generator"),1);var ae=require("@fluixi/template-parser");var Be={kind:"eager"},Fe=["pointerdown","focusin","keydown"],ie=new Set(["eager","idle","visible","interaction","media","never"]),f=class extends Error{};function O(e){return e.startsWith("load:")}function C(e,t){let n=e.slice(5);if(!ie.has(n))throw new f(`Unknown load strategy 'load:${n}'. Expected one of ${[...ie].join(", ")}.`);switch(n){case"eager":return Be;case"idle":return{kind:"idle"};case"never":return{kind:"never"};case"visible":return t?{kind:"visible",rootMargin:t}:{kind:"visible"};case"interaction":return{kind:"interaction",events:t?ze(t):[...Fe]};case"media":if(!t)throw new f(`'load:media' needs a query, e.g. load:media="(min-width: 1024px)".`);return{kind:"media",query:t};default:throw new f(`Unhandled load strategy '${n}'.`)}}function ze(e){let t=e.split(/[\s,]+/).map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new f("'load:interaction' was given no event names.");return t}function y(e){let t=e.split(/\r\n|\n|\r/),n=0;for(let i=0;i<t.length;i++)/[^ \t]/.test(t[i])&&(n=i);let r="";for(let i=0;i<t.length;i++){let o=t[i].replace(/\t/g," ");i!==0&&(o=o.replace(/^ +/,"")),i!==t.length-1&&(o=o.replace(/ +$/,"")),o&&(i!==n&&(o+=" "),r+=o)}return r}var oe=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]);function Ve(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function se(e){return e.charAt(0).toUpperCase()+e.slice(1)}var X=class{constructor(t,n){this.holes=t;this.used=n}hole(t){return this.holes[t]??{code:"undefined",reactive:!1}}emit(t){let{code:n,imports:r,templates:i}=x.emit(t,{});for(let o of r)this.used.add(o);return k(n,i)}lowerRoot(t){let n=this.lowerChildren(t);return n.length===1?n[0]:{kind:"fragment",children:n}}lowerChildren(t){let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(i.kind==="Element"||i.kind==="Component"){let l=i.attributes.find(s=>s.kind==="IfDirective");if(l&&l.kind==="IfDirective"){let s=r+1;s<t.length&&this.isBlankText(t[s])&&s++;let a=t[s],c=a&&(a.kind==="Element"||a.kind==="Component")&&a.attributes.some(p=>p.kind==="ElseDirective");n.push(this.lowerIf(i,l.hole,c?a:null)),c&&(r=s);continue}if(i.attributes.some(s=>s.kind==="EachDirective")){n.push(this.lowerEach(i));continue}}let o=this.lowerNode(i);o&&n.push(o)}return n}isBlankText(t){return t.kind==="Text"&&!t.raw&&y(t.value)===""}lowerNode(t){switch(t.kind){case"Text":{if(t.raw)return{kind:"text",value:t.value};let n=y(t.value);return n?{kind:"text",value:n}:null}case"Comment":return null;case"Expression":{let n=this.hole(t.hole);return{kind:"expr",code:n.code,reactive:n.reactive}}case"Fragment":return{kind:"fragment",children:this.lowerChildren(t.children)};case"Element":return this.lowerElement(t);case"Component":return this.lowerComponent(t);default:return null}}lowerElement(t){let n=t.attributes.find(r=>r.kind==="Attribute"&&r.name==="is");if(t.tag==="component"&&n&&n.value&&n.value.kind==="hole"){let r=t.attributes.filter(o=>o!==n),i=this.lowerComponent({...t,kind:"Component",tag:"Dynamic",tagHole:null,attributes:r});return i.props.unshift({name:"component",kind:"attr",expr:`() => (${this.hole(n.value.hole).code})`}),i}return{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:this.lowerAttributes(t.attributes),children:this.lowerChildren(t.children),static:!1}}lowerComponent(t){let n=t.tagHole!=null?this.hole(t.tagHole).code:t.tag,r=this.lowerAttributes(t.attributes),{slots:i,rest:o}=this.partitionSlots(t.children);for(let[a,c]of i){let p=c.length===1?c[0]:{kind:"fragment",children:c},d={name:a,kind:"attr",expr:this.emit(p),jsxElement:!0},m=r.findIndex(I=>I.name===a);m>=0?r[m]=d:r.push(d)}let l=t.attributes.find(a=>a.kind==="LoadDirective"),s=l?C(`load:${l.strategy}`,l.modifier):void 0;return{kind:"component",name:n,props:r,children:this.lowerChildren(o),...s?{load:s}:{}}}partitionSlots(t){let n=new Map,r=[];for(let i of t){if(i.kind==="Element"||i.kind==="Component"){let o=i.attributes.find(l=>l.kind==="Attribute"&&l.name==="slot");if(o&&o.value&&o.value.kind==="static"){let l={...i,attributes:i.attributes.filter(c=>c!==o)},s=l.kind==="Element"?this.lowerElement(l):this.lowerComponent(l),a=n.get(o.value.value)??[];a.push(s),n.set(o.value.value,a);continue}}r.push(i)}return{slots:n,rest:r}}lowerIf(t,n,r){let i=this.hole(n),o=[{name:"when",kind:"attr",expr:i.code,reactive:i.reactive}];if(r){let s=this.stripAndLower(r,a=>a.kind==="ElseDirective");o.push({name:"fallback",kind:"attr",expr:this.emit(s),jsxElement:!0})}let l=this.stripAndLower(t,s=>s.kind==="IfDirective");return{kind:"component",name:"Show",props:o,children:[l]}}lowerEach(t){let n=t.attributes.find(a=>a.kind==="EachDirective");if(!n||n.kind!=="EachDirective")return this.lowerNode(t);let r=this.hole(n.hole),i=[{name:"each",kind:"attr",expr:r.code,reactive:r.reactive}];if(n.key){let a="static"in n.key?`(item) => item[${JSON.stringify(n.key.static)}]`:this.hole(n.key.hole).code;i.push({name:"by",kind:"attr",expr:a})}let o=this.itemArrow(t),l;if(o){let a={kind:"expr",code:o.body,reactive:o.bodyReactive},c=this.rebuildWithChildren(t,[a]);l=`(${o.params.join(", ")}) => (${this.emit(c)})`}else{let a=this.stripAndLower(t,c=>c.kind==="EachDirective");l=`() => (${this.emit(a)})`}return{kind:"component",name:"For",props:i,children:[{kind:"expr",code:l,reactive:!1}]}}itemArrow(t){let n=t.children.filter(r=>!this.isBlankText(r));return n.length!==1||n[0].kind!=="Expression"?null:this.hole(n[0].hole).arrow??null}stripAndLower(t,n){let r={...t,attributes:t.attributes.filter(i=>!n(i))};return r.kind==="Element"?this.lowerElement(r):this.lowerComponent(r)}rebuildWithChildren(t,n){let r=this.lowerAttributes(t.attributes.filter(i=>i.kind!=="EachDirective"));return t.kind==="Element"?{kind:"element",tag:t.tag,svg:t.namespace==="svg",props:r,children:n,static:!1}:{kind:"component",name:t.tag,props:r,children:n}}lowerAttributes(t){let n=[],r=[],i=!1,o=[],l=!1,s=[];for(let a of t)switch(a.kind){case"IfDirective":case"EachDirective":case"ElseDirective":break;case"Attribute":n.push(this.plainAttr(a));break;case"PropertyBinding":n.push({name:a.name,kind:"prop",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"EventBinding":n.push(this.eventProp(a));break;case"RefBinding":n.push({name:"ref",kind:"ref",expr:this.hole(a.hole).code,reactive:this.hole(a.hole).reactive});break;case"Spread":n.push({name:"",kind:"spread",expr:this.hole(a.hole).code});break;case"ClassDirective":{let c=this.hole(a.hole);r.push(`${JSON.stringify(a.name)}: ${c.code}`),i=i||c.reactive;break}case"StyleDirective":{let c=this.hole(a.hole);o.push(`${JSON.stringify(a.name)}: ${c.code}`),l=l||c.reactive;break}case"BindDirective":n.push(...this.bindProps(a.name,this.hole(a.hole).code));break;case"UseDirective":{let c=a.name??(a.hole!=null?this.hole(a.hole).code:null);if(!c)break;s.push(a.name!=null&&a.hole!=null?`[${c}, () => (${this.hole(a.hole).code})]`:`[${c}]`);break}}return r.length>0&&n.push({name:"classList",kind:"attr",expr:`{ ${r.join(", ")} }`,reactive:i}),o.length>0&&n.push({name:"style",kind:"attr",expr:`{ ${o.join(", ")} }`,reactive:l}),s.length>0&&n.push({name:"use",kind:"attr",expr:`[${s.join(", ")}]`}),n}eventProp(t){let n=t.name.toLowerCase(),r=this.hole(t.hole).code;if(!(t.syntax==="colon"||t.modifiers.length>0))return{name:"on"+se(t.name),kind:"event",event:{name:n,delegated:oe.has(n)},expr:r};let o=this.wrapHandler(r,t.modifiers),l=this.eventOptions(t.modifiers),s=l?`[${o}, ${l}]`:o;return{name:"on:"+n,kind:"attr",expr:s}}wrapHandler(t,n){let r=n.includes("self")?"if (e.target !== e.currentTarget) return; ":"",i=[];return n.includes("prevent")&&i.push("e.preventDefault();"),n.includes("stop")&&i.push("e.stopPropagation();"),!r&&i.length===0?t:`(e) => { ${r}${i.join(" ")} return (${t})(e); }`}eventOptions(t){let n=[];return t.includes("capture")&&n.push("capture: true"),t.includes("once")&&n.push("once: true"),t.includes("passive")&&n.push("passive: true"),n.length?`{ ${n.join(", ")} }`:null}bindProps(t,n){let r=t==="checked",i=r?"change":"input",o=r?"checked":"value",l=`(${n})`;return[{name:t,kind:"attr",expr:`${l}[0]()`,reactive:!0},{name:"on"+se(i),kind:"event",event:{name:i,delegated:oe.has(i)},expr:`(e) => ${l}[1](e.target.${o})`}]}plainAttr(t){let n=t.value,r=t.name;t.name==="class"?r=n&&n.kind==="hole"&&this.hole(n.hole).object?"classList":"className":t.name==="html"&&(r="innerHTML");let o={name:r,kind:"attr"};if(n==null)return o.literal=!0,o;if(n.kind==="static")return o.literal=n.value,o;if(n.kind==="hole"){let a=this.hole(n.hole);return o.expr=a.code,o.reactive=a.reactive,o}let l=!1,s=n.parts.map(a=>{if("text"in a)return Ve(a.text);let c=this.hole(a.hole);return l=l||c.reactive,"${"+c.code+"}"}).join("");return o.expr="`"+s+"`",o.reactive=l,o}};function le(e,t,n,r={}){let{root:i}=(0,ae.parseTemplate)(e,{svg:r.svg});return new X(t,n).lowerRoot(i.children)}var Ge=M.default.default??M.default;function We(e){return Ge(e,{concise:!0}).code}function qe(e,t,n){let r={code:N(e,t,n),reactive:A(e)};if(P.types.isArrowFunctionExpression(e)&&!P.types.isBlockStatement(e.body)){let i=e.body;r.arrow={params:e.params.map(o=>We(o)),body:N(i,t,n),bodyReactive:A(i)}}return P.types.isObjectExpression(e)&&(r.object=!0),r}function ce(e,t,n={}){let r=e.quasi,i=r.expressions.map(o=>qe(o,t,n.onNested));return le(Ue(r),i,t,n)}function Ue(e){let t=[];return e.quasis.forEach((n,r)=>{let i=n.value.cooked??n.value.raw;if(t.push({kind:"static",text:i,start:n.start??0}),r<e.expressions.length){let o=e.expressions[r];t.push({kind:"hole",index:r,start:o.start??0,end:o.end??0})}}),t}function Ke(e){switch(e.kind){case"event":return"event";case"ref":return"ref";case"spread":return"spread";case"class":case"style":return"class-or-style-directive";case"attr":case"prop":return e.reactive?"reactive-prop":e.expr!==void 0?"expression-prop":void 0;default:return"expression-prop"}}function J(e){let t=[],n=new Map,r=i=>{switch(i.kind){case"text":return!0;case"expr":return!1;case"component":case"control":for(let o of i.children)r(o);return!1;case"fragment":for(let o of i.children)r(o);return!1;case"element":{let o=!0;for(let s of i.children)r(s)||(o=!1);let l;for(let s of i.props)if(l=Ke(s),l)break;return!l&&!o&&(l=Ze(i)),i.static=!l,l?n.set(i,l):t.push(i),i.static}default:return!1}};for(let i of Array.isArray(e)?e:[e])r(i);return{staticElements:t,reasons:n}}function Ze(e){for(let t of e.children){if(t.kind==="expr")return"expression-child";if(t.kind==="component")return"component-child";if(t.kind==="control")return"control-child";if(t.kind==="element"&&!t.static||t.kind==="fragment")return"expression-child"}return"expression-child"}function pe(e,t=new Set,n={}){let r=ce(e,t,n);return J(r),r}var Ye="children";function E(e){switch(e.kind){case"call":return!0;case"member":return e.property!==Ye;case"compound":return e.parts.some(E);case"opaque":return!1}}var Qe=new Set(["CallExpression","OptionalCallExpression"]),et=new Set(["MemberExpression","OptionalMemberExpression"]);function b(e){if(!e)return{kind:"opaque"};if(Qe.has(e.type))return{kind:"call"};if(et.has(e.type)){let t=e.property;return{kind:"member",property:!(e.computed===!0)&&t?.type==="Identifier"?t.name:null}}return e.type==="ConditionalExpression"?{kind:"compound",parts:[e.test,e.consequent,e.alternate].map(R)}:e.type==="LogicalExpression"||e.type==="BinaryExpression"?{kind:"compound",parts:[e.left,e.right].map(R)}:e.type==="TemplateLiteral"?{kind:"compound",parts:e.expressions.map(R)}:e.type==="ObjectExpression"?{kind:"compound",parts:e.properties.filter(n=>(n.type==="ObjectProperty"||n.type==="Property")&&n.computed!==!0).map(n=>R(n.value))}:e.type==="ArrayExpression"?{kind:"compound",parts:e.elements.filter(n=>n!=null&&n.type!=="SpreadElement").map(R)}:{kind:"opaque"}}var R=e=>b(e);var tt=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]),nt=/^on[A-Z]/,rt=new Set(["click","dblclick","input","change","submit","focus","blur","keydown","keyup","keypress","mousedown","mouseup"]),me=e=>E(b(e));function S(e){if(e.type==="StringLiteral"||e.type==="NumericLiteral"||e.type==="BooleanLiteral"||e.type==="Literal"&&(typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"))return e.value}var H=e=>!!e&&typeof S(e)=="string";function it(e,t){return e.type==="JSXIdentifier"?{tag:e.name,component:e.name[0]!==e.name[0].toLowerCase()}:e.type==="JSXMemberExpression"?{tag:t.code(e),component:!0}:e.type==="JSXNamespacedName"?{tag:`${e.namespace.name}:${e.name.name}`,component:!1}:{tag:"div",component:!1}}function _(e){return e.type==="JSXIdentifier"?e.name==="class"?"className":e.name:e.type==="JSXNamespacedName"?`${e.namespace.name}:${e.name.name}`:"unknown"}function ot(e,t){let n=_(e.name),r=nt.test(n),i=r||n.startsWith("on:")||n==="ref",l={name:n,kind:r?"event":"attr"};if(r){let a=n.slice(2).toLowerCase();l.event={name:a,delegated:rt.has(a)}}let s=e.value;if(s==null)return l.literal=!0,l;if(H(s))return l.literal=S(s),l;if(s.type==="JSXExpressionContainer"&&s.expression?.type!=="JSXEmptyExpression"){let a=s.expression,c=S(a);return c!==void 0?(l.literal=c,l):(l.expr=t.code(a),l.reactive=i?!1:me(a),(a.type==="JSXElement"||a.type==="JSXFragment")&&(l.jsxElement=!0),l)}return l.literal=!0,l}function de(e,t){let n=e.value;return n==null?null:H(n)?JSON.stringify(S(n)):n.type==="JSXExpressionContainer"&&n.expression?.type!=="JSXEmptyExpression"?t.code(n.expression):null}function st(e,t){let n=[],r=[];for(let i of e){if(i.type==="JSXSpreadAttribute"){n.push({name:"",kind:"spread",expr:t.code(i.argument)});continue}if(i.type!=="JSXAttribute"||O(_(i.name)))continue;let o=i.name.type==="JSXNamespacedName"?i.name.namespace.name:null;if(o==="use"){let l=i.name.name.name;t.used.add(l);let s=de(i,t);r.push(s!=null?`[${l}, () => (${s})]`:`[${l}]`);continue}if(o==="oncapture"){let l=i.name.name.name.toLowerCase(),s=de(i,t)??"undefined";n.push({name:"on:"+l,kind:"attr",expr:`[${s}, { capture: true }]`});continue}n.push(ot(i,t))}return r.length>0&&n.push({name:"use",kind:"attr",expr:`[${r.join(", ")}]`}),n}function ue(e,t){let n=[];for(let r of e)if(r.type==="JSXText"){let i=y(r.value);i&&n.push({kind:"text",value:i})}else if(r.type==="JSXExpressionContainer"){if(r.expression?.type!=="JSXEmptyExpression"){let i=r.expression;n.push({kind:"expr",code:t.code(i),reactive:me(i)})}}else r.type==="JSXElement"||r.type==="JSXFragment"?n.push(fe(r,t)):r.type==="JSXSpreadChild"&&n.push({kind:"expr",code:t.code(r.expression),reactive:!1});return n}function at(e){for(let t of e){if(t.type!=="JSXAttribute")continue;let n=_(t.name);if(O(n)){if(t.value&&!H(t.value))throw new f(`'${n}' needs a literal value, not an expression — the strategy is compile-time.`);return C(n,t.value?S(t.value):null)}}}function fe(e,t){if(e.type==="JSXFragment")return{kind:"fragment",children:ue(e.children,t)};let{tag:n,component:r}=it(e.openingElement.name,t),i=st(e.openingElement.attributes,t),o=ue(e.children,t);if(r){let l=at(e.openingElement.attributes);return{kind:"component",name:n,props:i,children:o,...l?{load:l}:{}}}return{kind:"element",tag:n,svg:tt.has(n),props:i,children:o,static:!1}}function he(e,t){let n=fe(e,t);return J(n),n}var lt=B.default.default??B.default;function ge(e){return lt(e,{concise:!0}).code}function ct(e,t,n){let r=u.types.cloneNode(e,!0),i=u.types.file(u.types.program([u.types.expressionStatement(r)])),o=!1,l=(s,a,c)=>{for(let p of c)t.add(p);s.replaceWith(u.template.expression(a,{placeholderPattern:!1,plugins:["typescript"]})()),s.skip(),o=!0};return(0,u.traverse)(i,{"JSXElement|JSXFragment"(s){let a=s.node,c=ve(a,t,n);n?.(c);let{code:p,imports:d,templates:m}=x.emit(c,{});l(s,k(p,m),d)},TaggedTemplateExpression(s){let a=s.node.tag;if(!u.types.isIdentifier(a)||a.name!=="html"&&a.name!=="svg")return;let c=pe(s.node,t,{svg:a.name==="svg",onNested:n});n?.(c);let{code:p,imports:d,templates:m}=x.emit(c,{});l(s,k(p,m),d)}}),o?i.program.body[0].expression:e}function N(e,t,n){return ge(ct(e,t,n))}var pt=new Set(["svg","path","circle","rect","line","polygon","polyline","ellipse","g","defs","clipPath","text"]);function A(e){return E(b(e))}function ve(e,t=new Set,n){return he(e,{code:i=>i.type==="JSXMemberExpression"?ge(i):N(i,t,n),used:t})}
|
|
@@ -15,20 +15,22 @@
|
|
|
15
15
|
import { types as t } from '@babel/core';
|
|
16
16
|
import type { IRNode } from '../../ir/nodes.js';
|
|
17
17
|
/** Stringify an expression, compiling any JSX nested inside it first. */
|
|
18
|
-
export declare function genExpr(node: t.Expression, used: Set<string
|
|
19
|
-
export declare const SVG_TAGS: Set<string>;
|
|
18
|
+
export declare function genExpr(node: t.Expression, used: Set<string>, onNested?: NestedHook): string;
|
|
20
19
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
20
|
+
* Called with the IR of JSX (or a template) found inside an expression.
|
|
21
|
+
*
|
|
22
|
+
* That IR is compiled and thrown away during the walk, so anything the module
|
|
23
|
+
* needs because of it — a component import, a delegated event — has to be taken
|
|
24
|
+
* off it here or it is lost. Without this, `{(b) => <Input/>}` emitted a
|
|
25
|
+
* reference to `Input` that nothing imported.
|
|
24
26
|
*/
|
|
27
|
+
export type NestedHook = (ir: IRNode) => void;
|
|
28
|
+
export declare const SVG_TAGS: Set<string>;
|
|
25
29
|
export declare function isReactiveExpr(node: t.Expression): boolean;
|
|
26
|
-
/** Canonical JSX text cleaning — kept identical to plugin.ts cleanJSXText. */
|
|
27
|
-
export declare function cleanJSXText(value: string): string;
|
|
28
30
|
/**
|
|
29
|
-
* Build IR from a
|
|
30
|
-
*
|
|
31
|
-
*
|
|
31
|
+
* Build IR from a JSX node. The builder is shared (lower/jsx.ts); what this
|
|
32
|
+
* front-end supplies is how an expression becomes source — `genExpr`, which also
|
|
33
|
+
* compiles any JSX or `` html`` `` nested inside it.
|
|
32
34
|
*/
|
|
33
|
-
export declare function buildIR(node: t.JSXElement | t.JSXFragment, used?: Set<string
|
|
35
|
+
export declare function buildIR(node: t.JSXElement | t.JSXFragment, used?: Set<string>, onNested?: NestedHook): IRNode;
|
|
34
36
|
//# sourceMappingURL=build-ir.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-ir.d.ts","sourceRoot":"","sources":["../../../src/frontend/babel/build-ir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,KAAK,IAAI,CAAC,EAAsB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"build-ir.d.ts","sourceRoot":"","sources":["../../../src/frontend/babel/build-ir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,KAAK,IAAI,CAAC,EAAsB,MAAM,aAAa,CAAC;AAI7D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAwDhD,yEAAyE;AACzE,wBAAgB,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,UAAU,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,EAAE,UAAU,GAAG,MAAM,CAE5F;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;AAE9C,eAAO,MAAM,QAAQ,aAGnB,CAAC;AA2BH,wBAAgB,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,UAAU,GAAG,OAAO,CAE1D;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CACrB,IAAI,EAAE,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,WAAW,EAClC,IAAI,GAAE,GAAG,CAAC,MAAM,CAAa,EAC7B,QAAQ,CAAC,EAAE,UAAU,GACpB,MAAM,CAWR"}
|
|
@@ -16,8 +16,9 @@ import { types as t, traverse, template } from '@babel/core';
|
|
|
16
16
|
import _generate from '@babel/generator';
|
|
17
17
|
import { imperativeBackend, inlineTemplates } from '../../codegen/backends/imperative.js';
|
|
18
18
|
import { buildIRFromLit } from './build-ir-lit.js';
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
19
|
+
import { buildJsxIR } from '../../lower/jsx.js';
|
|
20
|
+
import { isReactiveShape } from '../../analyze/reactive-expr.js';
|
|
21
|
+
import { shapeOf } from '../../analyze/expr-shape.js';
|
|
21
22
|
// @babel/generator's ESM/CJS interop default (its types aren't callable under nodenext).
|
|
22
23
|
const generate = _generate.default ?? _generate;
|
|
23
24
|
/** Stringify an AST node back to source. */
|
|
@@ -29,7 +30,7 @@ function gen(node) {
|
|
|
29
30
|
* for it (build-ir -> emit), so the resulting expression is plain JS. Runtime
|
|
30
31
|
* symbols used by the nested code are added to `used`.
|
|
31
32
|
*/
|
|
32
|
-
function transformNestedJSX(node, used) {
|
|
33
|
+
function transformNestedJSX(node, used, onNested) {
|
|
33
34
|
const clone = t.cloneNode(node, true);
|
|
34
35
|
const file = t.file(t.program([t.expressionStatement(clone)]));
|
|
35
36
|
let changed = false;
|
|
@@ -45,7 +46,11 @@ function transformNestedJSX(node, used) {
|
|
|
45
46
|
traverse(file, {
|
|
46
47
|
'JSXElement|JSXFragment'(path) {
|
|
47
48
|
const jsx = path.node;
|
|
48
|
-
|
|
49
|
+
// Resolve before emitting: the emitted call refers to the component by name,
|
|
50
|
+
// and whoever injects the import has to have seen it.
|
|
51
|
+
const nestedIR = buildIR(jsx, used, onNested);
|
|
52
|
+
onNested?.(nestedIR);
|
|
53
|
+
const { code, imports, templates } = imperativeBackend.emit(nestedIR, {});
|
|
49
54
|
emitInto(path, inlineTemplates(code, templates), imports);
|
|
50
55
|
},
|
|
51
56
|
// Nested lit templates compose: ${cond ? html`…` : html`…`},
|
|
@@ -54,7 +59,8 @@ function transformNestedJSX(node, used) {
|
|
|
54
59
|
const tag = path.node.tag;
|
|
55
60
|
if (!t.isIdentifier(tag) || (tag.name !== 'html' && tag.name !== 'svg'))
|
|
56
61
|
return;
|
|
57
|
-
const ir = buildIRFromLit(path.node, used, { svg: tag.name === 'svg' });
|
|
62
|
+
const ir = buildIRFromLit(path.node, used, { svg: tag.name === 'svg', onNested });
|
|
63
|
+
onNested?.(ir);
|
|
58
64
|
const { code, imports, templates } = imperativeBackend.emit(ir, {});
|
|
59
65
|
emitInto(path, inlineTemplates(code, templates), imports);
|
|
60
66
|
},
|
|
@@ -64,8 +70,8 @@ function transformNestedJSX(node, used) {
|
|
|
64
70
|
: node;
|
|
65
71
|
}
|
|
66
72
|
/** Stringify an expression, compiling any JSX nested inside it first. */
|
|
67
|
-
export function genExpr(node, used) {
|
|
68
|
-
return gen(transformNestedJSX(node, used));
|
|
73
|
+
export function genExpr(node, used, onNested) {
|
|
74
|
+
return gen(transformNestedJSX(node, used, onNested));
|
|
69
75
|
}
|
|
70
76
|
export const SVG_TAGS = new Set([
|
|
71
77
|
'svg', 'path', 'circle', 'rect', 'line', 'polygon', 'polyline',
|
|
@@ -96,219 +102,23 @@ function attrName(name) {
|
|
|
96
102
|
return `${name.namespace.name}:${name.name.name}`;
|
|
97
103
|
return 'unknown';
|
|
98
104
|
}
|
|
99
|
-
/**
|
|
100
|
-
* Reactivity heuristic, aligned with the babel transform: calls and member
|
|
101
|
-
* accesses (e.g. `count()`, `store.value`) are wired reactively; bare
|
|
102
|
-
* identifiers and literals are passed through as-is.
|
|
103
|
-
*/
|
|
104
105
|
export function isReactiveExpr(node) {
|
|
105
|
-
|
|
106
|
-
return true;
|
|
107
|
-
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
|
108
|
-
// `props.children` (any `.children` access) is a stable subtree reference,
|
|
109
|
-
// not a reactive value. Compiling it to a `() => props.children` thunk adds
|
|
110
|
-
// an insert layer that fully unwraps the children's Suspense/memo to a static
|
|
111
|
-
// node, severing the reactive binding — so a nested lazy/Suspense that
|
|
112
|
-
// resolves later never propagates up through the component-children hop.
|
|
113
|
-
// Passing it through non-reactive (insert(el, props.children)) keeps the
|
|
114
|
-
// child's memo intact so insert binds to it (mirrors a direct <Outlet/>).
|
|
115
|
-
if (!node.computed && t.isIdentifier(node.property, { name: 'children' }))
|
|
116
|
-
return false;
|
|
117
|
-
return true;
|
|
118
|
-
}
|
|
119
|
-
if (t.isConditionalExpression(node)) {
|
|
120
|
-
return isReactiveExpr(node.test) || isReactiveExpr(node.consequent) || isReactiveExpr(node.alternate);
|
|
121
|
-
}
|
|
122
|
-
if (t.isLogicalExpression(node) || t.isBinaryExpression(node)) {
|
|
123
|
-
return isReactiveExpr(node.left) || isReactiveExpr(node.right);
|
|
124
|
-
}
|
|
125
|
-
if (t.isTemplateLiteral(node))
|
|
126
|
-
return node.expressions.some((e) => isReactiveExpr(e));
|
|
127
|
-
// Object/array literals are reactive when any value inside is — so
|
|
128
|
-
// `class=${{ active: active() }}` / `style=${{ width: w() }}` react per update.
|
|
129
|
-
if (t.isObjectExpression(node)) {
|
|
130
|
-
return node.properties.some((p) => t.isObjectProperty(p) && !p.computed && isReactiveExpr(p.value));
|
|
131
|
-
}
|
|
132
|
-
if (t.isArrayExpression(node)) {
|
|
133
|
-
return node.elements.some((e) => e != null && !t.isSpreadElement(e) && isReactiveExpr(e));
|
|
134
|
-
}
|
|
135
|
-
return false;
|
|
136
|
-
}
|
|
137
|
-
function buildAttr(attr, used) {
|
|
138
|
-
const name = attrName(attr.name);
|
|
139
|
-
const isEvent = EVENT_RE.test(name);
|
|
140
|
-
// on: passes through to the runtime as a native listener; a handler, never reactive.
|
|
141
|
-
// `ref` joins them: the runtime CALLS it with the element, so wrapping it in a thunk
|
|
142
|
-
// means the thunk gets called and the real ref never sees the element — the callback
|
|
143
|
-
// silently does nothing, along with everything that depended on it.
|
|
144
|
-
const isHandler = isEvent || name.startsWith('on:') || name === 'ref';
|
|
145
|
-
const kind = isEvent ? 'event' : 'attr';
|
|
146
|
-
const base = { name, kind };
|
|
147
|
-
if (isEvent) {
|
|
148
|
-
base.event = { name: name.slice(2).toLowerCase(), delegated: DELEGATED.has(name.slice(2).toLowerCase()) };
|
|
149
|
-
}
|
|
150
|
-
const v = attr.value;
|
|
151
|
-
if (v == null) {
|
|
152
|
-
base.literal = true; // valueless attribute
|
|
153
|
-
return base;
|
|
154
|
-
}
|
|
155
|
-
if (t.isStringLiteral(v)) {
|
|
156
|
-
base.literal = v.value;
|
|
157
|
-
return base;
|
|
158
|
-
}
|
|
159
|
-
if (t.isJSXExpressionContainer(v) && !t.isJSXEmptyExpression(v.expression)) {
|
|
160
|
-
const expr = v.expression;
|
|
161
|
-
if (t.isStringLiteral(expr) || t.isNumericLiteral(expr) || t.isBooleanLiteral(expr)) {
|
|
162
|
-
base.literal = expr.value;
|
|
163
|
-
return base;
|
|
164
|
-
}
|
|
165
|
-
base.expr = genExpr(expr, used);
|
|
166
|
-
base.reactive = isHandler ? false : isReactiveExpr(expr);
|
|
167
|
-
if (t.isJSXElement(expr) || t.isJSXFragment(expr))
|
|
168
|
-
base.jsxElement = true;
|
|
169
|
-
return base;
|
|
170
|
-
}
|
|
171
|
-
base.literal = true;
|
|
172
|
-
return base;
|
|
173
|
-
}
|
|
174
|
-
/** Attribute value as JS code (expr or string), or null when valueless. */
|
|
175
|
-
function attrExprCode(attr, used) {
|
|
176
|
-
const v = attr.value;
|
|
177
|
-
if (v == null)
|
|
178
|
-
return null;
|
|
179
|
-
if (t.isStringLiteral(v))
|
|
180
|
-
return JSON.stringify(v.value);
|
|
181
|
-
if (t.isJSXExpressionContainer(v) && !t.isJSXEmptyExpression(v.expression)) {
|
|
182
|
-
return genExpr(v.expression, used);
|
|
183
|
-
}
|
|
184
|
-
return null;
|
|
185
|
-
}
|
|
186
|
-
function buildProps(attrs, used) {
|
|
187
|
-
const props = [];
|
|
188
|
-
const usePairs = []; // Solid `use:name` directives → one `use` prop
|
|
189
|
-
for (const a of attrs) {
|
|
190
|
-
if (t.isJSXSpreadAttribute(a)) {
|
|
191
|
-
props.push({ name: '', kind: 'spread', expr: genExpr(a.argument, used) });
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
if (!t.isJSXAttribute(a))
|
|
195
|
-
continue;
|
|
196
|
-
// `load:` is a directive, not a prop — the resolve pass reads it off the node.
|
|
197
|
-
if (isLoadDirective(attrName(a.name)))
|
|
198
|
-
continue;
|
|
199
|
-
const ns = t.isJSXNamespacedName(a.name) ? a.name.namespace.name : null;
|
|
200
|
-
// use:name / use:name={opts} -> [dir, () => opts] pair; dir is an in-scope fn
|
|
201
|
-
if (ns === 'use') {
|
|
202
|
-
const dir = a.name.name.name;
|
|
203
|
-
used.add(dir); // keep the import
|
|
204
|
-
const opts = attrExprCode(a, used);
|
|
205
|
-
// parens around the body so an object literal isn't read as a block
|
|
206
|
-
usePairs.push(opts != null ? `[${dir}, () => (${opts})]` : `[${dir}]`);
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
// oncapture:name -> native on:name with { capture: true }
|
|
210
|
-
if (ns === 'oncapture') {
|
|
211
|
-
const evt = a.name.name.name.toLowerCase();
|
|
212
|
-
const h = attrExprCode(a, used) ?? 'undefined';
|
|
213
|
-
props.push({ name: 'on:' + evt, kind: 'attr', expr: `[${h}, { capture: true }]` });
|
|
214
|
-
continue;
|
|
215
|
-
}
|
|
216
|
-
props.push(buildAttr(a, used));
|
|
217
|
-
}
|
|
218
|
-
// one `use` prop = array of [dir, accessor?] pairs
|
|
219
|
-
if (usePairs.length > 0)
|
|
220
|
-
props.push({ name: 'use', kind: 'attr', expr: `[${usePairs.join(', ')}]` });
|
|
221
|
-
return props;
|
|
222
|
-
}
|
|
223
|
-
/** Canonical JSX text cleaning — kept identical to plugin.ts cleanJSXText. */
|
|
224
|
-
export function cleanJSXText(value) {
|
|
225
|
-
const lines = value.split(/\r\n|\n|\r/);
|
|
226
|
-
let lastNonEmpty = 0;
|
|
227
|
-
for (let i = 0; i < lines.length; i++) {
|
|
228
|
-
if (/[^ \t]/.test(lines[i]))
|
|
229
|
-
lastNonEmpty = i;
|
|
230
|
-
}
|
|
231
|
-
let out = '';
|
|
232
|
-
for (let i = 0; i < lines.length; i++) {
|
|
233
|
-
let line = lines[i].replace(/\t/g, ' ');
|
|
234
|
-
if (i !== 0)
|
|
235
|
-
line = line.replace(/^ +/, '');
|
|
236
|
-
if (i !== lines.length - 1)
|
|
237
|
-
line = line.replace(/ +$/, '');
|
|
238
|
-
if (!line)
|
|
239
|
-
continue;
|
|
240
|
-
if (i !== lastNonEmpty)
|
|
241
|
-
line += ' ';
|
|
242
|
-
out += line;
|
|
243
|
-
}
|
|
244
|
-
return out;
|
|
245
|
-
}
|
|
246
|
-
function buildChildren(children, used) {
|
|
247
|
-
const out = [];
|
|
248
|
-
for (const child of children) {
|
|
249
|
-
if (t.isJSXText(child)) {
|
|
250
|
-
// Canonical JSX whitespace (kept in sync with plugin.ts cleanJSXText):
|
|
251
|
-
// drop whitespace-only text spanning a newline so a lone child stays lone
|
|
252
|
-
// (an array insert won't reactively bind a memo/component inside it).
|
|
253
|
-
const text = cleanJSXText(child.value);
|
|
254
|
-
if (text)
|
|
255
|
-
out.push({ kind: 'text', value: text });
|
|
256
|
-
}
|
|
257
|
-
else if (t.isJSXExpressionContainer(child)) {
|
|
258
|
-
if (!t.isJSXEmptyExpression(child.expression)) {
|
|
259
|
-
const expr = child.expression;
|
|
260
|
-
out.push({ kind: 'expr', code: genExpr(expr, used), reactive: isReactiveExpr(expr) });
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
else if (t.isJSXElement(child)) {
|
|
264
|
-
out.push(buildIRNode(child, used));
|
|
265
|
-
}
|
|
266
|
-
else if (t.isJSXFragment(child)) {
|
|
267
|
-
out.push(buildIRNode(child, used));
|
|
268
|
-
}
|
|
269
|
-
else if (t.isJSXSpreadChild(child)) {
|
|
270
|
-
out.push({ kind: 'expr', code: genExpr(child.expression, used), reactive: false });
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return out;
|
|
106
|
+
return isReactiveShape(shapeOf(node));
|
|
274
107
|
}
|
|
275
108
|
/**
|
|
276
|
-
* Build IR from a
|
|
277
|
-
*
|
|
278
|
-
*
|
|
109
|
+
* Build IR from a JSX node. The builder is shared (lower/jsx.ts); what this
|
|
110
|
+
* front-end supplies is how an expression becomes source — `genExpr`, which also
|
|
111
|
+
* compiles any JSX or `` html`` `` nested inside it.
|
|
279
112
|
*/
|
|
280
|
-
export function buildIR(node, used = new Set()) {
|
|
281
|
-
const ir =
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
113
|
+
export function buildIR(node, used = new Set(), onNested) {
|
|
114
|
+
const ir = buildJsxIR(node, {
|
|
115
|
+
code: (n) =>
|
|
116
|
+
// A member-expression tag (`<ns.Foo/>`) is not an Expression, so it cannot go
|
|
117
|
+
// through the nested-JSX compile — it only ever needs printing.
|
|
118
|
+
n.type === 'JSXMemberExpression'
|
|
119
|
+
? gen(n)
|
|
120
|
+
: genExpr(n, used, onNested),
|
|
121
|
+
used,
|
|
122
|
+
});
|
|
285
123
|
return ir;
|
|
286
124
|
}
|
|
287
|
-
function buildIRNode(node, used) {
|
|
288
|
-
if (t.isJSXFragment(node)) {
|
|
289
|
-
return { kind: 'fragment', children: buildChildren(node.children, used) };
|
|
290
|
-
}
|
|
291
|
-
const { tag, component } = tagInfo(node.openingElement.name);
|
|
292
|
-
const props = buildProps(node.openingElement.attributes, used);
|
|
293
|
-
const children = buildChildren(node.children, used);
|
|
294
|
-
if (component) {
|
|
295
|
-
const load = readLoad(node.openingElement.attributes);
|
|
296
|
-
return { kind: 'component', name: tag, props, children, ...(load ? { load } : {}) };
|
|
297
|
-
}
|
|
298
|
-
return { kind: 'element', tag, svg: SVG_TAGS.has(tag), props, children, static: false };
|
|
299
|
-
}
|
|
300
|
-
/** The `load:` strategy written on a component tag, if any. */
|
|
301
|
-
function readLoad(attrs) {
|
|
302
|
-
for (const a of attrs) {
|
|
303
|
-
if (!t.isJSXAttribute(a))
|
|
304
|
-
continue;
|
|
305
|
-
const name = attrName(a.name);
|
|
306
|
-
if (!isLoadDirective(name))
|
|
307
|
-
continue;
|
|
308
|
-
if (a.value && !t.isStringLiteral(a.value)) {
|
|
309
|
-
throw new LoadDirectiveError(`'${name}' needs a literal value, not an expression — the strategy is compile-time.`);
|
|
310
|
-
}
|
|
311
|
-
return parseLoadDirective(name, a.value ? a.value.value : null);
|
|
312
|
-
}
|
|
313
|
-
return undefined;
|
|
314
|
-
}
|