@barocss/browser 0.5.0 → 0.7.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/dist/index.umd.js CHANGED
@@ -1,10 +1,12 @@
1
- (function(a,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@barocss/kit")):typeof define=="function"&&define.amd?define(["exports","@barocss/kit"],c):(a=typeof globalThis<"u"?globalThis:a||self,c(a.BaroCSSBrowser={},a.BaroCSSKit))})(this,(function(a,c){"use strict";const M=/^\s*@(media|container)\s+([^{]*)\{/,v=/prefers-color-scheme|\bprint\b|forced-colors|orientation/,N=/(?:min-width\s*:\s*|width\s*>=?\s*)([\d.]+)(px|rem|em)?/,D=/(?:max-width\s*:\s*|width\s*<=?\s*)([\d.]+)(px|rem|em)?/;function p(n,t){const e=parseFloat(n);return t==="rem"||t==="em"?e*16:e}function L(n,t){const e=n==="container",s=N.exec(t);if(s)return[e?4:2,p(s[1],s[2])];const i=D.exec(t);return i?[e?3:1,-p(i[1],i[2])]:!e&&v.test(t)?[5,0]:[0,0]}function C(n){const t=[];let e=n,s;for(;s=M.exec(e);){const[i,r]=L(s[1],s[2]);t.push(i,r),e=e.slice(s[0].length)}return t}function P(n,t){const e=Math.min(n.length,t.length);for(let s=0;s<e;s++)if(n[s]!==t[s])return n[s]-t[s];return n.length-t.length}function I(n,t){let e=0,s=n.length;for(;e<s;){const i=e+s>>1;P(n[i],t)<=0?e=i+1:s=i}return e}class f{constructor(t,e=50,s="barocss-style-partition-",i=r=>c.parseClassName(r).utility?.category){this.partitions=[],this.categoryPartitions=new Map,this.partitionCounter=0,this.maxRulesPerPartition=50,this.classToPartitionMap=new Map,this.classToCategoryPartitionMap=new Map,this.styleIdPrefix="barocss-style-partition-",this.insertionPoint=t,this.maxRulesPerPartition=e,this.styleIdPrefix=s,this.getCategory=i,this.initializeDefaultPartition()}insertSorted(t,e,s){const i=t.keys??=[],r=I(i,s),o=t.styleElement.sheet;o&&o.cssRules.length===i.length?(o.insertRule(this.escapeCssRule(e),r),t.styles.splice(r,0,e)):(t.styles.splice(r,0,e),t.styleElement.textContent=t.styles.join(`
1
+ (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@barocss/kit")):typeof define=="function"&&define.amd?define(["exports","@barocss/kit"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l.BaroCSSBrowser={},l.BaroCSSKit))})(this,(function(l,h){"use strict";class g{constructor(t,e=50,s="barocss-style-partition-",i=r=>h.parseClassName(r).utility?.category){this.partitions=[],this.categoryPartitions=new Map,this.partitionCounter=0,this.maxRulesPerPartition=50,this.classToPartitionMap=new Map,this.classToCategoryPartitionMap=new Map,this.styleIdPrefix="barocss-style-partition-",this.insertionPoint=t,this.maxRulesPerPartition=e,this.styleIdPrefix=s,this.getCategory=i,this.initializeDefaultPartition()}insertSorted(t,e,s){const i=t.keys??=[],r=h.upperBound(i,s),n=t.styleElement.sheet;n&&n.cssRules.length===i.length?(n.insertRule(this.escapeCssRule(e),r),t.styles.splice(r,0,e)):(t.styles.splice(r,0,e),t.styleElement.textContent=t.styles.join(`
2
2
  `)+`
3
- `),i.splice(r,0,s)}initializeDefaultPartition(){this.createNewPartition()}createNewCategoryPartition(t,e=!1){const s={id:this.styleIdPrefix+`-${t}`,styles:[],styleElement:document.createElement("style")};s.styleElement.id=s.id,s.styleElement.setAttribute("data-barocss","partition"),s.styleElement.setAttribute("data-category",t);const i=this.insertionPoint.ownerDocument?.head;return e&&i?i.insertBefore(s.styleElement,i.firstChild):this.insertionPoint.appendChild(s.styleElement),this.categoryPartitions.set(t,s),s}createNewPartition(){const t={id:this.styleIdPrefix+`-${this.partitionCounter++}`,styles:[],styleElement:document.createElement("style")};return this.partitions.push(t),t.styleElement.id=t.id,t.styleElement.setAttribute("data-barocss","partition"),t.styleElement.setAttribute("data-partition-index",this.partitionCounter.toString()),this.insertionPoint.appendChild(t.styleElement),t}hasRule(t){return this.classToPartitionMap.has(t)}hasCategoryRule(t,e){return this.classToCategoryPartitionMap.get(t)===e}setRuleCache(t,e){this.classToPartitionMap.set(t,e)}setCategoryRuleCache(t,e){this.classToCategoryPartitionMap.set(t,e)}get currentPartition(){return this.partitions[this.partitions.length-1]}getCategoryPartition(t){return this.categoryPartitions.get(t)}hasDetachedPartitions(){return[...this.partitions,...this.categoryPartitions.values()].some(t=>!t.styleElement.isConnected)}escapeCssRule(t){return t.replace(/\\\//g,"\\/")}addRule(t){if(this.hasRule(t))return!1;const e=C(t);let s=this.partitions.findIndex(r=>{const o=r.keys;return!!o&&o.length>0&&P(o[o.length-1],e)>0});s===-1&&(this.currentPartition.styles.length>=this.maxRulesPerPartition&&this.createNewPartition(),s=this.partitions.length-1);const i=this.partitions[s];try{return this.insertSorted(i,t,e),this.setRuleCache(t,s),!0}catch(r){return console.warn(`[StylePartitionManager] Failed to insert rule: ${t}`,r),!1}}addCategoryRule(t,e){if(this.hasCategoryRule(t,e))return!1;let s=this.getCategoryPartition(e);s||(s=this.createNewCategoryPartition(e));try{this.insertSorted(s,t,C(t))}catch(i){return console.warn(`[StylePartitionManager] Failed to insert rule in category: ${e} ${t}`,i),!1}return this.setCategoryRuleCache(t,e),!0}addRootRules(t){let e=this.getCategoryPartition("root");e||(e=this.createNewCategoryPartition("root"));try{const s=e.styleElement.sheet;for(const i of t)s?s.insertRule(this.escapeCssRule(i),s.cssRules.length):e.styleElement.textContent+=i+`
3
+ `),i.splice(r,0,s)}initializeDefaultPartition(){this.createNewPartition()}createNewCategoryPartition(t,e=!1){const s={id:this.styleIdPrefix+`-${t}`,styles:[],styleElement:document.createElement("style")};s.styleElement.id=s.id,s.styleElement.setAttribute("data-barocss","partition"),s.styleElement.setAttribute("data-category",t);const i=this.insertionPoint.ownerDocument?.head;return e&&i?i.insertBefore(s.styleElement,i.firstChild):this.insertionPoint.appendChild(s.styleElement),this.categoryPartitions.set(t,s),s}createNewPartition(){const t={id:this.styleIdPrefix+`-${this.partitionCounter++}`,styles:[],styleElement:document.createElement("style")};return this.partitions.push(t),t.styleElement.id=t.id,t.styleElement.setAttribute("data-barocss","partition"),t.styleElement.setAttribute("data-partition-index",this.partitionCounter.toString()),this.insertionPoint.appendChild(t.styleElement),t}hasRule(t){return this.classToPartitionMap.has(t)}hasCategoryRule(t,e){return this.classToCategoryPartitionMap.get(t)===e}setRuleCache(t,e){this.classToPartitionMap.set(t,e)}setCategoryRuleCache(t,e){this.classToCategoryPartitionMap.set(t,e)}get currentPartition(){return this.partitions[this.partitions.length-1]}getCategoryPartition(t){return this.categoryPartitions.get(t)}hasDetachedPartitions(){return[...this.partitions,...this.categoryPartitions.values()].some(t=>!t.styleElement.isConnected)}escapeCssRule(t){return t.replace(/\\\//g,"\\/")}addRule(t){if(this.hasRule(t))return!1;const e=h.ruleSortKey(t);let s=this.partitions.findIndex(r=>{const n=r.keys;return!!n&&n.length>0&&h.compareKeys(n[n.length-1],e)>0});s===-1&&(this.currentPartition.styles.length>=this.maxRulesPerPartition&&this.createNewPartition(),s=this.partitions.length-1);const i=this.partitions[s];try{return this.insertSorted(i,t,e),this.setRuleCache(t,s),!0}catch(r){return console.warn(`[StylePartitionManager] Failed to insert rule: ${t}`,r),!1}}addCategoryRule(t,e){if(this.hasCategoryRule(t,e))return!1;let s=this.getCategoryPartition(e);s||(s=this.createNewCategoryPartition(e));try{this.insertSorted(s,t,h.ruleSortKey(t))}catch(i){return console.warn(`[StylePartitionManager] Failed to insert rule in category: ${e} ${t}`,i),!1}return this.setCategoryRuleCache(t,e),!0}addRootRules(t){let e=this.getCategoryPartition("root");e||(e=this.createNewCategoryPartition("root"));try{const s=e.styleElement.sheet;for(const i of t)s?s.insertRule(this.escapeCssRule(i),s.cssRules.length):e.styleElement.textContent+=i+`
4
4
  `}catch(s){return console.warn(`[StylePartitionManager] Failed to insert rule in category: root ${t.join(`
5
- `)}`,s),{success:0,failed:t.length}}return{success:t.length,failed:0}}addRules(t){let e=0,s=0;for(const i of t){const r=this.getCategory(i.cls);if(r)for(const o of i.cssList)this.addCategoryRule(o,r);else for(const o of i.cssList)this.addRule(o)?e++:s++}return{success:e,failed:s}}findRulePartition(t){const e=this.classToPartitionMap.get(t);if(e!==void 0&&this.partitions[e])return this.partitions[e];const s=this.classToCategoryPartitionMap.get(t);return s!==void 0&&this.categoryPartitions.get(s)||null}updateRuleContent(t,e,s=!1){const i=this.getCategoryPartition(t);if(i)i.styleElement.textContent=e;else{const r=this.createNewCategoryPartition(t,s);console.log(`[StylePartitionManager] Created new partition for category: ${t}`),r.styleElement.textContent=e}}cleanup(){this.partitions.forEach(t=>{t.styleElement.parentNode&&t.styleElement.parentNode.removeChild(t.styleElement)}),this.categoryPartitions.forEach(t=>{t.styleElement.parentNode&&t.styleElement.parentNode.removeChild(t.styleElement)}),this.partitions=[],this.categoryPartitions.clear(),this.partitionCounter=0,this.classToPartitionMap.clear(),this.classToCategoryPartitionMap.clear()}}function R(n){return n?typeof n=="object"&&typeof n.baseVal=="string"?n.baseVal:n.toString():""}function u(n){return n?R(n).split(/\s+/).filter(Boolean):[]}class b{constructor(t,e,s=i=>c.parseClassName(i).utility?.category){this.observer=null,this.incrementalParser=t,this.BrowserRuntime=e,this.getCategory=s}setParser(t){this.incrementalParser=t}observe(t=document.body,e){return typeof window>"u"?new MutationObserver(()=>{}):(this.observer&&this.observer.disconnect(),this.observer=new MutationObserver(s=>{const i=new Set;if(s.forEach(r=>{if(r.type==="attributes"&&r.attributeName==="class"&&t.contains(r.target)){const o=r.target;o.className&&u(o.className).forEach(h=>{this.incrementalParser.isProcessed(h)||i.add(h)})}r.type==="childList"&&r.addedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE&&t.contains(o)){const l=o;this.processElement(l,i),l.querySelectorAll("[class]").forEach(h=>{this.processElement(h,i)})}})}),i.size>0){const r=Array.from(i),o=this.incrementalParser.processClasses(r);this.BrowserRuntime?.applyParseResults(o)}else this.BrowserRuntime?.applyParseResults([])}),this.observer.observe(t,{attributes:!0,subtree:!0,attributeFilter:["class"],childList:!0}),e?.scan&&this.scanExistingClasses(t,e),this.observer)}scanExistingClasses(t,e){const s=new Set;t.className&&u(t.className).forEach(o=>{this.incrementalParser.isProcessed(o)||s.add(o)});const i=t.querySelectorAll("[class]");for(const r of i)if(r.className){const o=u(r.className);for(const l of o)this.incrementalParser.isProcessed(l)||s.add(l)}if(s.size>0){const r=Array.from(s),o=this.incrementalParser.processClasses(r),l=o.filter(m=>this.getCategory(m.cls)==="layout"),h=o.filter(m=>this.getCategory(m.cls)!=="layout");this.BrowserRuntime?.applyParseResults(l),e?.onReady?.(),this.BrowserRuntime?.applyParseResults(h)}else e?.onReady?.()}processElement(t,e){t.className&&u(t.className).forEach(i=>{this.incrementalParser.isProcessed(i)||e.add(i)})}disconnect(){this.observer&&(this.observer.disconnect(),this.observer=null)}}function T(n){return n.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(t,e,s)=>e?String.fromCodePoint(parseInt(e,16)):s)}const B=/^\s*\.((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7F])+)/;function $(n){const t=[];let e=0,s=0;for(let i=0;i<n.length;i++){const r=n[i];r==="\\"?i++:r==="("||r==="["?e++:r===")"||r==="]"?e--:r===","&&e===0&&(t.push(n.slice(s,i)),s=i+1)}return t.push(n.slice(s)),t}function S(n,t=new Set){for(const e of Array.from(n)){const s=e.selectorText;if(typeof s=="string")for(const r of $(s)){const o=B.exec(r);o&&t.add(T(o[1]))}const i=e.cssRules;i&&i.length&&S(i,t)}return t}const E="@layer theme, base, components, utilities;";class w{constructor(t={}){this.cache=new Map,this.rootCache=new Set,this.isDestroyed=!1,this.existing=null,this.existingSheetCount=-1,this.getCategory=s=>c.parseClassName(s,this.context).utility?.category;const e={};this.options={config:t.config||e,styleId:t.styleId||"barocss-runtime",insertionPoint:t.insertionPoint||"head",maxRulesPerPartition:t.maxRulesPerPartition||50,skipExisting:t.skipExisting??!1},this.context=c.createContext(this.options.config),this.incrementalParser=new c.IncrementalParser(this.context),this.changeDetector=new b(this.incrementalParser,this,this.getCategory),this.stylePartitionManager=new f(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.init()}debugLog(t,e,s){(console[t]||console.log)(`[BrowserRuntime:${t.toUpperCase()}] ${e}`,s||"")}init(){console.log("[BrowserRuntime] init"),this.injectPreflightCSS(),this.ensureCssVars()}injectPreflightCSS(){const t=this.options.config.preflight??!0;if(t){const e=this.context.getPreflightCSS(t);this.stylePartitionManager.updateRuleContent("preflight",`${E}
5
+ `)}`,s),{success:0,failed:t.length}}return{success:t.length,failed:0}}addRules(t){let e=0,s=0;for(const i of t){const r=this.getCategory(i.cls);if(r)for(const n of i.cssList)this.addCategoryRule(n,r);else for(const n of i.cssList)this.addRule(n)?e++:s++}return{success:e,failed:s}}removeRule(t,e){let s;if(e){if(this.classToCategoryPartitionMap.get(t)!==e)return!1;s=this.categoryPartitions.get(e)}else{const o=this.classToPartitionMap.get(t);s=o===void 0?void 0:this.partitions[o]}if(!s)return!1;const i=s.styles.indexOf(t);if(i===-1)return!1;const r=s.styleElement.sheet,n=!!r&&r.cssRules.length===s.styles.length;return s.styles.splice(i,1),s.keys?.splice(i,1),n&&r?r.deleteRule(i):s.styleElement.textContent=s.styles.length?s.styles.join(`
6
+ `)+`
7
+ `:"",e?this.classToCategoryPartitionMap.delete(t):this.classToPartitionMap.delete(t),!0}get ruleCount(){return this.classToPartitionMap.size+this.classToCategoryPartitionMap.size}findRulePartition(t){const e=this.classToPartitionMap.get(t);if(e!==void 0&&this.partitions[e])return this.partitions[e];const s=this.classToCategoryPartitionMap.get(t);return s!==void 0&&this.categoryPartitions.get(s)||null}updateRuleContent(t,e,s=!1){const i=this.getCategoryPartition(t);if(i)i.styleElement.textContent=e;else{const r=this.createNewCategoryPartition(t,s);console.log(`[StylePartitionManager] Created new partition for category: ${t}`),r.styleElement.textContent=e}}cleanup(){this.partitions.forEach(t=>{t.styleElement.parentNode&&t.styleElement.parentNode.removeChild(t.styleElement)}),this.categoryPartitions.forEach(t=>{t.styleElement.parentNode&&t.styleElement.parentNode.removeChild(t.styleElement)}),this.partitions=[],this.categoryPartitions.clear(),this.partitionCounter=0,this.classToPartitionMap.clear(),this.classToCategoryPartitionMap.clear()}}function C(a){return a?typeof a=="object"&&typeof a.baseVal=="string"?a.baseVal:a.toString():""}function d(a){return a?C(a).split(/\s+/).filter(Boolean):[]}class P{constructor(t,e,s=i=>h.parseClassName(i).utility?.category){this.observer=null,this.gc=null,this.incrementalParser=t,this.BrowserRuntime=e,this.getCategory=s}setGc(t){this.gc=t}setParser(t){this.incrementalParser=t}observe(t=document.body,e){return typeof window>"u"?new MutationObserver(()=>{}):(this.observer&&this.observer.disconnect(),this.gc?.setRoot(t),this.observer=new MutationObserver(s=>{const i=new Set,r=this.gc;if(s.forEach(n=>{if(r&&(n.type==="attributes"?r.reconcile(n.target):n.type==="childList"&&(n.removedNodes.forEach(o=>r.reconcileTree(o)),n.addedNodes.forEach(o=>r.reconcileTree(o)))),n.type==="attributes"&&n.attributeName==="class"&&t.contains(n.target)){const o=n.target;o.className&&d(o.className).forEach(u=>{this.incrementalParser.isProcessed(u)||i.add(u)})}n.type==="childList"&&n.addedNodes.forEach(o=>{if(o.nodeType===Node.ELEMENT_NODE&&t.contains(o)){const c=o;this.processElement(c,i),c.querySelectorAll("[class]").forEach(u=>{this.processElement(u,i)})}})}),i.size>0){const n=Array.from(i),o=this.incrementalParser.processClasses(n);this.BrowserRuntime?.applyParseResults(o)}else this.BrowserRuntime?.applyParseResults([]);r?.afterBatch()}),this.observer.observe(t,{attributes:!0,subtree:!0,attributeFilter:["class"],childList:!0}),e?.scan&&this.scanExistingClasses(t,e),this.observer)}scanExistingClasses(t,e){const s=new Set;t.className&&d(t.className).forEach(n=>{this.incrementalParser.isProcessed(n)||s.add(n)});const i=t.querySelectorAll("[class]");for(const r of i)if(r.className){const n=d(r.className);for(const o of n)this.incrementalParser.isProcessed(o)||s.add(o)}if(s.size>0){const r=Array.from(s),n=this.incrementalParser.processClasses(r),o=n.filter(u=>this.getCategory(u.cls)==="layout"),c=n.filter(u=>this.getCategory(u.cls)!=="layout");this.BrowserRuntime?.applyParseResults(o),e?.onReady?.(),this.BrowserRuntime?.applyParseResults(c)}else e?.onReady?.()}processElement(t,e){t.className&&d(t.className).forEach(i=>{this.incrementalParser.isProcessed(i)||e.add(i)})}disconnect(){this.observer&&(this.observer.disconnect(),this.observer=null)}}function M(a){return a.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g,(t,e,s)=>e?String.fromCodePoint(parseInt(e,16)):s)}const v=/^\s*(?::(?:where|is)\(\s*)?\.((?:\\[0-9a-fA-F]{1,6}\s?|\\.|[\w-]|[^\x00-\x7F])+)/;function A(a){const t=[];let e=0,s=0;for(let i=0;i<a.length;i++){const r=a[i];r==="\\"?i++:r==="("||r==="["?e++:r===")"||r==="]"?e--:r===","&&e===0&&(t.push(a.slice(s,i)),s=i+1)}return t.push(a.slice(s)),t}function R(a,t=new Set){for(const e of Array.from(a)){if(e.type===7&&typeof e.name=="string"){t.add(e.name);continue}const s=e.cssRules;s&&s.length&&R(s,t)}return t}function y(a,t=new Set){for(const e of Array.from(a)){const s=e.selectorText;if(typeof s=="string")for(const r of A(s)){const n=v.exec(r);n&&t.add(M(n[1]))}const i=e.cssRules;i&&i.length&&y(i,t)}return t}class T{constructor(t,e,s,i=()=>Date.now()){this.host=t,this.graceMs=e,this.maxRules=s,this.now=i,this.counts=new Map,this.counted=new WeakMap,this.candidates=new Map,this.timer=null,this.root=null}setRoot(t){this.counts.clear(),this.counted=new WeakMap,this.candidates.clear(),this.cancel(),this.root=t,this.reconcileTree(t)}count(t){return this.counts.get(t)??0}reconcileTree(t){if(t.nodeType!==1)return;const e=t;this.reconcile(e),e.querySelectorAll("[class]").forEach(s=>this.reconcile(s))}reconcile(t){const e=this.root,i=!!e&&e.contains(t)?Array.from(new Set(d(t.getAttribute("class")))):[],r=this.counted.get(t);if(!r&&i.length===0)return;const n=new Set(r??[]),o=new Set(i);for(const c of o){if(n.has(c))continue;const u=(this.counts.get(c)??0)+1;this.counts.set(c,u),this.candidates.delete(c)}for(const c of n){if(o.has(c))continue;const u=(this.counts.get(c)??0)-1;u>0?this.counts.set(c,u):(this.counts.delete(c),this.candidates.delete(c),this.candidates.set(c,this.now()))}i.length?this.counted.set(t,i):this.counted.delete(t)}afterBatch(){this.candidates.size!==0&&(this.host.cachedCount()>this.maxRules?this.schedule(0):this.schedule(this.graceMs))}schedule(t){if(this.timer!==null){if(t>0)return;clearTimeout(this.timer)}this.timer=setTimeout(()=>{this.timer=null,this.sweep()},t)}sweep(){const t=this.now(),e=Math.max(0,this.host.cachedCount()-this.maxRules),s=[];let i=0;for(const[r,n]of this.candidates){const o=t-n>=this.graceMs;!o&&i>=e||(this.candidates.delete(r),!(this.count(r)>0||this.inDom(r)||this.host.isPermanent(r))&&(s.push(r),o||i++))}s.length&&this.host.reclaim(s),this.candidates.size&&this.schedule(this.graceMs)}inDom(t){const e=this.root;if(!e)return!1;const s=e.ownerDocument??document;return e.classList.contains(t)||s.documentElement.classList.contains(t)||s.getElementsByClassName(t).length>0}cancel(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}stats(){return{trackedClasses:this.counts.size,candidates:this.candidates.size}}}const S="style[data-barocss-ssr]",b="@layer theme, base, components, utilities;";class w{constructor(t={}){this.cache=new Map,this.rootCache=new Set,this.isDestroyed=!1,this.existing=null,this.existingKeyframes=new Set,this.existingSheetCount=-1,this.pinned=new Set,this.gc=null,this.reclaimedCount=0,this.ssrRules=[],this.ssrClasses=new Set,this.observedOnce=!1,this.getCategory=s=>h.parseClassName(s,this.context).utility?.category;const e={};this.options={config:t.config||e,styleId:t.styleId||"barocss-runtime",insertionPoint:t.insertionPoint||"head",maxRulesPerPartition:t.maxRulesPerPartition||50,skipExisting:t.skipExisting??!1,gc:t.gc??!0,gcGraceMs:t.gcGraceMs??3e3,maxRules:t.maxRules??1/0},this.context=h.createContext(this.options.config),this.incrementalParser=new h.IncrementalParser(this.context),this.changeDetector=new P(this.incrementalParser,this,this.getCategory),this.stylePartitionManager=new g(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.options.gc&&(this.gc=new T({reclaim:s=>this.reclaim(s),isPermanent:s=>this.isPermanent(s),cachedCount:()=>this.cache.size},this.options.gcGraceMs,this.options.maxRules),this.changeDetector.setGc(this.gc)),this.init()}debugLog(t,e,s){(console[t]||console.log)(`[BrowserRuntime:${t.toUpperCase()}] ${e}`,s||"")}init(){console.log("[BrowserRuntime] init"),this.injectPreflightCSS(),this.ensureCssVars(),this.adoptSsrSheets()}adoptSsrSheets(){if(typeof document>"u")return;const t=[];if(document.head){for(const e of Array.from(document.head.querySelectorAll(`${S}:not([data-barocss-adopted])`))){const s=e.sheet;if(!s)continue;e.setAttribute("data-barocss-adopted","");const i=[];for(let r=s.cssRules.length-1;r>=0;r--){const n=s.cssRules[r],o=y([n]);o.size!==0&&(o.forEach(c=>this.ssrClasses.add(c)),i.unshift({css:n.cssText,cls:o.values().next().value}),s.deleteRule(r))}t.push(...i)}t.length!==0&&(this.ssrRules.push(...t),this.insertSsrRules(t))}}insertSsrRules(t){for(const{css:e,cls:s}of t){const i=this.getCategory(s);i?this.stylePartitionManager.addCategoryRule(e,i):this.stylePartitionManager.addRule(e)}}injectPreflightCSS(){const t=this.options.config.preflight??!0;if(t){const e=this.context.getPreflightCSS(t);this.stylePartitionManager.updateRuleContent("preflight",`${b}
6
8
  @layer base {
7
9
  ${e}
8
- }`,!0)}}ensureCssVars(){if(this.isDestroyed)return;const t=this.context.themeToCssVars?this.context.themeToCssVars():":root { /* CSS Variables will be generated here */ }";this.stylePartitionManager.updateRuleContent("css-vars",t)}getInsertionPoint(){if(typeof this.options.insertionPoint!="string")return this.options.insertionPoint;switch(this.options.insertionPoint){case"body":return document.body||document.head;case"head":default:return document.head}}addClass(t){if(this.isDestroyed)return;const e=this.normalizeClasses(t);this.processClasses(e)}processClasses(t){this.processClassesIncremental(t)}processClassesIncremental(t){const e=typeof window<"u",s=this.incrementalParser.processClasses(t);console.log("[BrowserRuntime] results",s,...t),this.applyParseResults(s,{isBrowser:e})}applyParseResults(t,e){if(this.isDestroyed)return;if(this.getInsertionPoint().isConnected&&this.stylePartitionManager.hasDetachedPartitions()){const r=Array.from(this.cache.values());this.reset(),t=[...r,...t],t.forEach(o=>this.incrementalParser.markProcessed(o.cls))}if(this.options.skipExisting&&t.length>0&&typeof document<"u"){const r=this.getExistingClasses();t=t.filter(o=>!r.has(o.cls))}if(t.length===0)return;const s=[],i=[];for(const r of t)if(r.css&&Array.isArray(r.cssList)&&(s.push(r),this.cache.set(r.cls,r)),r.rootCss&&Array.isArray(r.rootCssList))for(const o of r.rootCssList)this.rootCache.has(o)||(this.rootCache.add(o),i.push(o));i.length>0&&this.stylePartitionManager.addRootRules(i.filter(Boolean)),s.length>0&&this.stylePartitionManager.addRules(s),this.debugLog("info",`Applied ${t.length} parser results`,{cssRuleCount:s.length,rootCssCount:i.length})}getExistingClasses(){const t=Array.from(document.styleSheets).filter(s=>{const i=s.ownerNode;return!(i&&typeof i.hasAttribute=="function"&&(i.hasAttribute("data-barocss")||(i.id||"").startsWith(this.options.styleId)))});if(this.existing&&t.length===this.existingSheetCount)return this.existing;const e=new Set;for(const s of t){let i;try{i=s.cssRules}catch{continue}S(i,e)}return this.existing=e,this.existingSheetCount=t.length,e}observe(t=document.body,e){return this.changeDetector.observe(t,e)}normalizeClasses(t){return Array.isArray(t)?t.flatMap(e=>e.split(/\s+/)):t.split(/\s+/)}has(t){return this.cache.has(t)}getCss(t){return this.cache.get(t)?.cssList.join(`
10
+ }`,!0)}}ensureCssVars(){if(this.isDestroyed)return;const t=this.context.themeToCssVars?this.context.themeToCssVars():":root { /* CSS Variables will be generated here */ }";this.stylePartitionManager.updateRuleContent("css-vars",t)}getInsertionPoint(){if(typeof this.options.insertionPoint!="string")return this.options.insertionPoint;switch(this.options.insertionPoint){case"body":return document.body||document.head;case"head":default:return document.head}}addClass(t){if(this.isDestroyed)return;const e=this.normalizeClasses(t).filter(Boolean);e.forEach(s=>this.pinned.add(s)),this.processClasses(e)}processClasses(t){this.processClassesIncremental(t)}processClassesIncremental(t){const e=typeof window<"u",s=this.incrementalParser.processClasses(t);console.log("[BrowserRuntime] results",s,...t),this.applyParseResults(s,{isBrowser:e})}applyParseResults(t,e){if(this.isDestroyed)return;if(this.getInsertionPoint().isConnected&&this.stylePartitionManager.hasDetachedPartitions()){const n=Array.from(this.cache.values());this.reset(),t=[...n,...t],t.forEach(o=>this.incrementalParser.markProcessed(o.cls))}if(this.ssrClasses.size>0&&(t=t.filter(n=>!this.ssrClasses.has(n.cls))),this.options.skipExisting&&t.length>0&&typeof document<"u"){const n=this.getExistingClasses();t=t.filter(o=>!n.has(o.cls))}if(t.length===0)return;const s=[],i=[],r=this.options.skipExisting&&typeof document<"u"?(this.getExistingClasses(),this.existingKeyframes):null;for(const n of t)if(n.css&&Array.isArray(n.cssList)&&(s.push(n),this.cache.set(n.cls,n)),n.rootCss&&Array.isArray(n.rootCssList))for(const o of n.rootCssList){if(r?.size){const c=/^\s*@keyframes\s+([^\s{]+)/.exec(o)?.[1];if(c&&r.has(c))continue}this.rootCache.has(o)||(this.rootCache.add(o),i.push(o))}i.length>0&&this.stylePartitionManager.addRootRules(i.filter(Boolean)),s.length>0&&this.stylePartitionManager.addRules(s),this.debugLog("info",`Applied ${t.length} parser results`,{cssRuleCount:s.length,rootCssCount:i.length})}isPermanent(t){return this.pinned.has(t)||this.ssrClasses.has(t)||typeof document>"u"?!0:this.getExistingClasses().has(t)}reclaim(t){if(this.isDestroyed)return;const e=t.filter(r=>this.cache.has(r));if(e.length===0)return;const s=e.map(r=>this.cache.get(r));e.forEach(r=>{this.cache.delete(r),this.incrementalParser.unmarkProcessed(r)});const i=new Set;for(const r of this.cache.values())r.cssList.forEach(n=>i.add(n));for(const r of s){const n=this.getCategory(r.cls);for(const o of r.cssList)i.has(o)||this.stylePartitionManager.removeRule(o,n)}this.reclaimedCount+=e.length}getExistingClasses(){const t=new Set(Array.from(document.querySelectorAll("style[data-barocss]"),r=>r.sheet)),e=Array.from(document.styleSheets).filter(r=>{if(t.has(r))return!1;const n=r.ownerNode;return!(n&&typeof n.hasAttribute=="function"&&(n.hasAttribute("data-barocss")||(n.id||"").startsWith(this.options.styleId)))});if(this.existing&&e.length===this.existingSheetCount)return this.existing;const s=new Set,i=new Set;for(const r of e){let n;try{n=r.cssRules}catch{continue}y(n,s),R(n,i)}return this.existingKeyframes=i,this.existing=s,this.existingSheetCount=e.length,s}observe(t=document.body,e){return this.observedOnce||(this.observedOnce=!0,this.adoptSsrSheets()),this.changeDetector.observe(t,e)}normalizeClasses(t){return Array.isArray(t)?t.flatMap(e=>e.split(/\s+/)):t.split(/\s+/)}has(t){return this.cache.has(t)}getCss(t){return this.cache.get(t)?.cssList.join(`
9
11
  `)}getAllCss(){return[...this.rootCache,...Array.from(this.cache.values()).flatMap(e=>e.cssList)].join(`
10
- `)}getClasses(){return Array.from(this.cache.keys())}getCacheStats(){const t=this.incrementalParser.getStats();return{runtime:{cachedClasses:this.cache.size,rootCacheSize:this.rootCache.size},ast:t.cacheStats.ast,incremental:t}}clearCaches(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),c.clearAstCache(this.context),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new f(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars())}reset(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new f(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars())}updateConfig(t){if(this.isDestroyed)return;const e=Array.from(this.cache.keys());this.options.config=t,this.context=c.createContext(t),this.incrementalParser=new c.IncrementalParser(this.context),this.changeDetector.setParser(this.incrementalParser),this.reset(),e.length>0&&this.addClass(e)}removeClass(t){if(this.isDestroyed)return;const e=new Set(this.normalizeClasses(t)),s=Array.from(this.cache.values()).filter(i=>!e.has(i.cls));s.length!==this.cache.size&&(this.reset(),s.forEach(i=>this.incrementalParser.markProcessed(i.cls)),this.applyParseResults(s))}destroy(){this.isDestroyed||(this.changeDetector.disconnect(),this.stylePartitionManager.cleanup(),this.cache.clear(),this.rootCache.clear(),this.isDestroyed=!0)}getStats(){return{cachedClasses:this.cache.size,styleElementId:this.options.styleId,isDestroyed:this.isDestroyed,config:this.options.config,cacheStats:this.getCacheStats()}}}let d=null,y;function x(n={}){return!d||d.getStats().isDestroyed?(d=new w(n),y=n.config):n.config&&n.config!==y&&(d.updateConfig(n.config),y=n.config),d}function g({loadingClassName:n="baro-boot",...t}={}){if(!document.body){document.addEventListener("DOMContentLoaded",()=>g({loadingClassName:n,...t}),{once:!0});return}const e=`${n}-doing`,s=`${n}-done`;try{document.body.classList.add(e),x(t).observe(document.body,{scan:!0,onReady:()=>{document.body.classList.remove(e),document.body.classList.add(s)}})}catch(i){document.body?.classList.remove(e),console.error("BaroCSS boot failed:",i)}}const j=g;function A(n){if(!n||typeof n!="object"||Array.isArray(n))return[];const t=n.elements;if(!t||typeof t!="object"||Array.isArray(t))return[];const e=new Set;for(const s of Object.keys(t)){const i=t[s];if(!i||typeof i!="object"||Array.isArray(i))continue;const r=i.props;if(!r||typeof r!="object"||Array.isArray(r))continue;const o=r.className;if(typeof o=="string")for(const l of o.split(/\s+/))l&&e.add(l)}return Array.from(e)}function z(n,t){const e=A(n);e.length>0&&t.addClass(e)}const _={colors:Object.fromEntries(["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","destructive","border","input","ring","chart-1","chart-2","chart-3","chart-4","chart-5","sidebar","sidebar-foreground","sidebar-primary","sidebar-primary-foreground","sidebar-accent","sidebar-accent-foreground","sidebar-border","sidebar-ring"].map(n=>[n,`var(--${n})`])),borderRadius:{sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)"}};a.BrowserRuntime=w,a.ChangeDetector=b,a.LAYER_ORDER=E,a.StylePartitionManager=f,a.baroBoot=g,a.baroStart=j,a.collectJsonRenderClassNames=A,a.getRuntime=x,a.normalizeClassName=R,a.normalizeClassNameList=u,a.preloadJsonRenderClasses=z,a.shadcnTheme=_,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})}));
12
+ `)}getClasses(){return Array.from(this.cache.keys())}getCacheStats(){const t=this.incrementalParser.getStats();return{runtime:{cachedClasses:this.cache.size,rootCacheSize:this.rootCache.size,ruleCount:this.stylePartitionManager.ruleCount,reclaimedClasses:this.reclaimedCount,gc:this.gc?.stats()??null},ast:t.cacheStats.ast,incremental:t}}clearCaches(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),h.clearAstCache(this.context),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new g(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars(),this.insertSsrRules(this.ssrRules))}reset(){this.isDestroyed||(this.cache.clear(),this.rootCache.clear(),this.incrementalParser.clearProcessed(),this.stylePartitionManager.cleanup(),this.stylePartitionManager=new g(this.getInsertionPoint(),this.options.maxRulesPerPartition,`${this.options.styleId}-partition`,this.getCategory),this.injectPreflightCSS(),this.ensureCssVars(),this.insertSsrRules(this.ssrRules))}updateConfig(t){if(this.isDestroyed)return;const e=Array.from(this.cache.keys());this.options.config=t,this.context=h.createContext(t),this.incrementalParser=new h.IncrementalParser(this.context),this.changeDetector.setParser(this.incrementalParser),this.reset(),e.length>0&&this.addClass(e)}removeClass(t){if(this.isDestroyed)return;const e=new Set(this.normalizeClasses(t)),s=Array.from(this.cache.values()).filter(i=>!e.has(i.cls));s.length!==this.cache.size&&(this.reset(),s.forEach(i=>this.incrementalParser.markProcessed(i.cls)),this.applyParseResults(s))}destroy(){this.isDestroyed||(this.changeDetector.disconnect(),this.gc?.cancel(),this.stylePartitionManager.cleanup(),this.cache.clear(),this.rootCache.clear(),this.isDestroyed=!0)}getStats(){return{cachedClasses:this.cache.size,styleElementId:this.options.styleId,isDestroyed:this.isDestroyed,config:this.options.config,cacheStats:this.getCacheStats()}}}let f=null,m;function E(a={}){return!f||f.getStats().isDestroyed?(f=new w(a),m=a.config):a.config&&a.config!==m&&(f.updateConfig(a.config),m=a.config),f}function p({loadingClassName:a="baro-boot",...t}={}){if(!document.body){document.addEventListener("DOMContentLoaded",()=>p({loadingClassName:a,...t}),{once:!0});return}const e=`${a}-doing`,s=`${a}-done`;try{document.body.classList.add(e),E(t).observe(document.body,{scan:!0,onReady:()=>{document.body.classList.remove(e),document.body.classList.add(s)}})}catch(i){document.body?.classList.remove(e),console.error("BaroCSS boot failed:",i)}}const N=p;function x(a){if(!a||typeof a!="object"||Array.isArray(a))return[];const t=a.elements;if(!t||typeof t!="object"||Array.isArray(t))return[];const e=new Set;for(const s of Object.keys(t)){const i=t[s];if(!i||typeof i!="object"||Array.isArray(i))continue;const r=i.props;if(!r||typeof r!="object"||Array.isArray(r))continue;const n=r.className;if(typeof n=="string")for(const o of n.split(/\s+/))o&&e.add(o)}return Array.from(e)}function L(a,t){const e=x(a);e.length>0&&t.addClass(e)}const D={colors:Object.fromEntries(["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","destructive","border","input","ring","chart-1","chart-2","chart-3","chart-4","chart-5","sidebar","sidebar-foreground","sidebar-primary","sidebar-primary-foreground","sidebar-accent","sidebar-accent-foreground","sidebar-border","sidebar-ring"].map(a=>[a,`var(--${a})`])),borderRadius:{sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)"}};l.BrowserRuntime=w,l.ChangeDetector=P,l.LAYER_ORDER=b,l.SSR_STYLE_SELECTOR=S,l.StylePartitionManager=g,l.baroBoot=p,l.baroStart=N,l.collectJsonRenderClassNames=x,l.getRuntime=E,l.normalizeClassName=C,l.normalizeClassNameList=d,l.preloadJsonRenderClasses=L,l.shadcnTheme=D,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barocss/browser",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/barocss/barocss.git",
@@ -24,7 +24,7 @@
24
24
  "access": "public"
25
25
  },
26
26
  "dependencies": {
27
- "@barocss/kit": "0.5.0"
27
+ "@barocss/kit": "0.7.0"
28
28
  },
29
29
  "devDependencies": {
30
30
  "jsdom": "^26.1.0",