mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-26 08:29:41 -05:00
address coderabbit comments and make popupPreview work in fullscreen
This commit is contained in:
19 files changed
+211
-69
No files matched your search
@@ -16,7 +16,7 @@
|
||||
<p
|
||||
v-for="(line, index) in lyrics"
|
||||
:key="index"
|
||||
:class="{ active: syncedLyrics && line.timestamp === lyrics[activeLyricIndex]?.timestamp, 'no-seek': !syncedLyrics }"
|
||||
:class="{ active: syncedLyrics && !line.untimed && line.timestamp === lyrics[activeLyricIndex]?.timestamp, 'no-seek': !syncedLyrics }"
|
||||
class="lyric-line"
|
||||
@click.stop="syncedLyrics && seek(line.timestamp)"
|
||||
@keydown.enter.stop.prevent="syncedLyrics && seek(line.timestamp)"
|
||||
@@ -97,12 +97,14 @@ function seek(timestampMs: number) {
|
||||
if (player) player.currentTime = timestampMs / 1000;
|
||||
}
|
||||
|
||||
function findActiveIndex(items: readonly { timestamp: number }[], currentMs: number) {
|
||||
function findActiveIndex(items: readonly { timestamp: number; untimed?: boolean }[], currentMs: number, preferLast = false) {
|
||||
let idx = -1;
|
||||
let best = Number.NEGATIVE_INFINITY;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const timestamp = items.at(i)?.timestamp ?? Number.POSITIVE_INFINITY;
|
||||
if (timestamp <= currentMs && timestamp > best) {
|
||||
const item = items.at(i);
|
||||
if (item?.untimed) continue;
|
||||
const timestamp = item?.timestamp ?? Number.POSITIVE_INFINITY;
|
||||
if (timestamp <= currentMs && (timestamp > best || (preferLast && timestamp === best))) {
|
||||
best = timestamp;
|
||||
idx = i;
|
||||
}
|
||||
@@ -122,7 +124,7 @@ function syncLyrics() {
|
||||
activeWordIndex.value = -1;
|
||||
}
|
||||
const words = first >= 0 ? lyrics.at(first)?.words : null;
|
||||
activeWordIndex.value = words?.length ? findActiveIndex(words, currentMs) : -1;
|
||||
activeWordIndex.value = words?.length ? findActiveIndex(words, currentMs, true) : -1;
|
||||
}
|
||||
|
||||
function scrollToActiveLine() {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<template>
|
||||
<Teleport :to="fullscreenHost || 'body'" :disabled="!fullscreenHost">
|
||||
<div class="popup-preview" v-show="sourceInfo" ref="popup" :style="popupStyle"
|
||||
:class="{ 'popup-preview--3d': sourceInfo && sourceInfo.type === '3d', 'popup-preview--text': sourceInfo && sourceInfo.type === 'text' }">
|
||||
<div v-if="sourceInfo && sourceInfo.type === '3d' && sourceInfo.fbdata" class="popup-preview__3d">
|
||||
@@ -18,15 +19,20 @@
|
||||
</div>
|
||||
<img v-else-if="sourceInfo?.url" :src="sourceInfo.url" :alt="$t('profileSettings.popupPreview')" @load="onImageLoad" />
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { createAsyncComponent } from "@/utils/asyncComponent.js";
|
||||
import { state, getters, mutations } from "@/store/index.ts";
|
||||
import { setImageLoaded } from "@/utils/cache/imageCache.ts";
|
||||
import { useFullscreen } from "@/composables/useFullscreen.ts";
|
||||
|
||||
export default {
|
||||
name: "PopupPreview",
|
||||
setup() {
|
||||
return { fullscreenHost: useFullscreen() };
|
||||
},
|
||||
components: {
|
||||
ThreeJs: createAsyncComponent(() => import('@/views/files/ThreeJs.vue')),
|
||||
TextPreview: createAsyncComponent(() => import('@/components/files/TextPreview.vue')),
|
||||
@@ -114,8 +120,7 @@ export default {
|
||||
const width = popup.offsetWidth || (hasFixedSize ? size3d : 0);
|
||||
const height = popup.offsetHeight || (hasFixedSize ? size3d : 0);
|
||||
const padding = 10;
|
||||
|
||||
const minLeft = getters.isSidebarVisible() ? 320 : padding;
|
||||
const minLeft = getters.isSidebarVisible() && !this.fullscreenHost ? 320 : padding;
|
||||
const minTop = padding + 100;
|
||||
|
||||
if (getters.isMobile()) {
|
||||
@@ -183,6 +188,7 @@ export default {
|
||||
border-color: var(--primaryColor);
|
||||
overflow: hidden;
|
||||
z-index: 1000;
|
||||
text-align: start;
|
||||
transition: top 0.3s ease-in-out, left 0.3s ease-in-out, right 0.3s ease-in-out,
|
||||
margin 0.3s ease-in-out, max-width 0.3s ease-in-out, max-height 0.3s ease-in-out,
|
||||
transform 0.3s ease-in-out;
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
@press="showMobileLyrics = !showMobileLyrics"
|
||||
/>
|
||||
<div v-if="showMobileLyrics" class="lyrics-mobile">
|
||||
<LyricsList compact :lyrics="lyrics" :player="player" />
|
||||
<LyricsList v-model:scroll-locked="mobileLyricsScrollLocked" compact :lyrics="lyrics" :player="player" />
|
||||
</div>
|
||||
</template>
|
||||
<!-- Audio controls -->
|
||||
@@ -115,7 +115,7 @@ import AudioPanel from "@/components/files/AudioPanel.vue";
|
||||
import LyricsList from "@/components/files/LyricsList.vue";
|
||||
import FloatingActionButton from "@/components/settings/FloatingActionButton.vue";
|
||||
import PlayerOverlays from "@/components/player/PlayerOverlays.vue";
|
||||
import { getSettingsElements } from "@/composables/player/settingsElements.ts";
|
||||
import { getSettingsElements, isSettingsMenuOpen } from "@/composables/player/settingsElements.ts";
|
||||
import {
|
||||
readAlbumArtSize,
|
||||
readDesktopPanelOpen,
|
||||
@@ -189,6 +189,7 @@ const albumArtSize = ref(readAlbumArtSize());
|
||||
const isHovering = ref(false);
|
||||
const showDesktopPanel = ref(readDesktopPanelOpen());
|
||||
const showMobileLyrics = ref(readMobileLyricsOpen());
|
||||
const mobileLyricsScrollLocked = ref<boolean | undefined>(false);
|
||||
|
||||
const isMobile = computed(() => getters.isMobile());
|
||||
const filetype = computed(() => getTypeFromMime(props.req.type || ""));
|
||||
@@ -341,9 +342,7 @@ function ensurePlaybackModeApplied(): void {
|
||||
if (!player.value) return;
|
||||
try {
|
||||
const settings = getSettingsElements(player.value);
|
||||
const settingsMenu = settings?.menu;
|
||||
const menuOpen =
|
||||
settingsMenu && settingsMenu.style.display !== "none" && settingsMenu.getAttribute("hidden") === null;
|
||||
const menuOpen = isSettingsMenuOpen(player.value);
|
||||
const needPlayback = settings?.buttons?.playback && !playbackMenuInitialized.value;
|
||||
const needLoop = settings?.buttons?.loop && !loopMenuInitialized.value;
|
||||
if (menuOpen || needPlayback || needLoop) {
|
||||
@@ -382,10 +381,10 @@ function restoreFileSource(): void {
|
||||
async function onFileSwap(newKey?: string, oldKey?: string): Promise<void> {
|
||||
if (!newKey || newKey === oldKey || lifecycle.tornDown) return;
|
||||
const generation = ++swapGeneration;
|
||||
swipe.resetEdgeGestureImmediate();
|
||||
releaseFile();
|
||||
doubleTap.cancelPendingEdgeClick();
|
||||
releaseFile(swipe.resetEdgeGestureImmediate());
|
||||
setMountedFile(props.req?.source, props.req?.path);
|
||||
loadMediaMetadata();
|
||||
refreshMetadata();
|
||||
if (!player.value) {
|
||||
void initializePlayer();
|
||||
return;
|
||||
@@ -398,6 +397,22 @@ async function onFileSwap(newKey?: string, oldKey?: string): Promise<void> {
|
||||
|
||||
watch(() => props.fileKey, onFileSwap, { flush: "pre" });
|
||||
|
||||
let metadataReq: AudioFile | null = null;
|
||||
function refreshMetadata(): void {
|
||||
if (metadataReq === props.req) return;
|
||||
metadataReq = props.req;
|
||||
loadMediaMetadata();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.req,
|
||||
() => {
|
||||
if (lifecycle.tornDown) return;
|
||||
refreshMetadata();
|
||||
if (player.value) updateMediaSessionMetadata(mediaSessionInfo());
|
||||
},
|
||||
);
|
||||
|
||||
async function mountPlayer(): Promise<void> {
|
||||
if (!audioElement.value || player.value || lifecycle.mountInProgress || lifecycle.tornDown) return;
|
||||
lifecycle.mountInProgress = true;
|
||||
@@ -462,7 +477,7 @@ function onPageHide(event: PageTransitionEvent): void {
|
||||
|
||||
onMounted(async () => {
|
||||
lifecycle.mountedFile = resolveMountedFileKey(props.req?.source, props.req?.path);
|
||||
loadMediaMetadata();
|
||||
refreshMetadata();
|
||||
await initializePlayer();
|
||||
if (lifecycle.unmounted || lifecycle.tornDown) return;
|
||||
attachKeyboard();
|
||||
|
||||
@@ -98,7 +98,7 @@ import PreviewNotice from "@/components/files/PreviewNotice.vue";
|
||||
import LoadingSpinner from "@/components/LoadingSpinner.vue";
|
||||
import FloatingActionButton from "@/components/settings/FloatingActionButton.vue";
|
||||
import PlayerOverlays from "@/components/player/PlayerOverlays.vue";
|
||||
import { getPlayerI18n, getSettingsElements } from "@/composables/player/settingsElements.ts";
|
||||
import { getPlayerI18n, getSettingsElements, isSettingsMenuOpen } from "@/composables/player/settingsElements.ts";
|
||||
import {
|
||||
CAPTION_SIZE_IDS,
|
||||
getCaptionSizeLabel,
|
||||
@@ -405,6 +405,7 @@ const swipe = useSwipeNavigationGestures({
|
||||
const { speedToastVisible, speedToastMessage, setupSwipeGestures, teardownSwipeGestures, clearDismissAnimTimers } = swipe;
|
||||
const { onFullscreenEnter, onFullscreenExit } = useFullscreenState({
|
||||
onEnter: swipe.resetEdgeGestureImmediate,
|
||||
getPlayer: () => player.value,
|
||||
});
|
||||
const {
|
||||
lifecycle,
|
||||
@@ -663,10 +664,8 @@ function ensurePlaybackModeApplied(): void {
|
||||
if (!player.value) return;
|
||||
try {
|
||||
const settings = getSettingsElements(player.value);
|
||||
const settingsMenuEl = settings?.menu;
|
||||
const buttons = settings?.buttons;
|
||||
const menuOpen =
|
||||
settingsMenuEl && settingsMenuEl.style.display !== "none" && settingsMenuEl.getAttribute("hidden") === null;
|
||||
const menuOpen = isSettingsMenuOpen(player.value);
|
||||
const needPlayback = buttons?.playback && !playbackMenuInitialized.value;
|
||||
const needCaptionSize = buttons?.captionSize && !captionSizeMenuInitialized;
|
||||
const needLoop = buttons?.loop && !loopMenuInitialized.value;
|
||||
@@ -817,11 +816,12 @@ async function onFileSwap(newKey?: string, oldKey?: string): Promise<void> {
|
||||
return;
|
||||
}
|
||||
const generation = ++swapGeneration;
|
||||
swipe.resetEdgeGestureImmediate();
|
||||
doubleTap.cancelPendingEdgeClick();
|
||||
const heldRate = swipe.resetEdgeGestureImmediate();
|
||||
offerCheckPending.value = false;
|
||||
const isCurrent = () =>
|
||||
generation === swapGeneration && !lifecycle.unmounted && !lifecycle.tornDown && Boolean(player.value);
|
||||
releaseFile();
|
||||
releaseFile(heldRate);
|
||||
resetFilePlaybackState();
|
||||
startRequested.value = false;
|
||||
transcodeOffer.value = null;
|
||||
|
||||
@@ -62,6 +62,7 @@ vi.mock("@/composables/player/useDoubleTapSeek.ts", () => ({
|
||||
flashSkipFeedback: vi.fn(),
|
||||
setupDoubleTapSeek: vi.fn(),
|
||||
teardownDoubleTapSeek: vi.fn(),
|
||||
cancelPendingEdgeClick: vi.fn(),
|
||||
setupRewindForwardFeedback: vi.fn(),
|
||||
clearRewindForwardFeedback: vi.fn(),
|
||||
getGestureSurface: vi.fn(),
|
||||
|
||||
@@ -96,6 +96,7 @@ vi.mock("@/composables/player/useDoubleTapSeek.ts", async () => {
|
||||
flashSkipFeedback: vi.fn(),
|
||||
setupDoubleTapSeek: vi.fn(),
|
||||
teardownDoubleTapSeek: vi.fn(),
|
||||
cancelPendingEdgeClick: vi.fn(),
|
||||
setupRewindForwardFeedback: vi.fn(),
|
||||
clearRewindForwardFeedback: vi.fn(),
|
||||
setupOverlaidHintController: vi.fn(),
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
zIndex: 5 + prompts.indexOf(prompt),
|
||||
}"
|
||||
:aria-label="`${prompt.name}-prompt`"
|
||||
tabindex="-1"
|
||||
>
|
||||
<header
|
||||
class="prompt-taskbar"
|
||||
@@ -240,6 +241,7 @@ export default {
|
||||
for (const p of newVal) {
|
||||
if (!oldIds.has(p.id)) {
|
||||
this.triggerPromptBorderFlash(p.id);
|
||||
this.$nextTick().then(() => this.focusPrompt(p.id));
|
||||
if (this.isEditorPrompt(p)) {
|
||||
this.ensureEditorPromptSize(p.id);
|
||||
}
|
||||
@@ -290,6 +292,41 @@ export default {
|
||||
this.flashBorderTimers = omitObjectProperty(this.flashBorderTimers, id);
|
||||
}, 500));
|
||||
},
|
||||
getFocusable(root) {
|
||||
const selector = 'a[href], button, input, select, textarea, [tabindex]';
|
||||
return Array.from(root.querySelectorAll(selector)).filter(
|
||||
(el) => el.tabIndex >= 0 && !el.disabled && el.getClientRects().length > 0,
|
||||
);
|
||||
},
|
||||
focusPrompt(id) {
|
||||
const root = this.getPromptElement(id);
|
||||
if (!root || root.contains(document.activeElement)) return;
|
||||
const target = this.getFocusable(root).find((el) => !el.classList.contains('prompt-close')) || root;
|
||||
target.focus({ preventScroll: true });
|
||||
},
|
||||
trapTabFocus(event, id) {
|
||||
const root = this.getPromptElement(id);
|
||||
if (!root) return;
|
||||
const items = this.getFocusable(root);
|
||||
if (!items.length) {
|
||||
event.preventDefault();
|
||||
root.focus({ preventScroll: true });
|
||||
return;
|
||||
}
|
||||
const first = items[0];
|
||||
const last = items.at(-1);
|
||||
const active = document.activeElement;
|
||||
if (!root.contains(active) || active === root) {
|
||||
event.preventDefault();
|
||||
(event.shiftKey ? last : first).focus();
|
||||
} else if (event.shiftKey && active === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && active === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
},
|
||||
handleWindowResize() {
|
||||
const maxWidth = window.innerWidth * 0.9;
|
||||
const maxHeight = window.innerHeight * 0.9;
|
||||
@@ -505,7 +542,10 @@ export default {
|
||||
if (this.isBlocked(top)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'Tab') {
|
||||
this.trapTabFocus(event, top.id);
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
|
||||
@@ -14,6 +14,12 @@ export function getSettingsElements(player: Plyr): PlayerSettingsElements | unde
|
||||
return (player.elements as unknown as { settings?: PlayerSettingsElements }).settings;
|
||||
}
|
||||
|
||||
/** Whether Plyr's settings menu is open. */
|
||||
export function isSettingsMenuOpen(player: Plyr | null | undefined): boolean {
|
||||
const menu = player ? getSettingsElements(player)?.menu : undefined;
|
||||
return Boolean(menu && menu.style.display !== "none" && menu.getAttribute("hidden") === null);
|
||||
}
|
||||
|
||||
/** Plyr's resolved config (typed as private); used for the i18n strings of the custom menus. */
|
||||
export function getPlayerI18n(player: Plyr): Record<string, string | undefined> | undefined {
|
||||
return (player as unknown as { config?: { i18n?: Record<string, string | undefined> } }).config?.i18n;
|
||||
|
||||
@@ -30,6 +30,7 @@ export function useDoubleTapSeek({
|
||||
getAudioGestureRoot,
|
||||
requestPlay,
|
||||
}: DoubleTapSeekOptions) {
|
||||
let cancelEdgeClick: (() => void) | null = null;
|
||||
const skipFeedbackVisible = ref(false);
|
||||
const skipFeedbackSide = ref<"left" | "right">("left");
|
||||
const skipFeedbackIcon = ref("replay_10");
|
||||
@@ -175,6 +176,7 @@ export function useDoubleTapSeek({
|
||||
edgeClickToggleTimer = null;
|
||||
}
|
||||
};
|
||||
cancelEdgeClick = clearEdgeClickToggleTimer;
|
||||
const onClick = (event: MouseEvent) => {
|
||||
if (isControlOrMenuTarget(event.target)) return;
|
||||
if (Date.now() < ignoreClickUntil) {
|
||||
@@ -367,6 +369,7 @@ export function useDoubleTapSeek({
|
||||
flashSkipFeedback,
|
||||
setupDoubleTapSeek,
|
||||
teardownDoubleTapSeek,
|
||||
cancelPendingEdgeClick: () => cancelEdgeClick?.(),
|
||||
setupRewindForwardFeedback,
|
||||
clearRewindForwardFeedback,
|
||||
setupOverlaidHintController,
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type Plyr from "plyr";
|
||||
import { onBeforeUnmount, ref } from "vue";
|
||||
import { isSettingsMenuOpen } from "@/composables/player/settingsElements.ts";
|
||||
import { state } from "@/store/index.ts";
|
||||
|
||||
interface FullscreenStateOptions {
|
||||
onEnter?: () => void;
|
||||
getPlayer?: () => Plyr | null | undefined;
|
||||
}
|
||||
|
||||
/** Keyboard Lock API (this only works in chromium, not in firefox sadly) */
|
||||
@@ -12,14 +15,6 @@ function getKeyboard(): KeyboardWithLock | undefined {
|
||||
return (navigator as Navigator & { keyboard?: KeyboardWithLock }).keyboard;
|
||||
}
|
||||
|
||||
function onEscapeKey(event: KeyboardEvent): void {
|
||||
if (event.key !== "Escape" || state.prompts.length > 0 || state.isSearchActive) return;
|
||||
if (!document.fullscreenElement) return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
void document.exitFullscreen();
|
||||
}
|
||||
|
||||
const ORIENTATION_LOCK_POLICY_ERRORS = new Set([
|
||||
"NotSupportedError",
|
||||
"SecurityError",
|
||||
@@ -28,9 +23,17 @@ const ORIENTATION_LOCK_POLICY_ERRORS = new Set([
|
||||
]);
|
||||
|
||||
/** Tracks the player's fullscreen state and frees the screen orientation while in fullscreen. */
|
||||
export function useFullscreenState({ onEnter }: FullscreenStateOptions = {}) {
|
||||
export function useFullscreenState({ onEnter, getPlayer }: FullscreenStateOptions = {}) {
|
||||
const isFullscreen = ref(false);
|
||||
|
||||
function onEscapeKey(event: KeyboardEvent): void {
|
||||
if (event.key !== "Escape" || state.prompts.length > 0 || state.isSearchActive) return;
|
||||
if (!document.fullscreenElement || isSettingsMenuOpen(getPlayer?.())) return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
void document.exitFullscreen();
|
||||
}
|
||||
|
||||
function lockEscape(): void {
|
||||
getKeyboard()
|
||||
?.lock?.(["Escape"])
|
||||
|
||||
@@ -24,7 +24,7 @@ export function useMediaKeyboard(options: MediaKeyboardOptions) {
|
||||
return;
|
||||
}
|
||||
// 'P' and 'L' keys for playback mode and loop
|
||||
if (key === "p" || key === "l") {
|
||||
if ((key === "p" || key === "l") && state.prompts.length === 0) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
if (key === "p") options.cyclePlaybackModes();
|
||||
@@ -41,6 +41,7 @@ export function useMediaKeyboard(options: MediaKeyboardOptions) {
|
||||
// "Q" open/close panel on desktop audio, queue prompt on video
|
||||
if (key === "q") {
|
||||
if (options.getPreviewType() === "audio" && !getters.isMobile()) {
|
||||
if (state.prompts.length > 0) return;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
options.toggleDesktopPanel();
|
||||
|
||||
@@ -268,9 +268,9 @@ export function useMediaPlayer(options: MediaPlayerOptions) {
|
||||
}
|
||||
|
||||
/** Stops the current file and keeps the instance alive; the playback rate survives the `load()`. */
|
||||
function releaseFile(): void {
|
||||
function releaseFile(intendedRate?: number): void {
|
||||
const media = getActiveMediaElement();
|
||||
if (media) media.defaultPlaybackRate = media.playbackRate;
|
||||
if (media) media.defaultPlaybackRate = intendedRate ?? media.playbackRate;
|
||||
stopMediaElement(media);
|
||||
resetCaptionTrack();
|
||||
options.onReleaseFile?.();
|
||||
|
||||
@@ -233,6 +233,7 @@ export function useSwipeNavigationGestures({
|
||||
}, 240);
|
||||
}
|
||||
function resetSwipeVisualState() {
|
||||
teardownSwipeMouseDocListeners();
|
||||
clearDismissAnimTimers();
|
||||
clearSnapBackTimer();
|
||||
swipeSuppressedTouchId = null;
|
||||
@@ -249,7 +250,8 @@ export function useSwipeNavigationGestures({
|
||||
applySwipeTransform();
|
||||
mutations.setNavigationGestureHint({});
|
||||
}
|
||||
function resetEdgeGestureImmediate() {
|
||||
function resetEdgeGestureImmediate(): number | undefined {
|
||||
const heldFromRate = gestures.longPressTriggered.value ? gestures.longPressPreviousSpeed.value : undefined;
|
||||
gestures.clearLongPressTimer();
|
||||
gestures.longPressPending.value = false;
|
||||
if (gestures.longPressTriggered.value) {
|
||||
@@ -258,6 +260,7 @@ export function useSwipeNavigationGestures({
|
||||
resetSwipeVisualState();
|
||||
gestures.clearEdgeTapGestureState();
|
||||
gestures.clearSkipNextTap();
|
||||
return heldFromRate;
|
||||
}
|
||||
function clearDismissAnimTimers() {
|
||||
if (dismissCloseTimer) {
|
||||
|
||||
@@ -161,6 +161,7 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
const transcodePlayback = ref<TranscodePlaybackController | null>(null);
|
||||
const transcodeSwitchInProgress = ref(false);
|
||||
let transcodeSwitchOwner: symbol | null = null;
|
||||
let modeSwitchToken: symbol | null = null;
|
||||
const transcodeMode = ref("native");
|
||||
const transcodeOffer = ref<TranscodeOffer | null>(null);
|
||||
/** The user accepted the offer: play through transcoding from the start. */
|
||||
@@ -872,7 +873,7 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
invalidateOfferRequest();
|
||||
const startSource = getReq()?.source;
|
||||
const startPath = getReq()?.path;
|
||||
const preparationId = startPreparationId;
|
||||
const preparationId = ++startPreparationId;
|
||||
const switchToken = Symbol("transcodeSwitch");
|
||||
const manageSwitch =
|
||||
manageSwitchState && (!transcodeSwitchInProgress.value || transcodeSwitchOwner !== null);
|
||||
@@ -1057,6 +1058,7 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
const currentTime = player.value?.currentTime ?? 0;
|
||||
const shouldPlay = autoplay ?? !!player.value?.playing;
|
||||
transcodeLog("switchToNativePlayback", { currentTime, shouldPlay });
|
||||
const generation = fileGeneration;
|
||||
|
||||
// Release the HLS source even when a shared controller owns it.
|
||||
teardownTranscodePlayback({ stopSession: true });
|
||||
@@ -1069,6 +1071,7 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
media.removeAttribute("src");
|
||||
}
|
||||
await nextTick();
|
||||
if (generation !== fileGeneration || isTornDown()) return;
|
||||
|
||||
// Restore the playhead through the resume path, which waits for the
|
||||
// new source to report metadata before seeking
|
||||
@@ -1111,13 +1114,21 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
shouldAutoplay: shouldAutoplay.value,
|
||||
currentTime: player.value?.currentTime,
|
||||
});
|
||||
const switchToken = Symbol("modeSwitch");
|
||||
modeSwitchToken = switchToken;
|
||||
transcodeSwitchInProgress.value = true;
|
||||
const releaseModeSwitch = () => {
|
||||
if (modeSwitchToken === switchToken) {
|
||||
modeSwitchToken = null;
|
||||
transcodeSwitchInProgress.value = false;
|
||||
}
|
||||
};
|
||||
const generation = fileGeneration;
|
||||
// Capture before mode/teardown changes so same-file profile switches always
|
||||
// send replaceSessionId even if the controller is mid-start.
|
||||
const replaceSessionId = transcodePlayback.value?.sessionController?.session?.id ?? (await resolveReuseSessionId());
|
||||
if (generation !== fileGeneration) {
|
||||
transcodeSwitchInProgress.value = false;
|
||||
releaseModeSwitch();
|
||||
return;
|
||||
}
|
||||
transcodeMode.value = mode;
|
||||
@@ -1135,19 +1146,25 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
manageSwitchState: false,
|
||||
});
|
||||
} else if (needsTranscodeFirst(transcodeProbeParams())) {
|
||||
transcodeOfferEmitted = false;
|
||||
teardownTranscodePlayback({ stopSession: true });
|
||||
let status: TranscodeStatus | null = null;
|
||||
try {
|
||||
const status = await getTranscodeSessions();
|
||||
if (generation === fileGeneration) {
|
||||
status = await getTranscodeSessions();
|
||||
} catch (err) {
|
||||
console.error("Failed to check transcode sessions:", err);
|
||||
}
|
||||
if (generation === fileGeneration) {
|
||||
transcodeOfferEmitted = false;
|
||||
if (status) {
|
||||
showTranscodeOffer(normalizeTranscodeSessionStatus(status, {
|
||||
source: getReq()?.source,
|
||||
path: getReq()?.path,
|
||||
}),
|
||||
);
|
||||
} else if (transcodeActive.value) {
|
||||
transcodeMode.value = previousMode;
|
||||
} else {
|
||||
showTranscodeOffer({ enabled: true, canStart: true, sessions: [] });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to check transcode sessions:", err);
|
||||
}
|
||||
} else {
|
||||
await switchToNativePlayback({ autoplay: wasPlaying });
|
||||
@@ -1166,7 +1183,7 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
transcodeSwitchInProgress.value = false;
|
||||
releaseModeSwitch();
|
||||
if (generation === fileGeneration) {
|
||||
syncPlaybackUrl({ transcodeMode: transcodeMode.value });
|
||||
}
|
||||
@@ -1315,6 +1332,9 @@ export function useTranscodePlayback(options: UseTranscodePlaybackOptions) {
|
||||
cancelNativeResume?.();
|
||||
invalidateOfferRequest();
|
||||
startPreparationId++;
|
||||
modeSwitchToken = null;
|
||||
transcodeSwitchOwner = null;
|
||||
transcodeSwitchInProgress.value = false;
|
||||
videoStreamAttached.value = false;
|
||||
resumeSnapshot.value = null;
|
||||
resumeSeekSeconds.value = null;
|
||||
|
||||
@@ -9,6 +9,7 @@ import { goToItem, removeLastDir } from "@/utils/url.js";
|
||||
|
||||
interface PreviewNavigationOptions {
|
||||
onBeforeTeardown?: () => void;
|
||||
canDelete?: () => boolean;
|
||||
}
|
||||
|
||||
/** Listing context, prev/next nav, close and key handling */
|
||||
@@ -16,6 +17,8 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
const listing = ref<FileListItem[] | null>(null);
|
||||
const listingKey = ref<string | null>(null);
|
||||
const listingIsFailureFallback = ref(false);
|
||||
let unmounted = false;
|
||||
let previewGeneration = 0;
|
||||
|
||||
function listingContextKey(directoryPath: string): string {
|
||||
return getters.isShare()
|
||||
@@ -28,7 +31,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
* context changed, refreshes the view token, then adopts the listing that
|
||||
* came with the request, if any.
|
||||
*/
|
||||
async function loadListingContext() {
|
||||
async function loadListingContext(isStale?: () => boolean) {
|
||||
const currentDirectoryPath = removeLastDir(state.req.path) || "/";
|
||||
const currentListingKey = listingContextKey(currentDirectoryPath);
|
||||
if (listingKey.value !== currentListingKey) {
|
||||
@@ -47,7 +50,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
console.warn("Failed to refresh view token for preview:", err);
|
||||
}
|
||||
}
|
||||
|
||||
if (unmounted || isStale?.()) return;
|
||||
if (!listing.value || listingIsFailureFallback.value) {
|
||||
// The request may have moved to another directory while the token refresh was pending.
|
||||
if (listingContextKey(removeLastDir(state.req.path) || "/") !== currentListingKey) {
|
||||
@@ -65,7 +68,9 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
}
|
||||
|
||||
/** Loads the folder listing if needed and sets up prev/next navigation for the current file. */
|
||||
async function updatePreview() {
|
||||
async function updatePreview(isStale?: () => boolean) {
|
||||
const generation = ++previewGeneration;
|
||||
const isInactive = () => unmounted || generation !== previewGeneration || !!isStale?.();
|
||||
const expectedPath = state.req.path;
|
||||
let directoryPath = removeLastDir(state.req.path);
|
||||
|
||||
@@ -88,6 +93,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
res = await resourcesApi.fetchFiles(state.req.source, directoryPath);
|
||||
}
|
||||
if (
|
||||
isInactive() ||
|
||||
state.req.path !== expectedPath ||
|
||||
listingContextKey(directoryPath) !== expectedListingKey
|
||||
) {
|
||||
@@ -97,6 +103,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
listingIsFailureFallback.value = false;
|
||||
} catch (error) {
|
||||
if (
|
||||
isInactive() ||
|
||||
state.req.path !== expectedPath ||
|
||||
listingContextKey(directoryPath) !== expectedListingKey
|
||||
) {
|
||||
@@ -111,7 +118,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
listingIsFailureFallback.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isInactive()) return;
|
||||
if (!listing.value) {
|
||||
listing.value = [state.req as FileListItem];
|
||||
}
|
||||
@@ -238,6 +245,9 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
close();
|
||||
break;
|
||||
case "Delete":
|
||||
if (options.canDelete && !options.canDelete()) {
|
||||
break;
|
||||
}
|
||||
showDeletePrompt();
|
||||
break;
|
||||
}
|
||||
@@ -248,6 +258,7 @@ export function usePreviewNavigation(options: PreviewNavigationOptions = {}) {
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
unmounted = true;
|
||||
window.removeEventListener("keydown", keyEvent);
|
||||
options.onBeforeTeardown?.();
|
||||
mutations.clearNavigation();
|
||||
|
||||
@@ -310,7 +310,9 @@ function attachNativeHls({
|
||||
video.addEventListener('canplay', onReady);
|
||||
video.addEventListener('error', onError);
|
||||
timeoutId = setTimeout(onTimeout, deadlineMs);
|
||||
video.preload = 'auto';
|
||||
video.src = playlistURL;
|
||||
video.load();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -379,6 +381,11 @@ export function attachHlsToVideo({
|
||||
let settled = false;
|
||||
let readyToPlay = false;
|
||||
let startApplied = false;
|
||||
let playbackBegan = false;
|
||||
const onPlaying = () => {
|
||||
playbackBegan = true;
|
||||
};
|
||||
video?.addEventListener('playing', onPlaying);
|
||||
let bufferedFrags = 0;
|
||||
// The synthetic VOD playlist lists the full media duration; a single
|
||||
// buffered fragment is enough to start playback.
|
||||
@@ -398,7 +405,7 @@ export function attachHlsToVideo({
|
||||
: Number.isFinite(data?.frag?.start)
|
||||
? data.frag.start
|
||||
: (Number.isFinite(initialStart) && initialStart >= 0 ? initialStart : 0);
|
||||
const shouldAutoplay = playbackStarted ? !video.paused && !video.ended : undefined;
|
||||
const shouldAutoplay = playbackBegan ? !video.paused && !video.ended : undefined;
|
||||
transcodeWarn('hls requesting transcode session recovery', {
|
||||
reason,
|
||||
resumeAt,
|
||||
@@ -435,6 +442,7 @@ export function attachHlsToVideo({
|
||||
let hardTimeoutId = null;
|
||||
let stallTimeoutId = null;
|
||||
let fragmentProgressed = false;
|
||||
let awaitingFirstByte = false;
|
||||
|
||||
const finish = (kind, payload) => {
|
||||
if (settled) {
|
||||
@@ -480,15 +488,19 @@ export function attachHlsToVideo({
|
||||
if (remaining <= 0) {
|
||||
return;
|
||||
}
|
||||
const limitMs = fragmentProgressed
|
||||
? ATTACH_STALL_TIMEOUT_MS
|
||||
: ATTACH_STARTUP_STALL_TIMEOUT_MS;
|
||||
let limitMs = ATTACH_STARTUP_STALL_TIMEOUT_MS;
|
||||
if (awaitingFirstByte) {
|
||||
limitMs = FRAG_FIRST_BYTE_TIMEOUT_MS;
|
||||
} else if (fragmentProgressed) {
|
||||
limitMs = ATTACH_STALL_TIMEOUT_MS;
|
||||
}
|
||||
stallTimeoutId = setTimeout(onAttachTimeout, Math.min(limitMs, remaining));
|
||||
};
|
||||
const noteFragmentResponseStarted = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
awaitingFirstByte = false;
|
||||
clearTimeout(stallTimeoutId);
|
||||
const remaining = deadlineMs - (performance.now() - attachStartedAt);
|
||||
if (remaining <= 0) {
|
||||
@@ -597,6 +609,7 @@ export function attachHlsToVideo({
|
||||
const cleanup = () => {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
video?.removeEventListener('playing', onPlaying);
|
||||
transcodeLog('hls destroy', { sessionId: session?.id });
|
||||
// Detach before destroy: destroying with a live MediaSource attached can
|
||||
// leave the element feeding buffered audio after the preview unmounts.
|
||||
@@ -649,15 +662,15 @@ export function attachHlsToVideo({
|
||||
|
||||
hls.on(Hls.Events.FRAG_LOADING, (_event, data) => {
|
||||
transcodeLog('hls frag loading', { frag: describeFrag(data?.frag) });
|
||||
if (!fragmentProgressed) {
|
||||
noteAttachProgress();
|
||||
}
|
||||
awaitingFirstByte = true;
|
||||
noteAttachProgress();
|
||||
});
|
||||
|
||||
hls.on(Hls.Events.FRAG_LOADED, (_event, data) => {
|
||||
// First byte of the seek fragment arrived: the producer is making
|
||||
// progress, so push the stall guard out.
|
||||
fragmentProgressed = true;
|
||||
awaitingFirstByte = false;
|
||||
noteAttachProgress();
|
||||
transcodeLog('hls frag loaded', {
|
||||
frag: describeFrag(data?.frag),
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface LyricWord {
|
||||
export interface LyricLine {
|
||||
text: string;
|
||||
timestamp: number;
|
||||
untimed?: true;
|
||||
words?: LyricWord[];
|
||||
}
|
||||
|
||||
@@ -90,7 +91,7 @@ function parseLrc(raw: string): LyricLine[] {
|
||||
if (isMetadataTag(line)) continue;
|
||||
const tag = matchLrcTags(line);
|
||||
if (!tag) {
|
||||
lines.push({ text: line.replace(INLINE_TAG_RE, "").trim(), timestamp: 0 });
|
||||
lines.push({ text: line.replace(INLINE_TAG_RE, "").trim(), timestamp: 0, untimed: true });
|
||||
continue;
|
||||
}
|
||||
const text = tag.text.replace(INLINE_TAG_RE, "").trim();
|
||||
@@ -109,7 +110,7 @@ function parseElrc(raw: string): LyricLine[] {
|
||||
if (isMetadataTag(line)) continue;
|
||||
const tag = matchLrcTags(line);
|
||||
if (!tag) {
|
||||
lines.push({ text: line.replace(INLINE_TAG_RE, "").trim(), timestamp: 0, words: [] });
|
||||
lines.push({ text: line.replace(INLINE_TAG_RE, "").trim(), timestamp: 0, untimed: true, words: [] });
|
||||
continue;
|
||||
}
|
||||
const rawWords = splitWordTags(tag.text).map((word) => ({ ...word, text: word.text.trim() }));
|
||||
|
||||
@@ -91,6 +91,7 @@ let mediaEnrichDoneForPath: string | null = null;
|
||||
let loadOwner = 0;
|
||||
let loadIdentity: string | null = null;
|
||||
let inFlightIdentity: string | null = null;
|
||||
let inFlightSubtitleInputs: string | null = null;
|
||||
/** enables autoplay for queue navigation even when autoplayMedia pref is off */
|
||||
const playbackStarted = ref(false);
|
||||
|
||||
@@ -107,6 +108,7 @@ const {
|
||||
audioRef.value?.destroy?.();
|
||||
videoRef.value?.destroy?.();
|
||||
},
|
||||
canDelete: () => (committed.value ? committed.value.key === mediaIdentity() : !avMetadataLoading.value),
|
||||
});
|
||||
|
||||
const isDarkMode = computed(() => getters.isDarkMode());
|
||||
@@ -192,6 +194,10 @@ async function attachDirMediaMetadata(
|
||||
}
|
||||
}
|
||||
|
||||
function subtitleInputsFor(req: ReqObject): string {
|
||||
return JSON.stringify((req.subtitles ?? []).map((track) => [track?.name, track?.embedded, track?.srclang || track?.language]));
|
||||
}
|
||||
|
||||
async function loadMediaForReq() {
|
||||
if (!getters.isLoggedIn() && !getters.isShare()) {
|
||||
return;
|
||||
@@ -205,8 +211,12 @@ async function loadMediaForReq() {
|
||||
loadOwner += 1;
|
||||
} else if (inFlightIdentity === identity) {
|
||||
// the running load commits `state.req` as it is at the end, so it sees this update too
|
||||
return;
|
||||
if (inFlightSubtitleInputs === null || inFlightSubtitleInputs === subtitleInputsFor(state.req)) {
|
||||
return;
|
||||
}
|
||||
loadOwner += 1;
|
||||
}
|
||||
inFlightSubtitleInputs = null;
|
||||
const owner = loadOwner;
|
||||
const isStale = () => owner !== loadOwner;
|
||||
inFlightIdentity = identity;
|
||||
@@ -226,7 +236,7 @@ async function loadMediaForReq() {
|
||||
}
|
||||
|
||||
async function loadAndCommit(identity: string, isStale: () => boolean) {
|
||||
await loadListingContext();
|
||||
await loadListingContext(isStale);
|
||||
if (isStale()) {
|
||||
return;
|
||||
}
|
||||
@@ -252,7 +262,7 @@ async function loadAndCommit(identity: string, isStale: () => boolean) {
|
||||
mediaEnrichDoneForPath = null;
|
||||
}
|
||||
|
||||
await updatePreview();
|
||||
await updatePreview(isStale);
|
||||
if (isStale()) {
|
||||
return;
|
||||
}
|
||||
@@ -272,7 +282,8 @@ async function loadAndCommit(identity: string, isStale: () => boolean) {
|
||||
const kind = previewType.value as "audio" | "video";
|
||||
const current = committed.value;
|
||||
const reuse = current?.key === identity && current.kind === kind ? current : null;
|
||||
const subtitleInputs = JSON.stringify((state.req.subtitles ?? []).map((track) => [track?.name, track?.embedded, track?.srclang || track?.language]));
|
||||
const subtitleInputs = subtitleInputsFor(state.req);
|
||||
inFlightSubtitleInputs = subtitleInputs;
|
||||
const lyricsInputs = kind === "audio" && state.req.metadata?.hasLyrics ? "lyrics" : "";
|
||||
const reuseSubtitles = reuse?.subtitleInputs === subtitleInputs ? reuse : null;
|
||||
const reuseLyrics = reuse?.lyricsInputs === lyricsInputs ? reuse : null;
|
||||
|
||||
@@ -211,9 +211,14 @@ export function nativeVideo(page: Page) {
|
||||
return page.locator(".media-player video").first();
|
||||
}
|
||||
|
||||
/** Preview transcode-offer screen (not the in-player settings menu). */
|
||||
function previewTranscodeOfferButton(page: Page) {
|
||||
return page.locator(".preview-notice button[aria-label='Transcode']");
|
||||
/** Preview notice shown instead of the player */
|
||||
function previewNotice(page: Page) {
|
||||
return page.locator(".preview-notice");
|
||||
}
|
||||
|
||||
/** The native video inside Plyr */
|
||||
function plyrVideo(page: Page) {
|
||||
return page.locator(".media-player .plyr video").first();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,15 +228,15 @@ function previewTranscodeOfferButton(page: Page) {
|
||||
export async function waitForNativePlayerMounted(page: Page) {
|
||||
await expect(page.locator(".av-preview-loading")).toHaveCount(0, { timeout: 30_000 });
|
||||
await expect.poll(async () => {
|
||||
if (await previewTranscodeOfferButton(page).count()) {
|
||||
return "offer";
|
||||
if (await previewNotice(page).isVisible()) {
|
||||
return "notice";
|
||||
}
|
||||
if (await page.locator(".media-player").count()) {
|
||||
if (await plyrVideo(page).isVisible()) {
|
||||
return "player";
|
||||
}
|
||||
return "pending";
|
||||
}, { timeout: 30_000, intervals: [100, 250, 500, 1000] }).toBe("player");
|
||||
await expect(nativeVideo(page)).toBeAttached({ timeout: 15_000 });
|
||||
await expect(nativeVideo(page)).toBeVisible({ timeout: 15_000 });
|
||||
}
|
||||
|
||||
async function clickPlayControl(page: Page) {
|
||||
|
||||
Reference in new issue
Block a user