websocket消息支持 (#188)
* Release (#162) * feat: ✨ websocket server demo * feat: ✨ ws server demo dev * feat: ✨ ws server and mobile page * feat: ✨ 手机端发送消息 * feat: ✨ 手机网页发送消息 * 添加了抽奖中和抽奖完成时的音效 * feat: ✨ 自定义设置弹幕服务器地址 * feat: ✨ ws not done * fix: 🐛 fix pr-185 #185 为播放音效添加控制 * feat: ✨ server worker demo not done * feat: ✨ websocket server * feat: ✨ 全局接收websocket消息并存储到indexdb中 --------- Co-authored-by: Silence@2024 <707261624@qq.com>
This commit is contained in:
12
src/api/msg/index.ts
Normal file
12
src/api/msg/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import request from '../request'
|
||||
|
||||
export function api_sendMsg(userSignature: string, data: any) {
|
||||
return request<{ status: string }>({
|
||||
url: '/user-msg',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
userSignature,
|
||||
},
|
||||
data,
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
|
||||
import axios from 'axios'
|
||||
import openModal from '@/components/ErrorModal'
|
||||
|
||||
class Request {
|
||||
private instance: AxiosInstance
|
||||
@@ -15,14 +16,10 @@ class Request {
|
||||
this.instance.interceptors.request.use(
|
||||
(config: InternalAxiosRequestConfig) => {
|
||||
// 在发送请求之前做些什么
|
||||
console.log('请求拦截器被触发')
|
||||
|
||||
return config
|
||||
},
|
||||
(error: any) => {
|
||||
// 对请求错误做些什么
|
||||
console.error('请求拦截器发生错误:', error)
|
||||
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
@@ -31,15 +28,16 @@ class Request {
|
||||
this.instance.interceptors.response.use(
|
||||
(response: AxiosResponse) => {
|
||||
// 对响应数据做些什么
|
||||
console.log('响应拦截器被触发')
|
||||
const responseData = response.data
|
||||
|
||||
return responseData
|
||||
return response
|
||||
},
|
||||
(error: any) => {
|
||||
// 对响应错误做些什么
|
||||
console.error('响应拦截器发生错误:', error)
|
||||
|
||||
if (error.response && error.response.data) {
|
||||
const { code, msg } = error.response.data
|
||||
openModal({ title: code, desc: msg })
|
||||
return Promise.reject(error.response.data)
|
||||
}
|
||||
openModal({ title: '请求错误', desc: error.message })
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
BIN
src/assets/audio/end.mp3
Normal file
BIN
src/assets/audio/end.mp3
Normal file
Binary file not shown.
BIN
src/assets/audio/worldcup.mp3
Normal file
BIN
src/assets/audio/worldcup.mp3
Normal file
Binary file not shown.
@@ -9,11 +9,15 @@ interface Props {
|
||||
submitText?: string
|
||||
submitFunc?: () => void
|
||||
cancelFunc?: () => void
|
||||
footer?: null | 'center' | 'left' | 'right'
|
||||
dialogClass?: string // 添加动态class属性
|
||||
}
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
cancelText: i18n.global.t('button.cancel'),
|
||||
submitText: i18n.global.t('button.confirm'),
|
||||
cancelFunc: () => {},
|
||||
footer: 'right',
|
||||
dialogClass: '',
|
||||
})
|
||||
const visible = defineModel('visible', {
|
||||
type: Boolean,
|
||||
@@ -43,7 +47,7 @@ const { title, desc, cancelText, submitText, submitFunc, cancelFunc = defaultCan
|
||||
|
||||
<template>
|
||||
<dialog id="my_modal" ref="dialogRef" class="border-none modal">
|
||||
<div class="modal-box">
|
||||
<div class="modal-box" :class="[dialogClass]">
|
||||
<h3 v-if="title" class="text-lg font-bold">
|
||||
{{ title }}
|
||||
</h3>
|
||||
@@ -53,7 +57,7 @@ const { title, desc, cancelText, submitText, submitFunc, cancelFunc = defaultCan
|
||||
<div>
|
||||
<slot name="content" />
|
||||
</div>
|
||||
<div class="modal-action">
|
||||
<div class="modal-action" :class="{ 'flex justify-center': footer === 'center' }">
|
||||
<form method="dialog" class="flex gap-3">
|
||||
<!-- if there is a button in form, it will close the modal -->
|
||||
<button class="btn" @click="cancelFunc">
|
||||
|
||||
57
src/components/ErrorModal/index.ts
Normal file
57
src/components/ErrorModal/index.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { createVNode, render } from 'vue'
|
||||
import ErrorModalVue from './index.vue'
|
||||
|
||||
// 定义弹窗调用函数
|
||||
function openModal(options = {}) {
|
||||
// 默认配置
|
||||
const defaultOptions = {
|
||||
title: '提示',
|
||||
desc: '',
|
||||
// 确认按钮回调
|
||||
onConfirm: () => {},
|
||||
// 关闭按钮回调
|
||||
onClose: () => {},
|
||||
}
|
||||
|
||||
// 合并配置
|
||||
const finalOptions = { ...defaultOptions, ...options }
|
||||
|
||||
// 创建容器
|
||||
const container = document.createElement('div')
|
||||
|
||||
// 创建虚拟节点
|
||||
const vnode = createVNode(ErrorModalVue, {
|
||||
'title': finalOptions.title,
|
||||
'desc': finalOptions.desc,
|
||||
'modelValue': true, // 默认打开
|
||||
'onUpdate:modelValue': (val: any) => {
|
||||
if (!val) {
|
||||
// 关闭时销毁组件
|
||||
render(null, container)
|
||||
document.body.removeChild(container)
|
||||
}
|
||||
},
|
||||
'onConfirm': () => {
|
||||
finalOptions.onConfirm()
|
||||
},
|
||||
'onClose': () => {
|
||||
finalOptions.onClose()
|
||||
},
|
||||
})
|
||||
|
||||
// 渲染组件到容器
|
||||
render(vnode, container)
|
||||
|
||||
// 将容器添加到body
|
||||
document.body.appendChild(container)
|
||||
|
||||
// 返回关闭方法(可选)
|
||||
return {
|
||||
close: () => {
|
||||
render(null, container)
|
||||
document.body.removeChild(container)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default openModal
|
||||
127
src/components/ErrorModal/index.vue
Normal file
127
src/components/ErrorModal/index.vue
Normal file
@@ -0,0 +1,127 @@
|
||||
<script setup>
|
||||
import { Dialog, DialogDescription, DialogPanel, DialogTitle } from '@headlessui/vue'
|
||||
import { CircleAlert } from 'lucide-vue-next'
|
||||
import { defineEmits, defineProps, ref, watch } from 'vue'
|
||||
// 定义组件属性
|
||||
const props = defineProps({
|
||||
title: {
|
||||
type: String,
|
||||
default: '提示',
|
||||
},
|
||||
desc: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
// 控制弹窗显隐
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
// 定义事件
|
||||
const emit = defineEmits(['update:modelValue', 'close'])
|
||||
|
||||
// 内部显隐状态
|
||||
const visible = ref(props.modelValue)
|
||||
|
||||
// 同步外部 modelValue 变化
|
||||
watch(() => props.modelValue, (val) => {
|
||||
visible.value = val
|
||||
})
|
||||
|
||||
// 关闭弹窗
|
||||
function handleClose() {
|
||||
visible.value = false
|
||||
emit('update:modelValue', false)
|
||||
emit('close')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<teleport to="body">
|
||||
<Dialog :open="visible" class="relative z-50" @close="handleClose">
|
||||
<!-- The backdrop, rendered as a fixed sibling to the panel container -->
|
||||
<div class="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
<!-- Full-screen container to center the panel -->
|
||||
<div class="fixed inset-0 flex w-screen items-center justify-center p-4">
|
||||
<DialogPanel class="max-w-sm rounded bg-base-100 w-9/10 p-6 shadow-md">
|
||||
<DialogTitle class="font-bold text-lg">
|
||||
<p class="w-full flex items-center gap-2">
|
||||
<CircleAlert class="text-red-500" />
|
||||
<span>
|
||||
{{ title || '提示' }}
|
||||
</span>
|
||||
</p>
|
||||
</DialogTitle>
|
||||
<DialogDescription class="py-4">
|
||||
{{ desc }}
|
||||
</DialogDescription>
|
||||
<div class="mr-4 mt-4 flex justify-end">
|
||||
<button class="btn" @click="handleClose">
|
||||
确定
|
||||
</button>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
</div>
|
||||
</Dialog>
|
||||
</teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.modal-container {
|
||||
width: 400px;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
border-bottom: 1px solid #eee;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.modal-header button {
|
||||
background: transparent;
|
||||
border: none;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
margin-top: 20px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.modal-footer button {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-footer button:first-child {
|
||||
background: #409eff;
|
||||
color: #fff;
|
||||
border-color: #409eff;
|
||||
}
|
||||
</style>
|
||||
28
src/hooks/useTimerWorker/index.ts
Normal file
28
src/hooks/useTimerWorker/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { onUnmounted } from 'vue'
|
||||
import TimerWorker from './timerWorker.ts?worker'
|
||||
|
||||
export function useTimerWorker(interval: number) {
|
||||
let timerWorker: Worker | null = null
|
||||
const init = (callback: () => void) => {
|
||||
close()
|
||||
timerWorker = new TimerWorker()
|
||||
timerWorker.postMessage({ interval })
|
||||
if (timerWorker.onmessage)
|
||||
return
|
||||
timerWorker.addEventListener('message', () => callback())
|
||||
}
|
||||
|
||||
function close() {
|
||||
timerWorker?.terminate()
|
||||
timerWorker = null
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
close()
|
||||
})
|
||||
|
||||
return {
|
||||
init,
|
||||
close,
|
||||
}
|
||||
}
|
||||
12
src/hooks/useTimerWorker/timerworker.ts
Normal file
12
src/hooks/useTimerWorker/timerworker.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/* eslint-disable no-restricted-globals */
|
||||
let intervalId: number | null = null
|
||||
self.addEventListener('message', (e) => {
|
||||
const { interval } = e.data
|
||||
if (!interval)
|
||||
throw new Error('invalid params')
|
||||
if (intervalId)
|
||||
clearInterval(intervalId)
|
||||
intervalId = setInterval(() => {
|
||||
self.postMessage(true)
|
||||
}, interval)
|
||||
})
|
||||
114
src/hooks/useWebsocket.ts
Normal file
114
src/hooks/useWebsocket.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import type { IMsgType } from '@/types/msgType'
|
||||
import type { WsMsgData } from '@/types/storeType'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useTimerWorker } from './useTimerWorker'
|
||||
|
||||
export function useWebsocket() {
|
||||
const { init: initWorker, close: closeWorker } = useTimerWorker(30 * 1000)
|
||||
const status = ref<{ status: WebSocket['readyState'], connected: boolean }>()
|
||||
const data = ref<WsMsgData>()
|
||||
const registration = ref<ServiceWorkerRegistration | null>(null)
|
||||
async function registerSW() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
registration.value = await navigator.serviceWorker.register('/log-lottery/sw.js')
|
||||
console.log('Service Worker 注册成功:', registration)
|
||||
listenSWMessage()
|
||||
}
|
||||
catch (error) {
|
||||
console.error('Service Worker 注册失败:', error)
|
||||
}
|
||||
}
|
||||
else {
|
||||
console.error('浏览器不支持 Service Worker')
|
||||
}
|
||||
}
|
||||
|
||||
function open(url: string) {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.active?.postMessage({
|
||||
type: 'CONNECT_WS',
|
||||
payload: { url },
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function close() {
|
||||
closeWorker()
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.active?.postMessage({
|
||||
type: 'DISCONNECT_WS',
|
||||
})
|
||||
})
|
||||
}
|
||||
function send(message: string) {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.active?.postMessage({
|
||||
type: 'SEND_WS_MESSAGE',
|
||||
payload: { message, id: uuidv4() },
|
||||
})
|
||||
})
|
||||
}
|
||||
function getStatus() {
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.active?.postMessage({
|
||||
type: 'GET_WS_STATUS',
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 监听service worker消息
|
||||
function listenSWMessage() {
|
||||
navigator.serviceWorker.addEventListener('message', (event) => {
|
||||
const msgType = event.data.type
|
||||
switch (msgType) {
|
||||
case 'WS_STATUS':
|
||||
status.value = event.data.payload
|
||||
break
|
||||
case 'WS_MESSAGE':{
|
||||
const receivedMsg: IMsgType = event.data.payload as IMsgType
|
||||
data.value = {
|
||||
...receivedMsg,
|
||||
id: uuidv4(),
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'WS_ERROR':
|
||||
console.error('ws error:', event.data.payload)
|
||||
status.value = {
|
||||
status: WebSocket.CLOSED,
|
||||
connected: false,
|
||||
}
|
||||
closeWorker()
|
||||
break
|
||||
case 'WS_CLOSE':
|
||||
status.value = {
|
||||
status: WebSocket.CLOSED,
|
||||
connected: false,
|
||||
}
|
||||
closeWorker()
|
||||
break
|
||||
case 'WS_OPEN':
|
||||
status.value = {
|
||||
status: WebSocket.OPEN,
|
||||
connected: true,
|
||||
}
|
||||
initWorker(getStatus)
|
||||
break
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
registerSW()
|
||||
getStatus()
|
||||
})
|
||||
return {
|
||||
open,
|
||||
close,
|
||||
send,
|
||||
status,
|
||||
data,
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
<script setup lang='ts'>
|
||||
import { useFullscreen } from '@vueuse/core'
|
||||
import { Maximize, Minimize } from 'lucide-vue-next'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useQRCode } from '@vueuse/integrations/useQRCode'
|
||||
import { Maximize, Minimize, TabletSmartphone } from 'lucide-vue-next'
|
||||
import { onMounted, ref, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import CustomDialog from '@/components/Dialog/index.vue'
|
||||
import { getOriginUrl, getUniqueSignature } from '@/utils/auth'
|
||||
import { usePlayMusic } from './usePlayMusic'
|
||||
|
||||
const { playMusic, currentMusic, nextPlay } = usePlayMusic()
|
||||
@@ -12,8 +15,12 @@ const { t } = useI18n()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const customDialogRef = ref()
|
||||
const settingRef = ref()
|
||||
const fullScreenRef = ref()
|
||||
const mobileUrl = shallowRef<string>('')
|
||||
const qrCodeImg = useQRCode(mobileUrl)
|
||||
const visible = ref(true)
|
||||
|
||||
function enterConfig() {
|
||||
router.push('/log-lottery/config')
|
||||
@@ -21,7 +28,26 @@ function enterConfig() {
|
||||
function enterHome() {
|
||||
router.push('/log-lottery')
|
||||
}
|
||||
async function openMobileQrCode() {
|
||||
const originUrl = getOriginUrl()
|
||||
const userSignature = await getUniqueSignature()
|
||||
mobileUrl.value = `${originUrl}/log-lottery/mobile?userSignature=${userSignature}`
|
||||
customDialogRef.value.showDialog()
|
||||
}
|
||||
function handleSubmit() {
|
||||
|
||||
}
|
||||
|
||||
watch(() => route, (val) => {
|
||||
const { meta } = val
|
||||
if (meta && meta.isMobile) {
|
||||
visible.value = false
|
||||
}
|
||||
}, { immediate: true })
|
||||
onMounted(() => {
|
||||
if (!settingRef.value) {
|
||||
return
|
||||
}
|
||||
settingRef.value.addEventListener('mouseenter', () => {
|
||||
fullScreenRef.value.style.display = 'block'
|
||||
})
|
||||
@@ -32,7 +58,20 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="settingRef" class="flex flex-col gap-3">
|
||||
<div v-if="visible" ref="settingRef" class="flex flex-col gap-3">
|
||||
<CustomDialog
|
||||
ref="customDialogRef"
|
||||
title=""
|
||||
:submit-func="handleSubmit"
|
||||
footer="center"
|
||||
dialog-class="h-120 p-6"
|
||||
>
|
||||
<template #content>
|
||||
<div class="flex w-full justify-center h-90">
|
||||
<img :src="qrCodeImg" alt="qr code">
|
||||
</div>
|
||||
</template>
|
||||
</CustomDialog>
|
||||
<div ref="fullScreenRef" class="tooltip tooltip-left hidden" @click="toggleScreen">
|
||||
<div
|
||||
v-if="isFullscreen"
|
||||
@@ -71,6 +110,11 @@ onMounted(() => {
|
||||
<svg-icon :name="currentMusic.paused ? 'play' : 'pause'" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="tooltip tooltip-left" data-tip="访问手机端">
|
||||
<div class="flex items-center justify-center w-10 h-10 p-0 m-0 cursor-pointer setting-container bg-slate-500/50 rounded-l-xl hover:bg-slate-500/80 hover:text-blue-400/90" @click="openMobileQrCode">
|
||||
<TabletSmartphone />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { Ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { onMounted, provide, ref } from 'vue'
|
||||
import { onMounted, provide, ref, toRaw, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { loadingKey, loadingState } from '@/components/Loading'
|
||||
import { useWebsocket } from '@/hooks/useWebsocket'
|
||||
import useStore from '@/store'
|
||||
import { themeChange } from '@/utils'
|
||||
import { IndexDb } from '@/utils/dexie'
|
||||
|
||||
export function useMounted(tipDialog: Ref<any>) {
|
||||
provide(loadingKey, loadingState)
|
||||
@@ -15,6 +18,9 @@ export function useMounted(tipDialog: Ref<any>) {
|
||||
const { getPrizeConfig: prizeList, getTemporaryPrize: temporaryPrize } = storeToRefs(prizeConfig)
|
||||
const tipDesc = ref('')
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const { data } = useWebsocket()
|
||||
const msgListDb = new IndexDb('msgList', ['msgList'], 1, ['createTime'])
|
||||
// 设置当前奖列表
|
||||
function setCurrentPrize() {
|
||||
if (prizeList.value.length <= 0) {
|
||||
@@ -52,10 +58,26 @@ export function useMounted(tipDialog: Ref<any>) {
|
||||
|
||||
return isChrome || isEdge
|
||||
}
|
||||
const isShowMobileWarn = () => {
|
||||
const isMobilePage = judgeMobile()
|
||||
const { meta } = route
|
||||
let allowMobile = false
|
||||
if (meta && meta.isMobile) {
|
||||
allowMobile = true
|
||||
}
|
||||
return !allowMobile && isMobilePage
|
||||
}
|
||||
|
||||
watch(() => data.value, (newValue) => {
|
||||
if (!newValue) {
|
||||
return
|
||||
}
|
||||
msgListDb.setData('msgList', toRaw(newValue))
|
||||
}, { immediate: true, deep: true })
|
||||
onMounted(() => {
|
||||
themeChange(localTheme.value.name)
|
||||
setCurrentPrize()
|
||||
if (judgeMobile()) {
|
||||
if (isShowMobileWarn()) {
|
||||
tipDialog.value.showDialog()
|
||||
tipDesc.value = t('dialog.dialogPCWeb')
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export const sidebarEn = {
|
||||
imagesManagement: 'Images Management',
|
||||
musicManagement: 'Music Management',
|
||||
operatingInstructions: 'Operating Instructions',
|
||||
server: 'Server',
|
||||
}
|
||||
|
||||
export const sidebarZhCn = {
|
||||
@@ -20,6 +21,7 @@ export const sidebarZhCn = {
|
||||
imagesManagement: '图片管理',
|
||||
musicManagement: '音乐管理',
|
||||
operatingInstructions: '操作说明',
|
||||
server: '服务器',
|
||||
}
|
||||
|
||||
export const sidebar = {
|
||||
|
||||
@@ -51,4 +51,8 @@ pinia.use(piniaPluginPersist)
|
||||
|
||||
app.config.globalProperties.$THREE = THREE // 挂载到原型
|
||||
app.component('svg-icon', svgIcon)
|
||||
app.use(router).use(VueDOMPurifyHTML).use(pinia).use(i18n).mount('#app')
|
||||
app.use(router)
|
||||
app.use(VueDOMPurifyHTML)
|
||||
app.use(pinia)
|
||||
app.use(i18n)
|
||||
app.mount('#app')
|
||||
|
||||
@@ -101,6 +101,15 @@ export const configRoutes = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/log-lottery/config/server',
|
||||
name: 'Server',
|
||||
component: () => import('@/views/Config/Server/index.vue'),
|
||||
meta: {
|
||||
title: i18n.global.t('sidebar.server'),
|
||||
icon: 'server',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: '/log-lottery/config/readme',
|
||||
name: 'Readme',
|
||||
@@ -132,6 +141,14 @@ const routes = [
|
||||
name: 'Demo',
|
||||
component: () => import('@/views/Demo/index.vue'),
|
||||
},
|
||||
{
|
||||
path: '/log-lottery/mobile',
|
||||
name: 'Mobile',
|
||||
meta: {
|
||||
isMobile: true,
|
||||
},
|
||||
component: () => import('@/views/Mobile/index.vue'),
|
||||
},
|
||||
configRoutes,
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { IPersonConfig, IPrizeConfig } from '@/types/storeType'
|
||||
import { id } from 'zod/v4/locales'
|
||||
|
||||
const originUrl = 'https://to2026.xyz'
|
||||
type IPersonConfigWithoutUuid = Omit<IPersonConfig, 'uuid'>
|
||||
@@ -279,3 +280,24 @@ export const defaultImageList = [
|
||||
},
|
||||
]
|
||||
export const defaultPatternList = [21, 38, 55, 54, 53, 70, 87, 88, 89, 23, 40, 57, 74, 91, 92, 76, 59, 42, 25, 24, 27, 28, 29, 46, 63, 62, 61, 78, 95, 96, 97, 20, 19, 31, 48, 66, 67, 84, 101, 100, 32, 33, 93, 65, 82, 99]
|
||||
|
||||
export const defaultServerHostList = [
|
||||
{
|
||||
id: 'default',
|
||||
name: '默认服务器',
|
||||
value: 'default',
|
||||
host: 'https://to2026.xyz:8080',
|
||||
},
|
||||
{
|
||||
id: 'local',
|
||||
name: '本地服务器',
|
||||
value: 'local',
|
||||
host: 'http://127.0.0.1:8080',
|
||||
},
|
||||
{
|
||||
id: 'custom',
|
||||
name: '自定义服务器',
|
||||
value: 'custom',
|
||||
host: '',
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useGlobalConfig } from './globalConfig'
|
||||
import { usePersonConfig } from './personConfig'
|
||||
import { usePrizeConfig } from './prizeConfig'
|
||||
import { useServerConfig } from './serverConfig'
|
||||
import { useSystem } from './system'
|
||||
|
||||
export default function useStore() {
|
||||
@@ -9,5 +10,6 @@ export default function useStore() {
|
||||
prizeConfig: usePrizeConfig(),
|
||||
globalConfig: useGlobalConfig(),
|
||||
system: useSystem(),
|
||||
serverConfig: useServerConfig(),
|
||||
}
|
||||
}
|
||||
|
||||
57
src/store/serverConfig.ts
Normal file
57
src/store/serverConfig.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import type { ServerType } from '@/types/storeType'
|
||||
import { defineStore } from 'pinia'
|
||||
import { defaultServerHostList } from './data'
|
||||
|
||||
export const useServerConfig = defineStore('server', {
|
||||
state() {
|
||||
return {
|
||||
serverConfig: {
|
||||
serverList: defaultServerHostList,
|
||||
currentServer: defaultServerHostList[0],
|
||||
},
|
||||
}
|
||||
},
|
||||
getters: {
|
||||
// 获取服务器列表
|
||||
getServerList(state) {
|
||||
return state.serverConfig.serverList
|
||||
},
|
||||
// 获取当前服务器
|
||||
getCurrentServer(state) {
|
||||
return state.serverConfig.currentServer
|
||||
},
|
||||
|
||||
},
|
||||
actions: {
|
||||
// 设置服务器列表地址
|
||||
updateServerList(userServer: ServerType) {
|
||||
this.serverConfig.serverList.map((item) => {
|
||||
if (item.id === userServer.id) {
|
||||
item.host = userServer.host
|
||||
}
|
||||
return item
|
||||
})
|
||||
},
|
||||
// 设置当前服务器
|
||||
setCurrentServer(userServer: ServerType) {
|
||||
this.serverConfig.currentServer = userServer
|
||||
},
|
||||
// 重置所有配置
|
||||
resetDefault() {
|
||||
this.serverConfig = {
|
||||
serverList: defaultServerHostList,
|
||||
currentServer: defaultServerHostList[0],
|
||||
}
|
||||
},
|
||||
},
|
||||
persist: {
|
||||
enabled: true,
|
||||
strategies: [
|
||||
{
|
||||
// 如果要存储在localStorage中
|
||||
storage: localStorage,
|
||||
key: 'serverConfig',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
6
src/types/msgType.ts
Normal file
6
src/types/msgType.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export interface IMsgType {
|
||||
data: string
|
||||
image?: string | Blob | ArrayBuffer // TODO
|
||||
dateTime: string
|
||||
user?: string // TODO
|
||||
}
|
||||
@@ -52,3 +52,11 @@ export interface IImage {
|
||||
name: string
|
||||
url: string | Blob | ArrayBuffer
|
||||
}
|
||||
|
||||
export interface WsMsgData { data: string, id: string, dateTime: string }
|
||||
export interface ServerType {
|
||||
id: string
|
||||
name: string
|
||||
value: string
|
||||
host: string
|
||||
}
|
||||
|
||||
@@ -1,3 +1,20 @@
|
||||
import FingerprintJS from '@fingerprintjs/fingerprintjs'
|
||||
|
||||
export function getToken() {
|
||||
return window.localStorage.getItem('userToken')
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户浏览器唯一标识
|
||||
* @returns {Promise<string>} 唯一标识符
|
||||
*/
|
||||
export async function getUniqueSignature() {
|
||||
const fp = await FingerprintJS.load()
|
||||
const result = await fp.get()
|
||||
return result.visitorId
|
||||
}
|
||||
|
||||
// 获取origin url
|
||||
export function getOriginUrl() {
|
||||
return window.location.origin
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { EntityTable } from 'dexie'
|
||||
import type { DbData } from './type'
|
||||
import dayjs from 'dayjs'
|
||||
import Dexie from 'dexie'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
|
||||
class IndexDb {
|
||||
name: string
|
||||
@@ -38,6 +39,10 @@ class IndexDb {
|
||||
if (!data.type) {
|
||||
data.type = 'info'
|
||||
}
|
||||
if (!data.id) {
|
||||
data.id = uuidv4()
|
||||
}
|
||||
|
||||
this.dbStore[tableName].add(data)
|
||||
}
|
||||
|
||||
|
||||
32
src/views/Config/Server/index.vue
Normal file
32
src/views/Config/Server/index.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<script setup lang='ts'>
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import PageHeader from '@/components/PageHeader/index.vue'
|
||||
import MsgListContainer from './parts/MsgListContainer.vue'
|
||||
import ServerSetting from './parts/ServerSetting.vue'
|
||||
import { useViewModel } from './useViewModel'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { serverList, currentServerValue, wsStatus, handleConnectWs, closeWs, msgList } = useViewModel()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader :title="t('sidebar.server')" />
|
||||
<div>
|
||||
<ServerSetting
|
||||
v-model:current-server="currentServerValue"
|
||||
:server-list="serverList"
|
||||
:ws-status="wsStatus"
|
||||
:open-ws="handleConnectWs"
|
||||
:close-ws="closeWs"
|
||||
/>
|
||||
<MsgListContainer
|
||||
:msg-list="msgList"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
29
src/views/Config/Server/parts/MsgListContainer.vue
Normal file
29
src/views/Config/Server/parts/MsgListContainer.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang='ts'>
|
||||
import type { WsMsgData } from '@/types/storeType'
|
||||
|
||||
interface Props {
|
||||
msgList: WsMsgData[]
|
||||
}
|
||||
defineProps<Props>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-1/2 h-1/2 border rounded-md shadow-lg">
|
||||
<ul>
|
||||
<li v-for="item in msgList" :key="item.id" class="mb-3">
|
||||
<div class="chat chat-end">
|
||||
<div class="chat-header">
|
||||
<time class="text-xs opacity-50">{{ item.dateTime }}</time>
|
||||
</div>
|
||||
<div class="chat-bubble break-all whitespace-normal">
|
||||
{{ item.data }}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
107
src/views/Config/Server/parts/ServerSetting.vue
Normal file
107
src/views/Config/Server/parts/ServerSetting.vue
Normal file
@@ -0,0 +1,107 @@
|
||||
<script setup lang='ts'>
|
||||
import type { ServerType } from '@/types/storeType'
|
||||
import { ref, watch } from 'vue'
|
||||
// import { useI18n } from 'vue-i18n'
|
||||
|
||||
interface Props {
|
||||
serverList: ServerType[]
|
||||
wsStatus: { status: WebSocket['readyState'], connected: boolean } | undefined
|
||||
openWs: () => void
|
||||
closeWs: () => void
|
||||
}
|
||||
defineProps<Props>()
|
||||
|
||||
const currentServer = defineModel<ServerType>('currentServer', { required: true })
|
||||
const hostValue = ref('')
|
||||
// const { t } = useI18n()
|
||||
// 监听 currentServer 的 id 变化,重置 hostValue
|
||||
watch(() => currentServer.value?.id, (newId, oldId) => {
|
||||
if (newId !== oldId) {
|
||||
hostValue.value = currentServer.value?.host || ''
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// 监听 hostValue 变化,同步更新 currentServer.host
|
||||
watch(hostValue, (newHost) => {
|
||||
if (currentServer.value) {
|
||||
currentServer.value.host = newHost
|
||||
}
|
||||
})
|
||||
|
||||
// 初始化 hostValue
|
||||
hostValue.value = currentServer.value?.host || ''
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<fieldset class="p-4 border text-setting fieldset bg-base-200 border-base-300 rounded-box w-xs pb-10">
|
||||
<legend class="fieldset-legend">
|
||||
弹幕服务
|
||||
</legend>
|
||||
|
||||
<label class="flex flex-row items-center form-control">
|
||||
<div class="">
|
||||
<div class="label flex flex-col justify-start items-start">
|
||||
<label class="label">
|
||||
<span class="label-text text-left">弹幕服务地址</span>
|
||||
<div class="tooltip" data-tip="改变弹幕服务地址后会断开连接">
|
||||
<button class="btn btn-circle h-4 hover:bg-base-300">
|
||||
?
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<div class="radio-group flex gap-9">
|
||||
<ul class="flex gap-3">
|
||||
<li v-for="item in serverList" :key="item.id" class="flex flex-col">
|
||||
<label for="default-server">{{ item.name }}</label>
|
||||
<input id="default-server" type="radio" name="radio-1" class="radio" :checked="currentServer?.value === item.value" @change="currentServer = item">
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="请输入服务地址"
|
||||
:disabled="currentServer.value === 'default'"
|
||||
class="w-full max-w-xs input input-bordered"
|
||||
:value="hostValue"
|
||||
@input="hostValue = ($event.target as HTMLInputElement).value"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
<label class="flex flex-row items-center form-control">
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="label">
|
||||
<span class="label-text">弹幕服务器连接状态</span>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<div class="ws-status">
|
||||
<div v-if="wsStatus && wsStatus.connected">
|
||||
<div aria-label="success" class="status status-success" />
|
||||
<span>已连接</span>
|
||||
</div>
|
||||
<div v-else-if="wsStatus && wsStatus.connected === false">
|
||||
<div aria-label="error" class="status status-error" />
|
||||
<span>已断开</span>
|
||||
</div>
|
||||
<div v-else-if="wsStatus && wsStatus.status">
|
||||
<div aria-label="error" class="status status-error" />
|
||||
<span>操作中</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
<div aria-label="warning" class="status status-warning" />
|
||||
<span>未连接</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<button v-if="wsStatus?.connected === true" class="btn btn-error btn-sm" @click="closeWs">断开</button>
|
||||
<button v-else class="btn btn-primary btn-sm" @click="openWs">连接</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
</fieldset>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
55
src/views/Config/Server/useViewModel.ts
Normal file
55
src/views/Config/Server/useViewModel.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { ServerType, WsMsgData } from '@/types/storeType'
|
||||
import { cloneDeep } from 'lodash-es'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { useWebsocket } from '@/hooks/useWebsocket'
|
||||
import useStore from '@/store'
|
||||
import { getUniqueSignature } from '@/utils/auth'
|
||||
import { IndexDb } from '@/utils/dexie'
|
||||
|
||||
export function useViewModel() {
|
||||
const serverConfig = useStore().serverConfig
|
||||
const { getServerList: serverList, getCurrentServer: currentServer } = storeToRefs(serverConfig)
|
||||
const currentServerValue = ref<ServerType>(cloneDeep(currentServer.value))
|
||||
const wsUrl = ref<string>('ws://localhost:8080/echo')
|
||||
const msgList = ref<WsMsgData[]>([])
|
||||
const { open: openWs, close: closeWs, status: wsStatus } = useWebsocket()
|
||||
const msgListDb = new IndexDb('msgList', ['msgList'], 1, ['createTime'])
|
||||
const handleConnectWs = async () => {
|
||||
const userSignature = await getUniqueSignature()
|
||||
wsUrl.value = `ws://localhost:8080/echo?userSignature=${userSignature}`
|
||||
openWs(wsUrl.value)
|
||||
}
|
||||
const getAllMsg = async () => {
|
||||
msgListDb.getDataSortedByDateTime('msgList', 'dateTime').then((data) => {
|
||||
msgList.value = data
|
||||
})
|
||||
}
|
||||
|
||||
watch(
|
||||
() => currentServerValue.value.id,
|
||||
(newValue) => {
|
||||
serverList.value.forEach((item) => {
|
||||
if (item.id === newValue) {
|
||||
currentServerValue.value = item
|
||||
serverConfig.setCurrentServer(currentServerValue.value)
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
watch(() => currentServer.value.host, (newValue) => {
|
||||
currentServerValue.value.host = newValue
|
||||
serverConfig.updateServerList(currentServerValue.value)
|
||||
})
|
||||
onMounted(() => {
|
||||
getAllMsg()
|
||||
})
|
||||
return {
|
||||
serverList,
|
||||
currentServerValue,
|
||||
wsStatus,
|
||||
handleConnectWs,
|
||||
closeWs,
|
||||
msgList,
|
||||
}
|
||||
}
|
||||
@@ -1,241 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import gsap from 'gsap'
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
import { onBeforeUnmount, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { onMounted, onUnmounted, ref, shallowRef, watch } from 'vue'
|
||||
import { useToast } from 'vue-toast-notification'
|
||||
import { api_sendMsg } from '@/api/msg'
|
||||
import { getOriginUrl, getUniqueSignature } from '@/utils/auth'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
const toast = useToast()
|
||||
const mobileUrl = shallowRef<string>('')
|
||||
const wsQuery = ref<{ userSignature: string }>({
|
||||
userSignature: '',
|
||||
})
|
||||
|
||||
const list = ref<any[]>([])
|
||||
|
||||
list.value = [{
|
||||
label: 1,
|
||||
value: 1,
|
||||
color: 'red',
|
||||
}, {
|
||||
label: 2,
|
||||
value: 2,
|
||||
color: 'blue',
|
||||
}, {
|
||||
label: 3,
|
||||
value: 3,
|
||||
color: 'yellow',
|
||||
}, {
|
||||
label: 4,
|
||||
value: 4,
|
||||
color: 'green',
|
||||
}, {
|
||||
label: 5,
|
||||
value: 5,
|
||||
color: 'pink',
|
||||
}, {
|
||||
label: 6,
|
||||
value: 6,
|
||||
color: 'orange',
|
||||
}, {
|
||||
label: 7,
|
||||
value: 7,
|
||||
color: 'purple',
|
||||
}, {
|
||||
label: 8,
|
||||
value: 8,
|
||||
color: 'brown',
|
||||
}, {
|
||||
label: 9,
|
||||
value: 9,
|
||||
color: 'gray',
|
||||
}, {
|
||||
label: 10,
|
||||
value: 10,
|
||||
color: 'cyan',
|
||||
}, {
|
||||
label: 11,
|
||||
value: 11,
|
||||
color: 'white',
|
||||
}, {
|
||||
label: 12,
|
||||
value: 12,
|
||||
color: 'black',
|
||||
}, {
|
||||
label: 13,
|
||||
value: 13,
|
||||
color: 'orange',
|
||||
}, {
|
||||
label: 14,
|
||||
value: 14,
|
||||
color: 'yellow',
|
||||
}, {
|
||||
label: 15,
|
||||
value: 14,
|
||||
color: 'pink',
|
||||
}, {
|
||||
label: 15,
|
||||
value: 15,
|
||||
color: 'orange',
|
||||
}, {
|
||||
label: 16,
|
||||
value: 16,
|
||||
color: 'yellow',
|
||||
}, {
|
||||
label: 17,
|
||||
value: 17,
|
||||
color: 'green',
|
||||
}, {
|
||||
label: 18,
|
||||
value: 18,
|
||||
color: 'purple',
|
||||
}]
|
||||
|
||||
// 为每个 li 元素创建引用
|
||||
const liRefs = ref()
|
||||
const scrollContainerRef = ref()
|
||||
const ctx = ref()
|
||||
const showUpButton = ref(false)
|
||||
const showDownButton = ref(true)
|
||||
|
||||
function initGsapAnimation() {
|
||||
ctx.value = gsap.context(() => {
|
||||
liRefs.value.forEach((box: any) => {
|
||||
gsap.fromTo(box, { rotationX: -90, rotateZ: -20, opacity: 0 }, {
|
||||
rotationX: 0,
|
||||
rotateZ: 0,
|
||||
opacity: 1,
|
||||
scrollTrigger: {
|
||||
trigger: box,
|
||||
scroller: scrollContainerRef.value, // <- Specify the scroller!
|
||||
start: 'bottom 100%',
|
||||
end: 'top 70%',
|
||||
scrub: true,
|
||||
},
|
||||
})
|
||||
function connectUserMsg() {
|
||||
api_sendMsg(wsQuery.value.userSignature, `hello world ${wsQuery.value.userSignature}`).then((res: any) => {
|
||||
toast.open({
|
||||
message: res.msg || '发送成功',
|
||||
type: 'success',
|
||||
position: 'top-right',
|
||||
})
|
||||
}, scrollContainerRef.value) // <- Scope!
|
||||
})
|
||||
}
|
||||
|
||||
function disposeGsapAnimation() {
|
||||
ctx.value.revert() // <- Easy Cleanup!
|
||||
async function getFinger() {
|
||||
const userSignature = await getUniqueSignature()
|
||||
wsQuery.value.userSignature = userSignature
|
||||
return userSignature
|
||||
}
|
||||
function scrollHandler() {
|
||||
const scrollHeight = scrollContainerRef.value.scrollHeight
|
||||
const scrollTop = scrollContainerRef.value.scrollTop
|
||||
const containerHeight = scrollContainerRef.value.clientHeight
|
||||
// 滚动滑到底部
|
||||
if (scrollTop + containerHeight >= scrollHeight) {
|
||||
showDownButton.value = false
|
||||
showUpButton.value = true
|
||||
}
|
||||
// 在中间
|
||||
else if (scrollTop && scrollTop + containerHeight < scrollHeight) {
|
||||
showDownButton.value = true
|
||||
showUpButton.value = true
|
||||
}
|
||||
// 滚动滑到顶部
|
||||
else {
|
||||
showDownButton.value = true
|
||||
showUpButton.value = false
|
||||
}
|
||||
}
|
||||
function listenScrollContainer() {
|
||||
scrollContainerRef.value.addEventListener('scroll', scrollHandler)
|
||||
}
|
||||
function removeScrollContainer() {
|
||||
if (scrollContainerRef.value) {
|
||||
scrollContainerRef.value.removeEventListener('scroll', scrollHandler)
|
||||
}
|
||||
}
|
||||
|
||||
function handleScroll(h: number) {
|
||||
scrollContainerRef.value.scrollTop += h
|
||||
async function setMobileUrl() {
|
||||
const originUrl = getOriginUrl()
|
||||
const userSignature = await getFinger()
|
||||
mobileUrl.value = `${originUrl}/log-lottery/mobile?userSignature=${userSignature}`
|
||||
}
|
||||
onMounted(() => {
|
||||
initGsapAnimation()
|
||||
listenScrollContainer()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
removeScrollContainer()
|
||||
getFinger()
|
||||
setMobileUrl()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
disposeGsapAnimation()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full w-48 flex flex-col justify-center overflow-hidden relative">
|
||||
<div class="w-full h-16 flex justify-center scroll-button scroll-button-up">
|
||||
<SvgIcon v-show="showUpButton" name="chevron-up" size="64px" class="text-gray-200/80 cursor-pointer" @click="handleScroll(-100)" />
|
||||
</div>
|
||||
<div ref="scrollContainerRef" class="h-150 w-48 overflow-y-auto overflow-x-hidden relative scroll-smooth hide-scrollbar">
|
||||
<ul class="li-container relative bg-slate-500/50">
|
||||
<li
|
||||
v-for="item in list" :key="item.value" ref="liRefs" :style="{ backgroundColor: item.color }"
|
||||
class="w-full h-28 text-center leading-30 cursor-pointer duration-300"
|
||||
>
|
||||
{{ item.label }}
|
||||
</li>
|
||||
<li class="h-16" />
|
||||
</ul>
|
||||
</div>
|
||||
<div class="w-full h-16 flex justify-center scroll-button scroll-button-down">
|
||||
<SvgIcon v-show="showDownButton" name="chevron-down" size="64px" class="text-gray-200/80 cursor-pointer" @click="handleScroll(100)" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-3">
|
||||
<button class="btn btn-primary btn-sm w-32" @click="connectUserMsg">
|
||||
connectUserMsg
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.scroll-button::before,
|
||||
.scroll-button::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: -1;
|
||||
transform: translate(12px 12px);
|
||||
}
|
||||
|
||||
.scroll-button::before {
|
||||
transform: translate(0, -6px);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.scroll-button::after {
|
||||
transform: translate(0, 6px);
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
/* 添加动画效果 */
|
||||
.scroll-button-down {
|
||||
animation: bounce-down 2s infinite;
|
||||
}
|
||||
/* 添加动画效果 */
|
||||
.scroll-button-up {
|
||||
animation: bounce-up 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes bounce-down {
|
||||
0%, 20%, 50%, 80%, 100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
40% {
|
||||
transform: translateY(-5px);
|
||||
}
|
||||
60% {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
@keyframes bounce-up {
|
||||
0%, 20%, 50%, 80%, 100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
40% {
|
||||
transform: translateY(5px);
|
||||
}
|
||||
60% {
|
||||
transform: translateY(2px);
|
||||
}
|
||||
}
|
||||
|
||||
.scroll-button:hover {
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
</style>
|
||||
<style lang="scss" scoped></style>
|
||||
|
||||
@@ -8,7 +8,9 @@ import { CSS3DObject, CSS3DRenderer } from 'three-css3d'
|
||||
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls.js'
|
||||
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useToast } from 'vue-toast-notification'
|
||||
import dongSound from '@/assets/audio/end.mp3'
|
||||
import enterAudio from '@/assets/audio/enter.wav'
|
||||
import worldCupAudio from '@/assets/audio/worldcup.mp3'
|
||||
import { useElementPosition, useElementStyle } from '@/hooks/useElement'
|
||||
import i18n from '@/locales/i18n'
|
||||
import useStore from '@/store'
|
||||
@@ -70,6 +72,10 @@ export function useViewModel() {
|
||||
const isInitialDone = ref<boolean>(false)
|
||||
const animationFrameId = ref<any>(null)
|
||||
const playingAudios = ref<HTMLAudioElement[]>([])
|
||||
|
||||
// 抽奖音乐相关
|
||||
const lotteryMusic = ref<HTMLAudioElement | null>(null)
|
||||
|
||||
function initThreeJs() {
|
||||
const felidView = 40
|
||||
const width = window.innerWidth
|
||||
@@ -312,6 +318,104 @@ export function useViewModel() {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 开始抽奖音乐
|
||||
*/
|
||||
function startLotteryMusic() {
|
||||
if (!isPlayWinMusic.value) {
|
||||
return
|
||||
}
|
||||
if (lotteryMusic.value) {
|
||||
lotteryMusic.value.pause()
|
||||
lotteryMusic.value = null
|
||||
}
|
||||
|
||||
lotteryMusic.value = new Audio(worldCupAudio)
|
||||
lotteryMusic.value.loop = true
|
||||
lotteryMusic.value.volume = 0.7
|
||||
|
||||
lotteryMusic.value.play().catch((error) => {
|
||||
console.error('播放抽奖音乐失败:', error)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 停止抽奖音乐
|
||||
*/
|
||||
function stopLotteryMusic() {
|
||||
if (!isPlayWinMusic.value) {
|
||||
return
|
||||
}
|
||||
if (lotteryMusic.value) {
|
||||
lotteryMusic.value.pause()
|
||||
lotteryMusic.value = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 播放结束音效
|
||||
*/
|
||||
function playEndSound() {
|
||||
if (!isPlayWinMusic.value) {
|
||||
return
|
||||
}
|
||||
console.log('准备播放结束音效', dongSound)
|
||||
|
||||
// 清理已结束的音频
|
||||
playingAudios.value = playingAudios.value.filter(audio => !audio.ended)
|
||||
|
||||
try {
|
||||
const endSound = new Audio(dongSound)
|
||||
endSound.volume = 1.0
|
||||
|
||||
// 简化播放逻辑
|
||||
const playPromise = endSound.play()
|
||||
|
||||
if (playPromise) {
|
||||
playPromise
|
||||
.then(() => {
|
||||
console.log('结束音效播放成功')
|
||||
playingAudios.value.push(endSound)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('播放失败:', err.name, err.message)
|
||||
if (err.name === 'NotAllowedError') {
|
||||
console.warn('自动播放被阻止,需用户交互后播放')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
endSound.onended = () => {
|
||||
console.log('结束音效播放完成')
|
||||
const index = playingAudios.value.indexOf(endSound)
|
||||
if (index > -1)
|
||||
playingAudios.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error('创建音频对象失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 重置音频状态
|
||||
*/
|
||||
function resetAudioState() {
|
||||
if (!isPlayWinMusic.value) {
|
||||
return
|
||||
}
|
||||
// 停止抽奖音乐
|
||||
stopLotteryMusic()
|
||||
|
||||
// 清理所有正在播放的音频
|
||||
playingAudios.value.forEach((audio) => {
|
||||
if (!audio.ended && !audio.paused) {
|
||||
audio.pause()
|
||||
}
|
||||
})
|
||||
playingAudios.value = []
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: 开始抽奖,由横铺变换为球体(或其他图形)
|
||||
* @returns 随机抽取球数据
|
||||
@@ -321,6 +425,21 @@ export function useViewModel() {
|
||||
if (!canOperate.value) {
|
||||
return
|
||||
}
|
||||
|
||||
// 重置音频状态
|
||||
resetAudioState()
|
||||
|
||||
// 预加载音频资源以解决浏览器自动播放策略
|
||||
try {
|
||||
const audioContext = window.AudioContext || (window as any).webkitAudioContext
|
||||
if (audioContext) {
|
||||
console.log('音频上下文可用')
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.warn('音频上下文不可用:', e)
|
||||
}
|
||||
|
||||
if (!intervalTimer.value) {
|
||||
randomBallData()
|
||||
}
|
||||
@@ -396,6 +515,10 @@ export function useViewModel() {
|
||||
position: 'top-right',
|
||||
duration: 8000,
|
||||
})
|
||||
|
||||
// 开始播放抽奖音乐
|
||||
startLotteryMusic()
|
||||
|
||||
currentStatus.value = LotteryStatus.running
|
||||
rollBall(10, 3000)
|
||||
if (definiteTime.value) {
|
||||
@@ -413,6 +536,12 @@ export function useViewModel() {
|
||||
if (!canOperate.value) {
|
||||
return
|
||||
}
|
||||
// 停止抽奖音乐
|
||||
stopLotteryMusic()
|
||||
|
||||
// 播放结束音效
|
||||
playEndSound()
|
||||
|
||||
// clearInterval(intervalTimer.value)
|
||||
// intervalTimer.value = null
|
||||
canOperate.value = false
|
||||
@@ -449,9 +578,8 @@ export function useViewModel() {
|
||||
.easing(TWEEN.Easing.Exponential.InOut)
|
||||
.start()
|
||||
.onComplete(() => {
|
||||
if (isPlayWinMusic.value) {
|
||||
playWinMusic()
|
||||
}
|
||||
playWinMusic()
|
||||
|
||||
confettiFire()
|
||||
resetCamera()
|
||||
})
|
||||
@@ -459,11 +587,20 @@ export function useViewModel() {
|
||||
}
|
||||
// 播放音频,中将卡片越多audio对象越多,声音越大
|
||||
function playWinMusic() {
|
||||
if (!isPlayWinMusic.value) {
|
||||
return
|
||||
}
|
||||
// 清理已结束的音频
|
||||
playingAudios.value = playingAudios.value.filter(audio => !audio.ended && !audio.paused)
|
||||
|
||||
if (playingAudios.value.length > maxAudioLimit) {
|
||||
console.log('音频播放数量已达到上限,请勿重复播放')
|
||||
return
|
||||
}
|
||||
|
||||
const enterNewAudio = new Audio(enterAudio)
|
||||
enterNewAudio.volume = 0.8
|
||||
|
||||
playingAudios.value.push(enterNewAudio)
|
||||
enterNewAudio.play()
|
||||
.then(() => {
|
||||
@@ -483,6 +620,14 @@ export function useViewModel() {
|
||||
playingAudios.value.splice(index, 1)
|
||||
}
|
||||
})
|
||||
|
||||
// 播放错误时从数组中移除
|
||||
enterNewAudio.onerror = () => {
|
||||
const index = playingAudios.value.indexOf(enterNewAudio)
|
||||
if (index > -1) {
|
||||
playingAudios.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @description: 继续,意味着这抽奖作数,计入数据库
|
||||
@@ -514,6 +659,9 @@ export function useViewModel() {
|
||||
* @description: 放弃本次抽奖,回到初始状态
|
||||
*/
|
||||
function quitLottery() {
|
||||
// 停止抽奖音乐
|
||||
stopLotteryMusic()
|
||||
|
||||
enterLottery()
|
||||
currentStatus.value = LotteryStatus.init
|
||||
}
|
||||
@@ -523,7 +671,7 @@ export function useViewModel() {
|
||||
* @param {string} mod 模式
|
||||
*/
|
||||
function randomBallData(mod: 'default' | 'lucky' | 'sphere' = 'default') {
|
||||
// 两秒执行一次
|
||||
// 两秒执行一次
|
||||
intervalTimer.value = setInterval(() => {
|
||||
// 产生随机数数组
|
||||
const indexLength = 4
|
||||
@@ -581,7 +729,7 @@ export function useViewModel() {
|
||||
* @description: 清理资源,避免内存溢出
|
||||
*/
|
||||
function cleanup() {
|
||||
// 停止所有Tween动画
|
||||
// 停止所有Tween动画
|
||||
TWEEN.removeAll()
|
||||
|
||||
// 清理动画循环
|
||||
@@ -590,6 +738,21 @@ export function useViewModel() {
|
||||
}
|
||||
clearInterval(intervalTimer.value)
|
||||
intervalTimer.value = null
|
||||
|
||||
// 停止抽奖音乐
|
||||
stopLotteryMusic()
|
||||
|
||||
// 清理所有音频资源
|
||||
playingAudios.value.forEach((audio) => {
|
||||
if (!audio.ended && !audio.paused) {
|
||||
audio.pause()
|
||||
}
|
||||
// 释放音频资源
|
||||
audio.src = ''
|
||||
audio.load()
|
||||
})
|
||||
playingAudios.value = []
|
||||
|
||||
if (scene.value) {
|
||||
scene.value.traverse((object: Object3D) => {
|
||||
if ((object as any).material) {
|
||||
|
||||
90
src/views/Mobile/index.vue
Normal file
90
src/views/Mobile/index.vue
Normal file
@@ -0,0 +1,90 @@
|
||||
<script setup lang='ts'>
|
||||
import dayjs from 'dayjs'
|
||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useViewModel } from './useViewModel'
|
||||
|
||||
dayjs.extend(relativeTime)
|
||||
dayjs.locale('zh-cn') // 设置为中文
|
||||
|
||||
const textareaRef = ref()
|
||||
const messageArrayRef = ref()
|
||||
// 存储定时器ID
|
||||
const timer = ref()
|
||||
// 创建一个响应式的时间戳,用于触发更新
|
||||
const nowTimestamp = ref(Date.now())
|
||||
const { sendMsg, userInputMsg, userMsgArray } = useViewModel()
|
||||
async function handleEnterSend() {
|
||||
sendMsg(userInputMsg.value)
|
||||
textareaRef.value.blur()
|
||||
messageArrayRef.value.scrollTop = messageArrayRef.value.scrollHeight
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
if (!messageArrayRef.value) {
|
||||
return
|
||||
}
|
||||
setTimeout(() => {
|
||||
messageArrayRef.value.scrollTop = messageArrayRef.value.scrollHeight
|
||||
}, 0)
|
||||
}
|
||||
|
||||
// 带有实时更新的时间显示
|
||||
const formattedMessages = computed(() => {
|
||||
const _ = nowTimestamp.value
|
||||
return userMsgArray.value.map(item => ({
|
||||
...item,
|
||||
formattedTime: dayjs(item.dateTime).fromNow(),
|
||||
}))
|
||||
})
|
||||
watch(() => userMsgArray.value.length, () => {
|
||||
scrollToBottom()
|
||||
}, { immediate: true })
|
||||
|
||||
onMounted(() => {
|
||||
timer.value = setInterval(() => {
|
||||
nowTimestamp.value = Date.now()
|
||||
}, 60000) // 每分钟更新一次
|
||||
})
|
||||
onUnmounted(() => {
|
||||
if (timer.value) {
|
||||
clearInterval(timer.value)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col justify-around py-4">
|
||||
<div class="h-12 drop-shadow-md shadow-lg">
|
||||
<h2 class="text-center text-lg font-bold">
|
||||
发送弹幕
|
||||
</h2>
|
||||
</div>
|
||||
<div ref="messageArrayRef" class="overflow-y-auto h-[calc(100vh-15rem)]">
|
||||
<ul>
|
||||
<li v-for="item in formattedMessages" :key="item.id" class="mb-3">
|
||||
<div class="chat chat-end">
|
||||
<div class="chat-header">
|
||||
<time class="text-xs opacity-50">{{ item.formattedTime }}</time>
|
||||
</div>
|
||||
<div class="chat-bubble break-all whitespace-normal">
|
||||
{{ item.msg }}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="border-none rounded-2xl bg-base-200 mx-2 p-2 flex flex-col gap-3 items-center justify-center shadow-md mb-8 h-48">
|
||||
<textarea ref="textareaRef" v-model="userInputMsg" class="textarea w-full rounded-xl border-none bg-transparent focus:outline-none focus:ring-0" placeholder="发送弹幕 | 只展示您发送过的弹幕" rows="5" cols="50" @keydown.enter.prevent="handleEnterSend" />
|
||||
<div class="w-full flex justify-end">
|
||||
<button class="btn btn-primary w-24 mb-4" @click="handleEnterSend">
|
||||
发送
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
50
src/views/Mobile/useViewModel.ts
Normal file
50
src/views/Mobile/useViewModel.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { IMsgType } from '@/types/msgType'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useToast } from 'vue-toast-notification'
|
||||
import { api_sendMsg } from '@/api/msg'
|
||||
import { IndexDb } from '@/utils/dexie'
|
||||
|
||||
export function useViewModel() {
|
||||
const toast = useToast()
|
||||
const route = useRoute()
|
||||
const routeSignature = ref<string>('')
|
||||
const userInputMsg = ref('')
|
||||
const userMsgArray = ref<any[]>([])
|
||||
const userMsgDb = new IndexDb('userMsg', ['userMsg'], 1, ['createTime'])
|
||||
const getRouteSignature = async () => {
|
||||
routeSignature.value = route.query.userSignature as string
|
||||
}
|
||||
|
||||
const getAllMsg = async () => {
|
||||
userMsgDb.getDataSortedByDateTime('userMsg', 'dateTime').then((data) => {
|
||||
userMsgArray.value = data
|
||||
})
|
||||
}
|
||||
|
||||
function sendMsg(msg: string) {
|
||||
const msgData: IMsgType = {
|
||||
data: msg,
|
||||
dateTime: new Date().toLocaleString(),
|
||||
}
|
||||
api_sendMsg(routeSignature.value, msgData).then((res: any) => {
|
||||
toast.open({
|
||||
message: res.msg || '发送成功',
|
||||
type: 'success',
|
||||
position: 'top-right',
|
||||
})
|
||||
userMsgDb.setData('userMsg', { msg })
|
||||
getAllMsg()
|
||||
userInputMsg.value = ''
|
||||
})
|
||||
}
|
||||
onMounted(() => {
|
||||
getRouteSignature()
|
||||
getAllMsg()
|
||||
})
|
||||
return {
|
||||
sendMsg,
|
||||
userInputMsg,
|
||||
userMsgArray,
|
||||
}
|
||||
}
|
||||
3
src/vue-use.d.ts
vendored
Normal file
3
src/vue-use.d.ts
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare module '@vueuse/integrations/useQRCode' {
|
||||
export { useQRCode } from '@vueuse/integrations/useQRCode/dist/index.d.ts'
|
||||
}
|
||||
Reference in New Issue
Block a user