| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- /**
- * lib/css.js —— 阴影根样式注入(静态 CSS 文本 + adoptedStyleSheets)。
- * 说明:site/vendor 的 lit-html 构建对 css`` 标记模板的解析在个别源码位置会抛
- * "result must not have attributes",因此页面/组件一律使用本文件里的纯文本样式,
- * 由 <style> 注入 Shadow Root(或 light DOM),不依赖渲染时再解析 css。
- */
- const sheetCache = new Map();
- function makeSheet(text) {
- if (typeof CSSStyleSheet !== 'undefined' && 'adoptedStyleSheets' in Document.prototype) {
- try {
- const s = new CSSStyleSheet();
- s.replaceSync(text);
- return s;
- } catch { /* fallthrough */ }
- }
- return null;
- }
- /**
- * 把若干段 CSS 文本施加到 root(ShadowRoot 用 adoptedStyleSheets;light DOM 元素注入 <style>)。
- * light DOM 下 :host 不匹配,会改写成元素标签名(如 ph-bom),让组件级变量 / 容器查询照常生效。
- */
- export function applyCss(root, ...texts) {
- for (const raw of texts) {
- if (!raw) continue;
- let text = typeof raw === 'string' ? raw : String(raw);
- // 样式文本可能挂在自定义元素(light DOM)上::host 选择器在页面上不命中,改写成实际标签名
- if (root && root.localName) text = text.replace(/:host\b/g, root.localName);
- let sheet = sheetCache.get(text);
- if (sheet === undefined) { sheet = makeSheet(text); sheetCache.set(text, sheet); }
- if (sheet && 'adoptedStyleSheets' in root) {
- // ShadowRoot 才有 adoptedStyleSheets;light DOM 元素用 <style> 标签
- if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
- } else {
- const st = document.createElement('style');
- st.textContent = text;
- root.prepend(st);
- }
- }
- }
- /** 把 {text} 常量转成字符串 */
- export function cssText(x) { return typeof x === 'string' ? x : ''; }
|