web-component-gallery 2.2.7 → 2.2.8

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.
@@ -1,15 +1,33 @@
1
- // 引入所需依赖
2
1
  const fs = require("fs")
3
2
  const path = require("path")
4
- // 指向宿主项目路径 ../../为node_modules路径
5
- const hostPath = path.join(__dirname, '../../')
6
- const { cssFileName, parseCSSVariables, parseLessVariables, parseExtendVariables, fetchAndParseLessFile } = require('./UpdateTheme')
7
3
 
8
- // 提取颜色变量
4
+ // 导入UpdateTheme中的共享函数
5
+ const {
6
+ CONFIG,
7
+ fetchRemoteFiles,
8
+ fetchAndParseLessFile,
9
+ parseLessVariables,
10
+ parseCSSVariables,
11
+ parseExtendVariables
12
+ } = require('./UpdateTheme')
13
+
14
+ // 构建配置
15
+ const BUILD_CONFIG = {
16
+ // 宿主路径
17
+ DEPD_PATH: path.join(__dirname, '../../'),
18
+ // 入口路径
19
+ ENTRY_PATH: path.join(__dirname, '../../../src/')
20
+ }
21
+
22
+ /**
23
+ * 提取颜色变量
24
+ * @param {string} content - 文件内容
25
+ * @param {string} varName - 变量名
26
+ */
9
27
  function extractColor(content, varName) {
10
28
  const regex = new RegExp(`${varName}:\\s*(.+?);`)
11
29
  const match = content.match(regex)
12
- return match ? match[1] : null
30
+ return match ? match[1].trim() : null
13
31
  }
14
32
 
15
33
  /**
@@ -49,17 +67,18 @@ function addLessVariables(newVars, lessContent) {
49
67
  return lines.join('\n')
50
68
  }
51
69
 
52
- // 初始化处理并输出主题文件
70
+ /**
71
+ * 初始化处理并输出主题文件
72
+ * @param {string} resetTheme - 重置主题
73
+ */
53
74
  async function createStyleFiles(resetTheme) {
54
- // 初始化主题
55
75
  const theme = resetTheme || 'dark'
56
76
 
57
77
  try {
58
-
59
78
  // 并行获取文件内容
60
79
  const [fileAVariables, fileBContent] = await Promise.all([
61
80
  fetchAndParseLessFile(theme, true),
62
- fetchAndParseLessFile(cssFileName, false)
81
+ fetchAndParseLessFile(CONFIG.FILE.VAR, false)
63
82
  ])
64
83
 
65
84
  // 处理颜色变量
@@ -75,6 +94,7 @@ async function createStyleFiles(resetTheme) {
75
94
  )
76
95
  }
77
96
  }
97
+
78
98
  // 解析扩展变量
79
99
  const cssVariables = await parseLessVariables(processedContent)
80
100
  const result = parseExtendVariables(cssVariables, fileAVariables)
@@ -86,17 +106,17 @@ async function createStyleFiles(resetTheme) {
86
106
  processedContent
87
107
  )
88
108
 
89
- const basePath = path.resolve(hostPath, '../src/styles')
109
+ const basePath = path.resolve(BUILD_CONFIG.ENTRY_PATH, 'styles')
90
110
 
91
111
  // 确保目录存在
92
112
  fs.mkdirSync(basePath, { recursive: true })
93
113
 
94
114
  // 写入LESS文件
95
- const lessOutPut = path.join(basePath, `${cssFileName}.less`)
115
+ const lessOutPut = path.join(basePath, CONFIG.FILE.VAR)
96
116
  fs.writeFileSync(lessOutPut, processedContent)
97
117
 
98
118
  // 生成并写入CSS变量文件
99
- const cssOutPut = path.join(basePath, 'root.css')
119
+ const cssOutPut = path.join(basePath, CONFIG.FILE.CSS)
100
120
  fs.writeFileSync(cssOutPut, addLessVariables(
101
121
  {
102
122
  export: {
@@ -113,11 +133,14 @@ async function createStyleFiles(resetTheme) {
113
133
  }
114
134
  }
115
135
 
116
- // 自定义less内置函数处理
136
+
137
+ /**
138
+ * 自定义LESS函数
139
+ */
117
140
  const customFunctions = {
118
141
  install: function(less, pluginManager, functions) {
119
142
 
120
- // 辅助函数:检查是否为 CSS 变量(Call 类型)
143
+ // 检查是否为CSS变量
121
144
  function isCSSVariable(color) {
122
145
  return color.type === 'Call' &&
123
146
  color.name === 'var' &&
@@ -125,24 +148,24 @@ const customFunctions = {
125
148
  color.args[0].value.indexOf('--') === 0
126
149
  }
127
150
 
128
- // 辅助函数:提取 CSS 变量信息
151
+ // 提取CSS变量信息
129
152
  function extractCSSVariable(callNode) {
130
153
  if (callNode.name === 'var') {
131
154
  return {
132
- varName: callNode.args[0].value,
133
- defaultValue: callNode.args[1] ? callNode.args[1] : null
155
+ varName: callNode.args[0].value,
156
+ defaultValue: callNode.args[1] ? callNode.args[1] : null
134
157
  }
135
158
  }
136
159
  return null
137
160
  }
138
161
 
139
- // tint 函数实现(支持 Call 类型和静态颜色)
162
+ // tint函数实现
140
163
  functions.add('tint', function(color, amount) {
141
164
  if (isCSSVariable(color)) {
142
165
  const {varName, defaultValue} = extractCSSVariable(color)
143
166
  return new less.tree.Quoted('"', `tint(${defaultValue}, ${amount.value}%)`)
144
167
  }
145
- // 处理静态颜色值
168
+
146
169
  const ratio = Math.max(0, Math.min(1, parseFloat(amount.value) / 100))
147
170
  return new less.tree.Color(
148
171
  [
@@ -154,13 +177,13 @@ const customFunctions = {
154
177
  )
155
178
  })
156
179
 
157
- // lighten 函数实现
180
+ // lighten函数实现
158
181
  functions.add('lighten', function(color, amount) {
159
182
  if (isCSSVariable(color)) {
160
183
  const {varName, defaultValue} = extractCSSVariable(color)
161
184
  return new less.tree.Quoted('"', `lighten(${defaultValue}, ${amount.value}%)`)
162
185
  }
163
- // 处理静态颜色值
186
+
164
187
  const hsl = color.toHSL()
165
188
  const newLightness = Math.min(100, hsl.l + parseFloat(amount.value))
166
189
  return new less.tree.Color(
@@ -173,63 +196,32 @@ const customFunctions = {
173
196
  )
174
197
  })
175
198
 
176
- // fade 函数实现
199
+ // fade函数实现
177
200
  functions.add('fade', function(color, amount) {
178
201
  if (isCSSVariable(color)) {
179
202
  const {varName, defaultValue} = extractCSSVariable(color)
180
203
  return new less.tree.Quoted('"', `fade(${defaultValue}, ${amount.value}%)`)
181
204
  }
182
- // 处理静态颜色值
205
+
183
206
  const alpha = Math.max(0, Math.min(1, color.alpha * (amount.value / 100)))
184
207
  return new less.tree.Color(color.rgb, alpha)
185
208
  })
186
209
  }
187
210
  }
188
211
 
189
- // 生成AntdVue主题文件及自定义主题文件
190
- function createGeneratorTheme(theme) {
191
- // 初始化主题
192
- const resetTheme = theme || 'dark'
193
- // 抛出基础色
194
- const notIncludes = ['@white', '@black']
195
-
196
- // 输出自定义样式文件
197
- createStyleFiles(resetTheme).then(themeVariables => {
198
- // 输出AntdVue样式打包放置public引入
199
- const options = {
200
- antDir: path.join(hostPath, 'ant-design-vue'),
201
- // 指定项目自定义样式文件目录
202
- stylesDir: path.join(hostPath, 'ant-design-vue/lib/style/themes'),
203
- // 指定项目自定义样式文件目录
204
- // stylesDir: path.join(hostPath, '../src/styles'),
205
- // 指定自定义主题变量文件路径
206
- // varFile: path.join(hostPath, `../src/styles/${resetTheme}.less`),
207
- // 列出需要动态替换的主题变量
208
- themeVariables: Object.keys(themeVariables).filter(key => !notIncludes.includes(key)),
209
- outputFilePath: path.join(hostPath, '../public/static/style/antdVue.less')
210
- }
211
- generateTheme(options)
212
- })
213
- }
214
-
215
- // 生成传输信息文件
212
+ /**
213
+ * 生成传输信息文件
214
+ * @param {string} theme - 主题名称
215
+ */
216
216
  async function createTransferFile(theme) {
217
217
  // 输出自定义样式文件
218
- createStyleFiles(theme)
219
-
220
- // 默认请求源地址
221
- const origin = process.env.VUE_APP_STATIC_URL || 'http://qxfnkj.com'
218
+ await createStyleFiles(theme)
222
219
 
223
- const fileName = 'transferData.js'
224
-
225
- const response = await fetch(`${origin}/base-subject/iframe/${fileName}`)
226
- if (!response.ok) throw new Error(`${fileName}文件请求失败!`)
227
-
228
- const responseText = await response.text()
220
+ const jsContent = await fetchRemoteFiles('IFRAME', CONFIG.FILE.MESSAGE)
229
221
 
230
222
  // 写入传输文件
231
- const outPut = path.join(hostPath, `../src/utils/${fileName}`)
232
- fs.writeFileSync(outPut, responseText)
223
+ const outPut = path.join(BUILD_CONFIG.ENTRY_PATH, `utils/${CONFIG.FILE.MESSAGE}`)
224
+ fs.writeFileSync(outPut, jsContent)
233
225
  }
234
226
 
235
227
  module.exports = {
@@ -2,18 +2,39 @@
2
2
  const less = require('less')
3
3
 
4
4
  // CSS变量搭桥文件名
5
- const cssFileName = 'vars.module'
6
5
  const colorPalette = require('../utils/ColorPalette')
7
6
 
8
- // 获取并解析LESS文件
9
- async function fetchAndParseLessFile(fileName, isParseVariables) {
10
- // 确定请求源地址
11
- let origin = 'http://qxfnkj.com'
7
+ // 配置常量
8
+ const CONFIG = {
9
+ FILE: {
10
+ CSS: 'root.css',
11
+ VAR: 'vars.module.less',
12
+ MESSAGE: 'transferData.js'
13
+ },
14
+ REQUEST: {
15
+ IP: process.env.VUE_APP_STATIC_URL || 'http://qxfnkj.com',
16
+ PATHS: {
17
+ THEMES: '/base-subject/themes/',
18
+ IFRAME: '/base-subject/iframe/'
19
+ }
20
+ }
21
+ }
22
+
23
+ /**
24
+ * 获取服务器文件
25
+ * @param {string} dirPath - 文件夹名称
26
+ * @param {string} fileName - 文件名称
27
+ */
28
+ async function fetchRemoteFiles(dirPath, fileName) {
29
+ // 远程请求IP
30
+ let requestIP = CONFIG.REQUEST.IP
12
31
 
13
32
  // 浏览器环境:使用当前页面的origin
14
- if (typeof window !== 'undefined' && window.location && window.location.origin && process.env.NODE_ENV !== 'development') origin = window.location.origin
33
+ if (typeof window !== 'undefined' && window.location && window.location.origin && process.env.NODE_ENV !== 'development') {
34
+ requestIP = window.location.origin
35
+ }
15
36
 
16
- const response = await fetch(`${origin}/base-subject/themes/${fileName}.less`, {
37
+ const response = await fetch(`${requestIP}${CONFIG.REQUEST.PATHS[dirPath]}${fileName}`, {
17
38
  method: 'GET',
18
39
  mode: 'cors'
19
40
  })
@@ -22,28 +43,47 @@ async function fetchAndParseLessFile(fileName, isParseVariables) {
22
43
 
23
44
  const responseText = await response.text()
24
45
 
46
+ return responseText
47
+ }
48
+
49
+ /**
50
+ * 获取并解析LESS文件
51
+ * @param {string} fileName - 文件名
52
+ * @param {boolean} isParseVariables - 是否解析变量
53
+ */
54
+ async function fetchAndParseLessFile(fileName, isParseVariables) {
55
+ // 检测并补全文件后缀
56
+ let processedFileName = fileName
57
+ if (!fileName.endsWith('.less') && !fileName.endsWith('.css')) {
58
+ processedFileName = fileName + '.less'
59
+ }
60
+
61
+ const lessContent = await fetchRemoteFiles('THEMES', processedFileName)
62
+
25
63
  return isParseVariables
26
- ? await parseLessVariables(responseText)
27
- : responseText
64
+ ? await parseLessVariables(lessContent)
65
+ : lessContent
28
66
  }
29
67
 
30
- // 解析LESS变量
68
+ /**
69
+ * 解析LESS变量
70
+ * @param {string} content - LESS文件内容
71
+ */
31
72
  async function parseLessVariables(content) {
32
73
  try {
33
- const lessRoot = await less.parse(
34
- content,
35
- {
36
- javascriptEnabled: true,
37
- math: 'always'
38
- }
39
- )
74
+ const lessRoot = await less.parse(content, {
75
+ javascriptEnabled: true,
76
+ math: 'always'
77
+ })
78
+
40
79
  const env = new less.contexts.Eval()
41
80
  const evaluatedRoot = lessRoot.eval(env)
42
81
  const variables = {}
43
82
 
44
83
  evaluatedRoot.rules.forEach(rule => {
45
- if (rule.variable && rule.name)
84
+ if (rule.variable && rule.name) {
46
85
  variables[rule.name] = rule.value.toCSS()
86
+ }
47
87
  })
48
88
 
49
89
  return variables
@@ -53,23 +93,35 @@ async function parseLessVariables(content) {
53
93
  }
54
94
  }
55
95
 
56
- // 解析ROOT变量
96
+
97
+ /**
98
+ * 解析CSS变量
99
+ * @param {Object} cssVariables - CSS变量对象
100
+ * @param {Object} resetVar - 重置变量对象
101
+ */
57
102
  function parseCSSVariables(cssVariables, resetVar) {
58
103
  const result = {}
59
104
  for (const [key, value] of Object.entries(cssVariables)) {
60
- const match = value.match(/var\(\s*([^,)]+)\s*(?:,\s*((?:[^()]|\([^)]*\))+))?\s*\)/)
105
+ const match = value.match(/var$\s*([^,)]+)\s*(?:,\s*((?:[^()]|\([^)]*$)+))?\s*\)/)
61
106
  if (match) result[match[1]] = (match[2] || resetVar[key])
62
107
  }
63
108
  return result
64
109
  }
65
110
 
66
- // 解析扩展变量
111
+ /**
112
+ * 解析扩展变量
113
+ * @param {Object} extendVar - 扩展变量对象
114
+ * @param {Object} lessVariables - LESS变量对象
115
+ */
67
116
  function parseExtendVariables(extendVar, lessVariables) {
68
117
  const { '@extend-colors': extendColors, '@extend-light': extendLight } = extendVar
69
118
 
70
- // 初始化扩展、导出组
119
+ if (!extendColors || !extendLight) {
120
+ return { nonExport: {}, export: {} }
121
+ }
122
+
71
123
  return extendColors.split(',').reduce((acc, key) => {
72
- const varName = key.trim().replace(/"/g, '')
124
+ const varName = key.trim().replace(/\"/g, '')
73
125
  const [lessVar] = varName.split('-')
74
126
  const cssVar = `--${varName.slice(1)}`
75
127
  const hex = lessVariables[varName]
@@ -79,7 +131,7 @@ function parseExtendVariables(extendVar, lessVariables) {
79
131
  // 转换RGB值
80
132
  const [r, g, b] = [1, 3, 5].map(offset =>
81
133
  parseInt(hex.slice(offset, offset + 2), 16)
82
- )
134
+ )
83
135
 
84
136
  // 添加基础变量
85
137
  acc.nonExport[`${lessVar}-rgb`] = `var(${cssVar}-rgb)`
@@ -87,7 +139,7 @@ function parseExtendVariables(extendVar, lessVariables) {
87
139
 
88
140
  // 处理亮度变量
89
141
  extendLight.split(',').forEach(light => {
90
- const lightName = light.trim().replace(/"/g, '')
142
+ const lightName = light.trim().replace(/\"/g, '')
91
143
  acc.nonExport[`${lessVar}-${lightName}`] = `var(${cssVar}-${lightName})`
92
144
  acc.export[`${cssVar}-${lightName}`] = colorPalette(hex, lightName)
93
145
  })
@@ -96,61 +148,75 @@ function parseExtendVariables(extendVar, lessVariables) {
96
148
  }, { nonExport: {}, export: {} })
97
149
  }
98
150
 
99
- // 更新主题
151
+
152
+
153
+ /**
154
+ * 更新主题
155
+ * @param {string} theme - 主题名称
156
+ */
100
157
  async function updateTheme(theme) {
101
158
  if (!less || !less.modifyVars) return
102
159
 
103
160
  const root = document.documentElement
104
- // 并行获取主题变量和CSS变量
105
- const [themeVariables, cssVariables] = await Promise.all([
106
- fetchAndParseLessFile(theme, true),
107
- fetchAndParseLessFile(cssFileName, true)
108
- ])
109
- // 解析CSS变量
110
- const resetValue = parseCSSVariables(cssVariables, themeVariables)
111
-
112
- const updateVariables = {
113
- css: {},
114
- less: {}
115
- }
116
161
 
117
- // 对比新旧变量值,收集需要更新的变量
118
- for (const [key, colorA] of Object.entries(resetValue)) {
119
- const colorB = getComputedStyle(root).getPropertyValue(key).trim()
120
- // 只有当颜色值确实发生变化时才更新
121
- if (colorA !== colorB) {
122
- updateVariables.css[key] = colorA
123
- // 将CSS变量名转换为LESS变量名
124
- updateVariables.less[`@${key.slice(2)}`] = colorA
162
+ try {
163
+ // 并行获取主题变量和CSS变量
164
+ const [themeVariables, cssVariables] = await Promise.all([
165
+ fetchAndParseLessFile(theme, true),
166
+ fetchAndParseLessFile(CONFIG.FILE.VAR, true)
167
+ ])
168
+
169
+ // 解析CSS变量
170
+ const resetValue = parseCSSVariables(cssVariables, themeVariables)
171
+
172
+ const updateVariables = {
173
+ css: {},
174
+ less: {}
175
+ }
176
+
177
+ // 对比新旧变量值,收集需要更新的变量
178
+ for (const [key, colorA] of Object.entries(resetValue)) {
179
+ const colorB = getComputedStyle(root).getPropertyValue(key).trim()
180
+
181
+ // 只有当颜色值确实发生变化时才更新
182
+ if (colorA !== colorB) {
183
+ updateVariables.css[key] = colorA
184
+ // 将CSS变量名转换为LESS变量名
185
+ updateVariables.less[`@${key.slice(2)}`] = colorA
186
+ }
125
187
  }
126
- }
127
188
 
128
- await less.modifyVars({
129
- ...themeVariables,
130
- ...updateVariables.less
131
- }).then(console.log("换肤成功"))
189
+ // 应用LESS变量更新
190
+ await less.modifyVars({
191
+ ...themeVariables,
192
+ ...updateVariables.less
193
+ })
194
+
195
+ console.log("换肤成功")
132
196
 
133
- if (!Object.keys(updateVariables.css).length) return
197
+ if (!Object.keys(updateVariables.css).length) return
134
198
 
135
- // 解析并更新CSS变量
136
- const updateCSSViables = {
137
- ...updateVariables.css,
138
- ...parseExtendVariables(
139
- cssVariables,
140
- updateVariables.less
141
- ).export
142
- }
143
-
144
- for (const [key, color] of Object.entries(updateCSSViables)) {
145
- root.style.setProperty(key, color)
199
+ // 解析并更新CSS变量
200
+ const updateCSSVariables = {
201
+ ...updateVariables.css,
202
+ ...parseExtendVariables(cssVariables, updateVariables.less).export
203
+ }
204
+
205
+ for (const [key, color] of Object.entries(updateCSSVariables)) {
206
+ root.style.setProperty(key, color)
207
+ }
208
+ } catch (error) {
209
+ console.error('主题更新失败:', error)
210
+ throw error
146
211
  }
147
212
  }
148
213
 
149
- module.exports = {
150
- cssFileName,
214
+ module.exports = {
215
+ CONFIG,
151
216
  updateTheme,
152
217
  parseCSSVariables,
153
218
  parseLessVariables,
154
219
  parseExtendVariables,
155
- fetchAndParseLessFile
220
+ fetchAndParseLessFile,
221
+ fetchRemoteFiles
156
222
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "web-component-gallery",
3
- "version": "2.2.7",
3
+ "version": "2.2.8",
4
4
  "description": "基础vue、antdvue、less实现的私有组件库",
5
5
  "main": "dist/index.umd.js",
6
6
  "files": [