feat(projects): 1.0 beta

This commit is contained in:
Soybean
2023-11-17 08:45:00 +08:00
parent 1ea4817f6a
commit e918a2c0f5
499 changed files with 15918 additions and 24708 deletions

View File

@ -1,80 +0,0 @@
import type { GlobalThemeOverrides } from 'naive-ui';
import { cloneDeep } from 'lodash-es';
import { themeSetting } from '@/settings';
import { sessionStg, addColorAlpha, getColorPalette } from '@/utils';
/** 初始化主题配置 */
export function initThemeSettings() {
const isProd = import.meta.env.PROD;
// 生产环境才缓存主题配置本地开发实时调整配置更改配置的json
const storageSettings = sessionStg.get('themeSettings');
if (isProd && storageSettings) {
return storageSettings;
}
const themeColor = sessionStg.get('themeColor') || themeSetting.themeColor;
const info = themeSetting.isCustomizeInfoColor ? themeSetting.otherColor.info : getColorPalette(themeColor, 7);
const otherColor = { ...themeSetting.otherColor, info };
const setting = cloneDeep({ ...themeSetting, themeColor, otherColor });
return setting;
}
type ColorType = 'primary' | 'info' | 'success' | 'warning' | 'error';
type ColorScene = '' | 'Suppl' | 'Hover' | 'Pressed' | 'Active';
type ColorKey = `${ColorType}Color${ColorScene}`;
type ThemeColor = Partial<Record<ColorKey, string>>;
interface ColorAction {
scene: ColorScene;
handler: (color: string) => string;
}
/** 获取主题颜色的各种场景对应的颜色 */
function getThemeColors(colors: [ColorType, string][]) {
const colorActions: ColorAction[] = [
{ scene: '', handler: color => color },
{ scene: 'Suppl', handler: color => color },
{ scene: 'Hover', handler: color => getColorPalette(color, 5) },
{ scene: 'Pressed', handler: color => getColorPalette(color, 7) },
{ scene: 'Active', handler: color => addColorAlpha(color, 0.1) }
];
const themeColor: ThemeColor = {};
colors.forEach(color => {
colorActions.forEach(action => {
const [colorType, colorValue] = color;
const colorKey: ColorKey = `${colorType}Color${action.scene}`;
themeColor[colorKey] = action.handler(colorValue);
});
});
return themeColor;
}
/** 获取naive的主题颜色 */
export function getNaiveThemeOverrides(colors: Record<ColorType, string>): GlobalThemeOverrides {
const { primary, success, warning, error } = colors;
const info = themeSetting.isCustomizeInfoColor ? colors.info : getColorPalette(primary, 7);
const themeColors = getThemeColors([
['primary', primary],
['info', info],
['success', success],
['warning', warning],
['error', error]
]);
const colorLoading = primary;
return {
common: {
...themeColors
},
LoadingBar: {
colorLoading
}
};
}

View File

@ -1,181 +1,173 @@
import { ref, computed, effectScope, onScopeDispose, watch, toRefs } from 'vue';
import type { Ref } from 'vue';
import { defineStore } from 'pinia';
import { darkTheme } from 'naive-ui';
import { sessionStg } from '@/utils';
import { getNaiveThemeOverrides, initThemeSettings } from './helpers';
import { usePreferredColorScheme, useEventListener } from '@vueuse/core';
import { SetupStoreId } from '@/enum';
import { localStg } from '@/utils/storage';
import { createThemeToken, initThemeSettings, addThemeVarsToHtml, toggleCssDarkMode, getNaiveTheme } from './shared';
type ThemeState = Theme.Setting;
/**
* theme store
*/
export const useThemeStore = defineStore(SetupStoreId.Theme, () => {
const scope = effectScope();
const osTheme = usePreferredColorScheme();
export const useThemeStore = defineStore('theme-store', {
state: (): ThemeState => initThemeSettings(),
getters: {
/** naiveUI的主题配置 */
naiveThemeOverrides(state) {
const overrides = getNaiveThemeOverrides({ primary: state.themeColor, ...state.otherColor });
return overrides;
},
/** naive-ui暗黑主题 */
naiveTheme(state) {
return state.darkMode ? darkTheme : undefined;
},
/** 页面动画模式 */
pageAnimateMode(state) {
return state.page.animate ? state.page.animateMode : undefined;
/**
* theme settings
*/
const settings: Ref<App.Theme.ThemeSetting> = ref(initThemeSettings());
/**
* dark mode
*/
const darkMode = computed(() => {
if (settings.value.themeScheme === 'auto') {
return osTheme.value === 'dark';
}
},
actions: {
/** 重置theme状态 */
resetThemeStore() {
sessionStg.remove('themeSettings');
this.$reset();
},
/** 缓存主题配置 */
cacheThemeSettings() {
const isProd = import.meta.env.PROD;
if (isProd) {
sessionStg.set('themeSettings', this.$state);
}
},
/** 设置暗黑模式 */
setDarkMode(darkMode: boolean) {
this.darkMode = darkMode;
},
/** 设置自动跟随系统主题 */
setFollowSystemTheme(visible: boolean) {
this.followSystemTheme = visible;
},
/** 设置自动跟随系统主题 */
setIsCustomizeDarkModeTransition(isCustomize: boolean) {
this.isCustomizeDarkModeTransition = isCustomize;
},
/** 自动跟随系统主题 */
setAutoFollowSystemMode(darkMode: boolean) {
if (this.followSystemTheme) {
this.darkMode = darkMode;
}
},
/** 切换/关闭 暗黑模式 */
toggleDarkMode() {
this.darkMode = !this.darkMode;
},
/** 设置布局最小宽度 */
setLayoutMinWidth(minWidth: number) {
this.layout.minWidth = minWidth;
},
/** 设置布局模式 */
setLayoutMode(mode: UnionKey.ThemeLayoutMode) {
this.layout.mode = mode;
},
/** 设置滚动模式 */
setScrollMode(mode: UnionKey.ThemeScrollMode) {
this.scrollMode = mode;
},
/** 设置侧边栏反转色 */
setSiderInverted(isInverted: boolean) {
this.sider.inverted = isInverted;
},
/** 设置头部反转色 */
setHeaderInverted(isInverted: boolean) {
this.header.inverted = isInverted;
},
/** 设置系统主题颜色 */
setThemeColor(themeColor: string) {
this.themeColor = themeColor;
},
/** 设置固定头部和多页签 */
setIsFixedHeaderAndTab(isFixed: boolean) {
this.fixedHeaderAndTab = isFixed;
},
/** 设置重载按钮可见状态 */
setReloadVisible(visible: boolean) {
this.showReload = visible;
},
/** 设置头部高度 */
setHeaderHeight(height: number | null) {
if (height) {
this.header.height = height;
}
},
/** 设置头部面包屑可见 */
setHeaderCrumbVisible(visible: boolean) {
this.header.crumb.visible = visible;
},
/** 设置头部面包屑图标可见 */
setHeaderCrumbIconVisible(visible: boolean) {
this.header.crumb.showIcon = visible;
},
/** 设置多页签可见 */
setTabVisible(visible: boolean) {
this.tab.visible = visible;
},
/** 设置多页签高度 */
setTabHeight(height: number | null) {
if (height) {
this.tab.height = height;
}
},
/** 设置多页签风格 */
setTabMode(mode: UnionKey.ThemeTabMode) {
this.tab.mode = mode;
},
/** 设置多页签缓存 */
setTabIsCache(isCache: boolean) {
this.tab.isCache = isCache;
},
/** 侧边栏宽度 */
setSiderWidth(width: number | null) {
if (width) {
this.sider.width = width;
}
},
/** 侧边栏折叠时的宽度 */
setSiderCollapsedWidth(width: number) {
this.sider.collapsedWidth = width;
},
/** vertical-mix模式下侧边栏宽度 */
setMixSiderWidth(width: number | null) {
if (width) {
this.sider.mixWidth = width;
}
},
/** vertical-mix模式下侧边栏折叠时的宽度 */
setMixSiderCollapsedWidth(width: number) {
this.sider.mixCollapsedWidth = width;
},
/** vertical-mix模式下侧边栏展示子菜单的宽度 */
setMixSiderChildMenuWidth(width: number) {
this.sider.mixChildMenuWidth = width;
},
/** 设置水平模式的菜单的位置 */
setHorizontalMenuPosition(position: UnionKey.ThemeHorizontalMenuPosition) {
this.menu.horizontalPosition = position;
},
/** 设置底部是否显示 */
setFooterVisible(isVisible: boolean) {
this.footer.visible = isVisible;
},
/** 设置底部是否固定 */
setFooterIsFixed(isFixed: boolean) {
this.footer.fixed = isFixed;
},
/** 设置底部是否固定 */
setFooterIsRight(right: boolean) {
this.footer.right = right;
},
/** 设置底部高度 */
setFooterHeight(height: number) {
this.footer.height = height;
},
/** 设置底部高度 */
setFooterInverted(inverted: boolean) {
this.footer.inverted = inverted;
},
/** 设置切换页面时是否过渡动画 */
setPageIsAnimate(animate: boolean) {
this.page.animate = animate;
},
/** 设置页面过渡动画类型 */
setPageAnimateMode(mode: UnionKey.ThemeAnimateMode) {
this.page.animateMode = mode;
return settings.value.themeScheme === 'dark';
});
/**
* theme colors
*/
const themeColors = computed(() => {
const { themeColor, otherColor, isInfoFollowPrimary } = settings.value;
const colors: App.Theme.ThemeColor = {
primary: themeColor,
...otherColor,
info: isInfoFollowPrimary ? themeColor : otherColor.info
};
return colors;
});
/**
* naive theme
*/
const naiveTheme = computed(() => getNaiveTheme(themeColors.value));
/**
* settings json
* @description it is for copy settings
*/
const settingsJson = computed(() => JSON.stringify(settings.value));
/**
* reset store
*/
function resetStore() {
const themeStore = useThemeStore();
themeStore.$reset();
}
/**
* set theme scheme
* @param themeScheme
*/
function setThemeScheme(themeScheme: UnionKey.ThemeScheme) {
settings.value.themeScheme = themeScheme;
}
/**
* toggle theme scheme
*/
function toggleThemeScheme() {
const themeSchemes: UnionKey.ThemeScheme[] = ['light', 'dark', 'auto'];
const index = themeSchemes.findIndex(item => item === settings.value.themeScheme);
const nextIndex = index === themeSchemes.length - 1 ? 0 : index + 1;
const nextThemeScheme = themeSchemes[nextIndex];
setThemeScheme(nextThemeScheme);
}
/**
* update theme colors
* @param key theme color key
* @param color theme color
*/
function updateThemeColors(key: App.Theme.ThemeColorKey, color: string) {
if (key === 'primary') {
settings.value.themeColor = color;
} else {
settings.value.otherColor[key] = color;
}
}
/**
* set theme layout
* @param mode theme layout mode
*/
function setThemeLayout(mode: UnionKey.ThemeLayoutMode) {
settings.value.layout.mode = mode;
}
/**
* setup theme vars to html
*/
function setupThemeVarsToHtml() {
const { themeTokens, darkThemeTokens } = createThemeToken(themeColors.value);
addThemeVarsToHtml(themeTokens, darkThemeTokens);
}
/**
* cache theme settings
*/
function cacheThemeSettings() {
const isProd = import.meta.env.PROD;
if (!isProd) return;
localStg.set('themeSettings', settings.value);
}
// cache theme settings when page is closed or refreshed
useEventListener(window, 'beforeunload', () => {
cacheThemeSettings();
});
// watch store
scope.run(() => {
// watch dark mode
watch(
darkMode,
val => {
toggleCssDarkMode(val);
},
{ immediate: true }
);
// themeColors change, update css vars
watch(
themeColors,
() => {
setupThemeVarsToHtml();
},
{ immediate: true }
);
});
/**
* on scope dispose
*/
onScopeDispose(() => {
scope.stop();
});
return {
...toRefs(settings.value),
darkMode,
themeColors,
naiveTheme,
settingsJson,
resetStore,
setThemeScheme,
toggleThemeScheme,
updateThemeColors,
setThemeLayout
};
});

View File

@ -0,0 +1,231 @@
import type { GlobalThemeOverrides } from 'naive-ui';
import { getColorPalette, getColorByColorPaletteNumber } from '@sa/color-palette';
import { getRgbOfColor, addColorAlpha } from '@sa/utils';
import { themeSettings, overrideThemeSettings } from '@/theme/settings';
import { themeVars } from '@/theme/vars';
import { localStg } from '@/utils/storage';
const DARK_CLASS = 'dark';
/**
* init theme settings
* @param darkMode is dark mode
*/
export function initThemeSettings() {
const isProd = import.meta.env.PROD;
// if it is development mode, the theme settings will not be cached, by update `themeSettings` in `src/theme/settings.ts` to update theme settings
if (!isProd) return themeSettings;
// if it is production mode, the theme settings will be cached in localStorage
// if want to update theme settings when publish new version, please update `overrideThemeSettings` in `src/theme/settings.ts`
const settings = localStg.get('themeSettings') || themeSettings;
const isOverride = localStg.get('overrideThemeFlag') === BUILD_TIME;
if (!isOverride) {
Object.assign(settings, overrideThemeSettings);
localStg.set('overrideThemeFlag', BUILD_TIME);
}
return settings;
}
/**
* create theme token
* @param darkMode is dark mode
*/
export function createThemeToken(colors: App.Theme.ThemeColor) {
const paletteColors = createThemePaletteColors(colors);
const themeTokens: App.Theme.ThemeToken = {
colors: {
...paletteColors,
nprogress: paletteColors.primary,
container: 'rgb(255, 255, 255)',
layout: 'rgb(247, 250, 252)',
inverted: 'rgb(0, 20, 40)',
base_text: 'rgb(31, 31, 31)'
},
boxShadow: {
header: '0 1px 2px rgb(0, 21, 41, 0.08)',
sider: '2px 0 8px 0 rgb(29, 35, 41, 0.05)',
tab: '0 1px 2px rgb(0, 21, 41, 0.08)'
}
};
const darkThemeTokens: App.Theme.ThemeToken = {
colors: {
...themeTokens.colors,
container: 'rgb(28, 28, 28)',
layout: 'rgb(18, 18, 18)',
base_text: 'rgb(224, 224, 224)'
},
boxShadow: {
...themeTokens.boxShadow
}
};
return {
themeTokens,
darkThemeTokens
};
}
/**
* create theme palette colors
* @param colors theme colors
*/
function createThemePaletteColors(colors: App.Theme.ThemeColor) {
const colorKeys = Object.keys(colors) as App.Theme.ThemeColorKey[];
const colorPaletteVar = {} as App.Theme.ThemePaletteColor;
colorKeys.forEach(key => {
const { palettes, main } = getColorPalette(colors[key], key);
colorPaletteVar[key] = main.hexcode;
palettes.forEach(item => {
colorPaletteVar[`${key}-${item.number}`] = item.hexcode;
});
});
return colorPaletteVar;
}
/**
* get css var by tokens
* @param tokens theme base tokens
*/
function getCssVarByTokens(tokens: App.Theme.BaseToken) {
const styles: string[] = [];
function removeVarPrefix(value: string) {
return value.replace('var(', '').replace(')', '');
}
function removeRgbPrefix(value: string) {
return value.replace('rgb(', '').replace(')', '');
}
for (const [key, tokenValues] of Object.entries(themeVars)) {
for (const [tokenKey, tokenValue] of Object.entries(tokenValues)) {
let cssVarsKey = removeVarPrefix(tokenValue);
let cssValue = tokens[key][tokenKey];
if (key === 'colors') {
cssVarsKey = removeRgbPrefix(cssVarsKey);
const { r, g, b } = getRgbOfColor(cssValue);
cssValue = `${r} ${g} ${b}`;
}
styles.push(`${cssVarsKey}: ${cssValue}`);
}
}
const styleStr = styles.join(';');
return styleStr;
}
/**
* add theme vars to html
* @param tokens
*/
export function addThemeVarsToHtml(tokens: App.Theme.BaseToken, darkTokens: App.Theme.BaseToken) {
const cssVarStr = getCssVarByTokens(tokens);
const darkCssVarStr = getCssVarByTokens(darkTokens);
const css = `
html {
${cssVarStr}
}
`;
const darkCss = `
html.${DARK_CLASS} {
${darkCssVarStr}
`;
const style = document.createElement('style');
style.innerText = css + darkCss;
document.head.appendChild(style);
}
/**
* toggle css dark mode
* @param darkMode
*/
export function toggleCssDarkMode(darkMode = false) {
function addDarkClass() {
document.documentElement.classList.add(DARK_CLASS);
}
function removeDarkClass() {
document.documentElement.classList.remove(DARK_CLASS);
}
if (darkMode) {
addDarkClass();
} else {
removeDarkClass();
}
}
type NaiveColorScene = '' | 'Suppl' | 'Hover' | 'Pressed' | 'Active';
type NaiveColorKey = `${App.Theme.ThemeColorKey}Color${NaiveColorScene}`;
type NaiveThemeColor = Partial<Record<NaiveColorKey, string>>;
interface NaiveColorAction {
scene: NaiveColorScene;
handler: (color: string) => string;
}
/**
* get naive theme colors
* @param colors
*/
function getNaiveThemeColors(colors: App.Theme.ThemeColor) {
const colorActions: NaiveColorAction[] = [
{ scene: '', handler: color => color },
{ scene: 'Suppl', handler: color => color },
{ scene: 'Hover', handler: color => getColorByColorPaletteNumber(color, 500) },
{ scene: 'Pressed', handler: color => getColorByColorPaletteNumber(color, 700) },
{ scene: 'Active', handler: color => addColorAlpha(color, 0.1) }
];
const themeColors: NaiveThemeColor = {};
const colorEntries = Object.entries(colors) as [App.Theme.ThemeColorKey, string][];
colorEntries.forEach(color => {
colorActions.forEach(action => {
const [colorType, colorValue] = color;
const colorKey: NaiveColorKey = `${colorType}Color${action.scene}`;
themeColors[colorKey] = action.handler(colorValue);
});
});
return themeColors;
}
/**
* get naive theme
* @param colors theme colors
*/
export function getNaiveTheme(colors: App.Theme.ThemeColor) {
const { primary: colorLoading } = colors;
const theme: GlobalThemeOverrides = {
common: {
...getNaiveThemeColors(colors)
},
LoadingBar: {
colorLoading
}
};
return theme;
}