@unocss/runtime 0.49.7 → 0.50.0

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/core.global.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";(()=>{function Te(t){let e=t.length,r=-1,n,s="",i=t.charCodeAt(0);for(;++r<e;){if(n=t.charCodeAt(r),n===0){s+="\uFFFD";continue}if(n===44){s+="\\,";continue}if(n>=1&&n<=31||n===127||r===0&&n>=48&&n<=57||r===1&&n>=48&&n<=57&&i===45){s+=`\\${n.toString(16)} `;continue}if(r===0&&e===1&&n===45){s+=`\\${t.charAt(r)}`;continue}if(n>=128||n===45||n===95||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122){s+=t.charAt(r);continue}s+=`\\${t.charAt(r)}`}return s}var K=Te;function v(t=[]){return Array.isArray(t)?t:[t]}function j(t){return Array.from(new Set(t))}function b(t){return typeof t=="string"}function L(t){return b(t)?t:(Array.isArray(t)?t:Object.entries(t)).filter(e=>e[1]!=null)}function te(t){return Array.isArray(t)?t.find(e=>!Array.isArray(e)||Array.isArray(e[0]))?t.map(e=>L(e)):[t]:[L(t)]}function be(t){return t.filter(([e,r],n)=>{if(e.startsWith("$$"))return!1;for(let s=n-1;s>=0;s--)if(t[s][0]===e&&t[s][1]===r)return!1;return!0})}function F(t){return t==null?"":be(t).map(([e,r])=>r!=null?`${e}:${r};`:void 0).filter(Boolean).join("")}function H(t){return t&&typeof t=="object"&&!Array.isArray(t)}function N(t,e){let r=t,n=e;if(Array.isArray(r))return[...n];let s={...r};return H(r)&&H(n)&&Object.keys(n).forEach(i=>{H(r[i])&&H(n[i])||Array.isArray(r[i])&&Array.isArray(n[i])?s[i]=N(r[i],n[i]):Object.assign(s,{[i]:n[i]})}),s}function k(t){let e,r,n;if(Array.isArray(t)){for(r=Array(e=t.length);e--;)r[e]=(n=t[e])&&typeof n=="object"?k(n):n;return r}if(Object.prototype.toString.call(t)==="[object Object]"){r={};for(e in t)e==="__proto__"?Object.defineProperty(r,e,{value:k(t[e]),configurable:!0,enumerable:!0,writable:!0}):r[e]=(n=t[e])&&typeof n=="object"?k(n):n;return r}return t}function re(t){return b(t[0])}function ne(t){return b(t[0])}var Re=/[\w\u00A0-\uFFFF-_:%-?]/,Y="$$shortcut-no-merge";function se(t=""){return Re.test(t)}function ie(t){return typeof t=="function"?{match:t}:t}function q(t){return t.length===3}function oe(t){return t!=null}function ae(){}var G=class{_map=new Map;get(e,r){let n=this._map.get(e);if(n)return n.get(r)}getFallback(e,r,n){let s=this._map.get(e);return s||(s=new Map,this._map.set(e,s)),s.has(r)||s.set(r,n),s.get(r)}set(e,r,n){let s=this._map.get(e);return s||(s=new Map,this._map.set(e,s)),s.set(r,n),this}has(e,r){return this._map.get(e)?.has(r)}delete(e,r){return this._map.get(e)?.delete(r)||!1}deleteTop(e){return this._map.delete(e)}map(e){return Array.from(this._map.entries()).flatMap(([r,n])=>Array.from(n.entries()).map(([s,i])=>e(i,r,s)))}};var B={};function ve(t=["-",":"]){let e=t.join("|");return B[e]||(B[e]=new RegExp(`((?:[!@\\w+:_/-]|\\[&?>?:?\\S*\\])+?)(${e})\\(((?:[~!\\w\\s:/\\\\,%#.$?-]|\\[.*?\\])+?)\\)(?!\\s*?=>)`,"gm")),B[e].lastIndex=0,B[e]}function Ae(t,e=["-",":"],r=5){let n=ve(e),s=!1,i=t.toString(),o=new Set;do{let a=i;i=i.replace(n,(u,l,c,p)=>e.includes(c)?(o.add(l+c),p.split(/\s/g).filter(Boolean).map(g=>g==="~"?l:g.replace(/^(!?)(.*)/,`$1${l}${c}$2`)).join(" ")):u),s=i!==a,r-=1}while(s&&r);return{prefixes:Array.from(o),expanded:i,hasChanged:s}}function ce(t,e=["-",":"],r=5){let{expanded:n}=Ae(t.toString(),e,r);return typeof t=="string"?n:t.length()?t.overwrite(0,t.length(),n):t}var le=new Set;function ue(t){le.has(t)||(console.warn("[unocss]",t),le.add(t))}var we=/\\?[\s'"`;{}]+/g,Z=/\[(\\\W|[\w-])+:['"]?\S+?['"]?\]/g,Ue=new RegExp(`^${Z.source}$`),$e=t=>{let e=new Set;for(let r of t.matchAll(Z))t[r.index-1]?.match(/^[\s'"`]/)&&e.add(r[0]);return t.split(we).forEach(r=>{se(r)&&!Ue.test(r)&&e.add(r)}),[...e]},J={name:"split",order:0,extract({code:t}){return $e(t)}};function fe(){return{events:{},emit(t,...e){(this.events[t]||[]).forEach(r=>r(...e))},on(t,e){return(this.events[t]=this.events[t]||[]).push(e),()=>this.events[t]=(this.events[t]||[]).filter(r=>r!==e)}}}var z="default",I="preflights",Ve="shortcuts",pe={[I]:-100,[Ve]:-10,[z]:0};function de(t){return v(t).flatMap(e=>Array.isArray(e)?[e]:Object.entries(e))}function Me(t){let e=t.shortcuts?de(t.shortcuts):void 0;if(t.shortcuts=e,t.prefix||t.layer){let r=n=>{n[2]||(n[2]={});let s=n[2];s.prefix==null&&t.prefix&&(s.prefix=v(t.prefix)),s.layer==null&&t.layer&&(s.layer=t.layer)};e?.forEach(r),t.rules?.forEach(r)}return t}function Q(t={},e={}){let r=Object.assign({},e,t),n=(r.presets||[]).flatMap(v).map(Me),s=[...n.filter(f=>f.enforce==="pre"),...n.filter(f=>!f.enforce),...n.filter(f=>f.enforce==="post")],i=Object.assign(pe,...n.map(f=>f.layers),t.layers);function o(f){return j([...s.flatMap(d=>v(d[f]||[])),...v(r[f]||[])])}let a=o("extractors");a.length||a.push(J),a.sort((f,d)=>(f.order||0)-(d.order||0));let u=o("rules"),l={},c=u.length,p=u.map((f,d)=>{if(re(f)){v(f[2]?.prefix||"").forEach(y=>{l[y+f[0]]=[d,f[1],f[2],f]});return}return[d,...f]}).filter(Boolean).reverse(),g=k([...s.map(f=>f.theme||{}),r.theme||{}].reduce((f,d)=>N(f,d),{}));o("extendTheme").forEach(f=>f(g));let E={templates:j(s.map(f=>v(f.autocomplete?.templates)).flat()),extractors:s.map(f=>v(f.autocomplete?.extractors)).flat().sort((f,d)=>(f.order||0)-(d.order||0))},A=v(o("separators"));return A.length||(A=[":","-"]),{mergeSelectors:!0,warn:!0,blocklist:[],sortLayers:f=>f,...r,presets:s,envMode:r.envMode||"build",shortcutsLayer:r.shortcutsLayer||"shortcuts",layers:i,theme:g,rulesSize:c,rulesDynamic:p,rulesStaticMap:l,preprocess:o("preprocess"),postprocess:o("postprocess"),preflights:o("preflights"),autocomplete:E,variants:o("variants").map(ie),shortcuts:de(o("shortcuts")).reverse(),extractors:a,safelist:o("safelist"),separators:A}}var he="0.49.7";var X=class{constructor(e={},r={}){this.userConfig=e;this.defaults=r;this.config=Q(e,r),this.events.emit("config",this.config)}version=he;_cache=new Map;config;blocked=new Set;parentOrders=new Map;events=fe();setConfig(e,r){e&&(r&&(this.defaults=r),this.userConfig=e,this.blocked.clear(),this.parentOrders.clear(),this._cache.clear(),this.config=Q(e,this.defaults),this.events.emit("config",this.config))}async applyExtractors(e,r,n=new Set){let s={get original(){return e},code:e,id:r};for(let i of this.config.extractors){let o=await i.extract(s);if(o)for(let a of o)n.add(a)}return n}makeContext(e,r){let n={rawSelector:e,currentSelector:r[1],theme:this.config.theme,generator:this,variantHandlers:r[2],constructCSS:(...s)=>this.constructCustomCSS(n,...s),variantMatch:r};return n}async parseToken(e,r){if(this.blocked.has(e))return;let n=`${e}${r?` ${r}`:""}`;if(this._cache.has(n))return this._cache.get(n);let s=e;for(let l of this.config.preprocess)s=l(e);if(this.isBlocked(s)){this.blocked.add(e),this._cache.set(n,null);return}let i=this.matchVariants(e,s);if(!i||this.isBlocked(i[1])){this.blocked.add(e),this._cache.set(n,null);return}let o=this.makeContext(e,[r||i[0],i[1],i[2],i[3]]);this.config.details&&(o.variants=[...i[3]]);let a=this.expandShortcut(o.currentSelector,o),u=a?await this.stringifyShortcuts(o.variantMatch,o,a[0],a[1]):(await this.parseUtil(o.variantMatch,o))?.map(l=>this.stringifyUtil(l,o)).filter(oe);if(u?.length)return this._cache.set(n,u),u;this._cache.set(n,null)}async generate(e,r={}){let{id:n,scope:s,preflights:i=!0,safelist:o=!0,minify:a=!1}=r,u=b(e)?await this.applyExtractors(e,n):Array.isArray(e)?new Set(e):e;o&&this.config.safelist.forEach(h=>u.add(h));let l=a?"":`
2
- `,c=new Set([z]),p=new Set,g=new Map,E={},A=Array.from(u).map(async h=>{if(p.has(h))return;let T=await this.parseToken(h);if(T!=null){p.add(h);for(let S of T){let w=S[3]||"",$=S[4]?.layer;g.has(w)||g.set(w,[]),g.get(w).push(S),$&&c.add($)}}});await Promise.all(A),await(async()=>{if(!i)return;let h={generator:this,theme:this.config.theme},T=new Set([]);this.config.preflights.forEach(({layer:S=I})=>{c.add(S),T.add(S)}),E=Object.fromEntries(await Promise.all(Array.from(T).map(async S=>{let $=(await Promise.all(this.config.preflights.filter(_=>(_.layer||I)===S).map(async _=>await _.getCSS(h)))).filter(Boolean).join(l);return[S,$]})))})();let f=this.config.sortLayers(Array.from(c).sort((h,T)=>(this.config.layers[h]??0)-(this.config.layers[T]??0)||h.localeCompare(T))),d={},R=h=>{if(d[h])return d[h];let T=Array.from(g).sort((w,$)=>(this.parentOrders.get(w[0])??0)-(this.parentOrders.get($[0])??0)||w[0]?.localeCompare($[0]||"")||0).map(([w,$])=>{let _=$.length,D=$.filter(x=>(x[4]?.layer||z)===h).sort((x,U)=>x[0]-U[0]||(x[4]?.sort||0)-(U[4]?.sort||0)||x[1]?.localeCompare(U[1]||"")||x[2]?.localeCompare(U[2]||"")||0).map(([,x,U,,V,,O])=>[[[(x&&je(x,s))??"",V?.sort??0]],U,!!(O??V?.noMerge)]);if(!D.length)return;let m=D.reverse().map(([x,U,V],O)=>{if(!V&&this.config.mergeSelectors)for(let P=O+1;P<_;P++){let M=D[P];if(M&&!M[2]&&(x&&M[0]||x==null&&M[0]==null)&&M[1]===U)return x&&M[0]&&M[0].push(...x),null}let W=x?j(x.sort((P,M)=>P[1]-M[1]||P[0]?.localeCompare(M[0]||"")||0).map(P=>P[0]).filter(Boolean)):[];return W.length?`${W.join(`,${l}`)}{${U}}`:U}).filter(Boolean).reverse().join(l);if(!w)return m;let C=w.split(" $$ ");return`${C.join("{")}{${l}${m}${l}}${C.map(x=>"").join("}")}`}).filter(Boolean).join(l);i&&(T=[E[h],T].filter(Boolean).join(l));let S=a?"":`/* layer: ${h} */${l}`;return d[h]=T?S+T:""},y=(h=f,T)=>h.filter(S=>!T?.includes(S)).map(S=>R(S)||"").filter(Boolean).join(l);return{get css(){return y()},layers:f,matched:p,getLayers:y,getLayer:R}}matchVariants(e,r){let n=new Set,s=[],i=r||e,o=!1,a={rawSelector:e,theme:this.config.theme,generator:this};for(;;){o=!1;for(let u of this.config.variants){if(!u.multiPass&&n.has(u))continue;let l=u.match(i,a);if(l){b(l)&&(l={matcher:l}),i=l.matcher,s.unshift(l),n.add(u),o=!0;break}}if(!o)break;if(s.length>500)throw new Error(`Too many variants applied to "${e}"`)}return[e,i,s,n]}applyVariants(e,r=e[4],n=e[1]){let i=r.slice().sort((l,c)=>(l.order||0)-(c.order||0)).reduceRight((l,c)=>p=>{let g=c.body?.(p.entries)||p.entries,E=Array.isArray(c.parent)?c.parent:[c.parent,void 0];return(c.handle??ke)({...p,entries:g,selector:c.selector?.(p.selector,g)||p.selector,parent:E[0]||p.parent,parentOrder:E[1]||p.parentOrder,layer:c.layer||p.layer,sort:c.sort||p.sort},l)},l=>l)({prefix:"",selector:De(n),pseudo:"",entries:e[2]}),{parent:o,parentOrder:a}=i;o!=null&&a!=null&&this.parentOrders.set(o,a);let u={selector:Le([i.prefix,i.selector,i.pseudo].join("")),entries:i.entries,parent:o,layer:i.layer,sort:i.sort,noMerge:i.noMerge};for(let l of this.config.postprocess)l(u);return u}constructCustomCSS(e,r,n){let s=L(r);if(b(s))return s;let{selector:i,entries:o,parent:a}=this.applyVariants([0,n||e.rawSelector,s,void 0,e.variantHandlers]),u=`${i}{${F(o)}}`;return a?`${a}{${u}}`:u}async parseUtil(e,r,n=!1,s){let[i,o,a]=b(e)?this.matchVariants(e):e;this.config.details&&(r.rules=r.rules??[]);let u=this.config.rulesStaticMap[o];if(u&&u[1]&&(n||!u[2]?.internal)){this.config.details&&r.rules.push(u[3]);let c=u[0],p=L(u[1]),g=u[2];return b(p)?[[c,p,g]]:[[c,i,p,g,a]]}r.variantHandlers=a;let{rulesDynamic:l}=this.config;for(let[c,p,g,E]of l){if(E?.internal&&!n)continue;let A=o;if(E?.prefix){let y=v(E.prefix);if(s){let h=v(s);if(!y.some(T=>h.includes(T)))continue}else{let h=y.find(T=>o.startsWith(T));if(h==null)continue;A=o.slice(h.length)}}let f=A.match(p);if(!f)continue;let d=await g(f,r);if(!d)continue;this.config.details&&r.rules.push([p,g,E]);let R=te(d).filter(y=>y.length);if(R.length)return R.map(y=>b(y)?[c,y,E]:[c,i,y,E,a])}}stringifyUtil(e,r){if(!e)return;if(q(e))return[e[0],void 0,e[1],void 0,e[2],this.config.details?r:void 0,void 0];let{selector:n,entries:s,parent:i,layer:o,sort:a,noMerge:u}=this.applyVariants(e),l=F(s);if(!l)return;let{layer:c,sort:p,...g}=e[3]??{},E={...g,layer:o??c,sort:a??p};return[e[0],n,l,i,E,this.config.details?r:void 0,u]}expandShortcut(e,r,n=5){if(n===0)return;let s=this.config.details?a=>{r.shortcuts=r.shortcuts??[],r.shortcuts.push(a)}:ae,i,o;for(let a of this.config.shortcuts){let u=e;if(a[2]?.prefix){let c=v(a[2].prefix).find(p=>e.startsWith(p));if(c==null)continue;u=e.slice(c.length)}if(ne(a)){if(a[0]===u){i=i||a[2],o=a[1],s(a);break}}else{let l=u.match(a[0]);if(l&&(o=a[1](l,r)),o){i=i||a[2],s(a);break}}}if(b(o)&&(o=ce(o.trim()).split(/\s+/g)),!o){let[a,u]=b(e)?this.matchVariants(e):e;if(a!==u){let l=this.expandShortcut(u,r,n-1);l&&(o=l[0].map(c=>b(c)?a.replace(u,c):c))}}if(o)return[o.flatMap(a=>(b(a)?this.expandShortcut(a,r,n-1)?.[0]:void 0)||[a]).filter(Boolean),i]}async stringifyShortcuts(e,r,n,s={layer:this.config.shortcutsLayer}){let i=new G,o=(await Promise.all(j(n).map(async c=>{let p=b(c)?await this.parseUtil(c,r,!0,s.prefix):[[1/0,"{inline}",L(c),void 0,[]]];return p||ue(`unmatched utility "${c}" in shortcut "${e[1]}"`),p||[]}))).flat(1).filter(Boolean).sort((c,p)=>c[0]-p[0]),[a,,u]=e,l=[];for(let c of o){if(q(c)){l.push([c[0],void 0,c[1],void 0,c[2],r,void 0]);continue}let{selector:p,entries:g,parent:E,sort:A,noMerge:f}=this.applyVariants(c,[...c[4],...u],a);i.getFallback(p,E,[[],c[0]])[0].push([g,!!(f??c[3]?.noMerge),A??0])}return l.concat(i.map(([c,p],g,E)=>{let A=(d,R,y)=>{let h=Math.max(...y.map(S=>S[1])),T=y.map(S=>S[0]);return(d?[T.flat(1)]:T).map(S=>{let w=F(S);if(w)return[p,g,w,E,{...s,noMerge:R,sort:h},r,void 0]})};return[[c.filter(([,d])=>d).map(([d,,R])=>[d,R]),!0],[c.filter(([,d])=>!d).map(([d,,R])=>[d,R]),!1]].map(([d,R])=>[...A(!1,R,d.filter(([y])=>y.some(h=>h[0]===Y))),...A(!0,R,d.filter(([y])=>y.every(h=>h[0]!==Y)))])}).flat(2).filter(Boolean))}isBlocked(e){return!e||this.config.blocklist.some(r=>b(r)?r===e:r.test(e))}};function ge(t,e){return new X(t,e)}var Oe=/\s\$\$\s+/g,Pe=t=>t.match(/\s\$\$\s/);function je(t,e){return Pe(t)?t.replace(Oe,e?` ${e} `:" "):e?`${e} ${t}`:t}function Le(t){let e=t.match(/::[\w-]+(\([\w-]+\))?/g);if(e){for(let r of e)t=t.replace(r,"");t+=e.join("")}return t}var me=/^\[(.+?)(~?=)"(.*)"\]$/;function De(t){return me.test(t)?t.replace(me,(e,r,n,s)=>`[${K(r)}${n}"${K(s)}"]`):`.${K(t)}`}function ke(t,e){return e(t)}var Ke=t=>t.replace(/-(\w)/g,(e,r)=>r?r.toUpperCase():""),xe=t=>t.charAt(0).toUpperCase()+t.slice(1),ye=t=>t.replace(/(?:^|\B)([A-Z])/g,"-$1").toLowerCase(),Se=["Webkit","Moz","ms"];function Ce(t){let e={};function r(n){let s=e[n];if(s)return s;let i=Ke(n);if(i!=="filter"&&i in t)return e[n]=ye(i);i=xe(i);for(let o=0;o<Se.length;o++){let a=`${Se[o]}${i}`;if(a in t)return e[n]=ye(xe(a))}return n}return({entries:n})=>n.forEach(s=>{s[0].startsWith("--")||(s[0]=r(s[0]))})}function Ee(t){return t.replace(/&amp;/g,"&").replace(/&gt;/g,">").replace(/&lt;/g,"<")}function ee(t={}){if(typeof window>"u"){console.warn("@unocss/runtime been used in non-browser environment, skipped.");return}let e=window,r=document,n=e.__unocss||{},s=Object.assign({},t,n.runtime),i=s.defaults||{},o=s.cloakAttribute??"un-cloak";s.autoPrefix&&(i.postprocess=v(i.postprocess)).unshift(Ce(r.createElement("div").style)),s.configResolved?.(n,i);let a=ge(n,i),u=!0,l=new Set,c,p,g,E=[],A=()=>new Promise(m=>{E.push(m),g!=null&&clearTimeout(g),g=setTimeout(()=>R().then(()=>{let C=E;E=[],C.forEach(x=>x())}),0)});function f(m){if(m.nodeType!==1)return;let C=m;C.hasAttribute(o)&&C.removeAttribute(o),C.querySelectorAll(`[${o}]`).forEach(x=>{x.removeAttribute(o)})}function d(){return c||(c=r.createElement("style"),r.documentElement.prepend(c)),c}async function R(){let m=await a.generate(l),C=d();return C.innerHTML=m.css,l=m.matched,{...m,styleElement:C}}async function y(m){let C=l.size;await a.applyExtractors(m,void 0,l),C!==l.size&&await A()}async function h(){let m=r.body,C=m&&m.outerHTML;C&&(await y(`${C} ${Ee(C)}`),f(r.documentElement),f(m))}let T=new MutationObserver(m=>{u||m.forEach(async C=>{if(C.target.nodeType!==1)return;let x=C.target;if(x!==c)if(C.type==="childList")C.addedNodes.forEach(async U=>{if(U.nodeType!==1)return;let V=U;p&&!p(V)||(await y(V.outerHTML),f(V))});else{if(p&&!p(x))return;if(C.attributeName!==o){let U=Array.from(x.attributes).map(O=>O.value?`${O.name}="${O.value}"`:O.name).join(" "),V=`<${x.tagName.toLowerCase()} ${U}>`;await y(V)}x.hasAttribute(o)&&x.removeAttribute(o)}})}),S=!1;function w(){if(S)return;let m=r.documentElement||r.body;m&&(T.observe(m,{childList:!0,subtree:!0,attributes:!0}),S=!0)}function $(){h(),w()}function _(){r.readyState==="loading"?e.addEventListener("DOMContentLoaded",$):$()}let D=e.__unocss_runtime=e.__unocss_runtime={version:a.version,uno:a,async extract(m){b(m)||(m.forEach(C=>l.add(C)),m=""),await y(m)},extractAll:h,inspect(m){p=m},toggleObserver(m){m===void 0?u=!u:u=!!m,!S&&!u&&_()},update:R};s.ready?.(D)!==!1&&(u=!1,_())}ee();})();
1
+ "use strict";(()=>{function Re(t){let e=t.length,r=-1,n,s="",i=t.charCodeAt(0);for(;++r<e;){if(n=t.charCodeAt(r),n===0){s+="\uFFFD";continue}if(n===44){s+="\\,";continue}if(n>=1&&n<=31||n===127||r===0&&n>=48&&n<=57||r===1&&n>=48&&n<=57&&i===45){s+=`\\${n.toString(16)} `;continue}if(r===0&&e===1&&n===45){s+=`\\${t.charAt(r)}`;continue}if(n>=128||n===45||n===95||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122){s+=t.charAt(r);continue}s+=`\\${t.charAt(r)}`}return s}var H=Re;function A(t=[]){return Array.isArray(t)?t:[t]}function j(t){return Array.from(new Set(t))}function R(t){return typeof t=="string"}function D(t){return R(t)?t:(Array.isArray(t)?t:Object.entries(t)).filter(e=>e[1]!=null)}function te(t){return Array.isArray(t)?t.find(e=>!Array.isArray(e)||Array.isArray(e[0]))?t.map(e=>D(e)):[t]:[D(t)]}function be(t){return t.filter(([e,r],n)=>{if(e.startsWith("$$"))return!1;for(let s=n-1;s>=0;s--)if(t[s][0]===e&&t[s][1]===r)return!1;return!0})}function F(t){return t==null?"":be(t).map(([e,r])=>r!=null?`${e}:${r};`:void 0).filter(Boolean).join("")}function G(t){return t&&typeof t=="object"&&!Array.isArray(t)}function W(t,e){let r=t,n=e;if(Array.isArray(r))return[...n];let s={...r};return G(r)&&G(n)&&Object.keys(n).forEach(i=>{G(r[i])&&G(n[i])||Array.isArray(r[i])&&Array.isArray(n[i])?s[i]=W(r[i],n[i]):Object.assign(s,{[i]:n[i]})}),s}function k(t){let e,r,n;if(Array.isArray(t)){for(r=Array(e=t.length);e--;)r[e]=(n=t[e])&&typeof n=="object"?k(n):n;return r}if(Object.prototype.toString.call(t)==="[object Object]"){r={};for(e in t)e==="__proto__"?Object.defineProperty(r,e,{value:k(t[e]),configurable:!0,enumerable:!0,writable:!0}):r[e]=(n=t[e])&&typeof n=="object"?k(n):n;return r}return t}function re(t){return R(t[0])}function ne(t){return R(t[0])}var ve=/[\w\u00A0-\uFFFF-_:%-?]/,q="$$shortcut-no-merge";function se(t=""){return ve.test(t)}function ie(t){return typeof t=="function"?{match:t}:t}function Y(t){return t.length===3}function oe(t){return t!=null}function ae(){}var B=class{_map=new Map;get(e,r){let n=this._map.get(e);if(n)return n.get(r)}getFallback(e,r,n){let s=this._map.get(e);return s||(s=new Map,this._map.set(e,s)),s.has(r)||s.set(r,n),s.get(r)}set(e,r,n){let s=this._map.get(e);return s||(s=new Map,this._map.set(e,s)),s.set(r,n),this}has(e,r){return this._map.get(e)?.has(r)}delete(e,r){return this._map.get(e)?.delete(r)||!1}deleteTop(e){return this._map.delete(e)}map(e){return Array.from(this._map.entries()).flatMap(([r,n])=>Array.from(n.entries()).map(([s,i])=>e(i,r,s)))}};var z={};function we(t=["-",":"]){let e=t.join("|");return z[e]||(z[e]=new RegExp(`((?:[!@\\w+:_/-]|\\[&?>?:?\\S*\\])+?)(${e})\\(((?:[~!\\w\\s:/\\\\,%#.$?-]|\\[.*?\\])+?)\\)(?!\\s*?=>)`,"gm")),z[e].lastIndex=0,z[e]}function Ae(t,e=["-",":"],r=5){let n=we(e),s=!1,i=t.toString(),o=new Set;do{let a=i;i=i.replace(n,(u,l,c,d)=>e.includes(c)?(o.add(l+c),d.split(/\s/g).filter(Boolean).map(x=>x==="~"?l:x.replace(/^(!?)(.*)/,`$1${l}${c}$2`)).join(" ")):u),s=i!==a,r-=1}while(s&&r);return{prefixes:Array.from(o),expanded:i,hasChanged:s}}function ce(t,e=["-",":"],r=5){let{expanded:n}=Ae(t.toString(),e,r);return typeof t=="string"?n:t.length()?t.overwrite(0,t.length(),n):t}var le=new Set;function ue(t){le.has(t)||(console.warn("[unocss]",t),le.add(t))}var Ue=/\\?[\s'"`;{}]+/g,fe=/(?:[\w&:[\]-]|\[\S+=\S+\])+\[\\?['"]?\S+?['"]\]\]?[\w:-]*/g,Z=/\[(\\\W|[\w-])+:['"]?\S+?['"]?\]/g,$e=new RegExp(`^${Z.source}$`),Ve=t=>{let e=new Set;for(let r of t.matchAll(Z))t[r.index-1]?.match(/^[\s'"`]/)&&e.add(r[0]);for(let r of t.matchAll(fe))e.add(r[0]);return t.split(Ue).forEach(r=>{se(r)&&!$e.test(r)&&e.add(r)}),[...e]},J={name:"split",order:0,extract({code:t}){return Ve(t)}};function pe(){return{events:{},emit(t,...e){(this.events[t]||[]).forEach(r=>r(...e))},on(t,e){return(this.events[t]=this.events[t]||[]).push(e),()=>this.events[t]=(this.events[t]||[]).filter(r=>r!==e)}}}var I="default",N="preflights",Me="shortcuts",de={[N]:-100,[Me]:-10,[I]:0};function he(t){return A(t).flatMap(e=>Array.isArray(e)?[e]:Object.entries(e))}function _e(t){let e=t.shortcuts?he(t.shortcuts):void 0;if(t.shortcuts=e,t.prefix||t.layer){let r=n=>{n[2]||(n[2]={});let s=n[2];s.prefix==null&&t.prefix&&(s.prefix=A(t.prefix)),s.layer==null&&t.layer&&(s.layer=t.layer)};e?.forEach(r),t.rules?.forEach(r)}return t}function Q(t={},e={}){let r=Object.assign({},e,t),n=(r.presets||[]).flatMap(A).map(_e),s=[...n.filter(f=>f.enforce==="pre"),...n.filter(f=>!f.enforce),...n.filter(f=>f.enforce==="post")],i=Object.assign({},de,...n.map(f=>f.layers),r.layers);function o(f){return j([...s.flatMap(h=>A(h[f]||[])),...A(r[f]||[])])}let a=o("extractors");a.length||a.push(J),a.sort((f,h)=>(f.order||0)-(h.order||0));let u=o("rules"),l={},c=u.length,d=u.map((f,h)=>{if(re(f)){A(f[2]?.prefix||"").forEach(E=>{l[E+f[0]]=[h,f[1],f[2],f]});return}return[h,...f]}).filter(Boolean).reverse(),x=k([...s.map(f=>f.theme||{}),r.theme||{}].reduce((f,h)=>W(f,h),{}));o("extendTheme").forEach(f=>f(x));let C={templates:j(s.map(f=>A(f.autocomplete?.templates)).flat()),extractors:s.map(f=>A(f.autocomplete?.extractors)).flat().sort((f,h)=>(f.order||0)-(h.order||0))},v=A(o("separators"));return v.length||(v=[":","-"]),{mergeSelectors:!0,warn:!0,blocklist:[],sortLayers:f=>f,...r,presets:s,envMode:r.envMode||"build",shortcutsLayer:r.shortcutsLayer||"shortcuts",layers:i,theme:x,rulesSize:c,rulesDynamic:d,rulesStaticMap:l,preprocess:o("preprocess"),postprocess:o("postprocess"),preflights:o("preflights"),autocomplete:C,variants:o("variants").map(ie).sort((f,h)=>(f.order||0)-(h.order||0)),shortcuts:he(o("shortcuts")).reverse(),extractors:a,safelist:o("safelist"),separators:v}}var me="0.50.0";var X=class{constructor(e={},r={}){this.userConfig=e;this.defaults=r;this.config=Q(e,r),this.events.emit("config",this.config)}version=me;_cache=new Map;config;blocked=new Set;parentOrders=new Map;events=pe();setConfig(e,r){e&&(r&&(this.defaults=r),this.userConfig=e,this.blocked.clear(),this.parentOrders.clear(),this._cache.clear(),this.config=Q(e,this.defaults),this.events.emit("config",this.config))}async applyExtractors(e,r,n=new Set){let s={get original(){return e},code:e,id:r};for(let i of this.config.extractors){let o=await i.extract(s);if(o)for(let a of o)n.add(a)}return n}makeContext(e,r){let n={rawSelector:e,currentSelector:r[1],theme:this.config.theme,generator:this,variantHandlers:r[2],constructCSS:(...s)=>this.constructCustomCSS(n,...s),variantMatch:r};return n}async parseToken(e,r){if(this.blocked.has(e))return;let n=`${e}${r?` ${r}`:""}`;if(this._cache.has(n))return this._cache.get(n);let s=e;for(let l of this.config.preprocess)s=l(e);if(this.isBlocked(s)){this.blocked.add(e),this._cache.set(n,null);return}let i=await this.matchVariants(e,s);if(!i||this.isBlocked(i[1])){this.blocked.add(e),this._cache.set(n,null);return}let o=this.makeContext(e,[r||i[0],i[1],i[2],i[3]]);this.config.details&&(o.variants=[...i[3]]);let a=await this.expandShortcut(o.currentSelector,o),u=a?await this.stringifyShortcuts(o.variantMatch,o,a[0],a[1]):(await this.parseUtil(o.variantMatch,o))?.map(l=>this.stringifyUtil(l,o)).filter(oe);if(u?.length)return this._cache.set(n,u),u;this._cache.set(n,null)}async generate(e,r={}){let{id:n,scope:s,preflights:i=!0,safelist:o=!0,minify:a=!1}=r,u=R(e)?await this.applyExtractors(e,n):Array.isArray(e)?new Set(e):e;o&&this.config.safelist.forEach(g=>u.add(g));let l=a?"":`
2
+ `,c=new Set([I]),d=new Set,x=new Map,C={},v=Array.from(u).map(async g=>{if(d.has(g))return;let S=await this.parseToken(g);if(S!=null){d.add(g);for(let T of S){let w=T[3]||"",$=T[4]?.layer;x.has(w)||x.set(w,[]),x.get(w).push(T),$&&c.add($)}}});await Promise.all(v),await(async()=>{if(!i)return;let g={generator:this,theme:this.config.theme},S=new Set([]);this.config.preflights.forEach(({layer:T=N})=>{c.add(T),S.add(T)}),C=Object.fromEntries(await Promise.all(Array.from(S).map(async T=>{let $=(await Promise.all(this.config.preflights.filter(_=>(_.layer||N)===T).map(async _=>await _.getCSS(g)))).filter(Boolean).join(l);return[T,$]})))})();let f=this.config.sortLayers(Array.from(c).sort((g,S)=>(this.config.layers[g]??0)-(this.config.layers[S]??0)||g.localeCompare(S))),h={},b=g=>{if(h[g])return h[g];let S=Array.from(x).sort((w,$)=>(this.parentOrders.get(w[0])??0)-(this.parentOrders.get($[0])??0)||w[0]?.localeCompare($[0]||"")||0).map(([w,$])=>{let _=$.length,L=$.filter(p=>(p[4]?.layer||I)===g).sort((p,y)=>p[0]-y[0]||(p[4]?.sort||0)-(y[4]?.sort||0)||p[5]?.currentSelector?.localeCompare(y[5]?.currentSelector??"")||p[1]?.localeCompare(y[1]||"")||p[2]?.localeCompare(y[2]||"")||0).map(([,p,y,,U,,V])=>[[[(p&&je(p,s))??"",U?.sort??0]],y,!!(V??U?.noMerge)]);if(!L.length)return;let K=L.reverse().map(([p,y,U],V)=>{if(!U&&this.config.mergeSelectors)for(let O=V+1;O<_;O++){let M=L[O];if(M&&!M[2]&&(p&&M[0]||p==null&&M[0]==null)&&M[1]===y)return p&&M[0]&&M[0].push(...p),null}let P=p?j(p.sort((O,M)=>O[1]-M[1]||O[0]?.localeCompare(M[0]||"")||0).map(O=>O[0]).filter(Boolean)):[];return P.length?`${P.join(`,${l}`)}{${y}}`:y}).filter(Boolean).reverse().join(l);if(!w)return K;let m=w.split(" $$ ");return`${m.join("{")}{${l}${K}${l}}${m.map(p=>"").join("}")}`}).filter(Boolean).join(l);i&&(S=[C[g],S].filter(Boolean).join(l));let T=a?"":`/* layer: ${g} */${l}`;return h[g]=S?T+S:""},E=(g=f,S)=>g.filter(T=>!S?.includes(T)).map(T=>b(T)||"").filter(Boolean).join(l);return{get css(){return E()},layers:f,matched:d,getLayers:E,getLayer:b}}async matchVariants(e,r){let n=new Set,s=[],i=r||e,o=!1,a={rawSelector:e,theme:this.config.theme,generator:this};for(;;){o=!1;for(let u of this.config.variants){if(!u.multiPass&&n.has(u))continue;let l=await u.match(i,a);if(l){R(l)&&(l={matcher:l}),i=l.matcher,s.unshift(l),n.add(u),o=!0;break}}if(!o)break;if(s.length>500)throw new Error(`Too many variants applied to "${e}"`)}return[e,i,s,n]}applyVariants(e,r=e[4],n=e[1]){let i=r.slice().sort((l,c)=>(l.order||0)-(c.order||0)).reduceRight((l,c)=>d=>{let x=c.body?.(d.entries)||d.entries,C=Array.isArray(c.parent)?c.parent:[c.parent,void 0];return(c.handle??ke)({...d,entries:x,selector:c.selector?.(d.selector,x)||d.selector,parent:C[0]||d.parent,parentOrder:C[1]||d.parentOrder,layer:c.layer||d.layer,sort:c.sort||d.sort},l)},l=>l)({prefix:"",selector:De(n),pseudo:"",entries:e[2]}),{parent:o,parentOrder:a}=i;o!=null&&a!=null&&this.parentOrders.set(o,a);let u={selector:[i.prefix,i.selector,i.pseudo].join(""),entries:i.entries,parent:o,layer:i.layer,sort:i.sort,noMerge:i.noMerge};for(let l of this.config.postprocess)l(u);return u}constructCustomCSS(e,r,n){let s=D(r);if(R(s))return s;let{selector:i,entries:o,parent:a}=this.applyVariants([0,n||e.rawSelector,s,void 0,e.variantHandlers]),u=`${i}{${F(o)}}`;return a?`${a}{${u}}`:u}async parseUtil(e,r,n=!1,s){let[i,o,a]=R(e)?await this.matchVariants(e):e;this.config.details&&(r.rules=r.rules??[]);let u=this.config.rulesStaticMap[o];if(u&&u[1]&&(n||!u[2]?.internal)){this.config.details&&r.rules.push(u[3]);let c=u[0],d=D(u[1]),x=u[2];return R(d)?[[c,d,x]]:[[c,i,d,x,a]]}r.variantHandlers=a;let{rulesDynamic:l}=this.config;for(let[c,d,x,C]of l){if(C?.internal&&!n)continue;let v=o;if(C?.prefix){let E=A(C.prefix);if(s){let g=A(s);if(!E.some(S=>g.includes(S)))continue}else{let g=E.find(S=>o.startsWith(S));if(g==null)continue;v=o.slice(g.length)}}let f=v.match(d);if(!f)continue;let h=await x(f,r);if(!h)continue;this.config.details&&r.rules.push([d,x,C]);let b=te(h).filter(E=>E.length);if(b.length)return b.map(E=>R(E)?[c,E,C]:[c,i,E,C,a])}}stringifyUtil(e,r){if(!e)return;if(Y(e))return[e[0],void 0,e[1],void 0,e[2],this.config.details?r:void 0,void 0];let{selector:n,entries:s,parent:i,layer:o,sort:a,noMerge:u}=this.applyVariants(e),l=F(s);if(!l)return;let{layer:c,sort:d,...x}=e[3]??{},C={...x,layer:o??c,sort:a??d};return[e[0],n,l,i,C,this.config.details?r:void 0,u]}async expandShortcut(e,r,n=5){if(n===0)return;let s=this.config.details?a=>{r.shortcuts=r.shortcuts??[],r.shortcuts.push(a)}:ae,i,o;for(let a of this.config.shortcuts){let u=e;if(a[2]?.prefix){let c=A(a[2].prefix).find(d=>e.startsWith(d));if(c==null)continue;u=e.slice(c.length)}if(ne(a)){if(a[0]===u){i=i||a[2],o=a[1],s(a);break}}else{let l=u.match(a[0]);if(l&&(o=a[1](l,r)),o){i=i||a[2],s(a);break}}}if(R(o)&&(o=ce(o.trim()).split(/\s+/g)),!o){let[a,u]=R(e)?await this.matchVariants(e):e;if(a!==u){let l=await this.expandShortcut(u,r,n-1);l&&(o=l[0].map(c=>R(c)?a.replace(u,c):c))}}if(o)return[(await Promise.all(o.map(async a=>(R(a)?(await this.expandShortcut(a,r,n-1))?.[0]:void 0)||[a]))).flat(1).filter(Boolean),i]}async stringifyShortcuts(e,r,n,s={layer:this.config.shortcutsLayer}){let i=new B,o=(await Promise.all(j(n).map(async c=>{let d=R(c)?await this.parseUtil(c,r,!0,s.prefix):[[1/0,"{inline}",D(c),void 0,[]]];return d||ue(`unmatched utility "${c}" in shortcut "${e[1]}"`),d||[]}))).flat(1).filter(Boolean).sort((c,d)=>c[0]-d[0]),[a,,u]=e,l=[];for(let c of o){if(Y(c)){l.push([c[0],void 0,c[1],void 0,c[2],r,void 0]);continue}let{selector:d,entries:x,parent:C,sort:v,noMerge:f}=this.applyVariants(c,[...c[4],...u],a);i.getFallback(d,C,[[],c[0]])[0].push([x,!!(f??c[3]?.noMerge),v??0])}return l.concat(i.map(([c,d],x,C)=>{let v=(h,b,E)=>{let g=Math.max(...E.map(T=>T[1])),S=E.map(T=>T[0]);return(h?[S.flat(1)]:S).map(T=>{let w=F(T);if(w)return[d,x,w,C,{...s,noMerge:b,sort:g},r,void 0]})};return[[c.filter(([,h])=>h).map(([h,,b])=>[h,b]),!0],[c.filter(([,h])=>!h).map(([h,,b])=>[h,b]),!1]].map(([h,b])=>[...v(!1,b,h.filter(([E])=>E.some(g=>g[0]===q))),...v(!0,b,h.filter(([E])=>E.every(g=>g[0]!==q)))])}).flat(2).filter(Boolean))}isBlocked(e){return!e||this.config.blocklist.some(r=>R(r)?r===e:r.test(e))}};function ye(t,e){return new X(t,e)}var Oe=/\s\$\$\s+/g,Le=t=>t.match(/\s\$\$\s/);function je(t,e){return Le(t)?t.replace(Oe,e?` ${e} `:" "):e?`${e} ${t}`:t}var ge=/^\[(.+?)(~?=)"(.*)"\]$/;function De(t){return ge.test(t)?t.replace(ge,(e,r,n,s)=>`[${H(r)}${n}"${H(s)}"]`):`.${H(t)}`}function ke(t,e){return e(t)}var Ke=t=>t.replace(/-(\w)/g,(e,r)=>r?r.toUpperCase():""),xe=t=>t.charAt(0).toUpperCase()+t.slice(1),Se=t=>t.replace(/(?:^|\B)([A-Z])/g,"-$1").toLowerCase(),Ce=["Webkit","Moz","ms"];function Ee(t){let e={};function r(n){let s=e[n];if(s)return s;let i=Ke(n);if(i!=="filter"&&i in t)return e[n]=Se(i);i=xe(i);for(let o=0;o<Ce.length;o++){let a=`${Ce[o]}${i}`;if(a in t)return e[n]=Se(xe(a))}return n}return({entries:n})=>n.forEach(s=>{s[0].startsWith("--")||(s[0]=r(s[0]))})}function Te(t){return t.replace(/&amp;/g,"&").replace(/&gt;/g,">").replace(/&lt;/g,"<")}function ee(t={}){if(typeof window>"u"){console.warn("@unocss/runtime been used in non-browser environment, skipped.");return}let e=window,r=window.document,n=()=>r.documentElement,s=e.__unocss||{},i=Object.assign({},t,s.runtime),o=i.defaults||{},a=i.cloakAttribute??"un-cloak";i.autoPrefix&&(o.postprocess=A(o.postprocess)).unshift(Ee(r.createElement("div").style)),i.configResolved?.(s,o);let u=ye(s,o),l=new Map,c=!0,d=new Set,x,C,v=[],f=()=>new Promise(m=>{v.push(m),C!=null&&clearTimeout(C),C=setTimeout(()=>E().then(()=>{let p=v;v=[],p.forEach(y=>y())}),0)});function h(m){if(m.nodeType!==1)return;let p=m;p.hasAttribute(a)&&p.removeAttribute(a),p.querySelectorAll(`[${a}]`).forEach(y=>{y.removeAttribute(a)})}function b(m,p){let y=l.get(m);if(!y)if(y=r.createElement("style"),l.set(m,y),p==null)n().prepend(y);else{let U=b(p),V=U.parentNode;V?V.insertBefore(y,U.nextSibling):n().prepend(y)}return y}async function E(){let m=await u.generate(d);return m.layers.reduce((p,y)=>(b(y,p).innerHTML=m.getLayer(y)??"",y),void 0),d=m.matched,{...m,getStyleElement:p=>l.get(p),getStyleElements:()=>l}}async function g(m){let p=d.size;await u.applyExtractors(m,void 0,d),p!==d.size&&await f()}async function S(){let m=r.body,p=m&&m.outerHTML;p&&(await g(`${p} ${Te(p)}`),h(n()),h(m))}let T=new MutationObserver(m=>{c||m.forEach(async p=>{if(p.target.nodeType!==1)return;let y=p.target;for(let U of l)if(y===U[1])return;if(p.type==="childList")p.addedNodes.forEach(async U=>{if(U.nodeType!==1)return;let V=U;x&&!x(V)||(await g(V.outerHTML),h(V))});else{if(x&&!x(y))return;if(p.attributeName!==a){let U=Array.from(y.attributes).map(P=>P.value?`${P.name}="${P.value}"`:P.name).join(" "),V=`<${y.tagName.toLowerCase()} ${U}>`;await g(V)}y.hasAttribute(a)&&y.removeAttribute(a)}})}),w=!1;function $(){if(w)return;let m=n()||r.body;m&&(T.observe(m,{childList:!0,subtree:!0,attributes:!0}),w=!0)}function _(){S(),$()}function L(){r.readyState==="loading"?e.addEventListener("DOMContentLoaded",_):_()}let K=e.__unocss_runtime=e.__unocss_runtime={version:u.version,uno:u,async extract(m){R(m)||(m.forEach(p=>d.add(p)),m=""),await g(m)},extractAll:S,inspect(m){x=m},toggleObserver(m){m===void 0?c=!c:c=!!m,!w&&!c&&L()},update:E};i.ready?.(K)!==!1&&(c=!1,L())}ee();})();
package/dist/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import { UserConfig, UserConfigDefaults, UnoGenerator, GenerateResult } from '@unocss/core';
1
+ import { UserConfig, GenerateResult, UserConfigDefaults, UnoGenerator } from '@unocss/core';
2
2
 
3
+ interface RuntimeGenerateResult extends GenerateResult {
4
+ getStyleElement(name: string): HTMLStyleElement | undefined;
5
+ getStyleElements(): Map<string, HTMLStyleElement>;
6
+ }
3
7
  interface RuntimeOptions {
4
8
  /**
5
9
  * Default config of UnoCSS
@@ -63,11 +67,9 @@ interface RuntimeContext {
63
67
  /**
64
68
  * Manually run the update cycle.
65
69
  *
66
- * @returns {GenerateResult & { styleElement: HTMLStyleElement}}
70
+ * @returns {RuntimeGenerateResult}
67
71
  */
68
- update: () => Promise<GenerateResult & {
69
- styleElement: HTMLStyleElement;
70
- }>;
72
+ update: () => Promise<RuntimeGenerateResult>;
71
73
  /**
72
74
  * The UnoCSS version.
73
75
  *
@@ -85,4 +87,4 @@ declare global {
85
87
  }
86
88
  declare function init(inlineConfig?: RuntimeOptions): void;
87
89
 
88
- export { RuntimeContext, RuntimeInspectorCallback, RuntimeOptions, init as default };
90
+ export { RuntimeContext, RuntimeGenerateResult, RuntimeInspectorCallback, RuntimeOptions, init as default };
package/dist/index.js CHANGED
@@ -63,7 +63,8 @@ function init(inlineConfig = {}) {
63
63
  return;
64
64
  }
65
65
  const defaultWindow = window;
66
- const defaultDocument = document;
66
+ const defaultDocument = window.document;
67
+ const html = () => defaultDocument.documentElement;
67
68
  const userConfig = defaultWindow.__unocss || {};
68
69
  const runtimeOptions = Object.assign({}, inlineConfig, userConfig.runtime);
69
70
  const userConfigDefaults = runtimeOptions.defaults || {};
@@ -74,9 +75,9 @@ function init(inlineConfig = {}) {
74
75
  }
75
76
  runtimeOptions.configResolved?.(userConfig, userConfigDefaults);
76
77
  const uno = (0, import_core.createGenerator)(userConfig, userConfigDefaults);
78
+ const styleElements = /* @__PURE__ */ new Map();
77
79
  let paused = true;
78
80
  let tokens = /* @__PURE__ */ new Set();
79
- let styleElement;
80
81
  let inspector;
81
82
  let _timer;
82
83
  let _resolvers = [];
@@ -100,21 +101,35 @@ function init(inlineConfig = {}) {
100
101
  n.removeAttribute(cloakAttribute);
101
102
  });
102
103
  }
103
- function getStyleElement() {
104
+ function getStyleElement(layer, previousLayer) {
105
+ let styleElement = styleElements.get(layer);
104
106
  if (!styleElement) {
105
107
  styleElement = defaultDocument.createElement("style");
106
- defaultDocument.documentElement.prepend(styleElement);
108
+ styleElements.set(layer, styleElement);
109
+ if (previousLayer == null) {
110
+ html().prepend(styleElement);
111
+ } else {
112
+ const previousStyle = getStyleElement(previousLayer);
113
+ const parentNode = previousStyle.parentNode;
114
+ if (parentNode)
115
+ parentNode.insertBefore(styleElement, previousStyle.nextSibling);
116
+ else
117
+ html().prepend(styleElement);
118
+ }
107
119
  }
108
120
  return styleElement;
109
121
  }
110
122
  async function updateStyle() {
111
123
  const result = await uno.generate(tokens);
112
- const styleElement2 = getStyleElement();
113
- styleElement2.innerHTML = result.css;
124
+ result.layers.reduce((previous, current) => {
125
+ getStyleElement(current, previous).innerHTML = result.getLayer(current) ?? "";
126
+ return current;
127
+ }, void 0);
114
128
  tokens = result.matched;
115
129
  return {
116
130
  ...result,
117
- styleElement: styleElement2
131
+ getStyleElement: (layer) => styleElements.get(layer),
132
+ getStyleElements: () => styleElements
118
133
  };
119
134
  }
120
135
  async function extract(str) {
@@ -125,10 +140,10 @@ function init(inlineConfig = {}) {
125
140
  }
126
141
  async function extractAll() {
127
142
  const body = defaultDocument.body;
128
- const html = body && body.outerHTML;
129
- if (html) {
130
- await extract(`${html} ${decodeHtml(html)}`);
131
- removeCloak(defaultDocument.documentElement);
143
+ const outerHTML = body && body.outerHTML;
144
+ if (outerHTML) {
145
+ await extract(`${outerHTML} ${decodeHtml(outerHTML)}`);
146
+ removeCloak(html());
132
147
  removeCloak(body);
133
148
  }
134
149
  }
@@ -139,8 +154,10 @@ function init(inlineConfig = {}) {
139
154
  if (mutation.target.nodeType !== 1)
140
155
  return;
141
156
  const target = mutation.target;
142
- if (target === styleElement)
143
- return;
157
+ for (const item of styleElements) {
158
+ if (target === item[1])
159
+ return;
160
+ }
144
161
  if (mutation.type === "childList") {
145
162
  mutation.addedNodes.forEach(async (node) => {
146
163
  if (node.nodeType !== 1)
@@ -168,7 +185,7 @@ function init(inlineConfig = {}) {
168
185
  function observe() {
169
186
  if (observing)
170
187
  return;
171
- const target = defaultDocument.documentElement || defaultDocument.body;
188
+ const target = html() || defaultDocument.body;
172
189
  if (!target)
173
190
  return;
174
191
  mutationObserver.observe(target, {
package/dist/index.mjs CHANGED
@@ -39,7 +39,8 @@ function init(inlineConfig = {}) {
39
39
  return;
40
40
  }
41
41
  const defaultWindow = window;
42
- const defaultDocument = document;
42
+ const defaultDocument = window.document;
43
+ const html = () => defaultDocument.documentElement;
43
44
  const userConfig = defaultWindow.__unocss || {};
44
45
  const runtimeOptions = Object.assign({}, inlineConfig, userConfig.runtime);
45
46
  const userConfigDefaults = runtimeOptions.defaults || {};
@@ -50,9 +51,9 @@ function init(inlineConfig = {}) {
50
51
  }
51
52
  runtimeOptions.configResolved?.(userConfig, userConfigDefaults);
52
53
  const uno = createGenerator(userConfig, userConfigDefaults);
54
+ const styleElements = /* @__PURE__ */ new Map();
53
55
  let paused = true;
54
56
  let tokens = /* @__PURE__ */ new Set();
55
- let styleElement;
56
57
  let inspector;
57
58
  let _timer;
58
59
  let _resolvers = [];
@@ -76,21 +77,35 @@ function init(inlineConfig = {}) {
76
77
  n.removeAttribute(cloakAttribute);
77
78
  });
78
79
  }
79
- function getStyleElement() {
80
+ function getStyleElement(layer, previousLayer) {
81
+ let styleElement = styleElements.get(layer);
80
82
  if (!styleElement) {
81
83
  styleElement = defaultDocument.createElement("style");
82
- defaultDocument.documentElement.prepend(styleElement);
84
+ styleElements.set(layer, styleElement);
85
+ if (previousLayer == null) {
86
+ html().prepend(styleElement);
87
+ } else {
88
+ const previousStyle = getStyleElement(previousLayer);
89
+ const parentNode = previousStyle.parentNode;
90
+ if (parentNode)
91
+ parentNode.insertBefore(styleElement, previousStyle.nextSibling);
92
+ else
93
+ html().prepend(styleElement);
94
+ }
83
95
  }
84
96
  return styleElement;
85
97
  }
86
98
  async function updateStyle() {
87
99
  const result = await uno.generate(tokens);
88
- const styleElement2 = getStyleElement();
89
- styleElement2.innerHTML = result.css;
100
+ result.layers.reduce((previous, current) => {
101
+ getStyleElement(current, previous).innerHTML = result.getLayer(current) ?? "";
102
+ return current;
103
+ }, void 0);
90
104
  tokens = result.matched;
91
105
  return {
92
106
  ...result,
93
- styleElement: styleElement2
107
+ getStyleElement: (layer) => styleElements.get(layer),
108
+ getStyleElements: () => styleElements
94
109
  };
95
110
  }
96
111
  async function extract(str) {
@@ -101,10 +116,10 @@ function init(inlineConfig = {}) {
101
116
  }
102
117
  async function extractAll() {
103
118
  const body = defaultDocument.body;
104
- const html = body && body.outerHTML;
105
- if (html) {
106
- await extract(`${html} ${decodeHtml(html)}`);
107
- removeCloak(defaultDocument.documentElement);
119
+ const outerHTML = body && body.outerHTML;
120
+ if (outerHTML) {
121
+ await extract(`${outerHTML} ${decodeHtml(outerHTML)}`);
122
+ removeCloak(html());
108
123
  removeCloak(body);
109
124
  }
110
125
  }
@@ -115,8 +130,10 @@ function init(inlineConfig = {}) {
115
130
  if (mutation.target.nodeType !== 1)
116
131
  return;
117
132
  const target = mutation.target;
118
- if (target === styleElement)
119
- return;
133
+ for (const item of styleElements) {
134
+ if (target === item[1])
135
+ return;
136
+ }
120
137
  if (mutation.type === "childList") {
121
138
  mutation.addedNodes.forEach(async (node) => {
122
139
  if (node.nodeType !== 1)
@@ -144,7 +161,7 @@ function init(inlineConfig = {}) {
144
161
  function observe() {
145
162
  if (observing)
146
163
  return;
147
- const target = defaultDocument.documentElement || defaultDocument.body;
164
+ const target = html() || defaultDocument.body;
148
165
  if (!target)
149
166
  return;
150
167
  mutationObserver.observe(target, {