bug修改

This commit is contained in:
Developer
2026-05-12 20:27:30 +08:00
parent b0929a8094
commit 53c67079a1
23 changed files with 1026 additions and 387 deletions

46
hooks/useAutoHideTimer.ts Normal file
View File

@@ -0,0 +1,46 @@
import { useState, useRef, useCallback, useEffect } from 'react';
/**
* 控制栏自动隐藏 hookshow() 后 delayMs 内无交互即隐藏。
* keep() 用于"按住进度条不让消失"等场景:返回 true 时计时器会被推迟。
*/
export function useAutoHideTimer(delayMs = 3000, keep?: () => boolean) {
const [visible, setVisible] = useState(true);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const reset = useCallback(() => {
if (timerRef.current) clearTimeout(timerRef.current);
if (keep?.()) return;
timerRef.current = setTimeout(() => setVisible(false), delayMs);
}, [delayMs, keep]);
const show = useCallback(() => {
setVisible(true);
reset();
}, [reset]);
const hide = useCallback(() => {
if (timerRef.current) clearTimeout(timerRef.current);
setVisible(false);
}, []);
const toggle = useCallback(() => {
setVisible(prev => {
if (!prev) {
reset();
return true;
}
if (timerRef.current) clearTimeout(timerRef.current);
return false;
});
}, [reset]);
useEffect(() => {
reset();
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);
return { visible, show, hide, toggle, reset };
}

View File

@@ -2,7 +2,7 @@ import { useState, useEffect, useRef } from 'react';
import { getLiveDanmakuHistory } from '../services/bilibili';
import type { DanmakuItem } from '../services/types';
const POLL_INTERVAL = 3000;
const POLL_INTERVAL = 1500;
// 匹配 admin 消息中的礼物信息,如 "xxx 赠送了 辣条 x5" 或 "xxx 投喂 小心心 ×1"
const GIFT_PATTERN = /(?:赠送|投喂)\s*(?:了\s*)?(.+?)\s*[xX×]\s*(\d+)/;
@@ -36,9 +36,10 @@ export function useLiveDanmaku(roomId: number): {
const { danmakus: items, adminMsgs } = await getLiveDanmakuHistory(roomId);
if (cancelled) return;
// 去重弹幕
// 去重弹幕:以 uname + text + timeline 为 key
// 用 timeline 区分"同一人重复发同句"的合法重复gethistory 多次轮询会返回相同尾部数据,靠 timeline 过滤掉)
const newItems = items.filter(item => {
const key = `${item.uname ?? ''}:${item.text}`;
const key = `${item.uname ?? ''}:${item.text}:${item.timeline ?? ''}`;
if (seenTextsRef.current.has(key)) return false;
seenTextsRef.current.add(key);
return true;
@@ -50,7 +51,6 @@ export function useLiveDanmaku(roomId: number): {
// 解析 admin 消息中的礼物
const newGifts: Record<string, number> = {};
for (const msg of adminMsgs) {
console.log(msg,123)
// 去重 admin 消息
if (seenAdminRef.current.has(msg)) continue;
seenAdminRef.current.add(msg);

70
hooks/useMiniDrag.ts Normal file
View File

@@ -0,0 +1,70 @@
import { useRef } from 'react';
import { Animated, Dimensions, PanResponder } from 'react-native';
interface Options {
width: number;
height: number;
/** 命中"关闭按钮"区域的判定locationX, locationY→ true 时调 onClose否则调 onTap */
hitClose?: (locationX: number, locationY: number) => boolean;
onTap: () => void;
onClose?: () => void;
}
/**
* 全局浮动小窗的拖拽 + 吸边 + 点击/关闭分发。
* 返回 panHandlers 直接展开到容器transform 应用 pan.getTranslateTransform()。
*/
export function useMiniDrag({ width, height, hitClose, onTap, onClose }: Options) {
const pan = useRef(new Animated.ValueXY()).current;
const isDragging = useRef(false);
// 用 ref 保持最新回调,避免 PanResponder 闭包过期
const cbRef = useRef({ onTap, onClose, hitClose });
cbRef.current = { onTap, onClose, hitClose };
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderGrant: () => {
isDragging.current = false;
pan.setOffset({ x: (pan.x as any)._value, y: (pan.y as any)._value });
pan.setValue({ x: 0, y: 0 });
},
onPanResponderMove: (_, gs) => {
if (Math.abs(gs.dx) > 5 || Math.abs(gs.dy) > 5) {
isDragging.current = true;
}
pan.x.setValue(gs.dx);
pan.y.setValue(gs.dy);
},
onPanResponderRelease: (evt) => {
pan.flattenOffset();
if (!isDragging.current) {
const { locationX, locationY } = evt.nativeEvent;
const cb = cbRef.current;
if (cb.hitClose?.(locationX, locationY) && cb.onClose) {
cb.onClose();
} else {
cb.onTap();
}
return;
}
const { width: sw, height: sh } = Dimensions.get('window');
const curX = (pan.x as any)._value;
const curY = (pan.y as any)._value;
const snapRight = 0;
const snapLeft = -(sw - width - 24);
const snapX = curX < snapLeft / 2 ? snapLeft : snapRight;
const clampedY = Math.max(-sh + height + 60, Math.min(60, curY));
Animated.spring(pan, {
toValue: { x: snapX, y: clampedY },
useNativeDriver: false,
tension: 120,
friction: 10,
}).start();
},
onPanResponderTerminate: () => { pan.flattenOffset(); },
}),
).current;
return { pan, panHandlers: panResponder.panHandlers };
}

View File

@@ -2,6 +2,7 @@ import { useState, useEffect, useRef } from 'react';
import { getVideoDetail, getPlayUrl } from '../services/bilibili';
import { useAuthStore } from '../store/authStore';
import { useSettingsStore } from '../store/settingsStore';
import { usePlayProgressStore } from '../store/playProgressStore';
import type { VideoItem, PlayUrlResponse } from '../services/types';
export function useVideoDetail(bvid: string) {
@@ -11,6 +12,7 @@ export function useVideoDetail(bvid: string) {
const [currentQn, setCurrentQn] = useState<number>(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [initialTime, setInitialTime] = useState(0);
const cidRef = useRef<number>(0);
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
const trafficSaving = useSettingsStore(s => s.trafficSaving);
@@ -38,6 +40,8 @@ export function useVideoDetail(bvid: string) {
async function fetchData() {
try {
setLoading(true);
// 读取续播位置
setInitialTime(usePlayProgressStore.getState().get(bvid));
const detail = await getVideoDetail(bvid);
setVideo(detail);
const cid = detail.pages?.[0]?.cid ?? detail.cid as number;
@@ -53,13 +57,32 @@ export function useVideoDetail(bvid: string) {
}, [bvid]);
// 登录状态变化时重新拉取清晰度列表(登录后可能获得更高画质)
// cancelled flag 防止旧响应(切换登录态后)覆盖新响应
useEffect(() => {
if (cidRef.current) {
fetchPlayData(cidRef.current, defaultQn, true).catch((e) => {
console.warn('Failed to refresh quality list after login change:', e);
});
}
if (!cidRef.current) return;
let cancelled = false;
(async () => {
try {
const data = await getPlayUrl(bvid, cidRef.current, defaultQn);
if (cancelled) return;
setPlayData(data);
setCurrentQn(data.quality);
if (data.accept_quality?.length) {
setQualities(
data.accept_quality.map((q, i) => ({
qn: q,
desc: data.accept_description?.[i] ?? String(q),
})),
);
}
} catch (e) {
if (!cancelled) console.warn('Failed to refresh quality list after login change:', e);
}
})();
return () => {
cancelled = true;
};
}, [isLoggedIn]);
return { video, playData, loading, error, qualities, currentQn, changeQuality };
return { video, playData, loading, error, qualities, currentQn, changeQuality, initialTime };
}

View File

@@ -1,14 +1,12 @@
import { useState, useCallback, useRef, useMemo } from 'react';
import { getRecommendFeed, getLiveList } from '../services/bilibili';
import type { VideoItem, LiveRoom } from '../services/types';
import { getRecommendFeed } from '../services/bilibili';
import type { VideoItem } from '../services/types';
export function useVideoList() {
const [pages, setPages] = useState<VideoItem[][]>([]);
const [liveRooms, setLiveRooms] = useState<LiveRoom[]>([]);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
// Use refs to avoid stale closures — load() has stable identity
const loadingRef = useRef(false);
const freshIdxRef = useRef(0);
@@ -21,19 +19,8 @@ export function useVideoList() {
const idx = freshIdxRef.current;
setLoading(true);
try {
const promises: [Promise<VideoItem[]>, Promise<LiveRoom[]>] = [
getRecommendFeed(idx),
(reset || idx === 0)
? getLiveList(1, 0).catch(() => [] as LiveRoom[])
: Promise.resolve([] as LiveRoom[]),
];
const [data, live] = await Promise.all(promises);
const data = await getRecommendFeed(idx);
setPages(prev => reset ? [data] : [...prev, data]);
if (reset || idx === 0) {
// Take top 2 by online count
const sorted = [...live].sort((a, b) => b.online - a.online).slice(0, 10);
setLiveRooms(sorted);
}
freshIdxRef.current = idx + 1;
} catch (e) {
console.error('Failed to load videos', e);
@@ -42,7 +29,7 @@ export function useVideoList() {
setLoading(false);
setRefreshing(false);
}
}, []); // stable — no stale closure risk
}, []);
const refresh = useCallback(() => {
console.log('Refreshing video list');
@@ -51,5 +38,5 @@ export function useVideoList() {
}, [load]);
const videos = useMemo(() => pages.flat(), [pages]);
return { videos, pages, liveRooms, loading, refreshing, load, refresh };
return { videos, pages, loading, refreshing, load, refresh };
}