Files
kangyuan-mobile/pages/index/startPage.vue
T

525 lines
12 KiB
Vue

<template>
<view class="start-page">
<image v-if="USE_STATIC_START_PAGE" class="bg" src="/static/startPage.jpeg" mode="aspectFill" />
<video
v-if="!USE_STATIC_START_PAGE && bgSrc && isVideo"
class="bg"
:src="bgSrc"
autoplay
muted
:controls="false"
:show-fullscreen-btn="false"
:show-play-btn="false"
:show-center-play-btn="false"
:enable-progress-gesture="false"
:show-loading="true"
playsinline
webkit-playsinline
object-fit="cover"
@error="onMediaError"
@loadedmetadata="onVideoMetadata"
@canplay="onVideoReady"
@play="onVideoReady"
@timeupdate="onVideoTimeUpdate"
@ended="onVideoEnded"
@click="onMediaClick"
/>
<image
v-else-if="!USE_STATIC_START_PAGE && bgSrc && !isVideo"
class="bg"
:src="bgSrc"
mode="aspectFill"
@error="onMediaError"
@load="onImageLoaded"
@click="onMediaClick"
/>
<view
v-if="(USE_STATIC_START_PAGE || bgSrc) && mediaReady && countDown > 0 && !useNativeSkip"
class="count-down"
@click.stop="toHome"
>
<text class="count-down-text">{{ getSkipText() }}</text>
</view>
<view v-if="!USE_STATIC_START_PAGE && isLoading" class="loading-mask">
<view class="loading-box">
<view class="loading-spinner"></view>
<view class="loading-text">加载中...</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as IndexApi from '@/sheep/api/index/index'
const USE_STATIC_START_PAGE = false
const DEFAULT_IMAGE_SECONDS = 3
const FIXED_VIDEO_SECONDS = 5
const bgSrc = ref('')
const jumpUrl = ref('')
const isVideo = ref(false)
const mediaReady = ref(false)
const isLoading = ref(false)
const useNativeSkip = ref(false)
let downloadToken = 0
let readyFallbackTimer = null
let countDownTimer = null
let jumpTimer = null
let videoCountdownBootTimer = null
let nativeSkipView = null
let nativeSkipViewId = ''
let plusReadyListenerBound = false
let lastVideoTime = 0
const normalizeAppFileUrl = (path) => {
const p = String(path || '')
if (!p) return ''
if (/^https?:\/\//i.test(p)) return p
if (p.startsWith('file://')) return p
try {
if (typeof plus !== 'undefined' && plus?.io?.convertLocalFileSystemURL) {
const next = plus.io.convertLocalFileSystemURL(p)
return next || p
}
} catch (e) {}
if (p.startsWith('/')) return `file://${p}`
return p
}
const isVideoUrl = (url) => {
const u = String(url || '')
if (!u) return false
const clean = u.split('?')[0].split('#')[0]
return /\.(mp4|mov|m4v|webm|ogg)$/i.test(clean)
}
const fetchStartPage = async () => {
try {
const res = await IndexApi.getstartpage({})
if (res?.code !== 0) return false
const data = res?.data || {}
const media = String(data?.picUrl || '').trim()
const url = String(data?.url || '').trim()
if (!media) return false
jumpUrl.value = url
isVideo.value = isVideoUrl(media)
if (isVideo.value && typeof plus !== 'undefined') {
const token = (downloadToken += 1)
const downloadPromise = new Promise((resolve) => {
uni.downloadFile({
url: media,
success: (r) => resolve(r?.statusCode === 200 ? r.tempFilePath : ''),
fail: () => resolve(''),
})
})
downloadPromise.then((localPath) => {
const normalized = normalizeAppFileUrl(localPath)
if (!normalized) return
if (token !== downloadToken) return
if (mediaReady.value) return
bgSrc.value = normalized
})
const fastLocal = await Promise.race([
downloadPromise,
new Promise((resolve) => setTimeout(() => resolve(''), 1500)),
])
bgSrc.value = normalizeAppFileUrl(fastLocal) || media
return true
}
bgSrc.value = media
return true
} catch (e) {
return false
}
}
function onMediaError() {
toHome()
}
const countDown = ref(0)
const getSkipText = () => {
const s = Number(countDown.value) || 0
return s > 0 ? `跳过 ${s}s` : '跳过'
}
function closeNativeSplashIfNeeded() {
try {
if (typeof plus !== 'undefined' && plus?.navigator?.closeSplashscreen) {
plus.navigator.closeSplashscreen()
}
} catch (e) {}
}
function destroyNativeSkipView() {
try {
if (!nativeSkipView) return
if (typeof nativeSkipView.hide === 'function') nativeSkipView.hide()
if (typeof nativeSkipView.close === 'function') nativeSkipView.close()
} catch (e) {}
nativeSkipView = null
nativeSkipViewId = ''
useNativeSkip.value = false
}
function ensureNativeSkipView() {
try {
if (typeof plus === 'undefined') return
if (nativeSkipView) return
const screenWidth = Number(plus?.screen?.resolutionWidth || 0)
if (!screenWidth) return
const pxPerRpx = screenWidth / 750
const widthPx = Math.round(pxPerRpx * 180)
const heightPx = Math.round(pxPerRpx * 64)
const rightPx = Math.round(pxPerRpx * 60)
const topPx = Math.round(pxPerRpx * 100)
const leftPx = Math.max(0, screenWidth - rightPx - widthPx)
const radiusPx = Math.round(heightPx / 2)
const fontPx = Math.round(pxPerRpx * 28)
nativeSkipViewId = `start-page-skip-${Date.now()}-${Math.floor(Math.random() * 1e6)}`
nativeSkipView = new plus.nativeObj.View(
nativeSkipViewId,
{
top: `${topPx}px`,
left: `${leftPx}px`,
width: `${widthPx}px`,
height: `${heightPx}px`,
},
[]
)
nativeSkipView.drawRect(
{
color: 'rgba(0,0,0,0.4)',
radius: `${radiusPx}px`,
},
{
top: '0px',
left: '0px',
width: `${widthPx}px`,
height: `${heightPx}px`,
},
'bg'
)
nativeSkipView.addEventListener('click', () => {
toHome()
})
nativeSkipView.drawText(
getSkipText(),
{
top: '0px',
left: '0px',
width: `${widthPx}px`,
height: `${heightPx}px`,
},
{
size: `${fontPx}px`,
color: '#ffffff',
align: 'center',
verticalAlign: 'middle',
},
'text'
)
try {
const wv = typeof plus?.webview?.currentWebview === 'function' ? plus.webview.currentWebview() : null
if (wv && typeof wv.append === 'function') {
wv.append(nativeSkipView)
}
} catch (e) {}
nativeSkipView.show()
useNativeSkip.value = true
} catch (e) {
destroyNativeSkipView()
}
}
function updateNativeSkipText() {
try {
if (!nativeSkipView) return
const screenWidth = Number(plus?.screen?.resolutionWidth || 0)
if (!screenWidth) return
const pxPerRpx = screenWidth / 750
const widthPx = Math.round(pxPerRpx * 180)
const heightPx = Math.round(pxPerRpx * 64)
const fontPx = Math.round(pxPerRpx * 28)
nativeSkipView.drawText(
getSkipText(),
{
top: '0px',
left: '0px',
width: `${widthPx}px`,
height: `${heightPx}px`,
},
{
size: `${fontPx}px`,
color: '#ffffff',
align: 'center',
verticalAlign: 'middle',
},
'text'
)
} catch (e) {}
}
function clearTimers() {
if (readyFallbackTimer) clearTimeout(readyFallbackTimer)
readyFallbackTimer = null
if (countDownTimer) clearInterval(countDownTimer)
countDownTimer = null
if (jumpTimer) clearTimeout(jumpTimer)
jumpTimer = null
if (videoCountdownBootTimer) clearTimeout(videoCountdownBootTimer)
videoCountdownBootTimer = null
destroyNativeSkipView()
}
function startCountDown(seconds) {
const s = Math.max(1, Math.floor(Number(seconds) || 0))
countDown.value = s
if (countDownTimer) clearInterval(countDownTimer)
countDownTimer = setInterval(() => {
if (countDown.value <= 1) {
if (countDownTimer) clearInterval(countDownTimer)
countDownTimer = null
toHome()
return
}
countDown.value -= 1
}, 1000)
}
function scheduleJumpAfter(seconds) {
const ms = Math.max(0, Math.floor(Number(seconds) * 1000))
if (jumpTimer) clearTimeout(jumpTimer)
jumpTimer = setTimeout(() => {
toHome()
}, ms)
}
function onImageLoaded() {
if (mediaReady.value) return
mediaReady.value = true
isLoading.value = false
closeNativeSplashIfNeeded()
startCountDown(DEFAULT_IMAGE_SECONDS)
scheduleJumpAfter(DEFAULT_IMAGE_SECONDS + 0.2)
}
function onVideoReady() {
if (!mediaReady.value) {
mediaReady.value = true
isLoading.value = false
closeNativeSplashIfNeeded()
}
if (countDownTimer) return
if (videoCountdownBootTimer) return
videoCountdownBootTimer = setTimeout(() => {
videoCountdownBootTimer = null
if (countDownTimer) return
startCountDown(FIXED_VIDEO_SECONDS)
scheduleJumpAfter(FIXED_VIDEO_SECONDS + 0.2)
}, 300)
}
function onVideoMetadata(e) {
if (videoCountdownBootTimer) {
clearTimeout(videoCountdownBootTimer)
videoCountdownBootTimer = null
}
if (!mediaReady.value) {
mediaReady.value = true
isLoading.value = false
closeNativeSplashIfNeeded()
}
startCountDown(FIXED_VIDEO_SECONDS)
scheduleJumpAfter(FIXED_VIDEO_SECONDS + 0.2)
}
function onVideoTimeUpdate(e) {
const currentTime = Number(e?.detail?.currentTime || 0)
if (!Number.isFinite(currentTime) || currentTime <= 0) return
const loopDetected = lastVideoTime > 0.4 && currentTime + 0.2 < lastVideoTime
lastVideoTime = currentTime
if (loopDetected) {
toHome()
return
}
if (currentTime + 0.12 >= FIXED_VIDEO_SECONDS) {
toHome()
}
}
function onVideoEnded() {
toHome()
}
onMounted(() => {
closeNativeSplashIfNeeded()
if (USE_STATIC_START_PAGE) {
startCountDown(DEFAULT_IMAGE_SECONDS)
scheduleJumpAfter(DEFAULT_IMAGE_SECONDS + 0.2)
return
}
isLoading.value = true
fetchStartPage().then((ok) => {
if (!ok) {
toHome()
return
}
readyFallbackTimer = setTimeout(() => {
if (mediaReady.value) return
toHome()
}, isVideo.value ? 3500 : 2000)
})
})
onUnmounted(() => {
clearTimers()
})
function toHome() {
clearTimers()
isLoading.value = false
uni.reLaunch({
url: '/pages/index/index',
})
}
function onMediaClick() {
const url = String(jumpUrl.value || '').trim()
if (!url) return
if (/^https?:\/\//i.test(url)) {
uni.navigateTo({
url: `/pages/public/webview?url=${encodeURIComponent(url)}`,
})
return
}
if (url.startsWith('/pages/')) {
uni.navigateTo({ url })
return
}
}
watch(
[() => isVideo.value, () => countDown.value],
([v, s]) => {
if (!v || s <= 0) {
destroyNativeSkipView()
return
}
if (typeof plus !== 'undefined') {
ensureNativeSkipView()
updateNativeSkipText()
return
}
if (plusReadyListenerBound) return
plusReadyListenerBound = true
try {
if (typeof document !== 'undefined' && document?.addEventListener) {
document.addEventListener(
'plusready',
() => {
plusReadyListenerBound = false
if (isVideo.value && countDown.value > 0) {
ensureNativeSkipView()
updateNativeSkipText()
}
},
{ once: true }
)
}
} catch (e) {}
},
{ immediate: true }
)
</script>
<style lang="scss" scoped>
.start-page {
position: fixed;
inset: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
background: #fff;
}
.bg {
position: absolute;
inset: 0;
width: 100vw;
height: 100vh;
z-index: 0;
}
.count-down {
position: absolute;
top: calc(env(safe-area-inset-top) + 100rpx);
right: 60rpx;
height: 64rpx;
padding: 0 20rpx;
border-radius: 50rpx;
font-size: 28rpx;
line-height: 32rpx;
color: #fff;
background: rgba(0, 0, 0, 0.4);
z-index: 999999;
display: flex;
align-items: center;
justify-content: center;
}
.count-down-text {
color: #fff;
font-size: 28rpx;
line-height: 32rpx;
}
.loading-mask {
position: absolute;
inset: 0;
z-index: 9998;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
}
.loading-box {
padding: 22rpx 26rpx;
border-radius: 16rpx;
background: rgba(0, 0, 0, 0.45);
display: flex;
align-items: center;
gap: 16rpx;
}
.loading-spinner {
width: 32rpx;
height: 32rpx;
border-radius: 50%;
border: 4rpx solid rgba(255, 255, 255, 0.35);
border-top-color: rgba(255, 255, 255, 0.95);
animation: spin 0.85s linear infinite;
}
.loading-text {
font-size: 26rpx;
color: #fff;
line-height: 32rpx;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>