styimat 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![Forks](https://img.shields.io/badge/dynamic/json?label=Forks&query=%24.forks_count&url=https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Frepos%2Fwxy6987%2Fstyimat&color=red)](https://gitee.com/wxy6987/styimat/members)
4
4
  [![version](https://img.shields.io/npm/v/styimat.svg?color=brightgreen)](https://www.npmjs.com/package/styimat)
5
5
  [![license](https://img.shields.io/npm/l/styimat.svg?color=lightgrey)](LICENSE)
6
- ![size](https://img.shields.io/bundlephobia/minzip/styimat?label=size&color=blue)
6
+ [![npm 下载量](https://img.shields.io/npm/dt/styimat?label=download&color=blue)](https://www.npmjs.com/package/styimat)
7
7
 
8
8
  一个功能强大的 CSS 变量预处理库,支持嵌套规则、Lab/LCH 颜色空间转换、Display P3 广色域和增强的数学计算功能。
9
9
 
@@ -22,7 +22,7 @@ npm install
22
22
  ```
23
23
 
24
24
  ### 2. 直接下载 ZIP
25
- - [点击下载最新版本](https://gitee.com/wxy6987/styimat/repository/archive/main.zip)
25
+ [![下载ZIP压缩包](https://img.shields.io/badge/下载ZIP压缩包-007BFF?style=for-the-badge&logo=data:image/svg%2bxml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDQ4IDQ4IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxwYXRoIGQ9Ik02IDQyLjAwODNINDIiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNMzMgMjNMMjQgMzJMMTUgMjMiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI0IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNMjMuOTkxNyA2VjMyIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iNCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8%2bPC9zdmc%2b&logoColor=white)](https://gitee.com/wxy6987/styimat/repository/archive/main.zip)
26
26
 
27
27
  ### 3. NPM 安装
28
28
  ```bash
@@ -44,7 +44,7 @@ npm install styimat
44
44
  - **广色域显示** - 自动检测并支持 Display P3 广色域显示器
45
45
  - **变量系统** - 类似 Sass 的变量系统,支持作用域变量
46
46
  -️ **嵌套规则** - 支持 Sass 风格的嵌套选择器
47
- - **十六进制语法** - 支持 `lab#L16A16B16` 和 `lch#L16C16H` 简洁语法
47
+ - **十六进制语法** - 支持 `lab#LLAABB` 和 `lch#LLCCHHH` 简洁语法
48
48
  - **增强数学计算** - 支持 `math()` 函数和复杂数学表达式
49
49
  - **轻量高效** - 无依赖,压缩后仅约 20KB
50
50
  - **多种使用方式** - 浏览器、Node.js、命令行均可使用
@@ -277,6 +277,34 @@ $font-family: 'Inter', sans-serif;
277
277
  }
278
278
  ```
279
279
 
280
+ ### 导入语法
281
+
282
+ #### 您可以在CSS文件的开头使用导入文件来导入其他css文件,应该以`@import开头`:
283
+
284
+ ```css
285
+ @import "head.css";
286
+ @import url("tail.css");
287
+
288
+ /* 然后写您的CSS代码 */
289
+ $primary-color: lab#32a852;
290
+ $spacing: math(16px * 2 + 4px);
291
+
292
+ body {
293
+ color: $primary-color;
294
+ padding: $spacing;
295
+
296
+ .container {
297
+ margin: math($spacing / 2);
298
+ }
299
+ }
300
+ ```
301
+
302
+ #### 还可以使用style语法:
303
+ ```html
304
+ <!--这样就自动处理好了-->
305
+ <style src="head.css" e></style>
306
+ ```
307
+
280
308
  ### 配置头语法
281
309
 
282
310
  您可以在CSS文件的开头使用配置头来设置预处理选项,配置行以 `#` 开头:
@@ -584,7 +612,7 @@ $primary-transparent: lab(55 190 0 / 0.8);
584
612
  欢迎贡献代码!请遵循以下步骤:
585
613
 
586
614
  1. **Fork 本仓库**
587
- [![Forks](https://img.shields.io/badge/点击即可Forks-click?color=red)](https://gitee.com/wxy6987/styimat/members)
615
+ [![Forks](https://img.shields.io/badge/点击即可Forks-red?logo=gitee)](https://gitee.com/wxy6987/styimat/members)
588
616
  2. **创建特性分支**
589
617
  ```bash
590
618
  git checkout -b feature/AmazingFeature
@@ -9,7 +9,7 @@
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
11
 
12
- function main() {
12
+ async function main() {
13
13
  const args = process.argv.slice(2);
14
14
 
15
15
  let inputContent = '';
@@ -70,7 +70,7 @@ function main() {
70
70
  }
71
71
 
72
72
  // 执行转换
73
- const outputContent = huecss.convert(inputContent);
73
+ const outputContent = await huecss.convert(inputContent);
74
74
 
75
75
  // 输出结果
76
76
  if (outputFile) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "styimat",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "一个高效的CSS变量预处理库,支持Lab/LCH颜色空间自动转换、嵌套选择器和Display P3广色域,让现代CSS开发更简洁强大。",
5
5
  "keywords": [
6
6
  "css",
package/styimat.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * 支持 Display P3 广色域显示器
11
11
  * 增强 math() 函数,支持复杂数学计算
12
12
  * 支持配置头
13
+ * 支持 @import 语法
13
14
  */
14
15
  (function(root, factory) {
15
16
  if (typeof define === 'function' && define.amd) {
@@ -37,10 +38,16 @@
37
38
  enableP3: true,
38
39
  enableMath: true, // 启用math()函数增强
39
40
  mathPrecision: 6, // 数学计算精度
41
+ importBaseUrl: '', // @import 的基础URL
42
+ importCache: true, // 缓存导入的文件
43
+ importTimeout: 5000, // 导入超时时间(毫秒)
40
44
  };
41
45
 
42
46
  // 全局P3支持检测结果
43
47
  let p3Supported = null;
48
+
49
+ // 导入文件缓存
50
+ const importCache = new Map();
44
51
 
45
52
  /**
46
53
  * 解析配置头
@@ -1209,7 +1216,7 @@
1209
1216
  replaceVariableUsesInValue(value, variables),
1210
1217
  config
1211
1218
  );
1212
- return ` --${name}: ${processedValue};`;
1219
+ return " ".repeat(config.indentSize) + `--${name}: ${processedValue};`;
1213
1220
  })
1214
1221
  .join('\n');
1215
1222
 
@@ -1248,40 +1255,201 @@
1248
1255
  return result.trim();
1249
1256
  }
1250
1257
 
1251
- // 主转换函数
1252
- function convert(cssText, customConfig = {}) {
1253
- // 先解析配置头
1254
- const { config: headerConfig, css: cleanedCSS } = parseConfigHeader(cssText);
1255
- const config = { ...defaultConfig, ...customConfig,...headerConfig };
1258
+ /**
1259
+ * 处理 @import 语句
1260
+ * @param {string} cssText - CSS文本
1261
+ * @param {Object} config - 配置对象
1262
+ * @returns {Promise<string>} 处理后的CSS文本
1263
+ */
1264
+ async function processImports(cssText, config) {
1265
+ // 匹配所有@import语句
1266
+ const importRegex = /@import\s+(?:url\()?["']([^"']+)["'](?:\))?[^;]*;/g;
1267
+
1268
+ // 递归处理函数
1269
+ const processRecursive = async (text) => {
1270
+ // 使用replace更简单的方式
1271
+ const importPromises = [];
1272
+
1273
+ // 使用replace的回调函数收集所有import的promise
1274
+ const processedText = text.replace(importRegex, (match, url) => {
1275
+ const importPromise = fetchImportContent(url, config)
1276
+ .then(importedCSS => {
1277
+ // 递归处理导入的CSS中的import
1278
+ return processImports(importedCSS, config);
1279
+ })
1280
+ .catch(error => {
1281
+ console.warn(`无法导入CSS文件: ${url}`, error);
1282
+ // 导入失败时返回空字符串
1283
+ return '';
1284
+ });
1285
+
1286
+ importPromises.push(importPromise);
1287
+
1288
+ // 返回占位符
1289
+ return `__IMPORT_PLACEHOLDER_${importPromises.length - 1}__`;
1290
+ });
1291
+
1292
+ // 等待所有import完成
1293
+ if (importPromises.length > 0) {
1294
+ const importedContents = await Promise.all(importPromises);
1295
+
1296
+ // 替换占位符为实际内容
1297
+ let finalText = processedText;
1298
+ for (let i = 0; i < importedContents.length; i++) {
1299
+ finalText = finalText.replace(`__IMPORT_PLACEHOLDER_${i}__`, importedContents[i]);
1300
+ }
1301
+
1302
+ return finalText;
1303
+ }
1304
+
1305
+ return processedText;
1306
+ };
1307
+
1308
+ return processRecursive(cssText);
1309
+ }
1310
+
1311
+ /**
1312
+ * 获取导入的CSS内容
1313
+ * @param {string} url - CSS文件URL
1314
+ * @param {Object} config - 配置对象
1315
+ * @returns {Promise<string>} CSS内容
1316
+ */
1317
+ async function fetchImportContent(url, config) {
1318
+ // 检查缓存
1319
+ if (config.importCache && importCache.has(url)) {
1320
+ return importCache.get(url);
1321
+ }
1322
+
1323
+ // 构建完整的URL
1324
+ const fullUrl = config.importBaseUrl
1325
+ ? new URL(url, config.importBaseUrl).href
1326
+ : url;
1327
+
1328
+ let content;
1256
1329
 
1257
- // 1. 提取变量定义(区分全局和选择器局部)
1258
- const { globalVariables, selectorVariables, cssWithoutVars } =
1259
- extractVariablesAndCSS(cleanedCSS, config);
1330
+ // 检查是否为Node.js环境
1331
+ const isNode = typeof process !== 'undefined' &&
1332
+ process.versions &&
1333
+ process.versions.node;
1260
1334
 
1261
- // 2. 解析嵌套规则(如果启用)
1262
- let processedCSS = cssWithoutVars.trim();
1263
- if (config.enableNesting && cssWithoutVars.includes('{')) {
1335
+ if (isNode && typeof require !== 'undefined') {
1336
+ // Node.js环境:使用fs模块
1264
1337
  try {
1265
- processedCSS = parseNestedRules(cssWithoutVars, config);
1338
+ const fs = require('fs');
1339
+ const path = require('path');
1340
+
1341
+ // 处理相对路径
1342
+ let filePath = fullUrl;
1343
+ if (fullUrl.startsWith('.')) {
1344
+ filePath = path.join(process.cwd(), fullUrl);
1345
+ }
1346
+
1347
+ content = fs.readFileSync(filePath, 'utf-8');
1348
+ } catch (error) {
1349
+ throw new Error(`Node.js文件读取失败: ${fullUrl} - ${error.message}`);
1350
+ }
1351
+ } else {
1352
+ // 浏览器环境:使用fetch
1353
+ try {
1354
+ const controller = new AbortController();
1355
+ const timeoutId = setTimeout(() => controller.abort(), config.importTimeout);
1356
+
1357
+ const response = await fetch(fullUrl, {
1358
+ signal: controller.signal,
1359
+ headers: {
1360
+ 'Accept': 'text/css'
1361
+ }
1362
+ });
1363
+
1364
+ clearTimeout(timeoutId);
1365
+
1366
+ if (!response.ok) {
1367
+ throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
1368
+ }
1369
+
1370
+ content = await response.text();
1266
1371
  } catch (error) {
1267
- console.warn('嵌套解析失败,使用原始CSS:', error);
1372
+ if (error.name === 'AbortError') {
1373
+ throw new Error(`导入超时: ${fullUrl}`);
1374
+ }
1375
+ throw new Error(`无法获取CSS: ${fullUrl} - ${error.message}`);
1268
1376
  }
1269
1377
  }
1270
1378
 
1271
- // 3. 生成根规则(全局变量)
1272
- const rootRule = generateRootRule(globalVariables, config);
1273
-
1274
- // 4. 注入选择器局部变量
1275
- let finalCSS = processedCSS;
1276
- if (selectorVariables.size > 0) {
1277
- finalCSS = injectSelectorVariables(processedCSS, selectorVariables, config);
1379
+ // 缓存内容
1380
+ if (config.importCache) {
1381
+ importCache.set(url, content);
1278
1382
  }
1279
1383
 
1280
- // 5. 替换变量使用
1281
- finalCSS = replaceVariableUses(finalCSS, globalVariables, selectorVariables, config);
1384
+ return content;
1385
+ }
1386
+
1387
+ /**
1388
+ * 主转换函数
1389
+ * @param {string} cssText - CSS文本
1390
+ * @param {Object} customConfig - 自定义配置
1391
+ * @returns {string|Promise<string>} 转换后的CSS(如果是异步则为Promise)
1392
+ */
1393
+ function convert(cssText, customConfig = {}) {
1394
+ // 处理同步和异步版本
1395
+ const syncConvert = (cssText, config) => {
1396
+ // 先解析配置头
1397
+ const { config: headerConfig, css: cleanedCSS } = parseConfigHeader(cssText);
1398
+ const finalConfig = { ...defaultConfig, ...customConfig,...headerConfig };
1399
+
1400
+ // 1. 提取变量定义(区分全局和选择器局部)
1401
+ const { globalVariables, selectorVariables, cssWithoutVars } =
1402
+ extractVariablesAndCSS(cleanedCSS, finalConfig);
1403
+
1404
+ // 2. 解析嵌套规则(如果启用)
1405
+ let processedCSS = cssWithoutVars.trim();
1406
+ if (finalConfig.enableNesting && cssWithoutVars.includes('{')) {
1407
+ try {
1408
+ processedCSS = parseNestedRules(cssWithoutVars, finalConfig);
1409
+ } catch (error) {
1410
+ console.warn('嵌套解析失败,使用原始CSS:', error);
1411
+ }
1412
+ }
1413
+
1414
+ // 3. 生成根规则(全局变量)
1415
+ const rootRule = generateRootRule(globalVariables, finalConfig);
1416
+
1417
+ // 4. 注入选择器局部变量
1418
+ let finalCSS = processedCSS;
1419
+ if (selectorVariables.size > 0) {
1420
+ finalCSS = injectSelectorVariables(processedCSS, selectorVariables, finalConfig);
1421
+ }
1422
+
1423
+ // 5. 替换变量使用
1424
+ finalCSS = replaceVariableUses(finalCSS, globalVariables, selectorVariables, finalConfig);
1425
+
1426
+ // 6. 组合结果
1427
+ return rootRule + finalCSS;
1428
+ };
1429
+
1430
+ // 检查是否有@import语句(需要异步处理)
1431
+ const hasImports = cssText && /@import\s+(?:url\()?["']([^"']+)["']/i.test(cssText);
1432
+ const finalConfig = { ...defaultConfig, ...customConfig };
1282
1433
 
1283
- // 6. 组合结果
1284
- return rootRule + finalCSS;
1434
+ if (!hasImports) {
1435
+ // 没有@import,同步处理
1436
+ return syncConvert(cssText, finalConfig);
1437
+ } else {
1438
+ // 有@import,异步处理
1439
+ return (async () => {
1440
+ try {
1441
+ // 处理@import
1442
+ const processedWithImports = await processImports(cssText, finalConfig);
1443
+
1444
+ // 同步处理剩余部分
1445
+ return syncConvert(processedWithImports, finalConfig);
1446
+ } catch (error) {
1447
+ console.error('@import处理失败:', error);
1448
+ // 如果导入失败,尝试同步处理原始CSS
1449
+ return syncConvert(cleanedCSS, finalConfig);
1450
+ }
1451
+ })();
1452
+ }
1285
1453
  }
1286
1454
 
1287
1455
  // 自动处理带有 e 属性的 style 标签
@@ -1290,22 +1458,35 @@
1290
1458
  const styleTags = document.querySelectorAll(`style[${config.styleTagAttribute || 'e'}]`);
1291
1459
 
1292
1460
  styleTags.forEach(styleTag => {
1293
- const originalCSS = styleTag.textContent;
1294
- const convertedCSS = convert(originalCSS, config);
1461
+ let originalCSS = styleTag.textContent;
1295
1462
 
1296
- // 创建新的 style 标签
1297
- const newStyleTag = document.createElement('style');
1298
- newStyleTag.textContent = convertedCSS;
1299
-
1300
- // 插入到原标签后面
1301
- styleTag.parentNode.insertBefore(newStyleTag, styleTag.nextSibling);
1463
+ // 处理@import(如果是异步的)
1464
+ const processStyleTag = async () => {
1465
+ try {
1466
+ if (styleTag.getAttribute("src")){
1467
+ originalCSS = "@import url(\""+styleTag.getAttribute("src")+"\");";
1468
+ }
1469
+ const convertedCSS = await convert(originalCSS, config);
1470
+
1471
+ // 创建新的 style 标签
1472
+ const newStyleTag = document.createElement('style');
1473
+ newStyleTag.textContent = convertedCSS;
1474
+
1475
+ // 插入到原标签后面
1476
+ styleTag.parentNode.insertBefore(newStyleTag, styleTag.nextSibling);
1477
+
1478
+ // 可选:移除原标签
1479
+ if (!config.preserveOriginal) {
1480
+ styleTag.remove();
1481
+ } else {
1482
+ styleTag.style.display = 'none';
1483
+ }
1484
+ } catch (error) {
1485
+ console.error('处理style标签失败:', error);
1486
+ }
1487
+ };
1302
1488
 
1303
- // 可选:移除原标签
1304
- if (!config.preserveOriginal) {
1305
- styleTag.remove();
1306
- } else {
1307
- styleTag.style.display = 'none';
1308
- }
1489
+ processStyleTag();
1309
1490
  });
1310
1491
 
1311
1492
  return styleTags.length;
@@ -1320,11 +1501,31 @@
1320
1501
  const config = { ...defaultConfig, ...customConfig };
1321
1502
 
1322
1503
  if (cssText) {
1323
- const converted = convert(cssText, config);
1324
- const styleEl = document.createElement('style');
1325
- styleEl.textContent = converted;
1326
- document.head.appendChild(styleEl);
1327
- return styleEl;
1504
+ // 检查是否有@import
1505
+ const hasImports = /@import\s+(?:url\()?["']([^"']+)["']/i.test(cssText);
1506
+
1507
+ if (hasImports) {
1508
+ // 异步处理
1509
+ return (async () => {
1510
+ try {
1511
+ const converted = await convert(cssText, config);
1512
+ const styleEl = document.createElement('style');
1513
+ styleEl.textContent = converted;
1514
+ document.head.appendChild(styleEl);
1515
+ return styleEl;
1516
+ } catch (error) {
1517
+ console.error('应用CSS失败:', error);
1518
+ return null;
1519
+ }
1520
+ })();
1521
+ } else {
1522
+ // 同步处理
1523
+ const converted = convert(cssText, config);
1524
+ const styleEl = document.createElement('style');
1525
+ styleEl.textContent = converted;
1526
+ document.head.appendChild(styleEl);
1527
+ return styleEl;
1528
+ }
1328
1529
  } else {
1329
1530
  if (document.readyState === 'loading') {
1330
1531
  document.addEventListener('DOMContentLoaded', () => {
@@ -1349,6 +1550,40 @@
1349
1550
  // 重新检测P3支持(如果配置变化)
1350
1551
  detectP3Support: detectP3Support,
1351
1552
 
1553
+ // 导入相关方法
1554
+ imports: {
1555
+ /**
1556
+ * 清除导入缓存
1557
+ */
1558
+ clearCache: function() {
1559
+ importCache.clear();
1560
+ },
1561
+
1562
+ /**
1563
+ * 设置导入基础URL
1564
+ * @param {string} baseUrl - 基础URL
1565
+ */
1566
+ setBaseUrl: function(baseUrl) {
1567
+ defaultConfig.importBaseUrl = baseUrl;
1568
+ },
1569
+
1570
+ /**
1571
+ * 启用/禁用导入缓存
1572
+ * @param {boolean} enabled - 是否启用缓存
1573
+ */
1574
+ setCacheEnabled: function(enabled) {
1575
+ defaultConfig.importCache = enabled;
1576
+ },
1577
+
1578
+ /**
1579
+ * 设置导入超时时间
1580
+ * @param {number} timeout - 超时时间(毫秒)
1581
+ */
1582
+ setTimeout: function(timeout) {
1583
+ defaultConfig.importTimeout = timeout;
1584
+ }
1585
+ },
1586
+
1352
1587
  // 数学计算工具方法
1353
1588
  math: {
1354
1589
  /**
@@ -1526,7 +1761,13 @@
1526
1761
 
1527
1762
  // 如果传入CSS文本,则编译并返回结果
1528
1763
  if (typeof firstArg === 'string') {
1529
- return convert(firstArg, { ...defaultConfig, ...args[1] });
1764
+ const result = convert(firstArg, { ...defaultConfig, ...args[1] });
1765
+
1766
+ // 如果结果是Promise,返回Promise
1767
+ if (result && typeof result.then === 'function') {
1768
+ return result;
1769
+ }
1770
+ return result;
1530
1771
  }
1531
1772
 
1532
1773
  // 如果传入配置对象,则应用配置
@@ -1565,7 +1806,13 @@
1565
1806
  }
1566
1807
 
1567
1808
  // 使用convert函数处理
1568
- return convert(cssText, defaultConfig);
1809
+ const result = convert(cssText, defaultConfig);
1810
+
1811
+ // 如果结果是Promise,返回Promise
1812
+ if (result && typeof result.then === 'function') {
1813
+ return result;
1814
+ }
1815
+ return result;
1569
1816
  }
1570
1817
 
1571
1818
  // 将API的所有方法复制到主函数上
package/styimat.min.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * 支持 Display P3 广色域显示器
11
11
  * 增强 math() 函数,支持复杂数学计算
12
12
  * 支持配置头
13
+ * 支持 @import 语法
13
14
  */
14
15
  (function(root,factory){if(typeof define==="function"&&define.amd){
15
16
  // AMD 支持 (RequireJS)
@@ -20,9 +21,14 @@ module.exports=factory()}else{
20
21
  root.styimat=factory()}})(typeof self!=="undefined"?self:this,function(){
21
22
  // 默认配置
22
23
  let defaultConfig={rootSelector:":root",variablePrefix:"--",preserveOriginal:false,indentSize:4,enableNesting:true,autoProcessStyleTags:true,styleTagAttribute:"e",convertLabToRGB:true,convertLchToRGB:true,enableP3:true,enableMath:true,// 启用math()函数增强
23
- mathPrecision:6};
24
+ mathPrecision:6,// 数学计算精度
25
+ importBaseUrl:"",// @import 的基础URL
26
+ importCache:true,// 缓存导入的文件
27
+ importTimeout:5e3};
24
28
  // 全局P3支持检测结果
25
29
  let p3Supported=null;
30
+ // 导入文件缓存
31
+ const importCache=new Map;
26
32
  /**
27
33
  * 解析配置头
28
34
  * @param {string} cssText - CSS文本
@@ -418,45 +424,134 @@ result=result.replace(/(?:\$\$|\$)([a-zA-Z0-9_-]+)/g,(match,varName)=>match.star
418
424
  // 最后处理所有的LAB、LCH颜色和math()函数
419
425
  result=processCSSValue(result,config);return result}
420
426
  // 生成根规则
421
- function generateRootRule(variables,config){if(Object.keys(variables).length===0){return""}const declarations=Object.entries(variables).map(([name,value])=>{const processedValue=processCSSValue(replaceVariableUsesInValue(value,variables),config);return` --${name}: ${processedValue};`}).join("\n");return`${config.rootSelector} {\n${declarations}\n}\n\n`}
427
+ function generateRootRule(variables,config){if(Object.keys(variables).length===0){return""}const declarations=Object.entries(variables).map(([name,value])=>{const processedValue=processCSSValue(replaceVariableUsesInValue(value,variables),config);return" ".repeat(config.indentSize)+`--${name}: ${processedValue};`}).join("\n");return`${config.rootSelector} {\n${declarations}\n}\n\n`}
422
428
  // 处理选择器内部的变量
423
429
  function injectSelectorVariables(cssText,selectorVariables,config){let result="";const lines=cssText.split("\n");let currentSelector=null;for(let line of lines){const trimmed=line.trim();if(trimmed.endsWith("{")){currentSelector=trimmed.slice(0,-1).trim()}if(trimmed==="}"&&currentSelector){
424
430
  // 在选择器结束前插入变量声明
425
431
  if(selectorVariables.has(currentSelector)){const vars=selectorVariables.get(currentSelector);const indent=line.match(/^(\s*)/)[0];for(const[varName,varValue]of Object.entries(vars)){result+=" --"+varName+": "+varValue+";\n"}}currentSelector=null}
426
432
  // 使用全局处理函数处理所有math()和颜色
427
433
  result+=processCSSValue(line,config)+"\n"}return result.trim()}
428
- // 主转换函数
429
- function convert(cssText,customConfig={}){
434
+ /**
435
+ * 处理 @import 语句
436
+ * @param {string} cssText - CSS文本
437
+ * @param {Object} config - 配置对象
438
+ * @returns {Promise<string>} 处理后的CSS文本
439
+ */async function processImports(cssText,config){
440
+ // 匹配所有@import语句
441
+ const importRegex=/@import\s+(?:url\()?["']([^"']+)["'](?:\))?[^;]*;/g;
442
+ // 递归处理函数
443
+ const processRecursive=async text=>{
444
+ // 使用replace更简单的方式
445
+ const importPromises=[];
446
+ // 使用replace的回调函数收集所有import的promise
447
+ const processedText=text.replace(importRegex,(match,url)=>{const importPromise=fetchImportContent(url,config).then(importedCSS=>processImports(importedCSS,config)).catch(error=>{console.warn(`无法导入CSS文件: ${url}`,error);
448
+ // 导入失败时返回空字符串
449
+ return""});importPromises.push(importPromise);
450
+ // 返回占位符
451
+ return`__IMPORT_PLACEHOLDER_${importPromises.length-1}__`});
452
+ // 等待所有import完成
453
+ if(importPromises.length>0){const importedContents=await Promise.all(importPromises);
454
+ // 替换占位符为实际内容
455
+ let finalText=processedText;for(let i=0;i<importedContents.length;i++){finalText=finalText.replace(`__IMPORT_PLACEHOLDER_${i}__`,importedContents[i])}return finalText}return processedText};return processRecursive(cssText)}
456
+ /**
457
+ * 获取导入的CSS内容
458
+ * @param {string} url - CSS文件URL
459
+ * @param {Object} config - 配置对象
460
+ * @returns {Promise<string>} CSS内容
461
+ */async function fetchImportContent(url,config){
462
+ // 检查缓存
463
+ if(config.importCache&&importCache.has(url)){return importCache.get(url)}
464
+ // 构建完整的URL
465
+ const fullUrl=config.importBaseUrl?new URL(url,config.importBaseUrl).href:url;let content;
466
+ // 检查是否为Node.js环境
467
+ const isNode=typeof process!=="undefined"&&process.versions&&process.versions.node;if(isNode&&typeof require!=="undefined"){
468
+ // Node.js环境:使用fs模块
469
+ try{const fs=require("fs");const path=require("path");
470
+ // 处理相对路径
471
+ let filePath=fullUrl;if(fullUrl.startsWith(".")){filePath=path.join(process.cwd(),fullUrl)}content=fs.readFileSync(filePath,"utf-8")}catch(error){throw new Error(`Node.js文件读取失败: ${fullUrl} - ${error.message}`)}}else{
472
+ // 浏览器环境:使用fetch
473
+ try{const controller=new AbortController;const timeoutId=setTimeout(()=>controller.abort(),config.importTimeout);const response=await fetch(fullUrl,{signal:controller.signal,headers:{Accept:"text/css"}});clearTimeout(timeoutId);if(!response.ok){throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)}content=await response.text()}catch(error){if(error.name==="AbortError"){throw new Error(`导入超时: ${fullUrl}`)}throw new Error(`无法获取CSS: ${fullUrl} - ${error.message}`)}}
474
+ // 缓存内容
475
+ if(config.importCache){importCache.set(url,content)}return content}
476
+ /**
477
+ * 主转换函数
478
+ * @param {string} cssText - CSS文本
479
+ * @param {Object} customConfig - 自定义配置
480
+ * @returns {string|Promise<string>} 转换后的CSS(如果是异步则为Promise)
481
+ */function convert(cssText,customConfig={}){
482
+ // 处理同步和异步版本
483
+ const syncConvert=(cssText,config)=>{
430
484
  // 先解析配置头
431
- const{config:headerConfig,css:cleanedCSS}=parseConfigHeader(cssText);const config={...defaultConfig,...customConfig,...headerConfig};
485
+ const{config:headerConfig,css:cleanedCSS}=parseConfigHeader(cssText);const finalConfig={...defaultConfig,...customConfig,...headerConfig};
432
486
  // 1. 提取变量定义(区分全局和选择器局部)
433
- const{globalVariables:globalVariables,selectorVariables:selectorVariables,cssWithoutVars:cssWithoutVars}=extractVariablesAndCSS(cleanedCSS,config);
487
+ const{globalVariables:globalVariables,selectorVariables:selectorVariables,cssWithoutVars:cssWithoutVars}=extractVariablesAndCSS(cleanedCSS,finalConfig);
434
488
  // 2. 解析嵌套规则(如果启用)
435
- let processedCSS=cssWithoutVars.trim();if(config.enableNesting&&cssWithoutVars.includes("{")){try{processedCSS=parseNestedRules(cssWithoutVars,config)}catch(error){console.warn("嵌套解析失败,使用原始CSS:",error)}}
489
+ let processedCSS=cssWithoutVars.trim();if(finalConfig.enableNesting&&cssWithoutVars.includes("{")){try{processedCSS=parseNestedRules(cssWithoutVars,finalConfig)}catch(error){console.warn("嵌套解析失败,使用原始CSS:",error)}}
436
490
  // 3. 生成根规则(全局变量)
437
- const rootRule=generateRootRule(globalVariables,config);
491
+ const rootRule=generateRootRule(globalVariables,finalConfig);
438
492
  // 4. 注入选择器局部变量
439
- let finalCSS=processedCSS;if(selectorVariables.size>0){finalCSS=injectSelectorVariables(processedCSS,selectorVariables,config)}
493
+ let finalCSS=processedCSS;if(selectorVariables.size>0){finalCSS=injectSelectorVariables(processedCSS,selectorVariables,finalConfig)}
440
494
  // 5. 替换变量使用
441
- finalCSS=replaceVariableUses(finalCSS,globalVariables,selectorVariables,config);
495
+ finalCSS=replaceVariableUses(finalCSS,globalVariables,selectorVariables,finalConfig);
442
496
  // 6. 组合结果
443
- return rootRule+finalCSS}
497
+ return rootRule+finalCSS};
498
+ // 检查是否有@import语句(需要异步处理)
499
+ const hasImports=cssText&&/@import\s+(?:url\()?["']([^"']+)["']/i.test(cssText);const finalConfig={...defaultConfig,...customConfig};if(!hasImports){
500
+ // 没有@import,同步处理
501
+ return syncConvert(cssText,finalConfig)}else{
502
+ // 有@import,异步处理
503
+ return(async()=>{try{
504
+ // 处理@import
505
+ const processedWithImports=await processImports(cssText,finalConfig);
506
+ // 同步处理剩余部分
507
+ return syncConvert(processedWithImports,finalConfig)}catch(error){console.error("@import处理失败:",error);
508
+ // 如果导入失败,尝试同步处理原始CSS
509
+ return syncConvert(cleanedCSS,finalConfig)}})()}}
444
510
  // 自动处理带有 e 属性的 style 标签
445
- function autoProcessStyleTags(customConfig={}){const config={...defaultConfig,...customConfig};const styleTags=document.querySelectorAll(`style[${config.styleTagAttribute||"e"}]`);styleTags.forEach(styleTag=>{const originalCSS=styleTag.textContent;const convertedCSS=convert(originalCSS,config);
511
+ function autoProcessStyleTags(customConfig={}){const config={...defaultConfig,...customConfig};const styleTags=document.querySelectorAll(`style[${config.styleTagAttribute||"e"}]`);styleTags.forEach(styleTag=>{let originalCSS=styleTag.textContent;
512
+ // 处理@import(如果是异步的)
513
+ const processStyleTag=async()=>{try{if(styleTag.getAttribute("src")){originalCSS='@import url("'+styleTag.getAttribute("src")+'");'}const convertedCSS=await convert(originalCSS,config);
446
514
  // 创建新的 style 标签
447
515
  const newStyleTag=document.createElement("style");newStyleTag.textContent=convertedCSS;
448
516
  // 插入到原标签后面
449
517
  styleTag.parentNode.insertBefore(newStyleTag,styleTag.nextSibling);
450
518
  // 可选:移除原标签
451
- if(!config.preserveOriginal){styleTag.remove()}else{styleTag.style.display="none"}});return styleTags.length}function config(config={}){defaultConfig={...defaultConfig,...config}}
519
+ if(!config.preserveOriginal){styleTag.remove()}else{styleTag.style.display="none"}}catch(error){console.error("处理style标签失败:",error)}};processStyleTag()});return styleTags.length}function config(config={}){defaultConfig={...defaultConfig,...config}}
452
520
  // 初始化自动处理
453
- function apply(cssText,customConfig={}){const config={...defaultConfig,...customConfig};if(cssText){const converted=convert(cssText,config);const styleEl=document.createElement("style");styleEl.textContent=converted;document.head.appendChild(styleEl);return styleEl}else{if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",()=>{autoProcessStyleTags(config)})}else{autoProcessStyleTags(config)}}}
521
+ function apply(cssText,customConfig={}){const config={...defaultConfig,...customConfig};if(cssText){
522
+ // 检查是否有@import
523
+ const hasImports=/@import\s+(?:url\()?["']([^"']+)["']/i.test(cssText);if(hasImports){
524
+ // 异步处理
525
+ return(async()=>{try{const converted=await convert(cssText,config);const styleEl=document.createElement("style");styleEl.textContent=converted;document.head.appendChild(styleEl);return styleEl}catch(error){console.error("应用CSS失败:",error);return null}})()}else{
526
+ // 同步处理
527
+ const converted=convert(cssText,config);const styleEl=document.createElement("style");styleEl.textContent=converted;document.head.appendChild(styleEl);return styleEl}}else{if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",()=>{autoProcessStyleTags(config)})}else{autoProcessStyleTags(config)}}}
454
528
  // 返回公共 API
455
529
  const api={convert:convert,apply:apply,config:config,version:"1.9.0",
456
530
  // 检测P3支持
457
531
  supportsP3:detectP3Support(),
458
532
  // 重新检测P3支持(如果配置变化)
459
533
  detectP3Support:detectP3Support,
534
+ // 导入相关方法
535
+ imports:{
536
+ /**
537
+ * 清除导入缓存
538
+ */
539
+ clearCache:function(){importCache.clear()},
540
+ /**
541
+ * 设置导入基础URL
542
+ * @param {string} baseUrl - 基础URL
543
+ */
544
+ setBaseUrl:function(baseUrl){defaultConfig.importBaseUrl=baseUrl},
545
+ /**
546
+ * 启用/禁用导入缓存
547
+ * @param {boolean} enabled - 是否启用缓存
548
+ */
549
+ setCacheEnabled:function(enabled){defaultConfig.importCache=enabled},
550
+ /**
551
+ * 设置导入超时时间
552
+ * @param {number} timeout - 超时时间(毫秒)
553
+ */
554
+ setTimeout:function(timeout){defaultConfig.importTimeout=timeout}},
460
555
  // 数学计算工具方法
461
556
  math:{
462
557
  /**
@@ -516,7 +611,9 @@ return handleTemplateTag(...args)}
516
611
  // 获取第一个参数
517
612
  const firstArg=args[0];
518
613
  // 如果传入CSS文本,则编译并返回结果
519
- if(typeof firstArg==="string"){return convert(firstArg,{...defaultConfig,...args[1]})}
614
+ if(typeof firstArg==="string"){const result=convert(firstArg,{...defaultConfig,...args[1]});
615
+ // 如果结果是Promise,返回Promise
616
+ if(result&&typeof result.then==="function"){return result}return result}
520
617
  // 如果传入配置对象,则应用配置
521
618
  if(typeof firstArg==="object"&&firstArg!==null){defaultConfig={...defaultConfig,...firstArg};return styimat}
522
619
  // 如果没有参数,执行自动处理
@@ -528,7 +625,9 @@ let cssText=strings[0];for(let i=0;i<values.length;i++){
528
625
  // 处理插值(支持字符串、数字、函数等)
529
626
  const value=values[i];let result="";if(typeof value==="function"){result=value()}else if(Array.isArray(value)){result=value.join(" ")}else{result=String(value!=null?value:"")}cssText+=result+strings[i+1]}
530
627
  // 使用convert函数处理
531
- return convert(cssText,defaultConfig)}
628
+ const result=convert(cssText,defaultConfig);
629
+ // 如果结果是Promise,返回Promise
630
+ if(result&&typeof result.then==="function"){return result}return result}
532
631
  // 将API的所有方法复制到主函数上
533
632
  Object.assign(styimat,api);Object.setPrototypeOf(styimat,Function.prototype);
534
633
  // 自动初始化