This commit is contained in:
Lan
2024-10-07 15:20:31 +08:00
parent f069eb660a
commit 7c5933bc22
5 changed files with 226 additions and 238 deletions
+6 -22
View File
@@ -2,27 +2,15 @@
import { ref, watchEffect, provide, onMounted } from 'vue'
import { RouterView } from 'vue-router'
import ThemeToggle from './components/ThemeToggle.vue'
import AlertComponent from './components/AlertComponent.vue'
import { useRouter } from 'vue-router'
import api from './utils/api'
const isDarkMode = ref(false)
const isLoading = ref(false)
const router = useRouter()
import AlertComponent from '@/components/AlertComponent.vue'
import { useAlertStore } from '@/stores/alertStore'
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('success')
const closeAlert = () => {
showAlert.value = false
}
const showAlertMessage = (
message: string,
type: 'success' | 'error' | 'warning' | 'info' = 'success'
) => {
alertMessage.value = message
alertType.value = type
showAlert.value = true
}
const alertStore = useAlertStore()
// 检查系统颜色模式
const checkSystemColorScheme = () => {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
@@ -59,7 +47,7 @@ onMounted(() => {
localStorage.getItem('notify') !== res.detail.notify_title + res.detail.notify_content
) {
localStorage.setItem('notify', res.detail.notify_title + res.detail.notify_content)
showAlertMessage(res.detail.notify_title + ': ' + res.detail.notify_content, 'success')
alertStore.showAlert(res.detail.notify_title + ': ' + res.detail.notify_content, 'success')
}
}
})
@@ -96,12 +84,8 @@ provide('isLoading', isLoading)
<component :is="Component" :key="$route.fullPath" />
</transition>
</RouterView>
<AlertComponent
:show="showAlert"
:message="alertMessage"
:type="alertType"
@close="closeAlert"
/>
<AlertComponent />
</div>
</template>
+62 -105
View File
@@ -1,137 +1,94 @@
<template>
<transition name="alert-fade">
<div v-if="show" class="fixed top-4 right-4 max-w-sm w-full z-50">
<div
:class="[
'rounded-lg shadow-lg overflow-hidden transform transition-all duration-300',
alertTypeClasses[type]
]"
>
<div class="p-4">
<div class="flex items-start">
<div class="flex-shrink-0">
<CheckCircle v-if="type === 'success'" class="h-6 w-6 text-white" />
<AlertTriangle v-else-if="type === 'error'" class="h-6 w-6 text-white" />
<AlertCircle v-else-if="type === 'warning'" class="h-6 w-6 text-white" />
<Info v-else class="h-6 w-6 text-white" />
</div>
<div class="ml-3 w-0 flex-1 pt-0.5">
<p class="text-sm font-medium text-white" v-html="message"></p>
</div>
<div class="ml-4 flex-shrink-0 flex">
<button
@click="$emit('close')"
class="inline-flex text-white hover:text-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-white"
>
<span class="sr-only">关闭</span>
<X class="h-5 w-5" />
</button>
</div>
<transition-group
name="alert-fade"
tag="div"
class="fixed top-4 right-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"
:class="[
'w-full rounded-lg 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
@click="removeAlert(alert.id)"
class="inline-flex text-white hover:text-gray-200 focus:outline-none transition-colors duration-200"
>
<span class="sr-only">关闭</span>
<X class="h-5 w-5" />
</button>
</div>
</div>
<div class="h-1 bg-white bg-opacity-25">
<div
:class="[
'h-full transition-all duration-300 ease-out bg-white',
{ 'w-full': !autoClose }
]"
:style="{ width: `${progressWidth}%` }"
></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>
</transition-group>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAlertStore } from '@/stores/alertStore'
import { CheckCircle, AlertTriangle, AlertCircle, Info, X } from 'lucide-vue-next'
import { onMounted, onUnmounted } from 'vue'
const props = defineProps({
show: Boolean,
message: String,
type: {
type: String,
default: 'info',
validator: (value: string) => ['success', 'error', 'warning', 'info'].includes(value)
},
duration: {
type: Number,
default: 3000
},
autoClose: {
type: Boolean,
default: true
}
})
const alertStore = useAlertStore()
const { alerts } = storeToRefs(alertStore)
const { removeAlert, updateAlertProgress } = alertStore
const emit = defineEmits(['close'])
const alertTypeClasses: { [key: string]: string } = {
success: 'bg-green-500',
error: 'bg-red-500',
warning: 'bg-yellow-500',
info: 'bg-blue-500'
const gradientClasses = {
success: 'from-green-500 to-green-600',
error: 'from-red-500 to-red-600',
warning: 'from-yellow-500 to-yellow-600',
info: 'from-blue-500 to-blue-600'
}
const progressWidth = ref(100)
let timer: number | null = null
const startTimer = () => {
if (timer) {
clearInterval(timer)
}
progressWidth.value = 100
const startTime = Date.now()
const endTime = startTime + props.duration
timer = setInterval(() => {
const now = Date.now()
const remaining = endTime - now
progressWidth.value = (remaining / props.duration) * 100
if (remaining <= 0) {
clearInterval(timer!)
emit('close')
}
}, 10)
const alertIcons = {
success: CheckCircle,
error: AlertTriangle,
warning: AlertCircle,
info: Info
}
watch(
() => props.show,
(newValue) => {
if (newValue && props.autoClose) {
startTimer()
} else if (!newValue && timer) {
clearInterval(timer)
}
}
)
let intervalId: number
onMounted(() => {
if (props.show && props.autoClose) {
startTimer()
}
intervalId = setInterval(() => {
alerts.value.forEach((alert) => {
updateAlertProgress(alert.id)
})
}, 100)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
clearInterval(intervalId)
})
</script>
<style scoped>
.alert-fade-enter-active,
.alert-fade-leave-active {
transition:
opacity 0.3s,
transform 0.3s;
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(20px);
transform: translateX(50px) scale(0.95);
}
</style>
+45
View File
@@ -0,0 +1,45 @@
import { defineStore } from 'pinia'
interface Alert {
id: number
message: string
type: 'success' | 'error' | 'warning' | 'info'
progress: number
duration: number
startTime: number
}
export const useAlertStore = defineStore('alert', {
state: () => ({
alerts: [] as Alert[]
}),
actions: {
showAlert(
message: string,
type: 'success' | 'error' | 'warning' | 'info' = 'info',
duration = 5000
) {
const id = Date.now()
const startTime = Date.now()
this.alerts.push({ id, message, type, progress: 100, duration, startTime })
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)
}
},
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)
}
}
}
}
})
+7 -26
View File
@@ -330,13 +330,6 @@
</div>
</div>
</transition>
<AlertComponent
:show="showAlert"
:message="alertMessage"
:type="alertType"
@close="closeAlert"
/>
</div>
</template>
@@ -358,12 +351,13 @@ import {
import { useRouter, useRoute } from 'vue-router'
import QRCode from 'qrcode.vue'
import { useFileDataStore } from '@/stores/fileData'
import AlertComponent from '@/components/AlertComponent.vue'
import { storeToRefs } from 'pinia'
import api from '@/utils/api'
import { saveAs } from 'file-saver'
import { marked } from 'marked'
import { useAlertStore } from '@/stores/alertStore'
const alertStore = useAlertStore()
const baseUrl =
import.meta.env.MODE === 'production'
? import.meta.env.VITE_API_BASE_URL_PROD
@@ -373,19 +367,6 @@ const router = useRouter()
const isDarkMode = inject('isDarkMode')
const fileStore = useFileDataStore()
const { receiveData } = storeToRefs(fileStore)
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('success')
const showAlertMessage = (message, type) => {
alertMessage.value = message
alertType.value = type
showAlert.value = true
}
const closeAlert = () => {
showAlert.value = false
}
const code = ref('')
const inputStatus = ref({
readonly: false,
@@ -414,7 +395,7 @@ watch(code, (newVal) => {
const handleSubmit = async () => {
if (code.value.length !== 5) {
showAlertMessage('请输入5位取件码', 'error')
alertStore.showAlert('请输入5位取件码', 'error')
return
}
@@ -449,16 +430,16 @@ const handleSubmit = async () => {
fileStore.addReceiveData(newFileData)
}
showDrawer.value = true
showAlertMessage('文件获取成功', 'success')
alertStore.showAlert('文件获取成功', 'success')
} else {
showAlertMessage('无效的取件码', 'error')
alertStore.showAlert('无效的取件码', 'error')
}
} else {
showAlertMessage(res.message || '获取文件失败', 'error')
alertStore.showAlert(res.detail || '获取文件失败', 'error')
}
} catch (err) {
console.error('取件失败:', err)
showAlertMessage('取件失败,请稍后重试', 'error')
alertStore.showAlert('取件失败,请稍后重试', 'error')
} finally {
inputStatus.value.readonly = false
inputStatus.value.loading = false
+106 -85
View File
@@ -95,7 +95,7 @@
</div>
</div>
<div v-else key="text" class="grid grid-cols-1 gap-8">
<!-- 文本入区域 -->
<!-- 文本入区域 -->
<div v-if="sendType === 'text'" class="flex flex-col">
<textarea
id="text-content"
@@ -130,8 +130,9 @@
<option value="hour">按小时</option>
<option value="minute">按分钟</option>
<option value="count">按查看次数</option>
<option value="forever">永久</option>
</select>
<div class="flex items-center space-x-2">
<div v-if="expirationMethod !== 'forever'" class="flex items-center space-x-2">
<input
v-model="expirationValue"
type="number"
@@ -241,13 +242,24 @@
</div>
</div>
<div class="flex space-x-2">
<button
@click="copyRetrieveLink(record.retrieveCode)"
class="p-2 rounded-full hover:bg-opacity-20 transition duration-300"
:class="[
isDarkMode
? 'hover:bg-blue-400 text-blue-400'
: 'hover:bg-blue-100 text-blue-600'
]"
>
<ClipboardCopyIcon class="w-5 h-5" />
</button>
<button
@click="viewDetails(record)"
class="p-2 rounded-full hover:bg-opacity-20 transition duration-300"
:class="[
isDarkMode
? 'hover:bg-indigo-400 text-indigo-400'
: 'hover:bg-indigo-100 text-indigo-600'
? 'hover:bg-green-400 text-green-400'
: 'hover:bg-green-100 text-green-600'
]"
>
<EyeIcon class="w-5 h-5" />
@@ -282,7 +294,7 @@
class="text-2xl font-bold mb-6"
:class="[isDarkMode ? 'text-white' : 'text-gray-800']"
>
文件详
文件详
</h3>
<div class="space-y-4">
<div class="flex items-center">
@@ -367,13 +379,6 @@
</div>
</div>
</transition>
<!-- 使用新的 AlertComponent -->
<AlertComponent
:show="showAlert"
:message="alertMessage"
:type="alertType"
@close="closeAlert"
/>
</div>
</template>
@@ -390,14 +395,15 @@ import {
HardDriveIcon,
ClockIcon,
EyeIcon,
ShieldCheckIcon
ShieldCheckIcon,
ClipboardCopyIcon
} from 'lucide-vue-next'
import { useRouter } from 'vue-router'
import BorderProgressBar from '../components/BorderProgressBar.vue'
import QRCode from 'qrcode.vue'
import AlertComponent from '../components/AlertComponent.vue'
import SparkMD5 from 'spark-md5'
import { useFileDataStore } from '../stores/fileData'
import api from '@/utils/api'
const router = useRouter()
const isDarkMode = inject('isDarkMode')
@@ -412,25 +418,11 @@ const expirationValue = ref('')
const uploadProgress = ref(0)
const showDrawer = ref(false)
const selectedRecord = ref<any>(null)
import { useAlertStore } from '@/stores/alertStore'
const alertStore = useAlertStore()
const sendRecords = computed(() => fileDataStore.shareData)
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('success')
const showAlertMessage = (
message: string,
type: 'success' | 'error' | 'warning' | 'info' = 'success'
) => {
alertMessage.value = message
alertType.value = type
showAlert.value = true
}
const closeAlert = () => {
showAlert.value = false
}
// 新增状态
const fileHash = ref('')
const uploadedChunks = ref<Set<number>>(new Set())
@@ -516,10 +508,12 @@ const startChunkUpload = async () => {
// 所有切片上传完成,通知服务器合并文件
await mergeChunks(fileHash.value, totalChunks)
showAlertMessage('文件上传完成', 'success')
alertStore.showAlert('文件上传完成', 'success')
}
const checkUploadedChunks = async (fileHash: string) => {
console.log(fileHash)
// 这里应该调用后端API来检查已上传的切片
// 现在用模拟数据代替
return new Promise<{ uploadedList: number[] }>((resolve) => {
@@ -555,6 +549,8 @@ const getPlaceholder = () => {
return '输入分钟数'
case 'count':
return '输入查看次数'
case 'forever':
return '永久'
default:
return '输入值'
}
@@ -570,72 +566,83 @@ const getUnit = () => {
return '分钟'
case 'count':
return '次'
case 'forever':
return '永久'
default:
return ''
}
}
const handleSubmit = () => {
const handleSubmit = async () => {
if (sendType.value === 'file' && !selectedFile.value) {
showAlertMessage('请选择要上传的件', 'error')
alertStore.showAlert('请选择要上传的件', 'error')
return
}
if (sendType.value === 'text' && !textContent.value.trim()) {
showAlertMessage('请输入要发送的文本', 'error')
alertStore.showAlert('请输入要发送的文本', 'error')
return
}
if (!expirationValue.value) {
showAlertMessage('请输入过期值', 'error')
if (expirationMethod.value !== 'forever' && !expirationValue.value) {
alertStore.showAlert('请输入过期值', 'error')
return
}
// 处理文件/文本上传和过期设置的逻辑
console.log('Send Type:', sendType.value)
console.log('Selected File:', selectedFile.value)
console.log('Text Content:', textContent.value)
console.log('Expiration Method:', expirationMethod.value)
console.log('Expiration Value:', expirationValue.value)
try {
let response: any
if (sendType.value === 'text') {
// 使用 FormData 发送文本
const formData = new FormData()
formData.append('text', textContent.value)
if (expirationMethod.value !== 'forever') {
formData.append('expire_value', expirationValue.value)
}
formData.append('expire_style', expirationMethod.value)
response = await api.post('/share/text/', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
} else {
// 处理文件上传的逻辑
// ... 文件上传的代码 ...
}
// 计算过期时间
let expirationDate = new Date()
switch (expirationMethod.value) {
case 'day':
expirationDate.setDate(expirationDate.getDate() + parseInt(expirationValue.value))
break
case 'hour':
expirationDate.setHours(expirationDate.getHours() + parseInt(expirationValue.value))
break
case 'minute':
expirationDate.setMinutes(expirationDate.getMinutes() + parseInt(expirationValue.value))
break
case 'count':
// 对于查看次数,我们不设置具体的过期日期
break
if (response && response.code === 200) {
const retrieveCode = response.detail.code
// 添加新的发送记录
const newRecord = {
id: Date.now(),
filename: sendType.value === 'text' ? '文本内容.txt' : selectedFile.value!.name,
date: new Date().toISOString().split('T')[0],
size:
sendType.value === 'text'
? '0.1 MB'
: `${(selectedFile.value!.size / (1024 * 1024)).toFixed(1)} MB`,
expiration: `${expirationValue.value}${getUnit()}后过期`,
retrieveCode: retrieveCode
}
fileDataStore.addShareData(newRecord)
// 显示发送成功消息
alertStore.showAlert(`文件发送成功!取件码:${retrieveCode}`, 'success')
// 重置表单
selectedFile.value = null
textContent.value = ''
expirationValue.value = ''
uploadProgress.value = 0
// 自动打开抽屉
showDrawer.value = true
// 自动复制取件码链接
await copyRetrieveLink(retrieveCode)
} else {
throw new Error('服务器响应异常')
}
} catch (error) {
console.error('发送失败:', error)
alertStore.showAlert('发送失败,请稍后重试', 'error')
}
// 添加新的发送记录
const newRecord = {
id: Date.now(),
filename: selectedFile.value ? selectedFile.value.name : '文本内容.txt',
date: new Date().toISOString().split('T')[0],
size: selectedFile.value
? `${(selectedFile.value.size / (1024 * 1024)).toFixed(1)} MB`
: '0.1 MB',
expiration:
expirationMethod.value === 'count'
? `${expirationValue.value}次查看后过期`
: expirationDate.toISOString().split('T')[0],
retrieveCode: Math.random().toString(36).substring(2, 8).toUpperCase()
}
fileDataStore.addShareData(newRecord)
// 显示发送成功消息
showAlertMessage(`文件发送成功!取件码:${newRecord.retrieveCode}`, 'success')
// 重置表单
selectedFile.value = null
textContent.value = ''
expirationValue.value = ''
uploadProgress.value = 0
}
const toRetrieve = () => {
@@ -656,20 +663,34 @@ const deleteRecord = (id: number) => {
fileDataStore.deleteShareData(index)
}
}
const baseUrl =
import.meta.env.MODE === 'production'
? import.meta.env.VITE_API_BASE_URL_PROD
: import.meta.env.VITE_API_BASE_URL_DEV
const getQRCodeValue = (record: any) => {
// 这里返回你想要在二维码中编码的信息
// 例如,可以是一个包含文件ID和取件码的URL
return `https://your-domain.com/retrieve/${record.id}?code=${record.retrieveCode}`
return `${baseUrl}/?code=${record.retrieveCode}`
}
const copyRetrieveCode = async (code: string) => {
try {
await navigator.clipboard.writeText(code)
showAlertMessage('取件码已复制到剪贴板', 'success')
alertStore.showAlert('取件码已复制到剪贴板', 'success')
} catch (err) {
console.error('无法复制取件码: ', err)
showAlertMessage('复制失败,请手动复制取件码', 'error')
alertStore.showAlert('复制失败,请手动复制取件码', 'error')
}
}
const copyRetrieveLink = async (code: string) => {
const link = `${baseUrl}/?code=${code}`
try {
await navigator.clipboard.writeText(link)
alertStore.showAlert('取件链接已复制到剪贴板', 'success')
} catch (err) {
console.error('无法复制取件链接: ', err)
alertStore.showAlert('复制失败,请手动复制取件链接', 'error')
}
}