css.js 1.9 KB

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