mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 07:09:20 +08:00
update: 升级vben5.5.9到5.7.0
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/design",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -23,11 +23,16 @@
|
||||
"exports": {
|
||||
"./bem": {
|
||||
"development": "./src/scss-bem/bem.scss",
|
||||
"production": "./src/scss-bem/bem.scss",
|
||||
"default": "./dist/bem.scss"
|
||||
},
|
||||
"./theme": {
|
||||
"default": "./src/css/global.css"
|
||||
},
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/design.css"
|
||||
}
|
||||
},
|
||||
@@ -37,5 +42,8 @@
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@iconify/json": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,160 +1 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before {
|
||||
@apply border-border;
|
||||
|
||||
box-sizing: border-box;
|
||||
border-style: solid;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
html {
|
||||
@apply text-foreground bg-background font-sans text-[100%];
|
||||
|
||||
font-variation-settings: normal;
|
||||
line-height: 1.15;
|
||||
text-size-adjust: 100%;
|
||||
font-synthesis-weight: none;
|
||||
scroll-behavior: smooth;
|
||||
text-rendering: optimizelegibility;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
|
||||
/* -webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale; */
|
||||
}
|
||||
|
||||
#app,
|
||||
body,
|
||||
html {
|
||||
@apply size-full;
|
||||
|
||||
/* scrollbar-gutter: stable; */
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
|
||||
/* pointer-events: auto !important; */
|
||||
|
||||
/* overflow: overlay; */
|
||||
|
||||
/* -webkit-font-smoothing: antialiased; */
|
||||
|
||||
/* -moz-osx-font-smoothing: grayscale; */
|
||||
}
|
||||
|
||||
a,
|
||||
a:active,
|
||||
a:hover,
|
||||
a:link,
|
||||
a:visited {
|
||||
@apply no-underline;
|
||||
}
|
||||
|
||||
::view-transition-new(root),
|
||||
::view-transition-old(root) {
|
||||
@apply animate-none mix-blend-normal;
|
||||
}
|
||||
|
||||
::view-transition-old(root) {
|
||||
@apply z-[1];
|
||||
}
|
||||
|
||||
::view-transition-new(root) {
|
||||
@apply z-[2147483646];
|
||||
}
|
||||
|
||||
html.dark::view-transition-old(root) {
|
||||
@apply z-[2147483646];
|
||||
}
|
||||
|
||||
html.dark::view-transition-new(root) {
|
||||
@apply z-[1];
|
||||
}
|
||||
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
@apply opacity-100;
|
||||
}
|
||||
|
||||
/* input:-webkit-autofill {
|
||||
@apply border-none;
|
||||
|
||||
box-shadow: 0 0 0 1000px transparent inset;
|
||||
} */
|
||||
|
||||
input[type='number']::-webkit-inner-spin-button,
|
||||
input[type='number']::-webkit-outer-spin-button {
|
||||
@apply m-0 appearance-none;
|
||||
}
|
||||
|
||||
/* 只有非mac下才进行调整,mac下使用默认滚动条 */
|
||||
html:not([data-platform='macOs']) {
|
||||
::-webkit-scrollbar {
|
||||
@apply h-[10px] w-[10px];
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-border rounded-sm border-none;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
@apply rounded-sm border-none bg-transparent shadow-none;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-button {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.flex-center {
|
||||
@apply flex items-center justify-center;
|
||||
}
|
||||
|
||||
.flex-col-center {
|
||||
@apply flex flex-col items-center justify-center;
|
||||
}
|
||||
|
||||
.outline-box {
|
||||
@apply outline-border relative cursor-pointer rounded-md p-1 outline outline-1;
|
||||
}
|
||||
|
||||
.outline-box::after {
|
||||
@apply absolute left-1/2 top-1/2 z-20 h-0 w-[1px] rounded-sm opacity-0 outline outline-2 outline-transparent transition-all duration-300 content-[""];
|
||||
}
|
||||
|
||||
.outline-box.outline-box-active {
|
||||
@apply outline-primary outline outline-2;
|
||||
}
|
||||
|
||||
.outline-box.outline-box-active::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.outline-box:not(.outline-box-active):hover::after {
|
||||
@apply outline-primary left-0 top-0 h-full w-full p-1 opacity-100;
|
||||
}
|
||||
|
||||
.vben-link {
|
||||
@apply text-primary hover:text-primary-hover active:text-primary-active cursor-pointer;
|
||||
}
|
||||
|
||||
.card-box {
|
||||
@apply bg-card text-card-foreground border-border rounded-xl border;
|
||||
}
|
||||
}
|
||||
|
||||
html.invert-mode {
|
||||
@apply invert;
|
||||
}
|
||||
|
||||
html.grayscale-mode {
|
||||
@apply grayscale;
|
||||
}
|
||||
@import '@vben/tailwind-config/theme';
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
@reference "@vben/tailwind-config/theme";
|
||||
|
||||
/* Make clicks pass-through */
|
||||
#nprogress {
|
||||
@apply pointer-events-none;
|
||||
}
|
||||
|
||||
#nprogress .bar {
|
||||
@apply bg-primary fixed left-0 top-0 z-[1031] h-[2px] w-full;
|
||||
@apply bg-primary fixed top-0 left-0 z-1031 h-0.5 w-full;
|
||||
}
|
||||
|
||||
/* Fancy blur effect */
|
||||
#nprogress .peg {
|
||||
@apply absolute right-0 block h-full w-[100px];
|
||||
@apply absolute right-0 block h-full w-25;
|
||||
|
||||
box-shadow:
|
||||
0 0 10px hsl(var(--primary)),
|
||||
@@ -20,11 +22,11 @@
|
||||
|
||||
/* Remove these to get rid of the spinner */
|
||||
#nprogress .spinner {
|
||||
@apply fixed right-4 top-4 z-[1031] block;
|
||||
@apply fixed top-4 right-4 z-1031 block;
|
||||
}
|
||||
|
||||
#nprogress .spinner-icon {
|
||||
@apply border-t-primary border-l-primary size-4 rounded-full border-[2px] border-solid border-transparent;
|
||||
@apply border-t-primary border-l-primary size-4 rounded-full border-2 border-solid border-transparent;
|
||||
|
||||
animation: nprogress-spinner 400ms linear infinite;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
.side-content {
|
||||
animation-duration: 0.2s;
|
||||
animation-duration: 0.3s;
|
||||
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
@keyframes slide-down {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
transform: translateY(50px);
|
||||
}
|
||||
|
||||
to {
|
||||
@@ -49,7 +49,7 @@
|
||||
@keyframes slide-left {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-10px);
|
||||
transform: translateX(-50px);
|
||||
}
|
||||
|
||||
to {
|
||||
@@ -61,7 +61,7 @@
|
||||
@keyframes slide-right {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-10px);
|
||||
transform: translateX(50px);
|
||||
}
|
||||
|
||||
to {
|
||||
@@ -73,7 +73,7 @@
|
||||
@keyframes slide-up {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
transform: translateY(-50px);
|
||||
}
|
||||
|
||||
to {
|
||||
@@ -85,3 +85,17 @@
|
||||
.z-popup {
|
||||
z-index: var(--popup-z-index);
|
||||
}
|
||||
|
||||
@keyframes shrink {
|
||||
0% {
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: scale(0.9);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +93,7 @@
|
||||
|
||||
/* 基本文字大小 */
|
||||
--font-size-base: 16px;
|
||||
--menu-font-size: calc(var(--font-size-base) * 0.875);
|
||||
|
||||
/* =============component & UI============= */
|
||||
|
||||
@@ -108,6 +109,90 @@
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.light,
|
||||
.light[data-theme='custom'],
|
||||
.light[data-theme='default'] {
|
||||
/* Default background color of <body />...etc */
|
||||
--background: 0 0% 100%;
|
||||
|
||||
/* 主体区域背景色 */
|
||||
--background-deep: 216 20.11% 95.47%;
|
||||
--foreground: 210 6% 21%;
|
||||
|
||||
/* Background color for <Card /> */
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
|
||||
/* Background color for popovers such as <DropdownMenu />, <HoverCard />, <Popover /> */
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
|
||||
/* Muted backgrounds such as <TabsList />, <Skeleton /> and <Switch /> */
|
||||
--muted: 240 4.8% 95.9%;
|
||||
--muted-foreground: 240 3.8% 46.1%;
|
||||
|
||||
/* 主题颜色 */
|
||||
--primary-foreground: 0 0% 98%;
|
||||
|
||||
/* Used for destructive actions such as <Button variant="destructive"> */
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
|
||||
/* Used for success actions such as <message> */
|
||||
--info-foreground: 220, 4%, 58%;
|
||||
--success-foreground: 0 0% 98%;
|
||||
|
||||
/* Used for warning actions such as <message> */
|
||||
--warning-foreground: 0 0% 98%;
|
||||
|
||||
/* Secondary colors for <Button /> */
|
||||
--secondary: 240 5% 96%;
|
||||
--secondary-foreground: 240 6% 10%;
|
||||
|
||||
/* Used for accents such as hover effects on <DropdownMenuItem>, <SelectItem>...etc */
|
||||
--accent: 240 5% 96%;
|
||||
--accent-dark: 216 14% 93%;
|
||||
--accent-darker: 216 11% 91%;
|
||||
--accent-lighter: 240 0% 98%;
|
||||
--accent-hover: 200deg 10% 90%;
|
||||
--accent-foreground: 240 6% 10%;
|
||||
|
||||
/* Darker color */
|
||||
--heavy: 192deg 9.43% 89.61%;
|
||||
--heavy-foreground: var(--accent-foreground);
|
||||
|
||||
/* Default border color */
|
||||
--border: 240 5.9% 90%;
|
||||
|
||||
/* Border color for inputs such as <Input />, <Select />, <Textarea /> */
|
||||
--input: 240deg 5.88% 90%;
|
||||
--input-placeholder: 217 10.6% 65%;
|
||||
--input-background: 0 0% 100%;
|
||||
|
||||
/* Used for focus ring */
|
||||
--ring: 222.2 84% 4.9%;
|
||||
|
||||
/* ============= custom ============= */
|
||||
|
||||
/* 遮罩颜色 */
|
||||
--overlay: 0 0% 0% / 45%;
|
||||
--overlay-content: 0 0% 95% / 45%;
|
||||
|
||||
/* =============component & UI============= */
|
||||
|
||||
/* menu */
|
||||
--sidebar: 0 0% 100%;
|
||||
--sidebar-deep: 0 0% 100%;
|
||||
--menu: var(--sidebar);
|
||||
|
||||
/* header */
|
||||
--header: 0 0% 100%;
|
||||
|
||||
accent-color: var(--primary);
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.light[data-theme='violet'],
|
||||
[data-theme='violet'] .light,
|
||||
[data-theme='violet'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 224 71.4% 4.1%;
|
||||
@@ -129,6 +214,8 @@
|
||||
--ring: 262.1 83.3% 57.8%;
|
||||
}
|
||||
|
||||
.light[data-theme='pink'],
|
||||
[data-theme='pink'] .light,
|
||||
[data-theme='pink'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 240 10% 3.9%;
|
||||
@@ -150,6 +237,8 @@
|
||||
--ring: 346.8 77.2% 49.8%;
|
||||
}
|
||||
|
||||
.light[data-theme='rose'],
|
||||
[data-theme='rose'] .light,
|
||||
[data-theme='rose'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 240 10% 3.9%;
|
||||
@@ -171,6 +260,8 @@
|
||||
--ring: 346.8 77.2% 49.8%;
|
||||
}
|
||||
|
||||
.light[data-theme='sky-blue'],
|
||||
[data-theme='sky-blue'] .light,
|
||||
[data-theme='sky-blue'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
@@ -192,6 +283,8 @@
|
||||
--ring: 221.2 83.2% 53.3%;
|
||||
}
|
||||
|
||||
.light[data-theme='deep-blue'],
|
||||
[data-theme='deep-blue'] .light,
|
||||
[data-theme='deep-blue'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
@@ -213,6 +306,8 @@
|
||||
--ring: 221.2 83.2% 53.3%;
|
||||
}
|
||||
|
||||
.light[data-theme='green'],
|
||||
[data-theme='green'] .light,
|
||||
[data-theme='green'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 240 10% 3.9%;
|
||||
@@ -234,6 +329,8 @@
|
||||
--ring: 142.1 76.2% 36.3%;
|
||||
}
|
||||
|
||||
.light[data-theme='deep-green'],
|
||||
[data-theme='deep-green'] .light,
|
||||
[data-theme='deep-green'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 240 10% 3.9%;
|
||||
@@ -255,6 +352,8 @@
|
||||
--ring: 142.1 76.2% 36.3%;
|
||||
}
|
||||
|
||||
.light[data-theme='orange'],
|
||||
[data-theme='orange'] .light,
|
||||
[data-theme='orange'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 20 14.3% 4.1%;
|
||||
@@ -276,6 +375,8 @@
|
||||
--ring: 24.6 95% 53.1%;
|
||||
}
|
||||
|
||||
.light[data-theme='yellow'],
|
||||
[data-theme='yellow'] .light,
|
||||
[data-theme='yellow'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 20 14.3% 4.1%;
|
||||
@@ -297,6 +398,8 @@
|
||||
--ring: 20 14.3% 4.1%;
|
||||
}
|
||||
|
||||
.light[data-theme='zinc'],
|
||||
[data-theme='zinc'] .light,
|
||||
[data-theme='zinc'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 240 10% 3.9%;
|
||||
@@ -318,6 +421,8 @@
|
||||
--ring: 240 5.9% 10%;
|
||||
}
|
||||
|
||||
.light[data-theme='neutral'],
|
||||
[data-theme='neutral'] .light,
|
||||
[data-theme='neutral'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 0 0% 3.9%;
|
||||
@@ -339,6 +444,8 @@
|
||||
--ring: 0 0% 3.9%;
|
||||
}
|
||||
|
||||
.light[data-theme='slate'],
|
||||
[data-theme='slate'] .light,
|
||||
[data-theme='slate'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
@@ -360,6 +467,8 @@
|
||||
--ring: 222.2 84% 4.9%;
|
||||
}
|
||||
|
||||
.light[data-theme='gray'],
|
||||
[data-theme='gray'] .light,
|
||||
[data-theme='gray'] {
|
||||
/* --background: 0 0% 100%; */
|
||||
--foreground: 224 71.4% 4.1%;
|
||||
|
||||
@@ -1,4 +1,2 @@
|
||||
import './default.css';
|
||||
import './dark.css';
|
||||
|
||||
export {};
|
||||
|
||||
@@ -4,5 +4,3 @@ import './css/global.css';
|
||||
import './css/transition.css';
|
||||
import './css/nprogress.css';
|
||||
import './css/ui.css';
|
||||
|
||||
export {};
|
||||
|
||||
+1
@@ -1,3 +1,4 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { defineConfig } from '@vben/vite-config';
|
||||
|
||||
export default defineConfig(async () => {
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: ['src/index'],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/icons",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild"
|
||||
"build": "pnpm exec tsdown"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -22,6 +22,7 @@
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
export {
|
||||
TextAlignCenter as AlignCenter,
|
||||
TextAlignStart as AlignLeft,
|
||||
TextAlignEnd as AlignRight,
|
||||
ArrowDown,
|
||||
ArrowLeft,
|
||||
ArrowLeftToLine,
|
||||
@@ -7,11 +10,13 @@ export {
|
||||
ArrowUp,
|
||||
ArrowUpToLine,
|
||||
Bell,
|
||||
Bold,
|
||||
BookOpenText,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronsDown,
|
||||
ChevronsLeft,
|
||||
ChevronsRight,
|
||||
Circle,
|
||||
@@ -21,7 +26,9 @@ export {
|
||||
CircleX,
|
||||
Copy,
|
||||
CornerDownLeft,
|
||||
Download,
|
||||
Ellipsis,
|
||||
Eraser,
|
||||
Expand,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
@@ -29,12 +36,23 @@ export {
|
||||
FoldHorizontal,
|
||||
Fullscreen,
|
||||
Github,
|
||||
Grid,
|
||||
Grip,
|
||||
GripVertical,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Highlighter,
|
||||
Menu as IconDefault,
|
||||
ImagePlus,
|
||||
Inbox,
|
||||
Info,
|
||||
InspectionPanel,
|
||||
Italic,
|
||||
Languages,
|
||||
LayoutGrid,
|
||||
Link2,
|
||||
List,
|
||||
ListOrdered,
|
||||
LoaderCircle,
|
||||
LockKeyhole,
|
||||
LogOut,
|
||||
@@ -43,15 +61,19 @@ export {
|
||||
ArrowRightFromLine as MdiMenuClose,
|
||||
ArrowLeftFromLine as MdiMenuOpen,
|
||||
Menu,
|
||||
MessageSquareCode,
|
||||
Minimize,
|
||||
Minimize2,
|
||||
MoonStar,
|
||||
Paintbrush,
|
||||
Palette,
|
||||
PanelLeft,
|
||||
PanelRight,
|
||||
Pin,
|
||||
PinOff,
|
||||
Plus,
|
||||
Redo2,
|
||||
RemoveFormatting,
|
||||
RotateCw,
|
||||
Search,
|
||||
SearchX,
|
||||
@@ -59,10 +81,16 @@ export {
|
||||
Shrink,
|
||||
Square,
|
||||
SquareCheckBig,
|
||||
SquareCode,
|
||||
SquareMinus,
|
||||
Strikethrough,
|
||||
Sun,
|
||||
SunMoon,
|
||||
SwatchBook,
|
||||
TextQuote,
|
||||
Underline,
|
||||
Undo2,
|
||||
Unlink2,
|
||||
UserRoundPen,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: [
|
||||
'src/store',
|
||||
'src/constants/index',
|
||||
'src/utils/index',
|
||||
'src/color/index',
|
||||
'src/cache/index',
|
||||
'src/global-state',
|
||||
],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/shared",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,8 +11,8 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild",
|
||||
"stub": "pnpm unbuild --stub"
|
||||
"build": "pnpm exec tsdown",
|
||||
"stub": "pnpm run build"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -22,31 +22,37 @@
|
||||
"./constants": {
|
||||
"types": "./src/constants/index.ts",
|
||||
"development": "./src/constants/index.ts",
|
||||
"production": "./src/constants/index.ts",
|
||||
"default": "./dist/constants/index.mjs"
|
||||
},
|
||||
"./utils": {
|
||||
"types": "./src/utils/index.ts",
|
||||
"development": "./src/utils/index.ts",
|
||||
"production": "./src/utils/index.ts",
|
||||
"default": "./dist/utils/index.mjs"
|
||||
},
|
||||
"./color": {
|
||||
"types": "./src/color/index.ts",
|
||||
"development": "./src/color/index.ts",
|
||||
"production": "./src/color/index.ts",
|
||||
"default": "./dist/color/index.mjs"
|
||||
},
|
||||
"./cache": {
|
||||
"types": "./src/cache/index.ts",
|
||||
"development": "./src/cache/index.ts",
|
||||
"production": "./src/cache/index.ts",
|
||||
"default": "./dist/cache/index.mjs"
|
||||
},
|
||||
"./store": {
|
||||
"types": "./src/store.ts",
|
||||
"development": "./src/store.ts",
|
||||
"production": "./src/store.ts",
|
||||
"default": "./dist/store.mjs"
|
||||
},
|
||||
"./global-state": {
|
||||
"types": "./src/global-state.ts",
|
||||
"development": "./src/global-state.ts",
|
||||
"production": "./src/global-state.ts",
|
||||
"default": "./dist/global-state.mjs"
|
||||
}
|
||||
},
|
||||
@@ -85,19 +91,14 @@
|
||||
"clsx": "catalog:",
|
||||
"dayjs": "catalog:",
|
||||
"defu": "catalog:",
|
||||
"es-toolkit": "catalog:",
|
||||
"lodash.clonedeep": "catalog:",
|
||||
"lodash.get": "catalog:",
|
||||
"lodash.isequal": "catalog:",
|
||||
"lodash.set": "catalog:",
|
||||
"nprogress": "catalog:",
|
||||
"tailwind-merge": "catalog:",
|
||||
"theme-colors": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash.clonedeep": "catalog:",
|
||||
"@types/lodash.get": "catalog:",
|
||||
"@types/lodash.isequal": "catalog:",
|
||||
"@types/lodash.set": "catalog:",
|
||||
"@types/nprogress": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,418 @@
|
||||
# Cache 模块
|
||||
|
||||
基于**策略模式**的异步存储管理方案,支持多种存储后端(localStorage、IndexedDB、Memory),提供统一的 API 接口。
|
||||
|
||||
## 架构设计
|
||||
|
||||
```shell
|
||||
┌───────────────────────────────────────────────┐
|
||||
│ StorageManager │
|
||||
│ ┌─────────────┐ ┌───────────────────────┐ │
|
||||
│ │ Prefix 隔离 │ │ TTL 过期管理 │ │
|
||||
│ └─────────────┘ └───────────────────────┘ │
|
||||
├───────────────────────────────────────────────┤
|
||||
│ IStorageDriver │
|
||||
├──────────┬─────────────────┬──────────────────┤
|
||||
│ Local │ IndexedDB │ Memory │
|
||||
│ Storage │ Driver │ Driver │
|
||||
│ Driver │ │ │
|
||||
└──────────┴─────────────────┴──────────────────┘
|
||||
```
|
||||
|
||||
**分层职责:**
|
||||
|
||||
| 层级 | 职责 |
|
||||
| ---------------- | -------------------------------------------- |
|
||||
| `StorageManager` | 命名空间前缀隔离、TTL 过期检查、统一对外 API |
|
||||
| `IStorageDriver` | 纯粹的 KV 存取抽象接口 |
|
||||
| 各 Driver 实现 | 对接具体存储引擎,不感知前缀和 TTL |
|
||||
|
||||
---
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 基本使用(默认 localStorage)
|
||||
|
||||
```typescript
|
||||
import { StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({ prefix: 'myapp' });
|
||||
// 使用 IndexedDB
|
||||
//new StorageManager({ driver: new IndexedDBDriver(), prefix: 'app' });
|
||||
|
||||
// 使用 sessionStorage
|
||||
//new StorageManager({ driver: new LocalStorageDriver({ storageType: 'sessionStorage' }), prefix: 'app' });
|
||||
|
||||
// 测试环境
|
||||
//new StorageManager({ driver: new MemoryStorageDriver(), prefix: 'test' });
|
||||
|
||||
// 存储数据
|
||||
await cache.setItem('user', { name: '张三', age: 28 });
|
||||
|
||||
// 读取数据
|
||||
const user = await cache.getItem('user');
|
||||
// => { name: '张三', age: 28 }
|
||||
|
||||
// 带默认值读取
|
||||
const settings = await cache.getItem('settings', { theme: 'light' });
|
||||
// 如果不存在,返回 { theme: 'light' }
|
||||
|
||||
// 删除数据
|
||||
await cache.removeItem('user');
|
||||
|
||||
// 清除当前前缀下所有数据
|
||||
await cache.clear();
|
||||
```
|
||||
|
||||
### 带 TTL 过期
|
||||
|
||||
```typescript
|
||||
const cache = new StorageManager({ prefix: 'session' });
|
||||
|
||||
// 设置 5 分钟后过期(TTL 单位为毫秒)
|
||||
await cache.setItem('token', 'abc123', 5 * 60 * 1000);
|
||||
|
||||
// 5 分钟内可以正常读取
|
||||
const token = await cache.getItem('token');
|
||||
// => 'abc123'
|
||||
|
||||
// 5 分钟后自动返回 null(惰性删除)
|
||||
const expiredToken = await cache.getItem('token');
|
||||
// => null
|
||||
|
||||
// 主动清理所有过期项
|
||||
await cache.clearExpiredItems();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 存储驱动
|
||||
|
||||
### LocalStorageDriver(默认)
|
||||
|
||||
基于浏览器 `localStorage` 或 `sessionStorage`,数据持久化存储。
|
||||
|
||||
```typescript
|
||||
import { LocalStorageDriver, StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
// 使用 localStorage(默认)
|
||||
const cache = new StorageManager({
|
||||
driver: new LocalStorageDriver(),
|
||||
prefix: 'app',
|
||||
});
|
||||
|
||||
// 使用 sessionStorage
|
||||
const sessionCache = new StorageManager({
|
||||
driver: new LocalStorageDriver({ storageType: 'sessionStorage' }),
|
||||
prefix: 'app',
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 同步 API 用 async 包装,保持接口统一
|
||||
- 自动处理 JSON 序列化/反序列化
|
||||
- 数据损坏时自动清除并返回 null
|
||||
- 存储上限约 5-10MB(视浏览器而定)
|
||||
|
||||
**适用场景:** 用户偏好设置、小型配置数据、Token 存储
|
||||
|
||||
---
|
||||
|
||||
### IndexedDBDriver
|
||||
|
||||
基于浏览器 IndexedDB,支持大容量结构化数据存储。
|
||||
|
||||
```typescript
|
||||
import {IndexedDBDriver, StorageManager} from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({
|
||||
driver: new IndexedDBDriver({
|
||||
dbName: 'my-app-db', // 数据库名称,默认 'vben-storage'
|
||||
dbVersion: 1, // 数据库版本,默认 1
|
||||
storeName: 'cache-store', // 对象存储名称,默认 'kv-store'
|
||||
}),
|
||||
prefix: 'data',
|
||||
});
|
||||
|
||||
// 存储大量数据
|
||||
await cache.setItem('table-data', largeDataArray);
|
||||
|
||||
// 存储二进制友好的结构(IndexedDB 原生支持)
|
||||
await cache.setItem('config', {
|
||||
columns: [...],
|
||||
filters: [...],
|
||||
pagination: {page: 1, size: 20},
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 懒初始化:首次操作时自动打开数据库,无需手动调用 `init()`
|
||||
- 存储容量大(通常数百 MB 到 GB 级别)
|
||||
- 支持结构化克隆(可存储 Date、RegExp、Blob 等复杂类型)
|
||||
- 天然异步,不阻塞主线程
|
||||
|
||||
**适用场景:** 离线数据缓存、大型表格数据、文件/图片缓存、复杂业务数据
|
||||
|
||||
---
|
||||
|
||||
### MemoryStorageDriver
|
||||
|
||||
基于内存 Map,数据不持久化,页面刷新即丢失。
|
||||
|
||||
```typescript
|
||||
import { MemoryStorageDriver, StorageManager } from '@vben-core/shared/cache';
|
||||
|
||||
const cache = new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix: 'test',
|
||||
});
|
||||
```
|
||||
|
||||
**特点:**
|
||||
|
||||
- 读写速度最快
|
||||
- 无浏览器 API 依赖
|
||||
- 数据随页面生命周期销毁
|
||||
|
||||
**适用场景:** 单元测试、SSR 服务端渲染、临时运行时缓存
|
||||
|
||||
---
|
||||
|
||||
## API 参考
|
||||
|
||||
### StorageManager
|
||||
|
||||
#### 构造函数
|
||||
|
||||
```typescript
|
||||
new StorageManager(options?: StorageManagerOptions)
|
||||
```
|
||||
|
||||
| 参数 | 类型 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `driver` | `IStorageDriver` | `new LocalStorageDriver()` | 存储驱动实例 |
|
||||
| `prefix` | `string` | `''` | 键前缀,用于命名空间隔离 |
|
||||
|
||||
#### 方法
|
||||
|
||||
| 方法 | 签名 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `getItem` | `getItem<T>(key: string, defaultValue?: T \| null): Promise<T \| null>` | 获取存储项,过期或不存在返回默认值 |
|
||||
| `setItem` | `setItem<T>(key: string, value: T, ttl?: number): Promise<void>` | 设置存储项,可选 TTL(毫秒) |
|
||||
| `removeItem` | `removeItem(key: string): Promise<void>` | 删除指定存储项 |
|
||||
| `clear` | `clear(): Promise<void>` | 清除当前前缀下所有存储项 |
|
||||
| `clearExpiredItems` | `clearExpiredItems(): Promise<void>` | 主动清理所有过期项 |
|
||||
|
||||
---
|
||||
|
||||
### IStorageDriver 接口
|
||||
|
||||
自定义驱动需要实现此接口:
|
||||
|
||||
```typescript
|
||||
interface IStorageDriver {
|
||||
clear(): Promise<void>;
|
||||
|
||||
getItem<T>(key: string): Promise<null | T>;
|
||||
|
||||
keys(): Promise<string[]>;
|
||||
|
||||
removeItem(key: string): Promise<void>;
|
||||
|
||||
setItem<T>(key: string, value: T): Promise<void>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 高级用法
|
||||
|
||||
### 自定义 Driver
|
||||
|
||||
```typescript
|
||||
import type { IStorageDriver } from '@vben-core/shared/cache';
|
||||
|
||||
class CookieStorageDriver implements IStorageDriver {
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const value = getCookie(key);
|
||||
return value ? JSON.parse(value) : null;
|
||||
}
|
||||
|
||||
async setItem<T>(key: string, value: T): Promise<void> {
|
||||
setCookie(key, JSON.stringify(value));
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
deleteCookie(key);
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
clearAllCookies();
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
return getAllCookieNames();
|
||||
}
|
||||
}
|
||||
|
||||
// 使用自定义 Driver
|
||||
const cache = new StorageManager({
|
||||
driver: new CookieStorageDriver(),
|
||||
prefix: 'ck',
|
||||
});
|
||||
```
|
||||
|
||||
### 根据环境动态选择 Driver
|
||||
|
||||
```typescript
|
||||
import {
|
||||
IndexedDBDriver,
|
||||
LocalStorageDriver,
|
||||
MemoryStorageDriver,
|
||||
StorageManager,
|
||||
} from '@vben-core/shared/cache';
|
||||
|
||||
function createStorageManager(prefix: string) {
|
||||
// SSR 环境使用内存驱动
|
||||
if (typeof window === 'undefined') {
|
||||
return new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix,
|
||||
});
|
||||
}
|
||||
|
||||
// 大数据场景使用 IndexedDB
|
||||
if (needsLargeStorage()) {
|
||||
return new StorageManager({
|
||||
driver: new IndexedDBDriver({ dbName: `${prefix}-db` }),
|
||||
prefix,
|
||||
});
|
||||
}
|
||||
|
||||
// 默认使用 localStorage
|
||||
return new StorageManager({ prefix });
|
||||
}
|
||||
```
|
||||
|
||||
### 命名空间隔离
|
||||
|
||||
```typescript
|
||||
// 不同模块使用不同前缀,互不干扰
|
||||
const userCache = new StorageManager({ prefix: 'user' });
|
||||
const configCache = new StorageManager({ prefix: 'config' });
|
||||
|
||||
await userCache.setItem('profile', { name: '张三' });
|
||||
await configCache.setItem('profile', { theme: 'dark' });
|
||||
|
||||
// 各自独立
|
||||
await userCache.getItem('profile'); // => { name: '张三' }
|
||||
await configCache.getItem('profile'); // => { theme: 'dark' }
|
||||
|
||||
// 只清除 user 前缀的数据
|
||||
await userCache.clear();
|
||||
await configCache.getItem('profile'); // => { theme: 'dark' }(不受影响)
|
||||
```
|
||||
|
||||
### 定时清理过期数据
|
||||
|
||||
```typescript
|
||||
const cache = new StorageManager({ prefix: 'app' });
|
||||
|
||||
// 应用启动时清理一次
|
||||
await cache.clearExpiredItems();
|
||||
|
||||
// 或者定时清理(每 10 分钟)
|
||||
setInterval(
|
||||
async () => {
|
||||
await cache.clearExpiredItems();
|
||||
},
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 数据存储格式
|
||||
|
||||
`StorageManager` 在 Driver 层存储的数据结构为:
|
||||
|
||||
```typescript
|
||||
interface StorageItem<T> {
|
||||
expiry?: number; // 过期时间戳(毫秒),undefined 表示永不过期
|
||||
value: T; // 实际业务数据
|
||||
}
|
||||
```
|
||||
|
||||
实际存储的 key 格式为:`{prefix}-{key}`
|
||||
|
||||
例如 `prefix = 'app'`,`key = 'user'`,则实际存储键为 `app-user`。
|
||||
|
||||
---
|
||||
|
||||
## 过期策略
|
||||
|
||||
采用**惰性删除 + 主动清理**双重策略:
|
||||
|
||||
| 策略 | 触发时机 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 惰性删除 | 调用 `getItem` 时 | 读取时检查过期,过期则删除并返回默认值 |
|
||||
| 主动清理 | 调用 `clearExpiredItems` 时 | 遍历所有带前缀的 key,删除已过期项 |
|
||||
|
||||
---
|
||||
|
||||
## 各 Driver 对比
|
||||
|
||||
| 特性 | LocalStorageDriver | IndexedDBDriver | MemoryStorageDriver |
|
||||
| ---------- | ------------------- | ---------------- | ------------------- |
|
||||
| 持久化 | ✅ | ✅ | ❌ |
|
||||
| 容量 | 5-10 MB | 数百 MB+ | 受内存限制 |
|
||||
| 速度 | 快(同步) | 中等(异步 I/O) | 最快 |
|
||||
| 数据类型 | 仅 JSON 可序列化 | 结构化克隆 | 任意 JS 对象 |
|
||||
| 浏览器支持 | 所有现代浏览器 | 所有现代浏览器 | 任意环境 |
|
||||
| 阻塞主线程 | 是 | 否 | 否 |
|
||||
| 适用场景 | 配置、Token、小数据 | 离线缓存、大数据 | 测试、SSR |
|
||||
|
||||
---
|
||||
|
||||
## 在项目中的使用
|
||||
|
||||
本项目中 `StorageManager` 主要被 `PreferenceManager` 消费,用于持久化用户偏好设置:
|
||||
|
||||
```typescript
|
||||
// packages/@core/preferences/src/preferences.ts
|
||||
class PreferenceManager {
|
||||
private cache: StorageManager;
|
||||
|
||||
constructor() {
|
||||
this.cache = new StorageManager();
|
||||
this.state = reactive<Preferences>({ ...defaultPreferences });
|
||||
}
|
||||
|
||||
initPreferences = async ({ namespace }) => {
|
||||
// 用应用命名空间重新初始化
|
||||
this.cache = new StorageManager({ prefix: namespace });
|
||||
|
||||
// 从缓存加载偏好设置
|
||||
const cached = await this.cache.getItem<Preferences>('preferences');
|
||||
// ...
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **所有方法都是异步的** — 即使底层是同步的 localStorage,API 也返回 Promise,确保切换 Driver 时无需改动调用方。
|
||||
|
||||
2. **TTL 单位是毫秒** — `setItem('key', value, 60000)` 表示 60 秒后过期。
|
||||
|
||||
3. **IndexedDB 懒初始化** — 不需要手动调用 `init()` 或 `open()`,首次操作时自动打开数据库连接并复用。
|
||||
|
||||
4. **前缀隔离是逻辑隔离** — `clear()` 只清除当前前缀下的数据,不影响其他前缀或无前缀的数据。
|
||||
|
||||
5. **错误处理** — LocalStorageDriver 在 JSON 解析失败时自动清除损坏数据; `PreferenceManager.saveToCache` 内部 try-catch 防止未捕获异常。
|
||||
|
||||
6. **IndexedDB 版本升级** — 如果需要修改 objectStore 结构,需要递增 `dbVersion`。当前实现在 `upgradeneeded` 事件中自动创建 objectStore。
|
||||
+56
-63
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { MemoryStorageDriver } from '../memory-storage-driver';
|
||||
import { StorageManager } from '../storage-manager';
|
||||
|
||||
describe('storageManager', () => {
|
||||
@@ -7,123 +8,115 @@ describe('storageManager', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorage.clear();
|
||||
storageManager = new StorageManager({
|
||||
driver: new MemoryStorageDriver(),
|
||||
prefix: 'test_',
|
||||
});
|
||||
});
|
||||
|
||||
it('should set and get an item', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
const user = storageManager.getItem('user');
|
||||
it('should set and get an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should return default value if item does not exist', () => {
|
||||
const user = storageManager.getItem('nonexistent', {
|
||||
it('should return default value if item does not exist', async () => {
|
||||
const user = await storageManager.getItem('nonexistent', {
|
||||
age: 0,
|
||||
name: 'Default User',
|
||||
});
|
||||
expect(user).toEqual({ age: 0, name: 'Default User' });
|
||||
});
|
||||
|
||||
it('should remove an item', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
storageManager.removeItem('user');
|
||||
const user = storageManager.getItem('user');
|
||||
it('should remove an item', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.removeItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear all items with the prefix', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
storageManager.clear();
|
||||
expect(storageManager.getItem('user1')).toBeNull();
|
||||
expect(storageManager.getItem('user2')).toBeNull();
|
||||
it('should clear all items with the prefix', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
expect(await storageManager.getItem('user1')).toBeNull();
|
||||
expect(await storageManager.getItem('user2')).toBeNull();
|
||||
});
|
||||
|
||||
it('should clear expired items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
it('should clear expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not clear non-expired items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
it('should not clear non-expired items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should handle JSON parse errors gracefully', () => {
|
||||
localStorage.setItem('test_user', '{ invalid JSON }');
|
||||
const user = storageManager.getItem('user', {
|
||||
age: 0,
|
||||
name: 'Default User',
|
||||
});
|
||||
expect(user).toEqual({ age: 0, name: 'Default User' });
|
||||
});
|
||||
it('should return null for non-existent items without default value', () => {
|
||||
const user = storageManager.getItem('nonexistent');
|
||||
it('should return null for non-existent items without default value', async () => {
|
||||
const user = await storageManager.getItem('nonexistent');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should overwrite existing items', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
|
||||
const user = storageManager.getItem('user');
|
||||
it('should overwrite existing items', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user', { age: 25, name: 'Jane Doe' });
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items without expiry correctly', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
it('should handle items without expiry correctly', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should remove expired items when accessed', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
it('should remove expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
vi.advanceTimersByTime(1001); // 快进时间
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
|
||||
it('should not remove non-expired items when accessed', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
it('should not remove non-expired items when accessed', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' }, 10_000); // 10秒过期
|
||||
vi.advanceTimersByTime(5000); // 快进时间
|
||||
const user = storageManager.getItem('user');
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should handle multiple items with different expiry times', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
|
||||
it('should handle multiple items with different expiry times', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' }, 1000); // 1秒过期
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' }, 2000); // 2秒过期
|
||||
vi.advanceTimersByTime(1500); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user1 = storageManager.getItem('user1');
|
||||
const user2 = storageManager.getItem('user2');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toEqual({ age: 25, name: 'Jane Doe' });
|
||||
});
|
||||
|
||||
it('should handle items with no expiry', () => {
|
||||
storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
it('should handle items with no expiry', async () => {
|
||||
await storageManager.setItem('user', { age: 30, name: 'John Doe' });
|
||||
vi.advanceTimersByTime(10_000); // 快进时间
|
||||
storageManager.clearExpiredItems();
|
||||
const user = storageManager.getItem('user');
|
||||
await storageManager.clearExpiredItems();
|
||||
const user = await storageManager.getItem('user');
|
||||
expect(user).toEqual({ age: 30, name: 'John Doe' });
|
||||
});
|
||||
|
||||
it('should clear all items correctly', () => {
|
||||
storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
storageManager.clear();
|
||||
const user1 = storageManager.getItem('user1');
|
||||
const user2 = storageManager.getItem('user2');
|
||||
it('should clear all items correctly', async () => {
|
||||
await storageManager.setItem('user1', { age: 30, name: 'John Doe' });
|
||||
await storageManager.setItem('user2', { age: 25, name: 'Jane Doe' });
|
||||
await storageManager.clear();
|
||||
const user1 = await storageManager.getItem('user1');
|
||||
const user2 = await storageManager.getItem('user2');
|
||||
expect(user1).toBeNull();
|
||||
expect(user2).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
export * from './indexeddb-driver';
|
||||
export * from './local-storage-driver';
|
||||
export * from './memory-storage-driver';
|
||||
export * from './storage-manager';
|
||||
export type * from './types';
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
interface IndexedDBDriverOptions {
|
||||
/** 数据库名称 */
|
||||
dbName?: string;
|
||||
/** 数据库版本 */
|
||||
dbVersion?: number;
|
||||
/** 对象存储名称 */
|
||||
storeName?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* IndexedDB 驱动
|
||||
* 采用懒初始化模式,首次操作时自动打开数据库
|
||||
*/
|
||||
class IndexedDBDriver implements IStorageDriver {
|
||||
private dbName: string;
|
||||
private dbPromise: null | Promise<IDBDatabase> = null;
|
||||
private dbVersion: number;
|
||||
private storeName: string;
|
||||
|
||||
constructor({
|
||||
dbName = 'vben-storage',
|
||||
dbVersion = 1,
|
||||
storeName = 'kv-store',
|
||||
}: IndexedDBDriverOptions = {}) {
|
||||
this.dbName = dbName;
|
||||
this.dbVersion = dbVersion;
|
||||
this.storeName = storeName;
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.clear();
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readonly');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
const request = store.get(key);
|
||||
|
||||
request.addEventListener('success', () =>
|
||||
resolve(request.result ?? null),
|
||||
);
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readonly');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
const request = store.getAllKeys();
|
||||
|
||||
request.addEventListener('success', () =>
|
||||
resolve(request.result.map(String)),
|
||||
);
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.delete(key);
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
const db = await this.getDB();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(this.storeName, 'readwrite');
|
||||
const store = tx.objectStore(this.storeName);
|
||||
store.put(value, key);
|
||||
|
||||
tx.addEventListener('complete', () => resolve());
|
||||
tx.addEventListener('error', () => reject(tx.error));
|
||||
tx.addEventListener('abort', () =>
|
||||
reject(tx.error ?? new Error('Transaction aborted')),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 懒初始化:首次调用时打开数据库,后续复用同一个 Promise
|
||||
*/
|
||||
private getDB(): Promise<IDBDatabase> {
|
||||
if (!this.dbPromise) {
|
||||
this.dbPromise = this.openDB().catch((error) => {
|
||||
// allow retry on next call
|
||||
this.dbPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return this.dbPromise;
|
||||
}
|
||||
|
||||
private openDB(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(this.dbName, this.dbVersion);
|
||||
|
||||
request.addEventListener('upgradeneeded', () => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(this.storeName)) {
|
||||
db.createObjectStore(this.storeName);
|
||||
}
|
||||
});
|
||||
|
||||
request.addEventListener('success', () => resolve(request.result));
|
||||
request.addEventListener('error', () => reject(request.error));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { IndexedDBDriver };
|
||||
export type { IndexedDBDriverOptions };
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
|
||||
interface LocalStorageDriverOptions {
|
||||
/** 使用 localStorage 还是 sessionStorage */
|
||||
storageType?: StorageType;
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalStorage / SessionStorage 驱动
|
||||
* 用 async 包装同步 API,保持接口统一
|
||||
*/
|
||||
class LocalStorageDriver implements IStorageDriver {
|
||||
private storage: Storage;
|
||||
|
||||
constructor({
|
||||
storageType = 'localStorage',
|
||||
}: LocalStorageDriverOptions = {}) {
|
||||
if (typeof window === 'undefined') {
|
||||
// eslint-disable-next-line unicorn/prefer-type-error -- not a type check, it's an environment check
|
||||
throw new Error(
|
||||
'LocalStorageDriver is not available in non-browser environments. Use MemoryStorageDriver instead.',
|
||||
);
|
||||
}
|
||||
this.storage =
|
||||
storageType === 'localStorage'
|
||||
? window.localStorage
|
||||
: window.sessionStorage;
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.storage.clear();
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const raw = this.storage.getItem(key);
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
// 数据损坏,清除并返回 null
|
||||
this.storage.removeItem(key);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
const result: string[] = [];
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key !== null) {
|
||||
result.push(key);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
this.storage.removeItem(key);
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
this.storage.setItem(key, JSON.stringify(value));
|
||||
}
|
||||
}
|
||||
|
||||
export { LocalStorageDriver };
|
||||
export type { LocalStorageDriverOptions };
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { IStorageDriver } from './types';
|
||||
|
||||
/**
|
||||
* 内存存储驱动
|
||||
* 适用于测试环境和 SSR 场景,数据不持久化
|
||||
*/
|
||||
class MemoryStorageDriver implements IStorageDriver {
|
||||
private store = new Map<string, unknown>();
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
async getItem<T>(key: string): Promise<null | T> {
|
||||
const value = this.store.get(key);
|
||||
return (value as T) ?? null;
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
return [...this.store.keys()];
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
async setItem(key: string, value: unknown): Promise<void> {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
export { MemoryStorageDriver };
|
||||
@@ -1,53 +1,54 @@
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
import type {
|
||||
IStorageDriver,
|
||||
StorageItem,
|
||||
StorageManagerOptions,
|
||||
} from './types';
|
||||
|
||||
interface StorageManagerOptions {
|
||||
prefix?: string;
|
||||
storageType?: StorageType;
|
||||
}
|
||||
|
||||
interface StorageItem<T> {
|
||||
expiry?: number;
|
||||
value: T;
|
||||
}
|
||||
import { LocalStorageDriver } from './local-storage-driver';
|
||||
import { MemoryStorageDriver } from './memory-storage-driver';
|
||||
|
||||
/**
|
||||
* 存储管理器(策略模式)
|
||||
* - prefix(命名空间隔离)在此层处理
|
||||
* - TTL(过期机制)在此层处理
|
||||
* - Driver 只负责纯粹的 KV 存取
|
||||
*/
|
||||
class StorageManager {
|
||||
private driver: IStorageDriver;
|
||||
private prefix: string;
|
||||
private storage: Storage;
|
||||
|
||||
constructor({
|
||||
prefix = '',
|
||||
storageType = 'localStorage',
|
||||
}: StorageManagerOptions = {}) {
|
||||
constructor({ driver, prefix = '' }: StorageManagerOptions = {}) {
|
||||
this.driver = driver || this.createDefaultDriver();
|
||||
this.prefix = prefix;
|
||||
this.storage =
|
||||
storageType === 'localStorage'
|
||||
? window.localStorage
|
||||
: window.sessionStorage;
|
||||
if (!this.prefix && this.driver instanceof LocalStorageDriver) {
|
||||
console.warn(
|
||||
'[StorageManager] empty prefix combined with LocalStorageDriver — clear()/keys() will affect every localStorage entry.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有带前缀的存储项
|
||||
*/
|
||||
clear(): void {
|
||||
const keysToRemove: string[] = [];
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key && key.startsWith(this.prefix)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
keysToRemove.forEach((key) => this.storage.removeItem(key));
|
||||
async clear(): Promise<void> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
const prefixedKeys = allKeys.filter((key) => key.startsWith(fullPrefix));
|
||||
await Promise.all(prefixedKeys.map((key) => this.driver.removeItem(key)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有过期的存储项
|
||||
*/
|
||||
clearExpiredItems(): void {
|
||||
for (let i = 0; i < this.storage.length; i++) {
|
||||
const key = this.storage.key(i);
|
||||
if (key && key.startsWith(this.prefix)) {
|
||||
const shortKey = key.replace(this.prefix, '');
|
||||
this.getItem(shortKey); // 调用 getItem 方法检查并移除过期项
|
||||
async clearExpiredItems(): Promise<void> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
const prefixedKeys = allKeys.filter((key) => key.startsWith(fullPrefix));
|
||||
|
||||
for (const fullKey of prefixedKeys) {
|
||||
const raw = await this.driver.getItem<StorageItem<unknown>>(fullKey);
|
||||
if (raw && raw.expiry && Date.now() > raw.expiry) {
|
||||
await this.driver.removeItem(fullKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,36 +57,47 @@ class StorageManager {
|
||||
* 获取存储项
|
||||
* @param key 键
|
||||
* @param defaultValue 当项不存在或已过期时返回的默认值
|
||||
* @returns 值,如果项已过期或解析错误则返回默认值
|
||||
* @returns 值,如果项已过期则返回默认值
|
||||
*/
|
||||
getItem<T>(key: string, defaultValue: null | T = null): null | T {
|
||||
async getItem<T>(
|
||||
key: string,
|
||||
defaultValue: null | T = null,
|
||||
): Promise<null | T> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
const itemStr = this.storage.getItem(fullKey);
|
||||
if (!itemStr) {
|
||||
const raw = await this.driver.getItem<StorageItem<T>>(fullKey);
|
||||
|
||||
if (!raw) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
try {
|
||||
const item: StorageItem<T> = JSON.parse(itemStr);
|
||||
if (item.expiry && Date.now() > item.expiry) {
|
||||
this.storage.removeItem(fullKey);
|
||||
return defaultValue;
|
||||
}
|
||||
return item.value;
|
||||
} catch (error) {
|
||||
console.error(`Error parsing item with key "${fullKey}":`, error);
|
||||
this.storage.removeItem(fullKey); // 如果解析失败,删除该项
|
||||
// TTL 检查
|
||||
if (raw.expiry && Date.now() > raw.expiry) {
|
||||
await this.driver.removeItem(fullKey);
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return raw.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前前缀下的所有存储键(已去除前缀部分)
|
||||
*/
|
||||
async keys(): Promise<string[]> {
|
||||
const allKeys = await this.driver.keys();
|
||||
const fullPrefix = this.prefix ? `${this.prefix}-` : '';
|
||||
if (!fullPrefix) return allKeys;
|
||||
return allKeys
|
||||
.filter((key) => key.startsWith(fullPrefix))
|
||||
.map((key) => key.slice(fullPrefix.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除存储项
|
||||
* @param key 键
|
||||
*/
|
||||
removeItem(key: string): void {
|
||||
async removeItem(key: string): Promise<void> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
this.storage.removeItem(fullKey);
|
||||
await this.driver.removeItem(fullKey);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,24 +106,40 @@ class StorageManager {
|
||||
* @param value 值
|
||||
* @param ttl 存活时间(毫秒)
|
||||
*/
|
||||
setItem<T>(key: string, value: T, ttl?: number): void {
|
||||
async setItem(key: string, value: unknown, ttl?: number): Promise<void> {
|
||||
const fullKey = this.getFullKey(key);
|
||||
const expiry = ttl ? Date.now() + ttl : undefined;
|
||||
const item: StorageItem<T> = { expiry, value };
|
||||
try {
|
||||
this.storage.setItem(fullKey, JSON.stringify(item));
|
||||
} catch (error) {
|
||||
console.error(`Error setting item with key "${fullKey}":`, error);
|
||||
}
|
||||
const item: StorageItem<unknown> = { expiry, value };
|
||||
await this.driver.setItem(fullKey, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的存储键
|
||||
* 根据运行环境创建默认驱动:
|
||||
* - 浏览器环境(window.localStorage 可用)→ LocalStorageDriver
|
||||
* - SSR / Node 环境 → MemoryStorageDriver
|
||||
*/
|
||||
private createDefaultDriver(): IStorageDriver {
|
||||
try {
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
return new LocalStorageDriver();
|
||||
}
|
||||
} catch (error) {
|
||||
// localStorage access denied (e.g. Safari private mode)
|
||||
console.warn(
|
||||
'localStorage is not accessible, falling back to MemoryStorageDriver:',
|
||||
error,
|
||||
);
|
||||
}
|
||||
return new MemoryStorageDriver();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整的存储键(带前缀)
|
||||
* @param key 原始键
|
||||
* @returns 带前缀的完整键
|
||||
*/
|
||||
private getFullKey(key: string): string {
|
||||
return `${this.prefix}-${key}`;
|
||||
return this.prefix ? `${this.prefix}-${key}` : key;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-12
@@ -1,17 +1,39 @@
|
||||
type StorageType = 'localStorage' | 'sessionStorage';
|
||||
/**
|
||||
* 存储驱动接口(策略模式核心抽象)
|
||||
* 所有存储实现(localStorage、IndexedDB、Memory 等)都需要实现此接口
|
||||
* Driver 层只负责纯粹的 KV 存取,不感知 TTL 和前缀
|
||||
*/
|
||||
interface IStorageDriver {
|
||||
/** 清除所有存储项 */
|
||||
clear(): Promise<void>;
|
||||
|
||||
interface StorageValue<T> {
|
||||
data: T;
|
||||
expiry: null | number;
|
||||
/** 获取存储项 */
|
||||
getItem<T>(key: string): Promise<null | T>;
|
||||
|
||||
/** 获取所有 key */
|
||||
keys(): Promise<string[]>;
|
||||
|
||||
/** 移除存储项 */
|
||||
removeItem(key: string): Promise<void>;
|
||||
|
||||
/** 设置存储项 */
|
||||
setItem(key: string, value: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
interface IStorageCache {
|
||||
clear(): void;
|
||||
getItem<T>(key: string): null | T;
|
||||
key(index: number): null | string;
|
||||
length(): number;
|
||||
removeItem(key: string): void;
|
||||
setItem<T>(key: string, value: T, expiryInMinutes?: number): void;
|
||||
/**
|
||||
* 带 TTL 的存储项包装结构
|
||||
* TTL 逻辑由 StorageManager 统一管理,Driver 层不感知
|
||||
*/
|
||||
interface StorageItem<T> {
|
||||
expiry?: number;
|
||||
value: T;
|
||||
}
|
||||
|
||||
export type { IStorageCache, StorageType, StorageValue };
|
||||
interface StorageManagerOptions {
|
||||
/** 存储驱动实例 */
|
||||
driver?: IStorageDriver;
|
||||
/** 键前缀,用于命名空间隔离 */
|
||||
prefix?: string;
|
||||
}
|
||||
|
||||
export type { IStorageDriver, StorageItem, StorageManagerOptions };
|
||||
|
||||
@@ -19,8 +19,12 @@ export const VBEN_LOGO_URL =
|
||||
*/
|
||||
export const VBEN_PREVIEW_URL = 'https://www.vben.pro';
|
||||
|
||||
export const VBEN_ANTDV_NEXT_PREVIEW_URL = 'https://antdv-next.vben.pro';
|
||||
|
||||
export const VBEN_ELE_PREVIEW_URL = 'https://ele.vben.pro';
|
||||
|
||||
export const VBEN_NAIVE_PREVIEW_URL = 'https://naive.vben.pro';
|
||||
|
||||
export const VBEN_ANT_PREVIEW_URL = 'https://ant.vben.pro';
|
||||
|
||||
export const VBEN_TD_PREVIEW_URL = 'https://tdesign.vben.pro';
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import dayjs from 'dayjs';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
formatDate,
|
||||
formatDateTime,
|
||||
getCurrentTimezone,
|
||||
getSystemTimezone,
|
||||
isDate,
|
||||
isDayjsObject,
|
||||
setCurrentTimezone,
|
||||
} from '../date';
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
describe('dateUtils', () => {
|
||||
const sampleISO = '2024-10-30T12:34:56Z';
|
||||
const sampleTimestamp = Date.parse(sampleISO);
|
||||
|
||||
beforeEach(() => {
|
||||
// 重置时区
|
||||
dayjs.tz.setDefault();
|
||||
setCurrentTimezone(); // 重置为系统默认
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDate
|
||||
// ===============================
|
||||
describe('formatDate', () => {
|
||||
it('should format a valid ISO date string', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY/MM/DD');
|
||||
expect(formatted).toMatch(/2024\/10\/30/);
|
||||
});
|
||||
|
||||
it('should format a timestamp correctly', () => {
|
||||
const formatted = formatDate(sampleTimestamp);
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a Date object', () => {
|
||||
const formatted = formatDate(new Date(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should format a dayjs object', () => {
|
||||
const formatted = formatDate(dayjs(sampleISO));
|
||||
expect(formatted).toMatch(/2024-10-30/);
|
||||
});
|
||||
|
||||
it('should return original input if date is invalid', () => {
|
||||
const invalid = 'not-a-date';
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const formatted = formatDate(invalid);
|
||||
expect(formatted).toBe(invalid);
|
||||
expect(spy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should apply given format', () => {
|
||||
const formatted = formatDate(sampleISO, 'YYYY-MM-DD HH:mm');
|
||||
expect(formatted).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// formatDateTime
|
||||
// ===============================
|
||||
describe('formatDateTime', () => {
|
||||
it('should format date into full datetime', () => {
|
||||
const result = formatDateTime(sampleISO);
|
||||
expect(result).toMatch(/2024-10-30 \d{2}:\d{2}:\d{2}/);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDate
|
||||
// ===============================
|
||||
describe('isDate', () => {
|
||||
it('should return true for Date instances', () => {
|
||||
expect(isDate(new Date())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-Date values', () => {
|
||||
expect(isDate('2024-10-30')).toBe(false);
|
||||
expect(isDate(null)).toBe(false);
|
||||
expect(isDate(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// isDayjsObject
|
||||
// ===============================
|
||||
describe('isDayjsObject', () => {
|
||||
it('should return true for dayjs objects', () => {
|
||||
expect(isDayjsObject(dayjs())).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for other values', () => {
|
||||
expect(isDayjsObject(new Date())).toBe(false);
|
||||
expect(isDayjsObject('string')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// getSystemTimezone
|
||||
// ===============================
|
||||
describe('getSystemTimezone', () => {
|
||||
it('should return a valid IANA timezone string', () => {
|
||||
const tz = getSystemTimezone();
|
||||
expect(typeof tz).toBe('string');
|
||||
expect(tz).toMatch(/^[A-Z]+\/[A-Z_]+/i);
|
||||
});
|
||||
});
|
||||
|
||||
// ===============================
|
||||
// setCurrentTimezone / getCurrentTimezone
|
||||
// ===============================
|
||||
describe('setCurrentTimezone & getCurrentTimezone', () => {
|
||||
it('should set and retrieve the current timezone', () => {
|
||||
setCurrentTimezone('Asia/Shanghai');
|
||||
expect(getCurrentTimezone()).toBe('Asia/Shanghai');
|
||||
});
|
||||
|
||||
it('should reset to system timezone when called with no args', () => {
|
||||
const guessed = getSystemTimezone();
|
||||
setCurrentTimezone();
|
||||
expect(getCurrentTimezone()).toBe(guessed);
|
||||
});
|
||||
|
||||
it('should update dayjs default timezone', () => {
|
||||
setCurrentTimezone('America/New_York');
|
||||
const d = dayjs('2024-01-01T00:00:00Z');
|
||||
// 校验时区转换生效(小时变化)
|
||||
expect(d.tz().format('HH')).not.toBe('00');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -116,11 +116,11 @@ describe('getElementVisibleRect', () => {
|
||||
} as HTMLElement;
|
||||
|
||||
expect(getElementVisibleRect(element)).toEqual({
|
||||
bottom: 800,
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 1100,
|
||||
right: 1000,
|
||||
top: 900,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { loadScript } from '../resources';
|
||||
|
||||
const testJsPath =
|
||||
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js';
|
||||
|
||||
describe('loadScript', () => {
|
||||
beforeEach(() => {
|
||||
// 每个测试前清空 head,保证环境干净
|
||||
@@ -12,18 +9,14 @@ describe('loadScript', () => {
|
||||
});
|
||||
|
||||
it('should resolve when the script loads successfully', async () => {
|
||||
const promise = loadScript(testJsPath);
|
||||
// happy-dom v20+ auto-fires 'load' via handleDisabledFileLoadingAsSuccess
|
||||
const promise = loadScript('/test-script.js');
|
||||
|
||||
// 此时脚本元素已被创建并插入
|
||||
const script = document.querySelector(
|
||||
`script[src="${testJsPath}"]`,
|
||||
'script[src="/test-script.js"]',
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
|
||||
// 模拟加载成功
|
||||
script.dispatchEvent(new Event('load'));
|
||||
|
||||
// 等待 promise resolve
|
||||
await expect(promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -45,37 +38,44 @@ describe('loadScript', () => {
|
||||
});
|
||||
|
||||
it('should reject when the script fails to load', async () => {
|
||||
let capturedScript: HTMLScriptElement | null = null;
|
||||
|
||||
// 拦截 append,捕获 script 元素但不插入 DOM,
|
||||
// 防止 happy-dom v20+ 自动触发 load 事件
|
||||
const appendSpy = vi
|
||||
.spyOn(document.head, 'append')
|
||||
.mockImplementation((...nodes) => {
|
||||
for (const node of nodes) {
|
||||
if (node instanceof HTMLScriptElement) {
|
||||
capturedScript = node;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const promise = loadScript('error.js');
|
||||
|
||||
const script = document.querySelector(
|
||||
'script[src="error.js"]',
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
appendSpy.mockRestore();
|
||||
|
||||
// 模拟加载失败
|
||||
script.dispatchEvent(new Event('error'));
|
||||
expect(capturedScript).toBeTruthy();
|
||||
if (!capturedScript) {
|
||||
throw new Error('Expected the captured script element to exist');
|
||||
}
|
||||
capturedScript.dispatchEvent(new Event('error'));
|
||||
|
||||
await expect(promise).rejects.toThrow('Failed to load script: error.js');
|
||||
});
|
||||
|
||||
it('should handle multiple concurrent calls and only insert one script tag', async () => {
|
||||
const p1 = loadScript(testJsPath);
|
||||
const p2 = loadScript(testJsPath);
|
||||
|
||||
const script = document.querySelector(
|
||||
`script[src="${testJsPath}"]`,
|
||||
) as HTMLScriptElement;
|
||||
expect(script).toBeTruthy();
|
||||
|
||||
// 触发一次 load,两个 promise 都应该 resolve
|
||||
script.dispatchEvent(new Event('load'));
|
||||
const p1 = loadScript('/test-script.js');
|
||||
const p2 = loadScript('/test-script.js');
|
||||
|
||||
// happy-dom v20+ auto-fires 'load',两个 promise 都应该 resolve
|
||||
await expect(p1).resolves.toBeUndefined();
|
||||
await expect(p2).resolves.toBeUndefined();
|
||||
|
||||
// 只插入一次
|
||||
const scripts = document.head.querySelectorAll(
|
||||
`script[src="${testJsPath}"]`,
|
||||
'script[src="/test-script.js"]',
|
||||
);
|
||||
expect(scripts).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { createStack, Stack } from '../stack';
|
||||
|
||||
describe('stack', () => {
|
||||
let stack: Stack<number>;
|
||||
|
||||
beforeEach(() => {
|
||||
stack = new Stack<number>();
|
||||
});
|
||||
|
||||
it('push & size should work', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('peek should return top element without removing it', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.peek()).toBe(2);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('pop should remove and return top element', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
expect(stack.pop()).toBe(2);
|
||||
expect(stack.size).toBe(1);
|
||||
expect(stack.peek()).toBe(1);
|
||||
});
|
||||
|
||||
it('pop on empty stack should return undefined', () => {
|
||||
expect(stack.pop()).toBeUndefined();
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clear should remove all elements', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
stack.clear();
|
||||
|
||||
expect(stack.size).toBe(0);
|
||||
expect(stack.peek()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('toArray should return a shallow copy', () => {
|
||||
stack.push(1, 2);
|
||||
|
||||
const arr = stack.toArray();
|
||||
arr.push(3);
|
||||
|
||||
expect(stack.size).toBe(2);
|
||||
expect(stack.toArray()).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('dedup should remove existing item before push', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2, 1]);
|
||||
expect(stack.size).toBe(2);
|
||||
});
|
||||
|
||||
it('dedup = false should allow duplicate items', () => {
|
||||
const s = new Stack<number>(false);
|
||||
|
||||
s.push(1, 1, 1);
|
||||
|
||||
expect(s.toArray()).toEqual([1, 1, 1]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('remove should delete all matching items', () => {
|
||||
stack.push(1, 2, 1);
|
||||
|
||||
stack.remove(1);
|
||||
|
||||
expect(stack.toArray()).toEqual([2]);
|
||||
expect(stack.size).toBe(1);
|
||||
});
|
||||
|
||||
it('maxSize should limit stack capacity', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 4);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3, 4]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('dedup + maxSize should work together', () => {
|
||||
const s = new Stack<number>(true, 3);
|
||||
|
||||
s.push(1, 2, 3, 2); // 去重并重新入栈
|
||||
|
||||
expect(s.toArray()).toEqual([1, 3, 2]);
|
||||
expect(s.size).toBe(3);
|
||||
});
|
||||
|
||||
it('createStack should create a stack instance', () => {
|
||||
const s = createStack<number>(true, 2);
|
||||
|
||||
s.push(1, 2, 3);
|
||||
|
||||
expect(s.toArray()).toEqual([2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,9 @@ describe('stateHandler', () => {
|
||||
}, 10);
|
||||
|
||||
// 等待过程中,期望 Promise 被 reject
|
||||
await expect(handler.waitForCondition()).rejects.toThrow();
|
||||
await expect(handler.waitForCondition()).rejects.toThrow(
|
||||
'Condition was set to false',
|
||||
);
|
||||
expect(handler.isConditionTrue()).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -138,8 +138,10 @@ describe('getNestedValue', () => {
|
||||
expect(result).toBe(2);
|
||||
});
|
||||
|
||||
it('should return the entire object if path is empty', () => {
|
||||
expect(() => getNestedValue(data, '')()).toThrow();
|
||||
it('should throw if path is empty', () => {
|
||||
expect(() => getNestedValue(data, '')).toThrow(
|
||||
'Path must be a non-empty string',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle paths with array indexes', () => {
|
||||
|
||||
@@ -1,19 +1,41 @@
|
||||
import dayjs from 'dayjs';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
|
||||
export function formatDate(time: number | string, format = 'YYYY-MM-DD') {
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
|
||||
type FormatDate = Date | dayjs.Dayjs | number | string;
|
||||
|
||||
type Format =
|
||||
| 'HH'
|
||||
| 'HH:mm'
|
||||
| 'HH:mm:ss'
|
||||
| 'YYYY'
|
||||
| 'YYYY-MM'
|
||||
| 'YYYY-MM-DD'
|
||||
| 'YYYY-MM-DD HH'
|
||||
| 'YYYY-MM-DD HH:mm'
|
||||
| 'YYYY-MM-DD HH:mm:ss'
|
||||
| (string & {});
|
||||
|
||||
export function formatDate(time?: FormatDate, format: Format = 'YYYY-MM-DD') {
|
||||
if (time === undefined || time === null || time === '') {
|
||||
return '';
|
||||
}
|
||||
try {
|
||||
const date = dayjs(time);
|
||||
const date = dayjs.isDayjs(time) ? time : dayjs(time);
|
||||
if (!date.isValid()) {
|
||||
throw new Error('Invalid date');
|
||||
}
|
||||
return date.format(format);
|
||||
return date.tz().format(format);
|
||||
} catch (error) {
|
||||
console.error(`Error formatting date: ${error}`);
|
||||
return time;
|
||||
return String(time ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDateTime(time: number | string) {
|
||||
export function formatDateTime(time?: FormatDate) {
|
||||
return formatDate(time, 'YYYY-MM-DD HH:mm:ss');
|
||||
}
|
||||
|
||||
@@ -24,3 +46,33 @@ export function isDate(value: any): value is Date {
|
||||
export function isDayjsObject(value: any): value is dayjs.Dayjs {
|
||||
return dayjs.isDayjs(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时区
|
||||
* @returns 当前时区
|
||||
*/
|
||||
export const getSystemTimezone = () => {
|
||||
return dayjs.tz.guess();
|
||||
};
|
||||
|
||||
/**
|
||||
* 自定义设置的时区
|
||||
*/
|
||||
let currentTimezone = getSystemTimezone();
|
||||
|
||||
/**
|
||||
* 设置默认时区
|
||||
* @param timezone
|
||||
*/
|
||||
export const setCurrentTimezone = (timezone?: string) => {
|
||||
currentTimezone = timezone || getSystemTimezone();
|
||||
dayjs.tz.setDefault(currentTimezone);
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取设置的时区
|
||||
* @returns 设置的时区
|
||||
*/
|
||||
export const getCurrentTimezone = () => {
|
||||
return currentTimezone;
|
||||
};
|
||||
|
||||
@@ -41,6 +41,18 @@ export function getElementVisibleRect(
|
||||
const left = Math.max(rect.left, 0);
|
||||
const right = Math.min(rect.right, viewWidth);
|
||||
|
||||
// 如果元素完全不可见,则返回一个空的矩形
|
||||
if (top >= viewHeight || bottom <= 0 || left >= viewWidth || right <= 0) {
|
||||
return {
|
||||
bottom: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
bottom,
|
||||
height: Math.max(0, bottom - top),
|
||||
|
||||
@@ -8,6 +8,7 @@ export * from './letter';
|
||||
export * from './merge';
|
||||
export * from './nprogress';
|
||||
export * from './resources';
|
||||
export * from './stack';
|
||||
export * from './state-handler';
|
||||
export * from './to';
|
||||
export * from './tree';
|
||||
@@ -15,7 +16,6 @@ export * from './unique';
|
||||
export * from './update-css-variables';
|
||||
export * from './util';
|
||||
export * from './window';
|
||||
export { get, isEqual, set } from 'es-toolkit/compat';
|
||||
// export { cloneDeep } from 'es-toolkit/object';
|
||||
export { default as cloneDeep } from 'lodash.clonedeep';
|
||||
export { default as get } from 'lodash.get';
|
||||
export { default as isEqual } from 'lodash.isequal';
|
||||
export { default as set } from 'lodash.set';
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// eslint-disable-next-line vue/prefer-import-from-vue
|
||||
import { isFunction, isObject, isString } from '@vue/shared';
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @zh_CN 栈数据结构
|
||||
*/
|
||||
export class Stack<T> {
|
||||
/**
|
||||
* @zh_CN 栈内元素数量
|
||||
*/
|
||||
get size() {
|
||||
return this.items.length;
|
||||
}
|
||||
/**
|
||||
* @zh_CN 是否去重
|
||||
*/
|
||||
private readonly dedup: boolean;
|
||||
/**
|
||||
* @zh_CN 栈内元素
|
||||
*/
|
||||
private items: T[] = [];
|
||||
|
||||
/**
|
||||
* @zh_CN 栈的最大容量
|
||||
*/
|
||||
private readonly maxSize?: number;
|
||||
|
||||
constructor(dedup = true, maxSize?: number) {
|
||||
this.maxSize = maxSize;
|
||||
this.dedup = dedup;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 清空栈内元素
|
||||
*/
|
||||
clear() {
|
||||
this.items.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 查看栈顶元素
|
||||
* @returns 栈顶元素
|
||||
*/
|
||||
peek(): T | undefined {
|
||||
return this.items[this.items.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 出栈
|
||||
* @returns 栈顶元素
|
||||
*/
|
||||
pop(): T | undefined {
|
||||
return this.items.pop();
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 入栈
|
||||
* @param items 要入栈的元素
|
||||
*/
|
||||
push(...items: T[]) {
|
||||
items.forEach((item) => {
|
||||
// 去重
|
||||
if (this.dedup) {
|
||||
const index = this.items.indexOf(item);
|
||||
if (index !== -1) {
|
||||
this.items.splice(index, 1);
|
||||
}
|
||||
}
|
||||
this.items.push(item);
|
||||
if (this.maxSize && this.items.length > this.maxSize) {
|
||||
this.items.splice(0, this.items.length - this.maxSize);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @zh_CN 移除栈内元素
|
||||
* @param itemList 要移除的元素列表
|
||||
*/
|
||||
remove(...itemList: T[]) {
|
||||
this.items = this.items.filter((i) => !itemList.includes(i));
|
||||
}
|
||||
/**
|
||||
* @zh_CN 保留栈内元素
|
||||
* @param itemList 要保留的元素列表
|
||||
*/
|
||||
retain(itemList: T[]) {
|
||||
this.items = this.items.filter((i) => itemList.includes(i));
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 转换为数组
|
||||
* @returns 栈内元素数组
|
||||
*/
|
||||
toArray(): T[] {
|
||||
return [...this.items];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh_CN 创建一个栈实例
|
||||
* @param dedup 是否去重
|
||||
* @param maxSize 栈的最大容量
|
||||
* @returns 栈实例
|
||||
*/
|
||||
export const createStack = <T>(dedup = true, maxSize?: number) =>
|
||||
new Stack<T>(dedup, maxSize);
|
||||
@@ -1,6 +1,6 @@
|
||||
export class StateHandler {
|
||||
private condition: boolean = false;
|
||||
private rejectCondition: (() => void) | null = null;
|
||||
private rejectCondition: ((reason?: Error) => void) | null = null;
|
||||
private resolveCondition: (() => void) | null = null;
|
||||
|
||||
isConditionTrue(): boolean {
|
||||
@@ -16,7 +16,7 @@ export class StateHandler {
|
||||
setConditionFalse() {
|
||||
this.condition = false;
|
||||
if (this.rejectCondition) {
|
||||
this.rejectCondition();
|
||||
this.rejectCondition(new Error('Condition was set to false'));
|
||||
this.clearPromises();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,4 +94,33 @@ function mapTree<T, V extends Record<string, any>>(
|
||||
});
|
||||
}
|
||||
|
||||
export { filterTree, mapTree, traverseTreeValues };
|
||||
/**
|
||||
* 对树形结构数据进行递归排序
|
||||
* @param treeData - 树形数据数组
|
||||
* @param sortFunction - 排序函数,用于定义排序规则
|
||||
* @param options - 配置选项,包括子节点属性名
|
||||
* @returns 排序后的树形数据
|
||||
*/
|
||||
function sortTree<T extends Record<string, any>>(
|
||||
treeData: T[],
|
||||
sortFunction: (a: T, b: T) => number,
|
||||
options?: TreeConfigOptions,
|
||||
): T[] {
|
||||
const { childProps } = options || {
|
||||
childProps: 'children',
|
||||
};
|
||||
|
||||
// 不用 Array.toSorted:Chrome <110 无此 API,登录后生成菜单会直接抛错卡住
|
||||
return [...treeData].sort(sortFunction).map((item) => {
|
||||
const children = item[childProps];
|
||||
if (children && Array.isArray(children) && children.length > 0) {
|
||||
return {
|
||||
...item,
|
||||
[childProps]: sortTree(children, sortFunction, options),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
export { filterTree, mapTree, sortTree, traverseTreeValues };
|
||||
|
||||
@@ -30,7 +30,7 @@ function openWindow(url: string, options: OpenWindowOptions = {}): void {
|
||||
function openRouteInNewWindow(path: string) {
|
||||
const { hash, origin } = location;
|
||||
const fullPath = path.startsWith('/') ? path : `/${path}`;
|
||||
const url = `${origin}${hash ? '/#' : ''}${fullPath}`;
|
||||
const url = `${origin}${hash && !fullPath.startsWith('/#') ? '/#' : ''}${fullPath}`;
|
||||
openWindow(url, { target: '_blank' });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: {
|
||||
'cache/index': 'src/cache/index.ts',
|
||||
'color/index': 'src/color/index.ts',
|
||||
'constants/index': 'src/constants/index.ts',
|
||||
'global-state': 'src/global-state.ts',
|
||||
store: 'src/store.ts',
|
||||
'utils/index': 'src/utils/index.ts',
|
||||
},
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: ['src/index'],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/typings",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,10 +11,11 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild"
|
||||
"build": "pnpm exec tsdown"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
"vue-router.d.ts"
|
||||
],
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
@@ -23,6 +24,7 @@
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
},
|
||||
"./vue-router": {
|
||||
|
||||
+17
-2
@@ -10,12 +10,17 @@ type LayoutType =
|
||||
type ThemeModeType = 'auto' | 'dark' | 'light';
|
||||
|
||||
/**
|
||||
* 偏好设置按钮位置
|
||||
* 按钮位置
|
||||
* user-dropdown 用户的下拉弹出框中
|
||||
* fixed 固定在右侧
|
||||
* header 顶栏
|
||||
* auto 自动
|
||||
*/
|
||||
type PreferencesButtonPositionType = 'auto' | 'fixed' | 'header';
|
||||
type PreferencesButtonPositionType =
|
||||
| 'auto'
|
||||
| 'fixed'
|
||||
| 'header'
|
||||
| 'user-dropdown';
|
||||
|
||||
type BuiltinThemeType =
|
||||
| 'custom'
|
||||
@@ -93,6 +98,15 @@ type PageTransitionType = 'fade' | 'fade-down' | 'fade-slide' | 'fade-up';
|
||||
*/
|
||||
type AuthPageLayoutType = 'panel-center' | 'panel-left' | 'panel-right';
|
||||
|
||||
/**
|
||||
* 时区选项
|
||||
*/
|
||||
interface TimezoneOption {
|
||||
label: string;
|
||||
offset: number;
|
||||
timezone: string;
|
||||
}
|
||||
|
||||
export type {
|
||||
AccessModeType,
|
||||
AuthPageLayoutType,
|
||||
@@ -108,4 +122,5 @@ export type {
|
||||
PreferencesButtonPositionType,
|
||||
TabsStyleType,
|
||||
ThemeModeType,
|
||||
TimezoneOption,
|
||||
};
|
||||
|
||||
+7
-1
@@ -30,6 +30,12 @@ interface BasicUserInfo {
|
||||
username: string;
|
||||
}
|
||||
|
||||
type ClassType = Array<object | string> | object | string;
|
||||
type ClassType =
|
||||
| Array<ClassType>
|
||||
| boolean
|
||||
| null
|
||||
| object
|
||||
| string
|
||||
| undefined;
|
||||
|
||||
export type { BasicOption, BasicUserInfo, ClassType, SelectOption, TabOption };
|
||||
|
||||
+26
-8
@@ -1,20 +1,38 @@
|
||||
import type { ComputedRef, MaybeRef } from 'vue';
|
||||
|
||||
/**
|
||||
* 类型级递归中增加深度计数
|
||||
*/
|
||||
type Increment<A extends unknown[]> = [...A, unknown];
|
||||
/**
|
||||
* 深层递归所有属性为可选
|
||||
*/
|
||||
type DeepPartial<T> = T extends object
|
||||
? {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
}
|
||||
: T;
|
||||
type DeepPartial<
|
||||
T,
|
||||
D extends number = 10,
|
||||
C extends unknown[] = [],
|
||||
> = C['length'] extends D
|
||||
? T
|
||||
: T extends object
|
||||
? {
|
||||
[P in keyof T]?: DeepPartial<T[P], D, Increment<C>>;
|
||||
}
|
||||
: T;
|
||||
|
||||
/**
|
||||
* 深层递归所有属性为只读
|
||||
*/
|
||||
type DeepReadonly<T> = {
|
||||
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
|
||||
};
|
||||
type DeepReadonly<
|
||||
T,
|
||||
D extends number = 10,
|
||||
C extends unknown[] = [],
|
||||
> = C['length'] extends D
|
||||
? T
|
||||
: T extends object
|
||||
? {
|
||||
readonly [P in keyof T]: DeepReadonly<T[P], D, Increment<C>>;
|
||||
}
|
||||
: T;
|
||||
|
||||
/**
|
||||
* 任意类型的异步函数
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Component } from 'vue';
|
||||
import type { RouteRecordRaw } from 'vue-router';
|
||||
|
||||
import type { Recordable } from './helper';
|
||||
|
||||
/**
|
||||
* 扩展路由原始对象
|
||||
*/
|
||||
@@ -66,6 +68,10 @@ interface MenuRecordRaw extends MenuRecordBadgeRaw {
|
||||
* 菜单路径,唯一,可当作key
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* 菜单参数
|
||||
*/
|
||||
query?: Recordable<any>;
|
||||
/**
|
||||
* 是否显示菜单
|
||||
* @default true
|
||||
|
||||
@@ -43,6 +43,10 @@ interface RouteMeta {
|
||||
| 'success'
|
||||
| 'warning'
|
||||
| string;
|
||||
/**
|
||||
* 路由对应dom是否缓存起来
|
||||
*/
|
||||
domCached?: boolean;
|
||||
/**
|
||||
* 路由的完整路径作为key(默认true)
|
||||
*/
|
||||
@@ -118,17 +122,9 @@ interface RouteMeta {
|
||||
*/
|
||||
query?: Recordable;
|
||||
/**
|
||||
* 标题名称(侧栏菜单)
|
||||
* 标题名称
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* 标签页标题(可空;空则回退 title;运行时 setTabTitle 写入 newTabTitle 优先生效)
|
||||
*/
|
||||
tabTitle?: string;
|
||||
/**
|
||||
* 运行时覆盖的标签标题(如概览页动态名)
|
||||
*/
|
||||
newTabTitle?: string;
|
||||
}
|
||||
|
||||
// 定义递归类型以将 RouteRecordRaw 的 component 属性更改为 string
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
+1
-2
@@ -1,5 +1,4 @@
|
||||
/* eslint-disable no-restricted-imports */
|
||||
import type { RouteMeta as IRouteMeta } from '@vben-core/typings';
|
||||
import type { RouteMeta as IRouteMeta } from './dist/index.d.mts';
|
||||
|
||||
import 'vue-router';
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: ['src/index'],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/composables",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild"
|
||||
"build": "pnpm exec tsdown"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
@@ -23,6 +23,7 @@
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
@@ -37,7 +38,7 @@
|
||||
"dependencies": {
|
||||
"@vben-core/shared": "workspace:*",
|
||||
"@vueuse/core": "catalog:",
|
||||
"radix-vue": "catalog:",
|
||||
"reka-ui": "catalog:",
|
||||
"sortablejs": "catalog:",
|
||||
"vue": "catalog:"
|
||||
},
|
||||
|
||||
@@ -29,9 +29,9 @@ describe('useSortable', () => {
|
||||
await initializeSortable();
|
||||
|
||||
// Import sortablejs to access the mocked create function
|
||||
const Sortable = await import(
|
||||
'sortablejs/modular/sortable.complete.esm.js'
|
||||
);
|
||||
const Sortable =
|
||||
// @ts-expect-error - This is a dynamic import
|
||||
await import('sortablejs/modular/sortable.complete.esm.js');
|
||||
|
||||
// Verify that Sortable.create was called with the correct parameters
|
||||
expect(Sortable.default.create).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -10,4 +10,4 @@ export {
|
||||
useForwardExpose,
|
||||
useForwardProps,
|
||||
useForwardPropsEmits,
|
||||
} from 'radix-vue';
|
||||
} from 'reka-ui';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
@@ -17,18 +17,22 @@ exports[`defaultPreferences immutability test > should not modify the config obj
|
||||
"contentPaddingRight": 0,
|
||||
"contentPaddingTop": 0,
|
||||
"defaultAvatar": "https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp",
|
||||
"defaultHomePath": "/workbench",
|
||||
"defaultHomePath": "/analytics",
|
||||
"dynamicTitle": true,
|
||||
"enableCheckUpdates": true,
|
||||
"enableCopyPreferences": true,
|
||||
"enablePreferences": true,
|
||||
"enableRefreshToken": false,
|
||||
"enableStickyPreferencesNavigationBar": true,
|
||||
"isMobile": false,
|
||||
"layout": "sidebar-nav",
|
||||
"locale": "zh-CN",
|
||||
"loginExpiredMode": "page",
|
||||
"name": "Vben Admin",
|
||||
"preferencesButtonPosition": "auto",
|
||||
"timezone": "Asia/Shanghai",
|
||||
"watermark": false,
|
||||
"watermarkContent": "",
|
||||
"zIndex": 200,
|
||||
},
|
||||
"breadcrumb": {
|
||||
@@ -82,6 +86,7 @@ exports[`defaultPreferences immutability test > should not modify the config obj
|
||||
"collapsed": false,
|
||||
"collapsedButton": true,
|
||||
"collapsedShowTitle": false,
|
||||
"draggable": true,
|
||||
"enable": true,
|
||||
"expandOnHover": true,
|
||||
"extraCollapse": false,
|
||||
@@ -102,7 +107,9 @@ exports[`defaultPreferences immutability test > should not modify the config obj
|
||||
"showIcon": true,
|
||||
"showMaximize": true,
|
||||
"showMore": true,
|
||||
"showRefresh": true,
|
||||
"styleType": "chrome",
|
||||
"visitHistory": true,
|
||||
"wheelable": true,
|
||||
},
|
||||
"theme": {
|
||||
@@ -111,10 +118,12 @@ exports[`defaultPreferences immutability test > should not modify the config obj
|
||||
"colorPrimary": "hsl(212 100% 45%)",
|
||||
"colorSuccess": "hsl(144 57% 58%)",
|
||||
"colorWarning": "hsl(42 84% 61%)",
|
||||
"fontSize": 16,
|
||||
"mode": "dark",
|
||||
"radius": "0.5",
|
||||
"semiDarkHeader": false,
|
||||
"semiDarkSidebar": false,
|
||||
"semiDarkSidebarSub": false,
|
||||
},
|
||||
"transition": {
|
||||
"enable": true,
|
||||
@@ -131,6 +140,7 @@ exports[`defaultPreferences immutability test > should not modify the config obj
|
||||
"refresh": true,
|
||||
"sidebarToggle": true,
|
||||
"themeToggle": true,
|
||||
"timezone": true,
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { defaultPreferences } from '../src/config';
|
||||
import { PreferenceManager } from '../src/preferences';
|
||||
import { isDarkTheme } from '../src/update-css-variables';
|
||||
|
||||
describe('preferences', () => {
|
||||
let preferenceManager: PreferenceManager;
|
||||
let PreferenceManager: typeof import('../src/preferences').PreferenceManager;
|
||||
let preferenceManager: InstanceType<
|
||||
typeof import('../src/preferences').PreferenceManager
|
||||
>;
|
||||
|
||||
// 模拟 window.matchMedia 方法
|
||||
vi.stubGlobal(
|
||||
@@ -21,7 +23,36 @@ describe('preferences', () => {
|
||||
removeListener: vi.fn(), // Deprecated
|
||||
})),
|
||||
);
|
||||
|
||||
vi.stubGlobal('localStorage', {
|
||||
clear: vi.fn(),
|
||||
getItem: vi.fn(() => null),
|
||||
key: vi.fn(() => null),
|
||||
length: 0,
|
||||
removeItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
});
|
||||
|
||||
vi.stubGlobal('sessionStorage', {
|
||||
clear: vi.fn(),
|
||||
getItem: vi.fn(() => null),
|
||||
key: vi.fn(() => null),
|
||||
length: 0,
|
||||
removeItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
({ PreferenceManager } = await import('../src/preferences'));
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(localStorage.getItem).mockImplementation(() => null);
|
||||
vi.mocked(localStorage.removeItem).mockReset();
|
||||
vi.mocked(localStorage.setItem).mockReset();
|
||||
vi.mocked(sessionStorage.getItem).mockImplementation(() => null);
|
||||
vi.mocked(sessionStorage.removeItem).mockReset();
|
||||
vi.mocked(sessionStorage.setItem).mockReset();
|
||||
preferenceManager = new PreferenceManager();
|
||||
});
|
||||
|
||||
@@ -74,7 +105,7 @@ describe('preferences', () => {
|
||||
expect(preferenceManager.getPreferences().app.colorWeakMode).toBe(true);
|
||||
});
|
||||
|
||||
it('resets preferences to default', () => {
|
||||
it('resets preferences to default', async () => {
|
||||
// 先更新一些偏好设置
|
||||
preferenceManager.updatePreferences({
|
||||
theme: {
|
||||
@@ -83,7 +114,7 @@ describe('preferences', () => {
|
||||
});
|
||||
|
||||
// 然后重置偏好设置
|
||||
preferenceManager.resetPreferences();
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(defaultPreferences);
|
||||
});
|
||||
@@ -143,7 +174,7 @@ describe('preferences', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('resets preferences to default correctly', () => {
|
||||
it('resets preferences to default correctly', async () => {
|
||||
// 先更新一些偏好设置
|
||||
preferenceManager.updatePreferences({
|
||||
app: { locale: 'en-US' },
|
||||
@@ -154,7 +185,7 @@ describe('preferences', () => {
|
||||
});
|
||||
|
||||
// 然后重置偏好设置
|
||||
preferenceManager.resetPreferences();
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getPreferences()).toEqual(defaultPreferences);
|
||||
});
|
||||
@@ -214,7 +245,10 @@ describe('preferences', () => {
|
||||
},
|
||||
};
|
||||
|
||||
await preferenceManager.initPreferences(overrides);
|
||||
await preferenceManager.initPreferences({
|
||||
namespace: 'apply-updates',
|
||||
overrides,
|
||||
});
|
||||
|
||||
preferenceManager.updatePreferences({
|
||||
theme: { mode: 'light' },
|
||||
@@ -222,6 +256,265 @@ describe('preferences', () => {
|
||||
|
||||
expect(preferenceManager.getPreferences().theme.mode).toBe('light');
|
||||
});
|
||||
|
||||
it('initializes custom preferences extension with default values', async () => {
|
||||
const extension = {
|
||||
fields: [
|
||||
{
|
||||
component: 'switch',
|
||||
defaultValue: true,
|
||||
key: 'enableWorkbench',
|
||||
label: '启用工作台',
|
||||
},
|
||||
{
|
||||
component: 'select',
|
||||
defaultValue: 'single',
|
||||
key: 'tenantMode',
|
||||
label: '租户模式',
|
||||
options: [
|
||||
{ label: '单租户', value: 'single' },
|
||||
{ label: '多租户', value: 'multi' },
|
||||
],
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
title: '业务偏好',
|
||||
} as const;
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension,
|
||||
namespace: 'custom-defaults',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getPreferencesExtension()).toEqual(extension);
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
enableWorkbench: true,
|
||||
tenantMode: 'single',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not expose mutable custom preference baselines or extension schema', async () => {
|
||||
const extension = {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
title: '业务偏好',
|
||||
} as const;
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension,
|
||||
namespace: 'custom-readonly',
|
||||
});
|
||||
|
||||
const initialCustomPreferences =
|
||||
preferenceManager.getInitialCustomPreferences<{
|
||||
pageSize: number;
|
||||
}>() as { pageSize: number };
|
||||
const preferencesExtension = preferenceManager.getPreferencesExtension<{
|
||||
pageSize: number;
|
||||
}>() as {
|
||||
fields: Array<{ componentProps?: { max?: number }; label: string }>;
|
||||
};
|
||||
const [firstField] = preferencesExtension.fields;
|
||||
|
||||
initialCustomPreferences.pageSize = 8;
|
||||
expect(firstField).toBeDefined();
|
||||
expect(firstField?.componentProps).toBeDefined();
|
||||
|
||||
if (!firstField || !firstField.componentProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
firstField.label = '已修改';
|
||||
firstField.componentProps.max = 20;
|
||||
|
||||
expect(preferenceManager.getInitialCustomPreferences()).toEqual({
|
||||
pageSize: 4,
|
||||
});
|
||||
expect(preferenceManager.getPreferencesExtension()).toEqual(extension);
|
||||
});
|
||||
|
||||
it('updates and resets custom preferences correctly', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
defaultValue: 20,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
{
|
||||
component: 'input',
|
||||
defaultValue: '日报',
|
||||
key: 'reportTitle',
|
||||
label: '报表标题',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-reset',
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 50,
|
||||
reportTitle: '月报',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 50,
|
||||
reportTitle: '月报',
|
||||
});
|
||||
|
||||
await preferenceManager.resetPreferences();
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 20,
|
||||
reportTitle: '日报',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores invalid custom preferences updates', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'switch',
|
||||
defaultValue: true,
|
||||
key: 'enableWorkbench',
|
||||
label: '启用工作台',
|
||||
},
|
||||
{
|
||||
component: 'select',
|
||||
defaultValue: 'single',
|
||||
key: 'tenantMode',
|
||||
label: '租户模式',
|
||||
options: [
|
||||
{ label: '单租户', value: 'single' },
|
||||
{ label: '多租户', value: 'multi' },
|
||||
],
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-invalid',
|
||||
});
|
||||
|
||||
const originalCustomPreferences = preferenceManager.getCustomPreferences();
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
enableWorkbench: 'true' as unknown as boolean,
|
||||
tenantMode: 'unknown',
|
||||
unknownField: 'value',
|
||||
} as any);
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual(
|
||||
originalCustomPreferences,
|
||||
);
|
||||
});
|
||||
|
||||
it('enforces custom number field min max and step constraints', async () => {
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-number-constraints',
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 1,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 12,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
|
||||
preferenceManager.updateCustomPreferences({
|
||||
pageSize: 5,
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 8,
|
||||
});
|
||||
});
|
||||
|
||||
it('filters cached custom number values that violate field constraints', async () => {
|
||||
vi.mocked(localStorage.getItem).mockImplementation((key) => {
|
||||
if (key.endsWith('cache-preferences-custom')) {
|
||||
return JSON.stringify({
|
||||
value: {
|
||||
pageSize: 5,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
await preferenceManager.initPreferences({
|
||||
extension: {
|
||||
fields: [
|
||||
{
|
||||
component: 'number',
|
||||
componentProps: {
|
||||
max: 10,
|
||||
min: 2,
|
||||
step: 2,
|
||||
},
|
||||
defaultValue: 4,
|
||||
key: 'pageSize',
|
||||
label: '分页大小',
|
||||
},
|
||||
],
|
||||
tabLabel: '扩展',
|
||||
},
|
||||
namespace: 'custom-number-cache',
|
||||
});
|
||||
|
||||
expect(preferenceManager.getCustomPreferences()).toEqual({
|
||||
pageSize: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDarkTheme', () => {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: ['src/index'],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/preferences",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"#build": "pnpm unbuild"
|
||||
"#build": "pnpm exec tsdown"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
@@ -20,12 +20,23 @@
|
||||
"sideEffects": [
|
||||
"**/*.css"
|
||||
],
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"default": "./src/index.ts",
|
||||
"#default": "./dist/index.mjs"
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -17,18 +17,22 @@ const defaultPreferences: Preferences = {
|
||||
contentPaddingTop: 0,
|
||||
defaultAvatar:
|
||||
'https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp',
|
||||
defaultHomePath: '/workbench',
|
||||
defaultHomePath: '/analytics',
|
||||
dynamicTitle: true,
|
||||
enableCheckUpdates: true,
|
||||
enableCopyPreferences: true,
|
||||
enablePreferences: true,
|
||||
enableRefreshToken: false,
|
||||
enableStickyPreferencesNavigationBar: true,
|
||||
isMobile: false,
|
||||
layout: 'sidebar-nav',
|
||||
locale: 'zh-CN',
|
||||
loginExpiredMode: 'page',
|
||||
name: 'Vben Admin',
|
||||
preferencesButtonPosition: 'auto',
|
||||
timezone: 'Asia/Shanghai',
|
||||
watermark: false,
|
||||
watermarkContent: '',
|
||||
zIndex: 200,
|
||||
},
|
||||
breadcrumb: {
|
||||
@@ -83,6 +87,7 @@ const defaultPreferences: Preferences = {
|
||||
collapsedButton: true,
|
||||
collapsedShowTitle: false,
|
||||
collapseWidth: 60,
|
||||
draggable: true,
|
||||
enable: true,
|
||||
expandOnHover: true,
|
||||
extraCollapse: false,
|
||||
@@ -103,7 +108,9 @@ const defaultPreferences: Preferences = {
|
||||
showIcon: true,
|
||||
showMaximize: true,
|
||||
showMore: true,
|
||||
showRefresh: true,
|
||||
styleType: 'chrome',
|
||||
visitHistory: true,
|
||||
wheelable: true,
|
||||
},
|
||||
theme: {
|
||||
@@ -114,8 +121,10 @@ const defaultPreferences: Preferences = {
|
||||
colorWarning: 'hsl(42 84% 61%)',
|
||||
mode: 'dark',
|
||||
radius: '0.5',
|
||||
fontSize: 16,
|
||||
semiDarkHeader: false,
|
||||
semiDarkSidebar: false,
|
||||
semiDarkSidebarSub: false,
|
||||
},
|
||||
transition: {
|
||||
enable: true,
|
||||
@@ -126,12 +135,13 @@ const defaultPreferences: Preferences = {
|
||||
widget: {
|
||||
fullscreen: true,
|
||||
globalSearch: true,
|
||||
languageToggle: false,
|
||||
languageToggle: true,
|
||||
lockScreen: true,
|
||||
notification: false,
|
||||
notification: true,
|
||||
refresh: true,
|
||||
sidebarToggle: true,
|
||||
themeToggle: true,
|
||||
timezone: true,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BuiltinThemeType } from '@vben-core/typings';
|
||||
import type { BuiltinThemeType, TimezoneOption } from '@vben-core/typings';
|
||||
|
||||
interface BuiltinThemePreset {
|
||||
color: string;
|
||||
@@ -38,12 +38,10 @@ const BUILT_IN_THEME_PRESETS: BuiltinThemePreset[] = [
|
||||
primaryColor: 'hsl(240 5.9% 10%)',
|
||||
type: 'zinc',
|
||||
},
|
||||
|
||||
{
|
||||
color: 'hsl(181 84% 32%)',
|
||||
type: 'deep-green',
|
||||
},
|
||||
|
||||
{
|
||||
color: 'hsl(211 91% 39%)',
|
||||
type: 'deep-blue',
|
||||
@@ -56,7 +54,6 @@ const BUILT_IN_THEME_PRESETS: BuiltinThemePreset[] = [
|
||||
color: 'hsl(0 75% 42%)',
|
||||
type: 'rose',
|
||||
},
|
||||
|
||||
{
|
||||
color: 'hsl(0 0% 25%)',
|
||||
darkPrimaryColor: 'hsl(0 0% 98%)',
|
||||
@@ -81,8 +78,39 @@ const BUILT_IN_THEME_PRESETS: BuiltinThemePreset[] = [
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 时区选项
|
||||
*/
|
||||
const DEFAULT_TIME_ZONE_OPTIONS: TimezoneOption[] = [
|
||||
{
|
||||
offset: -5,
|
||||
timezone: 'America/New_York',
|
||||
label: 'America/New_York(GMT-5)',
|
||||
},
|
||||
{
|
||||
offset: 0,
|
||||
timezone: 'Europe/London',
|
||||
label: 'Europe/London(GMT0)',
|
||||
},
|
||||
{
|
||||
offset: 8,
|
||||
timezone: 'Asia/Shanghai',
|
||||
label: 'Asia/Shanghai(GMT+8)',
|
||||
},
|
||||
{
|
||||
offset: 9,
|
||||
timezone: 'Asia/Tokyo',
|
||||
label: 'Asia/Tokyo(GMT+9)',
|
||||
},
|
||||
{
|
||||
offset: 9,
|
||||
timezone: 'Asia/Seoul',
|
||||
label: 'Asia/Seoul(GMT+9)',
|
||||
},
|
||||
];
|
||||
|
||||
export const COLOR_PRESETS = [...BUILT_IN_THEME_PRESETS].slice(0, 7);
|
||||
|
||||
export { BUILT_IN_THEME_PRESETS };
|
||||
export { BUILT_IN_THEME_PRESETS, DEFAULT_TIME_ZONE_OPTIONS };
|
||||
|
||||
export type { BuiltinThemePreset };
|
||||
|
||||
@@ -2,33 +2,21 @@ import type { Preferences } from './types';
|
||||
|
||||
import { preferencesManager } from './preferences';
|
||||
|
||||
// 偏好设置(带有层级关系)
|
||||
const preferences: Preferences =
|
||||
preferencesManager.getPreferences.apply(preferencesManager);
|
||||
|
||||
// 更新偏好设置
|
||||
const updatePreferences =
|
||||
preferencesManager.updatePreferences.bind(preferencesManager);
|
||||
|
||||
// 重置偏好设置
|
||||
const resetPreferences =
|
||||
preferencesManager.resetPreferences.bind(preferencesManager);
|
||||
|
||||
const clearPreferencesCache =
|
||||
preferencesManager.clearCache.bind(preferencesManager);
|
||||
|
||||
// 初始化偏好设置
|
||||
const initPreferences =
|
||||
preferencesManager.initPreferences.bind(preferencesManager);
|
||||
|
||||
export {
|
||||
clearPreferencesCache,
|
||||
initPreferences,
|
||||
preferences,
|
||||
preferencesManager,
|
||||
resetPreferences,
|
||||
export const {
|
||||
getPreferences,
|
||||
getCustomPreferences,
|
||||
getInitialCustomPreferences,
|
||||
getPreferencesExtension,
|
||||
updatePreferences,
|
||||
};
|
||||
updateCustomPreferences,
|
||||
resetPreferences,
|
||||
clearCache,
|
||||
initPreferences,
|
||||
} = preferencesManager;
|
||||
|
||||
export const preferences: Preferences = getPreferences();
|
||||
|
||||
export { preferencesManager };
|
||||
|
||||
export * from './constants';
|
||||
export type * from './types';
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { DeepPartial } from '@vben-core/typings';
|
||||
|
||||
import type { InitialOptions, Preferences } from './types';
|
||||
import type {
|
||||
CustomPreferencesField,
|
||||
CustomPreferencesRecord,
|
||||
InitialOptions,
|
||||
Preferences,
|
||||
PreferencesExtension,
|
||||
} from './types';
|
||||
|
||||
import { markRaw, reactive, readonly, watch } from 'vue';
|
||||
|
||||
@@ -16,165 +22,393 @@ import {
|
||||
import { defaultPreferences } from './config';
|
||||
import { updateCSSVariables } from './update-css-variables';
|
||||
|
||||
const STORAGE_KEY = 'preferences';
|
||||
const STORAGE_KEY_LOCALE = `${STORAGE_KEY}-locale`;
|
||||
const STORAGE_KEY_THEME = `${STORAGE_KEY}-theme`;
|
||||
const STORAGE_KEYS = {
|
||||
CUSTOM: 'preferences-custom',
|
||||
MAIN: 'preferences',
|
||||
LOCALE: 'preferences-locale',
|
||||
THEME: 'preferences-theme',
|
||||
} as const;
|
||||
|
||||
class PreferenceManager {
|
||||
private cache: null | StorageManager = null;
|
||||
// private flattenedState: Flatten<Preferences>;
|
||||
private cache: StorageManager;
|
||||
private customPreferencesExtension: null | PreferencesExtension<any> = null;
|
||||
private customState = reactive<CustomPreferencesRecord>({});
|
||||
private debouncedSave: () => void;
|
||||
private initialCustomPreferences: CustomPreferencesRecord = {};
|
||||
private initialPreferences: Preferences = defaultPreferences;
|
||||
private isInitialized: boolean = false;
|
||||
private savePreferences: (preference: Preferences) => void;
|
||||
private state: Preferences = reactive<Preferences>({
|
||||
...this.loadPreferences(),
|
||||
});
|
||||
private isInitialized = false;
|
||||
private state: Preferences;
|
||||
|
||||
constructor() {
|
||||
this.cache = new StorageManager();
|
||||
|
||||
// 避免频繁的操作缓存
|
||||
this.savePreferences = useDebounceFn(
|
||||
(preference: Preferences) => this._savePreferences(preference),
|
||||
150,
|
||||
);
|
||||
}
|
||||
|
||||
clearCache() {
|
||||
[STORAGE_KEY, STORAGE_KEY_LOCALE, STORAGE_KEY_THEME].forEach((key) => {
|
||||
this.cache?.removeItem(key);
|
||||
});
|
||||
}
|
||||
|
||||
public getInitialPreferences() {
|
||||
return this.initialPreferences;
|
||||
}
|
||||
|
||||
public getPreferences() {
|
||||
return readonly(this.state);
|
||||
// 构造函数不再同步读取缓存,使用默认值初始化
|
||||
// 真正的缓存加载在 initPreferences 中完成(已经是 async)
|
||||
this.state = reactive<Preferences>({ ...defaultPreferences });
|
||||
this.debouncedSave = useDebounceFn(() => this.saveToCache(), 150);
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖偏好设置
|
||||
* overrides 要覆盖的偏好设置
|
||||
* namespace 命名空间
|
||||
* 清除所有缓存的偏好设置
|
||||
*/
|
||||
public async initPreferences({ namespace, overrides }: InitialOptions) {
|
||||
// 是否初始化过
|
||||
clearCache = async () => {
|
||||
await Promise.all(
|
||||
Object.values(STORAGE_KEYS).map((key) => this.cache.removeItem(key)),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取扩展偏好设置
|
||||
*/
|
||||
getCustomPreferences = <
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
>() => {
|
||||
return readonly(this.customState) as Readonly<TCustomPreferences>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取初始化扩展偏好设置
|
||||
*/
|
||||
getInitialCustomPreferences = <
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
>() => {
|
||||
return this.cloneValue(
|
||||
this.initialCustomPreferences,
|
||||
) as Readonly<TCustomPreferences>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取初始化偏好设置
|
||||
*/
|
||||
getInitialPreferences = () => {
|
||||
return this.initialPreferences;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取当前偏好设置(只读)
|
||||
*/
|
||||
getPreferences = () => {
|
||||
return readonly(this.state);
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取扩展偏好设置配置
|
||||
*/
|
||||
getPreferencesExtension = <
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
>() => {
|
||||
return this.customPreferencesExtension
|
||||
? (this.cloneValue(this.customPreferencesExtension) as Readonly<
|
||||
PreferencesExtension<TCustomPreferences>
|
||||
>)
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化偏好设置
|
||||
* @param options - 初始化配置项
|
||||
* @param options.namespace - 命名空间,用于隔离不同应用的配置
|
||||
* @param options.overrides - 要覆盖的偏好设置
|
||||
*/
|
||||
initPreferences = async <
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
>({
|
||||
namespace,
|
||||
overrides,
|
||||
extension,
|
||||
}: InitialOptions<TCustomPreferences>) => {
|
||||
// 防止重复初始化
|
||||
if (this.isInitialized) {
|
||||
return;
|
||||
}
|
||||
// 初始化存储管理器
|
||||
this.cache = new StorageManager({ prefix: namespace });
|
||||
// 合并初始偏好设置
|
||||
this.initialPreferences = merge({}, overrides, defaultPreferences);
|
||||
|
||||
// 加载并合并当前存储的偏好设置
|
||||
// 使用命名空间初始化存储管理器
|
||||
this.cache = new StorageManager({ prefix: namespace });
|
||||
|
||||
// 合并初始偏好设置:前面的对象优先,后面的对象仅补齐缺失字段
|
||||
this.initialPreferences = merge({}, overrides, defaultPreferences);
|
||||
this.customPreferencesExtension = extension ?? null;
|
||||
this.initialCustomPreferences = this.resolveCustomPreferencesDefaults(
|
||||
this.customPreferencesExtension,
|
||||
);
|
||||
|
||||
// 加载缓存的偏好设置:用户缓存优先,初始化配置仅补齐缺失字段
|
||||
// (5.7 上游写成了 initial 优先,会导致主题等个性化刷新后丢失)
|
||||
const cachedPreferences = (await this.loadFromCache()) || {};
|
||||
const mergedPreference = merge(
|
||||
{},
|
||||
// overrides,
|
||||
this.loadCachedPreferences() || {},
|
||||
cachedPreferences,
|
||||
this.initialPreferences,
|
||||
);
|
||||
|
||||
// 更新偏好设置
|
||||
this.updatePreferences(mergedPreference);
|
||||
|
||||
const cachedCustom = (await this.loadCustomFromCache()) || {};
|
||||
this.replaceCustomPreferences(
|
||||
merge(
|
||||
{},
|
||||
this.sanitizeCustomPreferences(cachedCustom),
|
||||
this.initialCustomPreferences,
|
||||
),
|
||||
);
|
||||
await this.saveToCache();
|
||||
|
||||
// 设置监听器
|
||||
this.setupWatcher();
|
||||
|
||||
// 初始化平台标识
|
||||
this.initPlatform();
|
||||
// 标记为已初始化
|
||||
|
||||
this.isInitialized = true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置偏好设置
|
||||
* 偏好设置将被重置为初始值,并从 localStorage 中移除。
|
||||
*
|
||||
* @example
|
||||
* 假设 initialPreferences 为 { theme: 'light', language: 'en' }
|
||||
* 当前 state 为 { theme: 'dark', language: 'fr' }
|
||||
* this.resetPreferences();
|
||||
* 调用后,state 将被重置为 { theme: 'light', language: 'en' }
|
||||
* 并且 localStorage 中的对应项将被移除
|
||||
* 重置偏好设置到初始状态
|
||||
*/
|
||||
resetPreferences() {
|
||||
resetPreferences = async () => {
|
||||
// 将状态重置为初始偏好设置
|
||||
Object.assign(this.state, this.initialPreferences);
|
||||
// 保存重置后的偏好设置
|
||||
this.savePreferences(this.state);
|
||||
// 从存储中移除偏好设置项
|
||||
[STORAGE_KEY, STORAGE_KEY_THEME, STORAGE_KEY_LOCALE].forEach((key) => {
|
||||
this.cache?.removeItem(key);
|
||||
});
|
||||
this.updatePreferences(this.state);
|
||||
}
|
||||
this.replaceCustomPreferences(this.initialCustomPreferences);
|
||||
|
||||
// 保存偏好设置至缓存
|
||||
await this.saveToCache();
|
||||
|
||||
// 直接触发 UI 更新
|
||||
this.handleUpdates(this.state);
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新扩展偏好设置
|
||||
* @param updates - 要更新的扩展偏好设置
|
||||
*/
|
||||
updateCustomPreferences = (updates: DeepPartial<object>) => {
|
||||
if (!this.customPreferencesExtension) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sanitizedUpdates = this.sanitizeCustomPreferences(
|
||||
updates as DeepPartial<CustomPreferencesRecord>,
|
||||
);
|
||||
|
||||
if (Object.keys(sanitizedUpdates).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.replaceCustomPreferences(
|
||||
merge({}, sanitizedUpdates, markRaw(this.customState)),
|
||||
);
|
||||
this.debouncedSave();
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新偏好设置
|
||||
* @param updates - 要更新的偏好设置
|
||||
*/
|
||||
public updatePreferences(updates: DeepPartial<Preferences>) {
|
||||
updatePreferences = (updates: DeepPartial<Preferences>) => {
|
||||
// 深度合并更新内容和当前状态
|
||||
const mergedState = merge({}, updates, markRaw(this.state));
|
||||
|
||||
Object.assign(this.state, mergedState);
|
||||
|
||||
// 根据更新的键值执行相应的操作
|
||||
// 根据更新的值执行更新
|
||||
this.handleUpdates(updates);
|
||||
this.savePreferences(this.state);
|
||||
|
||||
// 保存到缓存(fire-and-forget,通过 debounce 控制频率)
|
||||
this.debouncedSave();
|
||||
};
|
||||
|
||||
private cloneValue<T>(value: T): T {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => this.cloneValue(item)) as T;
|
||||
}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(
|
||||
([key, nestedValue]) => [key, this.cloneValue(nestedValue)],
|
||||
),
|
||||
) as T;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存偏好设置
|
||||
* @param {Preferences} preference - 需要保存的偏好设置
|
||||
*/
|
||||
private _savePreferences(preference: Preferences) {
|
||||
this.cache?.setItem(STORAGE_KEY, preference);
|
||||
this.cache?.setItem(STORAGE_KEY_LOCALE, preference.app.locale);
|
||||
this.cache?.setItem(STORAGE_KEY_THEME, preference.theme.mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理更新的键值
|
||||
* 根据更新的键值执行相应的操作。
|
||||
* @param {DeepPartial<Preferences>} updates - 部分更新的偏好设置
|
||||
* 处理更新
|
||||
* @param updates - 更新的偏好设置
|
||||
*/
|
||||
private handleUpdates(updates: DeepPartial<Preferences>) {
|
||||
const themeUpdates = updates.theme || {};
|
||||
const appUpdates = updates.app || {};
|
||||
if (themeUpdates && Object.keys(themeUpdates).length > 0) {
|
||||
const { theme, app } = updates;
|
||||
|
||||
if (
|
||||
theme &&
|
||||
(Object.keys(theme).length > 0 || Reflect.has(theme, 'fontSize'))
|
||||
) {
|
||||
updateCSSVariables(this.state);
|
||||
}
|
||||
|
||||
if (
|
||||
Reflect.has(appUpdates, 'colorGrayMode') ||
|
||||
Reflect.has(appUpdates, 'colorWeakMode')
|
||||
app &&
|
||||
(Reflect.has(app, 'colorGrayMode') || Reflect.has(app, 'colorWeakMode'))
|
||||
) {
|
||||
this.updateColorMode(this.state);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化平台标识
|
||||
*/
|
||||
private initPlatform() {
|
||||
const dom = document.documentElement;
|
||||
dom.dataset.platform = isMacOs() ? 'macOs' : 'window';
|
||||
document.documentElement.dataset.platform = isMacOs() ? 'macOs' : 'window';
|
||||
}
|
||||
|
||||
private isAlmostInteger(value: number, epsilon = Number.EPSILON * 10) {
|
||||
return Math.abs(value - Math.round(value)) < epsilon;
|
||||
}
|
||||
|
||||
private isValidCustomPreferenceValue(
|
||||
field: CustomPreferencesField,
|
||||
value: unknown,
|
||||
) {
|
||||
switch (field.component) {
|
||||
case 'number': {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const max = this.resolveNumericConstraint(field.componentProps?.max);
|
||||
const min = this.resolveNumericConstraint(field.componentProps?.min);
|
||||
const step = this.resolveNumericConstraint(field.componentProps?.step);
|
||||
|
||||
if (min !== undefined && value < min) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (max !== undefined && value > max) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (step !== undefined) {
|
||||
if (step <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const stepBase = min ?? 0;
|
||||
const stepCount = (value - stepBase) / step;
|
||||
|
||||
if (!this.isAlmostInteger(stepCount)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
case 'select': {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
field.options.some((option) => option.value === value)
|
||||
);
|
||||
}
|
||||
case 'switch': {
|
||||
return typeof value === 'boolean';
|
||||
}
|
||||
default: {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓存中加载偏好设置。如果缓存中没有找到对应的偏好设置,则返回默认偏好设置。
|
||||
* 从缓存加载扩展偏好设置
|
||||
* @returns 缓存的扩展偏好设置,如果不存在则返回 null
|
||||
*/
|
||||
private loadCachedPreferences() {
|
||||
return this.cache?.getItem<Preferences>(STORAGE_KEY);
|
||||
private async loadCustomFromCache(): Promise<CustomPreferencesRecord | null> {
|
||||
return this.cache.getItem<CustomPreferencesRecord>(STORAGE_KEYS.CUSTOM);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载偏好设置
|
||||
* @returns {Preferences} 加载的偏好设置
|
||||
* 从缓存加载偏好设置
|
||||
* @returns 缓存的偏好设置,如果不存在则返回 null
|
||||
*/
|
||||
private loadPreferences(): Preferences {
|
||||
return this.loadCachedPreferences() || { ...defaultPreferences };
|
||||
private async loadFromCache(): Promise<null | Preferences> {
|
||||
return this.cache.getItem<Preferences>(STORAGE_KEYS.MAIN);
|
||||
}
|
||||
|
||||
private replaceCustomPreferences(preferences: CustomPreferencesRecord) {
|
||||
Object.keys(this.customState).forEach((key) => {
|
||||
Reflect.deleteProperty(this.customState, key);
|
||||
});
|
||||
Object.assign(this.customState, preferences);
|
||||
}
|
||||
|
||||
private resolveCustomPreferencesDefaults(
|
||||
extension: null | PreferencesExtension<any>,
|
||||
) {
|
||||
if (!extension) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const result: CustomPreferencesRecord = {};
|
||||
|
||||
for (const field of extension.fields) {
|
||||
result[field.key] = field.defaultValue;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private resolveNumericConstraint(value: unknown) {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private sanitizeCustomPreferences(
|
||||
updates: DeepPartial<CustomPreferencesRecord>,
|
||||
) {
|
||||
if (!this.customPreferencesExtension) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const result: CustomPreferencesRecord = {};
|
||||
|
||||
for (const field of this.customPreferencesExtension.fields) {
|
||||
const value = updates[field.key];
|
||||
|
||||
if (
|
||||
value !== undefined &&
|
||||
this.isValidCustomPreferenceValue(field, value)
|
||||
) {
|
||||
result[field.key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听状态和系统偏好设置的变化。
|
||||
* 保存偏好设置到缓存
|
||||
*/
|
||||
private async saveToCache() {
|
||||
try {
|
||||
await this.cache.setItem(STORAGE_KEYS.MAIN, this.state);
|
||||
await this.cache.setItem(STORAGE_KEYS.LOCALE, this.state.app.locale);
|
||||
await this.cache.setItem(STORAGE_KEYS.THEME, this.state.theme.mode);
|
||||
|
||||
if (this.customPreferencesExtension) {
|
||||
await this.cache.setItem(STORAGE_KEYS.CUSTOM, {
|
||||
...this.customState,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await this.cache.removeItem(STORAGE_KEYS.CUSTOM);
|
||||
} catch (error) {
|
||||
console.error('Failed to save preferences to cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听状态和系统偏好设置的变化
|
||||
*/
|
||||
private setupWatcher() {
|
||||
if (this.isInitialized) {
|
||||
@@ -184,6 +418,7 @@ class PreferenceManager {
|
||||
// 监听断点,判断是否移动端
|
||||
const breakpoints = useBreakpoints(breakpointsTailwind);
|
||||
const isMobile = breakpoints.smaller('md');
|
||||
|
||||
watch(
|
||||
() => isMobile.value,
|
||||
(val) => {
|
||||
@@ -198,12 +433,13 @@ class PreferenceManager {
|
||||
window
|
||||
.matchMedia('(prefers-color-scheme: dark)')
|
||||
.addEventListener('change', ({ matches: isDark }) => {
|
||||
// 如果偏好设置中主题模式为auto,则跟随系统更新
|
||||
// 仅在自动模式下跟随系统主题
|
||||
if (this.state.theme.mode === 'auto') {
|
||||
// 先应用实际的主题
|
||||
this.updatePreferences({
|
||||
theme: { mode: isDark ? 'dark' : 'light' },
|
||||
});
|
||||
// 恢复为auto模式
|
||||
// 再恢复为 auto 模式,保持跟随系统的状态
|
||||
this.updatePreferences({
|
||||
theme: { mode: 'auto' },
|
||||
});
|
||||
@@ -213,23 +449,17 @@ class PreferenceManager {
|
||||
|
||||
/**
|
||||
* 更新页面颜色模式(灰色、色弱)
|
||||
* @param preference
|
||||
* @param preference - 偏好设置
|
||||
*/
|
||||
private updateColorMode(preference: Preferences) {
|
||||
if (preference.app) {
|
||||
const { colorGrayMode, colorWeakMode } = preference.app;
|
||||
const dom = document.documentElement;
|
||||
const COLOR_WEAK = 'invert-mode';
|
||||
const COLOR_GRAY = 'grayscale-mode';
|
||||
colorWeakMode
|
||||
? dom.classList.add(COLOR_WEAK)
|
||||
: dom.classList.remove(COLOR_WEAK);
|
||||
colorGrayMode
|
||||
? dom.classList.add(COLOR_GRAY)
|
||||
: dom.classList.remove(COLOR_GRAY);
|
||||
}
|
||||
const { colorGrayMode, colorWeakMode } = preference.app;
|
||||
const dom = document.documentElement;
|
||||
|
||||
dom.classList.toggle('invert-mode', colorWeakMode);
|
||||
dom.classList.toggle('grayscale-mode', colorGrayMode);
|
||||
}
|
||||
}
|
||||
|
||||
const preferencesManager = new PreferenceManager();
|
||||
|
||||
export { PreferenceManager, preferencesManager };
|
||||
|
||||
@@ -17,6 +17,84 @@ import type {
|
||||
} from '@vben-core/typings';
|
||||
|
||||
type SupportedLanguagesType = 'en-US' | 'zh-CN';
|
||||
type CustomPreferencesValue = boolean | number | string;
|
||||
|
||||
interface CustomPreferencesOption<TValue extends string = string> {
|
||||
label: string;
|
||||
value: TValue;
|
||||
}
|
||||
|
||||
interface BaseCustomPreferencesField<
|
||||
TKey extends string = string,
|
||||
TValue extends CustomPreferencesValue = CustomPreferencesValue,
|
||||
> {
|
||||
componentProps?: Record<string, any>;
|
||||
defaultValue: TValue;
|
||||
disabled?: boolean;
|
||||
key: TKey;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
tip?: string;
|
||||
}
|
||||
|
||||
interface CustomPreferencesInputField<
|
||||
TKey extends string = string,
|
||||
> extends BaseCustomPreferencesField<TKey, string> {
|
||||
component: 'input';
|
||||
}
|
||||
|
||||
interface CustomPreferencesNumberField<
|
||||
TKey extends string = string,
|
||||
> extends BaseCustomPreferencesField<TKey, number> {
|
||||
component: 'number';
|
||||
}
|
||||
|
||||
interface CustomPreferencesSelectField<
|
||||
TKey extends string = string,
|
||||
> extends BaseCustomPreferencesField<TKey, string> {
|
||||
component: 'select';
|
||||
options: CustomPreferencesOption[];
|
||||
}
|
||||
|
||||
interface CustomPreferencesSwitchField<
|
||||
TKey extends string = string,
|
||||
> extends BaseCustomPreferencesField<TKey, boolean> {
|
||||
component: 'switch';
|
||||
}
|
||||
|
||||
type CustomPreferencesRecord = Record<string, CustomPreferencesValue>;
|
||||
|
||||
type AnyCustomPreferencesField =
|
||||
| CustomPreferencesInputField
|
||||
| CustomPreferencesNumberField
|
||||
| CustomPreferencesSelectField
|
||||
| CustomPreferencesSwitchField;
|
||||
|
||||
type CustomPreferencesField<
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
> =
|
||||
string extends Extract<keyof TCustomPreferences, string>
|
||||
? AnyCustomPreferencesField
|
||||
: {
|
||||
[K in Extract<
|
||||
keyof TCustomPreferences,
|
||||
string
|
||||
>]: TCustomPreferences[K] extends boolean
|
||||
? CustomPreferencesSwitchField<K>
|
||||
: TCustomPreferences[K] extends number
|
||||
? CustomPreferencesNumberField<K>
|
||||
: TCustomPreferences[K] extends string
|
||||
? CustomPreferencesInputField<K> | CustomPreferencesSelectField<K>
|
||||
: never;
|
||||
}[Extract<keyof TCustomPreferences, string>];
|
||||
|
||||
interface PreferencesExtension<
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
> {
|
||||
fields: Array<CustomPreferencesField<TCustomPreferences>>;
|
||||
tabLabel: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
interface AppPreferences {
|
||||
/** 权限模式 */
|
||||
@@ -53,12 +131,18 @@ interface AppPreferences {
|
||||
dynamicTitle: boolean;
|
||||
/** 是否开启检查更新 */
|
||||
enableCheckUpdates: boolean;
|
||||
/** 是否显示复制偏好设置按钮 */
|
||||
enableCopyPreferences: boolean;
|
||||
/** 是否显示偏好设置 */
|
||||
enablePreferences: boolean;
|
||||
/**
|
||||
* @zh_CN 是否开启refreshToken
|
||||
*/
|
||||
enableRefreshToken: boolean;
|
||||
/**
|
||||
* @zh_CN 是否开启首选项导航栏吸顶效果
|
||||
*/
|
||||
enableStickyPreferencesNavigationBar: boolean;
|
||||
/** 是否移动端 */
|
||||
isMobile: boolean;
|
||||
/** 布局方式 */
|
||||
@@ -71,10 +155,18 @@ interface AppPreferences {
|
||||
name: string;
|
||||
/** 偏好设置按钮位置 */
|
||||
preferencesButtonPosition: PreferencesButtonPositionType;
|
||||
/**
|
||||
* @zh_CN 应用时区
|
||||
*/
|
||||
timezone: string;
|
||||
/**
|
||||
* @zh_CN 是否开启水印
|
||||
*/
|
||||
watermark: boolean;
|
||||
/**
|
||||
* @zh_CN 水印文案
|
||||
*/
|
||||
watermarkContent: string;
|
||||
/** z-index */
|
||||
zIndex: number;
|
||||
}
|
||||
@@ -138,6 +230,8 @@ interface LogoPreferences {
|
||||
fit: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down';
|
||||
/** logo地址 */
|
||||
source: string;
|
||||
/** 暗色主题logo地址 (可选,若不设置则使用 source) */
|
||||
sourceDark?: string;
|
||||
}
|
||||
|
||||
interface NavigationPreferences {
|
||||
@@ -160,6 +254,8 @@ interface SidebarPreferences {
|
||||
collapsedShowTitle: boolean;
|
||||
/** 侧边栏折叠宽度 */
|
||||
collapseWidth: number;
|
||||
/** 侧边栏菜单拖拽 */
|
||||
draggable: boolean;
|
||||
/** 侧边栏是否可见 */
|
||||
enable: boolean;
|
||||
/** 菜单自动展开状态 */
|
||||
@@ -212,8 +308,12 @@ interface TabbarPreferences {
|
||||
showMaximize: boolean;
|
||||
/** 显示更多按钮 */
|
||||
showMore: boolean;
|
||||
/** 显示刷新按钮 */
|
||||
showRefresh: boolean;
|
||||
/** 标签页风格 */
|
||||
styleType: TabsStyleType;
|
||||
/** 是否开启访问历史记录 */
|
||||
visitHistory: boolean;
|
||||
/** 是否开启鼠标滚轮响应 */
|
||||
wheelable: boolean;
|
||||
}
|
||||
@@ -229,6 +329,8 @@ interface ThemePreferences {
|
||||
colorSuccess: string;
|
||||
/** 警告色 */
|
||||
colorWarning: string;
|
||||
/** 字体大小(单位:px) */
|
||||
fontSize: number;
|
||||
/** 当前主题 */
|
||||
mode: ThemeModeType;
|
||||
/** 圆角 */
|
||||
@@ -237,6 +339,8 @@ interface ThemePreferences {
|
||||
semiDarkHeader: boolean;
|
||||
/** 是否开启半深色菜单(只在theme='light'时生效) */
|
||||
semiDarkSidebar: boolean;
|
||||
/** 是否开启半深色子菜单(只在theme='light'时生效) */
|
||||
semiDarkSidebarSub: boolean;
|
||||
}
|
||||
|
||||
interface TransitionPreferences {
|
||||
@@ -267,6 +371,8 @@ interface WidgetPreferences {
|
||||
sidebarToggle: boolean;
|
||||
/** 是否显示主题切换部件 */
|
||||
themeToggle: boolean;
|
||||
/** 是否显示时区部件 */
|
||||
timezone: boolean;
|
||||
}
|
||||
|
||||
interface Preferences {
|
||||
@@ -300,19 +406,33 @@ interface Preferences {
|
||||
|
||||
type PreferencesKeys = keyof Preferences;
|
||||
|
||||
interface InitialOptions {
|
||||
interface InitialOptions<
|
||||
TCustomPreferences extends object = CustomPreferencesRecord,
|
||||
> {
|
||||
extension?: PreferencesExtension<TCustomPreferences>;
|
||||
namespace: string;
|
||||
overrides?: DeepPartial<Preferences>;
|
||||
}
|
||||
export type {
|
||||
AnyCustomPreferencesField,
|
||||
AppPreferences,
|
||||
BaseCustomPreferencesField,
|
||||
BreadcrumbPreferences,
|
||||
CustomPreferencesField,
|
||||
CustomPreferencesInputField,
|
||||
CustomPreferencesNumberField,
|
||||
CustomPreferencesOption,
|
||||
CustomPreferencesRecord,
|
||||
CustomPreferencesSelectField,
|
||||
CustomPreferencesSwitchField,
|
||||
CustomPreferencesValue,
|
||||
FooterPreferences,
|
||||
HeaderPreferences,
|
||||
InitialOptions,
|
||||
LogoPreferences,
|
||||
NavigationPreferences,
|
||||
Preferences,
|
||||
PreferencesExtension,
|
||||
PreferencesKeys,
|
||||
ShortcutKeyPreferences,
|
||||
SidebarPreferences,
|
||||
|
||||
@@ -66,6 +66,19 @@ function updateCSSVariables(preferences: Preferences) {
|
||||
if (Reflect.has(theme, 'radius')) {
|
||||
document.documentElement.style.setProperty('--radius', `${radius}rem`);
|
||||
}
|
||||
|
||||
// 更新字体大小
|
||||
if (Reflect.has(theme, 'fontSize')) {
|
||||
const fontSize = theme.fontSize;
|
||||
document.documentElement.style.setProperty(
|
||||
'--font-size-base',
|
||||
`${fontSize}px`,
|
||||
);
|
||||
document.documentElement.style.setProperty(
|
||||
'--menu-font-size',
|
||||
`calc(${fontSize}px * 0.875)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,13 @@ import { isDarkTheme } from './update-css-variables';
|
||||
|
||||
function usePreferences() {
|
||||
const preferences = preferencesManager.getPreferences();
|
||||
const customPreferences = preferencesManager.getCustomPreferences();
|
||||
const initialPreferences = preferencesManager.getInitialPreferences();
|
||||
const initialCustomPreferences =
|
||||
preferencesManager.getInitialCustomPreferences();
|
||||
const preferencesExtension = computed(() =>
|
||||
preferencesManager.getPreferencesExtension(),
|
||||
);
|
||||
/**
|
||||
* @zh_CN 计算偏好设置的变化
|
||||
*/
|
||||
@@ -15,6 +21,10 @@ function usePreferences() {
|
||||
return diff(initialPreferences, preferences);
|
||||
});
|
||||
|
||||
const diffCustomPreference = computed(() => {
|
||||
return diff(initialCustomPreferences, customPreferences);
|
||||
});
|
||||
|
||||
const appPreferences = computed(() => preferences.app);
|
||||
|
||||
const shortcutKeysPreferences = computed(() => preferences.shortcutKeys);
|
||||
@@ -136,7 +146,7 @@ function usePreferences() {
|
||||
});
|
||||
|
||||
/**
|
||||
* @zh_CN 登录注册页面布局是否为左侧
|
||||
* @zh_CN 登录注册页面布局是否为右侧
|
||||
*/
|
||||
const authPanelRight = computed(() => {
|
||||
return appPreferences.value.authPageLayout === 'panel-right';
|
||||
@@ -185,12 +195,12 @@ function usePreferences() {
|
||||
*/
|
||||
const preferencesButtonPosition = computed(() => {
|
||||
const { enablePreferences, preferencesButtonPosition } = preferences.app;
|
||||
|
||||
// 如果没有启用偏好设置按钮
|
||||
if (!enablePreferences) {
|
||||
return {
|
||||
fixed: false,
|
||||
header: false,
|
||||
userDropdown: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -201,12 +211,15 @@ function usePreferences() {
|
||||
const contentIsMaximize = headerHidden && sidebarHidden;
|
||||
|
||||
const isHeaderPosition = preferencesButtonPosition === 'header';
|
||||
const isUserDropdownPosition =
|
||||
preferencesButtonPosition === 'user-dropdown';
|
||||
|
||||
// 如果设置了固定位置
|
||||
if (preferencesButtonPosition !== 'auto') {
|
||||
return {
|
||||
fixed: preferencesButtonPosition === 'fixed',
|
||||
header: isHeaderPosition,
|
||||
userDropdown: isUserDropdownPosition,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -220,6 +233,7 @@ function usePreferences() {
|
||||
return {
|
||||
fixed,
|
||||
header: !fixed,
|
||||
userDropdown: !fixed && isUserDropdownPosition,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -228,7 +242,9 @@ function usePreferences() {
|
||||
authPanelLeft,
|
||||
authPanelRight,
|
||||
contentIsMaximize,
|
||||
customPreferences,
|
||||
diffPreference,
|
||||
diffCustomPreference,
|
||||
globalLockScreenShortcutKey,
|
||||
globalLogoutShortcutKey,
|
||||
globalSearchShortcutKey,
|
||||
@@ -245,6 +261,7 @@ function usePreferences() {
|
||||
keepAlive,
|
||||
layout,
|
||||
locale,
|
||||
preferencesExtension,
|
||||
preferencesButtonPosition,
|
||||
sidebarCollapsed,
|
||||
theme,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
dts: true,
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
}),
|
||||
});
|
||||
@@ -44,6 +44,7 @@ describe('formApi', () => {
|
||||
await formApi.mount(formActions);
|
||||
expect(formApi.isMounted).toBe(true);
|
||||
expect(formApi.form).toEqual(formActions);
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get values from form', async () => {
|
||||
@@ -52,11 +53,54 @@ describe('formApi', () => {
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions);
|
||||
await formApi.mount(formActions, new Map());
|
||||
const values = await formApi.getValues();
|
||||
expect(values).toEqual({ name: 'test' });
|
||||
});
|
||||
|
||||
it('should format schema values when getting values', async () => {
|
||||
formApi.setState({
|
||||
schema: [
|
||||
{
|
||||
component: 'range-picker',
|
||||
fieldName: 'filters.range',
|
||||
valueFormat: (value, setValue) => {
|
||||
setValue('filters.startTime', value?.[0]);
|
||||
setValue('filters.endTime', value?.[1]);
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
values: {
|
||||
filters: {
|
||||
range: [1_710_000_000_000, 1_720_000_000_000],
|
||||
},
|
||||
},
|
||||
};
|
||||
const originalValuesSnapshot = structuredClone(formActions.values);
|
||||
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
expect(formApi.getLatestSubmissionValues()).toEqual({
|
||||
filters: {
|
||||
endTime: 1_720_000_000_000,
|
||||
startTime: 1_710_000_000_000,
|
||||
},
|
||||
});
|
||||
|
||||
const values = await formApi.getValues();
|
||||
expect(values).toEqual({
|
||||
filters: {
|
||||
endTime: 1_720_000_000_000,
|
||||
startTime: 1_710_000_000_000,
|
||||
},
|
||||
});
|
||||
expect(formActions.values).toEqual(originalValuesSnapshot);
|
||||
});
|
||||
|
||||
it('should set field value', async () => {
|
||||
const setFieldValueMock = vi.fn();
|
||||
const formActions: any = {
|
||||
@@ -65,7 +109,7 @@ describe('formApi', () => {
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions);
|
||||
await formApi.mount(formActions, new Map());
|
||||
await formApi.setFieldValue('name', 'new value');
|
||||
expect(setFieldValueMock).toHaveBeenCalledWith(
|
||||
'name',
|
||||
@@ -82,7 +126,7 @@ describe('formApi', () => {
|
||||
values: { name: 'test' },
|
||||
};
|
||||
|
||||
await formApi.mount(formActions);
|
||||
await formApi.mount(formActions, new Map());
|
||||
await formApi.resetForm();
|
||||
expect(resetFormMock).toHaveBeenCalled();
|
||||
});
|
||||
@@ -100,7 +144,7 @@ describe('formApi', () => {
|
||||
};
|
||||
|
||||
formApi.setState(state);
|
||||
await formApi.mount(formActions);
|
||||
await formApi.mount(formActions, new Map());
|
||||
|
||||
const result = await formApi.submitForm();
|
||||
expect(formActions.submitForm).toHaveBeenCalled();
|
||||
@@ -113,6 +157,39 @@ describe('formApi', () => {
|
||||
expect(formApi.isMounted).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear component refs on unmount before mounting again', async () => {
|
||||
const formActions: any = {
|
||||
meta: {},
|
||||
resetForm: vi.fn(),
|
||||
values: { name: 'test' },
|
||||
};
|
||||
const staleMap = new Map<string, unknown>([
|
||||
[
|
||||
'name',
|
||||
{
|
||||
$: {
|
||||
type: { name: 'MockComponent' },
|
||||
},
|
||||
$el: {},
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
await formApi.mount(formActions, staleMap);
|
||||
expect(formApi.getFieldComponentRef('name')).toEqual({
|
||||
$: {
|
||||
type: { name: 'MockComponent' },
|
||||
},
|
||||
$el: {},
|
||||
});
|
||||
|
||||
formApi.unmount();
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
|
||||
await formApi.mount(formActions);
|
||||
expect(formApi.getFieldComponentRef('name')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should validate form', async () => {
|
||||
const validateMock = vi.fn().mockResolvedValue(true);
|
||||
const formActions: any = {
|
||||
@@ -120,7 +197,7 @@ describe('formApi', () => {
|
||||
validate: validateMock,
|
||||
};
|
||||
|
||||
await formApi.mount(formActions);
|
||||
await formApi.mount(formActions, new Map());
|
||||
const isValid = await formApi.validate();
|
||||
expect(validateMock).toHaveBeenCalled();
|
||||
expect(isValid).toBe(true);
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: [
|
||||
{
|
||||
builder: 'mkdist',
|
||||
input: './src',
|
||||
loaders: ['vue'],
|
||||
pattern: ['**/*.vue'],
|
||||
},
|
||||
{
|
||||
builder: 'mkdist',
|
||||
format: 'esm',
|
||||
input: './src',
|
||||
loaders: ['js'],
|
||||
pattern: ['**/*.ts'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/form-ui",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild",
|
||||
"build": "pnpm exec tsdown",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
@@ -22,16 +22,19 @@
|
||||
],
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
@@ -48,5 +51,8 @@
|
||||
"vue": "catalog:",
|
||||
"zod": "catalog:",
|
||||
"zod-defaults": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"unplugin-vue": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from '@vben/tailwind-config/postcss';
|
||||
@@ -30,10 +30,6 @@ const submitButtonOptions = computed(() => {
|
||||
};
|
||||
});
|
||||
|
||||
// const isQueryForm = computed(() => {
|
||||
// return !!unref(rootProps).showCollapseButton;
|
||||
// });
|
||||
|
||||
async function handleSubmit(e: Event) {
|
||||
e?.preventDefault();
|
||||
e?.stopPropagation();
|
||||
@@ -47,7 +43,7 @@ async function handleSubmit(e: Event) {
|
||||
return;
|
||||
}
|
||||
|
||||
const values = toRaw(await props.formApi.getValues());
|
||||
const values = toRaw(await props.formApi.getValues()) ?? {};
|
||||
await props.handleSubmit?.(values);
|
||||
}
|
||||
|
||||
@@ -56,7 +52,7 @@ async function handleReset(e: Event) {
|
||||
e?.stopPropagation();
|
||||
const props = unref(rootProps);
|
||||
|
||||
const values = toRaw(await props.formApi?.getValues());
|
||||
const values = toRaw(await props.formApi?.getValues()) ?? {};
|
||||
|
||||
if (isFunction(props.handleReset)) {
|
||||
await props.handleReset?.(values);
|
||||
@@ -82,11 +78,11 @@ const actionWrapperClass = computed(() => {
|
||||
|
||||
const cls = [
|
||||
'flex',
|
||||
'w-full',
|
||||
'items-center',
|
||||
'gap-3',
|
||||
props.compact ? 'pb-2' : 'pb-4',
|
||||
props.layout === 'vertical' ? 'self-end' : 'self-center',
|
||||
props.layout === 'inline' ? '' : 'w-full',
|
||||
props.actionWrapperClass,
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
export function resolveFieldNamePath(fieldName: string) {
|
||||
if (fieldName.startsWith('[') && fieldName.endsWith(']')) {
|
||||
const rawKey = fieldName.slice(1, -1);
|
||||
return {
|
||||
pathSegments: [rawKey],
|
||||
rawKey,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
pathSegments: fieldName.match(/[^.[\]]+/g) ?? [],
|
||||
rawKey: undefined,
|
||||
};
|
||||
}
|
||||
@@ -16,16 +16,21 @@ import { isRef, toRaw } from 'vue';
|
||||
import { Store } from '@vben-core/shared/store';
|
||||
import {
|
||||
bindMethods,
|
||||
cloneDeep,
|
||||
createMerge,
|
||||
formatDate,
|
||||
get,
|
||||
isDate,
|
||||
isDayjsObject,
|
||||
isFunction,
|
||||
isObject,
|
||||
mergeWithArrayOverride,
|
||||
set,
|
||||
StateHandler,
|
||||
} from '@vben-core/shared/utils';
|
||||
|
||||
import { resolveFieldNamePath } from './field-name';
|
||||
|
||||
function getDefaultState(): VbenFormProps {
|
||||
return {
|
||||
actionWrapperClass: '',
|
||||
@@ -36,6 +41,7 @@ function getDefaultState(): VbenFormProps {
|
||||
handleReset: undefined,
|
||||
handleSubmit: undefined,
|
||||
handleValuesChange: undefined,
|
||||
handleCollapsedChange: undefined,
|
||||
layout: 'horizontal',
|
||||
resetButtonOptions: {},
|
||||
schema: [],
|
||||
@@ -74,19 +80,16 @@ export class FormApi {
|
||||
|
||||
const defaultState = getDefaultState();
|
||||
|
||||
this.store = new Store<VbenFormProps>(
|
||||
{
|
||||
...defaultState,
|
||||
...storeState,
|
||||
},
|
||||
{
|
||||
onUpdate: () => {
|
||||
this.prevState = this.state;
|
||||
this.state = this.store.state;
|
||||
this.updateState();
|
||||
},
|
||||
},
|
||||
);
|
||||
this.store = new Store<VbenFormProps>({
|
||||
...defaultState,
|
||||
...storeState,
|
||||
});
|
||||
|
||||
this.store.subscribe((state) => {
|
||||
this.prevState = this.state;
|
||||
this.state = state;
|
||||
this.updateState();
|
||||
});
|
||||
|
||||
this.state = this.store.state;
|
||||
this.stateHandler = new StateHandler();
|
||||
@@ -160,7 +163,10 @@ export class FormApi {
|
||||
|
||||
async getValues<T = Recordable<any>>() {
|
||||
const form = await this.getForm();
|
||||
return (form.values ? this.handleRangeTimeValue(form.values) : {}) as T;
|
||||
const values = form.values
|
||||
? this.handleRangeTimeValue(cloneDeep(toRaw(form.values)))
|
||||
: {};
|
||||
return this.handleValueFormat(values) as T;
|
||||
}
|
||||
|
||||
async isFieldValid(fieldName: string) {
|
||||
@@ -208,14 +214,18 @@ export class FormApi {
|
||||
return proxy;
|
||||
}
|
||||
|
||||
mount(formActions: FormActions, componentRefMap: Map<string, unknown>) {
|
||||
mount(formActions: FormActions, componentRefMap?: Map<string, unknown>) {
|
||||
if (!this.isMounted) {
|
||||
Object.assign(this.form, formActions);
|
||||
this.stateHandler.setConditionTrue();
|
||||
const initialValues = this.form.values
|
||||
? this.handleRangeTimeValue(cloneDeep(toRaw(this.form.values)))
|
||||
: {};
|
||||
this.setLatestSubmissionValues({
|
||||
...toRaw(this.handleRangeTimeValue(this.form.values)),
|
||||
...this.handleValueFormat(initialValues),
|
||||
});
|
||||
this.componentRefMap = componentRefMap;
|
||||
this.componentRefMap =
|
||||
componentRefMap ?? this.componentRefMap ?? new Map();
|
||||
this.isMounted = true;
|
||||
}
|
||||
}
|
||||
@@ -342,13 +352,12 @@ export class FormApi {
|
||||
isObject(obj[key]) &&
|
||||
!isDayjsObject(obj[key]) &&
|
||||
!isDate(obj[key])
|
||||
? fieldMergeFn(obj[key], value)
|
||||
? fieldMergeFn(value, obj[key])
|
||||
: value;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const filteredFields = fieldMergeFn(fields, form.values);
|
||||
this.handleStringToArrayFields(filteredFields);
|
||||
form.setValues(filteredFields, shouldValidate);
|
||||
}
|
||||
|
||||
@@ -358,7 +367,6 @@ export class FormApi {
|
||||
const form = await this.getForm();
|
||||
await form.submitForm();
|
||||
const rawValues = toRaw(await this.getValues());
|
||||
this.handleArrayToStringFields(rawValues);
|
||||
await this.state?.handleSubmit?.(rawValues);
|
||||
|
||||
return rawValues;
|
||||
@@ -367,6 +375,7 @@ export class FormApi {
|
||||
unmount() {
|
||||
this.form?.resetForm?.();
|
||||
// this.state = null;
|
||||
this.componentRefMap = new Map();
|
||||
this.latestSubmissionValues = null;
|
||||
this.isMounted = false;
|
||||
this.stateHandler.reset();
|
||||
@@ -447,6 +456,42 @@ export class FormApi {
|
||||
return validateResult;
|
||||
}
|
||||
|
||||
private deleteValueByFieldName(
|
||||
values: Record<string, any>,
|
||||
fieldName: string,
|
||||
) {
|
||||
const { pathSegments, rawKey } = resolveFieldNamePath(fieldName);
|
||||
if (rawKey) {
|
||||
Reflect.deleteProperty(values, rawKey);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!pathSegments || pathSegments.length === 0) {
|
||||
Reflect.deleteProperty(values, fieldName);
|
||||
return;
|
||||
}
|
||||
|
||||
let target: Record<string, any> | undefined = values;
|
||||
|
||||
for (const segment of pathSegments.slice(0, -1)) {
|
||||
if (!target || !isObject(target)) {
|
||||
return;
|
||||
}
|
||||
target = target[segment];
|
||||
}
|
||||
|
||||
if (!target || !isObject(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastPathSegment = pathSegments.at(-1);
|
||||
if (!lastPathSegment) {
|
||||
return;
|
||||
}
|
||||
|
||||
Reflect.deleteProperty(target, lastPathSegment);
|
||||
}
|
||||
|
||||
private async getForm() {
|
||||
if (!this.isMounted) {
|
||||
// 等待form挂载
|
||||
@@ -458,16 +503,31 @@ export class FormApi {
|
||||
return this.form;
|
||||
}
|
||||
|
||||
private handleArrayToStringFields = (originValues: Record<string, any>) => {
|
||||
private handleMultiFields = (originValues: Record<string, any>) => {
|
||||
const arrayToStringFields = this.state?.arrayToStringFields;
|
||||
if (!arrayToStringFields || !Array.isArray(arrayToStringFields)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const processFields = (fields: string[], separator: string = ',') => {
|
||||
this.processFields(fields, separator, originValues, (value, sep) =>
|
||||
Array.isArray(value) ? value.join(sep) : value,
|
||||
);
|
||||
this.processFields(fields, separator, originValues, (value, sep) => {
|
||||
if (Array.isArray(value)) {
|
||||
return value.join(sep);
|
||||
} else if (typeof value === 'string') {
|
||||
// 处理空字符串的情况
|
||||
if (value === '') {
|
||||
return [];
|
||||
}
|
||||
// 处理复杂分隔符的情况
|
||||
const escapedSeparator = sep.replaceAll(
|
||||
/[.*+?^${}()|[\]\\]/g,
|
||||
String.raw`\$&`,
|
||||
);
|
||||
return value.split(new RegExp(escapedSeparator));
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 处理简单数组格式 ['field1', 'field2', ';'] 或 ['field1', 'field2']
|
||||
@@ -503,8 +563,7 @@ export class FormApi {
|
||||
const values = { ...originValues };
|
||||
const fieldMappingTime = this.state?.fieldMappingTime;
|
||||
|
||||
this.handleStringToArrayFields(values);
|
||||
|
||||
this.handleMultiFields(values);
|
||||
if (!fieldMappingTime || !Array.isArray(fieldMappingTime)) {
|
||||
return values;
|
||||
}
|
||||
@@ -550,63 +609,34 @@ export class FormApi {
|
||||
return values;
|
||||
};
|
||||
|
||||
private handleStringToArrayFields = (originValues: Record<string, any>) => {
|
||||
const arrayToStringFields = this.state?.arrayToStringFields;
|
||||
if (!arrayToStringFields || !Array.isArray(arrayToStringFields)) {
|
||||
return;
|
||||
}
|
||||
private handleValueFormat = (originValues: Record<string, any>) => {
|
||||
const values = { ...originValues };
|
||||
const currentSchema = this.state?.schema ?? [];
|
||||
|
||||
const processFields = (fields: string[], separator: string = ',') => {
|
||||
this.processFields(fields, separator, originValues, (value, sep) => {
|
||||
if (typeof value !== 'string') {
|
||||
return value;
|
||||
}
|
||||
// 处理空字符串的情况
|
||||
if (value === '') {
|
||||
return [];
|
||||
}
|
||||
// 处理复杂分隔符的情况
|
||||
const escapedSeparator = sep.replaceAll(
|
||||
/[.*+?^${}()|[\]\\]/g,
|
||||
String.raw`\$&`,
|
||||
);
|
||||
return value.split(new RegExp(escapedSeparator));
|
||||
});
|
||||
};
|
||||
currentSchema.forEach((schema) => {
|
||||
if (!schema.valueFormat) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理简单数组格式 ['field1', 'field2', ';'] 或 ['field1', 'field2']
|
||||
if (arrayToStringFields.every((item) => typeof item === 'string')) {
|
||||
const lastItem =
|
||||
arrayToStringFields[arrayToStringFields.length - 1] || '';
|
||||
const fields =
|
||||
lastItem.length === 1
|
||||
? arrayToStringFields.slice(0, -1)
|
||||
: arrayToStringFields;
|
||||
const separator = lastItem.length === 1 ? lastItem : ',';
|
||||
processFields(fields, separator);
|
||||
return;
|
||||
}
|
||||
const fieldName = schema.fieldName;
|
||||
const value = this.resolveValueByFieldName(values, fieldName);
|
||||
|
||||
// 处理嵌套数组格式 [['field1'], ';']
|
||||
arrayToStringFields.forEach((fieldConfig) => {
|
||||
if (Array.isArray(fieldConfig)) {
|
||||
const [fields, separator = ','] = fieldConfig;
|
||||
if (Array.isArray(fields)) {
|
||||
processFields(fields, separator);
|
||||
} else if (typeof originValues[fields] === 'string') {
|
||||
const value = originValues[fields];
|
||||
if (value === '') {
|
||||
originValues[fields] = [];
|
||||
} else {
|
||||
const escapedSeparator = separator.replaceAll(
|
||||
/[.*+?^${}()|[\]\\]/g,
|
||||
String.raw`\$&`,
|
||||
);
|
||||
originValues[fields] = value.split(new RegExp(escapedSeparator));
|
||||
}
|
||||
}
|
||||
this.deleteValueByFieldName(values, fieldName);
|
||||
|
||||
const formattedValue = schema.valueFormat(
|
||||
value,
|
||||
(key, nextValue) => {
|
||||
this.setValueByFieldName(values, key, nextValue);
|
||||
},
|
||||
values,
|
||||
);
|
||||
|
||||
if (formattedValue !== undefined) {
|
||||
this.setValueByFieldName(values, fieldName, formattedValue);
|
||||
}
|
||||
});
|
||||
|
||||
return values;
|
||||
};
|
||||
|
||||
private processFields = (
|
||||
@@ -624,6 +654,32 @@ export class FormApi {
|
||||
});
|
||||
};
|
||||
|
||||
private resolveValueByFieldName(
|
||||
values: Record<string, any>,
|
||||
fieldName: string,
|
||||
) {
|
||||
const { rawKey } = resolveFieldNamePath(fieldName);
|
||||
if (rawKey) {
|
||||
return values[rawKey];
|
||||
}
|
||||
|
||||
return get(values, fieldName);
|
||||
}
|
||||
|
||||
private setValueByFieldName(
|
||||
values: Record<string, any>,
|
||||
fieldName: string,
|
||||
value: any,
|
||||
) {
|
||||
const { rawKey } = resolveFieldNamePath(fieldName);
|
||||
if (rawKey) {
|
||||
values[rawKey] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
set(values, fieldName, value);
|
||||
}
|
||||
|
||||
private updateState() {
|
||||
const currentSchema = this.state?.schema ?? [];
|
||||
const prevSchema = this.prevState?.schema ?? [];
|
||||
|
||||
@@ -1,31 +1,68 @@
|
||||
import type {
|
||||
ExtendedFormApi,
|
||||
FormItemDependencies,
|
||||
FormSchemaRuleType,
|
||||
MaybeComponentProps,
|
||||
} from '../types';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, isRef, ref, watch } from 'vue';
|
||||
|
||||
import { isBoolean, isFunction } from '@vben-core/shared/utils';
|
||||
import { get, isBoolean, isFunction } from '@vben-core/shared/utils';
|
||||
|
||||
import { useFormValues } from 'vee-validate';
|
||||
|
||||
import { resolveFieldNamePath } from '../field-name';
|
||||
import { injectFormProps } from '../use-form-context';
|
||||
import { injectRenderFormProps } from './context';
|
||||
|
||||
/**
|
||||
* 解析Nested Objects对应的字段值
|
||||
* @param values 表单值
|
||||
* @param fieldName 字段名
|
||||
*/
|
||||
function resolveValueByFieldName(
|
||||
values: Record<string, any>,
|
||||
fieldName: string,
|
||||
) {
|
||||
// vee-validate:[] 表示禁用嵌套
|
||||
const { rawKey } = resolveFieldNamePath(fieldName);
|
||||
if (rawKey) {
|
||||
return values[rawKey];
|
||||
}
|
||||
|
||||
return get(values, fieldName);
|
||||
}
|
||||
export default function useDependencies(
|
||||
getDependencies: () => FormItemDependencies | undefined,
|
||||
) {
|
||||
const values = useFormValues();
|
||||
|
||||
const [extendApi] = injectFormProps();
|
||||
const formRenderProps = injectRenderFormProps();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const formApi = formRenderProps.form!;
|
||||
const formApi = formRenderProps.form;
|
||||
|
||||
if (!formApi) {
|
||||
throw new Error('Form api is required in useDependencies');
|
||||
}
|
||||
|
||||
if (!values) {
|
||||
throw new Error('useDependencies should be used within <VbenForm>');
|
||||
}
|
||||
|
||||
// 在 dependencies 里提供访问extendApi的能力
|
||||
const getController = (): ExtendedFormApi => {
|
||||
const controller = isRef(extendApi)
|
||||
? extendApi.value.formApi
|
||||
: extendApi.formApi;
|
||||
|
||||
if (!controller) {
|
||||
throw new Error('formApi is required in useDependencies');
|
||||
}
|
||||
|
||||
return controller;
|
||||
};
|
||||
|
||||
const isIf = ref(true);
|
||||
const isDisabled = ref(false);
|
||||
const isShow = ref(true);
|
||||
@@ -37,7 +74,7 @@ export default function useDependencies(
|
||||
// 该字段可能会被多个字段触发
|
||||
const triggerFields = getDependencies()?.triggerFields ?? [];
|
||||
return triggerFields.map((dep) => {
|
||||
return values.value[dep];
|
||||
return resolveValueByFieldName(values.value, dep);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -71,7 +108,7 @@ export default function useDependencies(
|
||||
const formValues = values.value;
|
||||
|
||||
if (isFunction(whenIf)) {
|
||||
isIf.value = !!(await whenIf(formValues, formApi));
|
||||
isIf.value = !!(await whenIf(formValues, formApi, getController()));
|
||||
// 不渲染
|
||||
if (!isIf.value) return;
|
||||
} else if (isBoolean(whenIf)) {
|
||||
@@ -81,33 +118,43 @@ export default function useDependencies(
|
||||
|
||||
// 2. 判断show,如果show为false,则隐藏
|
||||
if (isFunction(show)) {
|
||||
isShow.value = !!(await show(formValues, formApi));
|
||||
if (!isShow.value) return;
|
||||
isShow.value = !!(await show(formValues, formApi, getController()));
|
||||
} else if (isBoolean(show)) {
|
||||
isShow.value = show;
|
||||
if (!isShow.value) return;
|
||||
}
|
||||
|
||||
if (isFunction(componentProps)) {
|
||||
dynamicComponentProps.value = await componentProps(formValues, formApi);
|
||||
dynamicComponentProps.value = await componentProps(
|
||||
formValues,
|
||||
formApi,
|
||||
getController(),
|
||||
);
|
||||
}
|
||||
|
||||
if (isFunction(rules)) {
|
||||
dynamicRules.value = await rules(formValues, formApi);
|
||||
dynamicRules.value = await rules(formValues, formApi, getController());
|
||||
}
|
||||
|
||||
if (isFunction(disabled)) {
|
||||
isDisabled.value = !!(await disabled(formValues, formApi));
|
||||
isDisabled.value = !!(await disabled(
|
||||
formValues,
|
||||
formApi,
|
||||
getController(),
|
||||
));
|
||||
} else if (isBoolean(disabled)) {
|
||||
isDisabled.value = disabled;
|
||||
}
|
||||
|
||||
if (isFunction(required)) {
|
||||
isRequired.value = !!(await required(formValues, formApi));
|
||||
isRequired.value = !!(await required(
|
||||
formValues,
|
||||
formApi,
|
||||
getController(),
|
||||
));
|
||||
}
|
||||
|
||||
if (isFunction(trigger)) {
|
||||
await trigger(formValues, formApi);
|
||||
await trigger(formValues, formApi, getController());
|
||||
}
|
||||
},
|
||||
{ deep: true, immediate: true },
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import type { ZodType } from 'zod';
|
||||
|
||||
import type { FormSchema, MaybeComponentProps } from '../types';
|
||||
import type {
|
||||
FormActions,
|
||||
FormFieldProps,
|
||||
MaybeComponentProps,
|
||||
} from '../types';
|
||||
|
||||
import { computed, nextTick, onUnmounted, useTemplateRef, watch } from 'vue';
|
||||
|
||||
import { CircleAlert } from '@vben-core/icons';
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onUnmounted,
|
||||
ref,
|
||||
useTemplateRef,
|
||||
watch,
|
||||
} from 'vue';
|
||||
|
||||
import { ChevronsDown, CircleAlert } from '@vben-core/icons';
|
||||
import {
|
||||
Button,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormMessage,
|
||||
VbenCollapsible,
|
||||
VbenRenderContent,
|
||||
VbenTooltip,
|
||||
} from '@vben-core/shadcn-ui';
|
||||
@@ -26,7 +39,7 @@ import useDependencies from './dependencies';
|
||||
import FormLabel from './form-label.vue';
|
||||
import { isEventObjectLike } from './helper';
|
||||
|
||||
interface Props extends FormSchema {}
|
||||
interface Props extends FormFieldProps {}
|
||||
|
||||
const {
|
||||
colon,
|
||||
@@ -41,12 +54,16 @@ const {
|
||||
emptyStateValue,
|
||||
fieldName,
|
||||
formFieldProps,
|
||||
hide,
|
||||
label,
|
||||
labelClass,
|
||||
labelWidth,
|
||||
modelPropName,
|
||||
renderComponentContent,
|
||||
rules,
|
||||
help,
|
||||
collapsible,
|
||||
defaultCollapsed = false,
|
||||
} = defineProps<
|
||||
Props & {
|
||||
commonComponentProps: MaybeComponentProps;
|
||||
@@ -59,8 +76,17 @@ const values = useFormValues();
|
||||
const errors = useFieldError(fieldName);
|
||||
const fieldComponentRef = useTemplateRef<HTMLInputElement>('fieldComponentRef');
|
||||
const formApi = formRenderProps.form;
|
||||
const compact = formRenderProps.compact;
|
||||
const compact = computed(() => formRenderProps.compact);
|
||||
const isInValid = computed(() => errors.value?.length > 0);
|
||||
const collapseOpen = ref(!defaultCollapsed);
|
||||
|
||||
function getFormApi(): FormActions {
|
||||
if (!formApi) {
|
||||
throw new Error('Form api is required in <FormField />');
|
||||
}
|
||||
|
||||
return formApi;
|
||||
}
|
||||
|
||||
const FieldComponent = computed(() => {
|
||||
const finalComponent = isString(component)
|
||||
@@ -95,7 +121,7 @@ const currentRules = computed(() => {
|
||||
});
|
||||
|
||||
const visible = computed(() => {
|
||||
return isIf.value && isShow.value;
|
||||
return !hide && isIf.value && isShow.value;
|
||||
});
|
||||
|
||||
const shouldRequired = computed(() => {
|
||||
@@ -155,7 +181,7 @@ const fieldRules = computed(() => {
|
||||
|
||||
const computedProps = computed(() => {
|
||||
const finalComponentProps = isFunction(componentProps)
|
||||
? componentProps(values.value, formApi!)
|
||||
? componentProps(values.value, getFormApi())
|
||||
: componentProps;
|
||||
|
||||
return {
|
||||
@@ -165,6 +191,18 @@ const computedProps = computed(() => {
|
||||
};
|
||||
});
|
||||
|
||||
// 自定义帮助信息
|
||||
const computedHelp = computed(() => {
|
||||
const helpContent = help;
|
||||
if (!helpContent) {
|
||||
return undefined;
|
||||
}
|
||||
return () =>
|
||||
isFunction(helpContent)
|
||||
? helpContent(values.value, getFormApi())
|
||||
: helpContent;
|
||||
});
|
||||
|
||||
watch(
|
||||
() => computedProps.value?.autofocus,
|
||||
(value) => {
|
||||
@@ -185,7 +223,7 @@ const customContentRender = computed(() => {
|
||||
if (!isFunction(renderComponentContent)) {
|
||||
return {};
|
||||
}
|
||||
return renderComponentContent(values.value, formApi!);
|
||||
return renderComponentContent(values.value, getFormApi());
|
||||
});
|
||||
|
||||
const renderContentKey = computed(() => {
|
||||
@@ -270,6 +308,15 @@ function autofocus() {
|
||||
fieldComponentRef.value?.focus?.();
|
||||
}
|
||||
}
|
||||
|
||||
const shouldCollapsible = computed(() => {
|
||||
return collapsible; /* && isVertical.value; */
|
||||
});
|
||||
|
||||
function toggleCollapsed() {
|
||||
collapseOpen.value = !collapseOpen.value;
|
||||
}
|
||||
|
||||
const componentRefMap = injectComponentRefMap();
|
||||
watch(fieldComponentRef, (componentRef) => {
|
||||
componentRefMap?.set(fieldName, componentRef);
|
||||
@@ -283,7 +330,7 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<FormField
|
||||
v-if="isIf"
|
||||
v-if="!hide && isIf"
|
||||
v-bind="fieldProps"
|
||||
v-slot="slotProps"
|
||||
:name="fieldName"
|
||||
@@ -307,13 +354,14 @@ onUnmounted(() => {
|
||||
cn(
|
||||
'flex leading-6',
|
||||
{
|
||||
'mr-2 flex-shrink-0 justify-end': !isVertical,
|
||||
'mr-2 shrink-0 justify-end': !isVertical,
|
||||
'mb-1 flex-row': isVertical,
|
||||
'self-start': shouldCollapsible && !isVertical,
|
||||
},
|
||||
labelClass,
|
||||
)
|
||||
"
|
||||
:help="help"
|
||||
:help="computedHelp"
|
||||
:colon="colon"
|
||||
:label="label"
|
||||
:required="shouldRequired && !hideRequiredMark"
|
||||
@@ -322,68 +370,90 @@ onUnmounted(() => {
|
||||
<template v-if="label">
|
||||
<VbenRenderContent :content="label" />
|
||||
</template>
|
||||
</FormLabel>
|
||||
<div class="flex-auto overflow-hidden p-[1px]">
|
||||
<div :class="cn('relative flex w-full items-center', wrapperClass)">
|
||||
<FormControl :class="cn(controlClass)">
|
||||
<slot
|
||||
v-bind="{
|
||||
...slotProps,
|
||||
...createComponentProps(slotProps),
|
||||
disabled: shouldDisabled,
|
||||
isInValid,
|
||||
<template #extra>
|
||||
<Button
|
||||
class="ml-0.5"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
@click.prevent="toggleCollapsed"
|
||||
v-if="shouldCollapsible"
|
||||
>
|
||||
<ChevronsDown
|
||||
:size="16"
|
||||
class="transition-transform"
|
||||
:class="{
|
||||
'rotate-180': !collapseOpen,
|
||||
}"
|
||||
>
|
||||
<component
|
||||
:is="FieldComponent"
|
||||
ref="fieldComponentRef"
|
||||
:class="{
|
||||
'border-destructive focus:border-destructive hover:border-destructive/80 focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]':
|
||||
/>
|
||||
</Button>
|
||||
</template>
|
||||
</FormLabel>
|
||||
<div class="flex-auto overflow-hidden p-px">
|
||||
<VbenCollapsible :show-trigger="false" v-model:open="collapseOpen">
|
||||
<template #collapsibleContent>
|
||||
<div :class="cn('relative flex w-full items-center', wrapperClass)">
|
||||
<FormControl :class="cn(controlClass)">
|
||||
<slot
|
||||
v-bind="{
|
||||
...slotProps,
|
||||
...createComponentProps(slotProps),
|
||||
disabled: shouldDisabled,
|
||||
isInValid,
|
||||
}"
|
||||
v-bind="createComponentProps(slotProps)"
|
||||
:disabled="shouldDisabled"
|
||||
>
|
||||
<template
|
||||
v-for="name in renderContentKey"
|
||||
:key="name"
|
||||
#[name]="renderSlotProps"
|
||||
}"
|
||||
>
|
||||
<VbenRenderContent
|
||||
:content="customContentRender[name]"
|
||||
v-bind="{ ...renderSlotProps, formContext: slotProps }"
|
||||
/>
|
||||
</template>
|
||||
<!-- <slot></slot> -->
|
||||
</component>
|
||||
<VbenTooltip
|
||||
v-if="compact && isInValid"
|
||||
:delay-duration="300"
|
||||
side="left"
|
||||
>
|
||||
<template #trigger>
|
||||
<slot name="trigger">
|
||||
<CircleAlert
|
||||
:class="
|
||||
cn(
|
||||
'text-foreground/80 hover:text-foreground inline-flex size-5 cursor-pointer',
|
||||
)
|
||||
"
|
||||
/>
|
||||
</slot>
|
||||
</template>
|
||||
<FormMessage />
|
||||
</VbenTooltip>
|
||||
</slot>
|
||||
</FormControl>
|
||||
<!-- 自定义后缀 -->
|
||||
<div v-if="suffix" class="ml-1">
|
||||
<VbenRenderContent :content="suffix" />
|
||||
</div>
|
||||
<FormDescription v-if="description" class="ml-1">
|
||||
<VbenRenderContent :content="description" />
|
||||
</FormDescription>
|
||||
</div>
|
||||
<component
|
||||
:is="FieldComponent"
|
||||
ref="fieldComponentRef"
|
||||
:class="{
|
||||
'border-destructive hover:border-destructive/80 focus:border-destructive focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]':
|
||||
isInValid,
|
||||
}"
|
||||
v-bind="createComponentProps(slotProps)"
|
||||
:disabled="shouldDisabled"
|
||||
>
|
||||
<template
|
||||
v-for="name in renderContentKey"
|
||||
:key="name"
|
||||
#[name]="renderSlotProps"
|
||||
>
|
||||
<VbenRenderContent
|
||||
:content="customContentRender[name]"
|
||||
v-bind="{ ...renderSlotProps, formContext: slotProps }"
|
||||
/>
|
||||
</template>
|
||||
<!-- <slot></slot> -->
|
||||
</component>
|
||||
<VbenTooltip
|
||||
v-if="compact && isInValid"
|
||||
:delay-duration="300"
|
||||
side="left"
|
||||
>
|
||||
<template #trigger>
|
||||
<slot name="trigger">
|
||||
<CircleAlert
|
||||
:class="
|
||||
cn(
|
||||
'inline-flex size-5 cursor-pointer text-foreground/80 hover:text-foreground',
|
||||
)
|
||||
"
|
||||
/>
|
||||
</slot>
|
||||
</template>
|
||||
<FormMessage />
|
||||
</VbenTooltip>
|
||||
</slot>
|
||||
</FormControl>
|
||||
<!-- 自定义后缀 -->
|
||||
<div v-if="suffix" class="ml-1">
|
||||
<VbenRenderContent :content="suffix" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</VbenCollapsible>
|
||||
|
||||
<FormDescription v-if="description" class="text-xs">
|
||||
<VbenRenderContent :content="description" />
|
||||
</FormDescription>
|
||||
|
||||
<Transition name="slide-up" v-if="!compact">
|
||||
<FormMessage class="absolute" />
|
||||
|
||||
@@ -21,11 +21,12 @@ const props = defineProps<Props>();
|
||||
|
||||
<template>
|
||||
<FormLabel :class="cn('flex items-center', props.class)">
|
||||
<span v-if="required" class="text-destructive mr-[2px]">*</span>
|
||||
<span v-if="required" class="mr-0.5 text-destructive">*</span>
|
||||
<slot></slot>
|
||||
<VbenHelpTooltip v-if="help" trigger-class="size-3.5 ml-1">
|
||||
<VbenRenderContent :content="help" />
|
||||
</VbenHelpTooltip>
|
||||
<span v-if="colon && label" class="ml-[2px]">:</span>
|
||||
<slot name="extra"></slot>
|
||||
<span v-if="colon && label" class="ml-0.5">:</span>
|
||||
</FormLabel>
|
||||
</template>
|
||||
|
||||
@@ -42,17 +42,18 @@ const emits = defineEmits<{
|
||||
}>();
|
||||
|
||||
const wrapperClass = computed(() => {
|
||||
const cls = ['flex flex-col'];
|
||||
if (props.layout === 'vertical') {
|
||||
cls.push(props.compact ? 'gap-x-2' : 'gap-x-4');
|
||||
const cls = ['flex'];
|
||||
if (props.layout === 'inline') {
|
||||
cls.push('flex-wrap gap-x-2');
|
||||
} else {
|
||||
cls.push('gap-2');
|
||||
cls.push(props.compact ? 'gap-x-2' : 'gap-x-4', 'flex-col grid');
|
||||
}
|
||||
return cn(...cls, props.wrapperClass);
|
||||
});
|
||||
|
||||
provideFormRenderProps(props);
|
||||
|
||||
// @ts-expect-error unused
|
||||
const { isCalculated, keepFormItemIndex, wrapperRef } = useExpandable(props);
|
||||
|
||||
const shapes = computed(() => {
|
||||
@@ -156,7 +157,7 @@ const computedSchema = computed(
|
||||
...schema.formFieldProps,
|
||||
},
|
||||
formItemClass: cn(
|
||||
'flex-shrink-0',
|
||||
'shrink-0',
|
||||
{ hidden },
|
||||
formItemClass,
|
||||
resolvedSchemaFormItemClass,
|
||||
@@ -170,7 +171,7 @@ const computedSchema = computed(
|
||||
|
||||
<template>
|
||||
<component :is="formComponent" v-bind="formComponentProps">
|
||||
<div ref="wrapperRef" :class="wrapperClass" class="grid">
|
||||
<div ref="wrapperRef" :class="wrapperClass">
|
||||
<template v-for="cSchema in computedSchema" :key="cSchema.fieldName">
|
||||
<!-- <div v-if="$slots[cSchema.fieldName]" :class="cSchema.formItemClass">
|
||||
<slot :definition="cSchema" :name="cSchema.fieldName"> </slot>
|
||||
|
||||
@@ -3,6 +3,7 @@ export { setupVbenForm } from './config';
|
||||
export type {
|
||||
BaseFormComponentType,
|
||||
ExtendedFormApi,
|
||||
FormLayout,
|
||||
VbenFormProps,
|
||||
FormSchema as VbenFormSchema,
|
||||
} from './types';
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { ClassType, MaybeComputedRef } from '@vben-core/typings';
|
||||
|
||||
import type { FormApi } from './form-api';
|
||||
|
||||
export type FormLayout = 'horizontal' | 'vertical';
|
||||
export type FormLayout = 'horizontal' | 'inline' | 'vertical';
|
||||
|
||||
export type BaseFormComponentType =
|
||||
| 'DefaultButton'
|
||||
@@ -67,6 +67,14 @@ export type FormActions = FormContext<GenericObject>;
|
||||
|
||||
export type CustomRenderType = (() => Component | string) | string;
|
||||
|
||||
// 动态渲染参数
|
||||
export type CustomParamsRenderType =
|
||||
| ((
|
||||
value: Partial<Record<string, any>>,
|
||||
actions: FormActions,
|
||||
) => Component | string)
|
||||
| string;
|
||||
|
||||
export type FormSchemaRuleType =
|
||||
| 'required'
|
||||
| 'selectRequired'
|
||||
@@ -77,16 +85,19 @@ export type FormSchemaRuleType =
|
||||
type FormItemDependenciesCondition<T = boolean | PromiseLike<boolean>> = (
|
||||
value: Partial<Record<string, any>>,
|
||||
actions: FormActions,
|
||||
controller: ExtendedFormApi, // 在 dependencies 里提供访问extendApi的能力
|
||||
) => T;
|
||||
|
||||
type FormItemDependenciesConditionWithRules = (
|
||||
value: Partial<Record<string, any>>,
|
||||
actions: FormActions,
|
||||
controller: ExtendedFormApi, // 在 dependencies 里提供访问extendApi的能力
|
||||
) => FormSchemaRuleType | PromiseLike<FormSchemaRuleType>;
|
||||
|
||||
type FormItemDependenciesConditionWithProps = (
|
||||
value: Partial<Record<string, any>>,
|
||||
actions: FormActions,
|
||||
controller: ExtendedFormApi, // 在 dependencies 里提供访问extendApi的能力
|
||||
) => MaybeComponentProps | PromiseLike<MaybeComponentProps>;
|
||||
|
||||
export interface FormItemDependencies {
|
||||
@@ -137,6 +148,11 @@ type ComponentProps =
|
||||
| MaybeComponentProps;
|
||||
|
||||
export interface FormCommonConfig {
|
||||
/**
|
||||
* 是否可折叠的
|
||||
* @default false
|
||||
*/
|
||||
collapsible?: boolean;
|
||||
/**
|
||||
* 在Label后显示一个冒号
|
||||
*/
|
||||
@@ -149,6 +165,11 @@ export interface FormCommonConfig {
|
||||
* 所有表单项的控件样式
|
||||
*/
|
||||
controlClass?: string;
|
||||
/**
|
||||
* 默认折叠
|
||||
* @default false
|
||||
*/
|
||||
defaultCollapsed?: boolean;
|
||||
/**
|
||||
* 所有表单项的禁用状态
|
||||
* @default false
|
||||
@@ -213,6 +234,79 @@ type RenderComponentContentType = (
|
||||
api: FormActions,
|
||||
) => Record<string, any>;
|
||||
|
||||
type MappedComponentProps<P> =
|
||||
| ((
|
||||
value: Partial<Record<string, any>>,
|
||||
actions: FormActions,
|
||||
) => P & Record<string, any>)
|
||||
| (P & Record<string, any>);
|
||||
|
||||
/**
|
||||
* 格式化 `getValues()` 输出中的当前字段值。
|
||||
* - 返回 `undefined`:保留当前字段已被移除的状态,通常配合 `setValue(key, nextValue)`
|
||||
* 把一个字段拆分写入到其他字段,例如 `startTime` / `endTime`
|
||||
* - 返回其他值:会将当前字段恢复/写回为该返回值
|
||||
* - `setValue` 回调签名为 `(key, nextValue) => void`
|
||||
*/
|
||||
export type FormValueFormat = (
|
||||
value: any,
|
||||
setValue: (fieldName: string, value: any) => void,
|
||||
values: Record<string, any>,
|
||||
) => any;
|
||||
|
||||
interface FormSchemaBody extends Omit<FormCommonConfig, 'componentProps'> {
|
||||
/** 默认值 */
|
||||
defaultValue?: any;
|
||||
/** 依赖 */
|
||||
dependencies?: FormItemDependencies;
|
||||
/** 描述 */
|
||||
description?: CustomRenderType;
|
||||
/** 字段名 */
|
||||
fieldName: string;
|
||||
/** 帮助信息 */
|
||||
help?: CustomParamsRenderType;
|
||||
/** 是否隐藏表单项 */
|
||||
hide?: boolean;
|
||||
/** 表单项 */
|
||||
label?: CustomRenderType;
|
||||
// 自定义组件内部渲染
|
||||
renderComponentContent?: RenderComponentContentType;
|
||||
/** 字段规则 */
|
||||
rules?: FormSchemaRuleType;
|
||||
/** 后缀 */
|
||||
suffix?: CustomRenderType;
|
||||
/**
|
||||
* 获取表单值时格式化当前字段。
|
||||
* - 返回值不为 `undefined` 时,会回写到当前 fieldName
|
||||
* - 返回值为 `undefined` 时,可通过 setValue 写入一个或多个目标字段
|
||||
*/
|
||||
valueFormat?: FormValueFormat;
|
||||
}
|
||||
|
||||
type FormSchemaDiscriminated<
|
||||
T extends BaseFormComponentType,
|
||||
P extends Record<string, any>,
|
||||
> = {
|
||||
[K in Extract<keyof P, T>]: {
|
||||
/** 组件 */
|
||||
component: K;
|
||||
/** 组件参数 */
|
||||
componentProps?: MappedComponentProps<P[K]>;
|
||||
} & FormSchemaBody;
|
||||
}[Extract<keyof P, T>];
|
||||
|
||||
type FormSchemaFallback<T extends BaseFormComponentType> = {
|
||||
/** 组件 */
|
||||
component: Component | T;
|
||||
/** 组件参数 */
|
||||
componentProps?: ComponentProps;
|
||||
} & FormSchemaBody;
|
||||
|
||||
export type FormSchema<
|
||||
T extends BaseFormComponentType = BaseFormComponentType,
|
||||
P extends Record<string, any> = Record<never, never>,
|
||||
> = FormSchemaDiscriminated<T, P> | FormSchemaFallback<T>;
|
||||
|
||||
export type HandleSubmitFn = (
|
||||
values: Record<string, any>,
|
||||
) => Promise<void> | void;
|
||||
@@ -238,46 +332,26 @@ export type ArrayToStringFields = Array<
|
||||
| string[] // 简单数组格式,最后一个元素可以是分隔符
|
||||
>;
|
||||
|
||||
export interface FormSchema<
|
||||
export interface FormFieldProps<
|
||||
T extends BaseFormComponentType = BaseFormComponentType,
|
||||
> extends FormCommonConfig {
|
||||
> extends FormSchemaBody {
|
||||
/** 组件 */
|
||||
component: Component | T;
|
||||
/** 组件参数 */
|
||||
componentProps?: ComponentProps;
|
||||
/** 默认值 */
|
||||
defaultValue?: any;
|
||||
/** 依赖 */
|
||||
dependencies?: FormItemDependencies;
|
||||
/** 描述 */
|
||||
description?: CustomRenderType;
|
||||
/** 字段名 */
|
||||
fieldName: string;
|
||||
/** 帮助信息 */
|
||||
help?: CustomRenderType;
|
||||
/** 表单项 */
|
||||
label?: CustomRenderType;
|
||||
// 自定义组件内部渲染
|
||||
renderComponentContent?: RenderComponentContentType;
|
||||
/** 字段规则 */
|
||||
rules?: FormSchemaRuleType;
|
||||
/** 后缀 */
|
||||
suffix?: CustomRenderType;
|
||||
}
|
||||
|
||||
export interface FormFieldProps extends FormSchema {
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export interface FormRenderProps<
|
||||
T extends BaseFormComponentType = BaseFormComponentType,
|
||||
P extends Record<string, any> = Record<never, never>,
|
||||
> {
|
||||
/**
|
||||
* 表单字段数组映射字符串配置 默认使用","
|
||||
*/
|
||||
arrayToStringFields?: ArrayToStringFields;
|
||||
/**
|
||||
* 是否展开,在showCollapseButton=true下生效
|
||||
* 是否折叠,在showCollapseButton=true下生效
|
||||
* true:折叠 false:展开
|
||||
*/
|
||||
collapsed?: boolean;
|
||||
/**
|
||||
@@ -321,7 +395,7 @@ export interface FormRenderProps<
|
||||
/**
|
||||
* 表单定义
|
||||
*/
|
||||
schema?: FormSchema<T>[];
|
||||
schema?: FormSchema<T, P>[];
|
||||
|
||||
/**
|
||||
* 是否显示展开/折叠
|
||||
@@ -346,10 +420,11 @@ export interface ActionButtonOptions extends VbenButtonProps {
|
||||
|
||||
export interface VbenFormProps<
|
||||
T extends BaseFormComponentType = BaseFormComponentType,
|
||||
P extends Record<string, any> = Record<never, never>,
|
||||
> extends Omit<
|
||||
FormRenderProps<T>,
|
||||
'componentBindEventMap' | 'componentMap' | 'form'
|
||||
> {
|
||||
FormRenderProps<T, P>,
|
||||
'componentBindEventMap' | 'componentMap' | 'form'
|
||||
> {
|
||||
/**
|
||||
* 操作按钮是否反转(提交按钮前置)
|
||||
*/
|
||||
@@ -376,6 +451,10 @@ export interface VbenFormProps<
|
||||
* 表单字段映射
|
||||
*/
|
||||
fieldMappingTime?: FieldMappingTime;
|
||||
/**
|
||||
* 表单收起展开状态变化回调
|
||||
*/
|
||||
handleCollapsedChange?: (collapsed: boolean) => void;
|
||||
/**
|
||||
* 表单重置回调
|
||||
*/
|
||||
|
||||
@@ -13,7 +13,7 @@ import { useForm } from 'vee-validate';
|
||||
import { object, ZodIntersection, ZodNumber, ZodObject, ZodString } from 'zod';
|
||||
import { getDefaultsForSchema } from 'zod-defaults';
|
||||
|
||||
type ExtendFormProps = VbenFormProps & { formApi: ExtendedFormApi };
|
||||
type ExtendFormProps = VbenFormProps & { formApi?: ExtendedFormApi };
|
||||
|
||||
export const [injectFormProps, provideFormProps] =
|
||||
createContext<[ComputedRef<ExtendFormProps> | ExtendFormProps, FormActions]>(
|
||||
|
||||
@@ -13,9 +13,10 @@ import VbenUseForm from './vben-use-form.vue';
|
||||
|
||||
export function useVbenForm<
|
||||
T extends BaseFormComponentType = BaseFormComponentType,
|
||||
>(options: VbenFormProps<T>) {
|
||||
P extends Record<string, any> = Record<never, never>,
|
||||
>(options: VbenFormProps<T, P>) {
|
||||
const IS_REACTIVE = isReactive(options);
|
||||
const api = new FormApi(options);
|
||||
const api = new FormApi(options as unknown as VbenFormProps);
|
||||
const extendedApi: ExtendedFormApi = api as never;
|
||||
extendedApi.useStore = (selector) => {
|
||||
return useStore(api.store, selector);
|
||||
|
||||
@@ -40,7 +40,9 @@ const { delegatedSlots, form } = useFormInitial(props);
|
||||
provideFormProps([props, form]);
|
||||
|
||||
const handleUpdateCollapsed = (value: boolean) => {
|
||||
currentCollapsed.value = !!value;
|
||||
currentCollapsed.value = value;
|
||||
// 触发收起展开状态变化回调
|
||||
props.handleCollapsedChange?.(value);
|
||||
};
|
||||
|
||||
watchEffect(() => {
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from './use-form-context';
|
||||
// 通过 extends 会导致热更新卡死,所以重复写了一遍
|
||||
interface Props extends VbenFormProps {
|
||||
formApi: ExtendedFormApi;
|
||||
formApi?: ExtendedFormApi;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
@@ -44,11 +44,13 @@ provideComponentRefMap(componentRefMap);
|
||||
props.formApi?.mount?.(form, componentRefMap);
|
||||
|
||||
const handleUpdateCollapsed = (value: boolean) => {
|
||||
props.formApi?.setState({ collapsed: !!value });
|
||||
props.formApi?.setState({ collapsed: value });
|
||||
// 触发收起展开状态变化回调
|
||||
forward.value.handleCollapsedChange?.(value);
|
||||
};
|
||||
|
||||
function handleKeyDownEnter(event: KeyboardEvent) {
|
||||
if (!state.value.submitOnEnter || !forward.value.formApi?.isMounted) {
|
||||
if (!state?.value.submitOnEnter || !forward.value.formApi?.isMounted) {
|
||||
return;
|
||||
}
|
||||
// 如果是 textarea 不阻止默认行为,否则会导致无法换行。
|
||||
@@ -58,11 +60,11 @@ function handleKeyDownEnter(event: KeyboardEvent) {
|
||||
}
|
||||
event.preventDefault();
|
||||
|
||||
forward.value.formApi.validateAndSubmitForm();
|
||||
forward.value.formApi?.validateAndSubmitForm();
|
||||
}
|
||||
|
||||
const handleValuesChangeDebounced = useDebounceFn(async () => {
|
||||
state.value.submitOnChange && forward.value.formApi?.validateAndSubmitForm();
|
||||
state?.value.submitOnChange && forward.value.formApi?.validateAndSubmitForm();
|
||||
}, 300);
|
||||
|
||||
const valuesCache: Recordable<any> = {};
|
||||
@@ -74,7 +76,7 @@ onMounted(async () => {
|
||||
() => form.values,
|
||||
async (newVal) => {
|
||||
if (forward.value.handleValuesChange) {
|
||||
const fields = state.value.schema?.map((item) => {
|
||||
const fields = state?.value.schema?.map((item) => {
|
||||
return item.fieldName;
|
||||
});
|
||||
|
||||
@@ -91,8 +93,9 @@ onMounted(async () => {
|
||||
|
||||
if (changedFields.length > 0) {
|
||||
// 调用handleValuesChange回调,传入所有表单值的深拷贝和变更的字段列表
|
||||
const values = await forward.value.formApi?.getValues();
|
||||
forward.value.handleValuesChange(
|
||||
cloneDeep(await forward.value.formApi.getValues()),
|
||||
cloneDeep(values ?? {}) as Record<string, any>,
|
||||
changedFields,
|
||||
);
|
||||
}
|
||||
@@ -109,7 +112,7 @@ onMounted(async () => {
|
||||
<Form
|
||||
@keydown.enter="handleKeyDownEnter"
|
||||
v-bind="forward"
|
||||
:collapsed="state.collapsed"
|
||||
:collapsed="state?.collapsed"
|
||||
:component-bind-event-map="COMPONENT_BIND_EVENT_MAP"
|
||||
:component-map="COMPONENT_MAP"
|
||||
:form="form"
|
||||
@@ -126,7 +129,7 @@ onMounted(async () => {
|
||||
<slot v-bind="slotProps">
|
||||
<FormActions
|
||||
v-if="forward.showDefaultActions"
|
||||
:model-value="state.collapsed"
|
||||
:model-value="state?.collapsed"
|
||||
@update:model-value="handleUpdateCollapsed"
|
||||
>
|
||||
<template #reset-before="resetSlotProps">
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from '@vben/tailwind-config';
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
import Vue from 'unplugin-vue/rolldown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
deps: {
|
||||
skipNodeModulesBundle: true,
|
||||
},
|
||||
dts: {
|
||||
vue: true,
|
||||
},
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
js: '.mjs',
|
||||
}),
|
||||
platform: 'neutral',
|
||||
plugins: [Vue({ isProduction: true })],
|
||||
unbundle: true,
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: [
|
||||
{
|
||||
builder: 'mkdist',
|
||||
input: './src',
|
||||
loaders: ['vue'],
|
||||
pattern: ['**/*.vue'],
|
||||
},
|
||||
{
|
||||
builder: 'mkdist',
|
||||
format: 'esm',
|
||||
input: './src',
|
||||
loaders: ['js'],
|
||||
pattern: ['**/*.ts'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/layout-ui",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild",
|
||||
"build": "pnpm exec tsdown",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
@@ -22,16 +22,19 @@
|
||||
],
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
@@ -44,5 +47,8 @@
|
||||
"@vben-core/typings": "workspace:*",
|
||||
"@vueuse/core": "catalog:",
|
||||
"vue": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"unplugin-vue": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from '@vben/tailwind-config/postcss';
|
||||
@@ -26,6 +26,7 @@ interface Props {
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {});
|
||||
|
||||
// @ts-expect-error - unused
|
||||
const { contentElement, overlayStyle } = useLayoutContentStyle();
|
||||
|
||||
const style = computed((): CSSProperties => {
|
||||
@@ -55,7 +56,7 @@ const style = computed((): CSSProperties => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main ref="contentElement" :style="style" class="bg-background-deep relative">
|
||||
<main ref="contentElement" :style="style" class="relative bg-background-deep">
|
||||
<Slot :style="overlayStyle">
|
||||
<slot name="overlay"></slot>
|
||||
</Slot>
|
||||
|
||||
@@ -37,7 +37,7 @@ const style = computed((): CSSProperties => {
|
||||
<template>
|
||||
<footer
|
||||
:style="style"
|
||||
class="bg-background-deep bottom-0 w-full transition-all duration-200"
|
||||
class="bottom-0 w-full bg-background-deep transition-all duration-200"
|
||||
>
|
||||
<slot></slot>
|
||||
</footer>
|
||||
|
||||
@@ -64,7 +64,7 @@ const logoStyle = computed((): CSSProperties => {
|
||||
<header
|
||||
:class="theme"
|
||||
:style="style"
|
||||
class="border-border bg-header top-0 flex w-full flex-[0_0_auto] items-center border-b pl-2 transition-[margin-top] duration-200"
|
||||
class="top-0 flex w-full flex-[0_0_auto] items-center border-b border-border bg-header pl-2 transition-[margin-top] duration-200"
|
||||
>
|
||||
<div v-if="slots.logo" :style="logoStyle">
|
||||
<slot name="logo"></slot>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import type { CSSProperties } from 'vue';
|
||||
|
||||
import { computed, shallowRef, useSlots, watchEffect } from 'vue';
|
||||
import { computed, onUnmounted, shallowRef, useSlots, watchEffect } from 'vue';
|
||||
|
||||
import { VbenScrollbar } from '@vben-core/shadcn-ui';
|
||||
|
||||
import { useScrollLock } from '@vueuse/core';
|
||||
|
||||
import { useSidebarDrag } from '../hooks/use-sidebar-drag';
|
||||
import { SidebarCollapseButton, SidebarFixedButton } from './widgets';
|
||||
|
||||
interface Props {
|
||||
@@ -77,7 +78,10 @@ interface Props {
|
||||
* 主题
|
||||
*/
|
||||
theme: string;
|
||||
|
||||
/**
|
||||
* 子主题
|
||||
*/
|
||||
themeSub: string;
|
||||
/**
|
||||
* 宽度
|
||||
*/
|
||||
@@ -104,7 +108,8 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
zIndex: 0,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ leave: [] }>();
|
||||
const emit = defineEmits<{ leave: []; 'update:width': [value: number] }>();
|
||||
const draggable = defineModel<boolean>('draggable');
|
||||
const collapse = defineModel<boolean>('collapse');
|
||||
const extraCollapse = defineModel<boolean>('extraCollapse');
|
||||
const expandOnHovering = defineModel<boolean>('expandOnHovering');
|
||||
@@ -114,7 +119,8 @@ const extraVisible = defineModel<boolean>('extraVisible');
|
||||
const isLocked = useScrollLock(document.body);
|
||||
const slots = useSlots();
|
||||
|
||||
const asideRef = shallowRef<HTMLDivElement | null>();
|
||||
const asideRef = shallowRef<HTMLElement | null>(null);
|
||||
const dragBarRef = shallowRef<HTMLElement | null>(null);
|
||||
|
||||
const hiddenSideStyle = computed((): CSSProperties => calcMenuWidthStyle(true));
|
||||
|
||||
@@ -151,9 +157,9 @@ const extraTitleStyle = computed((): CSSProperties => {
|
||||
});
|
||||
|
||||
const contentWidthStyle = computed((): CSSProperties => {
|
||||
const { collapseWidth, fixedExtra, isSidebarMixed, mixedWidth } = props;
|
||||
const { fixedExtra, isSidebarMixed, mixedWidth } = props;
|
||||
if (isSidebarMixed && fixedExtra) {
|
||||
return { width: `${collapse.value ? collapseWidth : mixedWidth}px` };
|
||||
return { width: `${mixedWidth}px` };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
@@ -196,19 +202,24 @@ watchEffect(() => {
|
||||
});
|
||||
|
||||
function calcMenuWidthStyle(isHiddenDom: boolean): CSSProperties {
|
||||
const { extraWidth, fixedExtra, isSidebarMixed, show, width } = props;
|
||||
const {
|
||||
collapseWidth,
|
||||
extraWidth,
|
||||
mixedWidth,
|
||||
fixedExtra,
|
||||
isSidebarMixed,
|
||||
show,
|
||||
width,
|
||||
} = props;
|
||||
|
||||
let widthValue =
|
||||
width === 0
|
||||
? '0px'
|
||||
: `${width + (isSidebarMixed && fixedExtra && extraVisible.value ? extraWidth : 0)}px`;
|
||||
|
||||
const { collapseWidth } = props;
|
||||
|
||||
if (isHiddenDom && expandOnHovering.value && !expandOnHover.value) {
|
||||
widthValue = `${collapseWidth}px`;
|
||||
widthValue = isSidebarMixed ? `${mixedWidth}px` : `${collapseWidth}px`;
|
||||
}
|
||||
|
||||
return {
|
||||
...(widthValue === '0px' ? { overflow: 'hidden' } : {}),
|
||||
flex: `0 0 ${widthValue}`,
|
||||
@@ -250,6 +261,40 @@ function handleMouseleave() {
|
||||
collapse.value = true;
|
||||
extraVisible.value = false;
|
||||
}
|
||||
|
||||
const { startDrag, endDrag } = useSidebarDrag();
|
||||
|
||||
const handleDragSidebar = (e: MouseEvent) => {
|
||||
const { isSidebarMixed, collapseWidth, width } = props;
|
||||
const minLimit = isSidebarMixed ? width + collapseWidth : collapseWidth;
|
||||
const maxLimit = isSidebarMixed ? width + 320 : 320;
|
||||
|
||||
startDrag(
|
||||
e,
|
||||
{
|
||||
min: minLimit,
|
||||
max: maxLimit,
|
||||
},
|
||||
{
|
||||
target: asideRef.value,
|
||||
dragBar: dragBarRef.value,
|
||||
},
|
||||
(newWidth) => {
|
||||
if (isSidebarMixed) {
|
||||
emit('update:width', newWidth - width);
|
||||
extraCollapse.value = collapse.value =
|
||||
newWidth - width <= collapseWidth;
|
||||
} else {
|
||||
emit('update:width', newWidth);
|
||||
collapse.value = extraCollapse.value = newWidth <= collapseWidth;
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
onUnmounted(() => {
|
||||
endDrag();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -260,42 +305,50 @@ function handleMouseleave() {
|
||||
class="h-full transition-all duration-150"
|
||||
></div>
|
||||
<aside
|
||||
:class="[
|
||||
theme,
|
||||
{
|
||||
'bg-sidebar-deep': isSidebarMixed,
|
||||
'bg-sidebar border-border border-r': !isSidebarMixed,
|
||||
},
|
||||
]"
|
||||
ref="asideRef"
|
||||
:style="style"
|
||||
class="fixed left-0 top-0 h-full transition-all duration-150"
|
||||
:class="theme"
|
||||
@mouseenter="handleMouseenter"
|
||||
@mouseleave="handleMouseleave"
|
||||
>
|
||||
<SidebarFixedButton
|
||||
v-if="!collapse && !isSidebarMixed && showFixedButton"
|
||||
v-model:expand-on-hover="expandOnHover"
|
||||
/>
|
||||
<div v-if="slots.logo" :style="headerStyle">
|
||||
<slot name="logo"></slot>
|
||||
</div>
|
||||
<VbenScrollbar :style="contentStyle" shadow shadow-border>
|
||||
<slot></slot>
|
||||
</VbenScrollbar>
|
||||
<div
|
||||
class="h-full"
|
||||
:class="[
|
||||
{
|
||||
'bg-sidebar-deep': isSidebarMixed,
|
||||
'border-r border-border bg-sidebar': !isSidebarMixed,
|
||||
},
|
||||
]"
|
||||
:style="{ width: `${width}px` }"
|
||||
>
|
||||
<SidebarFixedButton
|
||||
v-if="!collapse && !isSidebarMixed && showFixedButton"
|
||||
v-model:expand-on-hover="expandOnHover"
|
||||
/>
|
||||
<div v-if="slots.logo" :style="headerStyle">
|
||||
<slot name="logo"></slot>
|
||||
</div>
|
||||
<VbenScrollbar :style="contentStyle" shadow shadow-border>
|
||||
<slot></slot>
|
||||
</VbenScrollbar>
|
||||
|
||||
<div :style="collapseStyle"></div>
|
||||
<SidebarCollapseButton
|
||||
v-if="showCollapseButton && !isSidebarMixed"
|
||||
v-model:collapsed="collapse"
|
||||
/>
|
||||
<div :style="collapseStyle"></div>
|
||||
<SidebarCollapseButton
|
||||
v-if="showCollapseButton && !isSidebarMixed"
|
||||
v-model:collapsed="collapse"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="isSidebarMixed"
|
||||
ref="asideRef"
|
||||
:class="{
|
||||
'border-l': extraVisible,
|
||||
}"
|
||||
:class="[
|
||||
themeSub,
|
||||
{
|
||||
'border-l': extraVisible,
|
||||
},
|
||||
]"
|
||||
:style="extraStyle"
|
||||
class="border-border bg-sidebar fixed top-0 h-full overflow-hidden border-r transition-all duration-200"
|
||||
class="fixed top-0 h-full overflow-hidden border-r border-border bg-sidebar transition-all duration-200"
|
||||
>
|
||||
<SidebarCollapseButton
|
||||
v-if="isSidebarMixed && expandOnHover"
|
||||
@@ -318,5 +371,11 @@ function handleMouseleave() {
|
||||
<slot name="extra"></slot>
|
||||
</VbenScrollbar>
|
||||
</div>
|
||||
<div
|
||||
v-if="draggable"
|
||||
ref="dragBarRef"
|
||||
class="absolute inset-y-0 -right-px z-1000 w-0.5 cursor-col-resize hover:bg-primary"
|
||||
@mousedown="handleDragSidebar"
|
||||
></div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
@@ -23,7 +23,7 @@ const style = computed((): CSSProperties => {
|
||||
<template>
|
||||
<section
|
||||
:style="style"
|
||||
class="border-border bg-background flex w-full border-b transition-all"
|
||||
class="flex w-full border-b border-border bg-background transition-all"
|
||||
>
|
||||
<slot></slot>
|
||||
</section>
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ function handleCollapsed() {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex-center hover:text-foreground text-foreground/60 hover:bg-accent-hover bg-accent absolute bottom-2 left-3 z-10 cursor-pointer rounded-sm p-1"
|
||||
class="absolute bottom-2 left-3 z-10 flex-center cursor-pointer rounded-sm bg-accent p-1 text-foreground/60 hover:bg-accent-hover hover:text-foreground"
|
||||
@click.stop="handleCollapsed"
|
||||
>
|
||||
<ChevronsRight v-if="collapsed" class="size-4" />
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ function toggleFixed() {
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="flex-center hover:text-foreground text-foreground/60 hover:bg-accent-hover bg-accent absolute bottom-2 right-3 z-10 cursor-pointer rounded-sm p-[5px] transition-all duration-300"
|
||||
class="absolute right-3 bottom-2 z-10 flex-center cursor-pointer rounded-sm bg-accent p-1.25 text-foreground/60 transition-all duration-300 hover:bg-accent-hover hover:text-foreground"
|
||||
@click="toggleFixed"
|
||||
>
|
||||
<PinOff v-if="!expandOnHover" class="size-3.5" />
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
interface DragOptions {
|
||||
max: number;
|
||||
min: number;
|
||||
}
|
||||
|
||||
interface DragElements {
|
||||
dragBar: HTMLElement | null;
|
||||
target: HTMLElement | null;
|
||||
}
|
||||
|
||||
type DragCallback = (newWidth: number) => void;
|
||||
|
||||
export function useSidebarDrag() {
|
||||
const isDragging = ref(false);
|
||||
let cleanup: (() => void) | null = null;
|
||||
let dragOverlay: HTMLElement | null = null;
|
||||
|
||||
const startDrag = (
|
||||
e: MouseEvent,
|
||||
options: DragOptions,
|
||||
elements: DragElements,
|
||||
onDrag: DragCallback,
|
||||
) => {
|
||||
const { min, max } = options;
|
||||
const { dragBar, target } = elements;
|
||||
|
||||
if (isDragging.value || !dragBar || !target) return;
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
isDragging.value = true;
|
||||
|
||||
const startX = e.clientX;
|
||||
const startWidth = target.getBoundingClientRect().width;
|
||||
const startLeft = dragBar.offsetLeft;
|
||||
|
||||
dragBar.classList.add('bg-primary');
|
||||
dragBar.classList.remove('bg-primary/30');
|
||||
|
||||
const dragBarTransition = dragBar.style.transition;
|
||||
const targetTransition = target.style.transition;
|
||||
|
||||
dragBar.style.transition = 'none';
|
||||
target.style.transition = 'none';
|
||||
|
||||
dragOverlay = document.createElement('div');
|
||||
dragOverlay.style.position = 'fixed';
|
||||
dragOverlay.style.inset = '0';
|
||||
dragOverlay.style.zIndex = '9999';
|
||||
dragOverlay.style.cursor = 'col-resize';
|
||||
dragOverlay.style.userSelect = 'none';
|
||||
dragOverlay.style.outline = 'none';
|
||||
dragOverlay.tabIndex = -1;
|
||||
dragOverlay.style.background = 'rgba(0,0,0,0)';
|
||||
document.body.append(dragOverlay);
|
||||
|
||||
const onMouseMove = (moveEvent: MouseEvent) => {
|
||||
if (!isDragging.value || !dragBar || !target) {
|
||||
endDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
const deltaX = moveEvent.clientX - startX;
|
||||
let currentWidth = startWidth + deltaX;
|
||||
|
||||
const isOutOfMin = currentWidth < min;
|
||||
const isOutOfMax = currentWidth > max;
|
||||
const isOutOfBounds = isOutOfMin || isOutOfMax;
|
||||
|
||||
if (isOutOfMin) currentWidth = min;
|
||||
if (isOutOfMax) currentWidth = max;
|
||||
|
||||
const newLeft = startLeft + (currentWidth - startWidth);
|
||||
|
||||
if (dragOverlay)
|
||||
dragOverlay.style.cursor = isOutOfBounds ? 'not-allowed' : 'col-resize';
|
||||
|
||||
dragBar.style.left = `${newLeft}px`;
|
||||
|
||||
if (isOutOfBounds) {
|
||||
dragBar.classList.add('bg-primary/30');
|
||||
dragBar.classList.remove('bg-primary');
|
||||
} else {
|
||||
dragBar.classList.add('bg-primary');
|
||||
dragBar.classList.remove('bg-primary/30');
|
||||
}
|
||||
};
|
||||
|
||||
const onMouseUp = (upEvent: MouseEvent) => {
|
||||
if (!isDragging.value || !dragBar || !target) {
|
||||
endDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
const deltaX = upEvent.clientX - startX;
|
||||
let newWidth = startWidth + deltaX;
|
||||
|
||||
newWidth = Math.min(max, Math.max(min, newWidth));
|
||||
|
||||
dragBar.classList.remove('bg-primary', 'bg-primary/30');
|
||||
|
||||
try {
|
||||
onDrag?.(Math.round(newWidth));
|
||||
} finally {
|
||||
endDrag();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
|
||||
cleanup = () => {
|
||||
if (!cleanup) return;
|
||||
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
|
||||
if (dragBar) {
|
||||
dragBar.style.transition = dragBarTransition;
|
||||
dragBar.style.left = '';
|
||||
dragBar.classList.remove('bg-primary', 'bg-primary/30');
|
||||
}
|
||||
|
||||
if (target) {
|
||||
target.style.transition = targetTransition;
|
||||
}
|
||||
|
||||
if (dragOverlay) {
|
||||
dragOverlay.remove();
|
||||
dragOverlay = null;
|
||||
}
|
||||
|
||||
isDragging.value = false;
|
||||
cleanup = null;
|
||||
};
|
||||
};
|
||||
|
||||
const endDrag = () => {
|
||||
cleanup?.();
|
||||
};
|
||||
|
||||
return {
|
||||
startDrag,
|
||||
endDrag,
|
||||
get isDragging() {
|
||||
return isDragging.value;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -146,6 +146,11 @@ interface VbenLayoutProps {
|
||||
* @default dark
|
||||
*/
|
||||
sidebarTheme?: ThemeModeType;
|
||||
/**
|
||||
* 侧边栏子栏
|
||||
* @default dark
|
||||
*/
|
||||
sidebarThemeSub?: ThemeModeType;
|
||||
/**
|
||||
* 侧边栏宽度
|
||||
* @default 210
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
useLayoutFooterStyle,
|
||||
useLayoutHeaderStyle,
|
||||
} from '@vben-core/composables';
|
||||
import { Menu } from '@vben-core/icons';
|
||||
import { IconifyIcon } from '@vben-core/icons';
|
||||
import { VbenIconButton } from '@vben-core/shadcn-ui';
|
||||
import { ELEMENT_ID_MAIN_CONTENT } from '@vben-core/shared/constants';
|
||||
|
||||
@@ -56,6 +56,7 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
sidebarHidden: false,
|
||||
sidebarMixedWidth: 80,
|
||||
sidebarTheme: 'dark',
|
||||
sidebarThemeSub: 'dark',
|
||||
sidebarWidth: 180,
|
||||
sideCollapseWidth: 60,
|
||||
tabbarEnable: true,
|
||||
@@ -63,7 +64,14 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
zIndex: 200,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ sideMouseLeave: []; toggleSidebar: [] }>();
|
||||
const emit = defineEmits<{
|
||||
sideMouseLeave: [];
|
||||
toggleSidebar: [];
|
||||
'update:sidebar-width': [value: number];
|
||||
}>();
|
||||
const sidebarDraggable = defineModel<boolean>('sidebarDraggable', {
|
||||
default: true,
|
||||
});
|
||||
const sidebarCollapse = defineModel<boolean>('sidebarCollapse', {
|
||||
default: false,
|
||||
});
|
||||
@@ -119,13 +127,16 @@ const headerWrapperHeight = computed(() => {
|
||||
});
|
||||
|
||||
const getSideCollapseWidth = computed(() => {
|
||||
const { sidebarCollapseShowTitle, sidebarMixedWidth, sideCollapseWidth } =
|
||||
props;
|
||||
const {
|
||||
sidebarCollapseShowTitle,
|
||||
sidebarExtraCollapsedWidth,
|
||||
sideCollapseWidth,
|
||||
} = props;
|
||||
|
||||
return sidebarCollapseShowTitle ||
|
||||
isSidebarMixedNav.value ||
|
||||
isHeaderMixedNav.value
|
||||
? sidebarMixedWidth
|
||||
? sidebarExtraCollapsedWidth
|
||||
: sideCollapseWidth;
|
||||
});
|
||||
|
||||
@@ -236,9 +247,7 @@ const mainStyle = computed(() => {
|
||||
sidebarExtraVisible.value;
|
||||
|
||||
if (isSideNavEffective) {
|
||||
const sideCollapseWidth = sidebarCollapse.value
|
||||
? getSideCollapseWidth.value
|
||||
: props.sidebarMixedWidth;
|
||||
const sideCollapseWidth = props.sidebarMixedWidth;
|
||||
const sideWidth = sidebarExtraCollapse.value
|
||||
? props.sidebarExtraCollapsedWidth
|
||||
: props.sidebarWidth;
|
||||
@@ -247,10 +256,14 @@ const mainStyle = computed(() => {
|
||||
sidebarAndExtraWidth = `${sideCollapseWidth + sideWidth}px`;
|
||||
width = `calc(100% - ${sidebarAndExtraWidth})`;
|
||||
} else {
|
||||
sidebarAndExtraWidth =
|
||||
sidebarExpandOnHovering.value && !sidebarExpandOnHover.value
|
||||
? `${getSideCollapseWidth.value}px`
|
||||
: `${getSidebarWidth.value}px`;
|
||||
let sidebarWidth = getSidebarWidth.value;
|
||||
if (sidebarExpandOnHovering.value && !sidebarExpandOnHover.value) {
|
||||
sidebarWidth =
|
||||
isSidebarMixedNav.value || isHeaderMixedNav.value
|
||||
? props.sidebarMixedWidth
|
||||
: getSideCollapseWidth.value;
|
||||
}
|
||||
sidebarAndExtraWidth = `${sidebarWidth}px`;
|
||||
width = `calc(100% - ${sidebarAndExtraWidth})`;
|
||||
}
|
||||
}
|
||||
@@ -262,7 +275,7 @@ const mainStyle = computed(() => {
|
||||
|
||||
// 计算 tabbar 的样式
|
||||
const tabbarStyle = computed((): CSSProperties => {
|
||||
let width = '';
|
||||
let width: string;
|
||||
let marginLeft = 0;
|
||||
|
||||
// 如果不是混合导航,tabbar 的宽度为 100%
|
||||
@@ -403,13 +416,10 @@ watch(
|
||||
);
|
||||
|
||||
{
|
||||
const mouseMove = () => {
|
||||
mouseY.value > headerWrapperHeight.value
|
||||
? (headerIsHidden.value = true)
|
||||
: (headerIsHidden.value = false);
|
||||
};
|
||||
const HEADER_TRIGGER_DISTANCE = 12;
|
||||
|
||||
watch(
|
||||
[() => props.headerMode, () => mouseY.value],
|
||||
[() => props.headerMode, () => mouseY.value, () => headerIsHidden.value],
|
||||
() => {
|
||||
if (!isHeaderAutoMode.value || isMixedNav.value || isFullContent.value) {
|
||||
if (props.headerMode !== 'auto-scroll') {
|
||||
@@ -417,8 +427,12 @@ watch(
|
||||
}
|
||||
return;
|
||||
}
|
||||
headerIsHidden.value = true;
|
||||
mouseMove();
|
||||
|
||||
const isInTriggerZone = mouseY.value <= HEADER_TRIGGER_DISTANCE;
|
||||
const isInHeaderZone =
|
||||
!headerIsHidden.value && mouseY.value <= headerWrapperHeight.value;
|
||||
|
||||
headerIsHidden.value = !(isInTriggerZone || isInHeaderZone);
|
||||
},
|
||||
{
|
||||
immediate: true,
|
||||
@@ -484,6 +498,7 @@ const idMainContent = ELEMENT_ID_MAIN_CONTENT;
|
||||
<div class="relative flex min-h-full w-full">
|
||||
<LayoutSidebar
|
||||
v-if="sidebarEnableState"
|
||||
v-model:draggable="sidebarDraggable"
|
||||
v-model:collapse="sidebarCollapse"
|
||||
v-model:expand-on-hover="sidebarExpandOnHover"
|
||||
v-model:expand-on-hovering="sidebarExpandOnHovering"
|
||||
@@ -501,9 +516,11 @@ const idMainContent = ELEMENT_ID_MAIN_CONTENT;
|
||||
:mixed-width="sidebarMixedWidth"
|
||||
:show="showSidebar"
|
||||
:theme="sidebarTheme"
|
||||
:theme-sub="sidebarThemeSub"
|
||||
:width="getSidebarWidth"
|
||||
:z-index="sidebarZIndex"
|
||||
@leave="() => emit('sideMouseLeave')"
|
||||
@update:width="(val) => emit('update:sidebar-width', val)"
|
||||
>
|
||||
<template v-if="isSideMode && !isMixedNav" #logo>
|
||||
<slot name="logo"></slot>
|
||||
@@ -559,7 +576,8 @@ const idMainContent = ELEMENT_ID_MAIN_CONTENT;
|
||||
class="my-0 mr-1 rounded-md"
|
||||
@click="handleHeaderToggle"
|
||||
>
|
||||
<Menu class="size-4" />
|
||||
<IconifyIcon v-if="showSidebar" icon="ep:fold" />
|
||||
<IconifyIcon v-else icon="ep:expand" />
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
<slot name="header"></slot>
|
||||
@@ -609,7 +627,7 @@ const idMainContent = ELEMENT_ID_MAIN_CONTENT;
|
||||
<div
|
||||
v-if="maskVisible"
|
||||
:style="maskStyle"
|
||||
class="bg-overlay fixed left-0 top-0 h-full w-full transition-[background-color] duration-200"
|
||||
class="fixed top-0 left-0 size-full bg-overlay transition-[background-color] duration-200"
|
||||
@click="handleClickMask"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
export { default } from '@vben/tailwind-config';
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'tsdown';
|
||||
import Vue from 'unplugin-vue/rolldown';
|
||||
|
||||
export default defineConfig({
|
||||
clean: true,
|
||||
deps: {
|
||||
skipNodeModulesBundle: true,
|
||||
},
|
||||
dts: {
|
||||
vue: true,
|
||||
},
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
outExtensions: () => ({
|
||||
dts: '.d.ts',
|
||||
js: '.mjs',
|
||||
}),
|
||||
platform: 'neutral',
|
||||
plugins: [Vue({ isProduction: true })],
|
||||
unbundle: true,
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { defineBuildConfig } from 'unbuild';
|
||||
|
||||
export default defineBuildConfig({
|
||||
clean: true,
|
||||
declaration: true,
|
||||
entries: [
|
||||
{
|
||||
builder: 'mkdist',
|
||||
input: './src',
|
||||
pattern: ['**/*'],
|
||||
},
|
||||
{
|
||||
builder: 'mkdist',
|
||||
input: './src',
|
||||
loaders: ['vue'],
|
||||
pattern: ['**/*.vue'],
|
||||
},
|
||||
{
|
||||
builder: 'mkdist',
|
||||
format: 'esm',
|
||||
input: './src',
|
||||
loaders: ['js'],
|
||||
pattern: ['**/*.ts'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vben-core/menu-ui",
|
||||
"version": "5.5.9",
|
||||
"version": "5.7.0",
|
||||
"homepage": "https://github.com/vbenjs/vue-vben-admin",
|
||||
"bugs": "https://github.com/vbenjs/vue-vben-admin/issues",
|
||||
"repository": {
|
||||
@@ -11,7 +11,7 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "pnpm unbuild",
|
||||
"build": "pnpm exec tsdown",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
@@ -22,27 +22,36 @@
|
||||
],
|
||||
"main": "./dist/index.mjs",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"development": "./src/index.ts",
|
||||
"production": "./src/index.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.mjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@vben-core/composables": "workspace:*",
|
||||
"@vben-core/design": "workspace:*",
|
||||
"@vben-core/icons": "workspace:*",
|
||||
"@vben-core/shadcn-ui": "workspace:*",
|
||||
"@vben-core/shared": "workspace:*",
|
||||
"@vben-core/typings": "workspace:*",
|
||||
"@vueuse/core": "catalog:",
|
||||
"qs": "catalog:",
|
||||
"vue": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/qs": "catalog:",
|
||||
"unplugin-vue": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user