-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathcore.js
More file actions
363 lines (311 loc) · 10.8 KB
/
core.js
File metadata and controls
363 lines (311 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import cssbeautify from 'cssbeautify';
import { Color } from 'tvision-color';
import GENERATOR_VARIABLES from '!raw-loader!./built-in/css/vars.css';
import { appendStyleSheet, clearLocalItem, downloadFile, parseRootCss, setUpModeObserver } from '../utils';
import {
MOBILE_RECOMMEND_THEMES,
TDESIGN_MOBILE_THEME,
TDESIGN_WEB_THEME,
TENCENT_BLUE,
TENCENT_BLUE_DARK_PALETTE,
WEB_RECOMMEND_THEMES,
} from './built-in';
const GENERATOR_ID = 'TDESIGN_GENERATOR_SYMBOL';
/* stylesheet 的 ID */
export const CUSTOM_THEME_ID = 'custom-theme';
export const CUSTOM_DARK_ID = `${CUSTOM_THEME_ID}-dark`;
export const CUSTOM_EXTRA_ID = `${CUSTOM_THEME_ID}-extra`;
/* localStorage 的 key */
export const CUSTOM_OPTIONS_ID = `${CUSTOM_THEME_ID}-options`;
export const CUSTOM_TOKEN_ID = `${CUSTOM_THEME_ID}-tokens`;
export const isMiniProgram = (device) => device === 'mini-program';
export const isUniApp = (device) => device === 'uni-app';
export const isMobile = (device) => device === 'mobile' || isMiniProgram(device) || isUniApp(device);
export function normalizeDevice(device) {
return isMobile(device) ? 'mobile' : 'web';
}
/**
* 初始化给生成器本身使用的变量,避免部分样式在用户调整主题时产生冲突
*/
export function initGeneratorVars() {
const siteStylesheet = appendStyleSheet(GENERATOR_ID);
siteStylesheet.textContent = GENERATOR_VARIABLES;
}
export function getDefaultTheme(device) {
return isMobile(device) ? TDESIGN_MOBILE_THEME : TDESIGN_WEB_THEME;
}
export function getRecommendThemes(device) {
return isMobile(device) ? MOBILE_RECOMMEND_THEMES : WEB_RECOMMEND_THEMES;
}
/**
* 同步 site 的 亮暗模式给主题生成器 Web Component
*/
export function syncModeToGenerator() {
setUpModeObserver((theme) => {
const generator = document.querySelector('td-theme-generator');
if (!generator) return;
generator.setAttribute('theme-mode', theme);
});
}
export function findThemeByEnName(device, enName) {
const themes = getRecommendThemes(device);
for (const category of themes) {
const theme = category.options.find((t) => t.enName === enName);
if (theme) return theme;
}
return getDefaultTheme(device);
}
/**
* 初始化当前主题对应的样式表
*/
export function initThemeStyleSheet(themeName, device) {
const deviceType = normalizeDevice(device);
const theme = findThemeByEnName(deviceType, themeName);
const styleSheet = appendStyleSheet(CUSTOM_THEME_ID);
const darkStyleSheet = appendStyleSheet(CUSTOM_DARK_ID);
const extraStyleSheet = appendStyleSheet(CUSTOM_EXTRA_ID);
const { light, dark, extra } = theme.css;
styleSheet.textContent = light;
darkStyleSheet.textContent = dark;
extraStyleSheet.textContent = extra;
return theme;
}
export function exportCustomStyleSheet(device) {
const styleSheet = document.getElementById(CUSTOM_THEME_ID);
const darkStyleSheet = document.getElementById(CUSTOM_DARK_ID);
const extraStyleSheet = document.getElementById(CUSTOM_EXTRA_ID);
const { rootContent: cssString } = parseRootCss(styleSheet?.textContent);
const { rootContent: darkCssString } = parseRootCss(darkStyleSheet?.textContent);
const { rootContent: extraCssString, restContent: extraRestCssString } = parseRootCss(extraStyleSheet?.textContent);
let finalCssString;
if (isUniApp(device)) {
finalCssString = `
@media (prefers-color-scheme: light) {
/* #ifdef H5 */
:root,
/* #endif */
page, .page {
${cssString}
}
}
@media (prefers-color-scheme: dark) {
/* #ifdef H5 */
:root,
/* #endif */
page, .page {
${darkCssString}
}
}
/* #ifdef H5 */
:root,
/* #endif */
page, .page {
${extraCssString}
}
${extraRestCssString}
`;
} else if (isMiniProgram(device)) {
finalCssString = `
@media (prefers-color-scheme: light) {
page, .page {
${cssString}
}
}
@media (prefers-color-scheme: dark) {
page, .page {
${darkCssString}
}
}
page, .page {
${extraCssString}
}
${extraRestCssString}
`;
} else {
finalCssString = `
:root, :root[theme-mode="light"] {
${cssString}
}
:root.dark, :root[theme-mode="dark"] {
${darkCssString}
}
:root {
${extraCssString}
}
${extraRestCssString}
`;
}
const beautifyCssString = cssbeautify(finalCssString.trim());
const blob = new Blob([beautifyCssString], { type: 'text' });
const fileSuffix = isMiniProgram(device) ? 'wxss' : 'css';
downloadFile(blob, `theme.${fileSuffix}`);
}
export function modifyToken(tokenName, newVal, saveToLocal = true) {
// 获取所有可能包含 token 的样式表
const styleSheets = document.querySelectorAll(`#${CUSTOM_THEME_ID}, #${CUSTOM_DARK_ID}, #${CUSTOM_EXTRA_ID}`);
let tokenFound = false;
styleSheets.forEach((styleSheet) => {
const reg = new RegExp(`${tokenName}:\\s*(.*?);`);
const match = styleSheet.textContent.match(reg);
if (!match) return;
if (match[1] === newVal) {
tokenFound = true;
return;
}
const currentVal = match[1];
styleSheet.textContent = styleSheet.textContent.replace(`${tokenName}: ${currentVal}`, `${tokenName}: ${newVal}`);
tokenFound = true;
updateLocalToken(tokenName, saveToLocal ? newVal : null);
});
if (!tokenFound) {
console.warn(`CSS variable: ${tokenName} is not exist`);
}
}
export function getOptionFromLocal(optionName) {
const options = localStorage.getItem(CUSTOM_OPTIONS_ID);
if (!options) return;
const optionObj = JSON.parse(options);
return optionObj[optionName];
}
/**
* 如果不传入 `tokenName`,则返回所有的 `token` 对象
*/
export function getTokenFromLocal(tokenName) {
const tokens = localStorage.getItem(CUSTOM_TOKEN_ID);
if (!tokens) return;
const tokenObj = JSON.parse(tokens);
if (!tokenName) return tokenObj;
return tokenObj[tokenName];
}
/**
* @param {*} value 传入 `null` 或 `undefined`,则表示清除掉之前的存储
*/
export function updateLocalOption(optionName, value) {
if (value) {
const options = localStorage.getItem(CUSTOM_OPTIONS_ID) || '{}';
const optionObj = JSON.parse(options);
optionObj[optionName] = value;
localStorage.setItem(CUSTOM_OPTIONS_ID, JSON.stringify(optionObj));
} else {
clearLocalItem(CUSTOM_OPTIONS_ID, optionName);
}
}
/**
* @param {*} value 传入 `null` 或 `undefined`,则表示清除掉之前的存储
*/
export function updateLocalToken(tokenName, value) {
if (value) {
const tokens = localStorage.getItem(CUSTOM_TOKEN_ID) || '{}';
const tokenObj = JSON.parse(tokens);
tokenObj[tokenName] = value;
localStorage.setItem(CUSTOM_TOKEN_ID, JSON.stringify(tokenObj));
} else {
clearLocalItem(CUSTOM_TOKEN_ID, tokenName);
}
}
export function applyTokenFromLocal() {
const token = localStorage.getItem(CUSTOM_TOKEN_ID);
if (!token) return;
const tokenObj = JSON.parse(token);
Object.entries(tokenObj).forEach(([key, value]) => {
modifyToken(key, value);
});
}
export function clearLocalTheme() {
localStorage.removeItem(CUSTOM_OPTIONS_ID);
localStorage.removeItem(CUSTOM_TOKEN_ID);
}
export function convertFromHex(color, format) {
return `(${Color.colorTransform(color, 'hex', format).join(',')})`;
}
export function generateBrandPalette(hex, remainInput = false) {
const lowCaseHex = hex.toLowerCase();
const [{ colors, primary }] = Color.getColorGradations({
colors: [lowCaseHex],
step: 10,
remainInput,
});
const isTencentBlue = lowCaseHex === TENCENT_BLUE.toLowerCase();
const validPrimary = typeof primary === 'number' && !isNaN(primary) ? primary : 6;
const lightBrandIdx = isTencentBlue ? 7 : validPrimary + 1;
const lightPalette = [...colors];
const darkPalette = isTencentBlue ? TENCENT_BLUE_DARK_PALETTE : [...colors].reverse();
const darkBrandIdx = isTencentBlue ? 8 : 6;
return { lightPalette, lightBrandIdx, darkPalette, darkBrandIdx };
}
export function generateFunctionalPalette(hex, step = 10) {
const lowCaseHex = hex.toLowerCase();
const [{ colors }] = Color.getColorGradations({
colors: [lowCaseHex],
step,
});
const lightPalette = [...colors];
const darkPalette = [...colors].reverse();
return { lightPalette, darkPalette };
}
export function generateNeutralPalette(hex, isRelatedTheme) {
if (isRelatedTheme) {
return Color.getNeutralColor(hex);
} else {
return generateFunctionalPalette(hex, 14).lightPalette;
}
}
/**
* @param {'init' | 'update'} trigger - 触发类型
*/
export function updateStyleSheetColor(type, lightPalette, darkPalette, trigger) {
const styleSheet = appendStyleSheet(CUSTOM_THEME_ID);
const darkStyleSheet = appendStyleSheet(CUSTOM_DARK_ID);
const updateColorTokens = (styleSheet, palette) => {
palette.forEach((color, index) => {
const tokenName = `--td-${type}-color-${index + 1}`;
const regExp = new RegExp(`${tokenName}:.*?;`, 'g');
let replacement = `${tokenName}: ${color};`;
if (trigger === 'init') {
// 确保不覆盖用户本地自定义的值
replacement = `${tokenName}: ${getTokenFromLocal(tokenName) || color};`;
}
if (trigger === 'update') {
updateLocalToken(tokenName, null); // 清除本地存储的颜色 Token
}
styleSheet.textContent = styleSheet.textContent.replace(regExp, replacement);
});
};
updateColorTokens(styleSheet, lightPalette);
updateColorTokens(darkStyleSheet, darkPalette);
}
export function syncColorTokensToStyle(lightTokenMap, darkTokenMap) {
const styleSheet = appendStyleSheet(CUSTOM_THEME_ID);
const darkStyleSheet = appendStyleSheet(CUSTOM_DARK_ID);
const updateColorTokens = (styleSheet, tokenMap) => {
tokenMap.forEach(({ name, idx }) => {
const regExp = new RegExp(`${name}:.*?;`, 'g');
const replacement = `${name}: var(--td-brand-color-${idx});`;
styleSheet.textContent = styleSheet.textContent.replace(regExp, replacement);
});
};
updateColorTokens(styleSheet, lightTokenMap);
updateColorTokens(darkStyleSheet, darkTokenMap);
}
/**
* 根据 token 名称获取对应的索引
* 例如 `--td-brand-focus` -> 2
*/
export function collectTokenIndexes(tokenArr) {
const isDarkMode = document.documentElement.getAttribute('theme-mode') === 'dark';
const targetCss = document.querySelector(isDarkMode ? `#${CUSTOM_DARK_ID}` : `#${CUSTOM_THEME_ID}`);
return tokenArr
.map((token) => {
const reg = new RegExp(`${token}:\\s*var\\((--td-[\\w-]+)\\)`, 'i');
const match = targetCss?.textContent.match(reg);
if (match) {
return {
name: token,
idx: parseInt(match[1].match(/(\d+)$/)?.[1], 10),
};
}
return null;
})
.filter(Boolean)
.sort((a, b) => a.idx - b.idx);
}