adopted-style-sheets
Version:
This library implements functions to use the adopted style of web components for multiple themes.
12 lines (9 loc) • 10.7 kB
JavaScript
;const c$1=require("loglevel");function _interopDefaultCompat(e){return e&&typeof e=="object"&&"default"in e?e.default:e}const c__default=_interopDefaultCompat(c$1),createTranslation=(e,t)=>s=>s(e,t),createTheme=(e,t)=>s=>s(e,t,{append:!1}),isTestEnvironment=()=>{const e=typeof process<"u"&&process.env?process.env:{},t=e.NODE_ENV==="test",s="VITEST"in e,a="JEST_WORKER_ID"in e,o="PLAYWRIGHT_TEST_BASE_URL"in e,r=e.CI==="true",n=e.TEST==="true"||e.IS_TEST==="true",i=typeof navigator<"u"&&navigator.webdriver===!0,g=typeof navigator<"u"&&/playwright|puppeteer|webdriver|selenium|testcafe/i.test(navigator.userAgent);return t||s||a||o||r||n||i||g},STORE={A11yUi:{CSS_STYLE_CACHE:new Map,IS_TEST_ENVIRONMENT:isTestEnvironment(),PERFORMANCE_MEASURES:new Map,STYLING_TASK_QUEUE:new Map,THEMES:new Map,showAverageTimes:()=>{const e={};for(const[s,a]of STORE.A11yUi.PERFORMANCE_MEASURES.entries())e[s]=[a.totalTime/a.count,a.count];const t=Object.entries(e).sort((s,a)=>a[1][0]-s[1][0]);return console.table(Object.fromEntries(t.map(([s,[a,o]])=>[s,{"avg (ms)":parseFloat(a.toFixed(2)),count:o}]))),e}}};let l=!0,h$1=!1;const E$1=/^[a-z][a-z0-9]{1,}(-[a-z0-9]+)?$/,C$1=e=>typeof e=="string"&&E$1.test(e),m$1=e=>{if(!C$1(e))throw new Error(`[Theming] The theme identifier "${typeof e=="string"?e:""}" (Type: ${typeof e}) is not valid. Please use only follow this pattern: /^[a-z][a-z0-9]{1,}(-[a-z0-9]+)?$/`)},f$1=e=>e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s*([{}:;,])\s*/g,"$1").replace(/\s+/g," ").replace(/;\}/g,"}").trim(),patchThemeTag=(e,t,s,a)=>setThemeTag(e,t,s,a),setThemeTag=(e,t,s,a)=>{a=a??{},a.append=a.append??!1,m$1(e),l&&!h$1&&(h$1=!0,c__default.warn(`[Theming] The theme process is locked. This means that the theme "${e}" should not be patched.
import { register } from 'adopted-style-sheets';
import { defineCustomElements } from '...';
import { THEME } from '...';
register(THEME, defineCustomElements)
.then(() => {
// run your app or website
})
.catch(console.warn);`));let o=STORE.A11yUi.THEMES.get(e);if(o||(o=new Map,STORE.A11yUi.THEMES.set(e,o)),a.append&&o.has(t)){const r=o.get(t);o.set(t,f$1(`${r}${s}`))}else o.set(t,f$1(s))},patchTheme=(e,t,s,a)=>setTheme(e,t,s,a),setTheme=(e,t,s,a)=>(m$1(e),typeof t=="object"&&t!==null&&Object.getOwnPropertyNames(t).forEach(o=>{const r=t[o],n=o.toLowerCase(),i=typeof a?.transformTagName=="function"&&!["GLOBAL","PROPERTIES"].includes(o)?a.transformTagName(n):o;typeof r=="string"&&r.length>0&&setThemeTag(e,i.toUpperCase(),r,s)}),e),T$1=e=>{if(e instanceof HTMLElement){if(typeof e.dataset.theme=="string")return e;{let t=e.parentNode;for(;t instanceof ShadowRoot;)t=t.host;return T$1(t)}}else return null},d$1=(e={})=>e.themeEncroachCss==="false"||e.themeReset==="true"?!1:{mode:e.themeEncroachCssMode==="after"||e.themeEncroachCssMode==="before"?e.themeEncroachCssMode:"before"},u$1=()=>typeof STORE.A11yUi.Theme=="object"&&STORE.A11yUi.Theme!==null&&typeof STORE.A11yUi.Theme.cache=="boolean"&&typeof STORE.A11yUi.Theme.encroachCss=="object"&&STORE.A11yUi.Theme.encroachCss!==null&&typeof STORE.A11yUi.Theme.encroachCss.mode=="string"&&typeof STORE.A11yUi.Theme.name=="string",w=()=>!(typeof STORE.A11yUi.Theme=="object"&&STORE.A11yUi.Theme!==null)||STORE.A11yUi.Theme.name!=="default",getThemeDetails=e=>{if(u$1())return STORE.A11yUi.Theme;{const t={cache:!0,encroachCss:d$1(),loglevel:"silent",mode:"csr",name:null},s=T$1(e);return s instanceof HTMLElement&&(t.cache=s.dataset.themeCache!=="false",t.encroachCss=d$1(s.dataset),t.loglevel=s.dataset.themeLoglevel==="debug"?s.dataset.themeLoglevel:"silent",t.mode=s.dataset.themeMode==="ssr"?s.dataset.themeMode:"csr",t.name=s.dataset.theme||null),t}},getTheme=e=>getThemeDetails(e).name,M$1=(e,t)=>({cache:t.cache!==!1,detect:t.detect==="auto"?"auto":"fixed",encroachCss:t.encroachCss===!1?!1:typeof t.encroachCss=="object"&&t.encroachCss!=null&&(t.encroachCss.mode==="after"||t.encroachCss.mode==="before")?t.encroachCss:{mode:"before"},loglevel:t.loglevel==="debug"?t.loglevel:"silent",mode:t.mode==="ssr"?t.mode:"csr",name:typeof t.name=="string"?t.name:e}),A$1=(e,t)=>{u$1()===!1&&w()&&typeof t=="object"&&t!==null&&(t=M$1(e,t),t.detect==="fixed"?(t.name===null&&typeof e=="string"&&(t.name=e),e===t.name&&(STORE.A11yUi.Theme=t,c__default.info(`[Theming] Theme "${e}" was set as default theme.`))):h$1||(h$1=!0,c__default.warn("[Theming] The presetting of theme options is only relevant by using 'fixed' detection mode.")))},getRegisteredThemeNames=()=>Array.from(STORE.A11yUi.THEMES.keys()),getRegisteredThemes=()=>STORE.A11yUi.THEMES,getRegisteredThemeByName=e=>STORE.A11yUi.THEMES.get(e);let p$1=!1;const register=(e,t,s={})=>{p$1||(p$1=!0,l=!1,typeof window<"u"&&(window.A11yUi=STORE.A11yUi)),typeof e=="function"?e=new Set([e]):Array.isArray(e)&&(e=new Set(e)),e instanceof Set&&e.forEach(o=>{typeof o=="function"&&o.length===1?A$1(o((r,n,i)=>setTheme(r,n,i,s)),{cache:s.theme?.cache,detect:s.theme?.detect,encroachCss:s.theme?.encroachCss,mode:s.theme?.mode,name:s.theme?.name}):c__default.error("[Theming] An attempt was made to load an incompatible theme.")}),l=!0,typeof t=="function"?t=new Set([t]):Array.isArray(t)&&(t=new Set(t));const a=[];return t.forEach(o=>{const r=o();r instanceof Promise&&a.push(r)}),Promise.all(a)};class RobustStore{static options={enumerable:!1,immutable:!1};static instances=new Map;store;constructor(t,s){this.store=this.createStore(t,s)}static getInstance(t,s){let a=RobustStore.instances.get(t);return a===void 0&&(a=new RobustStore(s,t),RobustStore.instances.set(t,a)),a}createStore(t,s){return Object.defineProperty(t,s,{enumerable:!1,value:{},writable:!1}),t[s]}recursiveSetItem(t,s,a,o=RobustStore.options){let r=typeof a=="object"&&a!==null?{}:a;if(Object.defineProperty(t,s,{enumerable:o.enumerable===!0,get:()=>r,set:o.immutable===!0?void 0:n=>r=n}),typeof a=="object"&&a!==null)for(const[n,i]of Object.entries(a))this.recursiveSetItem(t[s],n,i,o)}setItem(t,s,a=RobustStore.options){return this.recursiveSetItem(this.store,t,s,a),this}getItem(t){return Array.isArray(t)?t.map(s=>this.getItem(s)):this.store[t]}}const S=new Set,L=/--[^;]+/g,p=/:/,A=typeof MutationObserver<"u";let E=25,h=()=>{E=Math.min(25+Math.log2(STORE.A11yUi.STYLING_TASK_QUEUE.size+1)*20,250)};const M=(e,t)=>{let s=t.match(L);if(Array.isArray(s)){s=s.filter(o=>p.test(o));const a=document.createElement("style");a.innerHTML=`.${e} {${s.join(";")}}`,document.querySelector("head")?.appendChild(a)}S.add(e)},getCssStyle=(e,t)=>{const s=STORE.A11yUi.THEMES.get(e);return s instanceof Map&&s.has(t)?s.get(t):""},R=e=>{for(const t of Array.from(e.childNodes))if(t instanceof HTMLStyleElement&&t.tagName==="STYLE"&&t.dataset.themingFallback===void 0)e.removeChild(t);else break},C=(e,t)=>{try{if(STORE.A11yUi.Theme?.mode==="ssr")throw new Error("SSR");const s=[];t.forEach(a=>{const o=new CSSStyleSheet;o.replaceSync(a),s.push(o)}),e.adoptedStyleSheets=s}catch{[...t].reverse().forEach((a,o)=>{if(typeof a!="string"||a.length===0)return;const r=document.createElement("style");switch(r.dataset.themingFallback="",o){case 4:r.dataset.themingBaseA11y="";break;case 3:r.dataset.themingBaseGlobal="";break;case 2:r.dataset.themingBaseComponent="";break;case 1:r.dataset.themingCustomGlobal="";break;case 0:r.dataset.themingCustomComponent="";break;default:r.dataset.themingUnknown="";break}r.innerHTML=a,e.insertBefore(r,e.firstChild)})}},_=(e,t,s)=>{if(s!==!1){const a=[...Array.from(e.childNodes).filter(r=>r instanceof HTMLStyleElement&&r.tagName==="STYLE")];let o;try{o=[...Array.from(e.adoptedStyleSheets)]}catch{o=[]}s?.mode==="before"?(a.reverse().forEach(r=>t.unshift(r.innerHTML)),o.reverse().forEach(r=>t.unshift(Array.from(r.cssRules).map(n=>n.cssText).join("")))):s?.mode==="after"&&(a.forEach(r=>t.push(r.innerHTML)),o.forEach(r=>t.push(Array.from(r.cssRules).map(n=>n.cssText).join(""))))}},b=(e,t,s)=>{const a=t.name||"default";let o;try{if(e.shadowRoot===null)throw new Error("ShadowRoot is null");o=e.shadowRoot}catch{o=e}if(STORE.A11yUi.CSS_STYLE_CACHE.get(a)?.has(e.tagName))T(e,o,STORE.A11yUi.CSS_STYLE_CACHE.get(a)?.get(e.tagName),s);else{const r=getCssStyle(a,"PROPERTIES"),n=getCssStyle(a,"GLOBAL"),i=getCssStyle(a,e.tagName);S.has(a)===!1&&M(a,n);const g=[r,n,i];_(o,g,t.encroachCss),t.cache===!0&&(STORE.A11yUi.CSS_STYLE_CACHE.has(a)===!1&&STORE.A11yUi.CSS_STYLE_CACHE.set(a,new Map),STORE.A11yUi.CSS_STYLE_CACHE.get(a)?.set(e.tagName,g)),T(e,o,g,s)}},T=(e,t,s,a)=>{const o=performance.now();if(R(t),C(t,s),u(e),a(),STORE.A11yUi.PERFORMANCE_MEASURES.has(e.tagName)){const r=STORE.A11yUi.PERFORMANCE_MEASURES.get(e.tagName);r.count+=1,r.totalTime+=performance.now()-o}else STORE.A11yUi.PERFORMANCE_MEASURES.set(e.tagName,{count:1,totalTime:performance.now()-o})},y=e=>{const t=STORE.A11yUi.STYLING_TASK_QUEUE.get(e);if(t){const{resetCss:s,themeDetails:a}=t;b(e,a,s),u(e)}};let c=e=>{const t=setTimeout(()=>{clearTimeout(t),e.classList.contains("hydrated")?y(e):c(e)},E)};const H={attributes:!0,attributeFilter:["class"],childList:!1,subtree:!1},U={attributes:!0,attributeFilter:[],childList:!1,subtree:!1},m=A?new MutationObserver((e,t)=>{for(const s of e){const a=s.target;a.classList.contains("hydrated")&&(y(a),t.observe(a,U))}}):null;m&&(c=e=>m.observe(e,H),h=()=>{});let d=e=>{const t=getComputedStyle(e).getPropertyValue("--theme-visibility-delay").trim();if(t.endsWith("ms"))return parseFloat(t);if(t.endsWith("s"))return parseFloat(t)*1e3;{const s=parseFloat(t);return isNaN(s)?0:s}};STORE.A11yUi.IS_TEST_ENVIRONMENT&&(d=()=>0);const f=(e,t)=>{e.style.setProperty("visibility",t),e.dataset.themed=""},N=(e,t)=>{const s=e.style.visibility||null;STORE.A11yUi.STYLING_TASK_QUEUE.set(e,{resetCss:()=>{const a=d(e);a>0?setTimeout(()=>{f(e,s)},a):f(e,s)},themeDetails:t}),e.style.setProperty("visibility","hidden","important"),c(e)},u=e=>{STORE.A11yUi.STYLING_TASK_QUEUE.delete(e),h()},setThemeStyle=(e,t)=>{N(e,{...STORE.A11yUi.Theme,...t})};class Theme{Prefix;Key;Tag;createTheme=(t,s)=>createTheme(t,s);createTranslation=(t,s)=>createTranslation(t,s);constructor(t,s,a){this.Prefix=t,this.Key=Object.getOwnPropertyNames(s),this.Tag=Object.getOwnPropertyNames(a)}}exports.RobustStore=RobustStore,exports.STORE=STORE,exports.Theme=Theme,exports.getCssStyle=getCssStyle,exports.getRegisteredThemeByName=getRegisteredThemeByName,exports.getRegisteredThemeNames=getRegisteredThemeNames,exports.getRegisteredThemes=getRegisteredThemes,exports.getTheme=getTheme,exports.getThemeDetails=getThemeDetails,exports.patchTheme=patchTheme,exports.patchThemeTag=patchThemeTag,exports.register=register,exports.setTheme=setTheme,exports.setThemeStyle=setThemeStyle,exports.setThemeTag=setThemeTag;