✨ feat(core): 实现管理端后台界面及核心功能模块
* 初始化后台管理布局与路由框架 * 新增文件管理、仪表盘、系统设置及日志视图 * 实现文件上传预签名、提取流程及发送记录管理 * 构建常用组件库如模态框、表格、分页及进度条 * 引入多语言支持(中英文)及主题切换功能 * 封装后台业务逻辑 Hooks 和数据持久化存储功能
This commit is contained in:
1 parent
925c6450ac
commit
8badb80600
114 files changed
+18812
No files matched your search
@@ -0,0 +1,13 @@
|
||||
FROM python:3.9.5
|
||||
LABEL author="Lan"
|
||||
LABEL email="vast@tom.com"
|
||||
LABEL version="1.0"
|
||||
|
||||
|
||||
COPY . /app
|
||||
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
RUN echo 'Asia/Shanghai' >/etc/timezone
|
||||
WORKDIR /app
|
||||
RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
|
||||
EXPOSE 123456
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "12345"]
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterView } from 'vue-router'
|
||||
import ThemeToggle from './components/common/ThemeToggle.vue'
|
||||
import LanguageSwitcher from './components/common/LanguageSwitcher.vue'
|
||||
import AlertComponent from '@/components/common/AlertComponent.vue'
|
||||
import { useAppShell } from '@/composables'
|
||||
|
||||
const {
|
||||
isDarkMode,
|
||||
isLoading,
|
||||
routeTransitionMode,
|
||||
routeTransitionName,
|
||||
routeViewKey,
|
||||
showGlobalControls
|
||||
} = useAppShell()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="['app-container', isDarkMode ? 'dark' : 'light']">
|
||||
<div
|
||||
v-if="showGlobalControls"
|
||||
class="fixed z-50 flex items-center space-x-3"
|
||||
:style="{
|
||||
top: 'max(1rem, env(safe-area-inset-top))',
|
||||
right: 'max(1rem, env(safe-area-inset-right))'
|
||||
}"
|
||||
>
|
||||
<LanguageSwitcher />
|
||||
<ThemeToggle v-model="isDarkMode" />
|
||||
</div>
|
||||
<div v-if="isLoading" class="loading-overlay" role="status" aria-live="polite" aria-label="Loading">
|
||||
<div class="loading-spinner"></div>
|
||||
</div>
|
||||
<RouterView v-slot="{ Component }">
|
||||
<transition :name="routeTransitionName" :mode="routeTransitionMode">
|
||||
<component :is="Component" :key="routeViewKey" />
|
||||
</transition>
|
||||
</RouterView>
|
||||
|
||||
<AlertComponent />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.app-container {
|
||||
min-height: 100dvh;
|
||||
width: 100%;
|
||||
transition: background-color 0.5s ease;
|
||||
}
|
||||
|
||||
.light {
|
||||
background:
|
||||
linear-gradient(135deg, #dfe9eb 0%, #edf3f2 46%, #f7f8f5 100%),
|
||||
linear-gradient(90deg, rgba(103, 135, 145, 0.12), rgba(162, 172, 154, 0.1));
|
||||
}
|
||||
|
||||
.dark {
|
||||
background:
|
||||
linear-gradient(135deg, #10191e 0%, #17252b 48%, #223036 100%),
|
||||
linear-gradient(90deg, rgba(113, 153, 168, 0.12), rgba(117, 143, 132, 0.08));
|
||||
}
|
||||
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.transfer-fade-enter-active,
|
||||
.transfer-fade-leave-active {
|
||||
transition:
|
||||
opacity 0.2s ease,
|
||||
transform 0.2s ease;
|
||||
}
|
||||
|
||||
.transfer-fade-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
.transfer-fade-leave-active {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.transfer-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
.loading-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border: 3px solid #fff;
|
||||
border-top: 3px solid #6f98a6;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Binary file not shown.
@@ -0,0 +1,451 @@
|
||||
@import 'tailwindcss/base';
|
||||
@import 'tailwindcss/components';
|
||||
@import 'tailwindcss/utilities';
|
||||
|
||||
html {
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
/* Shared shell for the public send/retrieve flows. Keep these pages visually
|
||||
related without coupling their form behavior or pickup-code handling. */
|
||||
.public-page-shell {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.public-page-card {
|
||||
border-color: rgba(191, 208, 211, 0.72);
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
box-shadow: 0 10px 26px rgba(128, 151, 155, 0.18);
|
||||
}
|
||||
|
||||
.dark .public-page-card {
|
||||
border-color: rgba(68, 86, 94, 0.82);
|
||||
background: rgba(34, 49, 56, 0.94);
|
||||
box-shadow: 0 16px 36px rgba(4, 10, 14, 0.34);
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 3px solid rgba(95, 135, 150, 0.78);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.native-date-input {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.dark .native-date-input {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
scroll-behavior: auto !important;
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
.native-date-input::-webkit-calendar-picker-indicator {
|
||||
cursor: pointer;
|
||||
min-height: 2.75rem;
|
||||
min-width: 2.75rem;
|
||||
}
|
||||
|
||||
.theme-2026-card {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(191, 208, 211, 0.72);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(255, 255, 255, 0.94), rgba(234, 243, 245, 0.9)),
|
||||
radial-gradient(circle at 14% 10%, rgba(122, 159, 171, 0.18), transparent 30%);
|
||||
box-shadow: 0 10px 26px rgba(128, 151, 155, 0.18);
|
||||
}
|
||||
|
||||
.theme-2026-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(120deg, rgba(255, 255, 255, 0.48), transparent 42%);
|
||||
opacity: 0.74;
|
||||
}
|
||||
|
||||
.theme-2026-card > * {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.theme-2026-card-hover {
|
||||
transition:
|
||||
transform 220ms ease,
|
||||
border-color 220ms ease,
|
||||
box-shadow 220ms ease,
|
||||
background-color 220ms ease;
|
||||
}
|
||||
|
||||
.theme-2026-card-hover:hover {
|
||||
border-color: rgba(116, 153, 165, 0.86);
|
||||
box-shadow: 0 16px 34px rgba(114, 143, 150, 0.26);
|
||||
}
|
||||
|
||||
.fcb-lifecycle-card {
|
||||
border-color: rgba(191, 208, 211, 0.78) !important;
|
||||
transition:
|
||||
border-color 260ms ease,
|
||||
box-shadow 260ms cubic-bezier(0.22, 1, 0.36, 1),
|
||||
transform 260ms cubic-bezier(0.22, 1, 0.36, 1),
|
||||
background-color 260ms ease;
|
||||
}
|
||||
|
||||
.fcb-lifecycle-card:hover {
|
||||
border-color: rgba(95, 135, 150, 0.9) !important;
|
||||
box-shadow: 0 10px 24px rgba(86, 118, 126, 0.18);
|
||||
transform: translate3d(0, -1px, 0);
|
||||
}
|
||||
|
||||
.fcb-interactive-row {
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
transition:
|
||||
background-color 180ms ease,
|
||||
border-color 180ms ease,
|
||||
box-shadow 180ms ease,
|
||||
transform 180ms ease;
|
||||
}
|
||||
|
||||
.fcb-interactive-row:hover {
|
||||
z-index: 1;
|
||||
box-shadow: inset 3px 0 0 rgba(95, 135, 150, 0.7), 0 10px 22px rgba(86, 118, 126, 0.16);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.dark .theme-2026-card {
|
||||
border-color: rgba(68, 86, 94, 0.82);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(34, 49, 56, 0.96), rgba(24, 35, 42, 0.92)),
|
||||
radial-gradient(circle at 14% 10%, rgba(102, 142, 156, 0.18), transparent 32%);
|
||||
box-shadow: 0 16px 36px rgba(4, 10, 14, 0.34);
|
||||
}
|
||||
|
||||
.dark .theme-2026-card-hover:hover {
|
||||
border-color: rgba(113, 153, 168, 0.68);
|
||||
box-shadow: 0 20px 44px rgba(4, 10, 14, 0.46);
|
||||
}
|
||||
|
||||
.dark .fcb-lifecycle-card {
|
||||
border-color: rgba(68, 86, 94, 0.86) !important;
|
||||
}
|
||||
|
||||
.dark .fcb-lifecycle-card:hover {
|
||||
border-color: rgba(113, 153, 168, 0.82) !important;
|
||||
box-shadow: 0 14px 30px rgba(4, 10, 14, 0.38);
|
||||
}
|
||||
|
||||
.data-table-2026 thead th {
|
||||
background: rgba(236, 244, 246, 0.76);
|
||||
}
|
||||
|
||||
.data-table-2026 tbody tr {
|
||||
transition:
|
||||
background-color 180ms ease,
|
||||
opacity 180ms ease;
|
||||
}
|
||||
|
||||
.data-table-2026 tbody tr:hover {
|
||||
background: rgba(226, 236, 238, 0.46);
|
||||
}
|
||||
|
||||
.data-table-2026 tbody tr.is-selected {
|
||||
background: rgba(213, 228, 230, 0.72);
|
||||
}
|
||||
|
||||
.data-table-2026 tbody tr.is-muted {
|
||||
opacity: 0.74;
|
||||
}
|
||||
|
||||
.dark .data-table-2026 thead th {
|
||||
background: rgba(31, 45, 52, 0.82);
|
||||
}
|
||||
|
||||
.dark .data-table-2026 tbody tr:hover {
|
||||
background: rgba(45, 71, 81, 0.42);
|
||||
}
|
||||
|
||||
.dark .data-table-2026 tbody tr.is-selected-dark {
|
||||
background: rgba(42, 64, 72, 0.68);
|
||||
}
|
||||
|
||||
.bg-indigo-50,
|
||||
.bg-blue-50 {
|
||||
background-color: #dce8eb !important;
|
||||
}
|
||||
|
||||
.bg-indigo-100,
|
||||
.bg-blue-100 {
|
||||
background-color: #d1e0e3 !important;
|
||||
}
|
||||
|
||||
.bg-indigo-500,
|
||||
.bg-blue-500,
|
||||
.bg-cyan-500 {
|
||||
background-color: #6f98a6 !important;
|
||||
}
|
||||
|
||||
.bg-indigo-600,
|
||||
.bg-blue-600,
|
||||
.bg-cyan-600 {
|
||||
background-color: #5f8796 !important;
|
||||
}
|
||||
|
||||
.bg-indigo-700,
|
||||
.bg-blue-700,
|
||||
.bg-cyan-700 {
|
||||
background-color: #527887 !important;
|
||||
}
|
||||
|
||||
.bg-green-50 {
|
||||
background-color: #e1eee8 !important;
|
||||
}
|
||||
|
||||
.bg-green-100 {
|
||||
background-color: #d4e5dd !important;
|
||||
}
|
||||
|
||||
.bg-green-500,
|
||||
.bg-green-600 {
|
||||
background-color: #6f9688 !important;
|
||||
}
|
||||
|
||||
.bg-green-700 {
|
||||
background-color: #5f8377 !important;
|
||||
}
|
||||
|
||||
.bg-red-50 {
|
||||
background-color: #f1e2e5 !important;
|
||||
}
|
||||
|
||||
.bg-red-100 {
|
||||
background-color: #e8d3d7 !important;
|
||||
}
|
||||
|
||||
.bg-red-500,
|
||||
.bg-red-600 {
|
||||
background-color: #9b6a72 !important;
|
||||
}
|
||||
|
||||
.bg-red-700 {
|
||||
background-color: #895c63 !important;
|
||||
}
|
||||
|
||||
.bg-purple-50 {
|
||||
background-color: #e7e2ea !important;
|
||||
}
|
||||
|
||||
.bg-purple-100 {
|
||||
background-color: #ddd6e2 !important;
|
||||
}
|
||||
|
||||
.bg-purple-500,
|
||||
.bg-pink-500 {
|
||||
background-color: #8c8294 !important;
|
||||
}
|
||||
|
||||
.bg-purple-600,
|
||||
.bg-pink-600 {
|
||||
background-color: #7b7284 !important;
|
||||
}
|
||||
|
||||
.text-indigo-200,
|
||||
.text-blue-200 {
|
||||
color: #d8e8eb !important;
|
||||
}
|
||||
|
||||
.text-indigo-300,
|
||||
.text-blue-300 {
|
||||
color: #b8d4dc !important;
|
||||
}
|
||||
|
||||
.text-indigo-400,
|
||||
.text-blue-400,
|
||||
.text-cyan-400 {
|
||||
color: #8fb2bf !important;
|
||||
}
|
||||
|
||||
.text-indigo-500,
|
||||
.text-blue-500,
|
||||
.text-cyan-500 {
|
||||
color: #6f98a6 !important;
|
||||
}
|
||||
|
||||
.text-indigo-600,
|
||||
.text-blue-600,
|
||||
.text-cyan-600 {
|
||||
color: #5f8796 !important;
|
||||
}
|
||||
|
||||
.text-indigo-700,
|
||||
.text-blue-700 {
|
||||
color: #3f6a77 !important;
|
||||
}
|
||||
|
||||
.text-green-300,
|
||||
.text-green-400 {
|
||||
color: #b6d6ca !important;
|
||||
}
|
||||
|
||||
.text-green-500,
|
||||
.text-green-600,
|
||||
.text-green-700 {
|
||||
color: #5f8377 !important;
|
||||
}
|
||||
|
||||
.text-red-200,
|
||||
.text-red-300,
|
||||
.text-red-400 {
|
||||
color: #e5c5ca !important;
|
||||
}
|
||||
|
||||
.text-red-500,
|
||||
.text-red-600,
|
||||
.text-red-700 {
|
||||
color: #8b5962 !important;
|
||||
}
|
||||
|
||||
.text-purple-300,
|
||||
.text-purple-400 {
|
||||
color: #d4c8dc !important;
|
||||
}
|
||||
|
||||
.text-purple-500,
|
||||
.text-purple-600,
|
||||
.text-purple-700 {
|
||||
color: #6f6379 !important;
|
||||
}
|
||||
|
||||
.border-indigo-100,
|
||||
.border-blue-100 {
|
||||
border-color: #cfe1e4 !important;
|
||||
}
|
||||
|
||||
.border-indigo-300,
|
||||
.border-blue-300 {
|
||||
border-color: #9db6bd !important;
|
||||
}
|
||||
|
||||
.border-indigo-400,
|
||||
.border-indigo-500,
|
||||
.border-blue-500 {
|
||||
border-color: #8fb2bf !important;
|
||||
}
|
||||
|
||||
.border-indigo-600 {
|
||||
border-color: #5f8796 !important;
|
||||
}
|
||||
|
||||
.border-red-100 {
|
||||
border-color: #e8d3d7 !important;
|
||||
}
|
||||
|
||||
.border-red-200,
|
||||
.border-red-500 {
|
||||
border-color: #c9a4aa !important;
|
||||
}
|
||||
|
||||
.focus\:ring-indigo-500:focus,
|
||||
.focus\:ring-blue-500:focus,
|
||||
.focus\:ring-cyan-500:focus,
|
||||
.focus\:ring-purple-500:focus {
|
||||
--tw-ring-color: #8fb2bf !important;
|
||||
}
|
||||
|
||||
.focus\:border-indigo-500:focus,
|
||||
.focus\:border-cyan-500:focus {
|
||||
border-color: #8fb2bf !important;
|
||||
}
|
||||
|
||||
.hover\:bg-indigo-100:hover,
|
||||
.hover\:bg-blue-100:hover {
|
||||
background-color: #cfe1e4 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-indigo-500:hover,
|
||||
.hover\:bg-blue-500:hover,
|
||||
.hover\:bg-cyan-500:hover {
|
||||
background-color: #6f98a6 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-indigo-600:hover,
|
||||
.hover\:bg-blue-600:hover,
|
||||
.hover\:bg-cyan-600:hover {
|
||||
background-color: #527887 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-indigo-700:hover,
|
||||
.hover\:bg-blue-700:hover,
|
||||
.hover\:bg-cyan-700:hover {
|
||||
background-color: #466b78 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-green-100:hover {
|
||||
background-color: #d4e5dd !important;
|
||||
}
|
||||
|
||||
.hover\:bg-green-400:hover,
|
||||
.hover\:bg-green-600:hover,
|
||||
.hover\:bg-green-700:hover {
|
||||
background-color: #5f8377 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-red-100:hover {
|
||||
background-color: #e8d3d7 !important;
|
||||
}
|
||||
|
||||
.hover\:bg-red-400:hover,
|
||||
.hover\:bg-red-600:hover,
|
||||
.hover\:bg-red-700:hover {
|
||||
background-color: #895c63 !important;
|
||||
}
|
||||
|
||||
.hover\:border-indigo-500:hover {
|
||||
border-color: #8fb2bf !important;
|
||||
}
|
||||
|
||||
.from-indigo-500,
|
||||
.from-indigo-600,
|
||||
.from-cyan-500,
|
||||
.from-cyan-600 {
|
||||
--tw-gradient-from: #5f8796 var(--tw-gradient-from-position) !important;
|
||||
--tw-gradient-to: rgba(95, 135, 150, 0) var(--tw-gradient-to-position) !important;
|
||||
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to) !important;
|
||||
}
|
||||
|
||||
.via-purple-500,
|
||||
.via-purple-600 {
|
||||
--tw-gradient-to: rgba(140, 130, 148, 0) var(--tw-gradient-to-position) !important;
|
||||
--tw-gradient-stops:
|
||||
var(--tw-gradient-from),
|
||||
#8c8294 var(--tw-gradient-via-position),
|
||||
var(--tw-gradient-to) !important;
|
||||
}
|
||||
|
||||
.to-purple-500,
|
||||
.to-purple-600,
|
||||
.to-pink-500,
|
||||
.to-pink-600 {
|
||||
--tw-gradient-to: #6f9688 var(--tw-gradient-to-position) !important;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<transition-group
|
||||
name="alert-fade"
|
||||
tag="div"
|
||||
class="fixed top-4 left-4 z-50 w-full sm:max-w-sm md:max-w-md space-y-4 px-4 sm:px-0"
|
||||
>
|
||||
<div
|
||||
v-for="alert in alerts"
|
||||
:key="alert.id"
|
||||
:role="alert.type === 'error' ? 'alert' : 'status'"
|
||||
:aria-live="alert.type === 'error' ? 'assertive' : 'polite'"
|
||||
:class="[
|
||||
'w-full rounded-[30px] shadow-xl overflow-hidden',
|
||||
'bg-gradient-to-r',
|
||||
gradientClasses[alert.type]
|
||||
]"
|
||||
>
|
||||
<div class="p-4">
|
||||
<div class="flex items-start">
|
||||
<div class="flex-shrink-0">
|
||||
<component :is="alertIcons[alert.type]" class="h-6 w-6 text-white" />
|
||||
</div>
|
||||
<div class="ml-3 flex-1 pt-0.5">
|
||||
<p class="text-sm font-medium text-white">{{ alert.message }}</p>
|
||||
</div>
|
||||
<div class="ml-4 flex-shrink-0 flex">
|
||||
<button
|
||||
type="button"
|
||||
@click="removeAlert(alert.id)"
|
||||
class="inline-flex h-11 w-11 items-center justify-center rounded-lg text-white transition-colors duration-200 hover:bg-white/10 hover:text-gray-100 focus:outline-none focus:ring-2 focus:ring-white"
|
||||
>
|
||||
<span class="sr-only">{{ t('common.close') }}</span>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="h-1 bg-white bg-opacity-25">
|
||||
<div
|
||||
class="h-full bg-white transition-all duration-100 ease-out"
|
||||
:style="{ width: `${alert.progress}%` }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</transition-group>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { CheckCircle, AlertTriangle, AlertCircle, Info, X } from 'lucide-vue-next'
|
||||
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const alertStore = useAlertStore()
|
||||
const { alerts } = storeToRefs(alertStore)
|
||||
const { removeAlert } = alertStore
|
||||
|
||||
const gradientClasses = {
|
||||
success: 'from-[#6f9688] to-[#5f8377]',
|
||||
error: 'from-[#9b6a72] to-[#895c63]',
|
||||
warning: 'from-[#b2a16f] to-[#9b8b5e]',
|
||||
info: 'from-[#5f8796] to-[#527887]'
|
||||
}
|
||||
|
||||
const alertIcons = {
|
||||
success: CheckCircle,
|
||||
error: AlertTriangle,
|
||||
warning: AlertCircle,
|
||||
info: Info
|
||||
}
|
||||
|
||||
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.alert-fade-enter-active,
|
||||
.alert-fade-leave-active {
|
||||
transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
|
||||
}
|
||||
.alert-fade-enter-from,
|
||||
.alert-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateX(-50px) scale(0.95);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,84 @@
|
||||
<template>
|
||||
<button
|
||||
:type="type"
|
||||
:disabled="disabled || loading"
|
||||
@click="$emit('click', $event)"
|
||||
class="inline-flex items-center justify-center rounded-[30px] px-4 py-2 font-medium shadow-sm transition-all duration-200 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:shadow-sm"
|
||||
:class="[
|
||||
sizeClasses,
|
||||
variantClasses,
|
||||
loading ? 'cursor-wait' : '',
|
||||
disabled ? 'pointer-events-none' : ''
|
||||
]"
|
||||
>
|
||||
<slot name="icon" v-if="$slots.icon && !loading"></slot>
|
||||
<div v-if="loading" class="animate-spin rounded-full h-4 w-4 border-2 border-current border-t-transparent mr-2"></div>
|
||||
<slot></slot>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useInjectedDarkMode } from '@/composables'
|
||||
|
||||
interface Props {
|
||||
variant?: 'primary' | 'secondary' | 'danger' | 'success' | 'outline'
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
type?: 'button' | 'submit' | 'reset'
|
||||
disabled?: boolean
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
variant: 'primary',
|
||||
size: 'md',
|
||||
type: 'button',
|
||||
disabled: false,
|
||||
loading: false
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
click: [event: MouseEvent]
|
||||
}>()
|
||||
|
||||
const isDarkMode = useInjectedDarkMode()
|
||||
|
||||
const sizeClasses = computed(() => {
|
||||
const sizes = {
|
||||
sm: 'min-h-11 px-3 py-2 text-sm sm:min-h-0 sm:py-1.5',
|
||||
md: 'min-h-11 px-4 py-2 text-sm',
|
||||
lg: 'min-h-12 px-6 py-3 text-base'
|
||||
}
|
||||
return sizes[props.size]
|
||||
})
|
||||
|
||||
const variantClasses = computed(() => {
|
||||
const baseClasses = 'focus:ring-2 focus:ring-offset-2'
|
||||
|
||||
if (props.variant === 'primary') {
|
||||
return `${baseClasses} bg-[#5f8796] text-white shadow-[#9fb8bf]/35 hover:bg-[#527887] focus:ring-[#8fb2bf]`
|
||||
}
|
||||
|
||||
if (props.variant === 'secondary') {
|
||||
return isDarkMode.value
|
||||
? `${baseClasses} border border-[#40545c] bg-[#263941] text-[#d8e3e5] hover:border-[#7199a8] hover:bg-[#2d4751] focus:ring-[#7199a8]`
|
||||
: `${baseClasses} border border-[#c8d8dc] bg-[#edf4f5] text-[#415d66] hover:border-[#9db6bd] hover:bg-[#e2ecee] focus:ring-[#8fb2bf]`
|
||||
}
|
||||
|
||||
if (props.variant === 'danger') {
|
||||
return `${baseClasses} bg-[#dc2626] text-white shadow-[#f87171]/35 hover:bg-[#b91c1c] focus:ring-[#ef4444]`
|
||||
}
|
||||
|
||||
if (props.variant === 'success') {
|
||||
return `${baseClasses} bg-[#6f9688] text-white shadow-[#aac4ba]/35 hover:bg-[#5f8377] focus:ring-[#92b3a7]`
|
||||
}
|
||||
|
||||
if (props.variant === 'outline') {
|
||||
return isDarkMode.value
|
||||
? `${baseClasses} border border-[#40545c] text-[#d8e3e5] hover:border-[#7199a8] hover:bg-[#263941] focus:ring-[#7199a8]`
|
||||
: `${baseClasses} border border-[#c8d8dc] text-[#415d66] hover:border-[#9db6bd] hover:bg-[#edf4f5] focus:ring-[#8fb2bf]`
|
||||
}
|
||||
|
||||
return ''
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,174 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="modal" appear>
|
||||
<div
|
||||
v-if="show"
|
||||
class="fixed inset-0 z-50 overflow-y-auto"
|
||||
@click="handleBackdropClick"
|
||||
>
|
||||
<div class="fixed inset-0 bg-black/50 transition-opacity" aria-hidden="true"></div>
|
||||
|
||||
<div class="flex min-h-full items-center justify-center p-3 sm:p-4">
|
||||
<div
|
||||
ref="modalRef"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="title || t('common.dialog')"
|
||||
tabindex="-1"
|
||||
class="relative flex max-h-[calc(100dvh-1.5rem)] transform flex-col overflow-hidden rounded-[24px] shadow-xl transition-all sm:max-h-[calc(100dvh-2rem)] sm:rounded-[30px]"
|
||||
:class="[sizeClasses, isDarkMode ? 'bg-gray-800' : 'bg-white']"
|
||||
@click.stop
|
||||
@keydown="handleKeydown"
|
||||
>
|
||||
<div
|
||||
v-if="$slots.header || title"
|
||||
class="flex shrink-0 items-center justify-between border-b px-3 py-3 sm:px-6 sm:py-4"
|
||||
:class="[isDarkMode ? 'border-gray-700' : 'border-gray-200']"
|
||||
>
|
||||
<slot name="header">
|
||||
<h3 class="text-lg font-medium" :class="[isDarkMode ? 'text-white' : 'text-gray-900']">
|
||||
{{ title }}
|
||||
</h3>
|
||||
</slot>
|
||||
<button
|
||||
v-if="closable"
|
||||
type="button"
|
||||
class="flex h-11 w-11 shrink-0 items-center justify-center rounded-[30px] transition-colors"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-gray-300 hover:bg-gray-700 hover:text-white'
|
||||
: 'text-gray-600 hover:bg-gray-100 hover:text-gray-800'
|
||||
]"
|
||||
:aria-label="t('common.close')"
|
||||
:title="t('common.close')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="h-5 w-5" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto px-3 py-3 sm:px-6 sm:py-4" tabindex="0">
|
||||
<slot></slot>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="$slots.footer"
|
||||
class="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t px-3 py-3 sm:px-6 sm:py-4"
|
||||
:class="[isDarkMode ? 'border-gray-700 bg-gray-900/50' : 'border-gray-200 bg-gray-50']"
|
||||
>
|
||||
<slot name="footer"></slot>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, nextTick, ref, watch } from 'vue'
|
||||
import { X } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface Props {
|
||||
show: boolean
|
||||
title?: string
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
closable?: boolean
|
||||
closeOnBackdrop?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
size: 'md',
|
||||
closable: true,
|
||||
closeOnBackdrop: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const modalRef = ref<HTMLElement>()
|
||||
let returnFocusElement: HTMLElement | null = null
|
||||
|
||||
const sizeClasses = computed(() => ({
|
||||
sm: 'max-w-md w-full',
|
||||
md: 'max-w-lg w-full',
|
||||
lg: 'max-w-2xl w-full',
|
||||
xl: 'max-w-4xl w-full'
|
||||
})[props.size])
|
||||
|
||||
const focusableSelector =
|
||||
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
|
||||
|
||||
const handleBackdropClick = () => {
|
||||
if (props.closeOnBackdrop) emit('close')
|
||||
}
|
||||
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && props.closable) {
|
||||
event.preventDefault()
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
if (event.key !== 'Tab' || !modalRef.value) return
|
||||
const focusable = [...modalRef.value.querySelectorAll<HTMLElement>(focusableSelector)]
|
||||
if (!focusable.length) {
|
||||
event.preventDefault()
|
||||
modalRef.value.focus()
|
||||
return
|
||||
}
|
||||
const first = focusable[0]
|
||||
const last = focusable[focusable.length - 1]
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault()
|
||||
last.focus()
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.show,
|
||||
async (show) => {
|
||||
if (show) {
|
||||
returnFocusElement = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
await nextTick()
|
||||
const first = modalRef.value?.querySelector<HTMLElement>(focusableSelector)
|
||||
;(first || modalRef.value)?.focus()
|
||||
} else {
|
||||
await nextTick()
|
||||
returnFocusElement?.focus()
|
||||
returnFocusElement = null
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.modal-enter-active,
|
||||
.modal-leave-active {
|
||||
transition: opacity 0.18s ease;
|
||||
}
|
||||
.modal-enter-active .relative,
|
||||
.modal-leave-active .relative {
|
||||
transition: transform 0.18s ease, opacity 0.18s ease;
|
||||
}
|
||||
.modal-enter-from,
|
||||
.modal-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
.modal-enter-from .relative,
|
||||
.modal-leave-to .relative {
|
||||
opacity: 0;
|
||||
transform: scale(0.985) translateY(-8px);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.modal-enter-active,
|
||||
.modal-leave-active,
|
||||
.modal-enter-active .relative,
|
||||
.modal-leave-active .relative {
|
||||
transition-duration: 0.01ms;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,154 @@
|
||||
<template>
|
||||
<div class="border-progress-container" ref="container">
|
||||
<canvas ref="canvas" class="border-progress-canvas"></canvas>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
|
||||
const props = defineProps<{
|
||||
progress: number;
|
||||
}>();
|
||||
|
||||
const container = ref<HTMLDivElement | null>(null);
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
let ctx: CanvasRenderingContext2D | null = null;
|
||||
|
||||
const drawProgress = () => {
|
||||
if (!ctx || !canvas.value || !container.value) return;
|
||||
|
||||
const width = container.value.clientWidth;
|
||||
const height = container.value.clientHeight;
|
||||
canvas.value.width = width;
|
||||
canvas.value.height = height;
|
||||
|
||||
const borderWidth = 4; // 边框宽度
|
||||
const cornerRadius = 8; // 拐角半径
|
||||
ctx.lineWidth = borderWidth;
|
||||
|
||||
// 创建渐变
|
||||
const gradient = ctx.createLinearGradient(0, 0, width, height);
|
||||
gradient.addColorStop(0, '#5f8796');
|
||||
gradient.addColorStop(0.5, '#6f9688');
|
||||
gradient.addColorStop(1, '#8c8294');
|
||||
|
||||
// 绘制背景
|
||||
ctx.strokeStyle = 'rgba(229, 231, 235, 0.2)'; // 淡灰色半透明
|
||||
drawRoundedRect(ctx, borderWidth / 2, borderWidth / 2, width - borderWidth, height - borderWidth, cornerRadius);
|
||||
ctx.stroke();
|
||||
|
||||
// 计算进度
|
||||
const totalLength = (width + height) * 2 - 8 * cornerRadius + 2 * Math.PI * cornerRadius;
|
||||
const progressLength = (totalLength * props.progress) / 100;
|
||||
|
||||
// 绘制进度
|
||||
ctx.strokeStyle = gradient;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.beginPath();
|
||||
|
||||
let remainingLength = progressLength;
|
||||
const halfBorder = borderWidth / 2;
|
||||
const innerWidth = width - borderWidth;
|
||||
const innerHeight = height - borderWidth;
|
||||
|
||||
// 上边
|
||||
if (remainingLength > 0) {
|
||||
const topLength = Math.min(innerWidth - 2 * cornerRadius, remainingLength);
|
||||
ctx.moveTo(cornerRadius + halfBorder, halfBorder);
|
||||
ctx.lineTo(topLength + cornerRadius + halfBorder, halfBorder);
|
||||
remainingLength -= topLength;
|
||||
}
|
||||
|
||||
// 右上角
|
||||
if (remainingLength > 0) {
|
||||
const angle = Math.min(Math.PI / 2, remainingLength / cornerRadius);
|
||||
ctx.arc(innerWidth - cornerRadius + halfBorder, cornerRadius + halfBorder, cornerRadius, -Math.PI / 2, angle - Math.PI / 2, false);
|
||||
remainingLength -= angle * cornerRadius;
|
||||
}
|
||||
|
||||
// 右边
|
||||
if (remainingLength > 0) {
|
||||
const rightLength = Math.min(innerHeight - 2 * cornerRadius, remainingLength);
|
||||
ctx.lineTo(innerWidth + halfBorder, rightLength + cornerRadius + halfBorder);
|
||||
remainingLength -= rightLength;
|
||||
}
|
||||
|
||||
// 右下角
|
||||
if (remainingLength > 0) {
|
||||
const angle = Math.min(Math.PI / 2, remainingLength / cornerRadius);
|
||||
ctx.arc(innerWidth - cornerRadius + halfBorder, innerHeight - cornerRadius + halfBorder, cornerRadius, 0, angle, false);
|
||||
remainingLength -= angle * cornerRadius;
|
||||
}
|
||||
|
||||
// 下边
|
||||
if (remainingLength > 0) {
|
||||
const bottomLength = Math.min(innerWidth - 2 * cornerRadius, remainingLength);
|
||||
ctx.lineTo(innerWidth - bottomLength - cornerRadius + halfBorder, innerHeight + halfBorder);
|
||||
remainingLength -= bottomLength;
|
||||
}
|
||||
|
||||
// 左下角
|
||||
if (remainingLength > 0) {
|
||||
const angle = Math.min(Math.PI / 2, remainingLength / cornerRadius);
|
||||
ctx.arc(cornerRadius + halfBorder, innerHeight - cornerRadius + halfBorder, cornerRadius, Math.PI / 2, Math.PI / 2 + angle, false);
|
||||
remainingLength -= angle * cornerRadius;
|
||||
}
|
||||
|
||||
// 左边
|
||||
if (remainingLength > 0) {
|
||||
const leftLength = Math.min(innerHeight - 2 * cornerRadius, remainingLength);
|
||||
ctx.lineTo(halfBorder, innerHeight - leftLength - cornerRadius + halfBorder);
|
||||
remainingLength -= leftLength;
|
||||
}
|
||||
|
||||
// 左上角
|
||||
if (remainingLength > 0) {
|
||||
const angle = Math.min(Math.PI / 2, remainingLength / cornerRadius);
|
||||
ctx.arc(cornerRadius + halfBorder, cornerRadius + halfBorder, cornerRadius, Math.PI, Math.PI + angle, false);
|
||||
}
|
||||
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
function drawRoundedRect(ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + radius, y);
|
||||
ctx.lineTo(x + width - radius, y);
|
||||
ctx.arcTo(x + width, y, x + width, y + radius, radius);
|
||||
ctx.lineTo(x + width, y + height - radius);
|
||||
ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
|
||||
ctx.lineTo(x + radius, y + height);
|
||||
ctx.arcTo(x, y + height, x, y + height - radius, radius);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.arcTo(x, y, x + radius, y, radius);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (canvas.value) {
|
||||
ctx = canvas.value.getContext('2d');
|
||||
drawProgress();
|
||||
}
|
||||
});
|
||||
|
||||
watch(() => props.progress, drawProgress);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.border-progress-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.border-progress-canvas {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,195 @@
|
||||
<template>
|
||||
<transition name="fade">
|
||||
<div
|
||||
v-if="visible"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
|
||||
@click.self="$emit('close')"
|
||||
>
|
||||
<div
|
||||
class="flex max-h-[88vh] w-full max-w-3xl flex-col overflow-hidden rounded-[24px] bg-opacity-70 p-4 shadow-2xl transform transition-all duration-200 ease-out backdrop-filter backdrop-blur-lg sm:mx-4 sm:rounded-[30px] sm:p-6"
|
||||
:class="[isDarkMode ? 'bg-gray-800' : 'bg-white']"
|
||||
>
|
||||
<div class="flex justify-between items-center mb-4 flex-shrink-0">
|
||||
<h3 class="text-xl font-bold sm:text-2xl" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">
|
||||
{{ t('contentPreview.title') }}
|
||||
</h3>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
@click="$emit('copy-content')"
|
||||
class="inline-flex items-center gap-2 rounded-[30px] px-3 py-1.5 text-sm font-medium transition duration-200 sm:px-4"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white'
|
||||
: 'bg-gray-100 hover:bg-gray-200 text-gray-700 hover:text-gray-900'
|
||||
]"
|
||||
>
|
||||
<CopyIcon class="w-4 h-4" />
|
||||
{{ t('common.copy') }}
|
||||
</button>
|
||||
<button
|
||||
@click="$emit('close')"
|
||||
class="rounded-[30px] p-1.5 transition duration-200 hover:bg-opacity-10"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-gray-400 hover:text-white hover:bg-white'
|
||||
: 'text-gray-500 hover:text-gray-900 hover:bg-black'
|
||||
]"
|
||||
>
|
||||
<XIcon class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 overflow-y-auto custom-scrollbar">
|
||||
<div
|
||||
class="prose max-w-none rounded-[20px] p-4 break-words overflow-wrap-anywhere sm:rounded-[24px] sm:p-6"
|
||||
:class="[isDarkMode ? 'prose-invert bg-gray-900 bg-opacity-50' : 'bg-gray-50']"
|
||||
v-html="renderedContent"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { CopyIcon, XIcon } from 'lucide-vue-next'
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
renderedContent: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
close: []
|
||||
'copy-content': []
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
defineEmits<Emits>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* 自定义滚动条样式 */
|
||||
.custom-scrollbar {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(156, 163, 175, 0.3) rgba(243, 244, 246, 0.5);
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: rgba(243, 244, 246, 0.5);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(156, 163, 175, 0.5);
|
||||
border-radius: 3px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(156, 163, 175, 0.7);
|
||||
}
|
||||
|
||||
/* 深色模式下的滚动条样式 */
|
||||
:deep([class*='dark']) .custom-scrollbar {
|
||||
scrollbar-color: rgba(75, 85, 99, 0.5) rgba(31, 41, 55, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: rgba(31, 41, 55, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(75, 85, 99, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(75, 85, 99, 0.7);
|
||||
}
|
||||
|
||||
/* 确保滚动容器有背景色 */
|
||||
.custom-scrollbar {
|
||||
background: inherit;
|
||||
}
|
||||
|
||||
/* 文本换行相关样式 */
|
||||
.break-words {
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.overflow-wrap-anywhere {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* 添加 Markdown 样式 */
|
||||
:deep(.prose) {
|
||||
text-align: left;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
:deep(.prose h1),
|
||||
:deep(.prose h2),
|
||||
:deep(.prose h3),
|
||||
:deep(.prose h4),
|
||||
:deep(.prose h5),
|
||||
:deep(.prose h6) {
|
||||
color: rgb(79, 70, 229);
|
||||
/* text-indigo-600 */
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
:deep(.prose p),
|
||||
:deep(.prose div),
|
||||
:deep(.prose span),
|
||||
:deep(.prose code),
|
||||
:deep(.prose pre) {
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
:deep(.prose pre) {
|
||||
white-space: pre-wrap;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
:deep(.prose code) {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:deep(.prose h1),
|
||||
:deep(.prose h2),
|
||||
:deep(.prose h3),
|
||||
:deep(.prose h4),
|
||||
:deep(.prose h5),
|
||||
:deep(.prose h6) {
|
||||
color: rgb(129, 140, 248);
|
||||
/* text-indigo-400 */
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,130 @@
|
||||
<template>
|
||||
<nav
|
||||
class="mt-4 flex flex-col gap-3 border-t px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-6"
|
||||
:class="[isDarkMode ? 'border-[#31454d]' : 'border-[#c8d7da]']"
|
||||
:aria-label="t('components.pagination.navigation')"
|
||||
>
|
||||
<div class="text-sm" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']">
|
||||
{{ t('components.pagination.range', { start: rangeStart, end: rangeEnd, total }) }}
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 sm:flex sm:flex-wrap">
|
||||
<select
|
||||
:value="pageSize"
|
||||
class="col-span-3 min-h-11 rounded-[30px] border px-3 text-sm shadow-sm transition-colors sm:col-auto lg:min-h-9"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'border-[#40545c] bg-[#263941] text-[#d8e3e5] hover:border-[#7199a8]'
|
||||
: 'border-[#c8d8dc] bg-[#edf4f5] text-[#415d66] hover:border-[#9db6bd]'
|
||||
]"
|
||||
:aria-label="t('components.pagination.pageSize')"
|
||||
@change="$emit('page-size-change', Number(($event.target as HTMLSelectElement).value))"
|
||||
>
|
||||
<option v-for="size in pageSizeOptions" :key="size" :value="size">
|
||||
{{ t('components.pagination.perPage', { size }) }}
|
||||
</option>
|
||||
</select>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
:disabled="currentPage === 1"
|
||||
class="inline-flex min-h-11 items-center justify-center rounded-[30px] px-3 py-1.5 shadow-sm transition-all duration-200 hover:shadow-md lg:min-h-9"
|
||||
:class="buttonClass(currentPage === 1)"
|
||||
@click="$emit('page-change', currentPage - 1)"
|
||||
>
|
||||
<ChevronLeftIcon class="h-4 w-4" aria-hidden="true" />
|
||||
<span class="max-[359px]:sr-only">{{ t('common.previous') }}</span>
|
||||
</button>
|
||||
|
||||
<span class="text-center text-sm font-medium sm:hidden" :class="[isDarkMode ? 'text-gray-200' : 'text-gray-700']">
|
||||
{{ currentPage }} / {{ totalPages }}
|
||||
</span>
|
||||
|
||||
<div class="hidden items-center gap-1 sm:flex">
|
||||
<template v-for="pageNum in displayedPages" :key="pageNum">
|
||||
<button
|
||||
v-if="pageNum !== '...'"
|
||||
type="button"
|
||||
class="inline-flex min-h-11 min-w-11 items-center justify-center rounded-[30px] px-3 py-1.5 shadow-sm transition-all duration-200 hover:shadow-md lg:min-h-9 lg:min-w-9"
|
||||
:class="[
|
||||
currentPage === pageNum
|
||||
? 'bg-[#5f8796] text-white shadow-[#9fb8bf]/35'
|
||||
: isDarkMode
|
||||
? 'bg-[#263941] text-[#d8e3e5] hover:bg-[#2d4751]'
|
||||
: 'bg-[#edf4f5] text-[#415d66] hover:bg-[#e2ecee]'
|
||||
]"
|
||||
:aria-label="t('components.pagination.goToPage', { page: pageNum })"
|
||||
:aria-current="currentPage === pageNum ? 'page' : undefined"
|
||||
@click="$emit('page-change', pageNum as number)"
|
||||
>
|
||||
{{ pageNum }}
|
||||
</button>
|
||||
<span v-else class="px-1" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']">…</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
:disabled="currentPage >= totalPages"
|
||||
class="inline-flex min-h-11 items-center justify-center rounded-[30px] px-3 py-1.5 shadow-sm transition-all duration-200 hover:shadow-md lg:min-h-9"
|
||||
:class="buttonClass(currentPage >= totalPages)"
|
||||
@click="$emit('page-change', currentPage + 1)"
|
||||
>
|
||||
<span class="max-[359px]:sr-only">{{ t('common.next') }}</span>
|
||||
<ChevronRightIcon class="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, type Ref } from 'vue'
|
||||
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface Props {
|
||||
currentPage: number
|
||||
pageSize: number
|
||||
total: number
|
||||
pageSizeOptions?: number[]
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
pageSizeOptions: () => [5, 10, 20, 50, 100]
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
'page-change': [page: number]
|
||||
'page-size-change': [size: number]
|
||||
}>()
|
||||
|
||||
const isDarkMode = inject<Ref<boolean>>('isDarkMode', computed(() => false))
|
||||
const { t } = useI18n()
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(props.total / props.pageSize)))
|
||||
const rangeStart = computed(() => (props.total ? (props.currentPage - 1) * props.pageSize + 1 : 0))
|
||||
const rangeEnd = computed(() => Math.min(props.currentPage * props.pageSize, props.total))
|
||||
|
||||
const displayedPages = computed(() => {
|
||||
const current = props.currentPage
|
||||
const total = totalPages.value
|
||||
const pages: (number | string)[] = [1]
|
||||
const left = Math.max(2, current - 2)
|
||||
const right = Math.min(total - 1, current + 2)
|
||||
if (left > 2) pages.push('...')
|
||||
for (let i = left; i <= right; i++) pages.push(i)
|
||||
if (right < total - 1) pages.push('...')
|
||||
if (total > 1) pages.push(total)
|
||||
return pages
|
||||
})
|
||||
|
||||
const buttonClass = (disabled: boolean) => {
|
||||
if (isDarkMode.value) {
|
||||
return disabled
|
||||
? 'cursor-not-allowed bg-[#223039] text-[#71878d]'
|
||||
: 'bg-[#263941] text-[#d8e3e5] hover:bg-[#2d4751]'
|
||||
}
|
||||
return disabled
|
||||
? 'cursor-not-allowed bg-[#e8eeee] text-[#7d8d91]'
|
||||
: 'bg-[#edf4f5] text-[#415d66] hover:bg-[#e2ecee]'
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,67 @@
|
||||
<template>
|
||||
<div
|
||||
class="data-table-2026 theme-2026-card theme-2026-card-hover overflow-hidden rounded-[30px] shadow-md transition-all duration-300 hover:-translate-y-0.5 hover:shadow-lg"
|
||||
>
|
||||
<div
|
||||
class="border-b px-6 py-4"
|
||||
:class="[isDarkMode ? 'border-gray-700/80' : 'border-[#d9e4e6]']"
|
||||
>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h3 class="text-lg font-medium" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<div v-if="slots.actions" class="flex shrink-0 flex-wrap items-center gap-2">
|
||||
<slot name="actions"></slot>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="slots.toolbar" class="mt-4">
|
||||
<slot name="toolbar"></slot>
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-x-auto" tabindex="0" role="region" :aria-label="title">
|
||||
<table
|
||||
class="divide-y"
|
||||
:class="[tableClass, isDarkMode ? 'divide-[#31454d]' : 'divide-[#d7e3e5]']"
|
||||
>
|
||||
<caption class="sr-only">{{ title }}</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
v-for="header in headers"
|
||||
:key="header"
|
||||
scope="col"
|
||||
class="px-6 py-3.5 text-left text-xs font-medium uppercase tracking-wider"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
>
|
||||
{{ header }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody
|
||||
class="divide-y"
|
||||
:class="[isDarkMode ? 'divide-[#31454d]/70' : 'divide-[#d7e3e5]/80']"
|
||||
>
|
||||
<slot name="body"></slot>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<slot name="footer"></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject, useSlots } from 'vue'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
headers: string[]
|
||||
tableClass?: string
|
||||
}
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
tableClass: 'min-w-full'
|
||||
})
|
||||
|
||||
const slots = useSlots()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
</script>
|
||||
@@ -0,0 +1,112 @@
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<label for="send-expiration-value" class="block text-sm font-medium" :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'">
|
||||
{{ t('send.expiration.label') }}
|
||||
</label>
|
||||
|
||||
<div v-if="expirationMethod !== 'forever'" class="grid grid-cols-[2.75rem_minmax(0,1fr)_2.75rem] gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-11 w-11 items-center justify-center rounded-xl border text-xl font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:class="controlClass"
|
||||
:disabled="numericValue <= 1"
|
||||
:aria-label="t('send.expiration.decrement')"
|
||||
@click="incrementValue(-1)"
|
||||
>
|
||||
<MinusIcon class="h-5 w-5" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<input
|
||||
id="send-expiration-value"
|
||||
:value="expirationValue"
|
||||
type="number"
|
||||
min="1"
|
||||
inputmode="numeric"
|
||||
class="h-11 min-w-0 rounded-xl border px-3 text-center font-semibold tabular-nums outline-none transition-colors focus:ring-2 focus:ring-indigo-500 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
|
||||
:class="controlClass"
|
||||
:placeholder="getPlaceholder()"
|
||||
@input="updateValue"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-11 w-11 items-center justify-center rounded-xl border text-xl font-semibold transition-colors"
|
||||
:class="controlClass"
|
||||
:aria-label="t('send.expiration.increment')"
|
||||
@click="incrementValue(1)"
|
||||
>
|
||||
<PlusIcon class="h-5 w-5" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label class="block">
|
||||
<span class="sr-only">{{ t('send.expiration.method') }}</span>
|
||||
<div class="relative">
|
||||
<select
|
||||
:value="expirationMethod"
|
||||
class="min-h-11 w-full cursor-pointer appearance-none rounded-xl border py-2.5 pl-4 pr-11 text-sm font-medium outline-none transition-colors focus:ring-2 focus:ring-indigo-500"
|
||||
:class="controlClass"
|
||||
:aria-label="t('send.expiration.method')"
|
||||
@change="updateMethod"
|
||||
>
|
||||
<option v-for="option in options" :key="option.value" :value="option.value">
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
<ChevronDownIcon class="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70" aria-hidden="true" />
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject } from 'vue'
|
||||
import { ChevronDownIcon, MinusIcon, PlusIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Props {
|
||||
expirationMethod: string
|
||||
expirationValue: string
|
||||
options: Array<{ label: string; value: string }>
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
'update:expirationMethod': [value: string]
|
||||
'update:expirationValue': [value: string]
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
|
||||
const numericValue = computed(() => Math.max(1, Number.parseInt(props.expirationValue) || 1))
|
||||
const controlClass = computed(() =>
|
||||
isDarkMode
|
||||
? 'border-gray-600 bg-gray-800/70 text-gray-100 hover:border-gray-500'
|
||||
: 'border-gray-300 bg-white text-gray-900 hover:border-gray-400'
|
||||
)
|
||||
|
||||
const updateMethod = (event: Event) => {
|
||||
emit('update:expirationMethod', (event.target as HTMLSelectElement).value)
|
||||
}
|
||||
|
||||
const updateValue = (event: Event) => {
|
||||
emit('update:expirationValue', (event.target as HTMLInputElement).value)
|
||||
}
|
||||
|
||||
const incrementValue = (delta: number) => {
|
||||
emit('update:expirationValue', Math.max(1, numericValue.value + delta).toString())
|
||||
}
|
||||
|
||||
const getPlaceholder = () => {
|
||||
switch (props.expirationMethod) {
|
||||
case 'count': return t('send.expiration.placeholders.count')
|
||||
case 'minute': return t('send.expiration.placeholders.minutes')
|
||||
case 'hour': return t('send.expiration.placeholders.hours')
|
||||
case 'day': return t('send.expiration.placeholders.days')
|
||||
default: return t('send.expiration.placeholders.default')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,153 @@
|
||||
<template>
|
||||
<transition name="fade">
|
||||
<div
|
||||
v-if="visible"
|
||||
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
|
||||
@click.self="$emit('close')"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-md mx-3 overflow-hidden rounded-[24px] shadow-2xl transform transition-all duration-200 ease-out backdrop-filter backdrop-blur-lg sm:mx-4 sm:rounded-[30px]"
|
||||
:class="[isDarkMode ? 'bg-gray-800 bg-opacity-70' : 'bg-white bg-opacity-95']"
|
||||
>
|
||||
<h3
|
||||
class="mb-4 truncate px-4 pt-4 text-xl font-bold sm:mb-5 sm:px-6 sm:pt-6 sm:text-2xl"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-gray-800']"
|
||||
>
|
||||
{{ t('fileDetail.title') }}
|
||||
</h3>
|
||||
<div class="space-y-3 px-4 sm:space-y-4 sm:px-6" v-if="record">
|
||||
<div class="flex items-center">
|
||||
<FileIcon
|
||||
class="w-6 h-6 mr-3 flex-shrink-0"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
/>
|
||||
<p
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
|
||||
class="truncate flex-grow"
|
||||
>
|
||||
<span class="font-medium">{{ t('fileRecord.filename') }}:</span>{{ record.filename }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<CalendarIcon
|
||||
class="w-6 h-6 mr-3 flex-shrink-0"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
/>
|
||||
<p
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
|
||||
class="truncate flex-grow"
|
||||
>
|
||||
<span class="font-medium">{{ t('fileRecord.date') }}:</span>{{ record.date }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<HardDriveIcon
|
||||
class="w-6 h-6 mr-3 flex-shrink-0"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
/>
|
||||
<p
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
|
||||
class="truncate flex-grow"
|
||||
>
|
||||
<span class="font-medium">{{ t('fileRecord.size') }}:</span>{{ record.size }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<DownloadIcon
|
||||
class="w-6 h-6 mr-3"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
/>
|
||||
<p :class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']">
|
||||
<span class="font-medium">{{ t('fileDetail.content') }}:</span>
|
||||
</p>
|
||||
<div v-if="record.filename === 'Text'" class="ml-2">
|
||||
<button
|
||||
@click="$emit('preview-content')"
|
||||
class="rounded-[30px] bg-indigo-600 px-4 py-2 text-white transition duration-200 hover:bg-indigo-700"
|
||||
>
|
||||
{{ t('fileDetail.previewContent') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else>
|
||||
<a
|
||||
:href="getDownloadUrl(record)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="rounded-[30px] bg-indigo-600 px-4 py-2 text-white transition duration-200 hover:bg-indigo-700"
|
||||
>
|
||||
{{ t('fileDetail.download') }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 flex flex-col items-center px-4 sm:mt-6 sm:px-6" v-if="record">
|
||||
<h4
|
||||
class="text-lg font-semibold mb-3"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-gray-800']"
|
||||
>
|
||||
{{ t('fileDetail.qrCode') }}
|
||||
</h4>
|
||||
<div class="bg-white p-2 rounded-lg shadow-md">
|
||||
<QRCode :value="getQRCodeValue(record)" :size="128" level="M" />
|
||||
</div>
|
||||
<p class="mt-2 text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">
|
||||
{{ t('fileDetail.scanQrCode') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
@click="$emit('close')"
|
||||
class="mt-6 w-full rounded-[30px] bg-gradient-to-r from-indigo-500 to-purple-600 px-5 py-3 font-medium text-white transition duration-200 transform hover:scale-[1.01] hover:from-indigo-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 sm:mt-8 sm:px-6"
|
||||
>
|
||||
{{ t('common.close') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent, inject } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { FileIcon, CalendarIcon, HardDriveIcon, DownloadIcon } from 'lucide-vue-next'
|
||||
|
||||
import type { ReceivedFileRecord } from '@/types'
|
||||
import { buildDownloadUrl, buildReceivedRecordQrValue } from '@/utils/share-url'
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
record: ReceivedFileRecord | null
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
close: []
|
||||
'preview-content': []
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
defineEmits<Emits>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const QRCode = defineAsyncComponent(() => import('qrcode.vue'))
|
||||
|
||||
const getDownloadUrl = (record: ReceivedFileRecord) => {
|
||||
return buildDownloadUrl(record.downloadUrl)
|
||||
}
|
||||
|
||||
const getQRCodeValue = (record: ReceivedFileRecord) => {
|
||||
return buildReceivedRecordQrValue(record)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,75 @@
|
||||
<template>
|
||||
<div class="space-y-2 group">
|
||||
<label
|
||||
class="text-sm font-medium flex items-center space-x-2 transition-colors duration-200"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-gray-300 group-focus-within:text-indigo-400'
|
||||
: 'text-gray-700 group-focus-within:text-indigo-600'
|
||||
]"
|
||||
>
|
||||
<span>{{ label }}</span>
|
||||
<div
|
||||
class="h-px flex-1 transition-colors duration-200"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-gray-700 group-focus-within:bg-indigo-500/50'
|
||||
: 'bg-gray-200 group-focus-within:bg-indigo-500/30'
|
||||
]"
|
||||
></div>
|
||||
</label>
|
||||
<div class="relative rounded-lg shadow-sm">
|
||||
<input
|
||||
:type="type"
|
||||
:value="modelValue ?? ''"
|
||||
class="block w-full rounded-lg border-0 py-2.5 pl-4 pr-10 transition-all duration-200 focus:ring-2 focus:ring-inset sm:text-sm"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-gray-700/50 text-white placeholder-gray-400 focus:ring-indigo-500/50'
|
||||
: 'bg-gray-50 text-gray-900 placeholder-gray-400 focus:ring-indigo-500'
|
||||
]"
|
||||
:placeholder="placeholder"
|
||||
@input="handleInput"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none transition-opacity duration-200 opacity-0 group-focus-within:opacity-100"
|
||||
>
|
||||
<CheckIcon class="w-5 h-5" :class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { CheckIcon } from 'lucide-vue-next'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
modelValue: string | number | null
|
||||
placeholder?: string
|
||||
type?: 'text' | 'number'
|
||||
}>(),
|
||||
{
|
||||
placeholder: '',
|
||||
type: 'text'
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string | number | null]
|
||||
}>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
|
||||
const handleInput = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
if (props.type === 'number') {
|
||||
emit('update:modelValue', target.value === '' ? null : target.valueAsNumber)
|
||||
return
|
||||
}
|
||||
|
||||
emit('update:modelValue', target.value)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<div class="flex-grow overflow-y-auto p-3 sm:p-6">
|
||||
<div v-if="records.length === 0" class="py-12 text-center text-sm" :class="isDarkMode ? 'text-gray-400' : 'text-gray-600'">
|
||||
{{ t('drawer.noRecords') }}
|
||||
</div>
|
||||
<transition-group v-else name="list" tag="div" class="space-y-3 sm:space-y-4">
|
||||
<article
|
||||
v-for="record in records"
|
||||
:key="record.id"
|
||||
class="rounded-xl bg-opacity-50 p-4 shadow-md transition duration-200 hover:shadow-lg"
|
||||
:class="[isDarkMode ? 'bg-gray-800 hover:bg-gray-700' : 'bg-gray-100 hover:bg-white']"
|
||||
>
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<FileIcon class="h-9 w-9 shrink-0" :class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" aria-hidden="true" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate text-base font-medium" :title="record.filename" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">{{ record.filename }}</p>
|
||||
<p class="truncate text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">{{ record.date }} · {{ record.size }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 grid grid-cols-3 gap-2">
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl px-2 text-xs font-medium" :class="actionClass" @click="$emit('view-details', record)">
|
||||
<EyeIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('common.fileDetails') }}
|
||||
</button>
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl px-2 text-xs font-medium" :class="actionClass" @click="$emit('download-record', record)">
|
||||
<DownloadIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('fileRecord.download') }}
|
||||
</button>
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl bg-red-600 px-2 text-xs font-medium text-white hover:bg-red-700" @click="$emit('delete-record', record.id)">
|
||||
<TrashIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('common.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</transition-group>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject } from 'vue'
|
||||
import { FileIcon, EyeIcon, DownloadIcon, TrashIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { ReceivedFileRecord } from '@/types'
|
||||
|
||||
defineProps<{ records: ReceivedFileRecord[] }>()
|
||||
defineEmits<{ 'view-details': [record: ReceivedFileRecord]; 'download-record': [record: ReceivedFileRecord]; 'delete-record': [id: number] }>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const actionClass = computed(() => isDarkMode ? 'bg-gray-700 text-gray-200 hover:bg-gray-600' : 'bg-white text-gray-700 hover:bg-gray-200')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.list-enter-active, .list-leave-active, .list-move { transition: all 0.24s ease; }
|
||||
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(20px); }
|
||||
</style>
|
||||
@@ -0,0 +1,345 @@
|
||||
<template>
|
||||
<div
|
||||
class="rounded-2xl p-5 sm:p-8 flex flex-col items-center justify-center border-2 border-dashed transition-all duration-300 group cursor-pointer relative min-h-56 sm:min-h-72 overflow-hidden"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-gray-800/60 border-gray-600 hover:border-indigo-400'
|
||||
: 'bg-white/80 border-gray-300 hover:border-indigo-500',
|
||||
isDragActive
|
||||
? isDarkMode
|
||||
? 'border-indigo-400 bg-indigo-500/10 shadow-lg shadow-indigo-900/30'
|
||||
: 'border-indigo-500 bg-indigo-50 shadow-lg shadow-indigo-100'
|
||||
: '',
|
||||
statusClass
|
||||
]"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-busy="isUploading"
|
||||
@click="triggerFileUpload"
|
||||
@keydown.enter.prevent="triggerFileUpload"
|
||||
@keydown.space.prevent="triggerFileUpload"
|
||||
@dragenter.prevent="handleDragEnter"
|
||||
@dragover.prevent="handleDragOver"
|
||||
@dragleave.prevent="handleDragLeave"
|
||||
@drop.prevent="handleFileDrop"
|
||||
>
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
class="hidden"
|
||||
@change="handleFileUpload"
|
||||
:accept="acceptedTypes"
|
||||
:disabled="isUploading"
|
||||
multiple
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 opacity-0 transition-opacity duration-300"
|
||||
:class="[isDragActive ? 'opacity-100' : '']"
|
||||
>
|
||||
<div
|
||||
class="absolute inset-3 rounded-2xl border"
|
||||
:class="[
|
||||
isDarkMode ? 'border-indigo-300/30 bg-indigo-400/5' : 'border-indigo-300 bg-indigo-50/80'
|
||||
]"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<div class="absolute inset-0 w-full h-full" v-if="progress > 0">
|
||||
<BorderProgressBar :progress="progress" />
|
||||
</div>
|
||||
|
||||
<!-- 上传状态图标 -->
|
||||
<component
|
||||
:is="statusIcon"
|
||||
:class="['relative z-10 w-16 h-16 transition-colors duration-300', statusIconClass]"
|
||||
/>
|
||||
|
||||
<!-- 文件名或占位文本 -->
|
||||
<p
|
||||
:class="[
|
||||
'relative z-10 mt-4 text-sm transition-colors duration-300 w-full text-center',
|
||||
isDarkMode
|
||||
? 'text-gray-400 group-hover:text-indigo-400'
|
||||
: 'text-gray-600 group-hover:text-indigo-600'
|
||||
]"
|
||||
>
|
||||
<span v-if="selectedFiles && selectedFiles.length > 1" class="block">
|
||||
<span v-for="f in uniqueFiles.slice(0, 3)" :key="fileKey(f)" class="block truncate">{{ f.name }}</span>
|
||||
</span>
|
||||
<span v-else class="block break-words line-clamp-2">
|
||||
{{ displayText }}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<!-- 状态描述或默认描述 -->
|
||||
<p :class="['relative z-10 mt-2 text-xs text-center leading-5', statusDescriptionClass]">
|
||||
{{ statusDescription }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="selectedFiles.length > 1"
|
||||
class="relative z-10 mt-4 flex flex-wrap items-center justify-center gap-2"
|
||||
>
|
||||
<span
|
||||
v-for="file in selectedFiles.slice(0, 3)"
|
||||
:key="`${file.name}-${file.size}`"
|
||||
class="max-w-40 truncate rounded-full px-3 py-1 text-xs"
|
||||
:class="[isDarkMode ? 'bg-gray-700/80 text-gray-200' : 'bg-gray-100 text-gray-700']"
|
||||
>
|
||||
{{ file.name }}
|
||||
</span>
|
||||
<span
|
||||
v-if="selectedFiles.length > 3"
|
||||
class="rounded-full px-3 py-1 text-xs"
|
||||
:class="[isDarkMode ? 'bg-indigo-500/20 text-indigo-200' : 'bg-indigo-100 text-indigo-700']"
|
||||
>
|
||||
+{{ selectedFiles.length - 3 }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 进度详情(上传中显示) -->
|
||||
<div v-if="isUploading && showProgressDetails" class="relative z-10 mt-3 w-full">
|
||||
<div
|
||||
class="flex justify-between text-xs mb-1"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
>
|
||||
<span>{{ formatBytes(uploadedBytes) }} / {{ formatBytes(totalBytes) }}</span>
|
||||
<span>{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 错误重试按钮 -->
|
||||
<button
|
||||
v-if="hasError && allowRetry"
|
||||
type="button"
|
||||
@click.stop="handleRetry"
|
||||
class="mt-3 min-h-11 rounded-lg px-4 py-2 text-sm transition-colors duration-200"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-indigo-600 hover:bg-indigo-500 text-white'
|
||||
: 'bg-indigo-500 hover:bg-indigo-600 text-white'
|
||||
]"
|
||||
>
|
||||
{{ retryLabel }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { UploadCloudIcon, CheckCircleIcon, XCircleIcon, LoaderIcon } from 'lucide-vue-next'
|
||||
import BorderProgressBar from './BorderProgressBar.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useInjectedDarkMode } from '@/composables'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
type UploadStatusType = 'idle' | 'uploading' | 'success' | 'error' | 'initializing' | 'confirming'
|
||||
|
||||
interface Props {
|
||||
selectedFile?: File | null
|
||||
selectedFiles?: File[]
|
||||
progress?: number
|
||||
placeholder?: string
|
||||
description?: string
|
||||
acceptedTypes?: string
|
||||
/** 上传状态 */
|
||||
uploadStatus?: UploadStatusType
|
||||
/** 已上传字节数 */
|
||||
uploadedBytes?: number
|
||||
/** 总字节数 */
|
||||
totalBytes?: number
|
||||
/** 错误消息 */
|
||||
errorMessage?: string
|
||||
/** 是否允许重试 */
|
||||
allowRetry?: boolean
|
||||
/** 重试按钮文本 */
|
||||
retryText?: string
|
||||
/** 是否显示进度详情 */
|
||||
showProgressDetails?: boolean
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
fileSelected: [file: File]
|
||||
filesSelected: [files: File[]]
|
||||
fileDrop: [event: DragEvent]
|
||||
retry: []
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
selectedFile: null,
|
||||
selectedFiles: () => [],
|
||||
progress: 0,
|
||||
placeholder: '',
|
||||
description: '',
|
||||
acceptedTypes: '*',
|
||||
uploadStatus: 'idle',
|
||||
uploadedBytes: 0,
|
||||
totalBytes: 0,
|
||||
errorMessage: '',
|
||||
allowRetry: true,
|
||||
retryText: '',
|
||||
showProgressDetails: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const isDarkMode = useInjectedDarkMode()
|
||||
|
||||
// 使用computed属性处理多语言文本
|
||||
const placeholderText = computed(() => props.placeholder || t('send.uploadArea.placeholder'))
|
||||
const descriptionText = computed(() => props.description || t('send.uploadArea.description'))
|
||||
const retryLabel = computed(() => props.retryText || t('send.uploadArea.retry'))
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const isDragActive = ref(false)
|
||||
|
||||
const isUploading = computed(() => {
|
||||
return ['uploading', 'initializing', 'confirming'].includes(props.uploadStatus)
|
||||
})
|
||||
|
||||
const hasError = computed(() => props.uploadStatus === 'error')
|
||||
|
||||
const isSuccess = computed(() => props.uploadStatus === 'success')
|
||||
|
||||
const displayText = computed(() => {
|
||||
if (props.selectedFiles && props.selectedFiles.length === 1) {
|
||||
return props.selectedFiles[0].name
|
||||
}
|
||||
if (props.selectedFiles && props.selectedFiles.length > 1) {
|
||||
return t('send.uploadArea.selectedFiles', { count: props.selectedFiles.length })
|
||||
}
|
||||
if (props.selectedFile) {
|
||||
return props.selectedFile.name
|
||||
}
|
||||
return placeholderText.value
|
||||
})
|
||||
|
||||
const uniqueFiles = computed(() => {
|
||||
const seen = new Set<string>()
|
||||
return props.selectedFiles.filter((file) => {
|
||||
const key = `${file.name}-${file.size}-${file.lastModified}`
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
})
|
||||
const fileKey = (file: File) => `${file.name}-${file.size}-${file.lastModified}`
|
||||
|
||||
const statusIcon = computed(() => {
|
||||
if (isUploading.value) return LoaderIcon
|
||||
if (isSuccess.value) return CheckCircleIcon
|
||||
if (hasError.value) return XCircleIcon
|
||||
return UploadCloudIcon
|
||||
})
|
||||
|
||||
const statusIconClass = computed(() => {
|
||||
if (isUploading.value) {
|
||||
return isDarkMode.value ? 'text-indigo-400 animate-spin' : 'text-indigo-600 animate-spin'
|
||||
}
|
||||
if (isSuccess.value) {
|
||||
return isDarkMode.value ? 'text-green-400' : 'text-green-600'
|
||||
}
|
||||
if (hasError.value) {
|
||||
return isDarkMode.value ? 'text-red-400' : 'text-red-600'
|
||||
}
|
||||
return isDarkMode.value
|
||||
? 'text-gray-400 group-hover:text-indigo-400'
|
||||
: 'text-gray-600 group-hover:text-indigo-600'
|
||||
})
|
||||
|
||||
const statusClass = computed(() => {
|
||||
if (hasError.value) {
|
||||
return isDarkMode.value ? 'border-red-500/50' : 'border-red-300'
|
||||
}
|
||||
if (isSuccess.value) {
|
||||
return isDarkMode.value ? 'border-green-500/50' : 'border-green-300'
|
||||
}
|
||||
return ''
|
||||
})
|
||||
|
||||
const statusDescription = computed(() => {
|
||||
if (hasError.value && props.errorMessage) {
|
||||
return props.errorMessage
|
||||
}
|
||||
if (props.uploadStatus === 'initializing') {
|
||||
return t('send.uploadArea.status.initializing')
|
||||
}
|
||||
if (props.uploadStatus === 'uploading') {
|
||||
return t('send.uploadArea.status.uploading')
|
||||
}
|
||||
if (props.uploadStatus === 'confirming') {
|
||||
return t('send.uploadArea.status.confirming')
|
||||
}
|
||||
if (isSuccess.value) {
|
||||
return t('send.uploadArea.status.success')
|
||||
}
|
||||
return descriptionText.value
|
||||
})
|
||||
|
||||
const statusDescriptionClass = computed(() => {
|
||||
if (hasError.value) {
|
||||
return isDarkMode.value ? 'text-red-400' : 'text-red-500'
|
||||
}
|
||||
if (isSuccess.value) {
|
||||
return isDarkMode.value ? 'text-green-400' : 'text-green-500'
|
||||
}
|
||||
return isDarkMode.value ? 'text-gray-500' : 'text-gray-400'
|
||||
})
|
||||
|
||||
const formatBytes = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 B'
|
||||
const k = 1024
|
||||
const sizes = ['B', 'KB', 'MB', 'GB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
const triggerFileUpload = () => {
|
||||
// 上传中或成功状态下不允许重新选择文件
|
||||
if (isUploading.value) return
|
||||
fileInput.value?.click()
|
||||
}
|
||||
|
||||
const handleDragEnter = () => {
|
||||
if (isUploading.value) return
|
||||
isDragActive.value = true
|
||||
}
|
||||
|
||||
const handleDragOver = () => {
|
||||
if (isUploading.value) return
|
||||
isDragActive.value = true
|
||||
}
|
||||
|
||||
const handleDragLeave = (event: DragEvent) => {
|
||||
const target = event.currentTarget as HTMLElement
|
||||
const relatedTarget = event.relatedTarget as Node | null
|
||||
if (!relatedTarget || !target.contains(relatedTarget)) {
|
||||
isDragActive.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileUpload = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
const files = target.files
|
||||
if (files && files.length > 0) {
|
||||
if (files.length === 1) {
|
||||
emit('fileSelected', files[0])
|
||||
} else {
|
||||
emit('filesSelected', Array.from(files))
|
||||
}
|
||||
}
|
||||
// 重置 input 值,允许选择同名文件
|
||||
target.value = ''
|
||||
}
|
||||
|
||||
const handleFileDrop = (event: DragEvent) => {
|
||||
// 上传中不允许拖放
|
||||
isDragActive.value = false
|
||||
if (isUploading.value) return
|
||||
emit('fileDrop', event)
|
||||
}
|
||||
|
||||
const handleRetry = () => {
|
||||
emit('retry')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,60 @@
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<label v-if="label" class="block text-sm font-medium" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-700']">
|
||||
{{ label }}
|
||||
<span v-if="required" class="text-red-500 ml-1">*</span>
|
||||
</label>
|
||||
<div class="relative">
|
||||
<input
|
||||
:type="type"
|
||||
:value="modelValue"
|
||||
@input="$emit('update:modelValue', ($event.target as HTMLInputElement).value)"
|
||||
:placeholder="placeholder"
|
||||
:required="required"
|
||||
:disabled="disabled"
|
||||
:minlength="minlength"
|
||||
:maxlength="maxlength"
|
||||
class="w-full rounded-md shadow-sm px-4 py-2.5 transition-all duration-200 ease-in-out border focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'bg-gray-700 border-gray-600 text-white placeholder-gray-400 hover:border-gray-500'
|
||||
: 'border-gray-300 hover:border-gray-400 placeholder-gray-500',
|
||||
disabled ? 'opacity-50 cursor-not-allowed' : '',
|
||||
error ? 'border-red-500 focus:border-red-500 focus:ring-red-500' : ''
|
||||
]"
|
||||
/>
|
||||
<slot name="suffix"></slot>
|
||||
</div>
|
||||
<p v-if="error" class="text-sm text-red-500">{{ error }}</p>
|
||||
<p v-if="hint" class="text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']">{{ hint }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
|
||||
interface Props {
|
||||
modelValue: string
|
||||
label?: string
|
||||
type?: string
|
||||
placeholder?: string
|
||||
required?: boolean
|
||||
disabled?: boolean
|
||||
error?: string
|
||||
hint?: string
|
||||
minlength?: number
|
||||
maxlength?: number
|
||||
}
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
type: 'text',
|
||||
required: false,
|
||||
disabled: false
|
||||
})
|
||||
|
||||
defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
</script>
|
||||
@@ -0,0 +1,111 @@
|
||||
<template>
|
||||
<div ref="switcherRef" class="relative">
|
||||
<button
|
||||
type="button"
|
||||
@click="toggleDropdown"
|
||||
:class="[
|
||||
'flex min-h-11 items-center space-x-2 rounded-lg px-3 py-2 transition-all duration-200',
|
||||
isDarkMode
|
||||
? 'bg-gray-800/60 hover:bg-gray-700/80 text-gray-300 hover:text-white'
|
||||
: 'bg-gray-100 hover:bg-gray-200 text-gray-700 hover:text-gray-900'
|
||||
]"
|
||||
:aria-expanded="isDropdownOpen"
|
||||
aria-haspopup="listbox"
|
||||
:aria-label="t('common.language')"
|
||||
>
|
||||
<GlobeIcon class="w-4 h-4" />
|
||||
<span class="text-sm font-medium">{{ currentLanguage.name }}</span>
|
||||
<ChevronDownIcon
|
||||
:class="[
|
||||
'w-4 h-4 transition-transform duration-200',
|
||||
{ 'rotate-180': isDropdownOpen }
|
||||
]"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<transition
|
||||
enter-active-class="transition ease-out duration-200"
|
||||
enter-from-class="opacity-0 scale-95"
|
||||
enter-to-class="opacity-100 scale-100"
|
||||
leave-active-class="transition ease-in duration-150"
|
||||
leave-from-class="opacity-100 scale-100"
|
||||
leave-to-class="opacity-0 scale-95"
|
||||
>
|
||||
<div
|
||||
v-if="isDropdownOpen"
|
||||
role="listbox"
|
||||
:class="[
|
||||
'absolute right-0 mt-2 w-32 rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 z-50',
|
||||
isDarkMode
|
||||
? 'bg-gray-800 border border-gray-700'
|
||||
: 'bg-white border border-gray-200'
|
||||
]"
|
||||
>
|
||||
<div class="py-1">
|
||||
<button
|
||||
v-for="language in availableLocales"
|
||||
:key="language.code"
|
||||
type="button"
|
||||
role="option"
|
||||
:aria-selected="currentLocale === language.code"
|
||||
@click="switchLanguage(language.code)"
|
||||
:class="[
|
||||
'min-h-11 w-full px-4 py-2 text-left text-sm transition-colors duration-150',
|
||||
currentLocale === language.code
|
||||
? isDarkMode
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'bg-indigo-50 text-indigo-600'
|
||||
: isDarkMode
|
||||
? 'text-gray-300 hover:bg-gray-700 hover:text-white'
|
||||
: 'text-gray-700 hover:bg-gray-100'
|
||||
]"
|
||||
>
|
||||
{{ language.name }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, inject, onMounted, onUnmounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { GlobeIcon, ChevronDownIcon } from 'lucide-vue-next'
|
||||
import { availableLocales, setLocale } from '@/i18n/index'
|
||||
|
||||
const { locale, t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const isDropdownOpen = ref(false)
|
||||
const switcherRef = ref<HTMLElement | null>(null)
|
||||
|
||||
const currentLocale = computed(() => locale.value)
|
||||
const currentLanguage = computed(() => {
|
||||
return availableLocales.find((lang: { code: string; name: string }) => lang.code === currentLocale.value) || availableLocales[0]
|
||||
})
|
||||
|
||||
const toggleDropdown = () => {
|
||||
isDropdownOpen.value = !isDropdownOpen.value
|
||||
}
|
||||
|
||||
const switchLanguage = (langCode: string) => {
|
||||
setLocale(langCode)
|
||||
isDropdownOpen.value = false
|
||||
}
|
||||
|
||||
// 点击外部关闭下拉菜单
|
||||
const handleClickOutside = (event: Event) => {
|
||||
const target = event.target as Node | null
|
||||
if (target && !switcherRef.value?.contains(target)) {
|
||||
isDropdownOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,271 @@
|
||||
<template>
|
||||
<div class="native-date-strip" :class="fieldClass" :aria-label="ariaLabel">
|
||||
<select
|
||||
:value="parts.year"
|
||||
class="native-date-part native-date-year"
|
||||
:aria-label="`${ariaLabel}年`"
|
||||
@change="updatePart('year', ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="year in years" :key="year" :value="year">{{ year }}</option>
|
||||
</select>
|
||||
<span class="native-date-separator">/</span>
|
||||
<select
|
||||
:value="parts.month"
|
||||
class="native-date-part native-date-month"
|
||||
:aria-label="`${ariaLabel}月`"
|
||||
@change="updatePart('month', ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="month in months" :key="month" :value="month">
|
||||
{{ month.toString().padStart(2, '0') }}
|
||||
</option>
|
||||
</select>
|
||||
<span class="native-date-separator">/</span>
|
||||
<select
|
||||
:value="parts.day"
|
||||
class="native-date-part native-date-day"
|
||||
:aria-label="`${ariaLabel}日`"
|
||||
@change="updatePart('day', ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="day in days" :key="day" :value="day">
|
||||
{{ day.toString().padStart(2, '0') }}
|
||||
</option>
|
||||
</select>
|
||||
<template v-if="includeTime">
|
||||
<span class="native-date-time-spacer" />
|
||||
<select
|
||||
:value="parts.hour"
|
||||
class="native-date-part native-date-time"
|
||||
:aria-label="`${ariaLabel}时`"
|
||||
@change="updatePart('hour', ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="hour in hours" :key="hour" :value="hour">
|
||||
{{ hour.toString().padStart(2, '0') }}
|
||||
</option>
|
||||
</select>
|
||||
<span class="native-date-separator">:</span>
|
||||
<select
|
||||
:value="parts.minute"
|
||||
class="native-date-part native-date-time"
|
||||
:aria-label="`${ariaLabel}分`"
|
||||
@change="updatePart('minute', ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="minute in minutes" :key="minute" :value="minute">
|
||||
{{ minute.toString().padStart(2, '0') }}
|
||||
</option>
|
||||
</select>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string
|
||||
fieldClass?: string | string[]
|
||||
ariaLabel?: string
|
||||
minYear?: number
|
||||
maxYear?: number
|
||||
includeTime?: boolean
|
||||
}>(),
|
||||
{
|
||||
fieldClass: '',
|
||||
ariaLabel: '日期',
|
||||
minYear: 1900,
|
||||
maxYear: 2100,
|
||||
includeTime: false
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
change: []
|
||||
}>()
|
||||
|
||||
type DatePart = 'year' | 'month' | 'day' | 'hour' | 'minute'
|
||||
|
||||
const pad = (value: number) => String(value).padStart(2, '0')
|
||||
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value))
|
||||
const getDaysInMonth = (year: number, month: number) => new Date(year, month, 0).getDate()
|
||||
|
||||
const years = computed(() =>
|
||||
Array.from({ length: props.maxYear - props.minYear + 1 }, (_, index) => props.minYear + index)
|
||||
)
|
||||
const months = Array.from({ length: 12 }, (_, index) => index + 1)
|
||||
const hours = Array.from({ length: 24 }, (_, index) => index)
|
||||
const minutes = Array.from({ length: 60 }, (_, index) => index)
|
||||
|
||||
const parts = computed(() => {
|
||||
const [rawDate = '', rawTime = ''] = props.modelValue.split('T')
|
||||
const [rawYear, rawMonth, rawDay] = rawDate.split('-').map(Number)
|
||||
const [rawHour, rawMinute] = rawTime.split(':').map(Number)
|
||||
const year = clamp(Number.isFinite(rawYear) ? rawYear : new Date().getFullYear(), props.minYear, props.maxYear)
|
||||
const month = clamp(Number.isFinite(rawMonth) ? rawMonth : new Date().getMonth() + 1, 1, 12)
|
||||
const day = clamp(
|
||||
Number.isFinite(rawDay) ? rawDay : new Date().getDate(),
|
||||
1,
|
||||
getDaysInMonth(year, month)
|
||||
)
|
||||
const hour = clamp(Number.isFinite(rawHour) ? rawHour : 0, 0, 23)
|
||||
const minute = clamp(Number.isFinite(rawMinute) ? rawMinute : 0, 0, 59)
|
||||
return { year, month, day, hour, minute }
|
||||
})
|
||||
|
||||
const days = computed(() =>
|
||||
Array.from(
|
||||
{ length: getDaysInMonth(parts.value.year, parts.value.month) },
|
||||
(_, index) => index + 1
|
||||
)
|
||||
)
|
||||
|
||||
const updatePart = (part: DatePart, value: string) => {
|
||||
const next = { ...parts.value, [part]: Number(value) }
|
||||
next.day = clamp(next.day, 1, getDaysInMonth(next.year, next.month))
|
||||
const nextDate = `${next.year}-${pad(next.month)}-${pad(next.day)}`
|
||||
const nextValue = props.includeTime
|
||||
? `${nextDate}T${pad(next.hour)}:${pad(next.minute)}`
|
||||
: nextDate
|
||||
emit('update:modelValue', nextValue)
|
||||
emit('change')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.native-date-strip {
|
||||
display: inline-flex;
|
||||
width: var(--native-date-width, max-content);
|
||||
max-width: 100%;
|
||||
min-height: 2.75rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
padding-inline: 0.65ch;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 30px;
|
||||
background: rgba(237, 244, 245, 0.52);
|
||||
color: #2d4650;
|
||||
font-variant-numeric: tabular-nums;
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.62);
|
||||
transition:
|
||||
background 180ms ease,
|
||||
border-color 180ms ease,
|
||||
box-shadow 180ms ease,
|
||||
transform 180ms ease;
|
||||
}
|
||||
|
||||
.native-date-strip:hover,
|
||||
.native-date-strip:focus-within {
|
||||
border-color: rgba(143, 178, 191, 0.7);
|
||||
background: rgba(226, 236, 238, 0.78);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.72),
|
||||
0 10px 24px rgba(126, 149, 154, 0.16);
|
||||
}
|
||||
|
||||
.native-date-strip:focus-within {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.native-date-part {
|
||||
height: 2.65rem;
|
||||
appearance: none;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
text-align: center;
|
||||
font-size: 0.95rem;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.native-date-part:focus-visible {
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 0 0 2px rgba(143, 178, 191, 0.58);
|
||||
}
|
||||
|
||||
.native-date-year {
|
||||
width: 4.2ch;
|
||||
}
|
||||
|
||||
.native-date-month,
|
||||
.native-date-day,
|
||||
.native-date-time {
|
||||
width: 2.2ch;
|
||||
}
|
||||
|
||||
.native-date-time-spacer {
|
||||
width: 0.9ch;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.native-date-separator {
|
||||
margin-inline: 0.35ch;
|
||||
color: #789096;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1;
|
||||
opacity: 0.78;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 639px) {
|
||||
:global(.analytics-date-range) {
|
||||
--native-date-width: auto;
|
||||
display: flex !important;
|
||||
width: 100%;
|
||||
flex-wrap: nowrap !important;
|
||||
gap: 0.2rem !important;
|
||||
}
|
||||
|
||||
.native-date-strip {
|
||||
width: min-content;
|
||||
min-width: 0;
|
||||
flex: 1 1 0;
|
||||
min-height: 2.75rem;
|
||||
padding-inline: 0.2rem;
|
||||
}
|
||||
|
||||
.native-date-part {
|
||||
height: 2.75rem;
|
||||
min-width: 0;
|
||||
font-size: clamp(0.75rem, 3.4vw, 0.9rem);
|
||||
}
|
||||
|
||||
.native-date-year {
|
||||
width: clamp(3.35rem, 15vw, 4rem);
|
||||
}
|
||||
|
||||
.native-date-month,
|
||||
.native-date-day {
|
||||
width: clamp(1.7rem, 8vw, 2.2rem);
|
||||
}
|
||||
|
||||
.native-date-separator {
|
||||
margin-inline: 0;
|
||||
font-size: clamp(0.72rem, 3vw, 0.85rem);
|
||||
}
|
||||
}
|
||||
|
||||
.dark .native-date-strip {
|
||||
background: rgba(38, 57, 65, 0.62);
|
||||
color: #d8e3e5;
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.dark .native-date-strip:hover,
|
||||
.dark .native-date-strip:focus-within {
|
||||
border-color: rgba(113, 153, 168, 0.72);
|
||||
background: rgba(45, 71, 81, 0.76);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.1),
|
||||
0 10px 24px rgba(4, 10, 14, 0.28);
|
||||
}
|
||||
|
||||
.dark .native-date-separator {
|
||||
color: #aabdc2;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="mb-6 text-center" v-if="linkText && linkTo">
|
||||
<router-link
|
||||
:to="linkTo"
|
||||
class="inline-flex min-h-11 items-center rounded-lg px-3 text-[#3f6a77] transition duration-200 hover:bg-[#dcebed] hover:text-[#315c69] dark:text-[#b8d4dc] dark:hover:bg-[#294047]"
|
||||
>
|
||||
{{ linkText }}
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex items-center justify-between gap-3 bg-opacity-50 px-4 py-3 sm:px-8 sm:py-4"
|
||||
:class="[isDarkMode ? 'bg-gray-800' : 'bg-gray-100']"
|
||||
>
|
||||
<span
|
||||
class="text-sm flex items-center"
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
|
||||
>
|
||||
<ShieldCheckIcon class="w-4 h-4 mr-1 text-green-400" />
|
||||
{{ t('send.secureEncryption') }}
|
||||
</span>
|
||||
<div class="flex items-center gap-2 sm:gap-4">
|
||||
<router-link
|
||||
to="/login"
|
||||
class="flex h-11 w-11 items-center justify-center rounded-lg text-sm transition duration-200 hover:bg-[#dcebed] dark:hover:bg-[#294047]"
|
||||
:aria-label="t('manage.login.title')"
|
||||
:title="t('manage.login.title')"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-gray-400 hover:text-indigo-400'
|
||||
: 'text-gray-500 hover:text-indigo-600'
|
||||
]"
|
||||
>
|
||||
<UserIcon class="w-4 h-4" />
|
||||
</router-link>
|
||||
<button
|
||||
type="button"
|
||||
@click="$emit('toggle-drawer')"
|
||||
class="flex min-h-11 items-center rounded-lg px-2 text-sm transition duration-200 hover:bg-[#dcebed] dark:hover:bg-[#294047]"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
>
|
||||
{{ drawerText }}
|
||||
<ClipboardListIcon class="w-4 h-4 ml-1" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { ShieldCheckIcon, ClipboardListIcon, UserIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Props {
|
||||
linkText?: string
|
||||
linkTo?: string
|
||||
drawerText: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
'toggle-drawer': []
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
defineEmits<Emits>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
</script>
|
||||
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<div class="text-center">
|
||||
<div class="mb-5 flex justify-center" aria-hidden="true">
|
||||
<div
|
||||
class="rounded-full bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 p-1 animate-spin-slow"
|
||||
>
|
||||
<div class="rounded-full bg-gray-900 p-2">
|
||||
<BoxIcon class="w-8 h-8 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@click="$emit('title-click')"
|
||||
class="mb-6 min-h-11 rounded-lg px-2 text-center text-3xl font-extrabold focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-transparent bg-clip-text bg-gradient-to-r from-indigo-300 via-purple-300 to-pink-300'
|
||||
: 'text-indigo-600'
|
||||
]"
|
||||
:aria-label="title"
|
||||
>
|
||||
{{ title }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { BoxIcon } from 'lucide-vue-next'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
'title-click': []
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
defineEmits<Emits>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@keyframes spin-slow {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-spin-slow {
|
||||
animation: spin-slow 3s linear infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animate-spin-slow {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,107 @@
|
||||
<template>
|
||||
<form @submit.prevent="$emit('submit')">
|
||||
<div class="mb-6 relative">
|
||||
<label
|
||||
for="code"
|
||||
class="block text-sm font-medium mb-2"
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
|
||||
>{{ t('retrieve.codeInput.label') }}</label
|
||||
>
|
||||
<div class="relative">
|
||||
<input
|
||||
id="code"
|
||||
v-model="code"
|
||||
type="text"
|
||||
inputmode="text"
|
||||
autocomplete="one-time-code"
|
||||
ref="codeInput"
|
||||
class="w-full px-4 py-3 rounded-lg placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300 pr-10"
|
||||
:class="[
|
||||
isDarkMode ? 'bg-gray-700 bg-opacity-50' : 'bg-gray-100',
|
||||
{ 'ring-2 ring-red-500': error },
|
||||
isDarkMode ? 'text-gray-300' : 'text-gray-800'
|
||||
]"
|
||||
:placeholder="t('retrieve.codeInput.placeholder')"
|
||||
required
|
||||
:aria-invalid="error"
|
||||
:readonly="inputStatus.readonly"
|
||||
maxlength="8"
|
||||
@focus="isInputFocused = true"
|
||||
@blur="isInputFocused = false"
|
||||
/>
|
||||
<div
|
||||
v-if="inputStatus.loading"
|
||||
class="absolute inset-y-0 right-0 flex items-center pr-3"
|
||||
>
|
||||
<span
|
||||
class="animate-spin rounded-full h-5 w-5 border-b-2 border-indigo-500"
|
||||
></span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="absolute -bottom-0.5 left-2 h-0.5 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 transition-all duration-300 ease-in-out"
|
||||
:class="{ 'w-97-100': isInputFocused, 'w-0': !isInputFocused }"
|
||||
></div>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="group relative w-full overflow-hidden rounded-lg bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 px-4 py-3 font-bold text-white transition duration-300 hover:from-indigo-600 hover:via-purple-600 hover:to-pink-600 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 disabled:cursor-not-allowed disabled:opacity-50 motion-safe:hover:scale-[1.02] disabled:hover:scale-100"
|
||||
:disabled="inputStatus.loading || ![5, 8].includes(code.trim().length)"
|
||||
>
|
||||
<span class="flex items-center justify-center relative z-10">
|
||||
<span>{{ inputStatus.loading ? t('common.loading') : t('retrieve.submit') }}</span>
|
||||
<ArrowRightIcon
|
||||
class="w-5 h-5 ml-2 transition-transform duration-300 transform group-hover:translate-x-1"
|
||||
/>
|
||||
</span>
|
||||
<span
|
||||
class="absolute top-0 left-0 w-full h-full bg-gradient-to-r from-pink-500 via-purple-500 to-indigo-500 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
|
||||
></span>
|
||||
</button>
|
||||
</form>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, inject, computed } from 'vue'
|
||||
import { ArrowRightIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface InputStatus {
|
||||
readonly: boolean
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
inputStatus: InputStatus
|
||||
error?: boolean
|
||||
modelValue: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
submit: []
|
||||
'update:modelValue': [value: string]
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const code = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value)
|
||||
})
|
||||
const isInputFocused = ref(false)
|
||||
const codeInput = ref<HTMLInputElement>()
|
||||
|
||||
defineExpose({
|
||||
focus: () => codeInput.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.w-97-100 {
|
||||
width: calc(100% - 1rem);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,56 @@
|
||||
<template>
|
||||
<div class="flex justify-center space-x-4 mb-6">
|
||||
<button
|
||||
type="button"
|
||||
@click="selectType('file')"
|
||||
:class="[
|
||||
'min-h-11 px-4 py-2 rounded-lg transition-colors duration-300',
|
||||
selectedType === 'file'
|
||||
? 'bg-indigo-600 text-white'
|
||||
: isDarkMode
|
||||
? 'bg-gray-700 text-gray-300 hover:bg-gray-600'
|
||||
: 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
||||
]"
|
||||
>
|
||||
{{ t('nav.sendFile') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@click="selectType('text')"
|
||||
:class="[
|
||||
'min-h-11 px-4 py-2 rounded-lg transition-colors duration-300',
|
||||
selectedType === 'text'
|
||||
? 'bg-indigo-600 text-white'
|
||||
: isDarkMode
|
||||
? 'bg-gray-700 text-gray-300 hover:bg-gray-600'
|
||||
: 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
||||
]"
|
||||
>
|
||||
{{ t('send.sendText') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import type { SendType } from '@/types'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Props {
|
||||
selectedType: SendType
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
'update:selectedType': [type: SendType]
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
const emit = defineEmits<Emits>()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
|
||||
const selectType = (type: SendType) => {
|
||||
emit('update:selectedType', type)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,273 @@
|
||||
<template>
|
||||
<transition name="fade">
|
||||
<div
|
||||
v-if="record"
|
||||
ref="modalRef"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-labelledby="modalTitleId"
|
||||
tabindex="-1"
|
||||
@keydown="handleKeydown"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/60 p-3 backdrop-blur-sm sm:p-4"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-2xl overflow-hidden rounded-[24px] shadow-2xl transform transition-all duration-200 ease-out sm:rounded-[30px]"
|
||||
:class="[isDarkMode ? 'bg-gray-900 bg-opacity-70' : 'bg-white bg-opacity-95']"
|
||||
>
|
||||
<div
|
||||
class="border-b px-3 py-3 sm:px-6 sm:py-4"
|
||||
:class="[isDarkMode ? 'border-gray-800' : 'border-gray-100']"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<h3
|
||||
:id="modalTitleId"
|
||||
class="text-base font-semibold sm:text-xl"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-gray-900']"
|
||||
>
|
||||
{{ t('send.fileDetails') }}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="关闭文件详情"
|
||||
@click="emit('close')"
|
||||
class="min-h-11 min-w-11 rounded-[30px] p-1.5 transition-colors hover:bg-gray-100 dark:hover:bg-gray-800 sm:p-2"
|
||||
>
|
||||
<XIcon
|
||||
class="w-4 h-4 sm:w-5 sm:h-5"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-3 sm:p-5 lg:p-6">
|
||||
<div
|
||||
class="mb-3 rounded-[20px] p-3 sm:mb-5 sm:rounded-[24px] sm:p-4"
|
||||
:class="[isDarkMode ? 'bg-gray-800 bg-opacity-50' : 'bg-gray-50 bg-opacity-95']"
|
||||
>
|
||||
<div class="flex items-center mb-3 sm:mb-4">
|
||||
<div class="rounded-[20px] p-2 sm:rounded-[24px] sm:p-3" :class="[isDarkMode ? 'bg-gray-800' : 'bg-white']">
|
||||
<FileIcon
|
||||
class="w-5 h-5 sm:w-6 sm:h-6"
|
||||
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
|
||||
/>
|
||||
</div>
|
||||
<div class="ml-3 sm:ml-4 min-w-0 flex-1">
|
||||
<h4
|
||||
class="font-medium text-sm sm:text-base break-words"
|
||||
:title="record.filename"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-gray-900']"
|
||||
>
|
||||
{{ record.filename }}
|
||||
</h4>
|
||||
<p
|
||||
class="text-xs sm:text-sm truncate"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
>
|
||||
{{ record.size }} · {{ record.date }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-3 sm:gap-4">
|
||||
<div class="flex items-center min-w-0">
|
||||
<ClockIcon
|
||||
class="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5 sm:mr-2 flex-shrink-0"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
/>
|
||||
<span
|
||||
class="text-xs sm:text-sm truncate"
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']"
|
||||
>
|
||||
{{ record.expiration }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center min-w-0">
|
||||
<ShieldCheckIcon
|
||||
class="w-3.5 h-3.5 sm:w-4 sm:h-4 mr-1.5 sm:mr-2 flex-shrink-0"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
/>
|
||||
<span
|
||||
class="text-xs sm:text-sm truncate"
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']"
|
||||
>
|
||||
安全加密
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
|
||||
<div class="space-y-3 sm:space-y-4">
|
||||
<div class="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl p-4 sm:p-5 text-white">
|
||||
<div class="flex items-center justify-between mb-3 sm:mb-4">
|
||||
<h4 class="font-medium text-sm sm:text-base">取件码</h4>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="复制取件码"
|
||||
@click="emit('copy-code', record)"
|
||||
class="min-h-11 min-w-11 p-1.5 sm:p-2 rounded-full hover:bg-white/10 transition-colors"
|
||||
>
|
||||
<ClipboardCopyIcon class="w-4 h-4 sm:w-5 sm:h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-2xl sm:text-3xl font-bold tracking-wider text-center break-all">
|
||||
{{ record.retrieveCode }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="rounded-xl p-3 sm:p-4"
|
||||
:class="[isDarkMode ? 'bg-gray-800 bg-opacity-50' : 'bg-gray-50 bg-opacity-95']"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-2 sm:mb-3">
|
||||
<h4
|
||||
class="font-medium text-sm sm:text-base flex items-center min-w-0"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-gray-900']"
|
||||
>
|
||||
<TerminalIcon class="w-4 h-4 sm:w-5 sm:h-5 mr-1.5 sm:mr-2 text-indigo-500 flex-shrink-0" />
|
||||
<span class="truncate">wget下载</span>
|
||||
</h4>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="复制 wget 命令"
|
||||
@click="emit('copy-wget', record)"
|
||||
class="min-h-11 min-w-11 p-1.5 sm:p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex-shrink-0"
|
||||
>
|
||||
<ClipboardCopyIcon
|
||||
class="w-4 h-4 sm:w-5 sm:h-5"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="!showWget"
|
||||
class="text-xs sm:text-sm font-mono break-all line-clamp-2"
|
||||
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']"
|
||||
>
|
||||
<button type="button" class="min-h-11 rounded-[30px] px-3 text-left hover:bg-gray-200 dark:hover:bg-gray-700" @click="showWget = true">显示 wget 命令</button>
|
||||
</p>
|
||||
<p v-else class="text-xs sm:text-sm font-mono break-all" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']">{{ wgetCommand }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="rounded-xl p-4 sm:p-5 flex flex-col items-center"
|
||||
:class="[isDarkMode ? 'bg-gray-800 bg-opacity-50' : 'bg-gray-50 bg-opacity-95']"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="bg-white p-3 sm:p-4 rounded-lg shadow-sm mb-3 sm:mb-4"
|
||||
aria-label="取件二维码"
|
||||
@click="showQr = !showQr"
|
||||
>
|
||||
<span v-if="!showQr" class="flex h-[140px] w-[140px] items-center justify-center text-sm text-gray-500 sm:h-[160px] sm:w-[160px]">显示二维码</span>
|
||||
<QRCode v-else :value="qrValue" :size="140" level="M" class="sm:w-[160px] sm:h-[160px]" />
|
||||
</button>
|
||||
<p
|
||||
class="text-xs sm:text-sm truncate max-w-full"
|
||||
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
|
||||
>
|
||||
扫描二维码快速取件
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="px-4 sm:px-6 py-3 sm:py-4 border-t"
|
||||
:class="[isDarkMode ? 'border-gray-800' : 'border-gray-100']"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@click="emit('copy-link', record)"
|
||||
class="min-h-11 w-full bg-teal-600 hover:bg-teal-700 text-white px-4 sm:px-6 py-2 sm:py-3 rounded-xl text-sm sm:text-base font-medium transition-colors"
|
||||
>
|
||||
复制取件链接
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, inject, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import {
|
||||
ClipboardCopyIcon,
|
||||
ClockIcon,
|
||||
FileIcon,
|
||||
ShieldCheckIcon,
|
||||
TerminalIcon,
|
||||
XIcon
|
||||
} from 'lucide-vue-next'
|
||||
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { SentFileRecord } from '@/types'
|
||||
import { buildAbsoluteUrl } from '@/utils/share-url'
|
||||
import { lockBodyScroll, unlockBodyScroll } from './scrollLock'
|
||||
|
||||
const props = defineProps<{
|
||||
record: SentFileRecord | null
|
||||
getQRCodeValue: (record: SentFileRecord) => string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
'copy-code': [record: SentFileRecord]
|
||||
'copy-link': [record: SentFileRecord]
|
||||
'copy-wget': [record: SentFileRecord]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const QRCode = defineAsyncComponent(() => import('qrcode.vue'))
|
||||
const qrValue = computed(() => (props.record ? props.getQRCodeValue(props.record) : ''))
|
||||
const modalRef = ref<HTMLElement>()
|
||||
|
||||
const modalTitleId = 'sent-record-detail-title'
|
||||
let returnFocusElement: HTMLElement | null = null
|
||||
let scrollLockOwner: ReturnType<typeof lockBodyScroll> | null = null
|
||||
const showQr = ref(false)
|
||||
const showWget = ref(false)
|
||||
const wgetCommand = computed(() => `wget ${buildAbsoluteUrl(`/share/select?code=${props.record?.retrieveCode ?? ''}`)} -O "${props.record?.filename ?? ''}"`)
|
||||
const focusableSelector = 'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') { event.preventDefault(); emit('close'); return }
|
||||
if (event.key !== 'Tab' || !modalRef.value) return
|
||||
const focusable = [...modalRef.value.querySelectorAll<HTMLElement>(focusableSelector)]
|
||||
const first = focusable[0]; const last = focusable[focusable.length - 1]
|
||||
if (first && last && ((event.shiftKey && document.activeElement === first) || (!event.shiftKey && document.activeElement === last))) {
|
||||
event.preventDefault(); (event.shiftKey ? last : first).focus()
|
||||
}
|
||||
}
|
||||
watch(() => props.record, async (record) => {
|
||||
if (scrollLockOwner) {
|
||||
unlockBodyScroll(scrollLockOwner)
|
||||
scrollLockOwner = null
|
||||
}
|
||||
showQr.value = false
|
||||
showWget.value = false
|
||||
if (record) {
|
||||
returnFocusElement = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
scrollLockOwner = lockBodyScroll(); await nextTick(); modalRef.value?.focus()
|
||||
} else {
|
||||
await nextTick(); returnFocusElement?.focus(); returnFocusElement = null
|
||||
}
|
||||
}, { immediate: true })
|
||||
onBeforeUnmount(() => { unlockBodyScroll(scrollLockOwner); scrollLockOwner = null; returnFocusElement = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition:
|
||||
opacity 0.3s ease,
|
||||
transform 0.3s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,56 @@
|
||||
<template>
|
||||
<div class="flex-grow overflow-y-auto p-3 sm:p-6">
|
||||
<div v-if="records.length === 0" class="py-12 text-center text-sm" :class="isDarkMode ? 'text-gray-400' : 'text-gray-600'">
|
||||
{{ t('drawer.noRecords') }}
|
||||
</div>
|
||||
<transition-group v-else name="list" tag="div" class="space-y-3 sm:space-y-4">
|
||||
<article
|
||||
v-for="record in records"
|
||||
:key="record.id"
|
||||
class="rounded-xl bg-opacity-50 p-4 shadow-md transition duration-200 hover:shadow-lg"
|
||||
:class="[isDarkMode ? 'bg-gray-800 hover:bg-gray-700' : 'bg-gray-100 hover:bg-white']"
|
||||
>
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<FileIcon class="h-9 w-9 shrink-0" :class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" aria-hidden="true" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate text-base font-medium" :title="record.filename || 'Text'" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">
|
||||
{{ record.filename || 'Text' }}
|
||||
</p>
|
||||
<p class="truncate text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">
|
||||
{{ record.date }} · {{ record.size }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 grid grid-cols-3 gap-2">
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl px-2 text-xs font-medium" :class="actionClass" @click="$emit('copy-link', record)">
|
||||
<ClipboardCopyIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('common.copy') }}
|
||||
</button>
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl px-2 text-xs font-medium" :class="actionClass" @click="$emit('view-details', record)">
|
||||
<EyeIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('common.fileDetails') }}
|
||||
</button>
|
||||
<button type="button" class="flex min-h-11 items-center justify-center rounded-xl bg-red-600 px-2 text-xs font-medium text-white hover:bg-red-700" @click="$emit('delete-record', record.id)">
|
||||
<TrashIcon class="mr-1.5 h-4 w-4" aria-hidden="true" />{{ t('common.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</transition-group>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject } from 'vue'
|
||||
import { ClipboardCopyIcon, EyeIcon, FileIcon, TrashIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { SentFileRecord } from '@/types'
|
||||
|
||||
defineProps<{ records: SentFileRecord[] }>()
|
||||
defineEmits<{ 'copy-link': [record: SentFileRecord]; 'view-details': [record: SentFileRecord]; 'delete-record': [id: number] }>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const actionClass = computed(() => isDarkMode ? 'bg-gray-700 text-gray-200 hover:bg-gray-600' : 'bg-white text-gray-700 hover:bg-gray-200')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.list-enter-active, .list-leave-active { transition: all 0.24s ease; }
|
||||
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(20px); }
|
||||
</style>
|
||||
@@ -0,0 +1,41 @@
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<label :for="inputId" class="block text-sm font-medium" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-700']">
|
||||
{{ label }}
|
||||
</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
:id="inputId"
|
||||
type="number"
|
||||
:value="modelValue"
|
||||
class="min-h-11 w-28 rounded-md border px-4 py-2.5 shadow-sm outline-none transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'border-gray-600 bg-gray-700 text-white hover:border-gray-500'
|
||||
: 'border-gray-300 bg-white text-gray-900 hover:border-gray-400'
|
||||
]"
|
||||
@input="handleInput"
|
||||
/>
|
||||
<span :class="[isDarkMode ? 'text-gray-300' : 'text-gray-700']">{{ suffix }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject } from 'vue'
|
||||
|
||||
const props = defineProps<{ label: string; modelValue: number; suffix: string }>()
|
||||
const inputId = computed(() => `setting-number-${props.label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi, '-')}`)
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: number] }>()
|
||||
|
||||
const handleInput = (event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
if (!input.value) {
|
||||
emit('update:modelValue', 0)
|
||||
return
|
||||
}
|
||||
const nextValue = input.valueAsNumber
|
||||
if (!Number.isNaN(nextValue)) emit('update:modelValue', nextValue)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,40 @@
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<span :id="labelId" class="block text-sm font-medium" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-700']">
|
||||
{{ label }}
|
||||
</span>
|
||||
<div class="flex min-h-11 items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-11 w-14 shrink-0 items-center justify-center rounded-full focus:outline-none focus:ring-2 focus:ring-[#8fb2bf] focus:ring-offset-2"
|
||||
role="switch"
|
||||
:aria-checked="modelValue === 1"
|
||||
:aria-labelledby="labelId"
|
||||
@click="$emit('toggle')"
|
||||
>
|
||||
<span
|
||||
class="relative inline-flex h-6 w-11 rounded-full border-2 border-transparent shadow-sm transition-colors duration-200"
|
||||
:class="modelValue === 1 ? 'bg-[#6f9688]' : isDarkMode ? 'bg-[#40545c]' : 'bg-[#cfdadc]'"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span
|
||||
class="pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200"
|
||||
:class="modelValue === 1 ? 'translate-x-5' : 'translate-x-0'"
|
||||
></span>
|
||||
</span>
|
||||
</button>
|
||||
<span class="text-sm" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-700']">
|
||||
{{ modelValue === 1 ? enabledText : disabledText }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject } from 'vue'
|
||||
|
||||
const props = defineProps<{ label: string; modelValue: number; enabledText: string; disabledText: string }>()
|
||||
defineEmits<{ toggle: [] }>()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const labelId = computed(() => `setting-switch-${props.label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi, '-')}`)
|
||||
</script>
|
||||
@@ -0,0 +1,131 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<transition name="drawer">
|
||||
<div v-if="visible" class="fixed inset-0 z-50">
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 bg-black/45"
|
||||
:aria-label="t('common.close')"
|
||||
@click="emit('close')"
|
||||
></button>
|
||||
<aside
|
||||
ref="drawerRef"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="title"
|
||||
tabindex="-1"
|
||||
class="absolute inset-y-0 right-0 flex w-full flex-col overflow-hidden bg-opacity-95 shadow-2xl backdrop-blur-xl sm:w-[30rem]"
|
||||
:class="[isDarkMode ? 'bg-gray-900' : 'bg-white']"
|
||||
@keydown="handleKeydown"
|
||||
>
|
||||
<div
|
||||
class="flex items-center justify-between border-b p-4 sm:p-6"
|
||||
:class="[isDarkMode ? 'border-gray-700' : 'border-gray-200']"
|
||||
>
|
||||
<h3 class="text-xl font-bold sm:text-2xl" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">
|
||||
{{ title }}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-11 w-11 items-center justify-center rounded-lg transition duration-200"
|
||||
:class="[isDarkMode ? 'text-gray-300 hover:bg-gray-800 hover:text-white' : 'text-gray-700 hover:bg-gray-100']"
|
||||
:aria-label="t('common.close')"
|
||||
:title="t('common.close')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<XIcon class="h-6 w-6" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto" tabindex="0">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { XIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { lockBodyScroll, unlockBodyScroll } from './scrollLock'
|
||||
|
||||
const props = defineProps<{ visible: boolean; title: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const drawerRef = ref<HTMLElement>()
|
||||
let returnFocusElement: HTMLElement | null = null
|
||||
let scrollLockOwner: ReturnType<typeof lockBodyScroll> | null = null
|
||||
const focusableSelector =
|
||||
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
|
||||
|
||||
const handleKeydown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
if (event.target !== event.currentTarget && (event.target as HTMLElement).closest('[role="dialog"]') !== event.currentTarget) return
|
||||
event.preventDefault()
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
if (event.key !== 'Tab' || !drawerRef.value) return
|
||||
const focusable = [...drawerRef.value.querySelectorAll<HTMLElement>(focusableSelector)]
|
||||
const first = focusable[0]
|
||||
const last = focusable[focusable.length - 1]
|
||||
if (!first || !last) return
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault()
|
||||
last.focus()
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
async (visible) => {
|
||||
if (visible) {
|
||||
scrollLockOwner = lockBodyScroll()
|
||||
returnFocusElement = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
await nextTick()
|
||||
const first = drawerRef.value?.querySelector<HTMLElement>(focusableSelector)
|
||||
;(first || drawerRef.value)?.focus()
|
||||
} else {
|
||||
unlockBodyScroll(scrollLockOwner)
|
||||
scrollLockOwner = null
|
||||
await nextTick()
|
||||
returnFocusElement?.focus()
|
||||
returnFocusElement = null
|
||||
}
|
||||
}
|
||||
)
|
||||
onBeforeUnmount(() => { unlockBodyScroll(scrollLockOwner); scrollLockOwner = null })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.drawer-enter-active,
|
||||
.drawer-leave-active {
|
||||
transition: opacity 0.24s ease;
|
||||
}
|
||||
.drawer-enter-active aside,
|
||||
.drawer-leave-active aside {
|
||||
transition: transform 0.24s ease;
|
||||
}
|
||||
.drawer-enter-from,
|
||||
.drawer-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
.drawer-enter-from aside,
|
||||
.drawer-leave-to aside {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.drawer-enter-active,
|
||||
.drawer-leave-active,
|
||||
.drawer-enter-active aside,
|
||||
.drawer-leave-active aside {
|
||||
transition-duration: 0.01ms;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,551 @@
|
||||
<template>
|
||||
<div class="relative overflow-visible rounded-[30px] border" :class="panelClass">
|
||||
<canvas
|
||||
ref="canvasRef"
|
||||
class="block h-72 min-h-72 w-full touch-pan-y select-none sm:h-80 sm:min-h-80 md:h-72 md:min-h-72"
|
||||
@wheel.prevent="handleWheel"
|
||||
@pointerdown="handlePointerDown"
|
||||
@pointermove="handlePointerMove"
|
||||
@pointerup="handlePointerUp"
|
||||
@pointercancel="handlePointerCancel"
|
||||
@pointerleave="handlePointerLeave"
|
||||
@dblclick.prevent="resetWindow"
|
||||
/>
|
||||
<div
|
||||
v-if="tooltip"
|
||||
class="pointer-events-none absolute z-30 w-max min-w-36 max-w-80 whitespace-nowrap rounded-xl border px-3 py-2 text-xs shadow-xl"
|
||||
:class="tooltipClass"
|
||||
:style="{
|
||||
left: `${tooltip.left}px`,
|
||||
top: `${tooltip.top}px`,
|
||||
transform: tooltip.transform
|
||||
}"
|
||||
>
|
||||
<p class="font-semibold">{{ tooltip.date }}</p>
|
||||
<p>下载次数:{{ tooltip.downloads }}</p>
|
||||
<p>上传次数:{{ tooltip.uploads }}</p>
|
||||
<p>下载流量:{{ tooltip.downloadTraffic }}</p>
|
||||
<p>上传流量:{{ tooltip.uploadTraffic }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import type { AnalyticsDailyRow } from '@/types'
|
||||
|
||||
const props = defineProps<{
|
||||
rows: AnalyticsDailyRow[]
|
||||
isDarkMode: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
windowChange: [text: string]
|
||||
}>()
|
||||
|
||||
type DragState = {
|
||||
startOffset: number
|
||||
lastX: number
|
||||
time: number
|
||||
pointerType: string
|
||||
isTimeline: boolean
|
||||
moved: boolean
|
||||
}
|
||||
|
||||
type TooltipState = {
|
||||
left: number
|
||||
top: number
|
||||
date: string
|
||||
downloads: number
|
||||
uploads: number
|
||||
downloadTraffic: string
|
||||
uploadTraffic: string
|
||||
transform: string
|
||||
}
|
||||
|
||||
type ChartPoint = {
|
||||
x: number
|
||||
y: number
|
||||
row: AnalyticsDailyRow
|
||||
}
|
||||
|
||||
type ScaleVisual = {
|
||||
max: number
|
||||
ticks: number[]
|
||||
}
|
||||
|
||||
const canvasRef = ref<HTMLCanvasElement | null>(null)
|
||||
const offset = ref(0)
|
||||
const windowSize = ref(30)
|
||||
const drag = ref<DragState | null>(null)
|
||||
const hoverX = ref<number | null>(null)
|
||||
const hoverVisual = ref<{ x: number; downloadY: number; uploadY: number } | null>(null)
|
||||
const velocity = ref(0)
|
||||
const rafId = ref<number | null>(null)
|
||||
const inertiaRafId = ref<number | null>(null)
|
||||
const lastInertiaTime = ref(0)
|
||||
const lastHoverTime = ref(0)
|
||||
const tooltip = ref<TooltipState | null>(null)
|
||||
const scaleVisual = ref<ScaleVisual | null>(null)
|
||||
const lastScaleTime = ref(0)
|
||||
|
||||
const INERTIA_REFERENCE_FRAME_MS = 1000 / 120
|
||||
const INERTIA_MAX_FRAME_MS = 1000 / 30
|
||||
const INERTIA_DECAY_PER_120HZ_FRAME = 0.96
|
||||
const INERTIA_STOP_VELOCITY = 0.01
|
||||
const HOVER_EASE_PER_120HZ_FRAME = 0.34
|
||||
const HOVER_SNAP_DISTANCE = 0.2
|
||||
const SCALE_EASE_PER_120HZ_FRAME = 0.2
|
||||
const SCALE_SNAP_DISTANCE = 0.01
|
||||
const getYAxisTicks = (rawMax: number) => {
|
||||
const roundedMax = Math.max(1, Math.ceil(rawMax))
|
||||
if (roundedMax <= 4) {
|
||||
return Array.from({ length: roundedMax + 1 }, (_, index) => roundedMax - index)
|
||||
}
|
||||
|
||||
const step = Math.ceil(roundedMax / 4)
|
||||
const scaleMax = step * Math.ceil(roundedMax / step)
|
||||
return Array.from({ length: scaleMax / step + 1 }, (_, index) => scaleMax - index * step)
|
||||
}
|
||||
|
||||
const formatAxisTick = (value: number) => {
|
||||
const rounded = Math.round(value)
|
||||
return Math.abs(value - rounded) < 0.01 ? String(rounded) : value.toFixed(1)
|
||||
}
|
||||
|
||||
const panelClass = computed(() =>
|
||||
props.isDarkMode
|
||||
? 'border-[#40545c] bg-[linear-gradient(135deg,rgba(34,49,56,0.96),rgba(24,35,42,0.92))] shadow-md shadow-black/25'
|
||||
: 'border-[#d4e0e3] bg-[linear-gradient(135deg,#f8fbfb,#edf5f6)] shadow-md shadow-[#a9bdc2]/35'
|
||||
)
|
||||
const tooltipClass = computed(() =>
|
||||
props.isDarkMode
|
||||
? 'border-[#40545c] bg-[#203039] text-[#eef5f5]'
|
||||
: 'border-[#c9d9dd] bg-[#fbfdfd] text-[#263f48]'
|
||||
)
|
||||
|
||||
const formatBytes = (value: number | string | undefined) => {
|
||||
const bytes = Number(value || 0)
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1)
|
||||
return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`
|
||||
}
|
||||
|
||||
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value))
|
||||
|
||||
const getDefaultWindow = () => {
|
||||
const width = canvasRef.value?.getBoundingClientRect().width || window.innerWidth
|
||||
return Math.max(2, Math.min(props.rows.length || 2, width < 640 ? 14 : 60))
|
||||
}
|
||||
|
||||
const clampState = () => {
|
||||
const total = props.rows.length
|
||||
windowSize.value = Math.max(
|
||||
2,
|
||||
Math.min(windowSize.value || getDefaultWindow(), Math.max(2, total || 2))
|
||||
)
|
||||
offset.value = Math.max(0, Math.min(offset.value, Math.max(0, total - windowSize.value)))
|
||||
}
|
||||
|
||||
const scheduleDraw = () => {
|
||||
if (rafId.value !== null) return
|
||||
rafId.value = window.requestAnimationFrame((timestamp) => {
|
||||
rafId.value = null
|
||||
draw(timestamp)
|
||||
})
|
||||
}
|
||||
|
||||
const draw = (timestamp = performance.now()) => {
|
||||
const canvas = canvasRef.value
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
if (!rect.width || !rect.height) return
|
||||
|
||||
clampState()
|
||||
const dpr = window.devicePixelRatio || 1
|
||||
const targetWidth = Math.round(rect.width * dpr)
|
||||
const targetHeight = Math.round(rect.height * dpr)
|
||||
if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
|
||||
canvas.width = targetWidth
|
||||
canvas.height = targetHeight
|
||||
}
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
||||
ctx.clearRect(0, 0, rect.width, rect.height)
|
||||
|
||||
const total = props.rows.length
|
||||
const start = Math.max(0, Math.floor(offset.value) - 1)
|
||||
const end = Math.min(total, Math.ceil(offset.value + windowSize.value) + 2)
|
||||
const visible = props.rows.slice(start, end)
|
||||
const mobile = rect.width < 640
|
||||
const padLeft = mobile ? 34 : 42
|
||||
const padRight = mobile ? 16 : 20
|
||||
const padTop = 26
|
||||
const padBottom = mobile ? 42 : 36
|
||||
const width = Math.max(1, rect.width - padLeft - padRight)
|
||||
const height = Math.max(1, rect.height - padTop - padBottom)
|
||||
const rawMax = Math.max(
|
||||
0,
|
||||
...visible.flatMap((row) => [Number(row.downloads || 0), Number(row.uploads || 0)])
|
||||
)
|
||||
const targetTicks = getYAxisTicks(rawMax)
|
||||
const targetMax = targetTicks[0]
|
||||
const elapsedScale = lastScaleTime.value
|
||||
? Math.min(timestamp - lastScaleTime.value, INERTIA_MAX_FRAME_MS)
|
||||
: INERTIA_REFERENCE_FRAME_MS
|
||||
lastScaleTime.value = timestamp
|
||||
if (!scaleVisual.value) {
|
||||
scaleVisual.value = { max: targetMax, ticks: targetTicks }
|
||||
} else {
|
||||
const ease = 1 - Math.pow(1 - SCALE_EASE_PER_120HZ_FRAME, elapsedScale / INERTIA_REFERENCE_FRAME_MS)
|
||||
const nextMax = scaleVisual.value.max + (targetMax - scaleVisual.value.max) * ease
|
||||
scaleVisual.value = {
|
||||
max: Math.abs(nextMax - targetMax) < SCALE_SNAP_DISTANCE ? targetMax : nextMax,
|
||||
ticks: targetTicks
|
||||
}
|
||||
}
|
||||
const max = scaleVisual.value.max
|
||||
const yTicks = targetTicks.map((tick) => (tick * max) / targetMax)
|
||||
const isScaleSettling = Math.abs(max - targetMax) >= SCALE_SNAP_DISTANCE
|
||||
const muted = props.isDarkMode ? '#9ca3af' : '#6b7280'
|
||||
const border = props.isDarkMode ? '#374151' : '#e5e7eb'
|
||||
const downloadColor = props.isDarkMode ? '#8fb6c5' : '#5f8fa3'
|
||||
const uploadColor = props.isDarkMode ? '#a9c7b8' : '#759f8e'
|
||||
|
||||
ctx.strokeStyle = border
|
||||
ctx.lineWidth = 1
|
||||
ctx.fillStyle = muted
|
||||
ctx.font = '12px system-ui'
|
||||
const yTickCount = Math.max(1, yTicks.length - 1)
|
||||
yTicks.forEach((tick, index) => {
|
||||
const y = padTop + (height * index) / yTickCount
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(padLeft, y)
|
||||
ctx.lineTo(padLeft + width, y)
|
||||
ctx.stroke()
|
||||
ctx.fillText(formatAxisTick(tick), 4, y + 4)
|
||||
})
|
||||
if (isScaleSettling) scheduleDraw()
|
||||
|
||||
const denominator = Math.max(1, windowSize.value - 1)
|
||||
const plotLeft = padLeft
|
||||
const plotRight = padLeft + width
|
||||
const buildPoints = (field: 'downloads' | 'uploads') =>
|
||||
visible
|
||||
.map((row, index) => {
|
||||
const sourceIndex = start + index
|
||||
return {
|
||||
x: clamp(
|
||||
padLeft + ((sourceIndex - offset.value) / denominator) * width,
|
||||
plotLeft,
|
||||
plotRight
|
||||
),
|
||||
y: padTop + height - (Number(row[field] || 0) / max) * height,
|
||||
row
|
||||
}
|
||||
})
|
||||
.filter((point) => point.x >= plotLeft && point.x <= plotRight)
|
||||
|
||||
const drawSeries = (points: ChartPoint[], color: string) => {
|
||||
ctx.strokeStyle = color
|
||||
ctx.lineWidth = 3
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
ctx.beginPath()
|
||||
points.forEach((point, index) => {
|
||||
if (index) ctx.lineTo(point.x, point.y)
|
||||
else ctx.moveTo(point.x, point.y)
|
||||
})
|
||||
ctx.stroke()
|
||||
ctx.fillStyle = color
|
||||
points.forEach((point) => {
|
||||
ctx.beginPath()
|
||||
ctx.arc(point.x, point.y, mobile ? 4.5 : 3.5, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
})
|
||||
}
|
||||
|
||||
const downloadPoints = buildPoints('downloads')
|
||||
const uploadPoints = buildPoints('uploads')
|
||||
drawSeries(downloadPoints, downloadColor)
|
||||
drawSeries(uploadPoints, uploadColor)
|
||||
|
||||
ctx.font = '12px system-ui'
|
||||
ctx.fillStyle = muted
|
||||
ctx.fillText('下载', padLeft, 16)
|
||||
ctx.fillText('上传', padLeft + 58, 16)
|
||||
ctx.fillStyle = downloadColor
|
||||
ctx.fillRect(padLeft - 14, 8, 8, 8)
|
||||
ctx.fillStyle = uploadColor
|
||||
ctx.fillRect(padLeft + 44, 8, 8, 8)
|
||||
|
||||
const points = downloadPoints
|
||||
|
||||
const drawHoverPoint = (point: Pick<ChartPoint, 'x' | 'y'>, color: string) => {
|
||||
ctx.fillStyle = props.isDarkMode ? '#111827' : '#fff'
|
||||
ctx.strokeStyle = color
|
||||
ctx.lineWidth = 3
|
||||
ctx.beginPath()
|
||||
ctx.arc(point.x, point.y, mobile ? 8 : 6, 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
const leftRow = props.rows[Math.max(0, Math.round(offset.value))]
|
||||
const rightRow = props.rows[Math.min(total - 1, Math.round(offset.value + windowSize.value - 1))]
|
||||
if (total) {
|
||||
ctx.fillStyle = muted
|
||||
ctx.fillText(leftRow?.date || '', padLeft, rect.height - 10)
|
||||
const last = rightRow?.date || ''
|
||||
ctx.fillText(
|
||||
last,
|
||||
Math.max(padLeft, rect.width - padRight - ctx.measureText(last).width),
|
||||
rect.height - 10
|
||||
)
|
||||
}
|
||||
|
||||
emit(
|
||||
'windowChange',
|
||||
total
|
||||
? `${Math.floor(offset.value) + 1}-${Math.min(total, Math.ceil(offset.value + windowSize.value))} / ${total}`
|
||||
: '无数据'
|
||||
)
|
||||
|
||||
if (hoverX.value !== null && points.length && total) {
|
||||
const hoverRatio = clamp((hoverX.value - padLeft) / width, 0, 1)
|
||||
const sourceIndex = Math.round(clamp(offset.value + hoverRatio * denominator, 0, total - 1))
|
||||
const row = props.rows[sourceIndex]
|
||||
const snapX = padLeft + ((sourceIndex - offset.value) / denominator) * width
|
||||
const downloads = Number(row.downloads || 0)
|
||||
const uploads = Number(row.uploads || 0)
|
||||
const downloadTraffic = Number(row.downloadTraffic || 0)
|
||||
const uploadTraffic = Number(row.uploadTraffic || 0)
|
||||
const downloadY = padTop + height - (downloads / max) * height
|
||||
const uploadY = padTop + height - (uploads / max) * height
|
||||
const elapsed = lastHoverTime.value
|
||||
? Math.min(timestamp - lastHoverTime.value, INERTIA_MAX_FRAME_MS)
|
||||
: INERTIA_REFERENCE_FRAME_MS
|
||||
lastHoverTime.value = timestamp
|
||||
|
||||
if (!hoverVisual.value) {
|
||||
hoverVisual.value = { x: snapX, downloadY, uploadY }
|
||||
} else {
|
||||
const ease = 1 - Math.pow(1 - HOVER_EASE_PER_120HZ_FRAME, elapsed / INERTIA_REFERENCE_FRAME_MS)
|
||||
const nextX = hoverVisual.value.x + (snapX - hoverVisual.value.x) * ease
|
||||
const nextDownloadY = hoverVisual.value.downloadY + (downloadY - hoverVisual.value.downloadY) * ease
|
||||
const nextUploadY = hoverVisual.value.uploadY + (uploadY - hoverVisual.value.uploadY) * ease
|
||||
hoverVisual.value = {
|
||||
x: Math.abs(nextX - snapX) < HOVER_SNAP_DISTANCE ? snapX : nextX,
|
||||
downloadY:
|
||||
Math.abs(nextDownloadY - downloadY) < HOVER_SNAP_DISTANCE ? downloadY : nextDownloadY,
|
||||
uploadY: Math.abs(nextUploadY - uploadY) < HOVER_SNAP_DISTANCE ? uploadY : nextUploadY
|
||||
}
|
||||
}
|
||||
|
||||
const visual = hoverVisual.value
|
||||
const anchorY = Math.min(visual.downloadY, visual.uploadY)
|
||||
const placeBelow = anchorY < 104
|
||||
const tooltipInset = Math.min(mobile ? 116 : 132, Math.max(48, rect.width / 2 - 8))
|
||||
|
||||
ctx.strokeStyle = props.isDarkMode ? 'rgba(148, 163, 184, 0.35)' : 'rgba(91, 121, 132, 0.28)'
|
||||
ctx.lineWidth = 1
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(visual.x, padTop)
|
||||
ctx.lineTo(visual.x, padTop + height)
|
||||
ctx.stroke()
|
||||
|
||||
tooltip.value = {
|
||||
left: clamp(visual.x, tooltipInset, rect.width - tooltipInset),
|
||||
top: placeBelow ? anchorY + 16 : anchorY - 12,
|
||||
date: row.date,
|
||||
downloads,
|
||||
uploads,
|
||||
downloadTraffic: formatBytes(downloadTraffic),
|
||||
uploadTraffic: formatBytes(uploadTraffic),
|
||||
transform: placeBelow ? 'translate(-50%, 0)' : 'translate(-50%, -100%)'
|
||||
}
|
||||
drawHoverPoint({ x: visual.x, y: visual.downloadY }, downloadColor)
|
||||
drawHoverPoint({ x: visual.x, y: visual.uploadY }, uploadColor)
|
||||
|
||||
if (
|
||||
Math.abs(visual.x - snapX) >= HOVER_SNAP_DISTANCE ||
|
||||
Math.abs(visual.downloadY - downloadY) >= HOVER_SNAP_DISTANCE ||
|
||||
Math.abs(visual.uploadY - uploadY) >= HOVER_SNAP_DISTANCE
|
||||
) {
|
||||
scheduleDraw()
|
||||
}
|
||||
} else {
|
||||
hoverVisual.value = null
|
||||
lastHoverTime.value = 0
|
||||
tooltip.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const pan = (deltaX: number, shouldScheduleDraw = true) => {
|
||||
const rect = canvasRef.value?.getBoundingClientRect()
|
||||
if (!rect) return
|
||||
offset.value += (-deltaX / Math.max(1, rect.width)) * Math.max(1, windowSize.value - 1) * 1.15
|
||||
clampState()
|
||||
if (shouldScheduleDraw) scheduleDraw()
|
||||
}
|
||||
|
||||
const zoom = (factor: number, center = 0.5) => {
|
||||
clampState()
|
||||
const minWindow = Math.min(props.rows.length || 2, window.innerWidth < 640 ? 5 : 7)
|
||||
const next = Math.max(minWindow, Math.min(props.rows.length || 2, windowSize.value * factor))
|
||||
const anchor = offset.value + windowSize.value * center
|
||||
windowSize.value = next
|
||||
offset.value = anchor - next * center
|
||||
clampState()
|
||||
scheduleDraw()
|
||||
}
|
||||
|
||||
const cancelInertia = () => {
|
||||
if (inertiaRafId.value !== null) {
|
||||
window.cancelAnimationFrame(inertiaRafId.value)
|
||||
inertiaRafId.value = null
|
||||
}
|
||||
lastInertiaTime.value = 0
|
||||
}
|
||||
|
||||
const applyInertia = (timestamp: number) => {
|
||||
if (Math.abs(velocity.value) < INERTIA_STOP_VELOCITY) {
|
||||
cancelInertia()
|
||||
return
|
||||
}
|
||||
|
||||
const elapsed = lastInertiaTime.value
|
||||
? Math.min(timestamp - lastInertiaTime.value, INERTIA_MAX_FRAME_MS)
|
||||
: INERTIA_REFERENCE_FRAME_MS
|
||||
lastInertiaTime.value = timestamp
|
||||
|
||||
pan(velocity.value * elapsed, false)
|
||||
draw(timestamp)
|
||||
velocity.value *= Math.pow(
|
||||
INERTIA_DECAY_PER_120HZ_FRAME,
|
||||
elapsed / INERTIA_REFERENCE_FRAME_MS
|
||||
)
|
||||
inertiaRafId.value = window.requestAnimationFrame(applyInertia)
|
||||
}
|
||||
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
const rect = canvasRef.value?.getBoundingClientRect()
|
||||
zoom(event.deltaY > 0 ? 1.16 : 0.86, rect ? (event.clientX - rect.left) / rect.width : 0.5)
|
||||
}
|
||||
|
||||
const setHoverFromClientX = (clientX: number) => {
|
||||
const rect = canvasRef.value?.getBoundingClientRect()
|
||||
if (!rect) return
|
||||
hoverX.value = clamp(clientX - rect.left, 0, rect.width)
|
||||
scheduleDraw()
|
||||
}
|
||||
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const rect = canvasRef.value?.getBoundingClientRect()
|
||||
canvasRef.value?.setPointerCapture(event.pointerId)
|
||||
cancelInertia()
|
||||
velocity.value = 0
|
||||
setHoverFromClientX(event.clientX)
|
||||
const isTimeline = Boolean(rect && event.clientY - rect.top >= rect.height - 52)
|
||||
drag.value = {
|
||||
startOffset: offset.value,
|
||||
lastX: event.clientX,
|
||||
time: event.timeStamp || performance.now(),
|
||||
pointerType: event.pointerType,
|
||||
isTimeline,
|
||||
moved: false
|
||||
}
|
||||
if (isTimeline) canvasRef.value!.style.touchAction = 'none'
|
||||
}
|
||||
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
const rect = canvasRef.value?.getBoundingClientRect()
|
||||
const coalescedEvents = event.getCoalescedEvents?.() || []
|
||||
const pointerEvents = coalescedEvents.length ? coalescedEvents : [event]
|
||||
const latestEvent = pointerEvents[pointerEvents.length - 1] || event
|
||||
if (rect) hoverX.value = latestEvent.clientX - rect.left
|
||||
if (!drag.value) {
|
||||
scheduleDraw()
|
||||
return
|
||||
}
|
||||
|
||||
if (drag.value.pointerType === 'touch' && !drag.value.isTimeline) {
|
||||
scheduleDraw()
|
||||
return
|
||||
}
|
||||
|
||||
const totalDistance = Math.abs(latestEvent.clientX - drag.value.lastX)
|
||||
const threshold = 3
|
||||
if (!drag.value.moved && totalDistance < threshold) {
|
||||
scheduleDraw()
|
||||
return
|
||||
}
|
||||
drag.value.moved = true
|
||||
|
||||
pointerEvents.forEach((pointerEvent) => {
|
||||
const now = pointerEvent.timeStamp || performance.now()
|
||||
const deltaX = pointerEvent.clientX - drag.value!.lastX
|
||||
const deltaTime = Math.max(1, now - drag.value!.time)
|
||||
velocity.value = deltaX / deltaTime
|
||||
pan(deltaX)
|
||||
drag.value = { ...drag.value!, lastX: pointerEvent.clientX, time: now, moved: true }
|
||||
})
|
||||
}
|
||||
|
||||
const handlePointerUp = () => {
|
||||
const timelineDrag = drag.value?.isTimeline
|
||||
const shouldInertia = Boolean(drag.value?.moved)
|
||||
drag.value = null
|
||||
if (canvasRef.value) canvasRef.value.style.touchAction = ''
|
||||
cancelInertia()
|
||||
if (shouldInertia && !timelineDrag) inertiaRafId.value = window.requestAnimationFrame(applyInertia)
|
||||
else scheduleDraw()
|
||||
}
|
||||
|
||||
const handlePointerCancel = () => {
|
||||
drag.value = null
|
||||
if (canvasRef.value) canvasRef.value.style.touchAction = ''
|
||||
}
|
||||
|
||||
const handlePointerLeave = () => {
|
||||
drag.value = null
|
||||
hoverX.value = null
|
||||
hoverVisual.value = null
|
||||
lastHoverTime.value = 0
|
||||
scheduleDraw()
|
||||
}
|
||||
|
||||
const resetWindow = () => {
|
||||
windowSize.value = getDefaultWindow()
|
||||
offset.value = Math.max(0, props.rows.length - windowSize.value)
|
||||
scheduleDraw()
|
||||
}
|
||||
|
||||
const handleResize = () => scheduleDraw()
|
||||
|
||||
watch(
|
||||
() => props.rows,
|
||||
async () => {
|
||||
await nextTick()
|
||||
resetWindow()
|
||||
},
|
||||
{ deep: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
resetWindow()
|
||||
window.addEventListener('resize', handleResize)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
if (rafId.value !== null) window.cancelAnimationFrame(rafId.value)
|
||||
cancelInertia()
|
||||
})
|
||||
|
||||
defineExpose({ zoom, resetWindow })
|
||||
</script>
|
||||
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<div
|
||||
class="theme-2026-card theme-2026-card-hover group rounded-[24px] p-4 shadow-md transition-all duration-300 hover:-translate-y-0.5 hover:shadow-lg sm:rounded-[30px] sm:p-6"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'hover:bg-gray-800 hover:shadow-black/20'
|
||||
: 'hover:shadow-gray-200/80'
|
||||
]"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<p class="line-clamp-2 text-xs leading-tight sm:text-sm" :title="title" :class="[isDarkMode ? 'text-gray-300' : 'text-gray-600']">
|
||||
{{ title }}
|
||||
</p>
|
||||
<h3 class="mt-1 whitespace-nowrap text-lg font-bold leading-tight tabular-nums sm:text-2xl" :title="String(value)" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">
|
||||
{{ value }}
|
||||
</h3>
|
||||
</div>
|
||||
<div
|
||||
class="shrink-0 rounded-full p-2.5 transition-transform duration-300 group-hover:scale-105 sm:p-3"
|
||||
:class="iconBgClass"
|
||||
>
|
||||
<component :is="icon" class="h-5 w-5 sm:h-6 sm:w-6" :class="iconClass" aria-hidden="true" />
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-2 line-clamp-2 text-xs sm:text-sm" :class="descriptionClass">
|
||||
<slot name="description"></slot>
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { Component } from 'vue'
|
||||
import { useInjectedDarkMode } from '@/composables'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
value: string | number
|
||||
icon: Component
|
||||
iconColor: 'indigo' | 'purple' | 'green' | 'blue'
|
||||
descriptionType?: 'success' | 'error' | 'neutral'
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
descriptionType: 'neutral'
|
||||
})
|
||||
|
||||
const isDarkMode = useInjectedDarkMode()
|
||||
|
||||
const iconBgClass = computed(() => {
|
||||
const colorMap = {
|
||||
indigo: isDarkMode.value ? 'bg-[#294047]' : 'bg-[#dcebed]',
|
||||
purple: isDarkMode.value ? 'bg-[#443d4b]' : 'bg-[#e7e2ea]',
|
||||
green: isDarkMode.value ? 'bg-[#31564f]' : 'bg-[#e1eee8]',
|
||||
blue: isDarkMode.value ? 'bg-[#2d4851]' : 'bg-[#dce8eb]'
|
||||
}
|
||||
return colorMap[props.iconColor]
|
||||
})
|
||||
|
||||
const iconClass = computed(() => {
|
||||
const colorMap = {
|
||||
indigo: isDarkMode.value ? 'text-[#b8d4dc]' : 'text-[#3f6a77]',
|
||||
purple: isDarkMode.value ? 'text-[#d4c8dc]' : 'text-[#6f6379]',
|
||||
green: isDarkMode.value ? 'text-[#c4dfd5]' : 'text-[#55796e]',
|
||||
blue: isDarkMode.value ? 'text-[#bfd9df]' : 'text-[#4b7380]'
|
||||
}
|
||||
return colorMap[props.iconColor]
|
||||
})
|
||||
|
||||
const descriptionClass = computed(() => {
|
||||
const typeMap = {
|
||||
success: isDarkMode.value ? 'text-[#b6d6ca]' : 'text-[#5f8377]',
|
||||
error: isDarkMode.value ? 'text-[#e5c5ca]' : 'text-[#8b5962]',
|
||||
neutral: isDarkMode.value ? 'text-gray-400' : 'text-gray-600'
|
||||
}
|
||||
return typeMap[props.descriptionType]
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,94 @@
|
||||
<template>
|
||||
<div class="flex flex-col">
|
||||
<textarea
|
||||
:value="modelValue"
|
||||
@input="updateValue"
|
||||
:rows="rows"
|
||||
:placeholder="placeholderText"
|
||||
:class="[
|
||||
'flex-grow px-4 py-3 rounded-xl placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-300 resize-none custom-scrollbar',
|
||||
isDarkMode
|
||||
? 'bg-gray-800 bg-opacity-50 text-white'
|
||||
: 'bg-white text-gray-900 border border-gray-300'
|
||||
]"
|
||||
></textarea>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { inject, computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
interface Props {
|
||||
modelValue: string
|
||||
rows?: number
|
||||
placeholder?: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
'update:modelValue': [value: string]
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
rows: 7,
|
||||
placeholder: '在此输入要发送的文本...'
|
||||
})
|
||||
|
||||
const emit = defineEmits<Emits>()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
|
||||
// 使用computed属性处理多语言文本
|
||||
const placeholderText = computed(() => props.placeholder || t('send.uploadArea.textInput'))
|
||||
|
||||
const updateValue = (event: Event) => {
|
||||
const target = event.target as HTMLTextAreaElement
|
||||
emit('update:modelValue', target.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 自定义滚动条样式 */
|
||||
.custom-scrollbar {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: rgba(156, 163, 175, 0.3) rgba(243, 244, 246, 0.5);
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: rgba(243, 244, 246, 0.5);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(156, 163, 175, 0.5);
|
||||
border-radius: 3px;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(156, 163, 175, 0.7);
|
||||
}
|
||||
|
||||
/* 深色模式下的滚动条样式 */
|
||||
:deep([class*='dark']) .custom-scrollbar {
|
||||
scrollbar-color: rgba(75, 85, 99, 0.5) rgba(31, 41, 55, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: rgba(31, 41, 55, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background-color: rgba(75, 85, 99, 0.5);
|
||||
}
|
||||
|
||||
:deep([class*='dark']) .custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(75, 85, 99, 0.7);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
import { inject } from 'vue'
|
||||
import { SunIcon, MoonIcon } from 'lucide-vue-next'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const isDarkMode = inject('isDarkMode') as { value: boolean }
|
||||
const toggleTheme = inject('toggleTheme') as () => void
|
||||
const { t } = useI18n()
|
||||
|
||||
const toggleColorMode = () => {
|
||||
toggleTheme()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
@click="toggleColorMode"
|
||||
class="flex h-11 w-11 items-center justify-center rounded-full shadow-sm transition-all duration-200 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-[#8fb2bf] focus:ring-offset-2 motion-safe:hover:rotate-180"
|
||||
:aria-label="isDarkMode ? t('common.switchToLight') : t('common.switchToDark')"
|
||||
:title="isDarkMode ? t('common.switchToLight') : t('common.switchToDark')"
|
||||
:class="
|
||||
isDarkMode
|
||||
? 'bg-[#263941] text-[#d8c98e]'
|
||||
: 'bg-[#edf4f5] text-[#4f6c75]'
|
||||
"
|
||||
>
|
||||
<SunIcon v-if="!isDarkMode" class="w-6 h-6" />
|
||||
<MoonIcon v-else class="w-6 h-6" />
|
||||
</button>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
type ScrollLockOwner = symbol
|
||||
|
||||
let owners = new Set<ScrollLockOwner>()
|
||||
let previousOverflow = ''
|
||||
|
||||
export function lockBodyScroll(): ScrollLockOwner {
|
||||
const owner = Symbol('scroll-lock-owner')
|
||||
if (owners.size === 0) {
|
||||
previousOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
owners.add(owner)
|
||||
return owner
|
||||
}
|
||||
|
||||
export function unlockBodyScroll(owner: ScrollLockOwner | null | undefined): void {
|
||||
if (!owner || !owners.delete(owner)) return
|
||||
if (owners.size === 0) {
|
||||
document.body.style.overflow = previousOverflow
|
||||
previousOverflow = ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export { useAdminActivities } from './useAdminActivities'
|
||||
export { useAdminTrash } from './useAdminTrash'
|
||||
export { useAdminFiles } from './useAdminFiles'
|
||||
export { useAdminLogin } from './useAdminLogin'
|
||||
export { useAdminSession } from './useAdminSession'
|
||||
export { useAppShell } from './useAppShell'
|
||||
export { useDashboardStats } from './useDashboardStats'
|
||||
export { useInjectedDarkMode } from './useInjectedDarkMode'
|
||||
export { useClipboard } from './useClipboard'
|
||||
export { usePresignedUpload } from './usePresignedUpload'
|
||||
export { usePublicConfigBootstrap } from './usePublicConfigBootstrap'
|
||||
export { useRetrieveFlow } from './useRetrieveFlow'
|
||||
export { useRouteLoading } from './useRouteLoading'
|
||||
export { useSendFlow } from './useSendFlow'
|
||||
export { useSystemConfig } from './useSystemConfig'
|
||||
export { useTheme } from './useTheme'
|
||||
export { useTransferAnalytics } from './useTransferAnalytics'
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ActivityService } from '@/services'
|
||||
import type { AdminActivityListParams, AdminActivityListResponse } from '@/types'
|
||||
|
||||
export function useAdminActivities() {
|
||||
const fetchAdminActivities = async (
|
||||
params: AdminActivityListParams
|
||||
): Promise<AdminActivityListResponse | null> => {
|
||||
const response = await ActivityService.getAdminActivities(params)
|
||||
return response.detail || null
|
||||
}
|
||||
|
||||
return { fetchAdminActivities }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
import { ref } from 'vue'
|
||||
import { AuthService } from '@/services'
|
||||
import { useAdminStore } from '@/stores/adminStore'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { getErrorMessage } from '@/utils/common'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useAdminLogin() {
|
||||
const { t } = useI18n()
|
||||
const alertStore = useAlertStore()
|
||||
const adminStore = useAdminStore()
|
||||
const password = ref('')
|
||||
const isLoading = ref(false)
|
||||
|
||||
const validateForm = () => {
|
||||
if (!password.value) {
|
||||
alertStore.showAlert(t('manage.login.invalidPassword'), 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (password.value.length < 6) {
|
||||
alertStore.showAlert(t('manage.login.passwordTooShort'), 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!validateForm()) return false
|
||||
|
||||
isLoading.value = true
|
||||
try {
|
||||
const response = await AuthService.login(password.value)
|
||||
if (!response.detail?.token) {
|
||||
alertStore.showAlert(t('manage.login.noValidToken'), 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
adminStore.login({
|
||||
id: response.detail.id || 'admin',
|
||||
username: response.detail.username || 'admin',
|
||||
token: response.detail.token,
|
||||
token_type: response.detail.token_type,
|
||||
expires_at: response.detail.expires_at
|
||||
})
|
||||
return true
|
||||
} catch (error: unknown) {
|
||||
alertStore.showAlert(getErrorMessage(error, t('manage.login.loginFailed')), 'error')
|
||||
return false
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
password,
|
||||
isLoading,
|
||||
handleSubmit
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { AuthService } from '@/services'
|
||||
import { useAdminStore } from '@/stores/adminStore'
|
||||
|
||||
export function useAdminSession() {
|
||||
const adminStore = useAdminStore()
|
||||
|
||||
const verifySession = async () => {
|
||||
if (!adminStore.hasToken) return false
|
||||
|
||||
try {
|
||||
const response = await AuthService.verifyToken()
|
||||
// The current stored bearer token is what was just verified by the server.
|
||||
// Do not redirect a valid session merely because an adapter omits a token
|
||||
// field in the verification payload; only replace it when one is supplied.
|
||||
if (response.code === 200) {
|
||||
if (response.detail?.token) {
|
||||
adminStore.login(response.detail)
|
||||
}
|
||||
return true
|
||||
}
|
||||
} catch {
|
||||
adminStore.logout()
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await AuthService.logout()
|
||||
} finally {
|
||||
adminStore.logout()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
verifySession,
|
||||
logout
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TrashService } from '@/services'
|
||||
import type { TrashListParams, TrashListResponse } from '@/types'
|
||||
|
||||
export function useAdminTrash() {
|
||||
const fetchTrash = async (params: TrashListParams): Promise<TrashListResponse | null> => {
|
||||
const response = await TrashService.list(params)
|
||||
return response.detail || null
|
||||
}
|
||||
|
||||
const restoreTrashItem = async (id: number) => TrashService.restore(id)
|
||||
const purgeTrashItem = async (id: number) => TrashService.purge(id)
|
||||
const updateTrashRetention = async (id: number, retentionDays: number) =>
|
||||
TrashService.updateRetention(id, retentionDays)
|
||||
|
||||
return { fetchTrash, restoreTrashItem, purgeTrashItem, updateTrashRetention }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { computed, onMounted, onUnmounted, provide } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { AUTH_EVENTS } from '@/services'
|
||||
import { ROUTES } from '@/constants'
|
||||
import { useTheme } from './useTheme'
|
||||
import { usePublicConfigBootstrap } from './usePublicConfigBootstrap'
|
||||
import { useRouteLoading } from './useRouteLoading'
|
||||
|
||||
export function useAppShell() {
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { isDarkMode, toggleTheme, initTheme } = useTheme()
|
||||
const { isLoading, setupRouteLoading } = useRouteLoading(router)
|
||||
const { syncPublicConfig } = usePublicConfigBootstrap()
|
||||
const showGlobalControls = computed(() => route.meta.showGlobalControls !== false)
|
||||
const routeTransitionName = computed(() => String(route.meta.routeTransition || 'fade'))
|
||||
const routeTransitionMode = computed(() => (route.meta.routeTransition ? undefined : 'out-in'))
|
||||
const routeViewKey = computed(() =>
|
||||
route.path === ROUTES.ADMIN || route.path.startsWith(`${ROUTES.ADMIN}/`)
|
||||
? ROUTES.ADMIN
|
||||
: route.fullPath
|
||||
)
|
||||
|
||||
let cleanupThemeListener: (() => void) | null = null
|
||||
|
||||
const handleUnauthorized = () => {
|
||||
if (router.currentRoute.value.path !== ROUTES.LOGIN) {
|
||||
void router.push({
|
||||
path: ROUTES.LOGIN,
|
||||
query: {
|
||||
redirect: router.currentRoute.value.fullPath
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
cleanupThemeListener = initTheme()
|
||||
setupRouteLoading()
|
||||
window.addEventListener(AUTH_EVENTS.UNAUTHORIZED, handleUnauthorized)
|
||||
void syncPublicConfig()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
cleanupThemeListener?.()
|
||||
window.removeEventListener(AUTH_EVENTS.UNAUTHORIZED, handleUnauthorized)
|
||||
})
|
||||
|
||||
provide('isDarkMode', isDarkMode)
|
||||
provide('toggleTheme', toggleTheme)
|
||||
provide('isLoading', isLoading)
|
||||
|
||||
return {
|
||||
isDarkMode,
|
||||
isLoading,
|
||||
route,
|
||||
routeTransitionMode,
|
||||
routeTransitionName,
|
||||
routeViewKey,
|
||||
showGlobalControls
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { copyToClipboard as copy } from '@/utils/clipboard'
|
||||
|
||||
export function useClipboard() {
|
||||
const copyToClipboard = (value: string) => copy(value)
|
||||
return { copyToClipboard }
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { computed, ref, reactive } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { StatsService } from '@/services'
|
||||
import type { DashboardData, DashboardHealthSummary, DashboardViewData } from '@/types'
|
||||
import { formatFileSize, getErrorMessage } from '@/utils/common'
|
||||
|
||||
type UseDashboardStatsOptions = {
|
||||
loadFailedMessage?: string
|
||||
}
|
||||
|
||||
const emptyDashboardData = (): DashboardViewData => ({
|
||||
hasExtendedStats: false,
|
||||
totalFiles: 0,
|
||||
storageUsed: 0,
|
||||
yesterdayCount: 0,
|
||||
todayCount: 0,
|
||||
yesterdaySize: 0,
|
||||
todaySize: 0,
|
||||
sysUptime: null,
|
||||
activeCount: 0,
|
||||
expiredCount: 0,
|
||||
textCount: 0,
|
||||
fileCount: 0,
|
||||
chunkedCount: 0,
|
||||
usedCount: 0,
|
||||
storageBackend: '-',
|
||||
uploadSizeLimit: 0,
|
||||
openUpload: 0,
|
||||
enableChunk: 0,
|
||||
maxSaveSeconds: 0,
|
||||
healthAttentionCount: 0,
|
||||
healthDangerCount: 0,
|
||||
healthWarningCount: 0,
|
||||
expiringSoonCount: 0,
|
||||
storageIssueCount: 0,
|
||||
neverRetrievedCount: 0,
|
||||
healthyCount: 0,
|
||||
permanentCount: 0,
|
||||
storageUsedText: '0 Bytes',
|
||||
yesterdaySizeText: '0 Bytes',
|
||||
todaySizeText: '0 Bytes',
|
||||
uploadSizeLimitText: '0 Bytes',
|
||||
sysUptimeText: '-',
|
||||
activeRatio: 0,
|
||||
textRatio: 0,
|
||||
fileRatio: 0,
|
||||
healthyRatio: 0,
|
||||
healthAttentionRatio: 0,
|
||||
todaySizeRatio: 0
|
||||
})
|
||||
|
||||
const toNumber = (value: number | string | null | undefined) => Number(value || 0)
|
||||
|
||||
const clampRatio = (value: number) => Math.max(0, Math.min(100, Math.round(value)))
|
||||
|
||||
const hasOwn = (target: object, key: string) => Object.prototype.hasOwnProperty.call(target, key)
|
||||
|
||||
const formatDuration = (startTimestamp: number | null, dayLabel: string, hourLabel: string) => {
|
||||
if (!startTimestamp) return '-'
|
||||
const uptime = Date.now() - startTimestamp
|
||||
const days = Math.floor(uptime / (24 * 60 * 60 * 1000))
|
||||
const hours = Math.floor((uptime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
|
||||
return `${days}${dayLabel} ${hours}${hourLabel}`
|
||||
}
|
||||
|
||||
const healthSummaryKeys: (keyof DashboardHealthSummary)[] = [
|
||||
'healthAttentionCount',
|
||||
'healthDangerCount',
|
||||
'healthWarningCount',
|
||||
'expiringSoonCount',
|
||||
'storageIssueCount',
|
||||
'neverRetrievedCount',
|
||||
'healthyCount',
|
||||
'permanentCount'
|
||||
]
|
||||
|
||||
const normalizeHealthSummary = (detail: DashboardData): DashboardHealthSummary => ({
|
||||
healthAttentionCount: toNumber(
|
||||
detail.healthSummary?.healthAttentionCount ?? detail.healthAttentionCount
|
||||
),
|
||||
healthDangerCount: toNumber(detail.healthSummary?.healthDangerCount ?? detail.healthDangerCount),
|
||||
healthWarningCount: toNumber(
|
||||
detail.healthSummary?.healthWarningCount ?? detail.healthWarningCount
|
||||
),
|
||||
expiringSoonCount: toNumber(detail.healthSummary?.expiringSoonCount ?? detail.expiringSoonCount),
|
||||
storageIssueCount: toNumber(detail.healthSummary?.storageIssueCount ?? detail.storageIssueCount),
|
||||
neverRetrievedCount: toNumber(
|
||||
detail.healthSummary?.neverRetrievedCount ?? detail.neverRetrievedCount
|
||||
),
|
||||
healthyCount: toNumber(detail.healthSummary?.healthyCount ?? detail.healthyCount),
|
||||
permanentCount: toNumber(detail.healthSummary?.permanentCount ?? detail.permanentCount)
|
||||
})
|
||||
|
||||
export function useDashboardStats(options: UseDashboardStatsOptions = {}) {
|
||||
const { t, locale } = useI18n()
|
||||
const dashboardData = reactive<DashboardViewData>(emptyDashboardData())
|
||||
const isLoading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const lastUpdatedAt = ref<Date | null>(null)
|
||||
const lastUpdatedText = computed(() =>
|
||||
lastUpdatedAt.value
|
||||
? new Intl.DateTimeFormat(locale.value, { dateStyle: 'medium', timeStyle: 'short' }).format(lastUpdatedAt.value)
|
||||
: '-'
|
||||
)
|
||||
|
||||
const fetchDashboardData = async () => {
|
||||
isLoading.value = true
|
||||
errorMessage.value = ''
|
||||
|
||||
try {
|
||||
const response = await StatsService.getDashboard()
|
||||
if (!response.detail) {
|
||||
throw new Error('No dashboard data')
|
||||
}
|
||||
|
||||
const detail = response.detail
|
||||
dashboardData.totalFiles = toNumber(detail.totalFiles)
|
||||
dashboardData.storageUsed = toNumber(detail.storageUsed)
|
||||
dashboardData.yesterdayCount = toNumber(detail.yesterdayCount)
|
||||
dashboardData.todayCount = toNumber(detail.todayCount)
|
||||
dashboardData.yesterdaySize = toNumber(detail.yesterdaySize)
|
||||
dashboardData.todaySize = toNumber(detail.todaySize)
|
||||
dashboardData.sysUptime = detail.sysUptime
|
||||
dashboardData.hasExtendedStats = hasOwn(detail, 'activeCount')
|
||||
dashboardData.activeCount = dashboardData.hasExtendedStats
|
||||
? toNumber(detail.activeCount)
|
||||
: dashboardData.totalFiles
|
||||
dashboardData.expiredCount = toNumber(detail.expiredCount)
|
||||
dashboardData.textCount = toNumber(detail.textCount)
|
||||
dashboardData.fileCount = toNumber(detail.fileCount)
|
||||
dashboardData.chunkedCount = toNumber(detail.chunkedCount)
|
||||
dashboardData.usedCount = toNumber(detail.usedCount)
|
||||
dashboardData.storageBackend = detail.storageBackend || '-'
|
||||
dashboardData.uploadSizeLimit = toNumber(detail.uploadSizeLimit)
|
||||
dashboardData.openUpload = toNumber(detail.openUpload)
|
||||
dashboardData.enableChunk = toNumber(detail.enableChunk)
|
||||
dashboardData.maxSaveSeconds = toNumber(detail.maxSaveSeconds)
|
||||
const healthSummary = normalizeHealthSummary(detail)
|
||||
healthSummaryKeys.forEach((key) => {
|
||||
dashboardData[key] = healthSummary[key]
|
||||
})
|
||||
|
||||
dashboardData.storageUsedText = formatFileSize(dashboardData.storageUsed)
|
||||
dashboardData.yesterdaySizeText = formatFileSize(dashboardData.yesterdaySize)
|
||||
dashboardData.todaySizeText = formatFileSize(dashboardData.todaySize)
|
||||
dashboardData.uploadSizeLimitText = formatFileSize(dashboardData.uploadSizeLimit)
|
||||
dashboardData.sysUptimeText = formatDuration(
|
||||
dashboardData.sysUptime,
|
||||
t('common.dayShort'),
|
||||
t('common.hourShort')
|
||||
)
|
||||
dashboardData.activeRatio = dashboardData.totalFiles
|
||||
? clampRatio((dashboardData.activeCount / dashboardData.totalFiles) * 100)
|
||||
: 0
|
||||
dashboardData.textRatio = dashboardData.totalFiles
|
||||
? clampRatio((dashboardData.textCount / dashboardData.totalFiles) * 100)
|
||||
: 0
|
||||
dashboardData.fileRatio = dashboardData.totalFiles
|
||||
? clampRatio((dashboardData.fileCount / dashboardData.totalFiles) * 100)
|
||||
: 0
|
||||
dashboardData.healthyRatio = dashboardData.totalFiles
|
||||
? clampRatio((dashboardData.healthyCount / dashboardData.totalFiles) * 100)
|
||||
: 0
|
||||
dashboardData.healthAttentionRatio = dashboardData.totalFiles
|
||||
? clampRatio((dashboardData.healthAttentionCount / dashboardData.totalFiles) * 100)
|
||||
: 0
|
||||
dashboardData.todaySizeRatio = dashboardData.uploadSizeLimit
|
||||
? clampRatio((dashboardData.todaySize / dashboardData.uploadSizeLimit) * 100)
|
||||
: 0
|
||||
lastUpdatedAt.value = new Date()
|
||||
} catch (error) {
|
||||
errorMessage.value = getErrorMessage(
|
||||
error,
|
||||
options.loadFailedMessage || 'Failed to load dashboard data'
|
||||
)
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dashboardData,
|
||||
errorMessage,
|
||||
fetchDashboardData,
|
||||
isLoading,
|
||||
lastUpdatedText
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { computed, inject, unref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
export function useInjectedDarkMode() {
|
||||
const injectedDarkMode = inject<Ref<boolean> | boolean>('isDarkMode', false)
|
||||
return computed(() => Boolean(unref(injectedDarkMode)))
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import { ref, computed, readonly } from 'vue'
|
||||
import { PresignUploadService } from '@/services'
|
||||
import type {
|
||||
PresignUploadStatus,
|
||||
PresignUploadMode,
|
||||
PresignInitResponse,
|
||||
PresignUploadOptions,
|
||||
PresignStatusResponse,
|
||||
UploadProgress,
|
||||
ExpireStyle,
|
||||
AlertType
|
||||
} from '@/types'
|
||||
import { getErrorMessage } from '@/utils/common'
|
||||
|
||||
// 预签名上传状态常量
|
||||
export const PRESIGN_UPLOAD_STATUS = {
|
||||
IDLE: 'idle',
|
||||
INITIALIZING: 'initializing',
|
||||
UPLOADING: 'uploading',
|
||||
CONFIRMING: 'confirming',
|
||||
SUCCESS: 'success',
|
||||
ERROR: 'error'
|
||||
} as const
|
||||
|
||||
// 默认过期配置
|
||||
const DEFAULT_EXPIRE_VALUE = 1
|
||||
const DEFAULT_EXPIRE_STYLE: ExpireStyle = 'day'
|
||||
|
||||
type ErrorWithResponse = {
|
||||
response?: {
|
||||
status?: number
|
||||
}
|
||||
}
|
||||
|
||||
type PresignedUploadNotifier = (message: string, type: AlertType) => void
|
||||
|
||||
type UsePresignedUploadOptions = {
|
||||
getMaxFileSize?: () => number
|
||||
notify?: PresignedUploadNotifier
|
||||
onStatus?: (status: PresignUploadStatus) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 预签名上传 Composable
|
||||
* 支持 S3 直传模式和服务器代理模式
|
||||
*/
|
||||
export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
|
||||
// 状态管理
|
||||
const presignStatus = ref<PresignUploadStatus>(PRESIGN_UPLOAD_STATUS.IDLE)
|
||||
const uploadSession = ref<PresignInitResponse | null>(null)
|
||||
const uploadProgress = ref<UploadProgress>({
|
||||
loaded: 0,
|
||||
total: 0,
|
||||
percentage: 0
|
||||
})
|
||||
const uploadedCode = ref<string>('')
|
||||
const errorMessage = ref<string>('')
|
||||
|
||||
// 计算属性
|
||||
const isInitializing = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.INITIALIZING)
|
||||
const isUploading = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.UPLOADING)
|
||||
const isConfirming = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.CONFIRMING)
|
||||
const isSuccess = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.SUCCESS)
|
||||
const isError = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.ERROR)
|
||||
const currentMode = computed<PresignUploadMode | null>(() => uploadSession.value?.mode ?? null)
|
||||
|
||||
const notify: PresignedUploadNotifier = (message, type) => {
|
||||
options.notify?.(message, type)
|
||||
}
|
||||
const onStatus = options.onStatus
|
||||
|
||||
/**
|
||||
* 文件大小验证
|
||||
*/
|
||||
const validateFileSize = (file: File): boolean => {
|
||||
const maxFileSize = options.getMaxFileSize?.()
|
||||
if (!maxFileSize) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (file.size > maxFileSize) {
|
||||
const maxSizeMB = Math.round(maxFileSize / 1024 / 1024)
|
||||
errorMessage.value = `文件大小不能超过 ${maxSizeMB}MB`
|
||||
notify(errorMessage.value, 'error')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 进度追踪回调
|
||||
*/
|
||||
const createProgressHandler = (
|
||||
externalHandler?: (progress: UploadProgress) => void
|
||||
): ((progress: UploadProgress) => void) => {
|
||||
return (progress: UploadProgress) => {
|
||||
// 确保进度值在有效范围内
|
||||
uploadProgress.value = {
|
||||
loaded: Math.max(0, progress.loaded),
|
||||
total: Math.max(0, progress.total),
|
||||
percentage: Math.min(100, Math.max(0, progress.percentage))
|
||||
}
|
||||
// 调用外部进度回调
|
||||
if (externalHandler) {
|
||||
externalHandler(uploadProgress.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误处理
|
||||
*/
|
||||
const handleUploadError = (error: unknown): void => {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.ERROR
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.ERROR)
|
||||
const status = (error as ErrorWithResponse)?.response?.status
|
||||
const fallback =
|
||||
status === 404
|
||||
? '上传会话不存在或已过期'
|
||||
: status === 500
|
||||
? '服务器错误,请稍后重试'
|
||||
: '上传失败,请重试'
|
||||
|
||||
errorMessage.value = getErrorMessage(error, fallback)
|
||||
notify(errorMessage.value, 'error')
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化上传会话
|
||||
*/
|
||||
const initUploadSession = async (
|
||||
file: File,
|
||||
options?: PresignUploadOptions
|
||||
): Promise<PresignInitResponse | null> => {
|
||||
try {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.INITIALIZING
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.INITIALIZING)
|
||||
|
||||
const response = await PresignUploadService.initUpload({
|
||||
file_name: file.name,
|
||||
file_size: file.size,
|
||||
expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE,
|
||||
expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE
|
||||
})
|
||||
|
||||
if (response.code === 200 && response.detail) {
|
||||
uploadSession.value = response.detail
|
||||
return response.detail
|
||||
} else {
|
||||
throw new Error(response.message || '初始化上传失败')
|
||||
}
|
||||
} catch (error) {
|
||||
handleUploadError(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直传模式上传到 S3
|
||||
*/
|
||||
const uploadDirect = async (
|
||||
file: File,
|
||||
session: PresignInitResponse,
|
||||
options?: PresignUploadOptions
|
||||
): Promise<string | null> => {
|
||||
try {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.UPLOADING
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.UPLOADING)
|
||||
|
||||
// 上传到 S3
|
||||
const progressHandler = createProgressHandler(options?.onProgress)
|
||||
const uploadSuccess = await PresignUploadService.directUploadToS3(
|
||||
session.upload_url,
|
||||
file,
|
||||
progressHandler
|
||||
)
|
||||
|
||||
if (!uploadSuccess) {
|
||||
throw new Error('S3 上传失败')
|
||||
}
|
||||
|
||||
// 确认上传
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.CONFIRMING)
|
||||
const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, {
|
||||
expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE,
|
||||
expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE
|
||||
})
|
||||
|
||||
if (confirmResponse.code === 200 && confirmResponse.detail?.code) {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.SUCCESS)
|
||||
uploadedCode.value = String(confirmResponse.detail.code)
|
||||
// 确保进度为 100%
|
||||
uploadProgress.value = {
|
||||
loaded: file.size,
|
||||
total: file.size,
|
||||
percentage: 100
|
||||
}
|
||||
notify('文件上传成功!', 'success')
|
||||
return uploadedCode.value
|
||||
} else {
|
||||
throw new Error(confirmResponse.message || '确认上传失败')
|
||||
}
|
||||
} catch (error) {
|
||||
handleUploadError(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 代理模式上传
|
||||
*/
|
||||
const uploadProxy = async (
|
||||
file: File,
|
||||
session: PresignInitResponse,
|
||||
options?: PresignUploadOptions
|
||||
): Promise<string | null> => {
|
||||
try {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.UPLOADING
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.UPLOADING)
|
||||
|
||||
const progressHandler = createProgressHandler(options?.onProgress)
|
||||
const uploadUrl =
|
||||
session.proxy_upload_url || session.upload_url || session.legacy_proxy_upload_url
|
||||
const response = await PresignUploadService.proxyUpload(
|
||||
session.upload_id,
|
||||
file,
|
||||
progressHandler,
|
||||
uploadUrl
|
||||
)
|
||||
|
||||
if (response.code === 200 && response.detail?.code) {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS
|
||||
onStatus?.(PRESIGN_UPLOAD_STATUS.SUCCESS)
|
||||
uploadedCode.value = String(response.detail.code)
|
||||
// 确保进度为 100%
|
||||
uploadProgress.value = {
|
||||
loaded: file.size,
|
||||
total: file.size,
|
||||
percentage: 100
|
||||
}
|
||||
notify('文件上传成功!', 'success')
|
||||
return uploadedCode.value
|
||||
} else {
|
||||
throw new Error(response.message || '代理上传失败')
|
||||
}
|
||||
} catch (error) {
|
||||
handleUploadError(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const uploadFile = async (file: File, options?: PresignUploadOptions): Promise<string | null> => {
|
||||
reset()
|
||||
|
||||
if (!validateFileSize(file)) {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.ERROR
|
||||
return null
|
||||
}
|
||||
|
||||
const session = await initUploadSession(file, options)
|
||||
if (!session) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (session.mode === 'direct') {
|
||||
return await uploadDirect(file, session, options)
|
||||
} else {
|
||||
return await uploadProxy(file, session, options)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消上传
|
||||
*/
|
||||
const cancelUpload = async (): Promise<void> => {
|
||||
if (!uploadSession.value?.upload_id) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await PresignUploadService.cancelUpload(uploadSession.value.upload_id)
|
||||
notify('上传已取消', 'info')
|
||||
} catch (error) {
|
||||
// 取消失败时静默处理,因为会话可能已过期
|
||||
console.warn('取消上传失败:', error)
|
||||
} finally {
|
||||
reset()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上传状态
|
||||
*/
|
||||
const getStatus = async (): Promise<PresignStatusResponse | null> => {
|
||||
if (!uploadSession.value?.upload_id) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await PresignUploadService.getUploadStatus(uploadSession.value.upload_id)
|
||||
if (response.code === 200 && response.detail) {
|
||||
// 检查会话是否过期
|
||||
if (response.detail.is_expired) {
|
||||
errorMessage.value = '上传会话已过期'
|
||||
notify(errorMessage.value, 'warning')
|
||||
}
|
||||
return response.detail
|
||||
}
|
||||
return null
|
||||
} catch (error) {
|
||||
handleUploadError(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置状态
|
||||
*/
|
||||
const reset = (): void => {
|
||||
presignStatus.value = PRESIGN_UPLOAD_STATUS.IDLE
|
||||
uploadSession.value = null
|
||||
uploadProgress.value = {
|
||||
loaded: 0,
|
||||
total: 0,
|
||||
percentage: 0
|
||||
}
|
||||
uploadedCode.value = ''
|
||||
errorMessage.value = ''
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态 (只读)
|
||||
presignStatus: readonly(presignStatus),
|
||||
uploadSession: readonly(uploadSession),
|
||||
uploadProgress: readonly(uploadProgress),
|
||||
uploadedCode: readonly(uploadedCode),
|
||||
errorMessage: readonly(errorMessage),
|
||||
|
||||
// 计算属性
|
||||
isInitializing,
|
||||
isUploading,
|
||||
isConfirming,
|
||||
isSuccess,
|
||||
isError,
|
||||
currentMode,
|
||||
|
||||
// 方法
|
||||
uploadFile,
|
||||
cancelUpload,
|
||||
getStatus,
|
||||
reset
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { ConfigService } from '@/services'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { useConfigStore } from '@/stores/configStore'
|
||||
|
||||
export function usePublicConfigBootstrap() {
|
||||
const alertStore = useAlertStore()
|
||||
const configStore = useConfigStore()
|
||||
|
||||
const syncPublicConfig = async () => {
|
||||
const res = await ConfigService.getUserConfig()
|
||||
|
||||
if (res.code !== 200 || !res.detail) {
|
||||
return
|
||||
}
|
||||
|
||||
configStore.applyPublicMeta(res.detail.meta)
|
||||
const notifyMessage = configStore.applyRemoteConfig(res.detail.config)
|
||||
if (notifyMessage) {
|
||||
alertStore.showAlert(notifyMessage, 'success')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
syncPublicConfig
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { FileService } from '@/services'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { useFileDataStore } from '@/stores/fileData'
|
||||
import type { ReceivedFileRecord, ShareMetadataResponse, ShareSelectResponse } from '@/types'
|
||||
import { copyToClipboard } from '@/utils/clipboard'
|
||||
import { getErrorMessage } from '@/utils/common'
|
||||
import { renderMarkdownPreview } from '@/utils/content-preview'
|
||||
import { downloadReceivedRecord } from '@/utils/download-action'
|
||||
import { isValidRetrievalCode } from '@/utils/retrieval-code'
|
||||
|
||||
type InputStatus = {
|
||||
readonly: boolean
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
export function useRetrieveFlow() {
|
||||
const { t } = useI18n()
|
||||
const alertStore = useAlertStore()
|
||||
const fileStore = useFileDataStore()
|
||||
const { receiveData: records } = storeToRefs(fileStore)
|
||||
|
||||
const code = ref('')
|
||||
const inspectedFile = ref<ShareMetadataResponse | null>(null)
|
||||
const isInspecting = ref(false)
|
||||
const isRetrieving = ref(false)
|
||||
const inputStatus = ref<InputStatus>({
|
||||
readonly: false,
|
||||
loading: false
|
||||
})
|
||||
const error = ref('')
|
||||
const selectedRecord = ref<ReceivedFileRecord | null>(null)
|
||||
const showDrawer = ref(false)
|
||||
const showPreview = ref(false)
|
||||
const renderedContent = ref('')
|
||||
const normalizedCode = computed(() => code.value.trim())
|
||||
const isWorking = computed(() => isInspecting.value || isRetrieving.value)
|
||||
const hasValidCode = computed(() => isValidRetrievalCode(normalizedCode.value))
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes === 0) return '0 ' + t('fileSize.bytes')
|
||||
const k = 1024
|
||||
const sizes = [
|
||||
t('fileSize.bytes'),
|
||||
t('fileSize.kb'),
|
||||
t('fileSize.mb'),
|
||||
t('fileSize.gb'),
|
||||
t('fileSize.tb')
|
||||
]
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
const createRecord = (detail: ShareSelectResponse): ReceivedFileRecord => {
|
||||
const isText =
|
||||
typeof detail.is_text === 'boolean'
|
||||
? detail.is_text
|
||||
: detail.type
|
||||
? detail.type === 'text'
|
||||
: detail.name === 'Text' && !detail.text.startsWith('/share/download')
|
||||
const content = isText ? (detail.content ?? detail.text) : null
|
||||
const downloadUrl = isText ? null : (detail.download_url ?? detail.text)
|
||||
|
||||
return {
|
||||
id: Date.now(),
|
||||
code: detail.code,
|
||||
filename: detail.name,
|
||||
size: formatFileSize(detail.size),
|
||||
downloadUrl,
|
||||
content,
|
||||
date: new Date().toLocaleString(),
|
||||
type: isText ? 'text' : 'file',
|
||||
remainingDownloads: detail.remaining_downloads
|
||||
}
|
||||
}
|
||||
|
||||
const resetInspection = () => {
|
||||
inspectedFile.value = null
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
const inspectCode = async () => {
|
||||
if (!hasValidCode.value) {
|
||||
alertStore.showAlert(t('retrieve.messages.invalidCode'), 'error')
|
||||
return
|
||||
}
|
||||
|
||||
isInspecting.value = true
|
||||
inputStatus.value.readonly = true
|
||||
inputStatus.value.loading = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const res = await FileService.inspectFile(normalizedCode.value)
|
||||
if (res.code === 200 && res.detail) {
|
||||
inspectedFile.value = res.detail
|
||||
} else {
|
||||
inspectedFile.value = null
|
||||
error.value = String(res.detail || res.message || '')
|
||||
alertStore.showAlert(t('retrieve.messages.retrieveFailure') + error.value, 'error')
|
||||
}
|
||||
} catch {
|
||||
inspectedFile.value = null
|
||||
error.value = t('retrieve.messages.previewUnavailable')
|
||||
alertStore.showAlert(error.value, 'warning')
|
||||
} finally {
|
||||
isInspecting.value = false
|
||||
inputStatus.value.readonly = false
|
||||
inputStatus.value.loading = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!hasValidCode.value) {
|
||||
alertStore.showAlert(t('retrieve.messages.invalidCode'), 'error')
|
||||
return
|
||||
}
|
||||
|
||||
isRetrieving.value = true
|
||||
inputStatus.value.readonly = true
|
||||
inputStatus.value.loading = true
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
const res = await FileService.selectFile(normalizedCode.value)
|
||||
if (res.code === 200 && res.detail) {
|
||||
const newFileData = createRecord(res.detail)
|
||||
const existingIndex = fileStore.receiveData.findIndex(
|
||||
(file) => file.code === newFileData.code
|
||||
)
|
||||
if (existingIndex !== -1) {
|
||||
fileStore.deleteReceiveData(existingIndex)
|
||||
}
|
||||
fileStore.addReceiveData(newFileData)
|
||||
selectedRecord.value = newFileData
|
||||
if (newFileData.content) {
|
||||
showPreview.value = true
|
||||
}
|
||||
inspectedFile.value = null
|
||||
alertStore.showAlert(t('retrieve.messages.retrieveSuccess'), 'success')
|
||||
} else {
|
||||
error.value = String(res.detail || '')
|
||||
alertStore.showAlert(t('retrieve.messages.retrieveFailure') + error.value, 'error')
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = getErrorMessage(err, t('retrieve.messages.unknownError'))
|
||||
error.value = errorMessage
|
||||
alertStore.showAlert(t('retrieve.messages.networkError') + errorMessage, 'error')
|
||||
} finally {
|
||||
isRetrieving.value = false
|
||||
inputStatus.value.readonly = false
|
||||
inputStatus.value.loading = false
|
||||
code.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const copyContent = async () => {
|
||||
if (selectedRecord.value?.content) {
|
||||
await copyToClipboard(selectedRecord.value.content, {
|
||||
successMsg: t('fileRecord.contentCopied'),
|
||||
errorMsg: t('fileRecord.copyFailed'),
|
||||
notify: (message, type) => alertStore.showAlert(message, type)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const viewDetails = (record: ReceivedFileRecord) => {
|
||||
selectedRecord.value = record
|
||||
}
|
||||
|
||||
const closeDetails = () => {
|
||||
selectedRecord.value = null
|
||||
}
|
||||
|
||||
const deleteRecord = (id: number) => {
|
||||
if (!window.confirm(t('fileRecord.deleteRecordConfirm'))) return
|
||||
const index = records.value.findIndex((record) => record.id === id)
|
||||
if (index !== -1) {
|
||||
fileStore.deleteReceiveData(index)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleDrawer = () => {
|
||||
showDrawer.value = !showDrawer.value
|
||||
}
|
||||
|
||||
const downloadRecord = (record: ReceivedFileRecord) => {
|
||||
downloadReceivedRecord(record)
|
||||
}
|
||||
|
||||
const showContentPreview = () => {
|
||||
showPreview.value = true
|
||||
}
|
||||
|
||||
const closeContentPreview = () => {
|
||||
showPreview.value = false
|
||||
}
|
||||
|
||||
watch(
|
||||
() => selectedRecord.value?.content,
|
||||
async (content) => {
|
||||
if (content) {
|
||||
renderedContent.value = await renderMarkdownPreview(content)
|
||||
} else {
|
||||
renderedContent.value = ''
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
watch(normalizedCode, (nextCode) => {
|
||||
if (inspectedFile.value && inspectedFile.value.code !== nextCode) {
|
||||
resetInspection()
|
||||
}
|
||||
|
||||
if (!isValidRetrievalCode(nextCode) && error.value) {
|
||||
error.value = ''
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
code,
|
||||
inspectedFile,
|
||||
isInspecting,
|
||||
isRetrieving,
|
||||
isWorking,
|
||||
hasValidCode,
|
||||
inputStatus,
|
||||
error,
|
||||
records,
|
||||
selectedRecord,
|
||||
showDrawer,
|
||||
showPreview,
|
||||
renderedContent,
|
||||
closeContentPreview,
|
||||
closeDetails,
|
||||
copyContent,
|
||||
deleteRecord,
|
||||
downloadRecord,
|
||||
handleSubmit,
|
||||
inspectCode,
|
||||
resetInspection,
|
||||
showContentPreview,
|
||||
toggleDrawer,
|
||||
viewDetails
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { onUnmounted, ref } from 'vue'
|
||||
import type { Router } from 'vue-router'
|
||||
|
||||
const ROUTE_LOADING_DELAY = 200
|
||||
|
||||
export function useRouteLoading(router: Router) {
|
||||
const isLoading = ref(false)
|
||||
let loadingTimer: number | null = null
|
||||
let cleanupBeforeGuard: (() => void) | null = null
|
||||
let cleanupAfterHook: (() => void) | null = null
|
||||
|
||||
const clearLoadingTimer = () => {
|
||||
if (loadingTimer !== null) {
|
||||
window.clearTimeout(loadingTimer)
|
||||
loadingTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const setupRouteLoading = () => {
|
||||
cleanupBeforeGuard = router.beforeEach((to) => {
|
||||
clearLoadingTimer()
|
||||
isLoading.value = to.meta.showRouteLoading !== false
|
||||
})
|
||||
|
||||
cleanupAfterHook = router.afterEach(() => {
|
||||
clearLoadingTimer()
|
||||
loadingTimer = window.setTimeout(() => {
|
||||
isLoading.value = false
|
||||
loadingTimer = null
|
||||
}, ROUTE_LOADING_DELAY)
|
||||
})
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
clearLoadingTimer()
|
||||
cleanupBeforeGuard?.()
|
||||
cleanupAfterHook?.()
|
||||
})
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
setupRouteLoading
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { useAdminStore } from '@/stores/adminStore'
|
||||
import { useConfigStore } from '@/stores/configStore'
|
||||
import { useFileDataStore } from '@/stores/fileData'
|
||||
import type { SendType, SentFileRecord } from '@/types'
|
||||
import { getClipboardFile, insertTextAtSelection } from '@/utils/clipboard-paste'
|
||||
import { getErrorMessage } from '@/utils/common'
|
||||
import { getStorageUnit } from '@/utils/convert'
|
||||
import { calculateFileHash } from '@/utils/file-processing'
|
||||
import { buildSentRecord, isExpirationWithinLimit } from '@/utils/send-record'
|
||||
import { createSentRecordActions } from '@/utils/sent-record-actions'
|
||||
import { useSendSubmit } from './useSendSubmit'
|
||||
|
||||
export function useSendFlow() {
|
||||
const { t } = useI18n()
|
||||
const alertStore = useAlertStore()
|
||||
const adminStore = useAdminStore()
|
||||
const configStore = useConfigStore()
|
||||
const fileDataStore = useFileDataStore()
|
||||
const config = computed(() => configStore.config)
|
||||
const sendType = ref<SendType>('file')
|
||||
const selectedFile = ref<File | null>(null)
|
||||
const selectedFiles = ref<File[]>([])
|
||||
const textContent = ref('')
|
||||
const expirationMethod = ref(config.value.expireStyle[0] || 'day')
|
||||
const expirationValue = ref('1')
|
||||
const uploadProgress = ref(0)
|
||||
const showDrawer = ref(false)
|
||||
const selectedRecord = ref<SentFileRecord | null>(null)
|
||||
const isSubmitting = ref(false)
|
||||
const fileHash = ref('')
|
||||
const uploadStatus = ref<'idle' | 'initializing' | 'uploading' | 'confirming' | 'success' | 'error'>('idle')
|
||||
const uploadedBytes = ref(0)
|
||||
const totalBytes = ref(0)
|
||||
const uploadError = ref('')
|
||||
const sendRecords = computed(() => fileDataStore.shareData)
|
||||
const uploadDescription = computed(() =>
|
||||
t('send.uploadArea.descriptionWithLimit', {
|
||||
size: getStorageUnit(config.value.uploadSize)
|
||||
})
|
||||
)
|
||||
const expirationOptions = computed(() =>
|
||||
config.value.expireStyle.map((value) => ({
|
||||
value,
|
||||
label: getUnit(value)
|
||||
}))
|
||||
)
|
||||
watch(
|
||||
() => config.value.expireStyle,
|
||||
(expireStyle) => {
|
||||
if (expireStyle.length > 0 && !expireStyle.includes(expirationMethod.value)) {
|
||||
expirationMethod.value = expireStyle[0]
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
const notifyCopyResult = (message: string, type: 'success' | 'error') => {
|
||||
alertStore.showAlert(message, type)
|
||||
}
|
||||
const sentRecordActions = createSentRecordActions(notifyCopyResult)
|
||||
const { resetPresignUpload, submitFile, submitText } = useSendSubmit({
|
||||
getMaxFileSize: () => configStore.uploadSizeLimit,
|
||||
notify: (message, type) => alertStore.showAlert(message, type),
|
||||
translate: t,
|
||||
onProgress: (progress) => {
|
||||
uploadProgress.value = progress.percentage
|
||||
totalBytes.value = progress.total
|
||||
uploadedBytes.value = progress.loaded
|
||||
},
|
||||
onStatus: (status) => { uploadStatus.value = status },
|
||||
onHashCalculated: (hash) => {
|
||||
fileHash.value = hash
|
||||
}
|
||||
})
|
||||
|
||||
const checkOpenUpload = () => {
|
||||
if (config.value.openUpload === 0 && !adminStore.hasToken) {
|
||||
alertStore.showAlert(t('send.messages.guestUploadDisabled'), 'error')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const checkFileSize = (file: File) => {
|
||||
if (file.size > config.value.uploadSize) {
|
||||
alertStore.showAlert(
|
||||
t('send.messages.fileSizeExceeded', { size: getStorageUnit(config.value.uploadSize) }),
|
||||
'error'
|
||||
)
|
||||
selectedFile.value = null
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const checkExpirationTime = (method: string, value: string): boolean =>
|
||||
isExpirationWithinLimit(method, value, config.value.max_save_seconds || 0)
|
||||
|
||||
const checkUpload = () => {
|
||||
if (!selectedFile.value) return false
|
||||
if (!checkOpenUpload()) return false
|
||||
if (!checkFileSize(selectedFile.value)) return false
|
||||
if (!checkExpirationTime(expirationMethod.value, expirationValue.value)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
const handleFileSelected = async (file: File) => {
|
||||
selectedFile.value = file
|
||||
selectedFiles.value = []
|
||||
if (!checkOpenUpload()) return
|
||||
if (!checkFileSize(file)) return
|
||||
fileHash.value = await calculateFileHash(file)
|
||||
}
|
||||
|
||||
const handleFilesSelected = async (files: File[]) => {
|
||||
if (!checkOpenUpload()) return
|
||||
selectedFiles.value = files
|
||||
selectedFile.value = null
|
||||
fileHash.value = ''
|
||||
}
|
||||
|
||||
const handleFileDrop = async (event: DragEvent) => {
|
||||
if (!event.dataTransfer?.files || event.dataTransfer.files.length === 0) return
|
||||
const files = Array.from(event.dataTransfer.files)
|
||||
if (files.length === 1) {
|
||||
const file = files[0]
|
||||
selectedFile.value = file
|
||||
selectedFiles.value = []
|
||||
if (!checkUpload()) return
|
||||
fileHash.value = await calculateFileHash(file)
|
||||
} else {
|
||||
if (!checkOpenUpload()) return
|
||||
selectedFiles.value = files
|
||||
selectedFile.value = null
|
||||
fileHash.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = async (event: ClipboardEvent) => {
|
||||
const items = event.clipboardData?.items
|
||||
if (!items) return
|
||||
|
||||
const file = getClipboardFile(items)
|
||||
if (file) {
|
||||
if (file.size === 0) {
|
||||
alertStore.showAlert(t('send.messages.emptyFileError'), 'error')
|
||||
return
|
||||
}
|
||||
|
||||
selectedFile.value = file
|
||||
if (!checkUpload()) return
|
||||
|
||||
try {
|
||||
fileHash.value = await calculateFileHash(file)
|
||||
alertStore.showAlert(
|
||||
t('send.messages.fileAddedFromClipboard', { filename: file.name }),
|
||||
'success'
|
||||
)
|
||||
} catch (err) {
|
||||
alertStore.showAlert(t('send.messages.fileProcessingFailed'), 'error')
|
||||
console.error('File hash calculation failed:', err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const textItem = items[0]
|
||||
if (!textItem) return
|
||||
|
||||
sendType.value = 'text'
|
||||
textItem.getAsString((str: string) => {
|
||||
const trimmedStr = str.trim()
|
||||
if (!trimmedStr) return
|
||||
|
||||
const textareaElement = document.getElementById('text-content') as HTMLTextAreaElement
|
||||
if (!textareaElement) {
|
||||
textContent.value += trimmedStr
|
||||
return
|
||||
}
|
||||
|
||||
const insertion = insertTextAtSelection({
|
||||
text: textContent.value,
|
||||
insertText: trimmedStr,
|
||||
selectionStart: textareaElement.selectionStart,
|
||||
selectionEnd: textareaElement.selectionEnd
|
||||
})
|
||||
textContent.value = insertion.value
|
||||
|
||||
setTimeout(() => {
|
||||
textareaElement.setSelectionRange(insertion.cursor, insertion.cursor)
|
||||
textareaElement.focus()
|
||||
}, 0)
|
||||
})
|
||||
}
|
||||
|
||||
const getUnit = (value: string = expirationMethod.value) => {
|
||||
switch (value) {
|
||||
case 'day':
|
||||
return t('send.expiration.units.days')
|
||||
case 'hour':
|
||||
return t('send.expiration.units.hours')
|
||||
case 'minute':
|
||||
return t('send.expiration.units.minutes')
|
||||
case 'count':
|
||||
return t('send.expiration.units.times')
|
||||
case 'forever':
|
||||
return t('send.expiration.units.forever')
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (isSubmitting.value) return
|
||||
isSubmitting.value = true
|
||||
uploadError.value = ''
|
||||
|
||||
try {
|
||||
if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) {
|
||||
alertStore.showAlert(t('send.messages.selectFile'), 'error')
|
||||
return
|
||||
}
|
||||
if (sendType.value === 'text' && !textContent.value.trim()) {
|
||||
alertStore.showAlert(t('send.messages.enterText'), 'error')
|
||||
return
|
||||
}
|
||||
if (!checkOpenUpload()) {
|
||||
return
|
||||
}
|
||||
if (expirationMethod.value !== 'forever' && !expirationValue.value) {
|
||||
alertStore.showAlert(t('send.messages.enterExpirationValue'), 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (!checkExpirationTime(expirationMethod.value, expirationValue.value)) {
|
||||
const maxDays = Math.floor(config.value.max_save_seconds / 86400)
|
||||
alertStore.showAlert(t('send.messages.expirationTooLong', { days: maxDays }), 'error')
|
||||
return
|
||||
}
|
||||
|
||||
const expireValue = expirationValue.value ? parseInt(expirationValue.value) : 1
|
||||
let response
|
||||
if (sendType.value === 'file') {
|
||||
response = await submitFile({
|
||||
selectedFile: selectedFile.value,
|
||||
selectedFiles: selectedFiles.value,
|
||||
expireValue,
|
||||
expireStyle: expirationMethod.value,
|
||||
enableChunk: Boolean(config.value.enableChunk),
|
||||
validateFileSize: checkFileSize
|
||||
})
|
||||
} else {
|
||||
response = await submitText({
|
||||
text: textContent.value,
|
||||
expireValue,
|
||||
expireStyle: expirationMethod.value
|
||||
})
|
||||
}
|
||||
|
||||
if (!response) return
|
||||
|
||||
if (response?.code === 200) {
|
||||
const newRecord = buildSentRecord({
|
||||
response,
|
||||
sendType: sendType.value,
|
||||
textContent: textContent.value,
|
||||
selectedFile: selectedFile.value,
|
||||
selectedFiles: selectedFiles.value,
|
||||
expirationMethod: expirationMethod.value,
|
||||
expirationValue: expirationValue.value,
|
||||
translate: t,
|
||||
getUnit
|
||||
})
|
||||
fileDataStore.addShareDataRecord(newRecord)
|
||||
alertStore.showAlert(
|
||||
t('send.messages.sendSuccess', { code: newRecord.retrieveCode }),
|
||||
'success'
|
||||
)
|
||||
selectedFile.value = null
|
||||
selectedFiles.value = []
|
||||
textContent.value = ''
|
||||
uploadProgress.value = 0
|
||||
uploadedBytes.value = 0
|
||||
totalBytes.value = 0
|
||||
uploadStatus.value = 'idle'
|
||||
resetPresignUpload()
|
||||
selectedRecord.value = newRecord
|
||||
await sentRecordActions.copyLink(newRecord)
|
||||
} else {
|
||||
throw new Error(t('send.messages.serverError'))
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
uploadStatus.value = 'error'
|
||||
uploadError.value = getErrorMessage(error, t('send.messages.sendFailed'))
|
||||
alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error')
|
||||
} finally {
|
||||
uploadProgress.value = 0
|
||||
if (uploadStatus.value !== 'success' && uploadStatus.value !== 'error') {
|
||||
uploadStatus.value = 'idle'
|
||||
}
|
||||
if (uploadStatus.value === 'success') uploadStatus.value = 'idle'
|
||||
isSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleDrawer = () => {
|
||||
showDrawer.value = !showDrawer.value
|
||||
}
|
||||
|
||||
const viewDetails = (record: SentFileRecord) => {
|
||||
selectedRecord.value = record
|
||||
}
|
||||
|
||||
const closeDetails = () => {
|
||||
selectedRecord.value = null
|
||||
}
|
||||
|
||||
const deleteRecord = (id: number) => {
|
||||
if (!window.confirm(t('fileRecord.deleteRecordConfirm'))) return
|
||||
const index = fileDataStore.shareData.findIndex((record) => record.id === id)
|
||||
if (index !== -1) {
|
||||
fileDataStore.deleteShareData(index)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
sendType,
|
||||
selectedFile,
|
||||
selectedFiles,
|
||||
textContent,
|
||||
expirationMethod,
|
||||
expirationValue,
|
||||
uploadProgress,
|
||||
showDrawer,
|
||||
selectedRecord,
|
||||
isSubmitting,
|
||||
uploadStatus,
|
||||
uploadedBytes,
|
||||
totalBytes,
|
||||
uploadError,
|
||||
sendRecords,
|
||||
uploadDescription,
|
||||
expirationOptions,
|
||||
closeDetails,
|
||||
deleteRecord,
|
||||
copySentRecordCode: sentRecordActions.copyCode,
|
||||
copySentRecordLink: sentRecordActions.copyLink,
|
||||
copySentRecordWgetCommand: sentRecordActions.copyWgetCommand,
|
||||
getQRCodeValue: sentRecordActions.getQRCodeValue,
|
||||
getUnit,
|
||||
handleFileDrop,
|
||||
handleFileSelected,
|
||||
handleFilesSelected,
|
||||
handlePaste,
|
||||
handleSubmit,
|
||||
toggleDrawer,
|
||||
viewDetails
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { FileService, uploadChunkedFile } from '@/services'
|
||||
import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types'
|
||||
import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing'
|
||||
import { usePresignedUpload } from './usePresignedUpload'
|
||||
|
||||
type Translate = (
|
||||
key: string,
|
||||
params?: Record<string, string | number | undefined>
|
||||
) => string
|
||||
|
||||
type UseSendSubmitOptions = {
|
||||
getMaxFileSize: () => number
|
||||
notify: (message: string, type: AlertType) => void
|
||||
translate: Translate
|
||||
onProgress: (progress: UploadProgress) => void
|
||||
onHashCalculated: (hash: string) => void
|
||||
onStatus?: (status: 'idle' | 'initializing' | 'uploading' | 'confirming' | 'success' | 'error') => void
|
||||
}
|
||||
|
||||
type SubmitFileOptions = {
|
||||
selectedFile: File | null
|
||||
selectedFiles: File[]
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
enableChunk: boolean
|
||||
validateFileSize: (file: File) => boolean
|
||||
}
|
||||
|
||||
type SubmitTextOptions = {
|
||||
text: string
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
}
|
||||
|
||||
export function useSendSubmit(options: UseSendSubmitOptions) {
|
||||
const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({
|
||||
getMaxFileSize: options.getMaxFileSize,
|
||||
notify: options.notify,
|
||||
onStatus: options.onStatus
|
||||
})
|
||||
|
||||
const handleChunkUpload = async (
|
||||
file: File,
|
||||
expireValue: number,
|
||||
expireStyle: string
|
||||
): Promise<ApiResponse> => {
|
||||
return uploadChunkedFile(file, {
|
||||
expireValue,
|
||||
expireStyle,
|
||||
onHashCalculated: options.onHashCalculated,
|
||||
onProgress: options.onProgress,
|
||||
onStatus: options.onStatus,
|
||||
messages: {
|
||||
initFailed: options.translate('send.messages.initChunkUploadFailed'),
|
||||
chunkFailed: (index) => options.translate('send.messages.chunkUploadFailed', { index }),
|
||||
completeFailed: options.translate('send.messages.completeUploadFailed')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const handlePresignedUpload = async (
|
||||
file: File,
|
||||
expireValue: number,
|
||||
expireStyle: string
|
||||
): Promise<ApiResponse<{ code?: string; name?: string }>> => {
|
||||
const code = await presignUploadFile(file, {
|
||||
expireValue,
|
||||
expireStyle: expireStyle as ExpireStyle,
|
||||
onProgress: (progress) => {
|
||||
options.onProgress(progress)
|
||||
}
|
||||
})
|
||||
|
||||
if (!code) {
|
||||
throw new Error(options.translate('send.messages.uploadFailed'))
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
detail: {
|
||||
code,
|
||||
name: file.name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const submitFile = async ({
|
||||
selectedFile,
|
||||
selectedFiles,
|
||||
expireValue,
|
||||
expireStyle,
|
||||
enableChunk,
|
||||
validateFileSize
|
||||
}: SubmitFileOptions): Promise<ApiResponse | null> => {
|
||||
let fileToUpload = selectedFile
|
||||
|
||||
if (selectedFiles.length > 0) {
|
||||
options.notify('正在打包文件...', 'success')
|
||||
fileToUpload = await packFilesAsZip(selectedFiles)
|
||||
if (!validateFileSize(fileToUpload)) {
|
||||
return null
|
||||
}
|
||||
options.onHashCalculated(await calculateFileHash(fileToUpload))
|
||||
}
|
||||
|
||||
if (!fileToUpload) {
|
||||
throw new Error(options.translate('send.messages.selectFile'))
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const response = enableChunk
|
||||
? await handleChunkUpload(fileToUpload, expireValue, expireStyle)
|
||||
: await handlePresignedUpload(fileToUpload, expireValue, expireStyle)
|
||||
if (response?.code === 200) options.onStatus?.('success')
|
||||
return response
|
||||
} catch (error) {
|
||||
options.onStatus?.('error')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) =>
|
||||
FileService.uploadText(text, expireValue, expireStyle)
|
||||
|
||||
return {
|
||||
resetPresignUpload,
|
||||
submitFile,
|
||||
submitText
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { ref, computed } from 'vue'
|
||||
import { ConfigService } from '@/services'
|
||||
import { useAlertStore } from '@/stores/alertStore'
|
||||
import { useConfigStore } from '@/stores/configStore'
|
||||
import type { ConfigState } from '@/types'
|
||||
import { DEFAULT_CONFIG_STATE, readStoredConfig } from '@/utils/config-storage'
|
||||
import { getErrorMessage } from '@/utils/common'
|
||||
import {
|
||||
buildConfigSubmitPayload,
|
||||
bytesToFileSizeForm,
|
||||
secondsToSaveTimeForm,
|
||||
type FileSizeUnit,
|
||||
type SaveTimeUnit
|
||||
} from '@/utils/config-form'
|
||||
|
||||
type ConfigFlagKey = 'enableChunk' | 's3_proxy' | 'openUpload'
|
||||
|
||||
export function useSystemConfig() {
|
||||
const alertStore = useAlertStore()
|
||||
const configStore = useConfigStore()
|
||||
|
||||
// 状态管理
|
||||
const config = ref<ConfigState>({ ...DEFAULT_CONFIG_STATE })
|
||||
const isRefreshing = ref(false)
|
||||
const isSaving = ref(false)
|
||||
const savedPayloadSnapshot = ref('')
|
||||
const fileSize = ref(1)
|
||||
const sizeUnit = ref<FileSizeUnit>('MB')
|
||||
const saveTime = ref(1)
|
||||
const saveTimeUnit = ref<SaveTimeUnit>('天')
|
||||
|
||||
const isLoading = computed(() => isRefreshing.value || isSaving.value)
|
||||
|
||||
const buildSubmitPayload = (): Partial<ConfigState> => {
|
||||
const payload: Partial<ConfigState> = buildConfigSubmitPayload(
|
||||
config.value,
|
||||
{ value: fileSize.value, unit: sizeUnit.value },
|
||||
{ value: saveTime.value, unit: saveTimeUnit.value }
|
||||
)
|
||||
|
||||
if (!payload.admin_token) {
|
||||
delete payload.admin_token
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
const snapshotPayload = (payload: Partial<ConfigState>) => JSON.stringify(payload)
|
||||
|
||||
const normalizeEditableConfig = (nextConfig: Partial<ConfigState>): ConfigState => ({
|
||||
...DEFAULT_CONFIG_STATE,
|
||||
...nextConfig,
|
||||
admin_token: ''
|
||||
})
|
||||
|
||||
const markConfigSaved = () => {
|
||||
savedPayloadSnapshot.value = snapshotPayload(buildSubmitPayload())
|
||||
}
|
||||
|
||||
const isDirty = computed(() => {
|
||||
if (!savedPayloadSnapshot.value) {
|
||||
return false
|
||||
}
|
||||
|
||||
return snapshotPayload(buildSubmitPayload()) !== savedPayloadSnapshot.value
|
||||
})
|
||||
|
||||
// 从本地存储获取配置
|
||||
const getStoredConfig = (): ConfigState | null => {
|
||||
const storedConfig = readStoredConfig<Partial<ConfigState>>()
|
||||
return storedConfig ? normalizeEditableConfig(storedConfig) : null
|
||||
}
|
||||
|
||||
// 保存配置到本地存储
|
||||
const saveConfigToStorage = (configData: ConfigState) => {
|
||||
configStore.updateConfig(configData)
|
||||
}
|
||||
|
||||
// 获取系统配置
|
||||
const fetchConfig = async (): Promise<ConfigState | null> => {
|
||||
try {
|
||||
isRefreshing.value = true
|
||||
|
||||
const response = await ConfigService.getConfig()
|
||||
|
||||
if (response.code === 200 && response.detail) {
|
||||
config.value = normalizeEditableConfig(response.detail)
|
||||
const notifyMessage = configStore.applyRemoteConfig(config.value)
|
||||
if (notifyMessage) {
|
||||
alertStore.showAlert(notifyMessage, 'success')
|
||||
}
|
||||
|
||||
return config.value
|
||||
} else {
|
||||
throw new Error(response.message || '获取配置失败')
|
||||
}
|
||||
} catch (error) {
|
||||
// 如果网络请求失败,尝试使用本地存储的配置
|
||||
const storedConfig = getStoredConfig()
|
||||
if (storedConfig) {
|
||||
config.value = storedConfig
|
||||
return config.value
|
||||
}
|
||||
|
||||
alertStore.showAlert(getErrorMessage(error, '获取配置失败'), 'error')
|
||||
return null
|
||||
} finally {
|
||||
isRefreshing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 更新系统配置
|
||||
const updateConfig = async (newConfig: Partial<ConfigState>): Promise<boolean> => {
|
||||
try {
|
||||
isSaving.value = true
|
||||
|
||||
const response = await ConfigService.updateConfig(newConfig)
|
||||
|
||||
if (response.code === 200) {
|
||||
config.value = normalizeEditableConfig({ ...config.value, ...newConfig })
|
||||
syncConfigForm(config.value)
|
||||
markConfigSaved()
|
||||
saveConfigToStorage(config.value)
|
||||
alertStore.showAlert('配置更新成功!', 'success')
|
||||
return true
|
||||
} else {
|
||||
throw new Error(response.message || '更新配置失败')
|
||||
}
|
||||
} catch (error) {
|
||||
alertStore.showAlert(getErrorMessage(error, '更新配置失败'), 'error')
|
||||
return false
|
||||
} finally {
|
||||
isSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleConfigFlag = (key: ConfigFlagKey) => {
|
||||
config.value[key] = config.value[key] === 1 ? 0 : 1
|
||||
}
|
||||
|
||||
const syncConfigForm = (nextConfig: ConfigState) => {
|
||||
const sizeForm = bytesToFileSizeForm(nextConfig.uploadSize)
|
||||
fileSize.value = sizeForm.value
|
||||
sizeUnit.value = sizeForm.unit
|
||||
|
||||
const saveTimeForm = secondsToSaveTimeForm(nextConfig.max_save_seconds)
|
||||
saveTime.value = saveTimeForm.value
|
||||
saveTimeUnit.value = saveTimeForm.unit
|
||||
}
|
||||
|
||||
const refreshConfig = async () => {
|
||||
const latestConfig = await fetchConfig()
|
||||
if (latestConfig) {
|
||||
syncConfigForm(latestConfig)
|
||||
markConfigSaved()
|
||||
}
|
||||
}
|
||||
|
||||
const submitConfig = () => {
|
||||
if (!isDirty.value || isSaving.value) {
|
||||
return Promise.resolve(false)
|
||||
}
|
||||
|
||||
return updateConfig(buildSubmitPayload())
|
||||
}
|
||||
|
||||
// 初始化配置
|
||||
const initConfig = async () => {
|
||||
// 先尝试从本地存储加载
|
||||
const storedConfig = getStoredConfig()
|
||||
if (storedConfig) {
|
||||
config.value = storedConfig
|
||||
syncConfigForm(storedConfig)
|
||||
markConfigSaved()
|
||||
}
|
||||
|
||||
// 然后从服务器获取最新配置
|
||||
await refreshConfig()
|
||||
}
|
||||
|
||||
// 计算属性
|
||||
const maxFileSizeMB = computed(() => {
|
||||
return Math.round(config.value.uploadSize / 1024 / 1024)
|
||||
})
|
||||
|
||||
const isConfigLoaded = computed(() => {
|
||||
return config.value.name !== DEFAULT_CONFIG_STATE.name || !isLoading.value
|
||||
})
|
||||
|
||||
return {
|
||||
// 状态
|
||||
config,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
isSaving,
|
||||
isDirty,
|
||||
fileSize,
|
||||
sizeUnit,
|
||||
saveTime,
|
||||
saveTimeUnit,
|
||||
|
||||
// 计算属性
|
||||
maxFileSizeMB,
|
||||
isConfigLoaded,
|
||||
|
||||
// 方法
|
||||
fetchConfig,
|
||||
updateConfig,
|
||||
refreshConfig,
|
||||
submitConfig,
|
||||
toggleConfigFlag,
|
||||
initConfig,
|
||||
getStoredConfig,
|
||||
saveConfigToStorage
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { ref, computed } from 'vue'
|
||||
import { THEME_MODES } from '@/constants'
|
||||
import type { ThemeMode } from '@/types'
|
||||
import { readStoredThemeMode, writeStoredThemeMode } from '@/utils/preference-storage'
|
||||
|
||||
export function useTheme() {
|
||||
// 状态管理
|
||||
const isDarkMode = ref(false)
|
||||
const themeMode = ref<ThemeMode>(THEME_MODES.SYSTEM)
|
||||
|
||||
// 检查系统颜色模式
|
||||
const checkSystemColorScheme = (): boolean => {
|
||||
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
// 从本地存储获取用户之前的选择
|
||||
const getUserPreference = (): ThemeMode | null => {
|
||||
const storedPreference = readStoredThemeMode()
|
||||
if (storedPreference && Object.values(THEME_MODES).includes(storedPreference as ThemeMode)) {
|
||||
return storedPreference as ThemeMode
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 设置颜色模式
|
||||
const setThemeMode = (mode: ThemeMode) => {
|
||||
themeMode.value = mode
|
||||
writeStoredThemeMode(mode)
|
||||
|
||||
// 根据模式设置实际的暗色模式状态
|
||||
if (mode === THEME_MODES.SYSTEM) {
|
||||
isDarkMode.value = checkSystemColorScheme()
|
||||
} else {
|
||||
isDarkMode.value = mode === THEME_MODES.DARK
|
||||
}
|
||||
|
||||
// 更新 HTML 类名
|
||||
updateHtmlClass()
|
||||
}
|
||||
|
||||
// 更新 HTML 元素的类名
|
||||
const updateHtmlClass = () => {
|
||||
const html = document.documentElement
|
||||
if (isDarkMode.value) {
|
||||
html.classList.add('dark')
|
||||
} else {
|
||||
html.classList.remove('dark')
|
||||
}
|
||||
}
|
||||
|
||||
// 切换主题
|
||||
const toggleTheme = () => {
|
||||
if (themeMode.value === THEME_MODES.LIGHT) {
|
||||
setThemeMode(THEME_MODES.DARK)
|
||||
} else if (themeMode.value === THEME_MODES.DARK) {
|
||||
setThemeMode(THEME_MODES.SYSTEM)
|
||||
} else {
|
||||
setThemeMode(THEME_MODES.LIGHT)
|
||||
}
|
||||
}
|
||||
|
||||
// 监听系统主题变化
|
||||
const setupSystemThemeListener = () => {
|
||||
if (window.matchMedia) {
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
|
||||
const handleChange = (e: MediaQueryListEvent) => {
|
||||
if (themeMode.value === THEME_MODES.SYSTEM) {
|
||||
isDarkMode.value = e.matches
|
||||
updateHtmlClass()
|
||||
}
|
||||
}
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange)
|
||||
|
||||
// 返回清理函数
|
||||
return () => {
|
||||
mediaQuery.removeEventListener('change', handleChange)
|
||||
}
|
||||
}
|
||||
return () => {}
|
||||
}
|
||||
|
||||
// 初始化主题
|
||||
const initTheme = () => {
|
||||
const userPreference = getUserPreference()
|
||||
if (userPreference) {
|
||||
setThemeMode(userPreference)
|
||||
} else {
|
||||
setThemeMode(THEME_MODES.SYSTEM)
|
||||
}
|
||||
|
||||
// 设置系统主题监听
|
||||
return setupSystemThemeListener()
|
||||
}
|
||||
|
||||
// 计算属性
|
||||
const themeIcon = computed(() => {
|
||||
switch (themeMode.value) {
|
||||
case THEME_MODES.LIGHT:
|
||||
return 'sun'
|
||||
case THEME_MODES.DARK:
|
||||
return 'moon'
|
||||
case THEME_MODES.SYSTEM:
|
||||
return 'monitor'
|
||||
default:
|
||||
return 'monitor'
|
||||
}
|
||||
})
|
||||
|
||||
const themeLabel = computed(() => {
|
||||
switch (themeMode.value) {
|
||||
case THEME_MODES.LIGHT:
|
||||
return '浅色模式'
|
||||
case THEME_MODES.DARK:
|
||||
return '深色模式'
|
||||
case THEME_MODES.SYSTEM:
|
||||
return '跟随系统'
|
||||
default:
|
||||
return '跟随系统'
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
// 状态
|
||||
isDarkMode,
|
||||
themeMode,
|
||||
|
||||
// 计算属性
|
||||
themeIcon,
|
||||
themeLabel,
|
||||
|
||||
// 方法
|
||||
setThemeMode,
|
||||
toggleTheme,
|
||||
initTheme,
|
||||
checkSystemColorScheme
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StatsService } from '@/services'
|
||||
import type { AnalyticsData } from '@/types'
|
||||
|
||||
export function useTransferAnalytics() {
|
||||
const fetchAnalytics = async (start?: string, end?: string): Promise<AnalyticsData | null> => {
|
||||
const response = await StatsService.getAnalytics(start, end)
|
||||
return response.detail || null
|
||||
}
|
||||
|
||||
return {
|
||||
fetchAnalytics
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// 应用常量配置
|
||||
|
||||
// 存储键名
|
||||
export const STORAGE_KEYS = {
|
||||
COLOR_MODE: 'colorMode',
|
||||
ADMIN_PASSWORD: 'adminPassword',
|
||||
TOKEN: 'token',
|
||||
CONFIG: 'config',
|
||||
NOTIFY: 'notify'
|
||||
} as const
|
||||
|
||||
// 主题模式
|
||||
export const THEME_MODES = {
|
||||
LIGHT: 'light',
|
||||
DARK: 'dark',
|
||||
SYSTEM: 'system'
|
||||
} as const
|
||||
|
||||
// 发送类型
|
||||
export const SEND_TYPES = {
|
||||
FILE: 'file',
|
||||
TEXT: 'text'
|
||||
} as const
|
||||
|
||||
// 警告类型
|
||||
export const ALERT_TYPES = {
|
||||
SUCCESS: 'success',
|
||||
ERROR: 'error',
|
||||
WARNING: 'warning',
|
||||
INFO: 'info'
|
||||
} as const
|
||||
|
||||
// 上传状态
|
||||
export const UPLOAD_STATUS = {
|
||||
IDLE: 'idle',
|
||||
UPLOADING: 'uploading',
|
||||
SUCCESS: 'success',
|
||||
ERROR: 'error'
|
||||
} as const
|
||||
|
||||
// API 响应状态码
|
||||
export const API_STATUS_CODES = {
|
||||
SUCCESS: 200,
|
||||
UNAUTHORIZED: 401,
|
||||
FORBIDDEN: 403,
|
||||
NOT_FOUND: 404,
|
||||
SERVER_ERROR: 500
|
||||
} as const
|
||||
|
||||
// 文件大小限制 (字节)
|
||||
export const FILE_SIZE_LIMITS = {
|
||||
MAX_FILE_SIZE: 100 * 1024 * 1024, // 100MB
|
||||
CHUNK_SIZE: 1024 * 1024 // 1MB
|
||||
} as const
|
||||
|
||||
// 时间相关常量
|
||||
export const TIME_CONSTANTS = {
|
||||
ALERT_DURATION: 5000, // 5秒
|
||||
REQUEST_TIMEOUT: 300000000,
|
||||
PROGRESS_UPDATE_INTERVAL: 100 // 100毫秒
|
||||
} as const
|
||||
|
||||
// 路由路径
|
||||
export const ROUTES = {
|
||||
HOME: '/',
|
||||
SEND: '/send',
|
||||
ADMIN: '/admin',
|
||||
LOGIN: '/login',
|
||||
DASHBOARD: '/admin/dashboard',
|
||||
FILE_MANAGE: '/admin/files',
|
||||
TRASH: '/admin/trash',
|
||||
ACTIVITY_LOG: '/admin/activities',
|
||||
SETTINGS: '/admin/settings'
|
||||
} as const
|
||||
|
||||
export const ROUTE_NAMES = {
|
||||
RETRIEVE: 'Retrieve',
|
||||
SEND: 'Send',
|
||||
ADMIN: 'Manage',
|
||||
LOGIN: 'Login',
|
||||
DASHBOARD: 'Dashboard',
|
||||
FILE_MANAGE: 'FileManage',
|
||||
TRASH: 'Trash',
|
||||
ACTIVITY_LOG: 'ActivityLog',
|
||||
SETTINGS: 'Settings'
|
||||
} as const
|
||||
|
||||
// 正则表达式
|
||||
export const REGEX_PATTERNS = {
|
||||
EMAIL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
||||
PHONE: /^1[3-9]\d{9}$/,
|
||||
CODE: /^[A-Za-z0-9]{4,16}$/ // 兼容旧码并支持当前 8 位及未来扩容
|
||||
} as const
|
||||
|
||||
// 默认配置
|
||||
export const DEFAULT_CONFIG = {
|
||||
name: 'FileCodeBox',
|
||||
description: '文件传输工具',
|
||||
maxFileSize: FILE_SIZE_LIMITS.MAX_FILE_SIZE,
|
||||
allowedFileTypes: ['*'] as string[],
|
||||
expireDays: 7
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// 自定义 Vue hooks 导出文件
|
||||
// 这里可以导出所有自定义的 Vue hooks
|
||||
|
||||
// 示例:导出常用的自定义 hooks
|
||||
// export { useLocalStorage } from './useLocalStorage'
|
||||
// export { useDebounce } from './useDebounce'
|
||||
// export { useThrottle } from './useThrottle'
|
||||
// export { useEventListener } from './useEventListener'
|
||||
// export { useClickOutside } from './useClickOutside'
|
||||
|
||||
// 目前项目中的业务逻辑已经通过 composables 进行了封装
|
||||
// hooks 文件夹主要用于存放更通用的、可复用的 Vue hooks
|
||||
|
||||
export {}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import zhCN from './locales/zh-CN'
|
||||
import enUS from './locales/en-US'
|
||||
import { readStoredLocale, writeStoredLocale } from '@/utils/preference-storage'
|
||||
|
||||
// 获取浏览器语言设置
|
||||
const getDefaultLocale = (): string => {
|
||||
const savedLocale = readStoredLocale()
|
||||
if (savedLocale) {
|
||||
return savedLocale
|
||||
}
|
||||
|
||||
const browserLocale = navigator.language.toLowerCase()
|
||||
if (browserLocale.startsWith('zh')) {
|
||||
return 'zh-CN'
|
||||
}
|
||||
return 'en-US'
|
||||
}
|
||||
|
||||
const messages = {
|
||||
'zh-CN': zhCN,
|
||||
'en-US': enUS
|
||||
}
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false, // 使用 Composition API 模式
|
||||
locale: getDefaultLocale(),
|
||||
fallbackLocale: 'zh-CN',
|
||||
messages,
|
||||
globalInjection: true // 全局注入 $t 函数
|
||||
})
|
||||
|
||||
export default i18n
|
||||
|
||||
// 导出切换语言的函数
|
||||
export const setLocale = (locale: string) => {
|
||||
i18n.global.locale.value = locale as 'zh-CN' | 'en-US'
|
||||
writeStoredLocale(locale)
|
||||
document.documentElement.lang = locale
|
||||
}
|
||||
|
||||
// 导出获取当前语言的函数
|
||||
export const getCurrentLocale = () => {
|
||||
return i18n.global.locale.value
|
||||
}
|
||||
|
||||
// 导出可用语言列表
|
||||
export const availableLocales = [
|
||||
{ code: 'zh-CN', name: '中文' },
|
||||
{ code: 'en-US', name: 'English' }
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,353 @@
|
||||
<template>
|
||||
<div
|
||||
class="flex h-screen overflow-hidden flex-col transition-colors duration-300 lg:flex-row"
|
||||
:class="[isDarkMode ? 'bg-[#10191e]' : 'bg-[#dfe9eb]']"
|
||||
>
|
||||
<button
|
||||
v-if="isSidebarOpen"
|
||||
type="button"
|
||||
class="fixed inset-0 z-40 bg-black/45 backdrop-blur-[1px] lg:hidden"
|
||||
:aria-label="t('common.closeMenu')"
|
||||
@click="closeSidebar"
|
||||
/>
|
||||
|
||||
<!-- Sidebar -->
|
||||
<aside
|
||||
ref="sidebarRef"
|
||||
class="fixed inset-y-0 left-0 z-50 flex h-full w-64 shrink-0 transform flex-col border-r shadow-2xl lg:relative lg:h-screen lg:translate-x-0 lg:shadow-none"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'border-[#3d555f] bg-[#18282f]'
|
||||
: 'border-[#b8cbd0] bg-[#f9fcfc]',
|
||||
isSidebarOpen ? 'translate-x-0' : '-translate-x-full',
|
||||
'transition-transform duration-300 ease-in-out lg:transition-none'
|
||||
]"
|
||||
>
|
||||
<!-- Logo区域 -->
|
||||
<div
|
||||
class="flex items-center justify-between h-16 px-4 border-b"
|
||||
:class="[isDarkMode ? 'border-[#3d555f]' : 'border-[#c8d7da]']"
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<div
|
||||
class="rounded-full bg-gradient-to-r from-[#6f98a6] via-[#8eaaa8] to-[#b7b2a1] p-1 animate-spin-slow"
|
||||
>
|
||||
<div class="rounded-full p-1" :class="[isDarkMode ? 'bg-[#18282f]' : 'bg-white']">
|
||||
<BoxIcon
|
||||
class="w-6 h-6"
|
||||
:class="[isDarkMode ? 'text-[#b9dbe2]' : 'text-[#356b7d]']"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<h1
|
||||
@click="router.push('/')"
|
||||
class="ml-2 text-xl font-semibold cursor-pointer"
|
||||
:class="[isDarkMode ? 'text-white' : 'text-[#173b47]']"
|
||||
>
|
||||
{{ t('common.appName') }}
|
||||
</h1>
|
||||
</div>
|
||||
<button type="button" :aria-label="t('common.closeMenu')" :title="t('common.closeMenu')" @click="closeSidebar" class="flex h-11 w-11 items-center justify-center rounded-lg transition-colors lg:hidden" :class="[isDarkMode ? 'hover:bg-[#294047]' : 'hover:bg-[#e5eff1]']">
|
||||
<XIcon class="w-6 h-6" :class="[isDarkMode ? 'text-[#d7e6e9]' : 'text-[#294b56]']" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 导航菜单 -->
|
||||
<nav class="flex-1 overflow-y-auto custom-scrollbar">
|
||||
<ul class="p-4 space-y-2">
|
||||
<li v-for="item in menuItems" :key="item.id">
|
||||
<RouterLink
|
||||
:to="item.redirect"
|
||||
class="flex min-h-11 w-full items-center rounded-lg border-l-4 px-3 text-sm font-medium"
|
||||
:class="[
|
||||
route.name === item.id
|
||||
? isDarkMode
|
||||
? 'border-[#8bc2cf] bg-[#29454f] text-white shadow-sm'
|
||||
: 'border-[#327a91] bg-[#dcecef] text-[#123f4e] shadow-sm'
|
||||
: isDarkMode
|
||||
? 'border-transparent text-[#d0dee1] hover:bg-[#223942] hover:text-white'
|
||||
: 'border-transparent text-[#294b56] hover:bg-[#e8f1f2] hover:text-[#163d49]'
|
||||
]"
|
||||
@click="closeSidebarForMobile"
|
||||
>
|
||||
<component :is="item.icon" class="mr-3 h-5 w-5 shrink-0" />
|
||||
{{ item.name }}
|
||||
</RouterLink>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<!-- 退出登录按钮 -->
|
||||
<div class="p-4 border-t" :class="[isDarkMode ? 'border-[#3d555f]' : 'border-[#c8d7da]']">
|
||||
<button
|
||||
@click="handleLogout"
|
||||
class="flex min-h-11 w-full items-center rounded-lg p-2 transition-colors duration-200"
|
||||
:class="[
|
||||
isDarkMode
|
||||
? 'text-[#d0dee1] hover:bg-[#223942] hover:text-white'
|
||||
: 'text-[#36535c] hover:bg-[#e8f1f2] hover:text-[#173b47]'
|
||||
]"
|
||||
>
|
||||
<LogOutIcon class="w-5 h-5 mr-3" />
|
||||
{{ t('admin.logout') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="flex h-full min-h-0 min-w-0 flex-1 flex-col">
|
||||
<!-- Header -->
|
||||
<header
|
||||
class="h-14 border-b shadow-md transition-colors duration-300 lg:hidden"
|
||||
:class="[isDarkMode ? 'bg-[#1a2930] border-[#31454d]' : 'bg-[#f2f6f5] border-[#c8d7da]']"
|
||||
>
|
||||
<div class="flex h-14 items-center justify-between px-4">
|
||||
<button ref="menuButtonRef" type="button" :aria-label="t('common.openMenu')" :title="t('common.openMenu')" :aria-expanded="isSidebarOpen" @click="openSidebar" class="flex h-11 w-11 items-center justify-center rounded-lg lg:hidden">
|
||||
<MenuIcon class="w-6 h-6" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Content -->
|
||||
<main
|
||||
class="min-h-0 flex-1 overflow-y-auto transition-colors duration-300 custom-scrollbar"
|
||||
:class="[isDarkMode ? 'bg-[#10191e]' : 'bg-[#dfe9eb]']"
|
||||
>
|
||||
<router-view />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, inject, nextTick, onMounted, onUnmounted, watch } from 'vue'
|
||||
import {
|
||||
BoxIcon,
|
||||
MenuIcon,
|
||||
XIcon,
|
||||
FolderIcon,
|
||||
Trash2Icon,
|
||||
CogIcon,
|
||||
LayoutDashboardIcon,
|
||||
ClipboardListIcon,
|
||||
LogOutIcon
|
||||
} from 'lucide-vue-next'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ROUTE_NAMES, ROUTES } from '@/constants'
|
||||
import { useAdminSession } from '@/composables'
|
||||
|
||||
interface MenuItem {
|
||||
id: string
|
||||
name: string
|
||||
icon: typeof LayoutDashboardIcon
|
||||
redirect: string
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const { t } = useI18n()
|
||||
const isDarkMode = inject('isDarkMode')
|
||||
const { logout } = useAdminSession()
|
||||
const menuItems: MenuItem[] = [
|
||||
{
|
||||
id: ROUTE_NAMES.DASHBOARD,
|
||||
name: t('admin.dashboard.title'),
|
||||
icon: LayoutDashboardIcon,
|
||||
redirect: ROUTES.DASHBOARD
|
||||
},
|
||||
{
|
||||
id: ROUTE_NAMES.FILE_MANAGE,
|
||||
name: t('admin.fileManage.title'),
|
||||
icon: FolderIcon,
|
||||
redirect: ROUTES.FILE_MANAGE
|
||||
},
|
||||
{
|
||||
id: ROUTE_NAMES.TRASH,
|
||||
name: '回收站',
|
||||
icon: Trash2Icon,
|
||||
redirect: ROUTES.TRASH
|
||||
},
|
||||
{
|
||||
id: ROUTE_NAMES.ACTIVITY_LOG,
|
||||
name: '操作记录',
|
||||
icon: ClipboardListIcon,
|
||||
redirect: ROUTES.ACTIVITY_LOG
|
||||
},
|
||||
{
|
||||
id: ROUTE_NAMES.SETTINGS,
|
||||
name: t('admin.settings.title'),
|
||||
icon: CogIcon,
|
||||
redirect: ROUTES.SETTINGS
|
||||
}
|
||||
]
|
||||
|
||||
const isSidebarOpen = ref(true)
|
||||
const sidebarRef = ref<HTMLElement | null>(null)
|
||||
const menuButtonRef = ref<HTMLButtonElement | null>(null)
|
||||
|
||||
const openSidebar = async () => {
|
||||
isSidebarOpen.value = true
|
||||
await nextTick()
|
||||
sidebarRef.value?.querySelector<HTMLElement>('button, a[href]')?.focus()
|
||||
}
|
||||
const closeSidebar = async () => {
|
||||
isSidebarOpen.value = false
|
||||
await nextTick()
|
||||
menuButtonRef.value?.focus()
|
||||
}
|
||||
|
||||
const closeSidebarForMobile = () => {
|
||||
if (window.innerWidth < 1024) {
|
||||
void closeSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && window.innerWidth < 1024 && isSidebarOpen.value) {
|
||||
void closeSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
watch(isSidebarOpen, (open) => {
|
||||
if (window.innerWidth < 1024) document.body.style.overflow = open ? 'hidden' : ''
|
||||
})
|
||||
|
||||
// 响应式处理
|
||||
const handleResize = () => {
|
||||
if (window.innerWidth >= 1024) {
|
||||
isSidebarOpen.value = true
|
||||
} else {
|
||||
isSidebarOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
handleResize()
|
||||
window.addEventListener('resize', handleResize)
|
||||
window.addEventListener('keydown', handleEscape)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
window.removeEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = ''
|
||||
})
|
||||
|
||||
// 登出处理
|
||||
const handleLogout = async () => {
|
||||
await logout()
|
||||
await router.push(ROUTES.LOGIN)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 60px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: #e5e7eb;
|
||||
transition: 0.4s;
|
||||
}
|
||||
|
||||
.dark .slider {
|
||||
background-color: #4b5563;
|
||||
}
|
||||
|
||||
input:checked + .slider {
|
||||
background-color: #6f9688;
|
||||
}
|
||||
|
||||
.dark input:checked + .slider {
|
||||
background-color: #6f9688;
|
||||
}
|
||||
|
||||
.slider:before {
|
||||
position: absolute;
|
||||
content: '';
|
||||
height: 26px;
|
||||
width: 26px;
|
||||
left: 4px;
|
||||
bottom: 4px;
|
||||
background-color: white;
|
||||
transition: 0.4s;
|
||||
}
|
||||
|
||||
.dark .slider:before {
|
||||
background-color: #e5e7eb;
|
||||
}
|
||||
|
||||
.slider.round {
|
||||
border-radius: 34px;
|
||||
}
|
||||
|
||||
.slider.round:before {
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-spin-slow {
|
||||
animation: spin 8s linear infinite;
|
||||
}
|
||||
|
||||
.transition-colors {
|
||||
transition-property: background-color, border-color, color, fill, stroke;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 300ms;
|
||||
}
|
||||
|
||||
.custom-scrollbar {
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: #cbd5e0;
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover {
|
||||
background-color: #a0aec0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 暗黑模式下的滚动条样式 */
|
||||
:global(.dark) .custom-scrollbar {
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: #4a5568;
|
||||
|
||||
&:hover {
|
||||
background-color: #2d3748;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
import './assets/style/main.css'
|
||||
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import i18n from './i18n'
|
||||
|
||||
document.documentElement.lang = i18n.global.locale.value
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(i18n)
|
||||
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,123 @@
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { ROUTE_NAMES, ROUTES } from '@/constants'
|
||||
import { readStoredToken } from '@/utils/auth-storage'
|
||||
|
||||
const publicPageMeta = {
|
||||
showGlobalControls: true,
|
||||
showRouteLoading: false,
|
||||
routeTransition: 'transfer-fade'
|
||||
}
|
||||
|
||||
const adminPageMeta = {
|
||||
requiresAuth: true,
|
||||
showGlobalControls: false,
|
||||
showRouteLoading: false
|
||||
}
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: ROUTE_NAMES.RETRIEVE,
|
||||
component: () => import('@/views/RetrievewFileView.vue'),
|
||||
meta: {
|
||||
...publicPageMeta,
|
||||
title: 'retrieve'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: ROUTES.SEND,
|
||||
name: ROUTE_NAMES.SEND,
|
||||
component: () => import('@/views/SendFileView.vue'),
|
||||
meta: {
|
||||
...publicPageMeta,
|
||||
title: 'send'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: ROUTES.ADMIN,
|
||||
name: ROUTE_NAMES.ADMIN,
|
||||
component: () => import('@/layout/AdminLayout/AdminLayout.vue'),
|
||||
redirect: ROUTES.DASHBOARD,
|
||||
meta: adminPageMeta,
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: ROUTE_NAMES.DASHBOARD,
|
||||
component: () => import('@/views/manage/DashboardView.vue'),
|
||||
meta: {
|
||||
...adminPageMeta,
|
||||
title: 'dashboard'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'files',
|
||||
name: ROUTE_NAMES.FILE_MANAGE,
|
||||
component: () => import('@/views/manage/FileManageView.vue'),
|
||||
meta: {
|
||||
...adminPageMeta,
|
||||
title: 'files'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'trash',
|
||||
name: ROUTE_NAMES.TRASH,
|
||||
component: () => import('@/views/manage/TrashView.vue'),
|
||||
meta: {
|
||||
...adminPageMeta,
|
||||
title: 'trash'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'activities',
|
||||
name: ROUTE_NAMES.ACTIVITY_LOG,
|
||||
component: () => import('@/views/manage/ActivityLogView.vue'),
|
||||
meta: {
|
||||
...adminPageMeta,
|
||||
title: 'activities'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'settings',
|
||||
name: ROUTE_NAMES.SETTINGS,
|
||||
component: () => import('@/views/manage/SystemSettingsView.vue'),
|
||||
meta: {
|
||||
...adminPageMeta,
|
||||
title: 'settings'
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ROUTES.LOGIN,
|
||||
name: ROUTE_NAMES.LOGIN,
|
||||
component: () => import('@/views/manage/LoginView.vue'),
|
||||
meta: {
|
||||
showGlobalControls: true,
|
||||
showRouteLoading: true,
|
||||
title: 'login'
|
||||
}
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: ROUTES.HOME
|
||||
}
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(import.meta.env.BASE_URL),
|
||||
routes
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.requiresAuth && !readStoredToken()) {
|
||||
return {
|
||||
path: ROUTES.LOGIN,
|
||||
query: {
|
||||
redirect: to.fullPath
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,10 @@
|
||||
import api from './client'
|
||||
import type { AdminActivityListParams, AdminActivityListResponse, ApiResponse } from '@/types'
|
||||
|
||||
export class ActivityService {
|
||||
static async getAdminActivities(
|
||||
params: AdminActivityListParams
|
||||
): Promise<ApiResponse<AdminActivityListResponse>> {
|
||||
return api.get('/admin/activities', { params })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import api from './client'
|
||||
import type { AdminUser, ApiResponse } from '@/types'
|
||||
|
||||
export class AuthService {
|
||||
static async login(password: string): Promise<ApiResponse<AdminUser>> {
|
||||
return api.post('/admin/login', { password })
|
||||
}
|
||||
|
||||
static async logout(): Promise<ApiResponse> {
|
||||
return api.post('/admin/logout')
|
||||
}
|
||||
|
||||
static async verifyToken(): Promise<ApiResponse<AdminUser>> {
|
||||
return api.get('/admin/verify')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { API_STATUS_CODES, TIME_CONSTANTS } from '@/constants'
|
||||
import type { ApiErrorPayload } from '@/types'
|
||||
import { clearStoredToken, readStoredToken } from '@/utils/auth-storage'
|
||||
|
||||
export const AUTH_EVENTS = {
|
||||
UNAUTHORIZED: 'filecodebox:auth:unauthorized'
|
||||
} as const
|
||||
|
||||
const rawBaseURL =
|
||||
import.meta.env.MODE === 'production'
|
||||
? import.meta.env.VITE_API_BASE_URL_PROD
|
||||
: import.meta.env.VITE_API_BASE_URL_DEV
|
||||
|
||||
export const apiBaseURL = typeof rawBaseURL === 'string' ? rawBaseURL.replace(/\/+$/, '') : ''
|
||||
|
||||
const clientOptions = {
|
||||
baseURL: apiBaseURL,
|
||||
timeout: TIME_CONSTANTS.REQUEST_TIMEOUT,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
const apiClient = axios.create(clientOptions)
|
||||
export const rawApiClient = axios.create(clientOptions)
|
||||
|
||||
const attachAuthToken = (config: InternalAxiosRequestConfig) => {
|
||||
const token = readStoredToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const handleAuthError = (error: AxiosError<ApiErrorPayload>) => {
|
||||
if (error.response?.status === API_STATUS_CODES.UNAUTHORIZED) {
|
||||
clearStoredToken()
|
||||
window.dispatchEvent(new CustomEvent(AUTH_EVENTS.UNAUTHORIZED))
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
apiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.request.use(
|
||||
attachAuthToken,
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response.data,
|
||||
handleAuthError
|
||||
)
|
||||
|
||||
rawApiClient.interceptors.response.use((response) => response, handleAuthError)
|
||||
|
||||
export default apiClient
|
||||
@@ -0,0 +1,52 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, ConfigState, PublicConfigPayload } from '@/types'
|
||||
|
||||
const isPublicConfigEnvelope = (
|
||||
detail: ConfigState | PublicConfigPayload | null | undefined
|
||||
): detail is PublicConfigPayload => {
|
||||
return !!detail && typeof detail === 'object' && 'config' in detail
|
||||
}
|
||||
|
||||
const normalizeUserConfigResponse = (
|
||||
response: ApiResponse<ConfigState | PublicConfigPayload>
|
||||
): ApiResponse<PublicConfigPayload> => {
|
||||
if (isPublicConfigEnvelope(response.detail)) {
|
||||
return {
|
||||
...response,
|
||||
detail: {
|
||||
config: response.detail.config,
|
||||
meta: response.detail.meta
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...response,
|
||||
detail: {
|
||||
config: response.detail ?? {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class ConfigService {
|
||||
static async getConfig(): Promise<ApiResponse<ConfigState>> {
|
||||
return api.get('/admin/config/get')
|
||||
}
|
||||
|
||||
static async getUserConfig(): Promise<ApiResponse<PublicConfigPayload>> {
|
||||
try {
|
||||
const response = (await api.get('/api/v1/config')) as ApiResponse<
|
||||
ConfigState | PublicConfigPayload
|
||||
>
|
||||
|
||||
return normalizeUserConfigResponse(response)
|
||||
} catch {
|
||||
const response = (await api.post('/')) as ApiResponse<ConfigState>
|
||||
return normalizeUserConfigResponse(response)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateConfig(config: Partial<ConfigState>): Promise<ApiResponse> {
|
||||
return api.patch('/admin/config/update', config)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import api, { rawApiClient } from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import type {
|
||||
AdminBatchDeleteFilesResponse,
|
||||
AdminBatchPolicyActionRequest,
|
||||
AdminBatchPolicyActionResponse,
|
||||
AdminBatchUpdateFilesRequest,
|
||||
AdminBatchUpdateFilesResponse,
|
||||
AdminFilePatchPayload,
|
||||
AdminFileDetailResponse,
|
||||
AdminFileListParams,
|
||||
AdminFileMetadataRequest,
|
||||
AdminFilePolicyActionRequest,
|
||||
AdminFilePreviewResponse,
|
||||
AdminFileViewPreset,
|
||||
AdminFileViewPresetRequest,
|
||||
AdminFileViewPresetsResponse,
|
||||
ApiResponse,
|
||||
ChunkUploadCompleteRequest,
|
||||
ChunkUploadInitRequest,
|
||||
ChunkUploadInitResponse,
|
||||
ChunkUploadResponse,
|
||||
FileEditForm,
|
||||
FileInfo,
|
||||
FileListResponse,
|
||||
FileUploadResponse,
|
||||
ShareMetadataResponse,
|
||||
ShareSelectResponse,
|
||||
TextSendResponse,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
const urlEncodedConfig = {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
}
|
||||
}
|
||||
|
||||
const toUrlEncodedForm = (data: Record<string, string | number>) => {
|
||||
const form = new URLSearchParams()
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
form.append(key, String(value))
|
||||
})
|
||||
return form
|
||||
}
|
||||
|
||||
const isMethodFallbackError = (error: unknown) => {
|
||||
const status = (error as { response?: { status?: number } })?.response?.status
|
||||
return status === 404 || status === 405
|
||||
}
|
||||
|
||||
export class FileService {
|
||||
static async uploadFile(
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.post('/share/file/', formData, multipartUploadConfig(onProgress))
|
||||
}
|
||||
|
||||
static async uploadText(
|
||||
text: string,
|
||||
expireValue = 1,
|
||||
expireStyle = 'day'
|
||||
): Promise<ApiResponse<TextSendResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('text', text)
|
||||
formData.append('expire_value', String(expireValue))
|
||||
formData.append('expire_style', expireStyle)
|
||||
return api.post('/share/text/', formData, multipartUploadConfig())
|
||||
}
|
||||
|
||||
static async initChunkUpload(
|
||||
request: ChunkUploadInitRequest
|
||||
): Promise<ApiResponse<ChunkUploadInitResponse>> {
|
||||
return api.post(
|
||||
'/chunk/upload/init/',
|
||||
toUrlEncodedForm({
|
||||
file_name: request.file_name,
|
||||
file_size: request.file_size,
|
||||
chunk_size: request.chunk_size,
|
||||
file_hash: request.file_hash
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async uploadChunk(
|
||||
uploadId: string,
|
||||
chunkIndex: number,
|
||||
chunk: Blob,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<ApiResponse<ChunkUploadResponse>> {
|
||||
const formData = new FormData()
|
||||
formData.append('chunk', chunk)
|
||||
return api.post(
|
||||
`/chunk/upload/chunk/${uploadId}/${chunkIndex}`,
|
||||
formData,
|
||||
multipartUploadConfig(onProgress)
|
||||
)
|
||||
}
|
||||
|
||||
static async completeChunkUpload(
|
||||
uploadId: string,
|
||||
request: ChunkUploadCompleteRequest
|
||||
): Promise<ApiResponse<FileUploadResponse>> {
|
||||
return api.post(
|
||||
`/chunk/upload/complete/${uploadId}`,
|
||||
toUrlEncodedForm({
|
||||
expire_value: request.expire_value,
|
||||
expire_style: request.expire_style
|
||||
}),
|
||||
urlEncodedConfig
|
||||
)
|
||||
}
|
||||
|
||||
static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> {
|
||||
return api.post('/share/select/', { code })
|
||||
}
|
||||
|
||||
static async inspectFile(code: string): Promise<ApiResponse<ShareMetadataResponse>> {
|
||||
return api.post('/share/metadata/', { code })
|
||||
}
|
||||
|
||||
static async getFile(code: string): Promise<ApiResponse<FileInfo>> {
|
||||
return api.get(`/file/${code}`)
|
||||
}
|
||||
|
||||
static async downloadFile(code: string): Promise<Blob> {
|
||||
const response = await rawApiClient.get<Blob>(`/download/${code}`, {
|
||||
responseType: 'blob'
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
static async getAdminFileList(
|
||||
params: AdminFileListParams
|
||||
): Promise<ApiResponse<FileListResponse>> {
|
||||
return api.get('/admin/file/list', { params })
|
||||
}
|
||||
|
||||
static async getAdminFileDetail(id: number): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
return api.get('/admin/file/detail', {
|
||||
params: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async updateFile(data: FileEditForm | AdminFilePatchPayload): Promise<ApiResponse> {
|
||||
return api.patch('/admin/file/update', data)
|
||||
}
|
||||
|
||||
static async applyAdminFilePolicyAction(
|
||||
data: AdminFilePolicyActionRequest
|
||||
): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/policy-action', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/policy-action', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async applyAdminFilesPolicyAction(
|
||||
data: AdminBatchPolicyActionRequest
|
||||
): Promise<ApiResponse<AdminBatchPolicyActionResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/batch-policy-action', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/batch-policy-action', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateAdminFileMetadata(
|
||||
data: AdminFileMetadataRequest
|
||||
): Promise<ApiResponse<AdminFileDetailResponse>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/metadata', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/metadata', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async getAdminFileViewPresets(): Promise<ApiResponse<AdminFileViewPresetsResponse>> {
|
||||
return api.get('/admin/file/view-presets')
|
||||
}
|
||||
|
||||
static async saveAdminFileViewPreset(
|
||||
data: AdminFileViewPresetRequest
|
||||
): Promise<ApiResponse<AdminFileViewPreset>> {
|
||||
try {
|
||||
return await api.patch('/admin/file/view-presets', data)
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/view-presets', data)
|
||||
}
|
||||
}
|
||||
|
||||
static async updateAdminFiles(
|
||||
data: AdminBatchUpdateFilesRequest
|
||||
): Promise<ApiResponse<AdminBatchUpdateFilesResponse>> {
|
||||
return api.patch('/admin/file/batch-update', data)
|
||||
}
|
||||
|
||||
static async deleteAdminFile(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/file/delete', {
|
||||
data: { id }
|
||||
})
|
||||
}
|
||||
|
||||
static async deleteAdminFiles(
|
||||
ids: number[]
|
||||
): Promise<ApiResponse<AdminBatchDeleteFilesResponse>> {
|
||||
return api.delete('/admin/file/batch-delete', {
|
||||
data: { ids }
|
||||
})
|
||||
}
|
||||
|
||||
static async deleteAdminFileViewPreset(id: string): Promise<ApiResponse> {
|
||||
try {
|
||||
return await api.delete('/admin/file/view-presets', {
|
||||
data: { id }
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (!isMethodFallbackError(error)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
return api.post('/admin/file/view-presets/delete', { id })
|
||||
}
|
||||
}
|
||||
|
||||
static async downloadAdminFile(
|
||||
id: number
|
||||
): Promise<{ data: Blob; headers: Record<string, string> }> {
|
||||
const response = await rawApiClient.get<Blob>('/admin/file/download', {
|
||||
params: { id },
|
||||
responseType: 'blob'
|
||||
})
|
||||
return {
|
||||
data: response.data,
|
||||
headers: response.headers as Record<string, string>
|
||||
}
|
||||
}
|
||||
|
||||
static async previewAdminFile(
|
||||
id: number,
|
||||
maxChars = 20000
|
||||
): Promise<ApiResponse<AdminFilePreviewResponse>> {
|
||||
return api.get('/admin/file/preview', {
|
||||
params: {
|
||||
id,
|
||||
maxChars
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export { AUTH_EVENTS } from './client'
|
||||
export { ActivityService } from './activity'
|
||||
export { AuthService } from './auth'
|
||||
export { ConfigService } from './config'
|
||||
export { FileService } from './file'
|
||||
export { PresignUploadService } from './presign-upload'
|
||||
export { StatsService } from './stats'
|
||||
export { TrashService } from './trash'
|
||||
export { uploadChunkedFile } from './upload-strategy'
|
||||
@@ -0,0 +1,58 @@
|
||||
import api from './client'
|
||||
import { multipartUploadConfig } from './shared'
|
||||
import { uploadToExternalUrl } from './upload-client'
|
||||
import type {
|
||||
ApiResponse,
|
||||
PresignConfirmRequest,
|
||||
PresignInitRequest,
|
||||
PresignInitResponse,
|
||||
PresignStatusResponse,
|
||||
PresignUploadResult,
|
||||
UploadProgress
|
||||
} from '@/types'
|
||||
|
||||
export class PresignUploadService {
|
||||
static async initUpload(request: PresignInitRequest): Promise<ApiResponse<PresignInitResponse>> {
|
||||
return api.post('/presign/upload/init', request)
|
||||
}
|
||||
|
||||
static async proxyUpload(
|
||||
uploadId: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void,
|
||||
uploadUrl?: string
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
|
||||
return api.put(
|
||||
uploadUrl || `/presign/upload/proxy/${uploadId}`,
|
||||
formData,
|
||||
multipartUploadConfig(onProgress)
|
||||
)
|
||||
}
|
||||
|
||||
static async confirmUpload(
|
||||
uploadId: string,
|
||||
request?: PresignConfirmRequest
|
||||
): Promise<ApiResponse<PresignUploadResult>> {
|
||||
return api.post(`/presign/upload/confirm/${uploadId}`, request || {})
|
||||
}
|
||||
|
||||
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
|
||||
return api.get(`/presign/upload/status/${uploadId}`)
|
||||
}
|
||||
|
||||
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> {
|
||||
return api.delete(`/presign/upload/${uploadId}`)
|
||||
}
|
||||
|
||||
static async directUploadToS3(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<boolean> {
|
||||
await uploadToExternalUrl(uploadUrl, file, onProgress)
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { AxiosRequestConfig } from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export const multipartUploadConfig = (
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): AxiosRequestConfig => ({
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (onProgress && progressEvent.total) {
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import api from './client'
|
||||
import type { AnalyticsData, ApiResponse, DashboardData } from '@/types'
|
||||
|
||||
export class StatsService {
|
||||
static async getDashboard(): Promise<ApiResponse<DashboardData>> {
|
||||
return api.get('/admin/dashboard')
|
||||
}
|
||||
|
||||
static async getAnalytics(start?: string, end?: string): Promise<ApiResponse<AnalyticsData>> {
|
||||
return api.get('/admin/analytics', {
|
||||
params: {
|
||||
start,
|
||||
end
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import api from './client'
|
||||
import type { ApiResponse, TrashListParams, TrashListResponse } from '@/types'
|
||||
|
||||
export class TrashService {
|
||||
static async list(params: TrashListParams): Promise<ApiResponse<TrashListResponse>> {
|
||||
return api.get('/admin/trash/list', { params })
|
||||
}
|
||||
|
||||
static async restore(id: number): Promise<ApiResponse> {
|
||||
return api.post('/admin/trash/restore', { id })
|
||||
}
|
||||
|
||||
static async purge(id: number): Promise<ApiResponse> {
|
||||
return api.delete('/admin/trash/purge', { data: { id } })
|
||||
}
|
||||
|
||||
static async updateRetention(id: number, retentionDays: number): Promise<ApiResponse> {
|
||||
return api.post('/admin/trash/retention', { id, retentionDays })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import axios from 'axios'
|
||||
import type { UploadProgress } from '@/types'
|
||||
|
||||
export async function uploadToExternalUrl(
|
||||
uploadUrl: string,
|
||||
file: File,
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
): Promise<void> {
|
||||
await axios.put(uploadUrl, file, {
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream'
|
||||
},
|
||||
timeout: 0,
|
||||
onUploadProgress: (progressEvent) => {
|
||||
if (!onProgress || !progressEvent.total) {
|
||||
return
|
||||
}
|
||||
|
||||
onProgress({
|
||||
loaded: progressEvent.loaded,
|
||||
total: progressEvent.total,
|
||||
percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { FileService } from './file'
|
||||
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
|
||||
import { calculateFileHash } from '@/utils/file-processing'
|
||||
|
||||
const CHUNK_SIZE = 5 * 1024 * 1024
|
||||
|
||||
type ChunkedUploadOptions = {
|
||||
expireValue: number
|
||||
expireStyle: string
|
||||
onHashCalculated?: (hash: string) => void
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
messages?: {
|
||||
initFailed?: string
|
||||
chunkFailed?: (index: number) => string
|
||||
completeFailed?: string
|
||||
}
|
||||
onStatus?: (status: 'initializing' | 'uploading' | 'confirming' | 'success' | 'error') => void
|
||||
}
|
||||
|
||||
type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse
|
||||
|
||||
const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number, fileSize: number) =>
|
||||
Array.from(uploadedChunks).reduce((total, index) => {
|
||||
const chunkStart = index * chunkSize
|
||||
const chunkEnd = Math.min((index + 1) * chunkSize, fileSize)
|
||||
return total + Math.max(0, chunkEnd - chunkStart)
|
||||
}, 0)
|
||||
|
||||
export const uploadChunkedFile = async (
|
||||
file: File,
|
||||
options: ChunkedUploadOptions
|
||||
): Promise<ApiResponse<ChunkedUploadResult>> => {
|
||||
options.onStatus?.('initializing')
|
||||
const fileHash = await calculateFileHash(file)
|
||||
options.onHashCalculated?.(fileHash)
|
||||
|
||||
const chunks = Math.ceil(file.size / CHUNK_SIZE)
|
||||
const initResponse = await FileService.initChunkUpload({
|
||||
file_name: file.name,
|
||||
file_size: file.size,
|
||||
chunk_size: CHUNK_SIZE,
|
||||
file_hash: fileHash
|
||||
})
|
||||
|
||||
if (initResponse.code !== 200) {
|
||||
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
||||
}
|
||||
|
||||
if (initResponse.detail?.existed) {
|
||||
return initResponse
|
||||
}
|
||||
|
||||
const initDetail = initResponse.detail
|
||||
const uploadId = initDetail?.upload_id
|
||||
if (!uploadId) {
|
||||
throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
|
||||
}
|
||||
|
||||
const uploadedChunks = new Set(initDetail.uploaded_chunks || [])
|
||||
options.onStatus?.('uploading')
|
||||
for (let index = 0; index < chunks; index++) {
|
||||
if (uploadedChunks.has(index)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const start = index * CHUNK_SIZE
|
||||
const end = Math.min(start + CHUNK_SIZE, file.size)
|
||||
const chunk = file.slice(start, end)
|
||||
const chunkResponse = await FileService.uploadChunk(
|
||||
uploadId,
|
||||
index,
|
||||
new Blob([chunk], { type: file.type }),
|
||||
(progress) => {
|
||||
const completedBytes = calculateCompletedBytes(uploadedChunks, CHUNK_SIZE, file.size)
|
||||
const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size)
|
||||
options.onProgress?.({
|
||||
loaded: completedBytes + progress.loaded,
|
||||
total: file.size,
|
||||
percentage: Math.min(percentage, 99)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
if (chunkResponse.code !== 200) {
|
||||
throw new Error(options.messages?.chunkFailed?.(index) || `Chunk upload failed: ${index}`)
|
||||
}
|
||||
uploadedChunks.add(index)
|
||||
}
|
||||
|
||||
options.onStatus?.('confirming')
|
||||
const completeResponse = await FileService.completeChunkUpload(uploadId, {
|
||||
expire_value: options.expireValue,
|
||||
expire_style: options.expireStyle
|
||||
})
|
||||
|
||||
if (completeResponse.code !== 200) {
|
||||
options.onStatus?.('error')
|
||||
throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
|
||||
}
|
||||
|
||||
options.onStatus?.('success')
|
||||
return completeResponse
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import type { AdminUser } from '@/types'
|
||||
import {
|
||||
clearStoredAuth,
|
||||
readStoredAdminPassword,
|
||||
readStoredToken,
|
||||
writeStoredAdminPassword,
|
||||
writeStoredToken
|
||||
} from '@/utils/auth-storage'
|
||||
|
||||
export const useAdminStore = defineStore('admin', () => {
|
||||
// 状态
|
||||
const adminPassword = ref(readStoredAdminPassword())
|
||||
const token = ref(readStoredToken())
|
||||
const isLoggedIn = ref(false)
|
||||
const userInfo = ref<AdminUser | null>(null)
|
||||
|
||||
// 计算属性
|
||||
const isAuthenticated = computed(() => {
|
||||
return isLoggedIn.value && !!token.value
|
||||
})
|
||||
const hasToken = computed(() => !!token.value)
|
||||
|
||||
// 方法
|
||||
const updateAdminPassword = (pwd: string) => {
|
||||
adminPassword.value = pwd
|
||||
writeStoredAdminPassword(pwd)
|
||||
}
|
||||
|
||||
const setToken = (newToken: string) => {
|
||||
token.value = newToken
|
||||
writeStoredToken(newToken)
|
||||
}
|
||||
|
||||
const setUserInfo = (user: AdminUser) => {
|
||||
userInfo.value = user
|
||||
isLoggedIn.value = true
|
||||
setToken(user.token)
|
||||
}
|
||||
|
||||
const login = (user: AdminUser) => {
|
||||
setUserInfo(user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
adminPassword.value = ''
|
||||
token.value = ''
|
||||
isLoggedIn.value = false
|
||||
userInfo.value = null
|
||||
|
||||
clearStoredAuth()
|
||||
}
|
||||
|
||||
const initAuth = () => {
|
||||
const storedToken = readStoredToken()
|
||||
if (storedToken) {
|
||||
token.value = storedToken
|
||||
isLoggedIn.value = true
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
adminPassword,
|
||||
token,
|
||||
isLoggedIn,
|
||||
userInfo,
|
||||
|
||||
// 计算属性
|
||||
isAuthenticated,
|
||||
hasToken,
|
||||
|
||||
// 方法
|
||||
updateAdminPassword,
|
||||
setToken,
|
||||
setUserInfo,
|
||||
login,
|
||||
logout,
|
||||
initAuth
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { Alert, AlertType } from '@/types'
|
||||
import { TIME_CONSTANTS } from '@/constants'
|
||||
|
||||
let progressTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
export const useAlertStore = defineStore('alert', {
|
||||
state: () => ({
|
||||
alerts: [] as Alert[]
|
||||
}),
|
||||
actions: {
|
||||
showAlert(
|
||||
message: string,
|
||||
type: AlertType = 'info',
|
||||
duration = TIME_CONSTANTS.ALERT_DURATION
|
||||
) {
|
||||
const id = Date.now()
|
||||
const startTime = Date.now()
|
||||
this.alerts.push({ id, message, type, progress: 100, duration, startTime })
|
||||
this.startProgressTimer()
|
||||
setTimeout(() => this.removeAlert(id), duration)
|
||||
},
|
||||
removeAlert(id: number) {
|
||||
const index = this.alerts.findIndex((alert) => alert.id === id)
|
||||
if (index > -1) {
|
||||
this.alerts.splice(index, 1)
|
||||
}
|
||||
if (this.alerts.length === 0) this.stopProgressTimer()
|
||||
},
|
||||
updateAlertProgress(id: number) {
|
||||
const alert = this.alerts.find((a) => a.id === id)
|
||||
if (alert) {
|
||||
const elapsedTime = Date.now() - alert.startTime
|
||||
const progress = 100 - (elapsedTime / alert.duration) * 100
|
||||
alert.progress = Math.max(0, progress)
|
||||
if (alert.progress <= 0) {
|
||||
this.removeAlert(id)
|
||||
}
|
||||
}
|
||||
},
|
||||
startProgressTimer() {
|
||||
if (progressTimer) {
|
||||
return
|
||||
}
|
||||
|
||||
progressTimer = setInterval(() => {
|
||||
this.alerts.forEach((alert) => {
|
||||
this.updateAlertProgress(alert.id)
|
||||
})
|
||||
}, TIME_CONSTANTS.PROGRESS_UPDATE_INTERVAL)
|
||||
},
|
||||
stopProgressTimer() {
|
||||
if (!progressTimer) {
|
||||
return
|
||||
}
|
||||
|
||||
clearInterval(progressTimer)
|
||||
progressTimer = null
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import type { ConfigState, PublicConfigMeta } from '@/types'
|
||||
import {
|
||||
DEFAULT_PUBLIC_CONFIG,
|
||||
readNotifyKey,
|
||||
readStoredConfig,
|
||||
toPublicConfig,
|
||||
writeNotifyKey,
|
||||
writeStoredConfig,
|
||||
type PublicConfig
|
||||
} from '@/utils/config-storage'
|
||||
|
||||
export const useConfigStore = defineStore('config', () => {
|
||||
const config = ref<PublicConfig>({
|
||||
...DEFAULT_PUBLIC_CONFIG,
|
||||
...toPublicConfig(readStoredConfig<Partial<ConfigState>>())
|
||||
})
|
||||
const publicMeta = ref<PublicConfigMeta>({})
|
||||
|
||||
const uploadSizeLimit = computed(() => config.value.uploadSize)
|
||||
const appVersion = computed(() => publicMeta.value.version || '')
|
||||
|
||||
const updateConfig = (nextConfig: Partial<ConfigState>) => {
|
||||
config.value = {
|
||||
...DEFAULT_PUBLIC_CONFIG,
|
||||
...config.value,
|
||||
...toPublicConfig(nextConfig)
|
||||
}
|
||||
writeStoredConfig(config.value)
|
||||
}
|
||||
|
||||
const applyRemoteConfig = (nextConfig: Partial<ConfigState>): string | null => {
|
||||
updateConfig(nextConfig)
|
||||
|
||||
const { notify_title: notifyTitle, notify_content: notifyContent } = nextConfig
|
||||
if (!notifyTitle || !notifyContent) {
|
||||
return null
|
||||
}
|
||||
|
||||
const notifyKey = notifyTitle + notifyContent
|
||||
if (readNotifyKey() === notifyKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
writeNotifyKey(notifyKey)
|
||||
return `${notifyTitle}: ${notifyContent}`
|
||||
}
|
||||
|
||||
const applyPublicMeta = (nextMeta: PublicConfigMeta | undefined) => {
|
||||
if (!nextMeta) return
|
||||
|
||||
publicMeta.value = {
|
||||
...publicMeta.value,
|
||||
...nextMeta
|
||||
}
|
||||
}
|
||||
|
||||
const reloadStoredConfig = () => {
|
||||
config.value = {
|
||||
...DEFAULT_PUBLIC_CONFIG,
|
||||
...toPublicConfig(readStoredConfig<Partial<ConfigState>>())
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
appVersion,
|
||||
config,
|
||||
publicMeta,
|
||||
uploadSizeLimit,
|
||||
applyPublicMeta,
|
||||
applyRemoteConfig,
|
||||
updateConfig,
|
||||
reloadStoredConfig
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import type { ReceivedFileRecord, SentFileRecord } from '@/types'
|
||||
|
||||
export const useFileDataStore = defineStore('fileData', () => {
|
||||
const receiveData = ref<ReceivedFileRecord[]>([])
|
||||
const shareData = ref<SentFileRecord[]>([])
|
||||
|
||||
const addReceiveData = (record: ReceivedFileRecord) => {
|
||||
receiveData.value.push(record)
|
||||
}
|
||||
|
||||
const removeReceiveData = (id: number) => {
|
||||
const index = receiveData.value.findIndex((record) => record.id === id)
|
||||
if (index !== -1) {
|
||||
receiveData.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteReceiveData = (index: number) => {
|
||||
if (index >= 0 && index < receiveData.value.length) {
|
||||
receiveData.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const clearReceiveData = () => {
|
||||
receiveData.value = []
|
||||
}
|
||||
|
||||
const addShareDataRecord = (record: SentFileRecord) => {
|
||||
shareData.value.push(record)
|
||||
}
|
||||
|
||||
const deleteShareData = (index: number) => {
|
||||
if (index >= 0 && index < shareData.value.length) {
|
||||
shareData.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const clearShareData = () => {
|
||||
shareData.value = []
|
||||
}
|
||||
|
||||
return {
|
||||
receiveData,
|
||||
shareData,
|
||||
addReceiveData,
|
||||
removeReceiveData,
|
||||
deleteReceiveData,
|
||||
clearReceiveData,
|
||||
addShareDataRecord,
|
||||
deleteShareData,
|
||||
clearShareData
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
export interface AdminActivityEvent {
|
||||
id: string
|
||||
action: string
|
||||
targetType: string
|
||||
target_type?: string
|
||||
targetId?: string | number | null
|
||||
target_id?: string | number | null
|
||||
targetName: string
|
||||
target_name?: string
|
||||
count: number
|
||||
meta: Record<string, unknown>
|
||||
createdAt: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export interface AdminActivityOption {
|
||||
value: string
|
||||
label: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface AdminActivityListResponse {
|
||||
activities?: AdminActivityEvent[]
|
||||
items?: AdminActivityEvent[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
storedTotal?: number
|
||||
stored_total?: number
|
||||
filters?: {
|
||||
action?: string
|
||||
targetType?: string
|
||||
target_type?: string
|
||||
keyword?: string
|
||||
}
|
||||
actionOptions?: AdminActivityOption[]
|
||||
action_options?: AdminActivityOption[]
|
||||
targetTypeOptions?: AdminActivityOption[]
|
||||
target_type_options?: AdminActivityOption[]
|
||||
}
|
||||
|
||||
export interface AdminActivityListParams {
|
||||
page: number
|
||||
size: number
|
||||
action?: string
|
||||
targetType?: string
|
||||
keyword?: string
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface ApiResponse<T = unknown> {
|
||||
code: number
|
||||
message?: string
|
||||
msg?: string
|
||||
detail?: T
|
||||
}
|
||||
|
||||
export interface ApiErrorPayload {
|
||||
detail?: string
|
||||
message?: string
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export interface AdminUser {
|
||||
id: string
|
||||
username: string
|
||||
token: string
|
||||
token_type?: string
|
||||
expires_at?: number
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export interface SystemConfig {
|
||||
name: string
|
||||
description?: string
|
||||
maxFileSize: number
|
||||
allowedFileTypes: string[]
|
||||
expireDays: number
|
||||
notify_title?: string
|
||||
notify_content?: string
|
||||
}
|
||||
|
||||
export interface ThemeChoice {
|
||||
key: string
|
||||
name: string
|
||||
author: string
|
||||
version: string
|
||||
}
|
||||
|
||||
export interface PublicConfigMeta {
|
||||
version?: string
|
||||
api?: Record<string, string>
|
||||
features?: Record<string, unknown>
|
||||
limits?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface PublicConfigPayload {
|
||||
config: Partial<ConfigState>
|
||||
meta?: PublicConfigMeta
|
||||
}
|
||||
|
||||
export interface ConfigState {
|
||||
name: string
|
||||
description: string
|
||||
file_storage: string
|
||||
themesChoices: ThemeChoice[]
|
||||
expireStyle: string[]
|
||||
admin_token: string
|
||||
robotsText: string
|
||||
keywords: string
|
||||
notify_title: string
|
||||
notify_content: string
|
||||
openUpload: number
|
||||
uploadSize: number
|
||||
storage_path: string
|
||||
uploadMinute: number
|
||||
max_save_seconds: number
|
||||
trashRetentionDays: number
|
||||
opacity: number
|
||||
enableChunk: number
|
||||
s3_access_key_id: string
|
||||
background: string
|
||||
showAdminAddr: number
|
||||
page_explain: string
|
||||
s3_secret_access_key: string
|
||||
aws_session_token: string
|
||||
s3_signature_version: string
|
||||
s3_region_name: string
|
||||
s3_bucket_name: string
|
||||
s3_endpoint_url: string
|
||||
s3_hostname: string
|
||||
uploadCount: number
|
||||
errorMinute: number
|
||||
errorCount: number
|
||||
s3_proxy: number
|
||||
themesSelect: string
|
||||
webdav_url: string
|
||||
webdav_username: string
|
||||
webdav_password: string
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { AdminFileHealthFilter } from './file'
|
||||
|
||||
export interface DashboardHealthSummary {
|
||||
healthAttentionCount: number
|
||||
healthDangerCount: number
|
||||
healthWarningCount: number
|
||||
expiringSoonCount: number
|
||||
storageIssueCount: number
|
||||
neverRetrievedCount: number
|
||||
healthyCount: number
|
||||
permanentCount: number
|
||||
}
|
||||
|
||||
export interface DashboardData {
|
||||
totalFiles: number
|
||||
storageUsed: number | string
|
||||
yesterdayCount: number
|
||||
todayCount: number
|
||||
yesterdaySize: number | string
|
||||
todaySize: number | string
|
||||
sysUptime: number | null
|
||||
activeCount?: number
|
||||
expiredCount?: number
|
||||
textCount?: number
|
||||
fileCount?: number
|
||||
chunkedCount?: number
|
||||
usedCount?: number
|
||||
storageBackend?: string
|
||||
uploadSizeLimit?: number
|
||||
openUpload?: number
|
||||
enableChunk?: number
|
||||
maxSaveSeconds?: number
|
||||
healthAttentionCount?: number
|
||||
healthDangerCount?: number
|
||||
healthWarningCount?: number
|
||||
expiringSoonCount?: number
|
||||
storageIssueCount?: number
|
||||
neverRetrievedCount?: number
|
||||
healthyCount?: number
|
||||
permanentCount?: number
|
||||
healthSummary?: Partial<DashboardHealthSummary>
|
||||
}
|
||||
|
||||
export type DashboardViewData = Omit<
|
||||
DashboardData,
|
||||
| keyof DashboardHealthSummary
|
||||
| 'activeCount'
|
||||
| 'expiredCount'
|
||||
| 'textCount'
|
||||
| 'fileCount'
|
||||
| 'chunkedCount'
|
||||
| 'usedCount'
|
||||
| 'storageBackend'
|
||||
| 'uploadSizeLimit'
|
||||
| 'openUpload'
|
||||
| 'enableChunk'
|
||||
| 'maxSaveSeconds'
|
||||
| 'storageUsed'
|
||||
| 'yesterdaySize'
|
||||
| 'todaySize'
|
||||
> &
|
||||
DashboardHealthSummary & {
|
||||
hasExtendedStats: boolean
|
||||
activeCount: number
|
||||
expiredCount: number
|
||||
textCount: number
|
||||
fileCount: number
|
||||
chunkedCount: number
|
||||
usedCount: number
|
||||
storageBackend: string
|
||||
uploadSizeLimit: number
|
||||
openUpload: number
|
||||
enableChunk: number
|
||||
maxSaveSeconds: number
|
||||
storageUsed: number
|
||||
yesterdaySize: number
|
||||
todaySize: number
|
||||
storageUsedText: string
|
||||
yesterdaySizeText: string
|
||||
todaySizeText: string
|
||||
uploadSizeLimitText: string
|
||||
sysUptimeText: string
|
||||
activeRatio: number
|
||||
textRatio: number
|
||||
fileRatio: number
|
||||
healthyRatio: number
|
||||
healthAttentionRatio: number
|
||||
todaySizeRatio: number
|
||||
}
|
||||
|
||||
export interface DashboardHealthAction {
|
||||
key: string
|
||||
label: string
|
||||
description: string
|
||||
count: number
|
||||
health: AdminFileHealthFilter
|
||||
tone: 'danger' | 'warning' | 'success' | 'neutral'
|
||||
}
|
||||
|
||||
export interface AnalyticsDailyRow {
|
||||
date: string
|
||||
downloads: number
|
||||
uploads: number
|
||||
downloadTraffic: number | string
|
||||
uploadTraffic: number | string
|
||||
}
|
||||
|
||||
export interface AnalyticsFileRow {
|
||||
code: string
|
||||
name: string
|
||||
size: number | string
|
||||
download_count: number
|
||||
download_traffic: number | string
|
||||
upload_count?: number
|
||||
upload_traffic?: number | string
|
||||
current: boolean
|
||||
expired?: boolean
|
||||
deleted?: boolean
|
||||
created_at?: string
|
||||
uploaded_at?: string
|
||||
expired_at?: string
|
||||
deleted_at?: string
|
||||
}
|
||||
|
||||
export interface AnalyticsData {
|
||||
range: {
|
||||
start: string
|
||||
end: string
|
||||
}
|
||||
totals: {
|
||||
totalDownloads: number
|
||||
downloadedFiles: number
|
||||
downloadTraffic: number | string
|
||||
historicalFiles: number
|
||||
currentFiles: number
|
||||
totalUploads?: number
|
||||
uploadTraffic?: number | string
|
||||
}
|
||||
daily: AnalyticsDailyRow[]
|
||||
topFiles: AnalyticsFileRow[]
|
||||
historyFiles: AnalyticsFileRow[]
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
export interface FileInfo {
|
||||
id: string
|
||||
name: string
|
||||
size: number
|
||||
type: string
|
||||
uploadTime: string
|
||||
downloadCount: number
|
||||
expireTime?: string
|
||||
}
|
||||
|
||||
export interface FileListItem {
|
||||
id: number
|
||||
code: string
|
||||
prefix: string
|
||||
suffix: string
|
||||
size: number
|
||||
text?: string
|
||||
description?: string
|
||||
expired_at: string | null
|
||||
expired_count: number | null
|
||||
created_at: string
|
||||
name?: string
|
||||
type?: 'text' | 'file'
|
||||
status?: 'active' | 'expired'
|
||||
isText?: boolean
|
||||
is_text?: boolean
|
||||
isExpired?: boolean
|
||||
is_expired?: boolean
|
||||
isChunked?: boolean
|
||||
is_chunked?: boolean
|
||||
statusInsights?: AdminFileDetailStatusInsights
|
||||
status_insights?: AdminFileDetailStatusInsights
|
||||
remainingDownloads?: number | null
|
||||
remaining_downloads?: number | null
|
||||
usedCount?: number
|
||||
used_count?: number
|
||||
fileHash?: string | null
|
||||
file_hash?: string | null
|
||||
}
|
||||
|
||||
export interface AdminFileViewItem extends FileListItem {
|
||||
displayName: string
|
||||
displaySize: string
|
||||
displayExpiredAt: string
|
||||
displayUsage: string
|
||||
displayHealthState: string
|
||||
displayHealthAction: string
|
||||
isTextFile: boolean
|
||||
isExpiredFile: boolean
|
||||
isPermanentFile: boolean
|
||||
isChunkedFile: boolean
|
||||
remainingDownloadsValue: number | null
|
||||
canPreviewText: boolean
|
||||
statusInsightSeverity: AdminFileInsightSeverity
|
||||
statusInsightState: string
|
||||
statusInsightNextAction: string
|
||||
statusInsightReasons: string[]
|
||||
}
|
||||
|
||||
export interface AdminFileSummary {
|
||||
totalFiles: number
|
||||
activeCount: number
|
||||
expiredCount: number
|
||||
textCount: number
|
||||
fileCount: number
|
||||
chunkedCount: number
|
||||
healthAttentionCount: number
|
||||
healthDangerCount: number
|
||||
healthWarningCount: number
|
||||
expiringSoonCount: number
|
||||
storageIssueCount: number
|
||||
neverRetrievedCount: number
|
||||
healthyCount: number
|
||||
permanentCount: number
|
||||
storageUsed: number
|
||||
usedCount: number
|
||||
}
|
||||
|
||||
export type AdminFileStatusFilter = 'all' | 'active' | 'expired'
|
||||
export type AdminFileTypeFilter = 'all' | 'file' | 'text' | 'chunked'
|
||||
export type AdminFileHealthFilter =
|
||||
| 'all'
|
||||
| 'attention'
|
||||
| 'danger'
|
||||
| 'warning'
|
||||
| 'healthy'
|
||||
| 'expired'
|
||||
| 'expiring_soon'
|
||||
| 'storage_issue'
|
||||
| 'never_retrieved'
|
||||
| 'permanent'
|
||||
export type AdminFileSortBy = 'created_at' | 'expired_at' | 'name' | 'size' | 'used_count' | 'code'
|
||||
export type AdminFileSortOrder = 'asc' | 'desc'
|
||||
|
||||
export interface AdminFileListParams {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
status?: AdminFileStatusFilter
|
||||
type?: AdminFileTypeFilter
|
||||
health?: AdminFileHealthFilter
|
||||
sortBy?: AdminFileSortBy
|
||||
sortOrder?: AdminFileSortOrder
|
||||
}
|
||||
|
||||
export interface AdminFileViewPresetParams {
|
||||
keyword: string
|
||||
status: AdminFileStatusFilter
|
||||
type: AdminFileTypeFilter
|
||||
health: AdminFileHealthFilter
|
||||
sortBy: AdminFileSortBy
|
||||
sortOrder: AdminFileSortOrder
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface AdminFileViewPreset {
|
||||
id: string
|
||||
name: string
|
||||
filters?: AdminFileViewPresetParams
|
||||
params?: AdminFileViewPresetParams
|
||||
isBuiltIn?: boolean
|
||||
isDefault?: boolean
|
||||
is_default?: boolean
|
||||
createdAt?: string | null
|
||||
created_at?: string | null
|
||||
updatedAt?: string | null
|
||||
updated_at?: string | null
|
||||
}
|
||||
|
||||
export interface AdminFileViewPresetRequest {
|
||||
id?: string
|
||||
name: string
|
||||
filters: AdminFileViewPresetParams
|
||||
params?: AdminFileViewPresetParams
|
||||
}
|
||||
|
||||
export interface AdminFileViewPresetsResponse {
|
||||
presets?: AdminFileViewPreset[]
|
||||
items?: AdminFileViewPreset[]
|
||||
total?: number
|
||||
}
|
||||
|
||||
export interface FileEditForm {
|
||||
id: number | null
|
||||
code: string
|
||||
prefix: string
|
||||
suffix: string
|
||||
expired_at: string
|
||||
expired_count: number | null
|
||||
}
|
||||
|
||||
export interface AdminFilePatchPayload {
|
||||
id: number
|
||||
code?: string
|
||||
prefix?: string
|
||||
suffix?: string
|
||||
expired_at?: string | null
|
||||
expired_count?: number | null
|
||||
}
|
||||
|
||||
export type AdminFilePolicyAction =
|
||||
| 'extend_24h'
|
||||
| 'extend_7d'
|
||||
| 'make_permanent'
|
||||
| 'reset_download_limit'
|
||||
|
||||
export interface AdminFilePolicyActionRequest {
|
||||
id: number
|
||||
action: AdminFilePolicyAction
|
||||
downloadLimit?: number
|
||||
download_limit?: number
|
||||
}
|
||||
|
||||
export interface AdminFileMetadata {
|
||||
note: string
|
||||
tags: string[]
|
||||
updatedAt?: string | null
|
||||
updated_at?: string | null
|
||||
}
|
||||
|
||||
export interface AdminFileMetadataRequest {
|
||||
id: number
|
||||
note?: string
|
||||
tags?: string[]
|
||||
}
|
||||
|
||||
export interface FileListResponse {
|
||||
data: FileListItem[]
|
||||
total: number
|
||||
page: number
|
||||
size: number
|
||||
summary?: AdminFileSummary
|
||||
}
|
||||
|
||||
export interface AdminFilePreviewResponse {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
type: 'text'
|
||||
content: string
|
||||
length: number
|
||||
previewLength?: number
|
||||
preview_length?: number
|
||||
truncated: boolean
|
||||
maxChars?: number
|
||||
max_chars?: number
|
||||
createdAt?: string | null
|
||||
created_at?: string | null
|
||||
expiredAt?: string | null
|
||||
expired_at?: string | null
|
||||
}
|
||||
|
||||
export interface AdminFileDetailPolicy {
|
||||
expiredAt?: string | null
|
||||
expired_at?: string | null
|
||||
expiredCount?: number | null
|
||||
expired_count?: number | null
|
||||
remainingDownloads?: number | null
|
||||
remaining_downloads?: number | null
|
||||
isExpired?: boolean
|
||||
is_expired?: boolean
|
||||
isPermanent?: boolean
|
||||
is_permanent?: boolean
|
||||
}
|
||||
|
||||
export interface AdminFileDetailStorage {
|
||||
backend?: string
|
||||
filePath?: string | null
|
||||
file_path?: string | null
|
||||
uuidFileName?: string | null
|
||||
uuid_file_name?: string | null
|
||||
fileHash?: string | null
|
||||
file_hash?: string | null
|
||||
isChunked?: boolean
|
||||
is_chunked?: boolean
|
||||
uploadId?: string | null
|
||||
upload_id?: string | null
|
||||
}
|
||||
|
||||
export type AdminFileInsightSeverity = 'success' | 'warning' | 'danger' | 'info' | 'neutral'
|
||||
|
||||
export interface AdminFileDetailInsightMetrics {
|
||||
ageSeconds?: number
|
||||
age_seconds?: number
|
||||
secondsUntilExpiration?: number | null
|
||||
seconds_until_expiration?: number | null
|
||||
remainingDownloads?: number | null
|
||||
remaining_downloads?: number | null
|
||||
usedCount?: number
|
||||
used_count?: number
|
||||
}
|
||||
|
||||
export interface AdminFileDetailStatusInsights {
|
||||
severity?: AdminFileInsightSeverity
|
||||
state?: string
|
||||
nextAction?: string
|
||||
next_action?: string
|
||||
reasons?: string[]
|
||||
metrics?: AdminFileDetailInsightMetrics
|
||||
}
|
||||
|
||||
export interface AdminFileDetailTimelineItem {
|
||||
key: string
|
||||
status?: string
|
||||
severity?: AdminFileInsightSeverity
|
||||
timestamp?: string | null
|
||||
value?: number | string | null
|
||||
detail?: string | null
|
||||
}
|
||||
|
||||
export interface AdminFileDetailTimelineViewItem extends AdminFileDetailTimelineItem {
|
||||
severity: AdminFileInsightSeverity
|
||||
displayTitle: string
|
||||
displayDescription: string
|
||||
displayMeta: string
|
||||
}
|
||||
|
||||
export interface AdminFileDetailResponse extends FileListItem {
|
||||
filename?: string
|
||||
displayName?: string
|
||||
display_name?: string
|
||||
isPermanent?: boolean
|
||||
is_permanent?: boolean
|
||||
hasDownloadLimit?: boolean
|
||||
has_download_limit?: boolean
|
||||
hasExpirationTime?: boolean
|
||||
has_expiration_time?: boolean
|
||||
textLength?: number
|
||||
text_length?: number
|
||||
canPreviewText?: boolean
|
||||
can_preview_text?: boolean
|
||||
canDownload?: boolean
|
||||
can_download?: boolean
|
||||
storageBackend?: string
|
||||
storage_backend?: string
|
||||
filePath?: string | null
|
||||
file_path?: string | null
|
||||
uuidFileName?: string | null
|
||||
uuid_file_name?: string | null
|
||||
uploadId?: string | null
|
||||
upload_id?: string | null
|
||||
policy?: AdminFileDetailPolicy
|
||||
storage?: AdminFileDetailStorage
|
||||
metadata?: AdminFileMetadata
|
||||
meta?: AdminFileMetadata
|
||||
note?: string
|
||||
tags?: string[]
|
||||
metadataUpdatedAt?: string | null
|
||||
metadata_updated_at?: string | null
|
||||
statusInsights?: AdminFileDetailStatusInsights
|
||||
status_insights?: AdminFileDetailStatusInsights
|
||||
timeline?: AdminFileDetailTimelineItem[]
|
||||
}
|
||||
|
||||
export interface AdminFileDetailViewItem extends AdminFileViewItem {
|
||||
displayCreatedAt: string
|
||||
displayRetrieveUrl: string
|
||||
textLengthValue: number
|
||||
canDownloadFile: boolean
|
||||
isPermanentFile: boolean
|
||||
hasDownloadLimitFile: boolean
|
||||
hasExpirationTimeFile: boolean
|
||||
isChunkedStorage: boolean
|
||||
storageBackendValue: string
|
||||
fileHashValue?: string | null
|
||||
filePathValue?: string | null
|
||||
uuidFileNameValue?: string | null
|
||||
uploadIdValue?: string | null
|
||||
metadataNote: string
|
||||
metadataTags: string[]
|
||||
metadataUpdatedAt: string | null
|
||||
statusInsightMetrics?: AdminFileDetailInsightMetrics
|
||||
detailTimeline: AdminFileDetailTimelineViewItem[]
|
||||
}
|
||||
|
||||
export interface AdminBatchDeleteFileFailure {
|
||||
id: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface AdminBatchDeleteFilesResponse {
|
||||
requestedCount?: number
|
||||
requested_count?: number
|
||||
uniqueCount?: number
|
||||
unique_count?: number
|
||||
deletedCount?: number
|
||||
deleted_count?: number
|
||||
missingCount?: number
|
||||
missing_count?: number
|
||||
failedCount?: number
|
||||
failed_count?: number
|
||||
deleted?: number[]
|
||||
missing?: number[]
|
||||
failed?: AdminBatchDeleteFileFailure[]
|
||||
}
|
||||
|
||||
export interface AdminBatchUpdateFileFailure {
|
||||
id: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface AdminBatchUpdateFilesRequest {
|
||||
ids: number[]
|
||||
expired_at?: string | null
|
||||
expired_count?: number | null
|
||||
clearExpiredAt?: boolean
|
||||
clear_expired_at?: boolean
|
||||
}
|
||||
|
||||
export interface AdminBatchUpdateFilesResponse {
|
||||
requestedCount?: number
|
||||
requested_count?: number
|
||||
uniqueCount?: number
|
||||
unique_count?: number
|
||||
updatedCount?: number
|
||||
updated_count?: number
|
||||
missingCount?: number
|
||||
missing_count?: number
|
||||
failedCount?: number
|
||||
failed_count?: number
|
||||
updated?: number[]
|
||||
missing?: number[]
|
||||
failed?: AdminBatchUpdateFileFailure[]
|
||||
}
|
||||
|
||||
export interface AdminBatchPolicyActionRequest {
|
||||
ids: number[]
|
||||
action: AdminFilePolicyAction
|
||||
downloadLimit?: number
|
||||
download_limit?: number
|
||||
}
|
||||
|
||||
export interface AdminBatchPolicyActionResponse extends AdminBatchUpdateFilesResponse {
|
||||
action?: AdminFilePolicyAction | string
|
||||
}
|
||||
|
||||
export type AdminBatchExpireUnit = 'hours' | 'days'
|
||||
|
||||
export type AdminBatchEditMode = 'expiresAt' | 'relativeExpire' | 'downloadLimit' | 'forever'
|
||||
|
||||
export interface AdminBatchEditForm {
|
||||
mode: AdminBatchEditMode
|
||||
expired_at: string
|
||||
expired_count: number | null
|
||||
relative_expire_value: number | null
|
||||
relative_expire_unit: AdminBatchExpireUnit
|
||||
}
|
||||
|
||||
export interface FileUploadResponse {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface TextSendResponse {
|
||||
code: string
|
||||
}
|
||||
|
||||
export interface ShareSelectResponse {
|
||||
code: string
|
||||
name: string
|
||||
text: string
|
||||
size: number
|
||||
type?: 'file' | 'text'
|
||||
is_text?: boolean
|
||||
content?: string | null
|
||||
download_url?: string | null
|
||||
created_at?: string | null
|
||||
expired_at?: string | null
|
||||
expires_at?: string | null
|
||||
expired_count?: number | null
|
||||
used_count?: number
|
||||
remaining_downloads?: number | null
|
||||
}
|
||||
|
||||
export interface ShareMetadataResponse {
|
||||
code: string
|
||||
name: string
|
||||
size: number
|
||||
type: 'file' | 'text'
|
||||
is_text: boolean
|
||||
created_at?: string | null
|
||||
expired_at?: string | null
|
||||
expires_at?: string | null
|
||||
expired_count?: number | null
|
||||
used_count?: number
|
||||
remaining_downloads?: number | null
|
||||
}
|
||||
|
||||
export interface ReceivedFileRecord {
|
||||
id: number
|
||||
code: string
|
||||
filename: string
|
||||
size: string
|
||||
downloadUrl: string | null
|
||||
content: string | null
|
||||
date: string
|
||||
type?: 'file' | 'text'
|
||||
remainingDownloads?: number | null
|
||||
}
|
||||
|
||||
export interface SentFileRecord {
|
||||
id: number
|
||||
filename: string
|
||||
date: string
|
||||
size: string
|
||||
expiration: string
|
||||
retrieveCode: string
|
||||
}
|
||||
|
||||
export interface UploadProgress {
|
||||
loaded: number
|
||||
total: number
|
||||
percentage: number
|
||||
}
|
||||
|
||||
export interface ChunkUploadInitRequest {
|
||||
file_name: string
|
||||
file_size: number
|
||||
chunk_size: number
|
||||
file_hash: string
|
||||
}
|
||||
|
||||
export interface ChunkUploadInitResponse {
|
||||
code?: string
|
||||
name?: string
|
||||
upload_id?: string
|
||||
existed?: boolean
|
||||
uploaded_chunks?: number[]
|
||||
}
|
||||
|
||||
export interface ChunkUploadCompleteRequest {
|
||||
expire_value: number
|
||||
expire_style: string
|
||||
}
|
||||
|
||||
export type ChunkUploadResponse = null
|
||||
@@ -0,0 +1,9 @@
|
||||
export * from './activity'
|
||||
export * from './api'
|
||||
export * from './auth'
|
||||
export * from './config'
|
||||
export * from './dashboard'
|
||||
export * from './file'
|
||||
export * from './presign-upload'
|
||||
export * from './trash'
|
||||
export * from './ui'
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { UploadProgress } from './file'
|
||||
|
||||
export type PresignUploadMode = 'direct' | 'proxy'
|
||||
|
||||
export type PresignUploadStatus =
|
||||
| 'idle'
|
||||
| 'initializing'
|
||||
| 'uploading'
|
||||
| 'confirming'
|
||||
| 'success'
|
||||
| 'error'
|
||||
|
||||
export type ExpireStyle = 'day' | 'hour' | 'minute' | 'forever' | 'count'
|
||||
|
||||
export interface PresignInitRequest {
|
||||
file_name: string
|
||||
file_size: number
|
||||
expire_value?: number
|
||||
expire_style?: ExpireStyle
|
||||
}
|
||||
|
||||
export interface PresignInitResponse {
|
||||
upload_id: string
|
||||
upload_url: string
|
||||
proxy_upload_url?: string
|
||||
legacy_proxy_upload_url?: string
|
||||
mode: PresignUploadMode
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export interface PresignConfirmRequest {
|
||||
expire_value?: number
|
||||
expire_style?: ExpireStyle
|
||||
}
|
||||
|
||||
export interface PresignUploadResult {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface PresignStatusResponse {
|
||||
upload_id: string
|
||||
file_name: string
|
||||
file_size: number
|
||||
mode: PresignUploadMode
|
||||
created_at: string
|
||||
expires_at: string
|
||||
is_expired: boolean
|
||||
}
|
||||
|
||||
export interface PresignUploadOptions {
|
||||
expireValue?: number
|
||||
expireStyle?: ExpireStyle
|
||||
onProgress?: (progress: UploadProgress) => void
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface TrashFileItem {
|
||||
id: number
|
||||
code: string
|
||||
name?: string
|
||||
prefix?: string
|
||||
suffix?: string
|
||||
size: number
|
||||
text?: string | null
|
||||
trashedAt?: string | null
|
||||
trashExpiresAt?: string | null
|
||||
trashReason?: string | null
|
||||
trashPurgedAt?: string | null
|
||||
isTrashPermanent?: boolean
|
||||
isTrashPurged?: boolean
|
||||
}
|
||||
|
||||
export interface TrashListResponse {
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
data: TrashFileItem[]
|
||||
}
|
||||
|
||||
export interface TrashListParams {
|
||||
page: number
|
||||
size: number
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||
|
||||
export type SendType = 'file' | 'text'
|
||||
|
||||
export type AlertType = 'success' | 'error' | 'warning' | 'info'
|
||||
|
||||
export interface Alert {
|
||||
id: number
|
||||
message: string
|
||||
type: AlertType
|
||||
progress: number
|
||||
duration: number
|
||||
startTime: number
|
||||
}
|
||||
|
||||
export type UploadStatus = 'idle' | 'uploading' | 'success' | 'error'
|
||||
|
||||
export interface RouteConfig {
|
||||
path: string
|
||||
name: string
|
||||
component: () => Promise<{ default: object }>
|
||||
meta?: {
|
||||
requiresAuth?: boolean
|
||||
title?: string
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { apiBaseURL, rawApiClient } from '@/services/client'
|
||||
export { default } from '@/services/client'
|
||||
@@ -0,0 +1,26 @@
|
||||
import { STORAGE_KEYS } from '@/constants'
|
||||
|
||||
export function readStoredAdminPassword(): string {
|
||||
return localStorage.getItem(STORAGE_KEYS.ADMIN_PASSWORD) || ''
|
||||
}
|
||||
|
||||
export function writeStoredAdminPassword(password: string) {
|
||||
localStorage.setItem(STORAGE_KEYS.ADMIN_PASSWORD, password)
|
||||
}
|
||||
|
||||
export function readStoredToken(): string {
|
||||
return localStorage.getItem(STORAGE_KEYS.TOKEN) || ''
|
||||
}
|
||||
|
||||
export function writeStoredToken(token: string) {
|
||||
localStorage.setItem(STORAGE_KEYS.TOKEN, token)
|
||||
}
|
||||
|
||||
export function clearStoredAuth() {
|
||||
localStorage.removeItem(STORAGE_KEYS.ADMIN_PASSWORD)
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN)
|
||||
}
|
||||
|
||||
export function clearStoredToken() {
|
||||
localStorage.removeItem(STORAGE_KEYS.TOKEN)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 剪贴板工具函数
|
||||
*/
|
||||
|
||||
import { buildRetrieveUrl, buildWgetCommand } from '@/utils/share-url'
|
||||
|
||||
type CopyNotifyType = 'success' | 'error'
|
||||
|
||||
interface CopyOptions {
|
||||
successMsg?: string
|
||||
errorMsg?: string
|
||||
showMsg?: boolean
|
||||
notify?: (message: string, type: CopyNotifyType) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制文本到剪贴板
|
||||
* @param text 要复制的文本
|
||||
* @param options 配置选项
|
||||
* @returns Promise<boolean> 是否复制成功
|
||||
*/
|
||||
export const copyToClipboard = async (
|
||||
text: string,
|
||||
options: CopyOptions = {}
|
||||
): Promise<boolean> => {
|
||||
const {
|
||||
successMsg = '复制成功',
|
||||
errorMsg = '复制失败,请手动复制',
|
||||
showMsg = true,
|
||||
notify
|
||||
} = options
|
||||
|
||||
const showCopyMessage = (message: string, type: CopyNotifyType) => {
|
||||
if (showMsg) {
|
||||
notify?.(message, type)
|
||||
}
|
||||
}
|
||||
|
||||
const showManualCopyDialog = () => {
|
||||
window.prompt('复制下面内容', text)
|
||||
}
|
||||
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
showCopyMessage(successMsg, 'success')
|
||||
return true
|
||||
} catch {
|
||||
// Continue to the DOM fallback.
|
||||
}
|
||||
}
|
||||
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = text
|
||||
textarea.setAttribute('readonly', '')
|
||||
textarea.style.cssText =
|
||||
'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1;'
|
||||
document.body.appendChild(textarea)
|
||||
textarea.focus()
|
||||
textarea.select()
|
||||
textarea.setSelectionRange(0, textarea.value.length)
|
||||
let success = false
|
||||
try {
|
||||
success = document.execCommand('copy')
|
||||
} finally {
|
||||
document.body.removeChild(textarea)
|
||||
}
|
||||
if (success) {
|
||||
showCopyMessage(successMsg, 'success')
|
||||
return true
|
||||
}
|
||||
|
||||
showManualCopyDialog()
|
||||
showCopyMessage('已打开手动复制窗口', 'error')
|
||||
return false
|
||||
} catch (err) {
|
||||
console.error('复制失败:', err)
|
||||
showManualCopyDialog()
|
||||
showCopyMessage(errorMsg, 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成并复制取件链接
|
||||
* @param code 取件码
|
||||
* @returns Promise<boolean> 是否复制成功
|
||||
*/
|
||||
export const copyRetrieveLink = async (
|
||||
code: string,
|
||||
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
|
||||
): Promise<boolean> => {
|
||||
const link = buildRetrieveUrl(code)
|
||||
return copyToClipboard(link, {
|
||||
successMsg: '取件链接已复制到剪贴板',
|
||||
errorMsg: '复制失败,请手动复制取件链接',
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制取件码
|
||||
* @param code 取件码
|
||||
* @returns Promise<boolean> 是否复制成功
|
||||
*/
|
||||
export const copyRetrieveCode = async (
|
||||
code: string,
|
||||
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
|
||||
): Promise<boolean> => {
|
||||
return copyToClipboard(code, {
|
||||
successMsg: '取件码已复制到剪贴板',
|
||||
errorMsg: '复制失败,请手动复制取件码',
|
||||
...options
|
||||
})
|
||||
}
|
||||
|
||||
export const copyWgetCommand = (
|
||||
retrieveCode: string,
|
||||
fileName: string,
|
||||
options: Pick<CopyOptions, 'notify' | 'showMsg'> = {}
|
||||
) => {
|
||||
const command = buildWgetCommand(retrieveCode, fileName)
|
||||
void copyToClipboard(command, {
|
||||
successMsg: '命令已复制到剪贴板',
|
||||
errorMsg: '复制失败,请手动复制命令',
|
||||
...options
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
export const getClipboardFile = (items: DataTransferItemList): File | null => {
|
||||
for (let index = 0; index < items.length; index++) {
|
||||
const item = items[index]
|
||||
if (item.kind !== 'file') {
|
||||
continue
|
||||
}
|
||||
|
||||
const file = item.getAsFile()
|
||||
if (file) {
|
||||
return file
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export type TextInsertionInput = {
|
||||
text: string
|
||||
insertText: string
|
||||
selectionStart: number
|
||||
selectionEnd: number
|
||||
}
|
||||
|
||||
export type TextInsertionResult = {
|
||||
value: string
|
||||
cursor: number
|
||||
}
|
||||
|
||||
export const insertTextAtSelection = ({
|
||||
text,
|
||||
insertText,
|
||||
selectionStart,
|
||||
selectionEnd
|
||||
}: TextInsertionInput): TextInsertionResult => {
|
||||
const beforeSelection = text.substring(0, selectionStart)
|
||||
const afterSelection = text.substring(selectionEnd)
|
||||
return {
|
||||
value: beforeSelection + insertText + afterSelection,
|
||||
cursor: selectionStart + insertText.length
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* 通用工具函数
|
||||
*/
|
||||
import type { ApiErrorPayload } from '@/types'
|
||||
|
||||
/**
|
||||
* 格式化时间戳为可读格式
|
||||
* @param timestamp 时间戳字符串
|
||||
* @param format 格式类型
|
||||
* @returns 格式化后的时间字符串
|
||||
*/
|
||||
export function formatTimestamp(timestamp: string, format: 'datetime' | 'date' | 'time' = 'datetime'): string {
|
||||
const date = new Date(timestamp)
|
||||
const year = date.getFullYear()
|
||||
const month = (date.getMonth() + 1).toString().padStart(2, '0')
|
||||
const day = date.getDate().toString().padStart(2, '0')
|
||||
const hours = date.getHours().toString().padStart(2, '0')
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0')
|
||||
const seconds = date.getSeconds().toString().padStart(2, '0')
|
||||
|
||||
switch (format) {
|
||||
case 'date':
|
||||
return `${year}-${month}-${day}`
|
||||
case 'time':
|
||||
return `${hours}:${minutes}:${seconds}`
|
||||
case 'datetime':
|
||||
default:
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化文件大小
|
||||
* @param bytes 字节数
|
||||
* @param decimals 小数位数
|
||||
* @returns 格式化后的文件大小字符串
|
||||
*/
|
||||
export function formatFileSize(bytes: number, decimals: number = 2): string {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
|
||||
const k = 1024
|
||||
const dm = decimals < 0 ? 0 : decimals
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化持续时间
|
||||
* @param seconds 秒数
|
||||
* @param t 翻译函数
|
||||
* @returns 格式化后的持续时间字符串
|
||||
*/
|
||||
export function formatDuration(seconds: number, t?: (key: string) => string): string {
|
||||
if (seconds === 0) return t ? t('utils.time.forever') : 'Forever'
|
||||
|
||||
const units = [
|
||||
{ key: 'utils.time.day', value: 86400 },
|
||||
{ key: 'utils.time.hour', value: 3600 },
|
||||
{ key: 'utils.time.minute', value: 60 },
|
||||
{ key: 'utils.time.second', value: 1 }
|
||||
]
|
||||
|
||||
for (const unit of units) {
|
||||
if (seconds >= unit.value) {
|
||||
const value = Math.floor(seconds / unit.value)
|
||||
const unitName = t ? t(unit.key) : unit.key.split('.').pop()
|
||||
return `${value}${unitName}`
|
||||
}
|
||||
}
|
||||
|
||||
const secondName = t ? t('utils.time.second') : 'second'
|
||||
return `${seconds}${secondName}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 防抖函数
|
||||
* @param func 要防抖的函数
|
||||
* @param wait 等待时间(毫秒)
|
||||
* @returns 防抖后的函数
|
||||
*/
|
||||
export function debounce<T extends (...args: unknown[]) => unknown>(
|
||||
func: T,
|
||||
wait: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
timeout = setTimeout(() => func(...args), wait)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 节流函数
|
||||
* @param func 要节流的函数
|
||||
* @param limit 限制时间(毫秒)
|
||||
* @returns 节流后的函数
|
||||
*/
|
||||
export function throttle<T extends (...args: unknown[]) => unknown>(
|
||||
func: T,
|
||||
limit: number
|
||||
): (...args: Parameters<T>) => void {
|
||||
let inThrottle: boolean = false
|
||||
|
||||
return (...args: Parameters<T>) => {
|
||||
if (!inThrottle) {
|
||||
func(...args)
|
||||
inThrottle = true
|
||||
setTimeout(() => inThrottle = false, limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证邮箱格式
|
||||
* @param email 邮箱地址
|
||||
* @returns 是否为有效邮箱
|
||||
*/
|
||||
export function isValidEmail(email: string): boolean {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
return emailRegex.test(email)
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证URL格式
|
||||
* @param url URL地址
|
||||
* @returns 是否为有效URL
|
||||
*/
|
||||
export function isValidUrl(url: string): boolean {
|
||||
try {
|
||||
new URL(url)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机字符串
|
||||
* @param length 字符串长度
|
||||
* @param chars 可选字符集
|
||||
* @returns 随机字符串
|
||||
*/
|
||||
export function generateRandomString(
|
||||
length: number = 8,
|
||||
chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
||||
): string {
|
||||
let result = ''
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += chars.charAt(Math.floor(Math.random() * chars.length))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度克隆对象
|
||||
* @param obj 要克隆的对象
|
||||
* @returns 克隆后的对象
|
||||
*/
|
||||
export function deepClone<T>(obj: T): T {
|
||||
if (obj === null || typeof obj !== 'object') {
|
||||
return obj
|
||||
}
|
||||
|
||||
if (obj instanceof Date) {
|
||||
return new Date(obj.getTime()) as T
|
||||
}
|
||||
|
||||
if (obj instanceof Array) {
|
||||
return obj.map(item => deepClone(item)) as T
|
||||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
const clonedObj = {} as T
|
||||
for (const key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
clonedObj[key] = deepClone(obj[key])
|
||||
}
|
||||
}
|
||||
return clonedObj
|
||||
}
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件扩展名
|
||||
* @param filename 文件名
|
||||
* @returns 文件扩展名(不包含点)
|
||||
*/
|
||||
export function getFileExtension(filename: string): string {
|
||||
return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为移动设备
|
||||
* @returns 是否为移动设备
|
||||
*/
|
||||
export function isMobile(): boolean {
|
||||
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化数字,添加千分位分隔符
|
||||
* @param num 数字
|
||||
* @returns 格式化后的数字字符串
|
||||
*/
|
||||
export function formatNumber(num: number): string {
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||||
}
|
||||
|
||||
type ErrorWithResponse = {
|
||||
response?: {
|
||||
data?: ApiErrorPayload
|
||||
}
|
||||
message?: string
|
||||
}
|
||||
|
||||
export function getErrorMessage(error: unknown, fallback: string): string {
|
||||
if (!error || typeof error !== 'object') {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const errorWithResponse = error as ErrorWithResponse
|
||||
return (
|
||||
errorWithResponse.response?.data?.detail ||
|
||||
errorWithResponse.response?.data?.message ||
|
||||
errorWithResponse.message ||
|
||||
fallback
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { ConfigState } from '@/types'
|
||||
|
||||
export type FileSizeUnit = 'KB' | 'MB' | 'GB'
|
||||
export type SaveTimeUnit = '秒' | '分' | '时' | '天'
|
||||
|
||||
export type FileSizeForm = {
|
||||
value: number
|
||||
unit: FileSizeUnit
|
||||
}
|
||||
|
||||
export type SaveTimeForm = {
|
||||
value: number
|
||||
unit: SaveTimeUnit
|
||||
}
|
||||
|
||||
const FILE_SIZE_UNITS: Record<FileSizeUnit, number> = {
|
||||
KB: 1024,
|
||||
MB: 1024 * 1024,
|
||||
GB: 1024 * 1024 * 1024
|
||||
}
|
||||
|
||||
const SAVE_TIME_UNITS: Record<SaveTimeUnit, number> = {
|
||||
秒: 1,
|
||||
分: 60,
|
||||
时: 3600,
|
||||
天: 86400
|
||||
}
|
||||
|
||||
export function bytesToFileSizeForm(bytes: number): FileSizeForm {
|
||||
if (bytes >= FILE_SIZE_UNITS.GB) {
|
||||
return {
|
||||
value: Math.round(bytes / FILE_SIZE_UNITS.GB),
|
||||
unit: 'GB'
|
||||
}
|
||||
}
|
||||
|
||||
if (bytes >= FILE_SIZE_UNITS.MB) {
|
||||
return {
|
||||
value: Math.round(bytes / FILE_SIZE_UNITS.MB),
|
||||
unit: 'MB'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
value: Math.round(bytes / FILE_SIZE_UNITS.KB),
|
||||
unit: 'KB'
|
||||
}
|
||||
}
|
||||
|
||||
export function fileSizeFormToBytes(value: number, unit: FileSizeUnit): number {
|
||||
return value * FILE_SIZE_UNITS[unit]
|
||||
}
|
||||
|
||||
export function secondsToSaveTimeForm(seconds: number): SaveTimeForm {
|
||||
if (seconds === 0) {
|
||||
return {
|
||||
value: 7,
|
||||
unit: '天'
|
||||
}
|
||||
}
|
||||
|
||||
if (seconds % SAVE_TIME_UNITS.天 === 0 && seconds >= SAVE_TIME_UNITS.天) {
|
||||
return {
|
||||
value: seconds / SAVE_TIME_UNITS.天,
|
||||
unit: '天'
|
||||
}
|
||||
}
|
||||
|
||||
if (seconds % SAVE_TIME_UNITS.时 === 0 && seconds >= SAVE_TIME_UNITS.时) {
|
||||
return {
|
||||
value: seconds / SAVE_TIME_UNITS.时,
|
||||
unit: '时'
|
||||
}
|
||||
}
|
||||
|
||||
if (seconds % SAVE_TIME_UNITS.分 === 0 && seconds >= SAVE_TIME_UNITS.分) {
|
||||
return {
|
||||
value: seconds / SAVE_TIME_UNITS.分,
|
||||
unit: '分'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
value: seconds,
|
||||
unit: '秒'
|
||||
}
|
||||
}
|
||||
|
||||
export function saveTimeFormToSeconds(value: number, unit: SaveTimeUnit): number {
|
||||
if (value === 0) {
|
||||
return 7 * SAVE_TIME_UNITS.天
|
||||
}
|
||||
|
||||
return value * SAVE_TIME_UNITS[unit]
|
||||
}
|
||||
|
||||
export function buildConfigSubmitPayload(
|
||||
config: ConfigState,
|
||||
fileSize: FileSizeForm,
|
||||
saveTime: SaveTimeForm
|
||||
): ConfigState {
|
||||
return {
|
||||
...config,
|
||||
uploadSize: fileSizeFormToBytes(fileSize.value, fileSize.unit),
|
||||
max_save_seconds: saveTimeFormToSeconds(saveTime.value, saveTime.unit)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { DEFAULT_CONFIG, FILE_SIZE_LIMITS, STORAGE_KEYS } from '@/constants'
|
||||
import type { ConfigState, SystemConfig } from '@/types'
|
||||
|
||||
export type PublicConfig = SystemConfig & {
|
||||
uploadSize: number
|
||||
expireStyle: string[]
|
||||
openUpload: number
|
||||
max_save_seconds: number
|
||||
enableChunk: number
|
||||
notify_title?: string
|
||||
notify_content?: string
|
||||
page_explain?: string
|
||||
showAdminAddr?: number
|
||||
themesSelect?: string
|
||||
background?: string
|
||||
opacity?: number
|
||||
}
|
||||
|
||||
export const DEFAULT_PUBLIC_CONFIG: PublicConfig = {
|
||||
...DEFAULT_CONFIG,
|
||||
uploadSize: FILE_SIZE_LIMITS.MAX_FILE_SIZE,
|
||||
expireStyle: ['day'],
|
||||
openUpload: 1,
|
||||
max_save_seconds: 0,
|
||||
enableChunk: 0
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG_STATE: ConfigState = {
|
||||
name: DEFAULT_PUBLIC_CONFIG.name,
|
||||
description: DEFAULT_PUBLIC_CONFIG.description || '',
|
||||
file_storage: '',
|
||||
themesChoices: [],
|
||||
expireStyle: DEFAULT_PUBLIC_CONFIG.expireStyle,
|
||||
admin_token: '',
|
||||
robotsText: '',
|
||||
keywords: '',
|
||||
notify_title: '',
|
||||
notify_content: '',
|
||||
openUpload: DEFAULT_PUBLIC_CONFIG.openUpload,
|
||||
uploadSize: DEFAULT_PUBLIC_CONFIG.uploadSize,
|
||||
storage_path: '',
|
||||
uploadMinute: 1,
|
||||
max_save_seconds: DEFAULT_PUBLIC_CONFIG.max_save_seconds,
|
||||
trashRetentionDays: 30,
|
||||
opacity: 0.9,
|
||||
enableChunk: DEFAULT_PUBLIC_CONFIG.enableChunk,
|
||||
s3_access_key_id: '',
|
||||
background: '',
|
||||
showAdminAddr: 0,
|
||||
page_explain: '',
|
||||
s3_secret_access_key: '',
|
||||
aws_session_token: '',
|
||||
s3_signature_version: '',
|
||||
s3_region_name: '',
|
||||
s3_bucket_name: '',
|
||||
s3_endpoint_url: '',
|
||||
s3_hostname: '',
|
||||
uploadCount: 1,
|
||||
errorMinute: 1,
|
||||
errorCount: 1,
|
||||
s3_proxy: 0,
|
||||
themesSelect: '',
|
||||
webdav_url: '',
|
||||
webdav_username: '',
|
||||
webdav_password: ''
|
||||
}
|
||||
|
||||
export function readStoredConfig<T extends object = Partial<ConfigState>>(): T | null {
|
||||
try {
|
||||
const rawConfig = localStorage.getItem(STORAGE_KEYS.CONFIG)
|
||||
return rawConfig ? (JSON.parse(rawConfig) as T) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function toPublicConfig(config: Partial<ConfigState> | null | undefined): Partial<PublicConfig> {
|
||||
if (!config) return {}
|
||||
|
||||
return {
|
||||
name: config.name,
|
||||
description: config.description,
|
||||
uploadSize: config.uploadSize,
|
||||
expireStyle: config.expireStyle,
|
||||
openUpload: config.openUpload,
|
||||
max_save_seconds: config.max_save_seconds,
|
||||
enableChunk: config.enableChunk,
|
||||
notify_title: config.notify_title,
|
||||
notify_content: config.notify_content,
|
||||
page_explain: config.page_explain,
|
||||
showAdminAddr: config.showAdminAddr,
|
||||
themesSelect: config.themesSelect,
|
||||
background: config.background,
|
||||
opacity: config.opacity
|
||||
}
|
||||
}
|
||||
|
||||
export function writeStoredConfig(config: object) {
|
||||
localStorage.setItem(STORAGE_KEYS.CONFIG, JSON.stringify(toPublicConfig(config as Partial<ConfigState>)))
|
||||
}
|
||||
|
||||
export function readNotifyKey(): string | null {
|
||||
return localStorage.getItem(STORAGE_KEYS.NOTIFY)
|
||||
}
|
||||
|
||||
export function writeNotifyKey(notifyKey: string) {
|
||||
localStorage.setItem(STORAGE_KEYS.NOTIFY, notifyKey)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
const MARKDOWN_ALLOWED_TAGS = [
|
||||
'p',
|
||||
'br',
|
||||
'strong',
|
||||
'em',
|
||||
'u',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'ul',
|
||||
'ol',
|
||||
'li',
|
||||
'blockquote',
|
||||
'code',
|
||||
'pre',
|
||||
'a',
|
||||
'img'
|
||||
]
|
||||
|
||||
const MARKDOWN_ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'class']
|
||||
|
||||
export async function renderMarkdownPreview(content: string): Promise<string> {
|
||||
try {
|
||||
const [{ marked }, { default: DOMPurify }] = await Promise.all([
|
||||
import('marked'),
|
||||
import('dompurify')
|
||||
])
|
||||
const rawHtml = await marked(content)
|
||||
return DOMPurify.sanitize(rawHtml, {
|
||||
ALLOWED_TAGS: MARKDOWN_ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: MARKDOWN_ALLOWED_ATTR,
|
||||
ALLOWED_URI_REGEXP:
|
||||
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Markdown 渲染失败:', error)
|
||||
return content
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// 存储单位转换
|
||||
export const getStorageUnit = (value: number) => {
|
||||
if (value >= 1024 * 1024 * 1024) {
|
||||
return Math.round(value / (1024 * 1024 * 1024)) + 'GB'
|
||||
} else if (value >= 1024 * 1024) {
|
||||
return Math.round(value / (1024 * 1024)) + 'MB'
|
||||
} else {
|
||||
return Math.round(value / 1024) + 'KB'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { saveAs } from 'file-saver'
|
||||
import type { AdminFileViewItem, ApiResponse, ReceivedFileRecord } from '@/types'
|
||||
import { buildDownloadUrl } from '@/utils/share-url'
|
||||
|
||||
const unsafeFilenamePattern = new RegExp(
|
||||
`[\\\\/:*?"<>|${String.fromCharCode(0)}-${String.fromCharCode(31)}]`,
|
||||
'g'
|
||||
)
|
||||
|
||||
export function downloadReceivedRecord(record: ReceivedFileRecord): void {
|
||||
if (record.downloadUrl) {
|
||||
window.open(buildDownloadUrl(record.downloadUrl), '_blank')
|
||||
return
|
||||
}
|
||||
|
||||
if (record.content) {
|
||||
const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' })
|
||||
saveAs(blob, `${record.filename}.txt`)
|
||||
}
|
||||
}
|
||||
|
||||
export const getSafeFilename = (name: string) =>
|
||||
name
|
||||
.replace(unsafeFilenamePattern, '_')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 180) || 'download'
|
||||
|
||||
const getFilenameFromDisposition = (disposition?: string) => {
|
||||
if (!disposition) return ''
|
||||
|
||||
const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i)
|
||||
if (utf8Match?.[1]) {
|
||||
try {
|
||||
return decodeURIComponent(utf8Match[1])
|
||||
} catch {
|
||||
return utf8Match[1]
|
||||
}
|
||||
}
|
||||
|
||||
const asciiMatch = disposition.match(/filename="?([^"]+)"?/i)
|
||||
return asciiMatch?.[1] || ''
|
||||
}
|
||||
|
||||
const readBlobAsText = (blob: Blob): Promise<string> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result || ''))
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsText(blob)
|
||||
})
|
||||
|
||||
export function exportAdminTextFile(file: AdminFileViewItem, content: string): void {
|
||||
const filename = getSafeFilename(file.displayName || file.code)
|
||||
const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
|
||||
saveAs(blob, `${filename}.txt`)
|
||||
}
|
||||
|
||||
export async function downloadAdminManagedFile(
|
||||
file: AdminFileViewItem,
|
||||
response: { data: Blob; headers: Record<string, string> }
|
||||
): Promise<void> {
|
||||
if (file.isTextFile) {
|
||||
const text = await readBlobAsText(response.data)
|
||||
let content = text
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(text) as ApiResponse<string>
|
||||
content = typeof payload.detail === 'string' ? payload.detail : text
|
||||
} catch {
|
||||
content = text
|
||||
}
|
||||
|
||||
exportAdminTextFile(file, content)
|
||||
return
|
||||
}
|
||||
|
||||
const disposition =
|
||||
response.headers['content-disposition'] || response.headers['Content-Disposition']
|
||||
const filename = getSafeFilename(
|
||||
getFilenameFromDisposition(disposition) || file.displayName || file.code
|
||||
)
|
||||
saveAs(response.data, filename)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
const SMALL_FILE_HASH_LIMIT = 10 * 1024 * 1024
|
||||
const LARGE_FILE_HASH_CHUNK_SIZE = 5 * 1024 * 1024
|
||||
|
||||
const generateFallbackHash = (file: File): string => {
|
||||
const fileInfo = `${file.name}-${file.size}-${file.lastModified}`
|
||||
let hash = 0
|
||||
for (let i = 0; i < fileInfo.length; i++) {
|
||||
const char = fileInfo.charCodeAt(i)
|
||||
hash = (hash << 5) - hash + char
|
||||
hash = hash & hash
|
||||
}
|
||||
return Math.abs(hash).toString(16).padStart(64, '0')
|
||||
}
|
||||
|
||||
const createSha256Hash = async (data: BufferSource): Promise<string> => {
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data)
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer))
|
||||
return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
export const calculateFileHash = async (file: File): Promise<string> => {
|
||||
try {
|
||||
if (file.size <= SMALL_FILE_HASH_LIMIT) {
|
||||
const buffer = await file.arrayBuffer()
|
||||
return window.isSecureContext ? createSha256Hash(buffer) : generateFallbackHash(file)
|
||||
}
|
||||
|
||||
const firstChunk = file.slice(0, LARGE_FILE_HASH_CHUNK_SIZE)
|
||||
const lastChunk = file.slice(-LARGE_FILE_HASH_CHUNK_SIZE)
|
||||
const [firstBuffer, lastBuffer] = await Promise.all([
|
||||
firstChunk.arrayBuffer(),
|
||||
lastChunk.arrayBuffer()
|
||||
])
|
||||
const combined = new Uint8Array(firstBuffer.byteLength + lastBuffer.byteLength + 16)
|
||||
combined.set(new Uint8Array(firstBuffer), 0)
|
||||
combined.set(new Uint8Array(lastBuffer), firstBuffer.byteLength)
|
||||
const sizeBytes = new TextEncoder().encode(file.size.toString())
|
||||
combined.set(sizeBytes, firstBuffer.byteLength + lastBuffer.byteLength)
|
||||
|
||||
return window.isSecureContext ? createSha256Hash(combined) : generateFallbackHash(file)
|
||||
} catch (error) {
|
||||
console.error('File hash calculation failed:', error)
|
||||
return generateFallbackHash(file)
|
||||
}
|
||||
}
|
||||
|
||||
export const packFilesAsZip = async (files: File[]): Promise<File> => {
|
||||
const { default: JSZip } = await import('jszip')
|
||||
const zip = new JSZip()
|
||||
for (const file of files) {
|
||||
zip.file(file.name, file)
|
||||
}
|
||||
const blob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
})
|
||||
return new File([blob], `files_${Date.now()}.zip`, { type: 'application/zip' })
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { STORAGE_KEYS } from '@/constants'
|
||||
import type { ThemeMode } from '@/types'
|
||||
|
||||
const LOCALE_STORAGE_KEY = 'locale'
|
||||
|
||||
export function readStoredThemeMode(): string | null {
|
||||
return localStorage.getItem(STORAGE_KEYS.COLOR_MODE)
|
||||
}
|
||||
|
||||
export function writeStoredThemeMode(mode: ThemeMode) {
|
||||
localStorage.setItem(STORAGE_KEYS.COLOR_MODE, mode)
|
||||
}
|
||||
|
||||
export function readStoredLocale(): string | null {
|
||||
return localStorage.getItem(LOCALE_STORAGE_KEY)
|
||||
}
|
||||
|
||||
export function writeStoredLocale(locale: string) {
|
||||
localStorage.setItem(LOCALE_STORAGE_KEY, locale)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export function readStoredRecords<T>(key: string): T[] {
|
||||
if (typeof window === 'undefined') return []
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(key)
|
||||
if (!raw) return []
|
||||
|
||||
const parsed = JSON.parse(raw)
|
||||
return Array.isArray(parsed) ? (parsed as T[]) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function writeStoredRecords<T>(key: string, records: T[]) {
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(records))
|
||||
} catch {
|
||||
// 本地存储不可用时保持内存记录,不影响当前会话。
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
const CODE_PATTERN = /^[A-Za-z0-9]+$/
|
||||
|
||||
export const isValidRetrievalCode = (value: string): boolean => {
|
||||
const code = value.trim()
|
||||
return (code.length === 5 || code.length === 8) && CODE_PATTERN.test(code)
|
||||
}
|
||||
|
||||
export const parseRetrievalCode = (value: string): string => {
|
||||
const raw = value.trim()
|
||||
if (isValidRetrievalCode(raw)) return raw
|
||||
try {
|
||||
const url = new URL(raw)
|
||||
const queryCode = url.searchParams.get('code') || ''
|
||||
if (queryCode) return isValidRetrievalCode(queryCode) ? queryCode : ''
|
||||
if (url.hash) {
|
||||
const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash
|
||||
const query = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : hash
|
||||
const hashCode = new URLSearchParams(query).get('code') || ''
|
||||
return isValidRetrievalCode(hashCode) ? hashCode : ''
|
||||
}
|
||||
return ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user