UNPKG

adopted-style-sheets

Version:

This library implements functions to use the adopted style of web components for multiple themes.

12 lines (9 loc) 8.62 kB
import l from"loglevel";const R=(e,t)=>s=>s(e,t),H=(e,t)=>s=>s(e,t,{append:!1}),$=new Map,M=[],Y=new Map,a={A11yUi:{CSS_STYLE_CACHE:$,HYDRATED_HISTORY:M,STYLING_TASK_QUEUE:Y,Themes:{}}};let T=!0,y=!1;const I=/^[a-z][a-z0-9]{1,}(-[a-z0-9]+)?$/,O=e=>typeof e=="string"&&I.test(e),A=e=>{if(O(e)===!1)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]+)?$/`)},k=(e,t,s,o)=>p(e,t,s,o),p=(e,t,s,o)=>{o=o??{},o.append=o.append??!1,A(e),T===!0&&y===!1&&(y=!0,l.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);`)),(typeof a.A11yUi.Themes[e]!="object"||a.A11yUi.Themes[e]===null)&&(a.A11yUi.Themes[e]={}),o.append&&typeof a.A11yUi.Themes[e][t]=="string"?a.A11yUi.Themes[e][t]+=s:a.A11yUi.Themes[e][t]=s},P=(e,t,s,o)=>u(e,t,s,o),u=(e,t,s,o)=>(A(e),typeof t=="object"&&t!==null&&Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],i=n.toLowerCase(),m=typeof o?.transformTagName=="function"&&!["GLOBAL","PROPERTIES"].includes(n)?o.transformTagName(i):n;typeof r=="string"&&r.length>0&&p(e,m.toUpperCase(),r,s)}),e),S=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 S(t)}}else return null},U=(e={})=>e.themeEncroachCss==="false"||e.themeReset==="true"?!1:{mode:e.themeEncroachCssMode==="after"||e.themeEncroachCssMode==="before"?e.themeEncroachCssMode:"before"},E=()=>typeof a.A11yUi=="object"&&a.A11yUi!==null&&typeof a.A11yUi.Theme=="object"&&a.A11yUi.Theme!==null&&typeof a.A11yUi.Theme.cache=="boolean"&&typeof a.A11yUi.Theme.encroachCss=="object"&&a.A11yUi.Theme.encroachCss!==null&&typeof a.A11yUi.Theme.encroachCss.mode=="string"&&typeof a.A11yUi.Theme.name=="string",D=()=>!(typeof a.A11yUi=="object"&&a.A11yUi!==null)||!(typeof a.A11yUi.Theme=="object"&&a.A11yUi.Theme!==null)||a.A11yUi.Theme.name!=="default",b=e=>{if(E())return a.A11yUi.Theme;{const t={cache:!0,encroachCss:U(),loglevel:"silent",mode:"csr",name:null},s=S(e);return s instanceof HTMLElement&&(t.cache=s.dataset.themeCache!=="false",t.encroachCss=U(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}},G=e=>b(e).name,K=(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}),Q=(e,t)=>{E()===!1&&D()&&typeof t=="object"&&t!==null&&(t=K(e,t),t.detect==="fixed"?(t.name===null&&typeof e=="string"&&(t.name=e),e===t.name&&(a.A11yUi.Theme=t,l.info(`[Theming] Theme "${e}" was set as default theme.`))):y||(y=!0,l.warn("[Theming] The presetting of theme options is only relevant by using 'fixed' detection mode.")))},x=()=>Object.keys(a.A11yUi.Themes),z=()=>a.A11yUi.Themes,B=e=>a.A11yUi.Themes[e];let C=!1;const F=(e,t,s={})=>{C===!1&&(C=!0,T=!1),typeof e=="function"?e=new Set([e]):Array.isArray(e)&&(e=new Set(e)),e instanceof Set&&e.forEach(n=>{typeof n=="function"&&n.length===1?Q(n((r,i,m)=>u(r,i,m,s)),{cache:s.theme?.cache,detect:s.theme?.detect,encroachCss:s.theme?.encroachCss,mode:s.theme?.mode,name:s.theme?.name}):l.error("[Theming] An attempt was made to load an incompatible theme.")}),T=!0,typeof t=="function"?t=new Set([t]):Array.isArray(t)&&(t=new Set(t));const o=[];return t.forEach(n=>{const r=n();r instanceof Promise&&o.push(r)}),Promise.all(o)},c=class{constructor(e,t){this.store=this.createStore(e,t)}static getInstance(e,t){let s=c.instances.get(e);return s===void 0&&(s=new c(t,e),c.instances.set(e,s)),s}createStore(e,t){return Object.defineProperty(e,t,{enumerable:!1,value:{},writable:!1}),e[t]}recursiveSetItem(e,t,s,o=c.options){let n=typeof s=="object"&&s!==null?{}:s;if(Object.defineProperty(e,t,{enumerable:o.enumerable===!0,get:()=>n,set:o.immutable===!0?void 0:r=>n=r}),typeof s=="object"&&s!==null)for(const[r,i]of Object.entries(s))this.recursiveSetItem(e[t],r,i,o)}setItem(e,t,s=c.options){return this.recursiveSetItem(this.store,e,t,s),this}getItem(e){return Array.isArray(e)?e.map(t=>this.getItem(t)):this.store[e]}};let g=c;g.options={enumerable:!1,immutable:!1},g.instances=new Map;const w=new Set,q=/--[^;]+/g,J=/:/,V=(e,t)=>{let s=t.match(q);if(Array.isArray(s)){s=s.filter(n=>J.test(n));const o=document.createElement("style");o.innerHTML=`.${e} {${s.join(";")}}`,document.querySelector("head")?.appendChild(o)}w.add(e)},f=(e,t)=>typeof a.A11yUi=="object"&&a.A11yUi!==null&&typeof a.A11yUi.Themes=="object"&&a.A11yUi.Themes!==null&&typeof a.A11yUi.Themes[e]=="object"&&a.A11yUi.Themes[e]!==null&&typeof a.A11yUi.Themes[e][t]=="string"?a.A11yUi.Themes[e][t].replace(/\r?\n/g,""):"",W=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},X=(e,t)=>{try{if(a.A11yUi.Theme?.mode==="ssr")throw new Error("SSR");const s=[];t.forEach(o=>{const n=new CSSStyleSheet;n.replaceSync(o),s.push(n)}),e.adoptedStyleSheets=s}catch{[...t].reverse().forEach((s,o)=>{if(typeof s!="string"||s.length===0)return;const n=document.createElement("style");switch(n.dataset.themingFallback="",o){case 4:n.dataset.themingBaseA11y="";break;case 3:n.dataset.themingBaseGlobal="";break;case 2:n.dataset.themingBaseComponent="";break;case 1:n.dataset.themingCustomGlobal="";break;case 0:n.dataset.themingCustomComponent="";break;default:n.dataset.themingUnknown="";break}n.innerHTML=s,e.insertBefore(n,e.firstChild)})}},Z=(e,t,s)=>{if(s!==!1){const o=[...Array.from(e.childNodes).filter(r=>r instanceof HTMLStyleElement&&r.tagName==="STYLE")];let n;try{n=[...Array.from(e.adoptedStyleSheets)]}catch{n=[]}s?.mode==="before"?(o.reverse().forEach(r=>t.unshift(r.innerHTML)),n.reverse().forEach(r=>t.unshift(Array.from(r.cssRules).map(i=>i.cssText).join("")))):s?.mode==="after"&&(o.forEach(r=>t.push(r.innerHTML)),n.forEach(r=>t.push(Array.from(r.cssRules).map(i=>i.cssText).join(""))))}},L=(e,t,s)=>{const o=t.name||"default";let n;try{if(e.shadowRoot===null)throw new Error("ShadowRoot is null");n=e.shadowRoot}catch{n=e}if(a.A11yUi.CSS_STYLE_CACHE.get(o)?.has(e.tagName))_(e,n,a.A11yUi.CSS_STYLE_CACHE.get(o)?.get(e.tagName),s);else{const r=f(o,"PROPERTIES"),i=f(o,"GLOBAL"),m=f(o,e.tagName);w.has(o)===!1&&V(o,i);const h=[r,i,m];Z(n,h,t.encroachCss),t.loglevel==="debug"&&console.log(e.tagName,h),t.cache===!0&&(a.A11yUi.CSS_STYLE_CACHE.has(o)===!1&&a.A11yUi.CSS_STYLE_CACHE.set(o,new Map),a.A11yUi.CSS_STYLE_CACHE.get(o)?.set(e.tagName,h)),_(e,n,h,s)}},_=(e,t,s,o)=>{W(t),X(t,s),e.style.display=o},N=e=>{e.loglevel==="debug"&&a.A11yUi.HYDRATED_HISTORY.push({timestamp:Date.now(),numberOfTasks:a.A11yUi.STYLING_TASK_QUEUE.size})},ee=(e,t)=>{a.A11yUi.STYLING_TASK_QUEUE.set(e,{styleDisplay:e.style.display?`${e.style.display}`:null,themeDetails:t})},te=(e,t)=>{ee(e,t),N(t)},se=e=>{a.A11yUi.STYLING_TASK_QUEUE.delete(e)},j=(e,t)=>{se(e),N(t)},v=e=>{const t=setTimeout(()=>{if(clearTimeout(t),a.A11yUi.STYLING_TASK_QUEUE.has(e)&&e.classList.contains("hydrated")){const{styleDisplay:s,themeDetails:o}=a.A11yUi.STYLING_TASK_QUEUE.get(e);L(e,o,s),j(e,o)}else v(e)},25)},oe=e=>{for(const t of e)if(a.A11yUi.STYLING_TASK_QUEUE.has(t.target)&&t.target.classList.contains("hydrated")){const{styleDisplay:s,themeDetails:o}=a.A11yUi.STYLING_TASK_QUEUE.get(t.target);L(t.target,o,s),j(t.target,o)}},ae={attributes:!0,attributeFilter:["class"],childList:!1,subtree:!1};let d;try{d=new MutationObserver(oe)}catch{d=null}const ne=(e,t)=>{t={...a.A11yUi.Theme,...t},te(e,t),d?d.observe(e,ae):v(e),e.style.display="none"};class re{constructor(t,s,o){this.createTheme=(n,r)=>H(n,r),this.createTranslation=(n,r)=>R(n,r),this.Prefix=t,this.Key=Object.getOwnPropertyNames(s),this.Tag=Object.getOwnPropertyNames(o)}}export{g as RobustStore,a as STORE,re as Theme,f as getCssStyle,B as getRegisteredThemeByName,x as getRegisteredThemeNames,z as getRegisteredThemes,G as getTheme,b as getThemeDetails,P as patchTheme,k as patchThemeTag,F as register,u as setTheme,ne as setThemeStyle,p as setThemeTag};