Files
monkey-ai-web/scripts/vite/legacy-css-layers.js
T
2026-11-18 19:09:00 +08:00

235 lines
9.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import postcss from 'postcss';
// 旧浏览器的级联层(@layer)兜底。
//
// index.css 把 Tailwind 的 base / components / utilities 整体包在原生 @layer 里,
// Semi 的按需样式也由 vitePluginSemi({ cssLayer: true }) 包进 @layer semi。
// @layer 自 Chromium 99 / Firefox 97 / Safari 15.4 才支持;更老的内核(停更的
// Edge、Win10 LTSC 自带 Edge、各类国产壳浏览器)把它当未知 at-rule 连同块内
// 全部规则一起丢弃 —— Tailwind 整体失效,页面只剩无尺寸约束的原图 logo。
//
// 这里在构建期把入口样式表里各层的内容按层序压平成一份不含 @layer 的样式表,
// index.html 里的内联探测脚本只在浏览器不认识 @layer 时才加载它。支持 @layer 的
// 浏览器不会请求这个文件,原有样式与层叠关系一个字节都不变。
//
// 压平只是近似,目标是页面可用而非像素一致。兜底表排在所有入口样式表之前,
// 因此「同特异性的普通声明,层外胜」得以保持;以下两点与原生级联层不同,
// 旧浏览器里会表现为局部外观差异(07 号文档 §95 有实例):
// - 层内 !important 本应无条件压过层外 !important,压平后改按特异性与先后;
// - 层内选择器特异性高于层外时会反超,原生层叠里层外恒胜。
// at 关键字大小写不敏感(@LAYER 也是合法写法),PostCSS 保留原始大小写,比较前统一
const isAtRule = (node, name) =>
node.type === 'atrule' && node.name.toLowerCase() === name;
const isLayer = (node) => isAtRule(node, 'layer');
// 文本里出现 @layer 不等于真有层规则(注释、字符串里也可能有这几个字),
// 先粗筛再解析确认,免得把没分层的样式表算进「必须兜底」的名单
const hasLayerRule = (css) => {
if (!/@layer/i.test(css)) return false;
let found = false;
postcss.parse(css).walkAtRules(/^layer$/i, () => {
found = true;
return false;
});
return found;
};
// 只认「顶层的具名/匿名层块 + 层序声明」这一种形态(当前产物仅此一种)。
// 嵌套层、点号层名、条件块里的层、@import layer() 的优先级规则各不相同,
// 近似处理会悄悄排错顺序或漏收样式,而这类错误在新浏览器上完全看不出来 ——
// 所以遇到就让构建失败,由人来决定怎么扩展。
const assertSupportedShape = (root) => {
const reject = (what) => {
throw new Error(
`[legacy-css-layers] 入口样式表出现了 ${what},旧浏览器兜底尚不支持这种写法。` +
'请先扩展 scripts/vite/legacy-css-layers.js 的 flattenCssLayers 再构建。',
);
};
root.walkAtRules((rule) => {
if (isLayer(rule) && rule.parent !== root) {
reject(`非顶层的 @layer ${rule.params}`);
}
if (isLayer(rule) && rule.params.includes('.')) {
reject(`带点号的层名 @layer ${rule.params}`);
}
if (isAtRule(rule, 'import')) {
// 先去掉 url() 与字符串,免得文件名里的 layer 字样被当成关键字
const flags = rule.params.replace(/url\([^)]*\)|"[^"]*"|'[^']*'/gi, '');
if (/\blayer\b/i.test(flags)) reject(`@import ${rule.params}`);
}
});
};
/**
* 从一组按文档顺序排列的 CSS 源码中取出所有级联层,按层序拼成不含 @layer 的 CSS。
* 层序与浏览器一致:按层名首次出现的先后(`@layer a, b;` 声明与 `@layer a {}` 块
* 都算出现),先出现的优先级低,因此排在前面。不在任何层里的规则不收录 ——
* 它们在旧浏览器里本来就生效。
*/
export function flattenCssLayers(sources) {
const roots = sources.map((css) => postcss.parse(css));
roots.forEach(assertSupportedShape);
// 层外已有逐字相同的规则时,层内那份不必收:选择器与声明都一样、层外的又加载
// 在后,它在旧浏览器里必然被覆盖。Semi 的 @layer 副本整份属于这种情况
// (index.jsx 另行全量引入了层外的 semi.css),剔掉后兜底表只剩约五分之一。
const unlayered = new Set();
for (const root of roots) {
root.each((node) => {
if (!isLayer(node) && node.type !== 'comment') {
unlayered.add(node.toString());
}
});
}
const layers = new Map();
const layerOf = (name) => {
if (!layers.has(name)) layers.set(name, []);
return layers.get(name);
};
for (const root of roots) {
root.each((node) => {
if (!isLayer(node)) return;
if (!node.nodes) {
postcss.list.comma(node.params).forEach(layerOf);
return;
}
// 匿名层各自独立,用块对象本身当 key 避免互相合并
layerOf(node.params.trim() || node).push(
node.nodes.filter((child) => !unlayered.has(child.toString())),
);
});
}
const flattened = postcss.root();
for (const blocks of layers.values()) {
for (const nodes of blocks) flattened.append(nodes);
}
return flattened.toString();
}
// 内联探测脚本:不经过转译,语法须停留在 ES5,且同步执行。
// 用 document.write 而非 createElement 插入 <link>:解析器创建的样式表与其余
// 入口样式表一样阻塞首帧,不会先闪一下无样式页面。
const buildLoader = (href) =>
`<script>
(function () {
try {
var probe = document.createElement('style');
probe.textContent = '@layer wl-probe{}';
document.head.appendChild(probe);
var supported = probe.sheet.cssRules.length > 0;
document.head.removeChild(probe);
if (supported) return;
} catch (e) {
return;
}
document.write('<link rel="stylesheet" href="${href}">');
})();
</script>
`;
const STYLESHEET_LINK = /<link\b[^>]*\brel="stylesheet"[^>]*>/g;
const CONDITIONAL_LINK = /\s(?:media|disabled)(?=[\s=>/])/i;
// Rollup 的 asset.source 可能是 string 或 Uint8Array
const sourceText = (asset) =>
typeof asset.source === 'string'
? asset.source
: Buffer.from(asset.source).toString('utf8');
export default function legacyCssLayers() {
let base = '/';
return {
name: 'legacy-css-layers',
apply: 'build',
// 排在 vite:build-html 之后:此时 index.html 已带上最终的样式表 <link>
enforce: 'post',
configResolved(config) {
base = config.base;
},
generateBundle(_, bundle) {
const layered = Object.keys(bundle).filter(
(name) =>
name.endsWith('.css') &&
bundle[name].type === 'asset' &&
hasLayerRule(sourceText(bundle[name])),
);
if (!layered.length) return;
// 走到这里说明产物确实依赖 @layer。注入所依赖的 index.html 或入口 <link>
// 找不到时,旧浏览器拿不到兜底而新浏览器上毫无征兆 —— 让构建失败,不静默跳过。
const page = bundle['index.html'];
if (page?.type !== 'asset') {
this.error('样式表用到了 @layer,但产物里没有 index.html 可供注入兜底');
}
const html = sourceText(page);
// 入口样式表:能对应到产物文件、且无条件加载的 <link>,按文档顺序(层序取决于它)。
// 只认解析得出产物文件的标签,注释或脚本字符串里的同形文本不会被当成锚点;
// 带 media / disabled 的标签只在特定条件下生效,它的规则既不能无条件收进兜底表,
// 也不能拿来给别的样式表剔重,所以不算入口。
const entry = [...html.matchAll(STYLESHEET_LINK)]
.filter(([tag]) => !CONDITIONAL_LINK.test(tag))
.map((match) => ({
at: match.index,
href: /\bhref="([^"]+)"/.exec(match[0])?.[1],
}))
.filter(({ href }) => href?.startsWith(base))
.map(({ at, href }) => ({ at, name: href.slice(base.length) }))
.filter(({ name }) => bundle[name]?.type === 'asset');
if (!entry.length) {
this.error(
'样式表用到了 @layer,但没能从 index.html 里解析出任何入口样式表 <link>,无法注入兜底',
);
}
const entryNames = entry.map(({ name }) => name);
// 不经过入口 <link> 的样式表(懒加载分包、条件加载的表)兜底覆盖不到:
// 旧浏览器会丢掉它们层内的那部分样式。
for (const name of layered) {
if (entryNames.includes(name)) continue;
this.warn(`${name} 含 @layer 但不是入口样式表,旧浏览器兜底覆盖不到它`);
}
const css = flattenCssLayers(
entryNames.map((name) => sourceText(bundle[name])),
);
// 层内规则在层外全都有逐字副本:旧浏览器什么也不缺
if (!css) return;
const fileName = this.getFileName(
this.emitFile({
type: 'asset',
name: 'legacy-layers.css',
source: css,
}),
);
// 插在第一个入口样式表之前,兜底表才排在所有入口样式表前面
const { at } = entry[0];
page.source =
html.slice(0, at) + buildLoader(base + fileName) + html.slice(at);
},
};
}