frontend: add OXC lint/format setup and apply semicolon fixes
This commit is contained in:
+5
-1
@@ -2,7 +2,11 @@
|
||||
"tasks": {
|
||||
"dev": "deno run -A npm:vite",
|
||||
"build": "deno run -A npm:vue-tsc --noEmit && deno run -A npm:vite build",
|
||||
"preview": "deno run -A npm:vite preview"
|
||||
"preview": "deno run -A npm:vite preview",
|
||||
"lint": "deno run -A npm:oxlint --vue-plugin --import-plugin src",
|
||||
"lint:fix": "deno task lint --fix",
|
||||
"format": "deno run -A npm:oxfmt --config oxfmt.json src",
|
||||
"format:check": "deno run -A npm:oxfmt --config oxfmt.json --check src"
|
||||
},
|
||||
"imports": {
|
||||
"vue": "npm:vue@^3.4.0"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"semi": false,
|
||||
"ignorePatterns": []
|
||||
}
|
||||
@@ -6,7 +6,11 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"lint": "oxlint --vue-plugin --import-plugin src",
|
||||
"lint:fix": "npm run lint -- --fix",
|
||||
"format": "oxfmt --config oxfmt.json src",
|
||||
"format:check": "oxfmt --config oxfmt.json --check src"
|
||||
},
|
||||
"dependencies": {
|
||||
"country-flag-icons": "^1.6.17",
|
||||
@@ -15,6 +19,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.0.0",
|
||||
"oxfmt": "^0.51.0",
|
||||
"oxlint": "^1.66.0",
|
||||
"typescript": "^5.3.0",
|
||||
"vite": "^5.0.0",
|
||||
"vue-tsc": "^2.0.0"
|
||||
|
||||
+655
-624
File diff suppressed because it is too large
Load Diff
+100
-95
@@ -1,99 +1,97 @@
|
||||
|
||||
|
||||
export interface PlayerStatus {
|
||||
remote: boolean;
|
||||
remote: boolean
|
||||
}
|
||||
|
||||
export interface RootStatus {
|
||||
root_id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
status: string;
|
||||
error: string | null;
|
||||
movies: number;
|
||||
series: number;
|
||||
root_id: string
|
||||
name: string
|
||||
path: string
|
||||
status: string
|
||||
error: string | null
|
||||
movies: number
|
||||
series: number
|
||||
}
|
||||
|
||||
export interface RootsResponse {
|
||||
roots: RootStatus[];
|
||||
roots: RootStatus[]
|
||||
}
|
||||
|
||||
export function normalizeMediaPath(input: string): string {
|
||||
return input
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^[A-Za-z]:\//, '')
|
||||
.replace(/^\/+/, '');
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/^[A-Za-z]:\//, "")
|
||||
.replace(/^\/+/, "")
|
||||
}
|
||||
|
||||
export function isVideoPath(path: string | null | undefined): boolean {
|
||||
return Boolean(path && /\.(webm|mp4|mkv|avi|mov)$/i.test(path));
|
||||
return Boolean(path && /\.(webm|mp4|mkv|avi|mov)$/i.test(path))
|
||||
}
|
||||
|
||||
export interface VideoSourceAttributes {
|
||||
type: string;
|
||||
codecs: string;
|
||||
type: string
|
||||
codecs: string
|
||||
}
|
||||
|
||||
export function isSafariBrowser(): boolean {
|
||||
if (typeof navigator === 'undefined') {
|
||||
return false;
|
||||
if (typeof navigator === "undefined") {
|
||||
return false
|
||||
}
|
||||
|
||||
const ua = navigator.userAgent;
|
||||
return /Safari/i.test(ua) && !/Chrome|Chromium|CriOS|Edg|OPR|FxiOS/i.test(ua);
|
||||
const ua = navigator.userAgent
|
||||
return /Safari/i.test(ua) && !/Chrome|Chromium|CriOS|Edg|OPR|FxiOS/i.test(ua)
|
||||
}
|
||||
|
||||
export function getVideoPreviewUrl(url: string): string {
|
||||
if (!url || !isSafariBrowser()) {
|
||||
return url;
|
||||
return url
|
||||
}
|
||||
|
||||
if (url.includes('#')) {
|
||||
return url;
|
||||
if (url.includes("#")) {
|
||||
return url
|
||||
}
|
||||
|
||||
// Safari often needs a tiny time offset to paint the first frame before playback.
|
||||
return `${url}#t=0.001`;
|
||||
return `${url}#t=0.001`
|
||||
}
|
||||
|
||||
export function getVideoSourceAttributes(path: string | null | undefined): VideoSourceAttributes {
|
||||
if (!path) {
|
||||
return { type: 'video/mp4', codecs: 'hvc1' };
|
||||
return { type: "video/mp4", codecs: "hvc1" }
|
||||
}
|
||||
|
||||
if (/\.webm$/i.test(path)) {
|
||||
return { type: 'video/webm', codecs: 'av1' };
|
||||
return { type: "video/webm", codecs: "av1" }
|
||||
}
|
||||
|
||||
if (/\.mp4$/i.test(path) || /\.m4v$/i.test(path)) {
|
||||
return { type: 'video/mp4', codecs: 'hvc1' };
|
||||
return { type: "video/mp4", codecs: "hvc1" }
|
||||
}
|
||||
|
||||
if (/\.mov$/i.test(path)) {
|
||||
return { type: 'video/quicktime', codecs: 'hvc1' };
|
||||
return { type: "video/quicktime", codecs: "hvc1" }
|
||||
}
|
||||
|
||||
if (/\.avi$/i.test(path)) {
|
||||
return { type: 'video/x-msvideo', codecs: '' };
|
||||
return { type: "video/x-msvideo", codecs: "" }
|
||||
}
|
||||
|
||||
if (/\.mkv$/i.test(path)) {
|
||||
return { type: 'video/x-matroska', codecs: '' };
|
||||
return { type: "video/x-matroska", codecs: "" }
|
||||
}
|
||||
|
||||
return { type: 'video/mp4', codecs: 'hvc1' };
|
||||
return { type: "video/mp4", codecs: "hvc1" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch active roots and their statuses
|
||||
*/
|
||||
export async function fetchRoots(): Promise<RootStatus[]> {
|
||||
const response = await fetch('/api/roots');
|
||||
const response = await fetch("/api/roots")
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load roots: ${response.statusText}`);
|
||||
throw new Error(`Failed to load roots: ${response.statusText}`)
|
||||
}
|
||||
const data = await response.json();
|
||||
return data.roots || [];
|
||||
const data = await response.json()
|
||||
return data.roots || []
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,59 +99,63 @@ export async function fetchRoots(): Promise<RootStatus[]> {
|
||||
*/
|
||||
export async function fetchResumePositions(): Promise<Record<string, number>> {
|
||||
try {
|
||||
const roots = await fetchRoots();
|
||||
const merged: Record<string, number> = {};
|
||||
const roots = await fetchRoots()
|
||||
const merged: Record<string, number> = {}
|
||||
await Promise.all(
|
||||
roots.map(async (root) => {
|
||||
const response = await fetch(`/api/roots/${encodeURIComponent(root.root_id)}/playback/resume-positions`);
|
||||
if (!response.ok) return;
|
||||
const data = await response.json().catch(() => ({}));
|
||||
const positions = data?.resume_positions;
|
||||
if (positions && typeof positions === 'object') {
|
||||
Object.assign(merged, positions);
|
||||
const response = await fetch(
|
||||
`/api/roots/${encodeURIComponent(root.root_id)}/playback/resume-positions`,
|
||||
)
|
||||
if (!response.ok) return
|
||||
const data = await response.json().catch(() => ({}))
|
||||
const positions = data?.resume_positions
|
||||
if (positions && typeof positions === "object") {
|
||||
Object.assign(merged, positions)
|
||||
}
|
||||
})
|
||||
);
|
||||
return merged;
|
||||
}),
|
||||
)
|
||||
return merged
|
||||
} catch {
|
||||
return {};
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the full root set atomically
|
||||
*/
|
||||
export async function replaceRoots(roots: Record<string, string>): Promise<{ accepted: RootStatus[]; failed: unknown[] }> {
|
||||
const response = await fetch('/api/roots', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
export async function replaceRoots(
|
||||
roots: Record<string, string>,
|
||||
): Promise<{ accepted: RootStatus[]; failed: unknown[] }> {
|
||||
const response = await fetch("/api/roots", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ roots }),
|
||||
});
|
||||
})
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({ detail: response.statusText }));
|
||||
throw new Error(err.detail || response.statusText);
|
||||
const err = await response.json().catch(() => ({ detail: response.statusText }))
|
||||
throw new Error(err.detail || response.statusText)
|
||||
}
|
||||
return response.json();
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Play a media file with the system's default player
|
||||
*/
|
||||
export async function playMedia(rootId: string, filePath: string): Promise<void> {
|
||||
const normalizedPath = normalizeMediaPath(filePath);
|
||||
const normalizedPath = normalizeMediaPath(filePath)
|
||||
try {
|
||||
const response = await fetch(`/api/roots/${encodeURIComponent(rootId)}/play`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ file_path: normalizedPath }),
|
||||
});
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.detail || response.statusText);
|
||||
const error = await response.json()
|
||||
throw new Error(error.detail || response.statusText)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Play media error:', e);
|
||||
alert(`Failed to play media.\n\n${e}`);
|
||||
console.error("Play media error:", e)
|
||||
alert(`Failed to play media.\n\n${e}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,20 +163,20 @@ export async function playMedia(rootId: string, filePath: string): Promise<void>
|
||||
* Open a folder in the system file manager
|
||||
*/
|
||||
export async function openFolder(rootId: string, folderPath: string): Promise<void> {
|
||||
const normalizedPath = normalizeMediaPath(folderPath);
|
||||
const normalizedPath = normalizeMediaPath(folderPath)
|
||||
try {
|
||||
const response = await fetch(`/api/roots/${encodeURIComponent(rootId)}/open-folder`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ folder_path: normalizedPath }),
|
||||
});
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.detail || response.statusText);
|
||||
const error = await response.json()
|
||||
throw new Error(error.detail || response.statusText)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Open folder error:', e);
|
||||
alert(`Failed to open folder.\n\n${e}`);
|
||||
console.error("Open folder error:", e)
|
||||
alert(`Failed to open folder.\n\n${e}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,11 +184,11 @@ export async function openFolder(rootId: string, folderPath: string): Promise<vo
|
||||
* Return player integration capabilities for the current OS.
|
||||
*/
|
||||
export async function getPlayerStatus(): Promise<PlayerStatus> {
|
||||
const response = await fetch('/api/player/status');
|
||||
const response = await fetch("/api/player/status")
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load player status: ${response.statusText}`);
|
||||
throw new Error(`Failed to load player status: ${response.statusText}`)
|
||||
}
|
||||
return response.json();
|
||||
return response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,12 +196,12 @@ export async function getPlayerStatus(): Promise<PlayerStatus> {
|
||||
*/
|
||||
export async function isMpcBeReachable(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch('/api/mpcbe/status');
|
||||
if (!response.ok) return false;
|
||||
const data = await response.json().catch(() => ({}));
|
||||
return Boolean(data.reachable);
|
||||
const response = await fetch("/api/mpcbe/status")
|
||||
if (!response.ok) return false
|
||||
const data = await response.json().catch(() => ({}))
|
||||
return Boolean(data.reachable)
|
||||
} catch {
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,33 +214,36 @@ export async function isMpcBeReachable(): Promise<boolean> {
|
||||
*/
|
||||
export function getCoverUrl(coverPath: string | null, rootId?: string | null): string {
|
||||
if (!coverPath) {
|
||||
return '';
|
||||
return ""
|
||||
}
|
||||
// Ignore TMDB relative paths (start with /) - these are bugs in the index
|
||||
if (coverPath.startsWith('/')) {
|
||||
return '';
|
||||
if (coverPath.startsWith("/")) {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Convert relative path to URL path for FastAPI server
|
||||
// .mediahive/covers/Movies/... -> /api/media/{root_id}/.mediahive/covers/Movies/...
|
||||
let urlPath = coverPath;
|
||||
let urlPath = coverPath
|
||||
|
||||
// Remove drive letter (Z:) and convert backslashes to forward slashes
|
||||
if (urlPath.match(/^[A-Za-z]:/)) {
|
||||
urlPath = urlPath.substring(2);
|
||||
urlPath = urlPath.substring(2)
|
||||
}
|
||||
urlPath = urlPath.replace(/\\/g, '/');
|
||||
urlPath = urlPath.replace(/\\/g, "/")
|
||||
|
||||
// Ensure path starts with /
|
||||
if (!urlPath.startsWith('/')) {
|
||||
urlPath = '/' + urlPath;
|
||||
if (!urlPath.startsWith("/")) {
|
||||
urlPath = "/" + urlPath
|
||||
}
|
||||
|
||||
// Encode URI components but preserve slashes
|
||||
const encodedPath = urlPath.split('/').map(segment => encodeURIComponent(segment)).join('/');
|
||||
const encodedPath = urlPath
|
||||
.split("/")
|
||||
.map((segment) => encodeURIComponent(segment))
|
||||
.join("/")
|
||||
|
||||
const rid = rootId || 'unknown';
|
||||
return `/api/media/${encodeURIComponent(rid)}${encodedPath}`;
|
||||
const rid = rootId || "unknown"
|
||||
return `/api/media/${encodeURIComponent(rid)}${encodedPath}`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,8 +252,8 @@ export function getCoverUrl(coverPath: string | null, rootId?: string | null): s
|
||||
*/
|
||||
export async function pickFolderAndAddRoot(): Promise<string | null> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const api = (window as any).pywebview?.api;
|
||||
if (!api) return null;
|
||||
const folder: string | null = await api.pick_folder();
|
||||
return folder;
|
||||
const api = (window as any).pywebview?.api
|
||||
if (!api) return null
|
||||
const folder: string | null = await api.pick_folder()
|
||||
return folder
|
||||
}
|
||||
|
||||
@@ -4,9 +4,17 @@
|
||||
<div class="collage-grid">
|
||||
<template v-for="(item, index) in collageItems" :key="item.id">
|
||||
<div
|
||||
:ref="el => setItemRef(el as HTMLElement, index)"
|
||||
:ref="(el) => setItemRef(el as HTMLElement, index)"
|
||||
class="collage-item"
|
||||
:class="[`collage-item-${index}`, { 'collage-featured': index === 0, 'collage-item-top-row': isTopRowItem(index), 'nav-focused': focusedIndex === index, 'collage-hidden': !isItemVisible(index) }]"
|
||||
:class="[
|
||||
`collage-item-${index}`,
|
||||
{
|
||||
'collage-featured': index === 0,
|
||||
'collage-item-top-row': isTopRowItem(index),
|
||||
'nav-focused': focusedIndex === index,
|
||||
'collage-hidden': !isItemVisible(index),
|
||||
},
|
||||
]"
|
||||
v-bind="getItemAttrs(index)"
|
||||
@click="handleItemClick(item, index)"
|
||||
@focus="focusedIndex = index"
|
||||
@@ -21,8 +29,15 @@
|
||||
/>
|
||||
</div>
|
||||
<!-- SVG focus outline for big hex -->
|
||||
<svg v-if="index === 0" class="hex-focus-outline hex-focus-big" viewBox="0 0 130 100" preserveAspectRatio="none">
|
||||
<polygon points="21.67,0 21.67,25 0,37.5 0,62.5 21.67,75 21.67,100 108.33,100 108.33,75 130,62.5 130,37.5 108.33,25 108.33,0" />
|
||||
<svg
|
||||
v-if="index === 0"
|
||||
class="hex-focus-outline hex-focus-big"
|
||||
viewBox="0 0 130 100"
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
<polygon
|
||||
points="21.67,0 21.67,25 0,37.5 0,62.5 21.67,75 21.67,100 108.33,100 108.33,75 130,62.5 130,37.5 108.33,25 108.33,0"
|
||||
/>
|
||||
</svg>
|
||||
<!-- Non-featured items: image, video, or placeholder -->
|
||||
<img
|
||||
@@ -44,124 +59,146 @@
|
||||
:src="source.src"
|
||||
:type="source.type"
|
||||
:codecs="source.codecs"
|
||||
>
|
||||
/>
|
||||
</video>
|
||||
<div v-if="index !== 0 && !getImageUrl(item) && getVideoSources(item).length === 0" class="collage-placeholder">
|
||||
<div
|
||||
v-if="index !== 0 && !getImageUrl(item) && getVideoSources(item).length === 0"
|
||||
class="collage-placeholder"
|
||||
>
|
||||
<span class="placeholder-title">{{ item.title }}</span>
|
||||
</div>
|
||||
<div class="collage-item-overlay"></div>
|
||||
<!-- SVG focus outline for small hex items -->
|
||||
<svg v-if="index !== 0 && index !== 2 && !isTopRowItem(index)" class="hex-focus-outline hex-focus-small" viewBox="0 0 86.6 100" preserveAspectRatio="none">
|
||||
<polygon points="43.3,0 86.6,25 86.6,75 43.3,100 0,75 0,25" />
|
||||
</svg>
|
||||
<!-- Item 2 uses a custom flat-bottom hex outline to match its clip-path -->
|
||||
<svg v-if="index === 2" class="hex-focus-outline hex-focus-small" viewBox="0 0 86.6 100" preserveAspectRatio="none">
|
||||
<polygon points="43.3,0 86.6,33.333 86.6,100 0,100 0,33.333" />
|
||||
</svg>
|
||||
<!-- Top-row items use a custom flat-top hex outline to match their clip-path -->
|
||||
<svg v-if="isTopRowItem(index)" class="hex-focus-outline hex-focus-small" viewBox="0 0 86.6 100" preserveAspectRatio="none">
|
||||
<polygon points="86.6,0 86.6,66.667 43.3,100 0,66.667 0,0" />
|
||||
</svg>
|
||||
<div class="collage-item-info" v-if="index === 0">
|
||||
<h1 class="collage-title">{{ item.title }}</h1>
|
||||
<div class="collage-meta">
|
||||
<span v-if="item.year" class="meta-year">{{ item.year }}</span>
|
||||
<span v-if="getRating(item)" class="meta-rating" :class="getRatingClass(item)">
|
||||
★ {{ getRating(item)?.toFixed(1) }}
|
||||
</span>
|
||||
<span v-if="getResolution(item)" class="meta-quality">{{ getResolution(item) }}</span>
|
||||
<div class="collage-item-overlay"></div>
|
||||
<!-- SVG focus outline for small hex items -->
|
||||
<svg
|
||||
v-if="index !== 0 && index !== 2 && !isTopRowItem(index)"
|
||||
class="hex-focus-outline hex-focus-small"
|
||||
viewBox="0 0 86.6 100"
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
<polygon points="43.3,0 86.6,25 86.6,75 43.3,100 0,75 0,25" />
|
||||
</svg>
|
||||
<!-- Item 2 uses a custom flat-bottom hex outline to match its clip-path -->
|
||||
<svg
|
||||
v-if="index === 2"
|
||||
class="hex-focus-outline hex-focus-small"
|
||||
viewBox="0 0 86.6 100"
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
<polygon points="43.3,0 86.6,33.333 86.6,100 0,100 0,33.333" />
|
||||
</svg>
|
||||
<!-- Top-row items use a custom flat-top hex outline to match their clip-path -->
|
||||
<svg
|
||||
v-if="isTopRowItem(index)"
|
||||
class="hex-focus-outline hex-focus-small"
|
||||
viewBox="0 0 86.6 100"
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
<polygon points="86.6,0 86.6,66.667 43.3,100 0,66.667 0,0" />
|
||||
</svg>
|
||||
<div class="collage-item-info" v-if="index === 0">
|
||||
<h1 class="collage-title">{{ item.title }}</h1>
|
||||
<div class="collage-meta">
|
||||
<span v-if="item.year" class="meta-year">{{ item.year }}</span>
|
||||
<span v-if="getRating(item)" class="meta-rating" :class="getRatingClass(item)">
|
||||
★ {{ getRating(item)?.toFixed(1) }}
|
||||
</span>
|
||||
<span v-if="getResolution(item)" class="meta-quality">{{ getResolution(item) }}</span>
|
||||
</div>
|
||||
<p v-if="getOverview(item)" class="collage-overview">{{ getOverview(item) }}</p>
|
||||
<div class="collage-buttons">
|
||||
<button class="btn btn-primary" @click.stop="handlePlay(item)">
|
||||
▶ {{ getPlayLabel(item) }}
|
||||
</button>
|
||||
<button class="btn btn-secondary" @click.stop="$emit('info', item)">ℹ Info</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="getOverview(item)" class="collage-overview">{{ getOverview(item) }}</p>
|
||||
<div class="collage-buttons">
|
||||
<button class="btn btn-primary" @click.stop="handlePlay(item)">▶ {{ getPlayLabel(item) }}</button>
|
||||
<button class="btn btn-secondary" @click.stop="$emit('info', item)">ℹ Info</button>
|
||||
<div class="collage-item-hover" v-else>
|
||||
<span class="hover-title">{{ item.title }}</span>
|
||||
<span v-if="getRating(item)" class="hover-rating"
|
||||
>★ {{ getRating(item)?.toFixed(1) }}</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div class="collage-item-hover" v-else>
|
||||
<span class="hover-title">{{ item.title }}</span>
|
||||
<span v-if="getRating(item)" class="hover-rating">★ {{ getRating(item)?.toFixed(1) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
||||
import type { MediaItem, Movie, Series } from '../types';
|
||||
import { getCoverUrl, getVideoPreviewUrl, getVideoSourceAttributes, isVideoPath } from '../api';
|
||||
import { navAttrs } from '../composables/useKeyboardNavigation';
|
||||
import { computed, ref, onMounted, onUnmounted, nextTick, watch } from "vue"
|
||||
import type { MediaItem, Movie, Series } from "../types"
|
||||
import { getCoverUrl, getVideoPreviewUrl, getVideoSourceAttributes, isVideoPath } from "../api"
|
||||
import { navAttrs } from "../composables/useKeyboardNavigation"
|
||||
|
||||
const focusedIndex = ref<number | null>(null);
|
||||
const itemRefs = ref<(HTMLElement | null)[]>([]);
|
||||
const focusedIndex = ref<number | null>(null)
|
||||
const itemRefs = ref<(HTMLElement | null)[]>([])
|
||||
// Track last row when on col=0 (big image) for sideways navigation
|
||||
const lastRow = ref(1);
|
||||
const lastRow = ref(1)
|
||||
|
||||
// Reset lastRow when entering the hero from outside (via global nav)
|
||||
watch(focusedIndex, (newVal, oldVal) => {
|
||||
if (newVal === 0 && oldVal === null) {
|
||||
// Entering big image from outside hero - reset to row 1
|
||||
lastRow.value = 1;
|
||||
lastRow.value = 1
|
||||
}
|
||||
});
|
||||
})
|
||||
// Track which items are visible (at least 75% in viewport)
|
||||
const visibleItems = ref<Set<number>>(new Set());
|
||||
const visibleItems = ref<Set<number>>(new Set())
|
||||
|
||||
function setItemRef(el: HTMLElement | null, index: number) {
|
||||
itemRefs.value[index] = el;
|
||||
itemRefs.value[index] = el
|
||||
}
|
||||
|
||||
// Check if element is at least 75% visible horizontally
|
||||
function isElementVisible(el: HTMLElement | null): boolean {
|
||||
if (!el) return false;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth;
|
||||
if (!el) return false
|
||||
const rect = el.getBoundingClientRect()
|
||||
const viewportWidth = window.innerWidth
|
||||
|
||||
// Calculate how much of the element is visible
|
||||
const visibleLeft = Math.max(0, rect.left);
|
||||
const visibleRight = Math.min(viewportWidth, rect.right);
|
||||
const visibleWidth = Math.max(0, visibleRight - visibleLeft);
|
||||
const visibleRatio = visibleWidth / rect.width;
|
||||
const visibleLeft = Math.max(0, rect.left)
|
||||
const visibleRight = Math.min(viewportWidth, rect.right)
|
||||
const visibleWidth = Math.max(0, visibleRight - visibleLeft)
|
||||
const visibleRatio = visibleWidth / rect.width
|
||||
|
||||
return visibleRatio >= 0.75;
|
||||
return visibleRatio >= 0.75
|
||||
}
|
||||
|
||||
function updateVisibility() {
|
||||
const newVisible = new Set<number>();
|
||||
const newVisible = new Set<number>()
|
||||
|
||||
for (let i = 0; i < itemRefs.value.length; i++) {
|
||||
// Always include items 0, 1, 2 (big image and left side)
|
||||
if (i <= 2 || isElementVisible(itemRefs.value[i])) {
|
||||
newVisible.add(i);
|
||||
newVisible.add(i)
|
||||
}
|
||||
}
|
||||
|
||||
visibleItems.value = newVisible;
|
||||
visibleItems.value = newVisible
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('resize', updateVisibility);
|
||||
document.addEventListener('focusin', handleDocumentFocusIn);
|
||||
window.addEventListener("resize", updateVisibility)
|
||||
document.addEventListener("focusin", handleDocumentFocusIn)
|
||||
// Initial visibility check after render
|
||||
nextTick(() => {
|
||||
updateVisibility();
|
||||
});
|
||||
});
|
||||
updateVisibility()
|
||||
})
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', updateVisibility);
|
||||
document.removeEventListener('focusin', handleDocumentFocusIn);
|
||||
});
|
||||
window.removeEventListener("resize", updateVisibility)
|
||||
document.removeEventListener("focusin", handleDocumentFocusIn)
|
||||
})
|
||||
|
||||
function clearHeroFocus() {
|
||||
focusedIndex.value = null;
|
||||
focusedIndex.value = null
|
||||
}
|
||||
|
||||
function handleDocumentFocusIn(event: FocusEvent) {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target?.closest('.collage-hero')) {
|
||||
clearHeroFocus();
|
||||
const target = event.target as HTMLElement | null
|
||||
if (!target?.closest(".collage-hero")) {
|
||||
clearHeroFocus()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,20 +217,23 @@ function handleDocumentFocusIn(event: FocusEvent) {
|
||||
// col 4: fourth right column (12, 14, 13)
|
||||
// col 5: fifth right column (15, 16)
|
||||
|
||||
interface NavCoord { row: number; col: number }
|
||||
interface NavCoord {
|
||||
row: number
|
||||
col: number
|
||||
}
|
||||
const coordMap: Record<number, NavCoord> = {
|
||||
0: { row: 1, col: 0 }, // Big image
|
||||
0: { row: 1, col: 0 }, // Big image
|
||||
// Left side (col -1)
|
||||
1: { row: 0, col: -1 }, // top left
|
||||
2: { row: 2, col: -1 }, // bottom left
|
||||
1: { row: 0, col: -1 }, // top left
|
||||
2: { row: 2, col: -1 }, // bottom left
|
||||
// Right side - sequential columns
|
||||
3: { row: 0, col: 1 },
|
||||
4: { row: 2, col: 1 },
|
||||
5: { row: 1, col: 1 },
|
||||
6: { row: 0, col: 2 },
|
||||
7: { row: 2, col: 2 },
|
||||
8: { row: 1, col: 2 },
|
||||
9: { row: 0, col: 3 },
|
||||
3: { row: 0, col: 1 },
|
||||
4: { row: 2, col: 1 },
|
||||
5: { row: 1, col: 1 },
|
||||
6: { row: 0, col: 2 },
|
||||
7: { row: 2, col: 2 },
|
||||
8: { row: 1, col: 2 },
|
||||
9: { row: 0, col: 3 },
|
||||
10: { row: 2, col: 3 },
|
||||
11: { row: 1, col: 3 },
|
||||
12: { row: 0, col: 4 },
|
||||
@@ -211,198 +251,198 @@ const coordMap: Record<number, NavCoord> = {
|
||||
24: { row: 0, col: 8 },
|
||||
25: { row: 2, col: 8 },
|
||||
26: { row: 1, col: 8 },
|
||||
};
|
||||
}
|
||||
|
||||
function isTopRowItem(index: number): boolean {
|
||||
const coord = coordMap[index];
|
||||
return index !== 0 && coord?.row === 0;
|
||||
const coord = coordMap[index]
|
||||
return index !== 0 && coord?.row === 0
|
||||
}
|
||||
|
||||
// Reverse lookup: find item index at given coordinates
|
||||
function findItemAt(row: number, col: number): number | null {
|
||||
for (const [idx, coord] of Object.entries(coordMap)) {
|
||||
if (coord.row === row && coord.col === col) return parseInt(idx);
|
||||
if (coord.row === row && coord.col === col) return parseInt(idx)
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
// Find nearest item in a direction from current position
|
||||
function findNext(currentIdx: number, direction: 'up' | 'down' | 'left' | 'right'): number | null {
|
||||
const current = coordMap[currentIdx];
|
||||
if (!current) return null;
|
||||
function findNext(currentIdx: number, direction: "up" | "down" | "left" | "right"): number | null {
|
||||
const current = coordMap[currentIdx]
|
||||
if (!current) return null
|
||||
|
||||
// Use lastRow for big image vertical navigation
|
||||
const effectiveRow = current.col === 0 ? lastRow.value : current.row;
|
||||
const effectiveRow = current.col === 0 ? lastRow.value : current.row
|
||||
|
||||
if (direction === 'left') {
|
||||
if (direction === "left") {
|
||||
// Moving left: decrease col
|
||||
const targetCol = current.col - 1;
|
||||
const targetCol = current.col - 1
|
||||
|
||||
if (current.col === 0) {
|
||||
// From big image, go to col -1 if it exists for the effective row
|
||||
// Row 1 has no col -1, so stay on big image (or could wrap to last item)
|
||||
const leftItem = findItemAt(effectiveRow, -1);
|
||||
const leftItem = findItemAt(effectiveRow, -1)
|
||||
if (leftItem !== null) {
|
||||
return leftItem;
|
||||
return leftItem
|
||||
}
|
||||
// Row 1 has no left item - fall back to top-left tile so left side stays reachable
|
||||
const topLeftItem = findItemAt(0, -1);
|
||||
const topLeftItem = findItemAt(0, -1)
|
||||
if (topLeftItem !== null) {
|
||||
lastRow.value = 0;
|
||||
return topLeftItem;
|
||||
lastRow.value = 0
|
||||
return topLeftItem
|
||||
}
|
||||
// No fallback available - stay put
|
||||
return 0;
|
||||
return 0
|
||||
}
|
||||
|
||||
if (targetCol < -1) {
|
||||
// Already at col -1, can't go further left - stay put
|
||||
return currentIdx;
|
||||
return currentIdx
|
||||
}
|
||||
|
||||
if (targetCol === 0) {
|
||||
// Moving to big image - remember current row
|
||||
lastRow.value = current.row;
|
||||
return 0;
|
||||
lastRow.value = current.row
|
||||
return 0
|
||||
}
|
||||
// Find item at same row, col-1
|
||||
return findItemAt(current.row, targetCol);
|
||||
return findItemAt(current.row, targetCol)
|
||||
}
|
||||
|
||||
if (direction === 'right') {
|
||||
if (direction === "right") {
|
||||
// Moving right: increase col
|
||||
const targetCol = current.col + 1;
|
||||
const targetCol = current.col + 1
|
||||
|
||||
if (current.col === 0) {
|
||||
// From big image, go to col 1 at remembered row
|
||||
return findItemAt(lastRow.value, 1);
|
||||
return findItemAt(lastRow.value, 1)
|
||||
}
|
||||
if (current.col === -1) {
|
||||
// From left column, go to big image
|
||||
lastRow.value = current.row;
|
||||
return 0;
|
||||
lastRow.value = current.row
|
||||
return 0
|
||||
}
|
||||
// Find item at same row, col+1, but only if it's visible
|
||||
const nextItem = findItemAt(current.row, targetCol);
|
||||
const nextItem = findItemAt(current.row, targetCol)
|
||||
if (nextItem !== null && visibleItems.value.has(nextItem)) {
|
||||
return nextItem;
|
||||
return nextItem
|
||||
}
|
||||
// No more visible items to the right - stay put
|
||||
return currentIdx;
|
||||
return currentIdx
|
||||
}
|
||||
|
||||
// Helper to check if item at row/col is visible
|
||||
const isItemVisibleAt = (row: number, col: number) => {
|
||||
const item = findItemAt(row, col);
|
||||
return item !== null && visibleItems.value.has(item);
|
||||
};
|
||||
const item = findItemAt(row, col)
|
||||
return item !== null && visibleItems.value.has(item)
|
||||
}
|
||||
|
||||
if (direction === 'up') {
|
||||
const targetRow = effectiveRow - 1;
|
||||
if (targetRow < 0) return null; // Exit up
|
||||
if (direction === "up") {
|
||||
const targetRow = effectiveRow - 1
|
||||
if (targetRow < 0) return null // Exit up
|
||||
|
||||
if (current.col === 0) {
|
||||
// Big image: up/down always exits the hero section
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
// Check if target row item at same col is visible
|
||||
if (!isItemVisibleAt(targetRow, current.col)) {
|
||||
// Skip to row above if middle row is not visible at this column
|
||||
if (targetRow === 1 && isItemVisibleAt(0, current.col)) {
|
||||
const item = findItemAt(0, current.col);
|
||||
if (item !== null) return item;
|
||||
const item = findItemAt(0, current.col)
|
||||
if (item !== null) return item
|
||||
}
|
||||
return currentIdx; // Stay put
|
||||
return currentIdx // Stay put
|
||||
}
|
||||
|
||||
// Find item at row-1, same col (or nearest)
|
||||
let item = findItemAt(targetRow, current.col);
|
||||
if (item !== null) return item;
|
||||
let item = findItemAt(targetRow, current.col)
|
||||
if (item !== null) return item
|
||||
// Try to find nearest col in target row
|
||||
for (let c = current.col; c >= -1; c--) {
|
||||
item = findItemAt(targetRow, c);
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item;
|
||||
item = findItemAt(targetRow, c)
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item
|
||||
}
|
||||
for (let c = current.col + 1; c <= 10; c++) {
|
||||
item = findItemAt(targetRow, c);
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item;
|
||||
item = findItemAt(targetRow, c)
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
if (direction === 'down') {
|
||||
const targetRow = effectiveRow + 1;
|
||||
if (targetRow > 2) return null; // Exit down
|
||||
if (direction === "down") {
|
||||
const targetRow = effectiveRow + 1
|
||||
if (targetRow > 2) return null // Exit down
|
||||
|
||||
if (current.col === 0) {
|
||||
// Big image: up/down always exits the hero section
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
// Check if target row item at same col is visible
|
||||
if (!isItemVisibleAt(targetRow, current.col)) {
|
||||
// Skip to row below if middle row is not visible at this column
|
||||
if (targetRow === 1 && isItemVisibleAt(2, current.col)) {
|
||||
const item = findItemAt(2, current.col);
|
||||
if (item !== null) return item;
|
||||
const item = findItemAt(2, current.col)
|
||||
if (item !== null) return item
|
||||
}
|
||||
return currentIdx; // Stay put
|
||||
return currentIdx // Stay put
|
||||
}
|
||||
|
||||
// Find item at row+1, same col (or nearest)
|
||||
let item = findItemAt(targetRow, current.col);
|
||||
if (item !== null) return item;
|
||||
let item = findItemAt(targetRow, current.col)
|
||||
if (item !== null) return item
|
||||
// Try to find nearest col in target row
|
||||
for (let c = current.col; c >= -1; c--) {
|
||||
item = findItemAt(targetRow, c);
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item;
|
||||
item = findItemAt(targetRow, c)
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item
|
||||
}
|
||||
for (let c = current.col + 1; c <= 10; c++) {
|
||||
item = findItemAt(targetRow, c);
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item;
|
||||
item = findItemAt(targetRow, c)
|
||||
if (item !== null && isItemVisibleAt(targetRow, c)) return item
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
// Only handle if focus is within this component
|
||||
const target = e.target as HTMLElement;
|
||||
if (!target.closest('.collage-hero')) return;
|
||||
const target = e.target as HTMLElement
|
||||
if (!target.closest(".collage-hero")) return
|
||||
|
||||
const direction = {
|
||||
ArrowUp: 'up',
|
||||
ArrowDown: 'down',
|
||||
ArrowLeft: 'left',
|
||||
ArrowRight: 'right',
|
||||
}[e.key] as 'up' | 'down' | 'left' | 'right' | undefined;
|
||||
ArrowUp: "up",
|
||||
ArrowDown: "down",
|
||||
ArrowLeft: "left",
|
||||
ArrowRight: "right",
|
||||
}[e.key] as "up" | "down" | "left" | "right" | undefined
|
||||
|
||||
if (!direction) {
|
||||
if (e.key === 'Enter' && focusedIndex.value !== null) {
|
||||
const item = collageItems.value[focusedIndex.value];
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (item) handleItemClick(item, focusedIndex.value);
|
||||
if (e.key === "Enter" && focusedIndex.value !== null) {
|
||||
const item = collageItems.value[focusedIndex.value]
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (item) handleItemClick(item, focusedIndex.value)
|
||||
}
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
const current = focusedIndex.value ?? 0;
|
||||
const next = findNext(current, direction);
|
||||
const current = focusedIndex.value ?? 0
|
||||
const next = findNext(current, direction)
|
||||
|
||||
if (next !== null && itemRefs.value[next]) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
focusedIndex.value = next;
|
||||
itemRefs.value[next]?.focus({ preventScroll: true });
|
||||
return;
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
focusedIndex.value = next
|
||||
itemRefs.value[next]?.focus({ preventScroll: true })
|
||||
return
|
||||
}
|
||||
|
||||
// Navigation is leaving this section; clear local highlight and let global handler continue.
|
||||
clearHeroFocus();
|
||||
clearHeroFocus()
|
||||
// If next is null, let event bubble to global navigation
|
||||
}
|
||||
|
||||
@@ -410,154 +450,167 @@ function handleKeyDown(e: KeyboardEvent) {
|
||||
function getItemAttrs(index: number) {
|
||||
if (index === 0) {
|
||||
// The hero always enters through the featured item when moving into row 0.
|
||||
return { ...navAttrs(0, index, 0) };
|
||||
return { ...navAttrs(0, index, 0) }
|
||||
}
|
||||
|
||||
// All tiles participate in the global focus model so only one visual highlight exists
|
||||
// and Enter/gamepad A targets the currently highlighted tile.
|
||||
return { ...navAttrs(0, index) };
|
||||
return { ...navAttrs(0, index) }
|
||||
}
|
||||
|
||||
// Check if an item index should be visible based on its column and row
|
||||
function isItemVisible(index: number): boolean {
|
||||
// Always show the first few items (big image and left side)
|
||||
if (index <= 2) return true;
|
||||
return visibleItems.value.has(index);
|
||||
if (index <= 2) return true
|
||||
return visibleItems.value.has(index)
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
items: MediaItem[];
|
||||
featuredItem?: MediaItem | null;
|
||||
hasResumePosition: (filePath: string | null) => boolean;
|
||||
}>();
|
||||
items: MediaItem[]
|
||||
featuredItem?: MediaItem | null
|
||||
hasResumePosition: (filePath: string | null) => boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
play: [string];
|
||||
info: [MediaItem];
|
||||
select: [MediaItem];
|
||||
}>();
|
||||
play: [string]
|
||||
info: [MediaItem]
|
||||
select: [MediaItem]
|
||||
}>()
|
||||
|
||||
// Max items we might ever need - use a generous constant
|
||||
const maxItems = 27;
|
||||
const maxItems = 27
|
||||
|
||||
// Get items for the collage based on visible columns
|
||||
const collageItems = computed(() => {
|
||||
const result: MediaItem[] = [];
|
||||
const result: MediaItem[] = []
|
||||
|
||||
// Add featured item first
|
||||
if (props.featuredItem) {
|
||||
result.push(props.featuredItem);
|
||||
result.push(props.featuredItem)
|
||||
}
|
||||
|
||||
// Add more items, avoiding duplicates, up to max needed
|
||||
for (const item of props.items) {
|
||||
if (result.length >= maxItems) break;
|
||||
if (!result.find(r => r.id === item.id)) {
|
||||
result.push(item);
|
||||
if (result.length >= maxItems) break
|
||||
if (!result.find((r) => r.id === item.id)) {
|
||||
result.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
return result
|
||||
})
|
||||
|
||||
function getImageUrl(item: MediaItem): string | undefined {
|
||||
const coverPath = item.cover_path;
|
||||
const backdropPath = item.type === 'movies'
|
||||
? (item.data as Movie).backdrop_path
|
||||
: (item.data as Series).backdrop_path;
|
||||
const imagePath = coverPath || backdropPath;
|
||||
const coverPath = item.cover_path
|
||||
const backdropPath =
|
||||
item.type === "movies"
|
||||
? (item.data as Movie).backdrop_path
|
||||
: (item.data as Series).backdrop_path
|
||||
const imagePath = coverPath || backdropPath
|
||||
|
||||
// Check if the path is an image (not a video)
|
||||
if (imagePath && /\.(webm|mp4|mkv|avi|mov)$/i.test(imagePath)) {
|
||||
return undefined;
|
||||
return undefined
|
||||
}
|
||||
|
||||
return getCoverUrl(imagePath, item.root_id);
|
||||
return getCoverUrl(imagePath, item.root_id)
|
||||
}
|
||||
|
||||
function getVideoSources(item: MediaItem): Array<{ src: string; type: string; codecs: string }> {
|
||||
if (isVideoPath(item.cover_path)) {
|
||||
return [{ src: getVideoPreviewUrl(getCoverUrl(item.cover_path, item.root_id)), ...getVideoSourceAttributes(item.cover_path) }];
|
||||
return [
|
||||
{
|
||||
src: getVideoPreviewUrl(getCoverUrl(item.cover_path, item.root_id)),
|
||||
...getVideoSourceAttributes(item.cover_path),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
const showreelSourceSets = item.showreel_source_sets;
|
||||
const showreelSourceSets = item.showreel_source_sets
|
||||
if (showreelSourceSets && showreelSourceSets.length > 0) {
|
||||
return showreelSourceSets[0]
|
||||
.filter(path => isVideoPath(path))
|
||||
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)), ...getVideoSourceAttributes(path) }));
|
||||
.filter((path) => isVideoPath(path))
|
||||
.map((path) => ({
|
||||
src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)),
|
||||
...getVideoSourceAttributes(path),
|
||||
}))
|
||||
}
|
||||
|
||||
const showreel = item.showreel_images;
|
||||
const showreel = item.showreel_images
|
||||
if (showreel && showreel.length > 0) {
|
||||
return showreel
|
||||
.filter(path => isVideoPath(path))
|
||||
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)), ...getVideoSourceAttributes(path) }));
|
||||
.filter((path) => isVideoPath(path))
|
||||
.map((path) => ({
|
||||
src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)),
|
||||
...getVideoSourceAttributes(path),
|
||||
}))
|
||||
}
|
||||
|
||||
return [];
|
||||
return []
|
||||
}
|
||||
|
||||
function getRating(item: MediaItem): number | null {
|
||||
if (item.type === 'movies') {
|
||||
return (item.data as Movie).info?.rating ?? null;
|
||||
if (item.type === "movies") {
|
||||
return (item.data as Movie).info?.rating ?? null
|
||||
}
|
||||
return (item.data as Series).info?.rating ?? null;
|
||||
return (item.data as Series).info?.rating ?? null
|
||||
}
|
||||
|
||||
function getRatingClass(item: MediaItem): string {
|
||||
const rating = getRating(item);
|
||||
if (!rating) return '';
|
||||
if (rating >= 7.5) return 'rating-high';
|
||||
if (rating >= 6) return 'rating-medium';
|
||||
return 'rating-low';
|
||||
const rating = getRating(item)
|
||||
if (!rating) return ""
|
||||
if (rating >= 7.5) return "rating-high"
|
||||
if (rating >= 6) return "rating-medium"
|
||||
return "rating-low"
|
||||
}
|
||||
|
||||
function getResolution(item: MediaItem): string | null {
|
||||
if (item.type === 'movies') {
|
||||
const movie = item.data as Movie;
|
||||
return Object.values(movie.torrents || {})[0]?.resolution ?? null;
|
||||
if (item.type === "movies") {
|
||||
const movie = item.data as Movie
|
||||
return Object.values(movie.torrents || {})[0]?.resolution ?? null
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
function getOverview(item: MediaItem): string | null {
|
||||
const overview = item.type === 'movies'
|
||||
? (item.data as Movie).info?.overview
|
||||
: (item.data as Series).info?.overview;
|
||||
if (!overview) return null;
|
||||
return overview.length > 150 ? overview.slice(0, 150) + '...' : overview;
|
||||
const overview =
|
||||
item.type === "movies"
|
||||
? (item.data as Movie).info?.overview
|
||||
: (item.data as Series).info?.overview
|
||||
if (!overview) return null
|
||||
return overview.length > 150 ? overview.slice(0, 150) + "..." : overview
|
||||
}
|
||||
|
||||
function getPlayableFile(item: MediaItem): string | null {
|
||||
if (item.type === 'movies') {
|
||||
const movie = item.data as Movie;
|
||||
return Object.values(movie.torrents || {})[0]?.playable_file ?? null;
|
||||
if (item.type === "movies") {
|
||||
const movie = item.data as Movie
|
||||
return Object.values(movie.torrents || {})[0]?.playable_file ?? null
|
||||
}
|
||||
const series = item.data as Series;
|
||||
const series = item.data as Series
|
||||
for (const season of series.seasons || []) {
|
||||
for (const episode of season.episodes || []) {
|
||||
for (const torrent of Object.values(episode.torrents || {})) {
|
||||
if (torrent.playable_file) return torrent.playable_file;
|
||||
if (torrent.playable_file) return torrent.playable_file
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
function handlePlay(item: MediaItem) {
|
||||
const file = getPlayableFile(item);
|
||||
if (file) emit('play', file);
|
||||
const file = getPlayableFile(item)
|
||||
if (file) emit("play", file)
|
||||
}
|
||||
|
||||
function getPlayLabel(item: MediaItem): string {
|
||||
return props.hasResumePosition(getPlayableFile(item)) ? 'Continue' : 'Play';
|
||||
return props.hasResumePosition(getPlayableFile(item)) ? "Continue" : "Play"
|
||||
}
|
||||
|
||||
function handleItemClick(item: MediaItem, index: number) {
|
||||
if (index === 0) {
|
||||
emit('info', item);
|
||||
emit("info", item)
|
||||
} else {
|
||||
emit('select', item);
|
||||
emit("select", item)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -571,7 +624,7 @@ function handleItemClick(item: MediaItem, index: number) {
|
||||
overflow: visible;
|
||||
background: var(--bg-primary);
|
||||
--h: clamp(450px, 70vh, 600px);
|
||||
--small-w: calc(0.433 * var(--h)); /* Small hex width = 0.866 * 50% of height */
|
||||
--small-w: calc(0.433 * var(--h)); /* Small hex width = 0.866 * 50% of height */
|
||||
--big-edge: calc(1.0833 * var(--h)); /* Big hex right edge = 1.3 * 0.8333 * height */
|
||||
}
|
||||
|
||||
@@ -584,7 +637,11 @@ function handleItemClick(item: MediaItem, index: number) {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
transition: transform 0.3s ease, filter 0.3s ease, opacity 0.3s ease, visibility 0.3s ease;
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
filter 0.3s ease,
|
||||
opacity 0.3s ease,
|
||||
visibility 0.3s ease;
|
||||
}
|
||||
|
||||
/* Media (images and videos) fill the collage item */
|
||||
@@ -595,7 +652,11 @@ function handleItemClick(item: MediaItem, index: number) {
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
object-position: center 30%;
|
||||
transition: transform 0.3s ease, filter 0.3s ease, opacity 0.3s ease, visibility 0.3s ease;
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
filter 0.3s ease,
|
||||
opacity 0.3s ease,
|
||||
visibility 0.3s ease;
|
||||
}
|
||||
|
||||
/* Hidden items - keep in DOM for measurement but invisible */
|
||||
@@ -637,7 +698,8 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
|
||||
/* Blinking animation for focus outline */
|
||||
@keyframes hex-outline-blink {
|
||||
0%, 100% {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
@@ -677,16 +739,16 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
clip-path: polygon(
|
||||
16.67% 0%,
|
||||
16.67% 25%,
|
||||
0% 37.5%,
|
||||
0% 62.5%,
|
||||
0% 37.5%,
|
||||
0% 62.5%,
|
||||
16.67% 75%,
|
||||
16.67% 100%,
|
||||
|
||||
83.33% 100%,
|
||||
|
||||
83.33% 75%,
|
||||
100% 62.5%,
|
||||
100% 37.5%,
|
||||
100% 62.5%,
|
||||
100% 37.5%,
|
||||
83.33% 25%,
|
||||
83.33% 0%
|
||||
);
|
||||
@@ -709,16 +771,16 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
clip-path: polygon(
|
||||
16.67% 0%,
|
||||
16.67% 25%,
|
||||
0% 37.5%,
|
||||
0% 62.5%,
|
||||
0% 37.5%,
|
||||
0% 62.5%,
|
||||
16.67% 75%,
|
||||
16.67% 100%,
|
||||
|
||||
83.33% 100%,
|
||||
|
||||
83.33% 75%,
|
||||
100% 62.5%,
|
||||
100% 37.5%,
|
||||
100% 62.5%,
|
||||
100% 37.5%,
|
||||
83.33% 25%,
|
||||
83.33% 0%
|
||||
);
|
||||
@@ -731,14 +793,7 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
.collage-item:not(.collage-featured) {
|
||||
height: 50%;
|
||||
aspect-ratio: 0.866 / 1;
|
||||
clip-path: polygon(
|
||||
50% 0%,
|
||||
100% 25%,
|
||||
100% 75%,
|
||||
50% 100%,
|
||||
0% 75%,
|
||||
0% 25%
|
||||
);
|
||||
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
|
||||
}
|
||||
|
||||
/* LEFT SIDE - positioned at left edge */
|
||||
@@ -758,13 +813,7 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
.collage-item.collage-item-2:not(.collage-featured) {
|
||||
height: 37.5%;
|
||||
width: var(--small-w);
|
||||
clip-path: polygon(
|
||||
50% 0%,
|
||||
100% 33.333%,
|
||||
100% 100%,
|
||||
0% 100%,
|
||||
0% 33.333%
|
||||
);
|
||||
clip-path: polygon(50% 0%, 100% 33.333%, 100% 100%, 0% 100%, 0% 33.333%);
|
||||
}
|
||||
|
||||
/* Top-row items: keep side angles but flatten top edge to avoid top overflow */
|
||||
@@ -772,13 +821,7 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
top: 0;
|
||||
height: 37.5%;
|
||||
width: var(--small-w);
|
||||
clip-path: polygon(
|
||||
100% 0%,
|
||||
100% 66.667%,
|
||||
50% 100%,
|
||||
0% 66.667%,
|
||||
0% 0%
|
||||
);
|
||||
clip-path: polygon(100% 0%, 100% 66.667%, 50% 100%, 0% 66.667%, 0% 0%);
|
||||
}
|
||||
|
||||
/* RIGHT SIDE - Column 0 (closest to big image) */
|
||||
@@ -929,7 +972,7 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
}
|
||||
|
||||
.collage-placeholder::before {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #e50914;
|
||||
@@ -942,7 +985,7 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
padding: 10px;
|
||||
text-shadow: 0 2px 4px rgba(0,0,0,0.8);
|
||||
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.8);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
@@ -987,9 +1030,15 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.rating-high { color: #46d369; }
|
||||
.rating-medium { color: #f9a825; }
|
||||
.rating-low { color: #e53935; }
|
||||
.rating-high {
|
||||
color: #46d369;
|
||||
}
|
||||
.rating-medium {
|
||||
color: #f9a825;
|
||||
}
|
||||
.rating-low {
|
||||
color: #e53935;
|
||||
}
|
||||
|
||||
.meta-quality {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
@@ -1027,7 +1076,9 @@ html:not(.mouse-active) .collage-item.nav-focused .hex-focus-outline {
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
border-radius: 4px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
transition:
|
||||
opacity 0.3s ease,
|
||||
transform 0.3s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,43 +1,39 @@
|
||||
<template>
|
||||
<div v-if="showDolbyLogo" class="dolby-badges" :class="{ compact }">
|
||||
<img
|
||||
:src="dolbyLogoSrc"
|
||||
:alt="dolbyLogoAlt"
|
||||
class="dolby-logo"
|
||||
/>
|
||||
<img :src="dolbyLogoSrc" :alt="dolbyLogoAlt" class="dolby-logo" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import dolbyAtmosUrl from '../assets/dolby-atmos.webp';
|
||||
import dolbyVisionUrl from '../assets/dolby-vision.webp';
|
||||
import dolbyVisionAtmosUrl from '../assets/dolby-vision-atmos.webp';
|
||||
import { computed } from "vue"
|
||||
import dolbyAtmosUrl from "../assets/dolby-atmos.webp"
|
||||
import dolbyVisionUrl from "../assets/dolby-vision.webp"
|
||||
import dolbyVisionAtmosUrl from "../assets/dolby-vision-atmos.webp"
|
||||
|
||||
const props = defineProps<{
|
||||
hasDolbyVision?: boolean | null;
|
||||
hasDolbyAtmos?: boolean | null;
|
||||
isHdr?: boolean | null;
|
||||
compact?: boolean;
|
||||
}>();
|
||||
hasDolbyVision?: boolean | null
|
||||
hasDolbyAtmos?: boolean | null
|
||||
isHdr?: boolean | null
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const hasDolbyVision = computed(() => props.hasDolbyVision === true);
|
||||
const hasDolbyAtmos = computed(() => props.hasDolbyAtmos === true);
|
||||
const compact = computed(() => props.compact === true);
|
||||
const hasDolbyVision = computed(() => props.hasDolbyVision === true)
|
||||
const hasDolbyAtmos = computed(() => props.hasDolbyAtmos === true)
|
||||
const compact = computed(() => props.compact === true)
|
||||
|
||||
const showDolbyLogo = computed(() => hasDolbyVision.value || hasDolbyAtmos.value);
|
||||
const showDolbyLogo = computed(() => hasDolbyVision.value || hasDolbyAtmos.value)
|
||||
|
||||
const dolbyLogoSrc = computed(() => {
|
||||
if (hasDolbyVision.value && hasDolbyAtmos.value) return dolbyVisionAtmosUrl;
|
||||
if (hasDolbyVision.value) return dolbyVisionUrl;
|
||||
return dolbyAtmosUrl;
|
||||
});
|
||||
if (hasDolbyVision.value && hasDolbyAtmos.value) return dolbyVisionAtmosUrl
|
||||
if (hasDolbyVision.value) return dolbyVisionUrl
|
||||
return dolbyAtmosUrl
|
||||
})
|
||||
|
||||
const dolbyLogoAlt = computed(() => {
|
||||
if (hasDolbyVision.value && hasDolbyAtmos.value) return 'Dolby Vision + Dolby Atmos';
|
||||
if (hasDolbyVision.value) return 'Dolby Vision';
|
||||
return 'Dolby Atmos';
|
||||
});
|
||||
if (hasDolbyVision.value && hasDolbyAtmos.value) return "Dolby Vision + Dolby Atmos"
|
||||
if (hasDolbyVision.value) return "Dolby Vision"
|
||||
return "Dolby Atmos"
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+124
-113
@@ -26,19 +26,10 @@
|
||||
</template>
|
||||
<!-- Detail mode: show current category + Details -->
|
||||
<template v-else>
|
||||
<button
|
||||
class="header-nav-item"
|
||||
v-bind="navAttrs(navRow, 0)"
|
||||
@focus="goToCategory"
|
||||
>
|
||||
{{ currentView === 'movies' ? 'Movies' : 'Series' }}
|
||||
</button>
|
||||
<button
|
||||
class="header-nav-item active"
|
||||
v-bind="navAttrs(navRow, 1, 1)"
|
||||
>
|
||||
Details
|
||||
<button class="header-nav-item" v-bind="navAttrs(navRow, 0)" @focus="goToCategory">
|
||||
{{ currentView === "movies" ? "Movies" : "Series" }}
|
||||
</button>
|
||||
<button class="header-nav-item active" v-bind="navAttrs(navRow, 1, 1)">Details</button>
|
||||
</template>
|
||||
</nav>
|
||||
</div>
|
||||
@@ -63,14 +54,22 @@
|
||||
</div>
|
||||
|
||||
<div class="header-settings">
|
||||
<button
|
||||
class="header-settings-btn"
|
||||
title="Settings"
|
||||
@click="showSettings = !showSettings"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 5 15.4 1.65 1.65 0 0 0 3.4 15H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||
<button class="header-settings-btn" title="Settings" @click="showSettings = !showSettings">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path
|
||||
d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 5 15.4 1.65 1.65 0 0 0 3.4 15H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
@@ -78,8 +77,18 @@
|
||||
<div v-if="showSettings" class="settings-view">
|
||||
<div class="settings-header">
|
||||
<button class="settings-back" @click="showSettings = false">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M19 12H5M12 19l-7-7 7-7"/>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
<span>Back</span>
|
||||
</button>
|
||||
@@ -118,11 +127,7 @@
|
||||
</div>
|
||||
|
||||
<div class="roots-actions">
|
||||
<button
|
||||
v-if="isDesktopApp"
|
||||
class="roots-add-btn"
|
||||
@click="addRoot"
|
||||
>
|
||||
<button v-if="isDesktopApp" class="roots-add-btn" @click="addRoot">
|
||||
+ Add Folder…
|
||||
</button>
|
||||
</div>
|
||||
@@ -134,125 +139,127 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { navAttrs } from '../composables/useKeyboardNavigation';
|
||||
import logoUrl from '../assets/mediahive.webp';
|
||||
import { fetchRoots, replaceRoots, pickFolderAndAddRoot } from '../api';
|
||||
import { ref, watch, computed, onMounted, onUnmounted } from "vue"
|
||||
import { useRouter } from "vue-router"
|
||||
import { navAttrs } from "../composables/useKeyboardNavigation"
|
||||
import logoUrl from "../assets/mediahive.webp"
|
||||
import { fetchRoots, replaceRoots, pickFolderAndAddRoot } from "../api"
|
||||
|
||||
interface RootEntry {
|
||||
root_id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
status: string;
|
||||
root_id: string
|
||||
name: string
|
||||
path: string
|
||||
status: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
currentView: 'movies' | 'series';
|
||||
searchQuery: string;
|
||||
mpcBeConnected: boolean;
|
||||
navRow: number;
|
||||
position: 'top' | 'after-hero' | 'after-movie-header' | 'after-series-hero';
|
||||
}>();
|
||||
currentView: "movies" | "series"
|
||||
searchQuery: string
|
||||
mpcBeConnected: boolean
|
||||
navRow: number
|
||||
position: "top" | "after-hero" | "after-movie-header" | "after-series-hero"
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
search: [string];
|
||||
goBack: [];
|
||||
}>();
|
||||
search: [string]
|
||||
goBack: []
|
||||
}>()
|
||||
|
||||
const router = useRouter();
|
||||
const searchInputRef = ref<HTMLInputElement | null>(null);
|
||||
const localSearch = ref(props.searchQuery);
|
||||
const router = useRouter()
|
||||
const searchInputRef = ref<HTMLInputElement | null>(null)
|
||||
const localSearch = ref(props.searchQuery)
|
||||
|
||||
const isDesktopApp = ref(typeof (window as any).pywebview !== 'undefined');
|
||||
function _onPywebviewReady() { isDesktopApp.value = true; }
|
||||
window.addEventListener('pywebviewready', _onPywebviewReady, { once: true });
|
||||
onUnmounted(() => window.removeEventListener('pywebviewready', _onPywebviewReady));
|
||||
const isDesktopApp = ref(typeof (window as any).pywebview !== "undefined")
|
||||
function _onPywebviewReady() {
|
||||
isDesktopApp.value = true
|
||||
}
|
||||
window.addEventListener("pywebviewready", _onPywebviewReady, { once: true })
|
||||
onUnmounted(() => window.removeEventListener("pywebviewready", _onPywebviewReady))
|
||||
|
||||
const showSettings = ref(false);
|
||||
const roots = ref<RootEntry[]>([]);
|
||||
const showSettings = ref(false)
|
||||
const roots = ref<RootEntry[]>([])
|
||||
|
||||
async function refreshRoots() {
|
||||
try {
|
||||
const data = await fetchRoots();
|
||||
roots.value = data.map(r => ({
|
||||
const data = await fetchRoots()
|
||||
roots.value = data.map((r) => ({
|
||||
root_id: r.root_id,
|
||||
name: r.name,
|
||||
path: r.path,
|
||||
status: r.status,
|
||||
}));
|
||||
}))
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch roots:', e);
|
||||
console.error("Failed to fetch roots:", e)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRoot(rootId: string) {
|
||||
const filtered = roots.value.filter(r => r.root_id !== rootId);
|
||||
const newRoots = Object.fromEntries(filtered.map(r => [r.name, r.path]));
|
||||
const filtered = roots.value.filter((r) => r.root_id !== rootId)
|
||||
const newRoots = Object.fromEntries(filtered.map((r) => [r.name, r.path]))
|
||||
try {
|
||||
await replaceRoots(newRoots);
|
||||
await refreshRoots();
|
||||
await replaceRoots(newRoots)
|
||||
await refreshRoots()
|
||||
} catch (e) {
|
||||
console.error('Failed to remove root:', e);
|
||||
alert('Failed to remove root');
|
||||
console.error("Failed to remove root:", e)
|
||||
alert("Failed to remove root")
|
||||
}
|
||||
}
|
||||
|
||||
async function addRoot() {
|
||||
const folder = await pickFolderAndAddRoot();
|
||||
if (!folder) return;
|
||||
const name = folder.split('/').pop() || folder.split('\\').pop() || 'media';
|
||||
const folder = await pickFolderAndAddRoot()
|
||||
if (!folder) return
|
||||
const name = folder.split("/").pop() || folder.split("\\").pop() || "media"
|
||||
// Resolve name collisions
|
||||
let uniqueName = name;
|
||||
let suffix = 2;
|
||||
const currentNames = new Set(roots.value.map(r => r.name));
|
||||
let uniqueName = name
|
||||
let suffix = 2
|
||||
const currentNames = new Set(roots.value.map((r) => r.name))
|
||||
while (currentNames.has(uniqueName)) {
|
||||
uniqueName = `${name}${suffix}`;
|
||||
suffix++;
|
||||
uniqueName = `${name}${suffix}`
|
||||
suffix++
|
||||
}
|
||||
const newRoots = Object.fromEntries(roots.value.map(r => [r.name, r.path]));
|
||||
newRoots[uniqueName] = folder;
|
||||
const newRoots = Object.fromEntries(roots.value.map((r) => [r.name, r.path]))
|
||||
newRoots[uniqueName] = folder
|
||||
try {
|
||||
await replaceRoots(newRoots);
|
||||
await refreshRoots();
|
||||
showSettings.value = false;
|
||||
await replaceRoots(newRoots)
|
||||
await refreshRoots()
|
||||
showSettings.value = false
|
||||
} catch (e) {
|
||||
console.error('Failed to add root:', e);
|
||||
alert('Failed to add root');
|
||||
console.error("Failed to add root:", e)
|
||||
alert("Failed to add root")
|
||||
}
|
||||
}
|
||||
|
||||
watch(showSettings, (visible) => {
|
||||
if (visible) void refreshRoots();
|
||||
});
|
||||
if (visible) void refreshRoots()
|
||||
})
|
||||
|
||||
// Check if we're on a detail page
|
||||
const isDetailPage = computed(() => {
|
||||
return props.position === 'after-movie-header' || props.position === 'after-series-hero';
|
||||
});
|
||||
return props.position === "after-movie-header" || props.position === "after-series-hero"
|
||||
})
|
||||
|
||||
// Check if search is active (has query and not on detail page)
|
||||
const isSearchActive = computed(() => {
|
||||
return !isDetailPage.value && !!localSearch.value;
|
||||
});
|
||||
return !isDetailPage.value && !!localSearch.value
|
||||
})
|
||||
|
||||
// Switch views on focus (no Enter required) - only in browse mode
|
||||
function switchToMovies() {
|
||||
if (!isDetailPage.value && props.currentView !== 'movies') {
|
||||
router.push('/movies');
|
||||
if (!isDetailPage.value && props.currentView !== "movies") {
|
||||
router.push("/movies")
|
||||
}
|
||||
}
|
||||
|
||||
function switchToSeries() {
|
||||
if (!isDetailPage.value && props.currentView !== 'series') {
|
||||
router.push('/series');
|
||||
if (!isDetailPage.value && props.currentView !== "series") {
|
||||
router.push("/series")
|
||||
}
|
||||
}
|
||||
|
||||
// Go back to category list from detail page
|
||||
function goToCategory() {
|
||||
// Emit goBack to let App.vue handle navigation and focus restoration
|
||||
emit('goBack');
|
||||
emit("goBack")
|
||||
}
|
||||
|
||||
// Handle search input focus - navigate to search if we have a query
|
||||
@@ -262,52 +269,56 @@ function handleSearchFocus() {
|
||||
|
||||
// Sync local search to parent
|
||||
watch(localSearch, (val) => {
|
||||
emit('search', val);
|
||||
});
|
||||
emit("search", val)
|
||||
})
|
||||
|
||||
// Sync parent search to local (for external clears)
|
||||
watch(() => props.searchQuery, (val) => {
|
||||
if (val !== localSearch.value) {
|
||||
localSearch.value = val;
|
||||
}
|
||||
});
|
||||
watch(
|
||||
() => props.searchQuery,
|
||||
(val) => {
|
||||
if (val !== localSearch.value) {
|
||||
localSearch.value = val
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
function handleEscape() {
|
||||
// Clear search and blur
|
||||
localSearch.value = '';
|
||||
searchInputRef.value?.blur();
|
||||
localSearch.value = ""
|
||||
searchInputRef.value?.blur()
|
||||
}
|
||||
|
||||
function focusSearchInput() {
|
||||
searchInputRef.value?.focus();
|
||||
searchInputRef.value?.select();
|
||||
searchInputRef.value?.focus()
|
||||
searchInputRef.value?.select()
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
const target = e.target as HTMLElement | null;
|
||||
const target = e.target as HTMLElement | null
|
||||
const isTypingTarget = Boolean(
|
||||
target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)
|
||||
);
|
||||
const isSearchShortcut = (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f';
|
||||
const isSlashShortcut = !e.ctrlKey && !e.metaKey && !e.altKey && e.code === 'Slash';
|
||||
target &&
|
||||
(target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable),
|
||||
)
|
||||
const isSearchShortcut = (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "f"
|
||||
const isSlashShortcut = !e.ctrlKey && !e.metaKey && !e.altKey && e.code === "Slash"
|
||||
|
||||
if (isTypingTarget && !isSearchShortcut) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
if (isSearchShortcut || isSlashShortcut) {
|
||||
e.preventDefault();
|
||||
focusSearchInput();
|
||||
e.preventDefault()
|
||||
focusSearchInput()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('keydown', handleKeydown);
|
||||
});
|
||||
window.addEventListener("keydown", handleKeydown)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('keydown', handleKeydown);
|
||||
});
|
||||
window.removeEventListener("keydown", handleKeydown)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -17,104 +17,98 @@
|
||||
</div>
|
||||
<p v-if="overview" class="hero-overview">{{ overview }}</p>
|
||||
<div class="hero-buttons">
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
@click="handlePlay"
|
||||
:disabled="!playableFile"
|
||||
>
|
||||
<button class="btn btn-primary" @click="handlePlay" :disabled="!playableFile">
|
||||
▶ Play
|
||||
</button>
|
||||
<button class="btn btn-secondary" @click="$emit('info', item)">
|
||||
ℹ More Info
|
||||
</button>
|
||||
<button class="btn btn-secondary" @click="$emit('info', item)">ℹ More Info</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import type { MediaItem, Movie, Series } from '../types';
|
||||
import { getCoverUrl } from '../api';
|
||||
import { computed } from "vue"
|
||||
import type { MediaItem, Movie, Series } from "../types"
|
||||
import { getCoverUrl } from "../api"
|
||||
|
||||
const props = defineProps<{
|
||||
item: MediaItem;
|
||||
}>();
|
||||
item: MediaItem
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
play: [string];
|
||||
info: [MediaItem];
|
||||
}>();
|
||||
play: [string]
|
||||
info: [MediaItem]
|
||||
}>()
|
||||
|
||||
const coverUrl = computed(() => {
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id);
|
||||
});
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id)
|
||||
})
|
||||
|
||||
const resolution = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
const movie = props.item.data as Movie;
|
||||
const torrents = Object.values(movie.torrents || {});
|
||||
return torrents.length > 0 ? torrents[0].resolution : null;
|
||||
if (props.item.type === "movies") {
|
||||
const movie = props.item.data as Movie
|
||||
const torrents = Object.values(movie.torrents || {})
|
||||
return torrents.length > 0 ? torrents[0].resolution : null
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return null
|
||||
})
|
||||
|
||||
const quality = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
const movie = props.item.data as Movie;
|
||||
const torrents = Object.values(movie.torrents || {});
|
||||
return torrents.length > 0 ? torrents[0].quality : null;
|
||||
if (props.item.type === "movies") {
|
||||
const movie = props.item.data as Movie
|
||||
const torrents = Object.values(movie.torrents || {})
|
||||
return torrents.length > 0 ? torrents[0].quality : null
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return null
|
||||
})
|
||||
|
||||
const rating = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
return (props.item.data as Movie).info?.rating;
|
||||
if (props.item.type === "movies") {
|
||||
return (props.item.data as Movie).info?.rating
|
||||
}
|
||||
return (props.item.data as Series).info?.rating;
|
||||
});
|
||||
return (props.item.data as Series).info?.rating
|
||||
})
|
||||
|
||||
const ratingClass = computed(() => {
|
||||
if (!rating.value) return '';
|
||||
if (rating.value >= 7.5) return 'rating-high';
|
||||
if (rating.value >= 6) return 'rating-medium';
|
||||
return 'rating-low';
|
||||
});
|
||||
if (!rating.value) return ""
|
||||
if (rating.value >= 7.5) return "rating-high"
|
||||
if (rating.value >= 6) return "rating-medium"
|
||||
return "rating-low"
|
||||
})
|
||||
|
||||
const overview = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
const o = (props.item.data as Movie).info?.overview;
|
||||
return o ? (o.length > 200 ? o.slice(0, 200) + '...' : o) : null;
|
||||
if (props.item.type === "movies") {
|
||||
const o = (props.item.data as Movie).info?.overview
|
||||
return o ? (o.length > 200 ? o.slice(0, 200) + "..." : o) : null
|
||||
}
|
||||
const o = (props.item.data as Series).info?.overview;
|
||||
return o ? (o.length > 200 ? o.slice(0, 200) + '...' : o) : null;
|
||||
});
|
||||
const o = (props.item.data as Series).info?.overview
|
||||
return o ? (o.length > 200 ? o.slice(0, 200) + "..." : o) : null
|
||||
})
|
||||
|
||||
const playableFile = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
const movie = props.item.data as Movie;
|
||||
const torrents = Object.values(movie.torrents || {});
|
||||
return torrents.length > 0 ? torrents[0].playable_file : null;
|
||||
if (props.item.type === "movies") {
|
||||
const movie = props.item.data as Movie
|
||||
const torrents = Object.values(movie.torrents || {})
|
||||
return torrents.length > 0 ? torrents[0].playable_file : null
|
||||
}
|
||||
// For series, get first available file from episodes
|
||||
const series = props.item.data as Series;
|
||||
const series = props.item.data as Series
|
||||
for (const season of series.seasons || []) {
|
||||
for (const episode of season.episodes || []) {
|
||||
const torrents = Object.values(episode.torrents || {});
|
||||
const torrents = Object.values(episode.torrents || {})
|
||||
for (const torrent of torrents) {
|
||||
if (torrent.playable_file) {
|
||||
return torrent.playable_file;
|
||||
return torrent.playable_file
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return null
|
||||
})
|
||||
|
||||
function handlePlay() {
|
||||
if (playableFile.value) {
|
||||
emit('play', playableFile.value);
|
||||
emit("play", playableFile.value)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -14,26 +14,27 @@
|
||||
:key="`raw-${code}`"
|
||||
class="language-code-fallback"
|
||||
:title="code"
|
||||
>{{ code }}</span>
|
||||
>{{ code }}</span
|
||||
>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { buildLanguageFlags } from '../utils/languageFlags';
|
||||
import { computed } from "vue"
|
||||
import { buildLanguageFlags } from "../utils/languageFlags"
|
||||
|
||||
const props = defineProps<{
|
||||
label?: string;
|
||||
codes: string[] | null | undefined;
|
||||
compact?: boolean;
|
||||
}>();
|
||||
label?: string
|
||||
codes: string[] | null | undefined
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const mapped = computed(() => buildLanguageFlags(props.codes));
|
||||
const flagEntries = computed(() => mapped.value.flags);
|
||||
const unmappedCodes = computed(() => mapped.value.unmappedCodes);
|
||||
const hasContent = computed(() => flagEntries.value.length > 0 || unmappedCodes.value.length > 0);
|
||||
const compact = computed(() => props.compact === true);
|
||||
const mapped = computed(() => buildLanguageFlags(props.codes))
|
||||
const flagEntries = computed(() => mapped.value.flags)
|
||||
const unmappedCodes = computed(() => mapped.value.unmappedCodes)
|
||||
const hasContent = computed(() => flagEntries.value.length > 0 || unmappedCodes.value.length > 0)
|
||||
const compact = computed(() => props.compact === true)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
playsinline
|
||||
></video>
|
||||
<div v-else class="media-card-placeholder">
|
||||
{{ item.type === 'movies' ? '🎬' : item.type === 'episode' ? '📺' : '📺' }}
|
||||
{{ item.type === "movies" ? "🎬" : item.type === "episode" ? "📺" : "📺" }}
|
||||
</div>
|
||||
<div v-if="rating" class="media-card-rating" :class="ratingClass">
|
||||
★ {{ rating.toFixed(1) }}
|
||||
@@ -38,24 +38,43 @@
|
||||
<span v-if="item.year" class="media-card-year">{{ item.year }}</span>
|
||||
</div>
|
||||
<template v-if="item.searchMatchInfo">
|
||||
<div v-if="matchedPeople && matchedPeople.length > 0" class="media-card-detail match-reason">
|
||||
<div
|
||||
v-if="matchedPeople && matchedPeople.length > 0"
|
||||
class="media-card-detail match-reason"
|
||||
>
|
||||
<template v-for="(person, idx) in matchedPeople" :key="person.name">
|
||||
<span :class="person.highlightRoles ? 'match-dim' : 'match-name'">{{ person.name }}</span>
|
||||
<span :class="person.highlightRoles ? 'match-highlight' : 'match-roles'">({{ person.roles }})</span><span v-if="idx < matchedPeople.length - 1">, </span>
|
||||
<span :class="person.highlightRoles ? 'match-dim' : 'match-name'">{{
|
||||
person.name
|
||||
}}</span>
|
||||
<span :class="person.highlightRoles ? 'match-highlight' : 'match-roles'"
|
||||
>({{ person.roles }})</span
|
||||
><span v-if="idx < matchedPeople.length - 1">, </span>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="item.searchMatchInfo.matchedEpisodes && item.searchMatchInfo.matchedEpisodes.length > 0" class="media-card-episodes">
|
||||
<div v-for="ep in item.searchMatchInfo.matchedEpisodes.slice(0, 3)" :key="ep.name" class="matched-episode">
|
||||
<div
|
||||
v-if="
|
||||
item.searchMatchInfo.matchedEpisodes && item.searchMatchInfo.matchedEpisodes.length > 0
|
||||
"
|
||||
class="media-card-episodes"
|
||||
>
|
||||
<div
|
||||
v-for="ep in item.searchMatchInfo.matchedEpisodes.slice(0, 3)"
|
||||
:key="ep.name"
|
||||
class="matched-episode"
|
||||
>
|
||||
<span class="match-name">{{ ep.name }}</span>
|
||||
<span class="match-roles"> ({{ ep.location }})</span>
|
||||
</div>
|
||||
<div v-if="item.searchMatchInfo.matchedEpisodes.length > 3" class="matched-episode-more">+{{ item.searchMatchInfo.matchedEpisodes.length - 3 }} more</div>
|
||||
<div v-if="item.searchMatchInfo.matchedEpisodes.length > 3" class="matched-episode-more">
|
||||
+{{ item.searchMatchInfo.matchedEpisodes.length - 3 }} more
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div v-if="subtitle" class="media-card-detail">{{ subtitle }}</div>
|
||||
<div v-if="directorAndCast" class="media-card-detail">
|
||||
<span v-if="director" class="director-name">{{ director }}</span><span v-if="director && filteredCastNames">, </span>{{ filteredCastNames }}
|
||||
<span v-if="director" class="director-name">{{ director }}</span
|
||||
><span v-if="director && filteredCastNames">, </span>{{ filteredCastNames }}
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -63,121 +82,122 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import type { MediaItem, Movie, Series, EpisodeWithSeries } from '../types';
|
||||
import { getCoverUrl, isVideoPath } from '../api';
|
||||
import { navAttrs } from '../composables/useKeyboardNavigation';
|
||||
import { computed, ref } from "vue"
|
||||
import type { MediaItem, Movie, Series, EpisodeWithSeries } from "../types"
|
||||
import { getCoverUrl, isVideoPath } from "../api"
|
||||
import { navAttrs } from "../composables/useKeyboardNavigation"
|
||||
|
||||
const props = defineProps<{
|
||||
item: MediaItem;
|
||||
navRow?: number;
|
||||
navCol?: number;
|
||||
}>();
|
||||
item: MediaItem
|
||||
navRow?: number
|
||||
navCol?: number
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
click: [];
|
||||
}>();
|
||||
click: []
|
||||
}>()
|
||||
|
||||
const navAttributes = computed(() => {
|
||||
if (props.navRow !== undefined && props.navCol !== undefined) {
|
||||
return navAttrs(props.navRow, props.navCol);
|
||||
return navAttrs(props.navRow, props.navCol)
|
||||
}
|
||||
return {};
|
||||
});
|
||||
return {}
|
||||
})
|
||||
|
||||
const imageError = ref(false);
|
||||
const imageError = ref(false)
|
||||
|
||||
const posterImageUrl = computed(() => {
|
||||
if (imageError.value) return null;
|
||||
if (imageError.value) return null
|
||||
if (!props.item.cover_path || isVideoPath(props.item.cover_path)) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id);
|
||||
});
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id)
|
||||
})
|
||||
|
||||
const posterVideoUrl = computed(() => {
|
||||
if (props.item.cover_path && isVideoPath(props.item.cover_path)) {
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id);
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id)
|
||||
}
|
||||
|
||||
const fallbackVideo = props.item.showreel_images?.find(path => isVideoPath(path));
|
||||
return fallbackVideo ? getCoverUrl(fallbackVideo, props.item.root_id) : null;
|
||||
});
|
||||
const fallbackVideo = props.item.showreel_images?.find((path) => isVideoPath(path))
|
||||
return fallbackVideo ? getCoverUrl(fallbackVideo, props.item.root_id) : null
|
||||
})
|
||||
|
||||
const rating = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
return (props.item.data as Movie).info?.rating;
|
||||
if (props.item.type === "movies") {
|
||||
return (props.item.data as Movie).info?.rating
|
||||
}
|
||||
if (props.item.type === 'episode') {
|
||||
const epData = props.item.data as EpisodeWithSeries;
|
||||
return epData.episode.rating ?? epData.series.info?.rating;
|
||||
if (props.item.type === "episode") {
|
||||
const epData = props.item.data as EpisodeWithSeries
|
||||
return epData.episode.rating ?? epData.series.info?.rating
|
||||
}
|
||||
return (props.item.data as Series).info?.rating;
|
||||
});
|
||||
return (props.item.data as Series).info?.rating
|
||||
})
|
||||
|
||||
const ratingClass = computed(() => {
|
||||
if (!rating.value) return '';
|
||||
if (rating.value >= 7.5) return 'rating-high';
|
||||
if (rating.value >= 6) return 'rating-medium';
|
||||
return 'rating-low';
|
||||
});
|
||||
if (!rating.value) return ""
|
||||
if (rating.value >= 7.5) return "rating-high"
|
||||
if (rating.value >= 6) return "rating-medium"
|
||||
return "rating-low"
|
||||
})
|
||||
|
||||
const displayTitle = computed(() => {
|
||||
if (props.item.type === 'episode') {
|
||||
const epData = props.item.data as EpisodeWithSeries;
|
||||
return epData.episode.name || `Episode ${epData.episode.episode_number}`;
|
||||
if (props.item.type === "episode") {
|
||||
const epData = props.item.data as EpisodeWithSeries
|
||||
return epData.episode.name || `Episode ${epData.episode.episode_number}`
|
||||
}
|
||||
return props.item.title;
|
||||
});
|
||||
return props.item.title
|
||||
})
|
||||
|
||||
const subtitle = computed(() => {
|
||||
if (props.item.type === 'episode') {
|
||||
const epData = props.item.data as EpisodeWithSeries;
|
||||
return `${epData.series.title} S${epData.seasonNumber}E${epData.episode.episode_number}`;
|
||||
if (props.item.type === "episode") {
|
||||
const epData = props.item.data as EpisodeWithSeries
|
||||
return `${epData.series.title} S${epData.seasonNumber}E${epData.episode.episode_number}`
|
||||
}
|
||||
if (props.item.type === 'series') {
|
||||
const creators = (props.item.data as Series).info?.creators;
|
||||
return creators && creators.length > 0 ? creators.join(', ') : null;
|
||||
if (props.item.type === "series") {
|
||||
const creators = (props.item.data as Series).info?.creators
|
||||
return creators && creators.length > 0 ? creators.join(", ") : null
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return null
|
||||
})
|
||||
|
||||
const director = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.director;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.director
|
||||
})
|
||||
|
||||
const directorAndCast = computed(() => {
|
||||
if (props.item.type !== 'movies') return false;
|
||||
return director.value || filteredCastNames.value;
|
||||
});
|
||||
if (props.item.type !== "movies") return false
|
||||
return director.value || filteredCastNames.value
|
||||
})
|
||||
|
||||
const filteredCastNames = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
const cast = (props.item.data as Movie).info?.cast;
|
||||
if (!cast || cast.length === 0) return null;
|
||||
if (props.item.type !== "movies") return null
|
||||
const cast = (props.item.data as Movie).info?.cast
|
||||
if (!cast || cast.length === 0) return null
|
||||
|
||||
const directorName = director.value?.toLowerCase();
|
||||
const directorName = director.value?.toLowerCase()
|
||||
const filteredCast = directorName
|
||||
? cast.filter(c => c.name.toLowerCase() !== directorName)
|
||||
: cast;
|
||||
? cast.filter((c) => c.name.toLowerCase() !== directorName)
|
||||
: cast
|
||||
|
||||
if (filteredCast.length === 0) return null;
|
||||
if (filteredCast.length === 0) return null
|
||||
|
||||
const names = filteredCast.slice(0, 3).map(c => c.name);
|
||||
return names.join(', ');
|
||||
});
|
||||
const names = filteredCast.slice(0, 3).map((c) => c.name)
|
||||
return names.join(", ")
|
||||
})
|
||||
|
||||
const matchedPeople = computed(() => {
|
||||
const info = props.item.searchMatchInfo;
|
||||
if (!info || !info.matchedPeople) return null;
|
||||
return info.matchedPeople;
|
||||
});
|
||||
const info = props.item.searchMatchInfo
|
||||
if (!info || !info.matchedPeople) return null
|
||||
return info.matchedPeople
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@keyframes card-outline-blink {
|
||||
0%, 100% {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
|
||||
@@ -14,10 +14,8 @@
|
||||
<!-- Full page view for movies -->
|
||||
<div v-else class="movie-page">
|
||||
<div class="movie-page-content">
|
||||
|
||||
<!-- Diagonal collage header -->
|
||||
<div class="collage-header">
|
||||
|
||||
<!-- Background collage of showreel videos -->
|
||||
<div class="collage-grid">
|
||||
<div
|
||||
@@ -27,13 +25,10 @@
|
||||
@mouseenter="handleVideoHover(slot.index, true)"
|
||||
@mouseleave="handleVideoHover(slot.index, false)"
|
||||
>
|
||||
<div
|
||||
class="collage-fallback-tile"
|
||||
:class="`collage-fallback-${slot.index + 1}`"
|
||||
></div>
|
||||
<div class="collage-fallback-tile" :class="`collage-fallback-${slot.index + 1}`"></div>
|
||||
<video
|
||||
v-if="slot.sourcePaths.length > 0"
|
||||
:ref="el => setVideoRef(el as HTMLVideoElement, slot.index)"
|
||||
:ref="(el) => setVideoRef(el as HTMLVideoElement, slot.index)"
|
||||
:class="{ 'is-ready': isVideoReady(slot.index) }"
|
||||
:autoplay="safariAutoplay"
|
||||
loop
|
||||
@@ -48,7 +43,7 @@
|
||||
:src="getShowreelUrl(sourcePath)"
|
||||
:type="getShowreelSourceAttributes(sourcePath).type"
|
||||
:codecs="getShowreelSourceAttributes(sourcePath).codecs"
|
||||
>
|
||||
/>
|
||||
</video>
|
||||
</div>
|
||||
</div>
|
||||
@@ -61,7 +56,9 @@
|
||||
<h1 class="modal-title">{{ item.title }}</h1>
|
||||
<p v-if="movieTagline" class="header-tagline">{{ movieTagline }}</p>
|
||||
<div class="modal-meta">
|
||||
<span v-if="rating" class="meta-rating" :class="ratingClass">★ {{ rating.toFixed(1) }}</span>
|
||||
<span v-if="rating" class="meta-rating" :class="ratingClass"
|
||||
>★ {{ rating.toFixed(1) }}</span
|
||||
>
|
||||
<span v-if="item.year" class="meta-year">{{ item.year }}</span>
|
||||
<span v-if="movieRuntime" class="meta-runtime">{{ formatRuntime(movieRuntime) }}</span>
|
||||
</div>
|
||||
@@ -85,7 +82,7 @@
|
||||
:src="synopsisPosterUrl"
|
||||
:alt="`${item.title} poster`"
|
||||
class="synopsis-poster"
|
||||
>
|
||||
/>
|
||||
</div>
|
||||
<div v-if="movieVersions.length > 0" class="versions-list versions-list-sidebar">
|
||||
<ReleaseVersionCard
|
||||
@@ -99,7 +96,11 @@
|
||||
@activate="handleVersionActivate(version, $event)"
|
||||
@keydown="handleVersionShortcutKeydown($event, version)"
|
||||
@contextmenu="handleVersionContextMenu($event, version)"
|
||||
:title="version.playable_file ? 'Click to play/continue. Alt+Click, Alt+Enter, or Cmd/Ctrl+E to open folder. Right-click for actions.' : 'No playable file'"
|
||||
:title="
|
||||
version.playable_file
|
||||
? 'Click to play/continue. Alt+Click, Alt+Enter, or Cmd/Ctrl+E to open folder. Right-click for actions.'
|
||||
: 'No playable file'
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -119,18 +120,24 @@
|
||||
:src="getCoverUrl(castMember.profile_path, item.root_id)"
|
||||
:alt="castMember.name"
|
||||
class="cast-photo"
|
||||
>
|
||||
<img v-else :src="getCastPlaceholderUrl(castMember.gender)" :alt="`${castMember.name} placeholder portrait`" class="cast-photo cast-photo-fallback">
|
||||
/>
|
||||
<img
|
||||
v-else
|
||||
:src="getCastPlaceholderUrl(castMember.gender)"
|
||||
:alt="`${castMember.name} placeholder portrait`"
|
||||
class="cast-photo cast-photo-fallback"
|
||||
/>
|
||||
<div class="cast-copy">
|
||||
<span class="cast-name">{{ castMember.name }}</span>
|
||||
<span v-if="castMember.character" class="cast-character">{{ castMember.character }}</span>
|
||||
<span v-if="castMember.character" class="cast-character">{{
|
||||
castMember.character
|
||||
}}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main content -->
|
||||
<div class="content-main">
|
||||
</div>
|
||||
<div class="content-main"></div>
|
||||
|
||||
<!-- Right sidebar - Metadata -->
|
||||
<div v-if="item.type === 'movies'" class="content-sidebar sidebar-right">
|
||||
@@ -144,10 +151,12 @@
|
||||
</div>
|
||||
<div v-if="movieStatus || movieReleaseDate" class="meta-summary">
|
||||
<span v-if="movieStatus" class="meta-summary-item">{{ movieStatus }}</span>
|
||||
<span v-if="movieReleaseDate" class="meta-summary-item">{{ movieReleaseDate }}</span>
|
||||
<span v-if="movieReleaseDate" class="meta-summary-item">{{
|
||||
movieReleaseDate
|
||||
}}</span>
|
||||
</div>
|
||||
<div v-if="movieKeywords && movieKeywords.length > 0" class="meta-keywords-section">
|
||||
<span class="meta-value keywords">{{ movieKeywords.join(', ') }}</span>
|
||||
<span class="meta-value keywords">{{ movieKeywords.join(", ") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -178,315 +187,328 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
|
||||
import type { CastMember, MediaItem, Movie, Series, Torrent } from '../types';
|
||||
import { getCoverUrl, getVideoPreviewUrl, getVideoSourceAttributes, isSafariBrowser, type VideoSourceAttributes } from '../api';
|
||||
import castPlaceholderFemaleUrl from '../assets/cast-placeholder-female.svg';
|
||||
import castPlaceholderMaleUrl from '../assets/cast-placeholder-male.svg';
|
||||
import SeriesFullView from './SeriesFullView.vue';
|
||||
import ReleaseVersionCard from './ReleaseVersionCard.vue';
|
||||
import ReleaseActionMenu from './ReleaseActionMenu.vue';
|
||||
import { navAttrs } from '../composables/useKeyboardNavigation';
|
||||
import { computed, ref, watch, onMounted, onUnmounted, nextTick } from "vue"
|
||||
import type { CastMember, MediaItem, Movie, Series, Torrent } from "../types"
|
||||
import {
|
||||
getCoverUrl,
|
||||
getVideoPreviewUrl,
|
||||
getVideoSourceAttributes,
|
||||
isSafariBrowser,
|
||||
type VideoSourceAttributes,
|
||||
} from "../api"
|
||||
import castPlaceholderFemaleUrl from "../assets/cast-placeholder-female.svg"
|
||||
import castPlaceholderMaleUrl from "../assets/cast-placeholder-male.svg"
|
||||
import SeriesFullView from "./SeriesFullView.vue"
|
||||
import ReleaseVersionCard from "./ReleaseVersionCard.vue"
|
||||
import ReleaseActionMenu from "./ReleaseActionMenu.vue"
|
||||
import { navAttrs } from "../composables/useKeyboardNavigation"
|
||||
|
||||
const props = defineProps<{
|
||||
item: MediaItem;
|
||||
focusEpisode?: { seasonNumber: number; episodeNumber: number } | null;
|
||||
hasResumePosition: (filePath: string | null) => boolean;
|
||||
getRootName: (rootId: string | null | undefined) => string | null;
|
||||
}>();
|
||||
item: MediaItem
|
||||
focusEpisode?: { seasonNumber: number; episodeNumber: number } | null
|
||||
hasResumePosition: (filePath: string | null) => boolean
|
||||
getRootName: (rootId: string | null | undefined) => string | null
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
play: [string];
|
||||
openFolder: [string, string | null | undefined];
|
||||
searchActor: [string];
|
||||
}>();
|
||||
close: []
|
||||
play: [string]
|
||||
openFolder: [string, string | null | undefined]
|
||||
searchActor: [string]
|
||||
}>()
|
||||
|
||||
// Track expanded episode for showing multiple releases
|
||||
|
||||
const videoRefs = ref<(HTMLVideoElement | null)[]>([]);
|
||||
const videoStates = ref<string[]>([]);
|
||||
const COLLAGE_SLOT_COUNT = 5;
|
||||
const safariAutoplay = isSafariBrowser();
|
||||
const COLLAGE_START_OFFSETS_SECONDS = [0, 8, 6, 4, 2];
|
||||
const videoRefs = ref<(HTMLVideoElement | null)[]>([])
|
||||
const videoStates = ref<string[]>([])
|
||||
const COLLAGE_SLOT_COUNT = 5
|
||||
const safariAutoplay = isSafariBrowser()
|
||||
const COLLAGE_START_OFFSETS_SECONDS = [0, 8, 6, 4, 2]
|
||||
|
||||
function setVideoRef(el: HTMLVideoElement | null, index: number) {
|
||||
videoRefs.value[index] = el;
|
||||
videoRefs.value[index] = el
|
||||
}
|
||||
|
||||
function handleVideoLoaded(index: number) {
|
||||
videoStates.value[index] = 'ready';
|
||||
videoStates.value[index] = "ready"
|
||||
}
|
||||
|
||||
function handleVideoError(index: number) {
|
||||
videoStates.value[index] = 'error';
|
||||
videoStates.value[index] = "error"
|
||||
}
|
||||
|
||||
function isVideoReady(index: number): boolean {
|
||||
return videoStates.value[index] === 'ready';
|
||||
return videoStates.value[index] === "ready"
|
||||
}
|
||||
|
||||
// Start staggered video playback
|
||||
function startStaggeredPlayback() {
|
||||
const videos = videoRefs.value.filter(v => v !== null) as HTMLVideoElement[];
|
||||
if (videos.length === 0) return;
|
||||
const videos = videoRefs.value.filter((v) => v !== null) as HTMLVideoElement[]
|
||||
if (videos.length === 0) return
|
||||
|
||||
if (safariAutoplay) {
|
||||
videos.forEach((video, index) => {
|
||||
const offset = COLLAGE_START_OFFSETS_SECONDS[index] ?? 0;
|
||||
const offset = COLLAGE_START_OFFSETS_SECONDS[index] ?? 0
|
||||
const startVideo = () => {
|
||||
video.currentTime = offset;
|
||||
video.play().catch(() => {});
|
||||
};
|
||||
video.currentTime = offset
|
||||
video.play().catch(() => {})
|
||||
}
|
||||
|
||||
if (video.readyState >= 1) {
|
||||
startVideo();
|
||||
startVideo()
|
||||
} else {
|
||||
video.addEventListener('loadedmetadata', startVideo, { once: true });
|
||||
video.addEventListener("loadedmetadata", startVideo, { once: true })
|
||||
}
|
||||
});
|
||||
return;
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Start first video immediately
|
||||
// Non-Safari keeps legacy behavior: start without explicit seek offset.
|
||||
videos[0].play().catch(() => {});
|
||||
videos[0].play().catch(() => {})
|
||||
|
||||
// Set up staggered start for remaining videos
|
||||
for (let i = 1; i < videos.length; i++) {
|
||||
setTimeout(() => {
|
||||
const video = videos[i];
|
||||
if (!video) return;
|
||||
video.play().catch(() => {});
|
||||
}, i * 2000);
|
||||
const video = videos[i]
|
||||
if (!video) return
|
||||
video.play().catch(() => {})
|
||||
}, i * 2000)
|
||||
}
|
||||
}
|
||||
|
||||
// Volume fade animation tracking
|
||||
const volumeFadeIntervals = new Map<number, ReturnType<typeof setInterval>>();
|
||||
const volumeFadeIntervals = new Map<number, ReturnType<typeof setInterval>>()
|
||||
|
||||
// Handle hover-based audio fade in/out
|
||||
function handleVideoHover(index: number, isEntering: boolean) {
|
||||
const video = videoRefs.value[index];
|
||||
if (!video) return;
|
||||
const video = videoRefs.value[index]
|
||||
if (!video) return
|
||||
|
||||
// Clear any existing fade for this video
|
||||
const existingInterval = volumeFadeIntervals.get(index);
|
||||
const existingInterval = volumeFadeIntervals.get(index)
|
||||
if (existingInterval) {
|
||||
clearInterval(existingInterval);
|
||||
volumeFadeIntervals.delete(index);
|
||||
clearInterval(existingInterval)
|
||||
volumeFadeIntervals.delete(index)
|
||||
}
|
||||
|
||||
if (isEntering) {
|
||||
// Mute all other videos immediately
|
||||
document.querySelectorAll('video').forEach(v => {
|
||||
document.querySelectorAll("video").forEach((v) => {
|
||||
if (v !== video) {
|
||||
v.volume = 0;
|
||||
v.muted = true;
|
||||
v.volume = 0
|
||||
v.muted = true
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// Fade in this video's audio
|
||||
video.muted = false;
|
||||
video.muted = false
|
||||
const fadeIn = setInterval(() => {
|
||||
if (video.volume < 0.95) {
|
||||
video.volume = Math.min(1, video.volume + 0.1);
|
||||
video.volume = Math.min(1, video.volume + 0.1)
|
||||
} else {
|
||||
video.volume = 1;
|
||||
clearInterval(fadeIn);
|
||||
volumeFadeIntervals.delete(index);
|
||||
video.volume = 1
|
||||
clearInterval(fadeIn)
|
||||
volumeFadeIntervals.delete(index)
|
||||
}
|
||||
}, 30);
|
||||
volumeFadeIntervals.set(index, fadeIn);
|
||||
}, 30)
|
||||
volumeFadeIntervals.set(index, fadeIn)
|
||||
} else {
|
||||
// Fade out this video's audio
|
||||
const fadeOut = setInterval(() => {
|
||||
if (video.volume > 0.05) {
|
||||
video.volume = Math.max(0, video.volume - 0.1);
|
||||
video.volume = Math.max(0, video.volume - 0.1)
|
||||
} else {
|
||||
video.volume = 0;
|
||||
video.muted = true;
|
||||
clearInterval(fadeOut);
|
||||
volumeFadeIntervals.delete(index);
|
||||
video.volume = 0
|
||||
video.muted = true
|
||||
clearInterval(fadeOut)
|
||||
volumeFadeIntervals.delete(index)
|
||||
}
|
||||
}, 30);
|
||||
volumeFadeIntervals.set(index, fadeOut);
|
||||
}, 30)
|
||||
volumeFadeIntervals.set(index, fadeOut)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// Wait for videos to be ready, then start staggered playback
|
||||
setTimeout(() => {
|
||||
startStaggeredPlayback();
|
||||
}, 100);
|
||||
});
|
||||
startStaggeredPlayback()
|
||||
}, 100)
|
||||
})
|
||||
|
||||
const showreelSourceSets = computed((): string[][] | null => {
|
||||
if (props.item.type === 'movies') {
|
||||
const movie = props.item.data as Movie;
|
||||
if (props.item.type === "movies") {
|
||||
const movie = props.item.data as Movie
|
||||
if (movie.showreel_source_sets && movie.showreel_source_sets.length > 0) {
|
||||
return movie.showreel_source_sets;
|
||||
return movie.showreel_source_sets
|
||||
}
|
||||
return movie.showreel_images?.map((path) => [path]) ?? null;
|
||||
return movie.showreel_images?.map((path) => [path]) ?? null
|
||||
} else {
|
||||
const series = props.item.data as Series;
|
||||
const sourceSets: string[][] = [];
|
||||
const series = props.item.data as Series
|
||||
const sourceSets: string[][] = []
|
||||
for (const season of series.seasons || []) {
|
||||
for (const episode of season.episodes || []) {
|
||||
if (episode.reel_sources && episode.reel_sources.length > 0) {
|
||||
sourceSets.push(episode.reel_sources);
|
||||
sourceSets.push(episode.reel_sources)
|
||||
} else if (episode.reel_image) {
|
||||
sourceSets.push([episode.reel_image]);
|
||||
sourceSets.push([episode.reel_image])
|
||||
}
|
||||
}
|
||||
}
|
||||
return sourceSets.length > 0 ? sourceSets : null;
|
||||
return sourceSets.length > 0 ? sourceSets : null
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
const collageSourceSets = computed((): string[][] => {
|
||||
if (!showreelSourceSets.value || showreelSourceSets.value.length === 0) return [];
|
||||
return showreelSourceSets.value.slice(0, 5);
|
||||
});
|
||||
if (!showreelSourceSets.value || showreelSourceSets.value.length === 0) return []
|
||||
return showreelSourceSets.value.slice(0, 5)
|
||||
})
|
||||
|
||||
const collageSlots = computed(() => {
|
||||
return Array.from({ length: COLLAGE_SLOT_COUNT }, (_, index) => ({
|
||||
index,
|
||||
sourcePaths: collageSourceSets.value[index] ?? [],
|
||||
}));
|
||||
});
|
||||
}))
|
||||
})
|
||||
|
||||
watch(collageSlots, async (slots) => {
|
||||
videoRefs.value = Array.from({ length: COLLAGE_SLOT_COUNT }, (_, index) => videoRefs.value[index] ?? null);
|
||||
videoStates.value = slots.map((slot) => slot.sourcePaths.length > 0 ? 'loading' : 'missing');
|
||||
await nextTick();
|
||||
setTimeout(() => {
|
||||
startStaggeredPlayback();
|
||||
}, 100);
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
collageSlots,
|
||||
async (slots) => {
|
||||
videoRefs.value = Array.from(
|
||||
{ length: COLLAGE_SLOT_COUNT },
|
||||
(_, index) => videoRefs.value[index] ?? null,
|
||||
)
|
||||
videoStates.value = slots.map((slot) => (slot.sourcePaths.length > 0 ? "loading" : "missing"))
|
||||
await nextTick()
|
||||
setTimeout(() => {
|
||||
startStaggeredPlayback()
|
||||
}, 100)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function getShowreelUrl(path: string): string {
|
||||
return getVideoPreviewUrl(getCoverUrl(path, props.item.root_id));
|
||||
return getVideoPreviewUrl(getCoverUrl(path, props.item.root_id))
|
||||
}
|
||||
|
||||
function getShowreelSourceAttributes(path: string): VideoSourceAttributes {
|
||||
return getVideoSourceAttributes(path);
|
||||
return getVideoSourceAttributes(path)
|
||||
}
|
||||
// Movie versions
|
||||
const movieVersions = computed((): Torrent[] => {
|
||||
if (props.item.type !== 'movies') return [];
|
||||
const movie = props.item.data as Movie;
|
||||
return Object.values(movie.torrents || {});
|
||||
});
|
||||
if (props.item.type !== "movies") return []
|
||||
const movie = props.item.data as Movie
|
||||
return Object.values(movie.torrents || {})
|
||||
})
|
||||
|
||||
// Page backdrop background
|
||||
const backdropStyle = computed(() => {
|
||||
if (props.item.type !== 'movies') return {};
|
||||
const movie = props.item.data as Movie;
|
||||
const imagePath = movie.backdrop_path;
|
||||
const imageUrl = getCoverUrl(imagePath, props.item.root_id);
|
||||
if (props.item.type !== "movies") return {}
|
||||
const movie = props.item.data as Movie
|
||||
const imagePath = movie.backdrop_path
|
||||
const imageUrl = getCoverUrl(imagePath, props.item.root_id)
|
||||
if (imageUrl) {
|
||||
return { backgroundImage: `url("${imageUrl}")` };
|
||||
return { backgroundImage: `url("${imageUrl}")` }
|
||||
}
|
||||
return {};
|
||||
});
|
||||
return {}
|
||||
})
|
||||
|
||||
const synopsisPosterUrl = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id);
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return getCoverUrl(props.item.cover_path, props.item.root_id)
|
||||
})
|
||||
|
||||
const movieGenres = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.genres;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.genres
|
||||
})
|
||||
|
||||
const movieTagline = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.tagline;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.tagline
|
||||
})
|
||||
|
||||
const movieDirector = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.director;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.director
|
||||
})
|
||||
|
||||
const movieCast = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.cast as CastMember[] | null;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.cast as CastMember[] | null
|
||||
})
|
||||
|
||||
const limitedMovieCast = computed(() => {
|
||||
if (!movieCast.value) return [];
|
||||
return movieCast.value;
|
||||
});
|
||||
if (!movieCast.value) return []
|
||||
return movieCast.value
|
||||
})
|
||||
|
||||
const movieRuntime = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.runtime;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.runtime
|
||||
})
|
||||
|
||||
const movieReleaseDate = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.release_date;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.release_date
|
||||
})
|
||||
|
||||
const movieStatus = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.status;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.status
|
||||
})
|
||||
|
||||
const movieKeywords = computed(() => {
|
||||
if (props.item.type !== 'movies') return null;
|
||||
return (props.item.data as Movie).info?.keywords;
|
||||
});
|
||||
if (props.item.type !== "movies") return null
|
||||
return (props.item.data as Movie).info?.keywords
|
||||
})
|
||||
|
||||
function getCastPlaceholderUrl(gender?: CastMember['gender']): string {
|
||||
return gender === 'female' ? castPlaceholderFemaleUrl : castPlaceholderMaleUrl;
|
||||
function getCastPlaceholderUrl(gender?: CastMember["gender"]): string {
|
||||
return gender === "female" ? castPlaceholderFemaleUrl : castPlaceholderMaleUrl
|
||||
}
|
||||
|
||||
function formatRuntime(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const mins = minutes % 60;
|
||||
if (hours === 0) return `${mins}m`;
|
||||
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const mins = minutes % 60
|
||||
if (hours === 0) return `${mins}m`
|
||||
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
|
||||
}
|
||||
|
||||
const rating = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
return (props.item.data as Movie).info?.rating;
|
||||
if (props.item.type === "movies") {
|
||||
return (props.item.data as Movie).info?.rating
|
||||
}
|
||||
return (props.item.data as Series).info?.rating;
|
||||
});
|
||||
return (props.item.data as Series).info?.rating
|
||||
})
|
||||
|
||||
const overview = computed(() => {
|
||||
if (props.item.type === 'movies') {
|
||||
return (props.item.data as Movie).info?.overview;
|
||||
if (props.item.type === "movies") {
|
||||
return (props.item.data as Movie).info?.overview
|
||||
}
|
||||
return (props.item.data as Series).info?.overview;
|
||||
});
|
||||
return (props.item.data as Series).info?.overview
|
||||
})
|
||||
|
||||
const ratingClass = computed(() => {
|
||||
if (!rating.value) return '';
|
||||
if (rating.value >= 7.5) return 'rating-high';
|
||||
if (rating.value >= 6) return 'rating-medium';
|
||||
return 'rating-low';
|
||||
});
|
||||
if (!rating.value) return ""
|
||||
if (rating.value >= 7.5) return "rating-high"
|
||||
if (rating.value >= 6) return "rating-medium"
|
||||
return "rating-low"
|
||||
})
|
||||
|
||||
const seasons = computed(() => {
|
||||
if (props.item.type !== 'series') return [];
|
||||
const series = props.item.data as Series;
|
||||
return series.seasons || [];
|
||||
});
|
||||
if (props.item.type !== "series") return []
|
||||
const series = props.item.data as Series
|
||||
return series.seasons || []
|
||||
})
|
||||
|
||||
const selectedSeasonIndex = ref<number>(0);
|
||||
const selectedSeasonIndex = ref<number>(0)
|
||||
|
||||
const versionActionMenu = ref<{
|
||||
visible: boolean;
|
||||
x: number;
|
||||
y: number;
|
||||
filePath: string | null;
|
||||
rootName: string | null;
|
||||
rootId: string | null;
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
filePath: string | null
|
||||
rootName: string | null
|
||||
rootId: string | null
|
||||
}>({
|
||||
visible: false,
|
||||
x: 0,
|
||||
@@ -494,30 +516,30 @@ const versionActionMenu = ref<{
|
||||
filePath: null,
|
||||
rootName: null,
|
||||
rootId: null,
|
||||
});
|
||||
})
|
||||
|
||||
function closeVersionActionMenu() {
|
||||
versionActionMenu.value.visible = false;
|
||||
versionActionMenu.value.filePath = null;
|
||||
versionActionMenu.value.rootName = null;
|
||||
versionActionMenu.value.rootId = null;
|
||||
versionActionMenu.value.visible = false
|
||||
versionActionMenu.value.filePath = null
|
||||
versionActionMenu.value.rootName = null
|
||||
versionActionMenu.value.rootId = null
|
||||
}
|
||||
|
||||
function getPlayLabel(filePath: string | null): string {
|
||||
return props.hasResumePosition(filePath) ? 'Continue' : 'Play';
|
||||
return props.hasResumePosition(filePath) ? "Continue" : "Play"
|
||||
}
|
||||
|
||||
function handlePlayVersion(filePath: string | null) {
|
||||
if (filePath) {
|
||||
emit('play', filePath);
|
||||
emit("play", filePath)
|
||||
}
|
||||
closeVersionActionMenu();
|
||||
closeVersionActionMenu()
|
||||
}
|
||||
|
||||
function handleVersionContextMenu(event: MouseEvent, version: Torrent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id);
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id)
|
||||
versionActionMenu.value = {
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
@@ -525,80 +547,86 @@ function handleVersionContextMenu(event: MouseEvent, version: Torrent) {
|
||||
filePath: version.playable_file || null,
|
||||
rootName: props.getRootName(rootId) || null,
|
||||
rootId,
|
||||
};
|
||||
}
|
||||
nextTick(() => {
|
||||
const firstAction = document.querySelector('.version-action-menu .version-action-item:not(:disabled)') as HTMLElement | null;
|
||||
firstAction?.focus();
|
||||
});
|
||||
const firstAction = document.querySelector(
|
||||
".version-action-menu .version-action-item:not(:disabled)",
|
||||
) as HTMLElement | null
|
||||
firstAction?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
function handleVersionShortcutKeydown(event: KeyboardEvent, version: Torrent) {
|
||||
if (!version.playable_file) return;
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id);
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === 'e' && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleOpenFolder(version.playable_file, rootId);
|
||||
return;
|
||||
if (!version.playable_file) return
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id)
|
||||
const key = event.key.toLowerCase()
|
||||
if (key === "e" && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
handleOpenFolder(version.playable_file, rootId)
|
||||
return
|
||||
}
|
||||
if (key === 'enter' && event.altKey) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleOpenFolder(version.playable_file, rootId);
|
||||
if (key === "enter" && event.altKey) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
handleOpenFolder(version.playable_file, rootId)
|
||||
}
|
||||
}
|
||||
|
||||
function handleMovieMenuKeydown(event: KeyboardEvent) {
|
||||
if (!versionActionMenu.value.visible) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
closeVersionActionMenu();
|
||||
if (!versionActionMenu.value.visible) return
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
closeVersionActionMenu()
|
||||
}
|
||||
}
|
||||
|
||||
// Select first season by default
|
||||
watch(seasons, (s) => {
|
||||
if (s.length > 0 && selectedSeasonIndex.value >= s.length) {
|
||||
selectedSeasonIndex.value = 0;
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
seasons,
|
||||
(s) => {
|
||||
if (s.length > 0 && selectedSeasonIndex.value >= s.length) {
|
||||
selectedSeasonIndex.value = 0
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function handlePlay(filePath: string | null) {
|
||||
if (filePath) {
|
||||
emit('play', filePath);
|
||||
emit("play", filePath)
|
||||
}
|
||||
}
|
||||
|
||||
function handleVersionActivate(version: Torrent, event: MouseEvent | KeyboardEvent) {
|
||||
if (!version.playable_file) return;
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id);
|
||||
if (!version.playable_file) return
|
||||
const rootId = version.root_id || ((props.item.data as Movie).root_id ?? props.item.root_id)
|
||||
if (event.altKey) {
|
||||
handleOpenFolder(version.playable_file, rootId);
|
||||
return;
|
||||
handleOpenFolder(version.playable_file, rootId)
|
||||
return
|
||||
}
|
||||
handlePlay(version.playable_file);
|
||||
handlePlay(version.playable_file)
|
||||
}
|
||||
|
||||
function handleOpenFolder(folderPath: string, rootId?: string | null) {
|
||||
closeVersionActionMenu();
|
||||
emit('openFolder', folderPath, rootId);
|
||||
closeVersionActionMenu()
|
||||
emit("openFolder", folderPath, rootId)
|
||||
}
|
||||
|
||||
function handleCastSelect(castName: string) {
|
||||
const name = castName.trim();
|
||||
if (!name) return;
|
||||
emit('searchActor', name);
|
||||
const name = castName.trim()
|
||||
if (!name) return
|
||||
emit("searchActor", name)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('keydown', handleMovieMenuKeydown, true);
|
||||
});
|
||||
document.addEventListener("keydown", handleMovieMenuKeydown, true)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('keydown', handleMovieMenuKeydown, true);
|
||||
});
|
||||
document.removeEventListener("keydown", handleMovieMenuKeydown, true)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -618,7 +646,7 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.movie-page-content::before {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 300px;
|
||||
/* Start clipped edge at reel 2/3 split bottom (y=300): 40vw - 0.8rem. */
|
||||
@@ -626,15 +654,16 @@ onUnmounted(() => {
|
||||
width: calc(40vw + 0.8rem);
|
||||
max-width: calc(100vw - 24px);
|
||||
height: var(--header-height);
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 0.72) 0%,
|
||||
rgba(5, 7, 10, 0.5) 100%
|
||||
);
|
||||
background: linear-gradient(to bottom, rgba(5, 7, 10, 0.72) 0%, rgba(5, 7, 10, 0.5) 100%);
|
||||
-webkit-backdrop-filter: blur(10px) saturate(115%);
|
||||
backdrop-filter: blur(10px) saturate(115%);
|
||||
/* Match reel slant angle: 2rem horizontal shift over 300px reel height. */
|
||||
-webkit-clip-path: polygon(0 0, 100% 0, calc(100% - (var(--header-height) * 0.1067)) 100%, 0 100%);
|
||||
-webkit-clip-path: polygon(
|
||||
0 0,
|
||||
100% 0,
|
||||
calc(100% - (var(--header-height) * 0.1067)) 100%,
|
||||
0 100%
|
||||
);
|
||||
clip-path: polygon(0 0, 100% 0, calc(100% - (var(--header-height) * 0.1067)) 100%, 0 100%);
|
||||
pointer-events: none;
|
||||
z-index: 30;
|
||||
@@ -675,8 +704,8 @@ onUnmounted(() => {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(260px, 360px) minmax(0, 1fr) minmax(240px, 320px);
|
||||
grid-template-areas:
|
||||
'left cast cast'
|
||||
'left main right';
|
||||
"left cast cast"
|
||||
"left main right";
|
||||
gap: 32px;
|
||||
align-items: start;
|
||||
position: relative;
|
||||
@@ -921,7 +950,7 @@ onUnmounted(() => {
|
||||
}
|
||||
|
||||
.cast-card::after {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
@@ -961,7 +990,12 @@ html:not(.mouse-active) .cast-card.nav-focused::after {
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
padding: 28px 8px 8px;
|
||||
background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.78) 45%, rgba(0, 0, 0, 0.95) 100%);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
rgba(0, 0, 0, 0) 0%,
|
||||
rgba(0, 0, 0, 0.78) 45%,
|
||||
rgba(0, 0, 0, 0.95) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.cast-name {
|
||||
@@ -983,9 +1017,9 @@ html:not(.mouse-active) .cast-card.nav-focused::after {
|
||||
.content-layout {
|
||||
grid-template-columns: minmax(240px, 320px) minmax(0, 1fr);
|
||||
grid-template-areas:
|
||||
'left cast'
|
||||
'left main'
|
||||
'left right';
|
||||
"left cast"
|
||||
"left main"
|
||||
"left right";
|
||||
gap: 24px;
|
||||
}
|
||||
}
|
||||
@@ -994,10 +1028,10 @@ html:not(.mouse-active) .cast-card.nav-focused::after {
|
||||
.content-layout {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-areas:
|
||||
'left'
|
||||
'cast'
|
||||
'main'
|
||||
'right';
|
||||
"left"
|
||||
"cast"
|
||||
"main"
|
||||
"right";
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
@@ -1093,7 +1127,9 @@ html.mouse-active .showreel-image:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
transition:
|
||||
background 0.2s,
|
||||
border-color 0.2s;
|
||||
}
|
||||
|
||||
html.mouse-active .version-item:hover {
|
||||
@@ -1290,7 +1326,9 @@ html.mouse-active .version-item:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
transition:
|
||||
background 0.2s,
|
||||
border-color 0.2s;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -1541,14 +1579,10 @@ html.mouse-active .release-item:hover {
|
||||
|
||||
/* Subtle vignette on each collage image */
|
||||
.collage-header .collage-item::before {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
transparent 0%,
|
||||
rgba(0, 0, 0, 0.3) 100%
|
||||
);
|
||||
background: linear-gradient(to bottom, transparent 0%, rgba(0, 0, 0, 0.3) 100%);
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
}
|
||||
@@ -1646,5 +1680,4 @@ html.mouse-active .release-item:hover {
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
@@ -16,16 +16,16 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { MediaItem } from '../types';
|
||||
import MediaCard from './MediaCard.vue';
|
||||
import type { MediaItem } from "../types"
|
||||
import MediaCard from "./MediaCard.vue"
|
||||
|
||||
defineProps<{
|
||||
items: MediaItem[];
|
||||
wrap?: boolean;
|
||||
rowIndex?: number;
|
||||
}>();
|
||||
items: MediaItem[]
|
||||
wrap?: boolean
|
||||
rowIndex?: number
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
select: [MediaItem];
|
||||
}>();
|
||||
select: [MediaItem]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
@@ -1,33 +1,24 @@
|
||||
<template>
|
||||
<div
|
||||
v-if="visible"
|
||||
ref="menuRef"
|
||||
class="version-action-menu"
|
||||
:style="menuStyle"
|
||||
>
|
||||
<div v-if="visible" ref="menuRef" class="version-action-menu" :style="menuStyle">
|
||||
<div class="version-action-path" :title="resolvedPath">
|
||||
{{ resolvedPath }}
|
||||
</div>
|
||||
<button
|
||||
class="version-action-item"
|
||||
:disabled="disabled"
|
||||
@click="emit('play')"
|
||||
>
|
||||
<button class="version-action-item" :disabled="disabled" @click="emit('play')">
|
||||
<span class="version-action-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" focusable="false">
|
||||
<path d="M4 3.2c0-.54.6-.86 1.05-.56l6.2 4.14a.67.67 0 0 1 0 1.12l-6.2 4.14A.67.67 0 0 1 4 11.44V3.2Z" />
|
||||
<path
|
||||
d="M4 3.2c0-.54.6-.86 1.05-.56l6.2 4.14a.67.67 0 0 1 0 1.12l-6.2 4.14A.67.67 0 0 1 4 11.44V3.2Z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
{{ playLabel }}
|
||||
</button>
|
||||
<button
|
||||
class="version-action-item"
|
||||
:disabled="disabled"
|
||||
@click="emit('openFolder')"
|
||||
>
|
||||
<button class="version-action-item" :disabled="disabled" @click="emit('openFolder')">
|
||||
<span class="version-action-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" focusable="false">
|
||||
<path d="M1.4 4.3c0-.72.58-1.3 1.3-1.3h3.55c.3 0 .58.13.77.35l.72.85h5.56c.72 0 1.3.58 1.3 1.3v.92H1.4V4.3Zm0 3.22h13.2v4.2c0 .72-.58 1.3-1.3 1.3H2.7c-.72 0-1.3-.58-1.3-1.3v-4.2Z" />
|
||||
<path
|
||||
d="M1.4 4.3c0-.72.58-1.3 1.3-1.3h3.55c.3 0 .58.13.77.35l.72.85h5.56c.72 0 1.3.58 1.3 1.3v.92H1.4V4.3Zm0 3.22h13.2v4.2c0 .72-.58 1.3-1.3 1.3H2.7c-.72 0-1.3-.58-1.3-1.3v-4.2Z"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
Open Folder
|
||||
@@ -36,93 +27,96 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue"
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
visible: boolean;
|
||||
x: number;
|
||||
y: number;
|
||||
filePath: string | null;
|
||||
rootName?: string | null;
|
||||
playLabel?: string;
|
||||
}>(), {
|
||||
rootName: null,
|
||||
playLabel: 'Play',
|
||||
});
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
filePath: string | null
|
||||
rootName?: string | null
|
||||
playLabel?: string
|
||||
}>(),
|
||||
{
|
||||
rootName: null,
|
||||
playLabel: "Play",
|
||||
},
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
play: [];
|
||||
openFolder: [];
|
||||
}>();
|
||||
play: []
|
||||
openFolder: []
|
||||
}>()
|
||||
|
||||
const menuRef = ref<HTMLElement | null>(null);
|
||||
const menuLeft = ref(0);
|
||||
const menuTop = ref(0);
|
||||
const VIEWPORT_MARGIN = 12;
|
||||
const menuRef = ref<HTMLElement | null>(null)
|
||||
const menuLeft = ref(0)
|
||||
const menuTop = ref(0)
|
||||
const VIEWPORT_MARGIN = 12
|
||||
|
||||
function toPosixPath(value: string | null | undefined): string {
|
||||
return (value || '').replace(/\\/g, '/');
|
||||
return (value || "").replace(/\\/g, "/")
|
||||
}
|
||||
|
||||
const resolvedPath = computed(() => {
|
||||
if (!props.filePath) return 'No playable file';
|
||||
const normalizedFilePath = toPosixPath(props.filePath);
|
||||
const rootName = toPosixPath((props.rootName || '').trim());
|
||||
if (!rootName) return normalizedFilePath;
|
||||
return `${rootName}/${normalizedFilePath}`;
|
||||
});
|
||||
if (!props.filePath) return "No playable file"
|
||||
const normalizedFilePath = toPosixPath(props.filePath)
|
||||
const rootName = toPosixPath((props.rootName || "").trim())
|
||||
if (!rootName) return normalizedFilePath
|
||||
return `${rootName}/${normalizedFilePath}`
|
||||
})
|
||||
|
||||
const menuStyle = computed(() => ({
|
||||
left: `${menuLeft.value}px`,
|
||||
top: `${menuTop.value}px`,
|
||||
}));
|
||||
}))
|
||||
|
||||
const disabled = computed(() => !props.filePath);
|
||||
const disabled = computed(() => !props.filePath)
|
||||
|
||||
function clampToViewport() {
|
||||
const menu = menuRef.value;
|
||||
if (!menu) return;
|
||||
const menu = menuRef.value
|
||||
if (!menu) return
|
||||
|
||||
const width = menu.offsetWidth;
|
||||
const height = menu.offsetHeight;
|
||||
const width = menu.offsetWidth
|
||||
const height = menu.offsetHeight
|
||||
|
||||
const maxLeft = Math.max(VIEWPORT_MARGIN, window.innerWidth - width - VIEWPORT_MARGIN);
|
||||
const maxTop = Math.max(VIEWPORT_MARGIN, window.innerHeight - height - VIEWPORT_MARGIN);
|
||||
const maxLeft = Math.max(VIEWPORT_MARGIN, window.innerWidth - width - VIEWPORT_MARGIN)
|
||||
const maxTop = Math.max(VIEWPORT_MARGIN, window.innerHeight - height - VIEWPORT_MARGIN)
|
||||
|
||||
menuLeft.value = Math.min(Math.max(props.x, VIEWPORT_MARGIN), maxLeft);
|
||||
menuTop.value = Math.min(Math.max(props.y, VIEWPORT_MARGIN), maxTop);
|
||||
menuLeft.value = Math.min(Math.max(props.x, VIEWPORT_MARGIN), maxLeft)
|
||||
menuTop.value = Math.min(Math.max(props.y, VIEWPORT_MARGIN), maxTop)
|
||||
}
|
||||
|
||||
function handleViewportChange() {
|
||||
if (!props.visible) return;
|
||||
clampToViewport();
|
||||
if (!props.visible) return
|
||||
clampToViewport()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.x, props.y, resolvedPath.value],
|
||||
async ([visible]) => {
|
||||
if (!visible) return;
|
||||
await nextTick();
|
||||
clampToViewport();
|
||||
if (!visible) return
|
||||
await nextTick()
|
||||
clampToViewport()
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
window.addEventListener('resize', handleViewportChange);
|
||||
return;
|
||||
window.addEventListener("resize", handleViewportChange)
|
||||
return
|
||||
}
|
||||
window.removeEventListener('resize', handleViewportChange);
|
||||
window.removeEventListener("resize", handleViewportChange)
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('resize', handleViewportChange);
|
||||
});
|
||||
window.removeEventListener("resize", handleViewportChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -22,43 +22,47 @@
|
||||
<span v-if="displayCodecBadge" class="v-badge codec">{{ displayCodecBadge }}</span>
|
||||
<span v-if="displayQualityBadge" class="v-badge qual">{{ displayQualityBadge }}</span>
|
||||
<span v-if="displayAudioBadge" class="v-badge audio">{{ displayAudioBadge }}</span>
|
||||
<span v-if="displayReleaseGroupBadge" class="v-badge group">{{ displayReleaseGroupBadge }}</span>
|
||||
<span v-if="displayReleaseGroupBadge" class="v-badge group">{{
|
||||
displayReleaseGroupBadge
|
||||
}}</span>
|
||||
</div>
|
||||
<div class="version-language-flags">
|
||||
<LanguageFlags class="language-flags-audio" :codes="torrent.audio_languages" :compact="compactFlags" />
|
||||
<LanguageFlags
|
||||
class="language-flags-audio"
|
||||
:codes="torrent.audio_languages"
|
||||
:compact="compactFlags"
|
||||
/>
|
||||
<span
|
||||
v-if="hasLanguageDisplay(torrent.audio_languages) && hasLanguageDisplay(torrent.subtitle_languages)"
|
||||
v-if="
|
||||
hasLanguageDisplay(torrent.audio_languages) &&
|
||||
hasLanguageDisplay(torrent.subtitle_languages)
|
||||
"
|
||||
class="language-separator"
|
||||
>•</span>
|
||||
<LanguageFlags class="language-flags-subs" :codes="torrent.subtitle_languages" :compact="compactFlags" />
|
||||
>•</span
|
||||
>
|
||||
<LanguageFlags
|
||||
class="language-flags-subs"
|
||||
:codes="torrent.subtitle_languages"
|
||||
:compact="compactFlags"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="version-dolby-cell">
|
||||
<img
|
||||
v-if="showBlurayLogo"
|
||||
class="version-disc-logo"
|
||||
:src="blurayLogoUrl"
|
||||
alt="Blu-ray"
|
||||
>
|
||||
<img
|
||||
v-else-if="showDvdLogo"
|
||||
class="version-disc-logo"
|
||||
:src="dvdLogoUrl"
|
||||
alt="DVD"
|
||||
>
|
||||
<img v-if="showBlurayLogo" class="version-disc-logo" :src="blurayLogoUrl" alt="Blu-ray" />
|
||||
<img v-else-if="showDvdLogo" class="version-disc-logo" :src="dvdLogoUrl" alt="DVD" />
|
||||
<img
|
||||
v-if="streamingServiceLogo"
|
||||
class="version-service-logo"
|
||||
:src="streamingServiceLogo.src"
|
||||
:alt="streamingServiceLogo.alt"
|
||||
:title="streamingServiceLogo.alt"
|
||||
>
|
||||
<DolbyBadges
|
||||
class="version-dolby"
|
||||
:has-dolby-vision="hasDolbyVision"
|
||||
:has-dolby-atmos="hasDolbyAtmos"
|
||||
:is-hdr="hasHdr"
|
||||
/>
|
||||
/>
|
||||
<DolbyBadges
|
||||
class="version-dolby"
|
||||
:has-dolby-vision="hasDolbyVision"
|
||||
:has-dolby-atmos="hasDolbyAtmos"
|
||||
:is-hdr="hasHdr"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="showActions" class="version-actions">
|
||||
<button
|
||||
@@ -66,225 +70,273 @@
|
||||
tabindex="0"
|
||||
@click.stop="emit('play')"
|
||||
:disabled="!torrent.playable_file"
|
||||
>▶ {{ playLabel }}</button>
|
||||
>
|
||||
▶ {{ playLabel }}
|
||||
</button>
|
||||
<button
|
||||
class="ctx-btn ctx-btn-folder"
|
||||
tabindex="0"
|
||||
@click.stop="emit('openFolder')"
|
||||
:disabled="!torrent.playable_file"
|
||||
>📁</button>
|
||||
>
|
||||
📁
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import type { Torrent } from '../types';
|
||||
import LanguageFlags from './LanguageFlags.vue';
|
||||
import DolbyBadges from './DolbyBadges.vue';
|
||||
import { buildLanguageFlags } from '../utils/languageFlags';
|
||||
import blurayLogoUrl from '../assets/bluray.webp';
|
||||
import dvdLogoUrl from '../assets/dvd.webp';
|
||||
import amazonLogoUrl from '../assets/service-amazon.webp';
|
||||
import appleTvLogoUrl from '../assets/service-apple-tv.webp';
|
||||
import netflixLogoUrl from '../assets/service-netflix.webp';
|
||||
import hboMaxLogoUrl from '../assets/service-hbo-max.webp';
|
||||
import huluLogoUrl from '../assets/service-hulu.webp';
|
||||
import disneyLogoUrl from '../assets/service-disney.svg';
|
||||
import itunesLogoUrl from '../assets/service-itunes.png';
|
||||
import { computed } from "vue"
|
||||
import type { Torrent } from "../types"
|
||||
import LanguageFlags from "./LanguageFlags.vue"
|
||||
import DolbyBadges from "./DolbyBadges.vue"
|
||||
import { buildLanguageFlags } from "../utils/languageFlags"
|
||||
import blurayLogoUrl from "../assets/bluray.webp"
|
||||
import dvdLogoUrl from "../assets/dvd.webp"
|
||||
import amazonLogoUrl from "../assets/service-amazon.webp"
|
||||
import appleTvLogoUrl from "../assets/service-apple-tv.webp"
|
||||
import netflixLogoUrl from "../assets/service-netflix.webp"
|
||||
import hboMaxLogoUrl from "../assets/service-hbo-max.webp"
|
||||
import huluLogoUrl from "../assets/service-hulu.webp"
|
||||
import disneyLogoUrl from "../assets/service-disney.svg"
|
||||
import itunesLogoUrl from "../assets/service-itunes.png"
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false,
|
||||
});
|
||||
})
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
torrent: Torrent;
|
||||
best?: boolean;
|
||||
selectable?: boolean;
|
||||
disabled?: boolean;
|
||||
compactFlags?: boolean;
|
||||
showActions?: boolean;
|
||||
playLabel?: string;
|
||||
title?: string;
|
||||
variant?: 'default' | 'menu';
|
||||
}>(), {
|
||||
best: false,
|
||||
selectable: undefined,
|
||||
disabled: undefined,
|
||||
compactFlags: false,
|
||||
showActions: false,
|
||||
playLabel: 'Play',
|
||||
title: undefined,
|
||||
variant: 'default',
|
||||
});
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
torrent: Torrent
|
||||
best?: boolean
|
||||
selectable?: boolean
|
||||
disabled?: boolean
|
||||
compactFlags?: boolean
|
||||
showActions?: boolean
|
||||
playLabel?: string
|
||||
title?: string
|
||||
variant?: "default" | "menu"
|
||||
}>(),
|
||||
{
|
||||
best: false,
|
||||
selectable: undefined,
|
||||
disabled: undefined,
|
||||
compactFlags: false,
|
||||
showActions: false,
|
||||
playLabel: "Play",
|
||||
title: undefined,
|
||||
variant: "default",
|
||||
},
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
activate: [MouseEvent | KeyboardEvent];
|
||||
play: [];
|
||||
openFolder: [];
|
||||
}>();
|
||||
activate: [MouseEvent | KeyboardEvent]
|
||||
play: []
|
||||
openFolder: []
|
||||
}>()
|
||||
|
||||
const dolbyTagPattern = /\b(dolby|atmos|vision|dovi|dv)\b/i;
|
||||
const dolbyVisionPattern = /\b(dolby\s*vision|dovi|\bdv\b)\b/i;
|
||||
const dolbyAtmosPattern = /\b(dolby\s*atmos|atmos)\b/i;
|
||||
const hdrPattern = /\bhdr\b|smpte\s*2084|bt\s*2020|hlg/i;
|
||||
const blurayTagPattern = /\bblu[\s.-]*ray\b/i;
|
||||
const blurayPlayablePattern = /(?:^|[\\/])(movieobject|index)\.bdmv$/i;
|
||||
const dvdPlayablePattern = /(?:^|[\\/])video_ts\.ifo$/i;
|
||||
const webQualityPattern = /^web(?:[ .-]?dl|[ .-]?rip)$/i;
|
||||
const dolbyTagPattern = /\b(dolby|atmos|vision|dovi|dv)\b/i
|
||||
const dolbyVisionPattern = /\b(dolby\s*vision|dovi|\bdv\b)\b/i
|
||||
const dolbyAtmosPattern = /\b(dolby\s*atmos|atmos)\b/i
|
||||
const hdrPattern = /\bhdr\b|smpte\s*2084|bt\s*2020|hlg/i
|
||||
const blurayTagPattern = /\bblu[\s.-]*ray\b/i
|
||||
const blurayPlayablePattern = /(?:^|[\\/])(movieobject|index)\.bdmv$/i
|
||||
const dvdPlayablePattern = /(?:^|[\\/])video_ts\.ifo$/i
|
||||
const webQualityPattern = /^web(?:[ .-]?dl|[ .-]?rip)$/i
|
||||
|
||||
const serviceLogoMap: Array<{ aliases: string[]; src: string; alt: string }> = [
|
||||
{ aliases: ['amazon studios', 'amazon prime video', 'prime video', 'amazon', 'amzn'], src: amazonLogoUrl, alt: 'Amazon Prime Video' },
|
||||
{ aliases: ['apple tv+', 'apple tv plus', 'apple tv', 'atvp'], src: appleTvLogoUrl, alt: 'Apple TV+' },
|
||||
{ aliases: ['itunes', 'it'], src: itunesLogoUrl, alt: 'iTunes' },
|
||||
{ aliases: ['netflix', 'nf', 'nflx'], src: netflixLogoUrl, alt: 'Netflix' },
|
||||
{ aliases: ['hbo max', 'max', 'hmax'], src: hboMaxLogoUrl, alt: 'HBO Max' },
|
||||
{ aliases: ['disney plus', 'disney+', 'disney plus hotstar', 'dsnp'], src: disneyLogoUrl, alt: 'Disney+' },
|
||||
{ aliases: ['hulu'], src: huluLogoUrl, alt: 'Hulu' },
|
||||
];
|
||||
{
|
||||
aliases: ["amazon studios", "amazon prime video", "prime video", "amazon", "amzn"],
|
||||
src: amazonLogoUrl,
|
||||
alt: "Amazon Prime Video",
|
||||
},
|
||||
{
|
||||
aliases: ["apple tv+", "apple tv plus", "apple tv", "atvp"],
|
||||
src: appleTvLogoUrl,
|
||||
alt: "Apple TV+",
|
||||
},
|
||||
{ aliases: ["itunes", "it"], src: itunesLogoUrl, alt: "iTunes" },
|
||||
{ aliases: ["netflix", "nf", "nflx"], src: netflixLogoUrl, alt: "Netflix" },
|
||||
{ aliases: ["hbo max", "max", "hmax"], src: hboMaxLogoUrl, alt: "HBO Max" },
|
||||
{
|
||||
aliases: ["disney plus", "disney+", "disney plus hotstar", "dsnp"],
|
||||
src: disneyLogoUrl,
|
||||
alt: "Disney+",
|
||||
},
|
||||
{ aliases: ["hulu"], src: huluLogoUrl, alt: "Hulu" },
|
||||
]
|
||||
|
||||
function hasDolbyTag(value: string | null | undefined): boolean {
|
||||
return Boolean(value && dolbyTagPattern.test(value));
|
||||
return Boolean(value && dolbyTagPattern.test(value))
|
||||
}
|
||||
|
||||
function hasAnyTag(
|
||||
pattern: RegExp,
|
||||
...values: Array<string | null | undefined>
|
||||
): boolean {
|
||||
return values.some((value) => Boolean(value && pattern.test(value)));
|
||||
function hasAnyTag(pattern: RegExp, ...values: Array<string | null | undefined>): boolean {
|
||||
return values.some((value) => Boolean(value && pattern.test(value)))
|
||||
}
|
||||
|
||||
function hasLanguageDisplay(codes: string[] | null | undefined): boolean {
|
||||
const mapped = buildLanguageFlags(codes);
|
||||
return mapped.flags.length > 0 || mapped.unmappedCodes.length > 0;
|
||||
const mapped = buildLanguageFlags(codes)
|
||||
return mapped.flags.length > 0 || mapped.unmappedCodes.length > 0
|
||||
}
|
||||
|
||||
function hasHdrTag(value: string | null | undefined): boolean {
|
||||
return Boolean(value && hdrPattern.test(value));
|
||||
return Boolean(value && hdrPattern.test(value))
|
||||
}
|
||||
|
||||
function normalizeProviderName(value: string | null | undefined): string {
|
||||
return (value || '').toLowerCase().replace(/[^a-z0-9+]+/g, ' ').trim();
|
||||
return (value || "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9+]+/g, " ")
|
||||
.trim()
|
||||
}
|
||||
|
||||
function normalizeQualityBadge(value: string): string {
|
||||
const normalized = value.toLowerCase().replace(/[^a-z0-9]+/g, '');
|
||||
const normalized = value.toLowerCase().replace(/[^a-z0-9]+/g, "")
|
||||
|
||||
if (normalized === 'hdtv' || normalized === 'pdtv' || normalized === 'tvrip' || normalized === 'sdtv') {
|
||||
return 'TV';
|
||||
if (
|
||||
normalized === "hdtv" ||
|
||||
normalized === "pdtv" ||
|
||||
normalized === "tvrip" ||
|
||||
normalized === "sdtv"
|
||||
) {
|
||||
return "TV"
|
||||
}
|
||||
|
||||
if (
|
||||
normalized.includes('cam')
|
||||
|| normalized === 'telesync'
|
||||
|| normalized === 'ts'
|
||||
|| normalized === 'hdts'
|
||||
|| normalized === 'telecine'
|
||||
|| normalized === 'tc'
|
||||
normalized.includes("cam") ||
|
||||
normalized === "telesync" ||
|
||||
normalized === "ts" ||
|
||||
normalized === "hdts" ||
|
||||
normalized === "telecine" ||
|
||||
normalized === "tc"
|
||||
) {
|
||||
return 'CAM';
|
||||
return "CAM"
|
||||
}
|
||||
|
||||
return value;
|
||||
return value
|
||||
}
|
||||
|
||||
const hasDolbyVision = computed(() => {
|
||||
return (
|
||||
props.torrent.has_dolby_vision === true
|
||||
|| hasAnyTag(dolbyVisionPattern, props.torrent.quality, props.torrent.codec, props.torrent.audio, props.torrent.title)
|
||||
);
|
||||
});
|
||||
props.torrent.has_dolby_vision === true ||
|
||||
hasAnyTag(
|
||||
dolbyVisionPattern,
|
||||
props.torrent.quality,
|
||||
props.torrent.codec,
|
||||
props.torrent.audio,
|
||||
props.torrent.title,
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
const hasDolbyAtmos = computed(() => {
|
||||
return (
|
||||
props.torrent.has_dolby_atmos === true
|
||||
|| hasAnyTag(dolbyAtmosPattern, props.torrent.quality, props.torrent.codec, props.torrent.audio, props.torrent.title)
|
||||
);
|
||||
});
|
||||
props.torrent.has_dolby_atmos === true ||
|
||||
hasAnyTag(
|
||||
dolbyAtmosPattern,
|
||||
props.torrent.quality,
|
||||
props.torrent.codec,
|
||||
props.torrent.audio,
|
||||
props.torrent.title,
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
const hasHdr = computed(() => {
|
||||
return (
|
||||
props.torrent.is_hdr === true
|
||||
|| hasAnyTag(hdrPattern, props.torrent.quality, props.torrent.codec, props.torrent.audio, props.torrent.title)
|
||||
);
|
||||
});
|
||||
props.torrent.is_hdr === true ||
|
||||
hasAnyTag(
|
||||
hdrPattern,
|
||||
props.torrent.quality,
|
||||
props.torrent.codec,
|
||||
props.torrent.audio,
|
||||
props.torrent.title,
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
const isBlurayDisc = computed(() => {
|
||||
if (!props.torrent.playable_file) return false;
|
||||
return blurayPlayablePattern.test(props.torrent.playable_file);
|
||||
});
|
||||
if (!props.torrent.playable_file) return false
|
||||
return blurayPlayablePattern.test(props.torrent.playable_file)
|
||||
})
|
||||
|
||||
const isDvdDisc = computed(() => {
|
||||
if (!props.torrent.playable_file) return false;
|
||||
return dvdPlayablePattern.test(props.torrent.playable_file);
|
||||
});
|
||||
if (!props.torrent.playable_file) return false
|
||||
return dvdPlayablePattern.test(props.torrent.playable_file)
|
||||
})
|
||||
|
||||
const showBlurayLogo = computed(() => {
|
||||
return isBlurayDisc.value;
|
||||
});
|
||||
return isBlurayDisc.value
|
||||
})
|
||||
|
||||
const showDvdLogo = computed(() => {
|
||||
return isDvdDisc.value;
|
||||
});
|
||||
return isDvdDisc.value
|
||||
})
|
||||
|
||||
const streamingServiceLogo = computed(() => {
|
||||
if (!props.torrent.quality || !webQualityPattern.test(props.torrent.quality)) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
const network = normalizeProviderName(props.torrent.network);
|
||||
if (!network) return null;
|
||||
const network = normalizeProviderName(props.torrent.network)
|
||||
if (!network) return null
|
||||
|
||||
const found = serviceLogoMap.find((entry) => entry.aliases.includes(network));
|
||||
return found ? { src: found.src, alt: found.alt } : null;
|
||||
});
|
||||
const found = serviceLogoMap.find((entry) => entry.aliases.includes(network))
|
||||
return found ? { src: found.src, alt: found.alt } : null
|
||||
})
|
||||
|
||||
const displayQualityBadge = computed(() => {
|
||||
if (!props.torrent.quality || hasDolbyTag(props.torrent.quality)) return null;
|
||||
if (streamingServiceLogo.value) return null;
|
||||
if (blurayTagPattern.test(props.torrent.quality)) return null;
|
||||
return normalizeQualityBadge(props.torrent.quality);
|
||||
});
|
||||
if (!props.torrent.quality || hasDolbyTag(props.torrent.quality)) return null
|
||||
if (streamingServiceLogo.value) return null
|
||||
if (blurayTagPattern.test(props.torrent.quality)) return null
|
||||
return normalizeQualityBadge(props.torrent.quality)
|
||||
})
|
||||
|
||||
const displayCodecBadge = computed(() => {
|
||||
if (!props.torrent.codec || hasDolbyTag(props.torrent.codec)) return null;
|
||||
return props.torrent.codec;
|
||||
});
|
||||
if (!props.torrent.codec || hasDolbyTag(props.torrent.codec)) return null
|
||||
return props.torrent.codec
|
||||
})
|
||||
|
||||
const displayAudioBadge = computed(() => {
|
||||
if (!props.torrent.audio || hasDolbyTag(props.torrent.audio)) return null;
|
||||
return props.torrent.audio;
|
||||
});
|
||||
if (!props.torrent.audio || hasDolbyTag(props.torrent.audio)) return null
|
||||
return props.torrent.audio
|
||||
})
|
||||
|
||||
const displayReleaseGroupBadge = computed(() => {
|
||||
const value = props.torrent.encoder?.trim();
|
||||
if (!value) return null;
|
||||
return value;
|
||||
});
|
||||
const value = props.torrent.encoder?.trim()
|
||||
if (!value) return null
|
||||
return value
|
||||
})
|
||||
|
||||
const showHdrBadge = computed(() => {
|
||||
if (!hasHdr.value) return false;
|
||||
return !hasHdrTag(props.torrent.quality) && !hasHdrTag(props.torrent.codec) && !hasHdrTag(props.torrent.audio);
|
||||
});
|
||||
if (!hasHdr.value) return false
|
||||
return (
|
||||
!hasHdrTag(props.torrent.quality) &&
|
||||
!hasHdrTag(props.torrent.codec) &&
|
||||
!hasHdrTag(props.torrent.audio)
|
||||
)
|
||||
})
|
||||
|
||||
const isSelectable = computed(() => {
|
||||
if (props.selectable !== undefined) return props.selectable;
|
||||
return Boolean(props.torrent.playable_file);
|
||||
});
|
||||
if (props.selectable !== undefined) return props.selectable
|
||||
return Boolean(props.torrent.playable_file)
|
||||
})
|
||||
|
||||
const isDisabled = computed(() => {
|
||||
if (props.disabled !== undefined) return props.disabled;
|
||||
return !isSelectable.value;
|
||||
});
|
||||
if (props.disabled !== undefined) return props.disabled
|
||||
return !isSelectable.value
|
||||
})
|
||||
|
||||
const resolvedTitle = computed(() => {
|
||||
if (props.title !== undefined) return props.title;
|
||||
return isSelectable.value ? 'Click to play/continue. Alt+Click to open folder.' : 'No playable file';
|
||||
});
|
||||
if (props.title !== undefined) return props.title
|
||||
return isSelectable.value
|
||||
? "Click to play/continue. Alt+Click to open folder."
|
||||
: "No playable file"
|
||||
})
|
||||
|
||||
function handleActivate(event: MouseEvent | KeyboardEvent) {
|
||||
if (!isSelectable.value || isDisabled.value) return;
|
||||
emit('activate', event);
|
||||
if (!isSelectable.value || isDisabled.value) return
|
||||
emit("activate", event)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -301,7 +353,9 @@ function handleActivate(event: MouseEvent | KeyboardEvent) {
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: background 0.2s, border-color 0.2s;
|
||||
transition:
|
||||
background 0.2s,
|
||||
border-color 0.2s;
|
||||
}
|
||||
|
||||
.version-row.version-menu {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<template>
|
||||
<div class="series-fullscreen">
|
||||
|
||||
<!-- Hero section with backdrop or season collage -->
|
||||
<section class="series-hero">
|
||||
<div class="hero-bg">
|
||||
<!-- Use backdrop if available, otherwise create collage from season posters -->
|
||||
<img v-if="backdropUrl" :src="backdropUrl" class="hero-img" :alt="series.title || 'Unknown'" />
|
||||
<img
|
||||
v-if="backdropUrl"
|
||||
:src="backdropUrl"
|
||||
class="hero-img"
|
||||
:alt="series.title || 'Unknown'"
|
||||
/>
|
||||
<div v-else class="hero-collage">
|
||||
<div
|
||||
v-for="(season, i) in seasonsWithPosters.slice(0, 5)"
|
||||
@@ -19,10 +23,16 @@
|
||||
<div class="hero-content">
|
||||
<h1 class="series-title">{{ series.title }}</h1>
|
||||
<div class="series-meta">
|
||||
<span v-if="series.info?.rating" class="meta-rating" :class="ratingClass">★ {{ series.info.rating.toFixed(1) }}</span>
|
||||
<span v-if="series.info?.number_of_seasons" class="meta-item">{{ series.info.number_of_seasons }} Seasons</span>
|
||||
<span v-if="series.info?.rating" class="meta-rating" :class="ratingClass"
|
||||
>★ {{ series.info.rating.toFixed(1) }}</span
|
||||
>
|
||||
<span v-if="series.info?.number_of_seasons" class="meta-item"
|
||||
>{{ series.info.number_of_seasons }} Seasons</span
|
||||
>
|
||||
<span v-if="series.info?.status" class="meta-badge">{{ series.info.status }}</span>
|
||||
<span v-if="series.info?.genres?.length" class="meta-genres">{{ series.info.genres.slice(0, 3).join(' • ') }}</span>
|
||||
<span v-if="series.info?.genres?.length" class="meta-genres">{{
|
||||
series.info.genres.slice(0, 3).join(" • ")
|
||||
}}</span>
|
||||
</div>
|
||||
<p v-if="series.info?.overview" class="series-overview">{{ series.info.overview }}</p>
|
||||
</div>
|
||||
@@ -53,7 +63,9 @@
|
||||
</div>
|
||||
<div class="poster-overlay">
|
||||
<div class="season-label">{{ season.name || `Season ${season.season_number}` }}</div>
|
||||
<div v-if="season.overview" class="season-overview-short">{{ truncate(season.overview, 120) }}</div>
|
||||
<div v-if="season.overview" class="season-overview-short">
|
||||
{{ truncate(season.overview, 120) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -80,7 +92,7 @@
|
||||
<div class="tile-bg">
|
||||
<video
|
||||
v-if="getEpisodeVideoSources(episode).length > 0"
|
||||
:ref="el => setVideoRef(el as HTMLVideoElement, `${sIndex}-${eIndex}`)"
|
||||
:ref="(el) => setVideoRef(el as HTMLVideoElement, `${sIndex}-${eIndex}`)"
|
||||
:autoplay="safariAutoplay"
|
||||
loop
|
||||
muted
|
||||
@@ -92,7 +104,7 @@
|
||||
:src="source.src"
|
||||
:type="source.type"
|
||||
:codecs="source.codecs"
|
||||
>
|
||||
/>
|
||||
</video>
|
||||
<div v-else class="tile-placeholder"></div>
|
||||
</div>
|
||||
@@ -104,8 +116,12 @@
|
||||
<div class="tile-info">
|
||||
<span class="ep-number">{{ episode.episode_number }}</span>
|
||||
<div class="ep-details">
|
||||
<span class="ep-name">{{ episode.name || `Episode ${episode.episode_number}` }}</span>
|
||||
<span v-if="episode.rating" class="ep-rating">★ {{ episode.rating.toFixed(1) }}</span>
|
||||
<span class="ep-name">{{
|
||||
episode.name || `Episode ${episode.episode_number}`
|
||||
}}</span>
|
||||
<span v-if="episode.rating" class="ep-rating"
|
||||
>★ {{ episode.rating.toFixed(1) }}</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -140,15 +156,17 @@
|
||||
:torrent="torrent"
|
||||
variant="menu"
|
||||
compact-flags
|
||||
:title="torrent.playable_file ? 'Click to play/continue. Alt+Click, Alt+Enter, or Cmd/Ctrl+E to open folder. Right-click for actions.' : 'No playable file'"
|
||||
:title="
|
||||
torrent.playable_file
|
||||
? 'Click to play/continue. Alt+Click, Alt+Enter, or Cmd/Ctrl+E to open folder. Right-click for actions.'
|
||||
: 'No playable file'
|
||||
"
|
||||
@activate="handleVersionActivate(torrent, $event)"
|
||||
@keydown="handleVersionShortcutKeydown($event, torrent)"
|
||||
@contextmenu="handleVersionContextMenu($event, torrent)"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="context-menu-empty">
|
||||
No versions available
|
||||
</div>
|
||||
<div v-else class="context-menu-empty">No versions available</div>
|
||||
</div>
|
||||
<ReleaseActionMenu
|
||||
:visible="versionActionMenu.visible"
|
||||
@@ -165,71 +183,77 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, nextTick, watch, onMounted, onUnmounted } from 'vue';
|
||||
import type { Series, Season, Episode, Torrent } from '../types';
|
||||
import { getCoverUrl, getVideoPreviewUrl, getVideoSourceAttributes, isSafariBrowser } from '../api';
|
||||
import { navAttrs } from '../composables/useKeyboardNavigation';
|
||||
import ReleaseVersionCard from './ReleaseVersionCard.vue';
|
||||
import ReleaseActionMenu from './ReleaseActionMenu.vue';
|
||||
import { computed, ref, nextTick, watch, onMounted, onUnmounted } from "vue"
|
||||
import type { Series, Season, Episode, Torrent } from "../types"
|
||||
import { getCoverUrl, getVideoPreviewUrl, getVideoSourceAttributes, isSafariBrowser } from "../api"
|
||||
import { navAttrs } from "../composables/useKeyboardNavigation"
|
||||
import ReleaseVersionCard from "./ReleaseVersionCard.vue"
|
||||
import ReleaseActionMenu from "./ReleaseActionMenu.vue"
|
||||
|
||||
const props = defineProps<{
|
||||
series: Series;
|
||||
focusEpisode?: { seasonNumber: number; episodeNumber: number } | null;
|
||||
hasResumePosition: (filePath: string | null) => boolean;
|
||||
getRootName: (rootId: string | null | undefined) => string | null;
|
||||
}>();
|
||||
series: Series
|
||||
focusEpisode?: { seasonNumber: number; episodeNumber: number } | null
|
||||
hasResumePosition: (filePath: string | null) => boolean
|
||||
getRootName: (rootId: string | null | undefined) => string | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
play: [string];
|
||||
openFolder: [string, string | null | undefined];
|
||||
}>();
|
||||
close: []
|
||||
play: [string]
|
||||
openFolder: [string, string | null | undefined]
|
||||
}>()
|
||||
|
||||
// Focus on matched episode when provided
|
||||
watch(() => props.focusEpisode, (ep) => {
|
||||
if (ep) {
|
||||
// Delay to ensure DOM is fully rendered after route transition
|
||||
setTimeout(() => {
|
||||
// Find the season index and episode index
|
||||
const seasonIndex = props.series.seasons?.findIndex(s => s.season_number === ep.seasonNumber) ?? -1;
|
||||
if (seasonIndex >= 0) {
|
||||
const episodeIndex = props.series.seasons?.[seasonIndex]?.episodes?.findIndex(
|
||||
e => e.episode_number === ep.episodeNumber
|
||||
) ?? -1;
|
||||
if (episodeIndex >= 0) {
|
||||
// Find the episode tile element using nav attributes
|
||||
const selector = `[data-nav-row="${seasonIndex + 2}"][data-nav-col="${episodeIndex}"]`;
|
||||
const element = document.querySelector(selector) as HTMLElement | null;
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
element.focus();
|
||||
watch(
|
||||
() => props.focusEpisode,
|
||||
(ep) => {
|
||||
if (ep) {
|
||||
// Delay to ensure DOM is fully rendered after route transition
|
||||
setTimeout(() => {
|
||||
// Find the season index and episode index
|
||||
const seasonIndex =
|
||||
props.series.seasons?.findIndex((s) => s.season_number === ep.seasonNumber) ?? -1
|
||||
if (seasonIndex >= 0) {
|
||||
const episodeIndex =
|
||||
props.series.seasons?.[seasonIndex]?.episodes?.findIndex(
|
||||
(e) => e.episode_number === ep.episodeNumber,
|
||||
) ?? -1
|
||||
if (episodeIndex >= 0) {
|
||||
// Find the episode tile element using nav attributes
|
||||
const selector = `[data-nav-row="${seasonIndex + 2}"][data-nav-col="${episodeIndex}"]`
|
||||
const element = document.querySelector(selector) as HTMLElement | null
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: "smooth", block: "center" })
|
||||
element.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 150);
|
||||
}
|
||||
}, { immediate: true });
|
||||
}, 150)
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// Context menu state
|
||||
const contextMenu = ref<{
|
||||
visible: boolean;
|
||||
x: number;
|
||||
y: number;
|
||||
episode: Episode | null;
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
episode: Episode | null
|
||||
}>({
|
||||
visible: false,
|
||||
x: 0,
|
||||
y: 0,
|
||||
episode: null,
|
||||
});
|
||||
})
|
||||
|
||||
const versionActionMenu = ref<{
|
||||
visible: boolean;
|
||||
x: number;
|
||||
y: number;
|
||||
filePath: string | null;
|
||||
rootName: string | null;
|
||||
rootId: string | null;
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
filePath: string | null
|
||||
rootName: string | null
|
||||
rootId: string | null
|
||||
}>({
|
||||
visible: false,
|
||||
x: 0,
|
||||
@@ -237,183 +261,192 @@ const versionActionMenu = ref<{
|
||||
filePath: null,
|
||||
rootName: null,
|
||||
rootId: null,
|
||||
});
|
||||
})
|
||||
|
||||
const releaseMenuOriginElement = ref<HTMLElement | null>(null);
|
||||
const releaseMenuOriginElement = ref<HTMLElement | null>(null)
|
||||
|
||||
// Show context menu on right-click
|
||||
function handleContextMenu(event: MouseEvent, episode: Episode) {
|
||||
event.preventDefault();
|
||||
releaseMenuOriginElement.value = event.currentTarget as HTMLElement | null;
|
||||
openEpisodeReleaseMenu(episode, event.clientX, event.clientY);
|
||||
event.preventDefault()
|
||||
releaseMenuOriginElement.value = event.currentTarget as HTMLElement | null
|
||||
openEpisodeReleaseMenu(episode, event.clientX, event.clientY)
|
||||
}
|
||||
|
||||
function openEpisodeReleaseMenu(episode: Episode, x: number, y: number) {
|
||||
closeVersionActionMenu();
|
||||
closeVersionActionMenu()
|
||||
contextMenu.value = {
|
||||
visible: true,
|
||||
x,
|
||||
y,
|
||||
episode,
|
||||
};
|
||||
}
|
||||
// Add Escape key listener (capturing phase to intercept before other handlers)
|
||||
nextTick(() => {
|
||||
document.addEventListener('keydown', handleContextMenuKeydown, true);
|
||||
document.addEventListener("keydown", handleContextMenuKeydown, true)
|
||||
// Focus first selectable version card.
|
||||
const firstCard = document.querySelector('.context-menu .version-row.version-selectable') as HTMLElement;
|
||||
const firstCard = document.querySelector(
|
||||
".context-menu .version-row.version-selectable",
|
||||
) as HTMLElement
|
||||
if (firstCard) {
|
||||
firstCard.focus();
|
||||
firstCard.focus()
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
function openEpisodeReleaseMenuFromElement(episode: Episode, element: HTMLElement | null) {
|
||||
releaseMenuOriginElement.value = element;
|
||||
releaseMenuOriginElement.value = element
|
||||
if (!element) {
|
||||
openEpisodeReleaseMenu(episode, window.innerWidth / 2, window.innerHeight / 2);
|
||||
return;
|
||||
openEpisodeReleaseMenu(episode, window.innerWidth / 2, window.innerHeight / 2)
|
||||
return
|
||||
}
|
||||
const rect = element.getBoundingClientRect();
|
||||
openEpisodeReleaseMenu(episode, rect.left + rect.width / 2, rect.top + rect.height / 2);
|
||||
const rect = element.getBoundingClientRect()
|
||||
openEpisodeReleaseMenu(episode, rect.left + rect.width / 2, rect.top + rect.height / 2)
|
||||
}
|
||||
|
||||
// Handle Escape and arrow keys in context menu (capturing phase to intercept before global handler)
|
||||
function handleContextMenuKeydown(event: KeyboardEvent) {
|
||||
if (!contextMenu.value.visible) return;
|
||||
if (!contextMenu.value.visible) return
|
||||
|
||||
const popupFocusable = getPopupFocusableElements();
|
||||
const popupFocusable = getPopupFocusableElements()
|
||||
|
||||
if (event.key === 'Tab') {
|
||||
if (popupFocusable.length === 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.key === "Tab") {
|
||||
if (popupFocusable.length === 0) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
const currentIndex = popupFocusable.findIndex((el) => el === document.activeElement);
|
||||
const delta = event.shiftKey ? -1 : 1;
|
||||
const nextIndex = currentIndex < 0
|
||||
? 0
|
||||
: (currentIndex + delta + popupFocusable.length) % popupFocusable.length;
|
||||
popupFocusable[nextIndex].focus();
|
||||
return;
|
||||
const currentIndex = popupFocusable.findIndex((el) => el === document.activeElement)
|
||||
const delta = event.shiftKey ? -1 : 1
|
||||
const nextIndex =
|
||||
currentIndex < 0 ? 0 : (currentIndex + delta + popupFocusable.length) % popupFocusable.length
|
||||
popupFocusable[nextIndex].focus()
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowRight' || event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
|
||||
if (popupFocusable.length === 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (
|
||||
event.key === "ArrowDown" ||
|
||||
event.key === "ArrowRight" ||
|
||||
event.key === "ArrowUp" ||
|
||||
event.key === "ArrowLeft"
|
||||
) {
|
||||
if (popupFocusable.length === 0) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
|
||||
const currentIndex = popupFocusable.findIndex((el) => el === document.activeElement);
|
||||
const delta = (event.key === 'ArrowDown' || event.key === 'ArrowRight') ? 1 : -1;
|
||||
const nextIndex = currentIndex < 0
|
||||
? 0
|
||||
: (currentIndex + delta + popupFocusable.length) % popupFocusable.length;
|
||||
popupFocusable[nextIndex].focus();
|
||||
return;
|
||||
const currentIndex = popupFocusable.findIndex((el) => el === document.activeElement)
|
||||
const delta = event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : -1
|
||||
const nextIndex =
|
||||
currentIndex < 0 ? 0 : (currentIndex + delta + popupFocusable.length) % popupFocusable.length
|
||||
popupFocusable[nextIndex].focus()
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
if (versionActionMenu.value.visible) {
|
||||
closeVersionActionMenu();
|
||||
return;
|
||||
closeVersionActionMenu()
|
||||
return
|
||||
}
|
||||
closeContextMenu();
|
||||
closeContextMenu()
|
||||
}
|
||||
}
|
||||
|
||||
function getPopupFocusableElements(): HTMLElement[] {
|
||||
const releaseItems = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('.context-menu .version-row.version-selectable')
|
||||
);
|
||||
document.querySelectorAll<HTMLElement>(".context-menu .version-row.version-selectable"),
|
||||
)
|
||||
const actionItems = versionActionMenu.value.visible
|
||||
? Array.from(document.querySelectorAll<HTMLElement>('.version-action-menu .version-action-item:not(:disabled)'))
|
||||
: [];
|
||||
return [...releaseItems, ...actionItems];
|
||||
? Array.from(
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
".version-action-menu .version-action-item:not(:disabled)",
|
||||
),
|
||||
)
|
||||
: []
|
||||
return [...releaseItems, ...actionItems]
|
||||
}
|
||||
|
||||
// Close context menu
|
||||
function closeContextMenu() {
|
||||
closeVersionActionMenu();
|
||||
contextMenu.value.visible = false;
|
||||
document.removeEventListener('keydown', handleContextMenuKeydown, true);
|
||||
closeVersionActionMenu()
|
||||
contextMenu.value.visible = false
|
||||
document.removeEventListener("keydown", handleContextMenuKeydown, true)
|
||||
nextTick(() => {
|
||||
releaseMenuOriginElement.value?.focus();
|
||||
});
|
||||
releaseMenuOriginElement.value?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
function closeVersionActionMenu() {
|
||||
versionActionMenu.value.visible = false;
|
||||
versionActionMenu.value.filePath = null;
|
||||
versionActionMenu.value.rootName = null;
|
||||
versionActionMenu.value.rootId = null;
|
||||
versionActionMenu.value.visible = false
|
||||
versionActionMenu.value.filePath = null
|
||||
versionActionMenu.value.rootName = null
|
||||
versionActionMenu.value.rootId = null
|
||||
}
|
||||
|
||||
function handleGamepadAction(event: Event) {
|
||||
const actionEvent = event as CustomEvent<{ action?: string }>;
|
||||
if (actionEvent.detail?.action !== 'menu') return;
|
||||
const actionEvent = event as CustomEvent<{ action?: string }>
|
||||
if (actionEvent.detail?.action !== "menu") return
|
||||
|
||||
const active = document.activeElement as HTMLElement | null;
|
||||
if (!active || !active.classList.contains('episode-tile')) return;
|
||||
const active = document.activeElement as HTMLElement | null
|
||||
if (!active || !active.classList.contains("episode-tile")) return
|
||||
|
||||
const row = parseInt(active.getAttribute('data-nav-row') || '-1', 10);
|
||||
const col = parseInt(active.getAttribute('data-nav-col') || '-1', 10);
|
||||
if (row < 2 || col < 0) return;
|
||||
const row = parseInt(active.getAttribute("data-nav-row") || "-1", 10)
|
||||
const col = parseInt(active.getAttribute("data-nav-col") || "-1", 10)
|
||||
if (row < 2 || col < 0) return
|
||||
|
||||
const season = props.series.seasons?.[row - 2];
|
||||
const episode = season?.episodes?.[col];
|
||||
if (!episode) return;
|
||||
const season = props.series.seasons?.[row - 2]
|
||||
const episode = season?.episodes?.[col]
|
||||
if (!episode) return
|
||||
|
||||
actionEvent.preventDefault();
|
||||
openEpisodeReleaseMenuFromElement(episode, active);
|
||||
actionEvent.preventDefault()
|
||||
openEpisodeReleaseMenuFromElement(episode, active)
|
||||
}
|
||||
|
||||
// Play specific version
|
||||
function handlePlayVersion(filePath: string | null) {
|
||||
if (filePath) {
|
||||
emit('play', filePath);
|
||||
emit("play", filePath)
|
||||
}
|
||||
closeVersionActionMenu();
|
||||
closeContextMenu();
|
||||
closeVersionActionMenu()
|
||||
closeContextMenu()
|
||||
}
|
||||
|
||||
function getPlayLabel(filePath: string | null): string {
|
||||
return props.hasResumePosition(filePath) ? 'Continue' : 'Play';
|
||||
return props.hasResumePosition(filePath) ? "Continue" : "Play"
|
||||
}
|
||||
|
||||
// Open folder for a version
|
||||
function handleOpenFolder(folderPath: string, rootId?: string | null) {
|
||||
if (!folderPath) return;
|
||||
emit('openFolder', folderPath, rootId);
|
||||
closeVersionActionMenu();
|
||||
closeContextMenu();
|
||||
if (!folderPath) return
|
||||
emit("openFolder", folderPath, rootId)
|
||||
closeVersionActionMenu()
|
||||
closeContextMenu()
|
||||
}
|
||||
|
||||
function handleVersionActivate(torrent: Torrent, event: MouseEvent | KeyboardEvent) {
|
||||
if (!torrent.playable_file) return;
|
||||
const rootId = torrent.root_id || props.series.root_id;
|
||||
if (!torrent.playable_file) return
|
||||
const rootId = torrent.root_id || props.series.root_id
|
||||
if (event.altKey) {
|
||||
handleOpenFolder(torrent.playable_file, rootId);
|
||||
return;
|
||||
handleOpenFolder(torrent.playable_file, rootId)
|
||||
return
|
||||
}
|
||||
handlePlayVersion(torrent.playable_file);
|
||||
handlePlayVersion(torrent.playable_file)
|
||||
}
|
||||
|
||||
function handleVersionShortcutKeydown(event: KeyboardEvent, torrent: Torrent) {
|
||||
if (!torrent.playable_file) return;
|
||||
const rootId = torrent.root_id || props.series.root_id;
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === 'e' && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleOpenFolder(torrent.playable_file, rootId);
|
||||
if (!torrent.playable_file) return
|
||||
const rootId = torrent.root_id || props.series.root_id
|
||||
const key = event.key.toLowerCase()
|
||||
if (key === "e" && (event.metaKey || event.ctrlKey)) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
handleOpenFolder(torrent.playable_file, rootId)
|
||||
}
|
||||
}
|
||||
|
||||
function handleVersionContextMenu(event: MouseEvent, torrent: Torrent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const rootId = torrent.root_id || props.series.root_id;
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const rootId = torrent.root_id || props.series.root_id
|
||||
versionActionMenu.value = {
|
||||
visible: true,
|
||||
x: event.clientX,
|
||||
@@ -421,172 +454,184 @@ function handleVersionContextMenu(event: MouseEvent, torrent: Torrent) {
|
||||
filePath: torrent.playable_file || null,
|
||||
rootName: props.getRootName(rootId) || null,
|
||||
rootId,
|
||||
};
|
||||
}
|
||||
nextTick(() => {
|
||||
const firstAction = document.querySelector('.version-action-menu .version-action-item:not(:disabled)') as HTMLElement | null;
|
||||
firstAction?.focus();
|
||||
});
|
||||
const firstAction = document.querySelector(
|
||||
".version-action-menu .version-action-item:not(:disabled)",
|
||||
) as HTMLElement | null
|
||||
firstAction?.focus()
|
||||
})
|
||||
}
|
||||
|
||||
// Video refs for hover effects
|
||||
const videoRefs = ref<Map<string, HTMLVideoElement>>(new Map());
|
||||
let videoIndex = 0;
|
||||
const safariAutoplay = isSafariBrowser();
|
||||
const videoRefs = ref<Map<string, HTMLVideoElement>>(new Map())
|
||||
let videoIndex = 0
|
||||
const safariAutoplay = isSafariBrowser()
|
||||
|
||||
// Set video ref with staggered playback
|
||||
function setVideoRef(el: HTMLVideoElement | null, key: string) {
|
||||
if (el) {
|
||||
videoRefs.value.set(key, el);
|
||||
videoRefs.value.set(key, el)
|
||||
// Staggered start times with 0.2 second offset
|
||||
const index = videoIndex++;
|
||||
setTimeout(() => {
|
||||
if (safariAutoplay && el.readyState >= 1) {
|
||||
el.currentTime = 0.001 + ((index % 6) * 0.03);
|
||||
}
|
||||
el.play().catch(() => {}); // Ignore autoplay policy errors
|
||||
}, safariAutoplay ? 0 : index * 200);
|
||||
const index = videoIndex++
|
||||
setTimeout(
|
||||
() => {
|
||||
if (safariAutoplay && el.readyState >= 1) {
|
||||
el.currentTime = 0.001 + (index % 6) * 0.03
|
||||
}
|
||||
el.play().catch(() => {}) // Ignore autoplay policy errors
|
||||
},
|
||||
safariAutoplay ? 0 : index * 200,
|
||||
)
|
||||
} else {
|
||||
videoRefs.value.delete(key);
|
||||
videoRefs.value.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
// Volume fade animation tracking
|
||||
const volumeFadeIntervals = new Map<string, ReturnType<typeof setInterval>>();
|
||||
const volumeFadeIntervals = new Map<string, ReturnType<typeof setInterval>>()
|
||||
|
||||
// Handle hover-based audio fade in/out for episode videos
|
||||
function handleEpisodeHover(key: string, isEntering: boolean) {
|
||||
const video = videoRefs.value.get(key);
|
||||
if (!video) return;
|
||||
const video = videoRefs.value.get(key)
|
||||
if (!video) return
|
||||
|
||||
// Clear any existing fade for this video
|
||||
const existingInterval = volumeFadeIntervals.get(key);
|
||||
const existingInterval = volumeFadeIntervals.get(key)
|
||||
if (existingInterval) {
|
||||
clearInterval(existingInterval);
|
||||
volumeFadeIntervals.delete(key);
|
||||
clearInterval(existingInterval)
|
||||
volumeFadeIntervals.delete(key)
|
||||
}
|
||||
|
||||
if (isEntering) {
|
||||
// Mute all other videos immediately
|
||||
videoRefs.value.forEach((v, k) => {
|
||||
if (k !== key) {
|
||||
v.volume = 0;
|
||||
v.muted = true;
|
||||
v.volume = 0
|
||||
v.muted = true
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// Fade in this video's audio
|
||||
video.muted = false;
|
||||
video.muted = false
|
||||
const fadeIn = setInterval(() => {
|
||||
if (video.volume < 0.95) {
|
||||
video.volume = Math.min(1, video.volume + 0.1);
|
||||
video.volume = Math.min(1, video.volume + 0.1)
|
||||
} else {
|
||||
video.volume = 1;
|
||||
clearInterval(fadeIn);
|
||||
volumeFadeIntervals.delete(key);
|
||||
video.volume = 1
|
||||
clearInterval(fadeIn)
|
||||
volumeFadeIntervals.delete(key)
|
||||
}
|
||||
}, 30);
|
||||
volumeFadeIntervals.set(key, fadeIn);
|
||||
}, 30)
|
||||
volumeFadeIntervals.set(key, fadeIn)
|
||||
} else {
|
||||
// Fade out this video's audio
|
||||
const fadeOut = setInterval(() => {
|
||||
if (video.volume > 0.05) {
|
||||
video.volume = Math.max(0, video.volume - 0.1);
|
||||
video.volume = Math.max(0, video.volume - 0.1)
|
||||
} else {
|
||||
video.volume = 0;
|
||||
video.muted = true;
|
||||
clearInterval(fadeOut);
|
||||
volumeFadeIntervals.delete(key);
|
||||
video.volume = 0
|
||||
video.muted = true
|
||||
clearInterval(fadeOut)
|
||||
volumeFadeIntervals.delete(key)
|
||||
}
|
||||
}, 30);
|
||||
volumeFadeIntervals.set(key, fadeOut);
|
||||
}, 30)
|
||||
volumeFadeIntervals.set(key, fadeOut)
|
||||
}
|
||||
}
|
||||
|
||||
// Backdrop URL - only use backdrop_path, fall back to collage (handled in template)
|
||||
const backdropUrl = computed(() => {
|
||||
if (props.series.info?.backdrop_path) {
|
||||
return getCoverUrl(props.series.info.backdrop_path, props.series.root_id);
|
||||
return getCoverUrl(props.series.info.backdrop_path, props.series.root_id)
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return null
|
||||
})
|
||||
|
||||
// Seasons that have poster images
|
||||
const seasonsWithPosters = computed(() => {
|
||||
return props.series.seasons.filter(s => s.poster_path);
|
||||
});
|
||||
return props.series.seasons.filter((s) => s.poster_path)
|
||||
})
|
||||
|
||||
// Rating class
|
||||
const ratingClass = computed(() => {
|
||||
if (!props.series.info?.rating) return '';
|
||||
if (props.series.info.rating >= 7.5) return 'rating-high';
|
||||
if (props.series.info.rating >= 6) return 'rating-medium';
|
||||
return 'rating-low';
|
||||
});
|
||||
if (!props.series.info?.rating) return ""
|
||||
if (props.series.info.rating >= 7.5) return "rating-high"
|
||||
if (props.series.info.rating >= 6) return "rating-medium"
|
||||
return "rating-low"
|
||||
})
|
||||
|
||||
// Get season poster
|
||||
function getSeasonPoster(season: Season): string | undefined {
|
||||
if (season.poster_path) {
|
||||
return getCoverUrl(season.poster_path, props.series.root_id);
|
||||
return getCoverUrl(season.poster_path, props.series.root_id)
|
||||
}
|
||||
return undefined;
|
||||
return undefined
|
||||
}
|
||||
|
||||
function getEpisodeVideoSources(episode: Episode): Array<{ src: string; type: string; codecs: string }> {
|
||||
const sources = episode.reel_sources && episode.reel_sources.length > 0
|
||||
? episode.reel_sources
|
||||
: episode.reel_image
|
||||
? [episode.reel_image]
|
||||
: [];
|
||||
function getEpisodeVideoSources(
|
||||
episode: Episode,
|
||||
): Array<{ src: string; type: string; codecs: string }> {
|
||||
const sources =
|
||||
episode.reel_sources && episode.reel_sources.length > 0
|
||||
? episode.reel_sources
|
||||
: episode.reel_image
|
||||
? [episode.reel_image]
|
||||
: []
|
||||
|
||||
return sources.map((path) => ({
|
||||
src: getVideoPreviewUrl(getCoverUrl(path, props.series.root_id)),
|
||||
...getVideoSourceAttributes(path),
|
||||
}));
|
||||
}))
|
||||
}
|
||||
|
||||
// Collage slice style for season posters
|
||||
function getCollageSliceStyle(season: Season, index: number) {
|
||||
const posterUrl = season.poster_path ? getCoverUrl(season.poster_path, props.series.root_id) : null;
|
||||
const totalSlices = Math.min(seasonsWithPosters.value.length, 5);
|
||||
const sliceWidth = 100 / totalSlices;
|
||||
const posterUrl = season.poster_path
|
||||
? getCoverUrl(season.poster_path, props.series.root_id)
|
||||
: null
|
||||
const totalSlices = Math.min(seasonsWithPosters.value.length, 5)
|
||||
const sliceWidth = 100 / totalSlices
|
||||
|
||||
return {
|
||||
backgroundImage: posterUrl ? `url('${posterUrl}')` : 'linear-gradient(135deg, #1a1a2e, #16213e)',
|
||||
backgroundImage: posterUrl
|
||||
? `url('${posterUrl}')`
|
||||
: "linear-gradient(135deg, #1a1a2e, #16213e)",
|
||||
left: `${index * sliceWidth}%`,
|
||||
width: `${sliceWidth + 5}%`, // overlap slightly
|
||||
clipPath: `polygon(${index * 10}% 0, 100% 0, ${100 - (totalSlices - index - 1) * 10}% 100%, 0% 100%)`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Truncate text
|
||||
function truncate(text: string, maxLength: number): string {
|
||||
if (text.length <= maxLength) return text;
|
||||
return text.slice(0, maxLength).trim() + '...';
|
||||
if (text.length <= maxLength) return text
|
||||
return text.slice(0, maxLength).trim() + "..."
|
||||
}
|
||||
|
||||
// Handle play
|
||||
function handlePlay(episode: Episode) {
|
||||
const playableFile = Object.values(episode.torrents || {})[0]?.playable_file;
|
||||
const playableFile = Object.values(episode.torrents || {})[0]?.playable_file
|
||||
if (playableFile) {
|
||||
emit('play', playableFile);
|
||||
emit("play", playableFile)
|
||||
}
|
||||
}
|
||||
|
||||
function handleEpisodeEnter(event: KeyboardEvent, episode: Episode) {
|
||||
if (event.altKey || event.metaKey || event.ctrlKey) {
|
||||
openEpisodeReleaseMenuFromElement(episode, event.currentTarget as HTMLElement | null);
|
||||
return;
|
||||
openEpisodeReleaseMenuFromElement(episode, event.currentTarget as HTMLElement | null)
|
||||
return
|
||||
}
|
||||
handlePlay(episode);
|
||||
handlePlay(episode)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('mediahive:gamepad-action', handleGamepadAction as EventListener);
|
||||
});
|
||||
window.addEventListener("mediahive:gamepad-action", handleGamepadAction as EventListener)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('mediahive:gamepad-action', handleGamepadAction as EventListener);
|
||||
});
|
||||
window.removeEventListener("mediahive:gamepad-action", handleGamepadAction as EventListener)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -675,9 +720,15 @@ onUnmounted(() => {
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.rating-high { color: #46d369; }
|
||||
.rating-medium { color: #f9a825; }
|
||||
.rating-low { color: #e53935; }
|
||||
.rating-high {
|
||||
color: #46d369;
|
||||
}
|
||||
.rating-medium {
|
||||
color: #f9a825;
|
||||
}
|
||||
.rating-low {
|
||||
color: #e53935;
|
||||
}
|
||||
|
||||
.meta-item {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
@@ -825,7 +876,8 @@ html:not(.mouse-active) .episode-tile.nav-focused {
|
||||
|
||||
/* Blinking animation for focus outline */
|
||||
@keyframes tile-outline-blink {
|
||||
0%, 100% {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
@@ -1061,5 +1113,4 @@ html.mouse-active .episode-tile:hover .tile-play {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
type GamepadAction = 'up' | 'down' | 'left' | 'right' | 'select' | 'back' | 'menu';
|
||||
type GamepadAction = "up" | "down" | "left" | "right" | "select" | "back" | "menu"
|
||||
|
||||
const GAMEPAD_AXIS_THRESHOLD = 0.55;
|
||||
const GAMEPAD_REPEAT_MS = 180;
|
||||
const GAMEPAD_AXIS_THRESHOLD = 0.55
|
||||
const GAMEPAD_REPEAT_MS = 180
|
||||
|
||||
const KEY_BY_ACTION: Partial<Record<GamepadAction, string>> = {
|
||||
up: 'ArrowUp',
|
||||
down: 'ArrowDown',
|
||||
left: 'ArrowLeft',
|
||||
right: 'ArrowRight',
|
||||
select: 'Enter',
|
||||
back: 'Escape',
|
||||
};
|
||||
up: "ArrowUp",
|
||||
down: "ArrowDown",
|
||||
left: "ArrowLeft",
|
||||
right: "ArrowRight",
|
||||
select: "Enter",
|
||||
back: "Escape",
|
||||
}
|
||||
|
||||
const gamepadPressedState: Record<GamepadAction, boolean> = {
|
||||
up: false,
|
||||
@@ -20,7 +20,7 @@ const gamepadPressedState: Record<GamepadAction, boolean> = {
|
||||
select: false,
|
||||
back: false,
|
||||
menu: false,
|
||||
};
|
||||
}
|
||||
|
||||
const gamepadLastTriggerAt: Record<GamepadAction, number> = {
|
||||
up: 0,
|
||||
@@ -30,111 +30,115 @@ const gamepadLastTriggerAt: Record<GamepadAction, number> = {
|
||||
select: 0,
|
||||
back: 0,
|
||||
menu: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let gamepadFrameId: number | null = null;
|
||||
let gamepadInstalled = false;
|
||||
let gamepadFrameId: number | null = null
|
||||
let gamepadInstalled = false
|
||||
|
||||
function dispatchKey(key: string) {
|
||||
const active = document.activeElement;
|
||||
const target = active instanceof HTMLElement ? active : document;
|
||||
target.dispatchEvent(new KeyboardEvent('keydown', {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}));
|
||||
const active = document.activeElement
|
||||
const target = active instanceof HTMLElement ? active : document
|
||||
target.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function applyGamepadAction(action: GamepadAction, isPressed: boolean, now: number) {
|
||||
const wasPressed = gamepadPressedState[action];
|
||||
gamepadPressedState[action] = isPressed;
|
||||
const wasPressed = gamepadPressedState[action]
|
||||
gamepadPressedState[action] = isPressed
|
||||
|
||||
if (!isPressed) return;
|
||||
if (!isPressed) return
|
||||
|
||||
const shouldRepeat = action === 'up' || action === 'down' || action === 'left' || action === 'right';
|
||||
const canTrigger = !wasPressed || (shouldRepeat && now - gamepadLastTriggerAt[action] >= GAMEPAD_REPEAT_MS);
|
||||
if (!canTrigger) return;
|
||||
const shouldRepeat =
|
||||
action === "up" || action === "down" || action === "left" || action === "right"
|
||||
const canTrigger =
|
||||
!wasPressed || (shouldRepeat && now - gamepadLastTriggerAt[action] >= GAMEPAD_REPEAT_MS)
|
||||
if (!canTrigger) return
|
||||
|
||||
gamepadLastTriggerAt[action] = now;
|
||||
const actionEvent = new CustomEvent('mediahive:gamepad-action', {
|
||||
gamepadLastTriggerAt[action] = now
|
||||
const actionEvent = new CustomEvent("mediahive:gamepad-action", {
|
||||
detail: { action },
|
||||
cancelable: true,
|
||||
});
|
||||
const shouldContinueWithKeyboard = window.dispatchEvent(actionEvent);
|
||||
if (!shouldContinueWithKeyboard) return;
|
||||
})
|
||||
const shouldContinueWithKeyboard = window.dispatchEvent(actionEvent)
|
||||
if (!shouldContinueWithKeyboard) return
|
||||
|
||||
const key = KEY_BY_ACTION[action];
|
||||
const key = KEY_BY_ACTION[action]
|
||||
if (key) {
|
||||
dispatchKey(key);
|
||||
dispatchKey(key)
|
||||
}
|
||||
}
|
||||
|
||||
function resetPressedState() {
|
||||
gamepadPressedState.up = false;
|
||||
gamepadPressedState.down = false;
|
||||
gamepadPressedState.left = false;
|
||||
gamepadPressedState.right = false;
|
||||
gamepadPressedState.select = false;
|
||||
gamepadPressedState.back = false;
|
||||
gamepadPressedState.menu = false;
|
||||
gamepadPressedState.up = false
|
||||
gamepadPressedState.down = false
|
||||
gamepadPressedState.left = false
|
||||
gamepadPressedState.right = false
|
||||
gamepadPressedState.select = false
|
||||
gamepadPressedState.back = false
|
||||
gamepadPressedState.menu = false
|
||||
}
|
||||
|
||||
function pollGamepad() {
|
||||
const gamepads = navigator.getGamepads?.() ?? [];
|
||||
const now = performance.now();
|
||||
const connectedGamepads = gamepads.filter((gp): gp is Gamepad => Boolean(gp && gp.connected));
|
||||
const gamepads = navigator.getGamepads?.() ?? []
|
||||
const now = performance.now()
|
||||
const connectedGamepads = gamepads.filter((gp): gp is Gamepad => Boolean(gp && gp.connected))
|
||||
|
||||
if (connectedGamepads.length > 0) {
|
||||
let up = false;
|
||||
let down = false;
|
||||
let left = false;
|
||||
let right = false;
|
||||
let select = false;
|
||||
let back = false;
|
||||
let menu = false;
|
||||
let up = false
|
||||
let down = false
|
||||
let left = false
|
||||
let right = false
|
||||
let select = false
|
||||
let back = false
|
||||
let menu = false
|
||||
|
||||
for (const gamepad of connectedGamepads) {
|
||||
const axisX = gamepad.axes[0] ?? 0;
|
||||
const axisY = gamepad.axes[1] ?? 0;
|
||||
const axisX = gamepad.axes[0] ?? 0
|
||||
const axisY = gamepad.axes[1] ?? 0
|
||||
|
||||
up = up || Boolean(gamepad.buttons[12]?.pressed) || axisY <= -GAMEPAD_AXIS_THRESHOLD;
|
||||
down = down || Boolean(gamepad.buttons[13]?.pressed) || axisY >= GAMEPAD_AXIS_THRESHOLD;
|
||||
left = left || Boolean(gamepad.buttons[14]?.pressed) || axisX <= -GAMEPAD_AXIS_THRESHOLD;
|
||||
right = right || Boolean(gamepad.buttons[15]?.pressed) || axisX >= GAMEPAD_AXIS_THRESHOLD;
|
||||
up = up || Boolean(gamepad.buttons[12]?.pressed) || axisY <= -GAMEPAD_AXIS_THRESHOLD
|
||||
down = down || Boolean(gamepad.buttons[13]?.pressed) || axisY >= GAMEPAD_AXIS_THRESHOLD
|
||||
left = left || Boolean(gamepad.buttons[14]?.pressed) || axisX <= -GAMEPAD_AXIS_THRESHOLD
|
||||
right = right || Boolean(gamepad.buttons[15]?.pressed) || axisX >= GAMEPAD_AXIS_THRESHOLD
|
||||
|
||||
// Xbox mapping on standard gamepads: A=0, B=1
|
||||
select = select || Boolean(gamepad.buttons[0]?.pressed);
|
||||
back = back || Boolean(gamepad.buttons[1]?.pressed);
|
||||
select = select || Boolean(gamepad.buttons[0]?.pressed)
|
||||
back = back || Boolean(gamepad.buttons[1]?.pressed)
|
||||
// Y/Triangle button opens contextual release list where supported.
|
||||
menu = menu || Boolean(gamepad.buttons[3]?.pressed);
|
||||
menu = menu || Boolean(gamepad.buttons[3]?.pressed)
|
||||
}
|
||||
|
||||
applyGamepadAction('up', up, now);
|
||||
applyGamepadAction('down', down, now);
|
||||
applyGamepadAction('left', left, now);
|
||||
applyGamepadAction('right', right, now);
|
||||
applyGamepadAction('select', select, now);
|
||||
applyGamepadAction('back', back, now);
|
||||
applyGamepadAction('menu', menu, now);
|
||||
applyGamepadAction("up", up, now)
|
||||
applyGamepadAction("down", down, now)
|
||||
applyGamepadAction("left", left, now)
|
||||
applyGamepadAction("right", right, now)
|
||||
applyGamepadAction("select", select, now)
|
||||
applyGamepadAction("back", back, now)
|
||||
applyGamepadAction("menu", menu, now)
|
||||
} else {
|
||||
resetPressedState();
|
||||
resetPressedState()
|
||||
}
|
||||
|
||||
gamepadFrameId = window.requestAnimationFrame(pollGamepad);
|
||||
gamepadFrameId = window.requestAnimationFrame(pollGamepad)
|
||||
}
|
||||
|
||||
export function installGamepadNavigation() {
|
||||
if (gamepadInstalled) return;
|
||||
gamepadInstalled = true;
|
||||
gamepadFrameId = window.requestAnimationFrame(pollGamepad);
|
||||
if (gamepadInstalled) return
|
||||
gamepadInstalled = true
|
||||
gamepadFrameId = window.requestAnimationFrame(pollGamepad)
|
||||
}
|
||||
|
||||
export function uninstallGamepadNavigation() {
|
||||
if (!gamepadInstalled) return;
|
||||
gamepadInstalled = false;
|
||||
if (!gamepadInstalled) return
|
||||
gamepadInstalled = false
|
||||
if (gamepadFrameId !== null) {
|
||||
window.cancelAnimationFrame(gamepadFrameId);
|
||||
gamepadFrameId = null;
|
||||
window.cancelAnimationFrame(gamepadFrameId)
|
||||
gamepadFrameId = null
|
||||
}
|
||||
resetPressedState();
|
||||
resetPressedState()
|
||||
}
|
||||
|
||||
@@ -1,135 +1,146 @@
|
||||
type InputModality = 'mouse' | 'keyboard' | 'gamepad';
|
||||
type InputModality = "mouse" | "keyboard" | "gamepad"
|
||||
|
||||
const MOUSE_IDLE_MS = 1400;
|
||||
const MOUSE_INTENT_DISTANCE_PX = 28;
|
||||
const MOUSE_INTENT_WINDOW_MS = 700;
|
||||
const MOUSE_IDLE_MS = 1400
|
||||
const MOUSE_INTENT_DISTANCE_PX = 28
|
||||
const MOUSE_INTENT_WINDOW_MS = 700
|
||||
const MOUSE_INTENT_SELECTOR = [
|
||||
'[data-nav-focusable]','button','a[href]','input','select','textarea','[role="button"]',
|
||||
'.media-card','.collage-item','.episode-tile','.version-row','.ctx-btn','.header-nav-item',
|
||||
].join(',');
|
||||
"[data-nav-focusable]",
|
||||
"button",
|
||||
"a[href]",
|
||||
"input",
|
||||
"select",
|
||||
"textarea",
|
||||
'[role="button"]',
|
||||
".media-card",
|
||||
".collage-item",
|
||||
".episode-tile",
|
||||
".version-row",
|
||||
".ctx-btn",
|
||||
".header-nav-item",
|
||||
].join(",")
|
||||
|
||||
let installed = false;
|
||||
let modality: InputModality = 'mouse';
|
||||
let mouseIdleTimer: number | null = null;
|
||||
let pointerVisible = false;
|
||||
let mouseTravelPx = 0;
|
||||
let lastMouseMoveAt = 0;
|
||||
let installed = false
|
||||
let modality: InputModality = "mouse"
|
||||
let mouseIdleTimer: number | null = null
|
||||
let pointerVisible = false
|
||||
let mouseTravelPx = 0
|
||||
let lastMouseMoveAt = 0
|
||||
|
||||
function clearMouseIdleTimer() {
|
||||
if (mouseIdleTimer !== null) {
|
||||
window.clearTimeout(mouseIdleTimer);
|
||||
mouseIdleTimer = null;
|
||||
window.clearTimeout(mouseIdleTimer)
|
||||
mouseIdleTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function applyInputState(mouseActive: boolean) {
|
||||
const root = document.documentElement;
|
||||
root.classList.toggle('mouse-active', mouseActive);
|
||||
root.classList.toggle('pointer-visible', pointerVisible);
|
||||
const root = document.documentElement
|
||||
root.classList.toggle("mouse-active", mouseActive)
|
||||
root.classList.toggle("pointer-visible", pointerVisible)
|
||||
}
|
||||
|
||||
function scheduleMouseIdle() {
|
||||
clearMouseIdleTimer();
|
||||
clearMouseIdleTimer()
|
||||
mouseIdleTimer = window.setTimeout(() => {
|
||||
pointerVisible = false;
|
||||
applyInputState(false);
|
||||
}, MOUSE_IDLE_MS);
|
||||
pointerVisible = false
|
||||
applyInputState(false)
|
||||
}, MOUSE_IDLE_MS)
|
||||
}
|
||||
|
||||
function activateMouseInput() {
|
||||
modality = 'mouse';
|
||||
pointerVisible = true;
|
||||
applyInputState(true);
|
||||
scheduleMouseIdle();
|
||||
modality = "mouse"
|
||||
pointerVisible = true
|
||||
applyInputState(true)
|
||||
scheduleMouseIdle()
|
||||
}
|
||||
|
||||
function activateNonMouseInput(next: InputModality) {
|
||||
modality = next;
|
||||
pointerVisible = false;
|
||||
mouseTravelPx = 0;
|
||||
clearMouseIdleTimer();
|
||||
applyInputState(false);
|
||||
modality = next
|
||||
pointerVisible = false
|
||||
mouseTravelPx = 0
|
||||
clearMouseIdleTimer()
|
||||
applyInputState(false)
|
||||
}
|
||||
|
||||
function showPointerFromMotion() {
|
||||
pointerVisible = true;
|
||||
applyInputState(modality === 'mouse');
|
||||
scheduleMouseIdle();
|
||||
pointerVisible = true
|
||||
applyInputState(modality === "mouse")
|
||||
scheduleMouseIdle()
|
||||
}
|
||||
|
||||
function isMouseIntentTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof Element)) return false;
|
||||
return Boolean(target.closest(MOUSE_INTENT_SELECTOR));
|
||||
if (!(target instanceof Element)) return false
|
||||
return Boolean(target.closest(MOUSE_INTENT_SELECTOR))
|
||||
}
|
||||
|
||||
function registerMouseIntentTravel(event: MouseEvent): boolean {
|
||||
const now = performance.now();
|
||||
const now = performance.now()
|
||||
if (now - lastMouseMoveAt > MOUSE_INTENT_WINDOW_MS) {
|
||||
mouseTravelPx = 0;
|
||||
mouseTravelPx = 0
|
||||
}
|
||||
lastMouseMoveAt = now;
|
||||
lastMouseMoveAt = now
|
||||
|
||||
const step = Math.hypot(event.movementX || 0, event.movementY || 0);
|
||||
mouseTravelPx += step;
|
||||
const step = Math.hypot(event.movementX || 0, event.movementY || 0)
|
||||
mouseTravelPx += step
|
||||
if (mouseTravelPx >= MOUSE_INTENT_DISTANCE_PX) {
|
||||
mouseTravelPx = 0;
|
||||
return true;
|
||||
mouseTravelPx = 0
|
||||
return true
|
||||
}
|
||||
return false;
|
||||
return false
|
||||
}
|
||||
|
||||
function handleMouseMove(event: MouseEvent) {
|
||||
showPointerFromMotion();
|
||||
showPointerFromMotion()
|
||||
|
||||
if (modality === 'mouse') {
|
||||
applyInputState(true);
|
||||
return;
|
||||
if (modality === "mouse") {
|
||||
applyInputState(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (!isMouseIntentTarget(event.target)) return;
|
||||
if (!isMouseIntentTarget(event.target)) return
|
||||
if (registerMouseIntentTravel(event)) {
|
||||
activateMouseInput();
|
||||
activateMouseInput()
|
||||
}
|
||||
}
|
||||
|
||||
function handleMouseOver(event: MouseEvent) {
|
||||
if (modality === 'mouse') return;
|
||||
if (!isMouseIntentTarget(event.target)) return;
|
||||
if (modality === "mouse") return
|
||||
if (!isMouseIntentTarget(event.target)) return
|
||||
|
||||
// Entering an interactive target indicates likely mouse intent.
|
||||
activateMouseInput();
|
||||
activateMouseInput()
|
||||
}
|
||||
|
||||
function handleMouseIntentAction(event: MouseEvent | WheelEvent) {
|
||||
pointerVisible = true;
|
||||
pointerVisible = true
|
||||
if (isMouseIntentTarget(event.target)) {
|
||||
activateMouseInput();
|
||||
return;
|
||||
activateMouseInput()
|
||||
return
|
||||
}
|
||||
|
||||
applyInputState(modality === 'mouse');
|
||||
scheduleMouseIdle();
|
||||
applyInputState(modality === "mouse")
|
||||
scheduleMouseIdle()
|
||||
}
|
||||
|
||||
function handleKeyboardActivity(event: KeyboardEvent) {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
activateNonMouseInput('keyboard');
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return
|
||||
activateNonMouseInput("keyboard")
|
||||
}
|
||||
|
||||
function handleGamepadActivity() {
|
||||
activateNonMouseInput('gamepad');
|
||||
activateNonMouseInput("gamepad")
|
||||
}
|
||||
|
||||
export function installInputModalityTracking() {
|
||||
if (installed) return;
|
||||
installed = true;
|
||||
if (installed) return
|
||||
installed = true
|
||||
|
||||
applyInputState(false);
|
||||
applyInputState(false)
|
||||
|
||||
window.addEventListener('mousemove', handleMouseMove, { passive: true });
|
||||
window.addEventListener('mouseover', handleMouseOver, { passive: true });
|
||||
window.addEventListener('mousedown', handleMouseIntentAction, { passive: true });
|
||||
window.addEventListener('wheel', handleMouseIntentAction, { passive: true });
|
||||
window.addEventListener('keydown', handleKeyboardActivity, { passive: true });
|
||||
window.addEventListener('mediahive:gamepad-action', handleGamepadActivity as EventListener);
|
||||
window.addEventListener("mousemove", handleMouseMove, { passive: true })
|
||||
window.addEventListener("mouseover", handleMouseOver, { passive: true })
|
||||
window.addEventListener("mousedown", handleMouseIntentAction, { passive: true })
|
||||
window.addEventListener("wheel", handleMouseIntentAction, { passive: true })
|
||||
window.addEventListener("keydown", handleKeyboardActivity, { passive: true })
|
||||
window.addEventListener("mediahive:gamepad-action", handleGamepadActivity as EventListener)
|
||||
}
|
||||
|
||||
@@ -1,60 +1,58 @@
|
||||
import { ref } from 'vue';
|
||||
import { ref } from "vue"
|
||||
|
||||
export interface FocusableElement {
|
||||
element: HTMLElement;
|
||||
row: number;
|
||||
col: number;
|
||||
element: HTMLElement
|
||||
row: number
|
||||
col: number
|
||||
}
|
||||
|
||||
// Global focus state
|
||||
const focusedElement = ref<HTMLElement | null>(null);
|
||||
const isNavigating = ref(false);
|
||||
const focusedElement = ref<HTMLElement | null>(null)
|
||||
const isNavigating = ref(false)
|
||||
// Track the "desired" column when moving vertically (to maintain column position across rows of different lengths)
|
||||
const desiredCol = ref<number | null>(null);
|
||||
const desiredCol = ref<number | null>(null)
|
||||
// Track if global handlers are installed
|
||||
let handlersInstalled = false;
|
||||
let handlersInstalled = false
|
||||
|
||||
// Data attribute names
|
||||
const FOCUSABLE_ATTR = 'data-nav-focusable';
|
||||
const ROW_ATTR = 'data-nav-row';
|
||||
const COL_ATTR = 'data-nav-col';
|
||||
const ENTRY_COL_ATTR = 'data-nav-entry-col';
|
||||
const SYNC_SCROLL_ROW_ATTR = 'data-sync-scroll-row';
|
||||
const FOCUSABLE_ATTR = "data-nav-focusable"
|
||||
const ROW_ATTR = "data-nav-row"
|
||||
const COL_ATTR = "data-nav-col"
|
||||
const ENTRY_COL_ATTR = "data-nav-entry-col"
|
||||
const SYNC_SCROLL_ROW_ATTR = "data-sync-scroll-row"
|
||||
|
||||
const SYNC_SCROLL_FIRST_CONTENT_ROW = 2;
|
||||
const SYNC_SCROLL_DEADZONE_RATIO = 0.18;
|
||||
const SYNC_SCROLL_EASING_MS = 220;
|
||||
const SYNC_SCROLL_TAIL_VAR = '--sync-row-tail';
|
||||
const SYNC_SCROLL_FIRST_CONTENT_ROW = 2
|
||||
const SYNC_SCROLL_DEADZONE_RATIO = 0.18
|
||||
const SYNC_SCROLL_EASING_MS = 220
|
||||
const SYNC_SCROLL_TAIL_VAR = "--sync-row-tail"
|
||||
|
||||
let syncedRowsFrame: number | null = null;
|
||||
let syncedRowsCurrentOffset = 0;
|
||||
let syncedRowsTargetOffset = 0;
|
||||
let syncedRowsTailPx = 0;
|
||||
let lastSyncedAnchorCol: number | null = null;
|
||||
let lastSyncedRowsAnimationAt: number | null = null;
|
||||
let syncedRowsFrame: number | null = null
|
||||
let syncedRowsCurrentOffset = 0
|
||||
let syncedRowsTargetOffset = 0
|
||||
let syncedRowsTailPx = 0
|
||||
let lastSyncedAnchorCol: number | null = null
|
||||
let lastSyncedRowsAnimationAt: number | null = null
|
||||
|
||||
function getSyncedRows(): HTMLElement[] {
|
||||
return Array.from(
|
||||
document.querySelectorAll<HTMLElement>(`[${SYNC_SCROLL_ROW_ATTR}="true"]`)
|
||||
);
|
||||
return Array.from(document.querySelectorAll<HTMLElement>(`[${SYNC_SCROLL_ROW_ATTR}="true"]`))
|
||||
}
|
||||
|
||||
function getSyncedRowMetrics(rows: HTMLElement[]) {
|
||||
for (const row of rows) {
|
||||
const cards = Array.from(row.querySelectorAll<HTMLElement>(`.media-card[${FOCUSABLE_ATTR}]`));
|
||||
if (cards.length === 0) continue;
|
||||
const cards = Array.from(row.querySelectorAll<HTMLElement>(`.media-card[${FOCUSABLE_ATTR}]`))
|
||||
if (cards.length === 0) continue
|
||||
|
||||
const firstRect = cards[0].getBoundingClientRect();
|
||||
const cardWidth = firstRect.width;
|
||||
if (cardWidth <= 0) continue;
|
||||
const firstRect = cards[0].getBoundingClientRect()
|
||||
const cardWidth = firstRect.width
|
||||
if (cardWidth <= 0) continue
|
||||
|
||||
const rowStyle = window.getComputedStyle(row);
|
||||
const paddingLeft = parseFloat(rowStyle.paddingLeft || '0');
|
||||
let gap = parseFloat(rowStyle.columnGap || rowStyle.gap || '0');
|
||||
const rowStyle = window.getComputedStyle(row)
|
||||
const paddingLeft = parseFloat(rowStyle.paddingLeft || "0")
|
||||
let gap = parseFloat(rowStyle.columnGap || rowStyle.gap || "0")
|
||||
|
||||
if (cards.length > 1) {
|
||||
const secondRect = cards[1].getBoundingClientRect();
|
||||
gap = Math.max(0, secondRect.left - firstRect.left - cardWidth);
|
||||
const secondRect = cards[1].getBoundingClientRect()
|
||||
gap = Math.max(0, secondRect.left - firstRect.left - cardWidth)
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -62,211 +60,213 @@ function getSyncedRowMetrics(rows: HTMLElement[]) {
|
||||
stride: cardWidth + gap,
|
||||
paddingLeft,
|
||||
viewportWidth: row.clientWidth,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
function clampRowScrollOffset(row: HTMLElement, offset: number): number {
|
||||
const maxOffset = Math.max(0, row.scrollWidth - row.clientWidth);
|
||||
return Math.min(Math.max(offset, 0), maxOffset);
|
||||
const maxOffset = Math.max(0, row.scrollWidth - row.clientWidth)
|
||||
return Math.min(Math.max(offset, 0), maxOffset)
|
||||
}
|
||||
|
||||
function getRowMaxOffset(row: HTMLElement): number {
|
||||
return Math.max(0, row.scrollWidth - row.clientWidth);
|
||||
return Math.max(0, row.scrollWidth - row.clientWidth)
|
||||
}
|
||||
|
||||
function getRowNaturalMaxOffset(row: HTMLElement): number {
|
||||
return Math.max(0, getRowMaxOffset(row) - syncedRowsTailPx);
|
||||
return Math.max(0, getRowMaxOffset(row) - syncedRowsTailPx)
|
||||
}
|
||||
|
||||
function getTailNeededForOffset(offset: number, rows: HTMLElement[]): number {
|
||||
if (rows.length === 0) return 0;
|
||||
if (rows.length === 0) return 0
|
||||
|
||||
let minNaturalMax = Number.POSITIVE_INFINITY;
|
||||
let minNaturalMax = Number.POSITIVE_INFINITY
|
||||
for (const row of rows) {
|
||||
minNaturalMax = Math.min(minNaturalMax, getRowNaturalMaxOffset(row));
|
||||
minNaturalMax = Math.min(minNaturalMax, getRowNaturalMaxOffset(row))
|
||||
}
|
||||
|
||||
if (!Number.isFinite(minNaturalMax)) return 0;
|
||||
return Math.max(0, offset - minNaturalMax);
|
||||
if (!Number.isFinite(minNaturalMax)) return 0
|
||||
return Math.max(0, offset - minNaturalMax)
|
||||
}
|
||||
|
||||
function setSyncedRowsTail(tailPx: number, rows: HTMLElement[] = getSyncedRows()) {
|
||||
const nextTail = Math.max(0, tailPx);
|
||||
syncedRowsTailPx = nextTail;
|
||||
const nextTail = Math.max(0, tailPx)
|
||||
syncedRowsTailPx = nextTail
|
||||
for (const row of rows) {
|
||||
row.style.setProperty(SYNC_SCROLL_TAIL_VAR, `${nextTail}px`);
|
||||
row.style.setProperty(SYNC_SCROLL_TAIL_VAR, `${nextTail}px`)
|
||||
}
|
||||
}
|
||||
|
||||
function applySyncedRowScroll(offset: number, rows: HTMLElement[] = getSyncedRows()) {
|
||||
for (const row of rows) {
|
||||
row.scrollLeft = clampRowScrollOffset(row, offset);
|
||||
row.scrollLeft = clampRowScrollOffset(row, offset)
|
||||
}
|
||||
}
|
||||
|
||||
function resetSyncedRows(immediate: boolean = false) {
|
||||
lastSyncedAnchorCol = null;
|
||||
syncedRowsTargetOffset = 0;
|
||||
setSyncedRowsTail(0);
|
||||
lastSyncedAnchorCol = null
|
||||
syncedRowsTargetOffset = 0
|
||||
setSyncedRowsTail(0)
|
||||
|
||||
if (immediate) {
|
||||
syncedRowsCurrentOffset = 0;
|
||||
applySyncedRowScroll(0);
|
||||
lastSyncedRowsAnimationAt = null;
|
||||
stopSyncedRowAnimation();
|
||||
return;
|
||||
syncedRowsCurrentOffset = 0
|
||||
applySyncedRowScroll(0)
|
||||
lastSyncedRowsAnimationAt = null
|
||||
stopSyncedRowAnimation()
|
||||
return
|
||||
}
|
||||
|
||||
if (Math.abs(syncedRowsCurrentOffset) < 0.5) {
|
||||
syncedRowsCurrentOffset = 0;
|
||||
applySyncedRowScroll(0);
|
||||
lastSyncedRowsAnimationAt = null;
|
||||
stopSyncedRowAnimation();
|
||||
return;
|
||||
syncedRowsCurrentOffset = 0
|
||||
applySyncedRowScroll(0)
|
||||
lastSyncedRowsAnimationAt = null
|
||||
stopSyncedRowAnimation()
|
||||
return
|
||||
}
|
||||
|
||||
if (syncedRowsFrame === null) {
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows);
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows)
|
||||
}
|
||||
}
|
||||
|
||||
function stopSyncedRowAnimation() {
|
||||
if (syncedRowsFrame !== null) {
|
||||
window.cancelAnimationFrame(syncedRowsFrame);
|
||||
syncedRowsFrame = null;
|
||||
window.cancelAnimationFrame(syncedRowsFrame)
|
||||
syncedRowsFrame = null
|
||||
}
|
||||
lastSyncedRowsAnimationAt = null;
|
||||
lastSyncedRowsAnimationAt = null
|
||||
}
|
||||
|
||||
function animateSyncedRows(now: number) {
|
||||
const rows = getSyncedRows();
|
||||
const rows = getSyncedRows()
|
||||
if (rows.length === 0) {
|
||||
stopSyncedRowAnimation();
|
||||
return;
|
||||
stopSyncedRowAnimation()
|
||||
return
|
||||
}
|
||||
|
||||
const delta = syncedRowsTargetOffset - syncedRowsCurrentOffset;
|
||||
const elapsedMs = lastSyncedRowsAnimationAt === null ? 16 : Math.max(1, now - lastSyncedRowsAnimationAt);
|
||||
lastSyncedRowsAnimationAt = now;
|
||||
const delta = syncedRowsTargetOffset - syncedRowsCurrentOffset
|
||||
const elapsedMs =
|
||||
lastSyncedRowsAnimationAt === null ? 16 : Math.max(1, now - lastSyncedRowsAnimationAt)
|
||||
lastSyncedRowsAnimationAt = now
|
||||
|
||||
const alpha = 1 - Math.exp(-elapsedMs / SYNC_SCROLL_EASING_MS);
|
||||
syncedRowsCurrentOffset += delta * alpha;
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows);
|
||||
const alpha = 1 - Math.exp(-elapsedMs / SYNC_SCROLL_EASING_MS)
|
||||
syncedRowsCurrentOffset += delta * alpha
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows)
|
||||
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
syncedRowsCurrentOffset = syncedRowsTargetOffset;
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows);
|
||||
stopSyncedRowAnimation();
|
||||
return;
|
||||
syncedRowsCurrentOffset = syncedRowsTargetOffset
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows)
|
||||
stopSyncedRowAnimation()
|
||||
return
|
||||
}
|
||||
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows);
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows)
|
||||
}
|
||||
|
||||
function updateSyncedRowTarget(anchorCol: number, anchorRow: HTMLElement | null = null) {
|
||||
const rows = getSyncedRows();
|
||||
if (rows.length === 0) return;
|
||||
const rows = getSyncedRows()
|
||||
if (rows.length === 0) return
|
||||
|
||||
const metrics = getSyncedRowMetrics(rows);
|
||||
if (!metrics) return;
|
||||
const metrics = getSyncedRowMetrics(rows)
|
||||
if (!metrics) return
|
||||
|
||||
const currentOffset = syncedRowsCurrentOffset;
|
||||
const currentOffset = syncedRowsCurrentOffset
|
||||
const effectiveAnchorOffset = anchorRow
|
||||
? clampRowScrollOffset(anchorRow, currentOffset)
|
||||
: currentOffset;
|
||||
: currentOffset
|
||||
const deadzoneInset = Math.max(
|
||||
metrics.paddingLeft,
|
||||
(metrics.viewportWidth - metrics.cardWidth) * SYNC_SCROLL_DEADZONE_RATIO,
|
||||
);
|
||||
const minVisibleLeft = deadzoneInset;
|
||||
)
|
||||
const minVisibleLeft = deadzoneInset
|
||||
const maxVisibleLeft = Math.max(
|
||||
minVisibleLeft,
|
||||
metrics.viewportWidth - metrics.cardWidth - deadzoneInset,
|
||||
);
|
||||
const itemLeft = metrics.paddingLeft + anchorCol * metrics.stride;
|
||||
const viewportLeft = itemLeft - effectiveAnchorOffset;
|
||||
)
|
||||
const itemLeft = metrics.paddingLeft + anchorCol * metrics.stride
|
||||
const viewportLeft = itemLeft - effectiveAnchorOffset
|
||||
|
||||
const desiredOffset = viewportLeft < minVisibleLeft
|
||||
? Math.max(0, itemLeft - minVisibleLeft)
|
||||
: (viewportLeft > maxVisibleLeft
|
||||
? Math.max(0, itemLeft - maxVisibleLeft)
|
||||
: currentOffset);
|
||||
const desiredOffset =
|
||||
viewportLeft < minVisibleLeft
|
||||
? Math.max(0, itemLeft - minVisibleLeft)
|
||||
: viewportLeft > maxVisibleLeft
|
||||
? Math.max(0, itemLeft - maxVisibleLeft)
|
||||
: currentOffset
|
||||
|
||||
const neededTail = getTailNeededForOffset(desiredOffset, rows);
|
||||
const neededTail = getTailNeededForOffset(desiredOffset, rows)
|
||||
if (Math.abs(neededTail - syncedRowsTailPx) >= 0.5) {
|
||||
setSyncedRowsTail(neededTail, rows);
|
||||
setSyncedRowsTail(neededTail, rows)
|
||||
}
|
||||
|
||||
lastSyncedAnchorCol = anchorCol;
|
||||
syncedRowsTargetOffset = desiredOffset;
|
||||
lastSyncedAnchorCol = anchorCol
|
||||
syncedRowsTargetOffset = desiredOffset
|
||||
|
||||
if (anchorRow) {
|
||||
// Preserve a global virtual offset, bounded by the focused row after tail-space is applied.
|
||||
syncedRowsTargetOffset = Math.min(syncedRowsTargetOffset, getRowMaxOffset(anchorRow));
|
||||
syncedRowsTargetOffset = Math.min(syncedRowsTargetOffset, getRowMaxOffset(anchorRow))
|
||||
} else if (syncedRowsTailPx > 0) {
|
||||
setSyncedRowsTail(0, rows);
|
||||
setSyncedRowsTail(0, rows)
|
||||
}
|
||||
|
||||
if (syncedRowsFrame === null) {
|
||||
syncedRowsCurrentOffset = currentOffset;
|
||||
syncedRowsCurrentOffset = currentOffset
|
||||
}
|
||||
|
||||
if (Math.abs(syncedRowsTargetOffset - syncedRowsCurrentOffset) < 0.5) {
|
||||
syncedRowsCurrentOffset = syncedRowsTargetOffset;
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows);
|
||||
stopSyncedRowAnimation();
|
||||
return;
|
||||
syncedRowsCurrentOffset = syncedRowsTargetOffset
|
||||
applySyncedRowScroll(syncedRowsCurrentOffset, rows)
|
||||
stopSyncedRowAnimation()
|
||||
return
|
||||
}
|
||||
|
||||
if (syncedRowsFrame === null) {
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows);
|
||||
syncedRowsFrame = window.requestAnimationFrame(animateSyncedRows)
|
||||
}
|
||||
}
|
||||
|
||||
function syncRowsToElement(element: HTMLElement) {
|
||||
const row = parseInt(element.getAttribute(ROW_ATTR) || '0', 10);
|
||||
const row = parseInt(element.getAttribute(ROW_ATTR) || "0", 10)
|
||||
if (row < SYNC_SCROLL_FIRST_CONTENT_ROW) {
|
||||
resetSyncedRows();
|
||||
return;
|
||||
resetSyncedRows()
|
||||
return
|
||||
}
|
||||
|
||||
const currentCol = parseInt(element.getAttribute(COL_ATTR) || '0', 10);
|
||||
const anchorCol = desiredCol.value ?? currentCol;
|
||||
const anchorRow = element.closest<HTMLElement>(`[${SYNC_SCROLL_ROW_ATTR}="true"]`);
|
||||
updateSyncedRowTarget(anchorCol, anchorRow);
|
||||
const currentCol = parseInt(element.getAttribute(COL_ATTR) || "0", 10)
|
||||
const anchorCol = desiredCol.value ?? currentCol
|
||||
const anchorRow = element.closest<HTMLElement>(`[${SYNC_SCROLL_ROW_ATTR}="true"]`)
|
||||
updateSyncedRowTarget(anchorCol, anchorRow)
|
||||
}
|
||||
|
||||
function handleSyncedRowResize() {
|
||||
if (lastSyncedAnchorCol === null) {
|
||||
resetSyncedRows(true);
|
||||
return;
|
||||
resetSyncedRows(true)
|
||||
return
|
||||
}
|
||||
updateSyncedRowTarget(lastSyncedAnchorCol);
|
||||
updateSyncedRowTarget(lastSyncedAnchorCol)
|
||||
}
|
||||
|
||||
function ensureElementVisibleVertically(element: HTMLElement) {
|
||||
const rootStyle = window.getComputedStyle(document.documentElement);
|
||||
const headerHeight = parseFloat(rootStyle.getPropertyValue('--header-height') || '0');
|
||||
const topMargin = headerHeight + 24;
|
||||
const bottomMargin = 24;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const rootStyle = window.getComputedStyle(document.documentElement)
|
||||
const headerHeight = parseFloat(rootStyle.getPropertyValue("--header-height") || "0")
|
||||
const topMargin = headerHeight + 24
|
||||
const bottomMargin = 24
|
||||
const rect = element.getBoundingClientRect()
|
||||
|
||||
if (rect.top < topMargin) {
|
||||
window.scrollBy({
|
||||
top: rect.top - topMargin,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
return;
|
||||
behavior: "smooth",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (rect.bottom > window.innerHeight - bottomMargin) {
|
||||
window.scrollBy({
|
||||
top: rect.bottom - (window.innerHeight - bottomMargin),
|
||||
behavior: 'smooth',
|
||||
});
|
||||
behavior: "smooth",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,91 +274,95 @@ function ensureElementVisibleVertically(element: HTMLElement) {
|
||||
* Get all focusable elements in the DOM, grouped by row
|
||||
*/
|
||||
function getFocusableElements(): FocusableElement[] {
|
||||
const elements = document.querySelectorAll(`[${FOCUSABLE_ATTR}]`);
|
||||
const result: FocusableElement[] = [];
|
||||
const elements = document.querySelectorAll(`[${FOCUSABLE_ATTR}]`)
|
||||
const result: FocusableElement[] = []
|
||||
|
||||
elements.forEach((el) => {
|
||||
const htmlEl = el as HTMLElement;
|
||||
const htmlEl = el as HTMLElement
|
||||
// Skip hidden elements
|
||||
if (htmlEl.offsetParent === null) return;
|
||||
if (htmlEl.offsetParent === null) return
|
||||
|
||||
const rect = htmlEl.getBoundingClientRect();
|
||||
const rect = htmlEl.getBoundingClientRect()
|
||||
// Skip elements not in viewport or zero-sized
|
||||
if (rect.width === 0 || rect.height === 0) return;
|
||||
if (rect.width === 0 || rect.height === 0) return
|
||||
|
||||
const row = parseInt(htmlEl.getAttribute(ROW_ATTR) || '0', 10);
|
||||
const col = parseInt(htmlEl.getAttribute(COL_ATTR) || '0', 10);
|
||||
const row = parseInt(htmlEl.getAttribute(ROW_ATTR) || "0", 10)
|
||||
const col = parseInt(htmlEl.getAttribute(COL_ATTR) || "0", 10)
|
||||
|
||||
result.push({
|
||||
element: htmlEl,
|
||||
row,
|
||||
col,
|
||||
});
|
||||
});
|
||||
})
|
||||
})
|
||||
|
||||
return result;
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Get elements grouped by row
|
||||
*/
|
||||
function getElementsByRow(): Map<number, FocusableElement[]> {
|
||||
const elements = getFocusableElements();
|
||||
const byRow = new Map<number, FocusableElement[]>();
|
||||
const elements = getFocusableElements()
|
||||
const byRow = new Map<number, FocusableElement[]>()
|
||||
|
||||
for (const el of elements) {
|
||||
if (!byRow.has(el.row)) {
|
||||
byRow.set(el.row, []);
|
||||
byRow.set(el.row, [])
|
||||
}
|
||||
byRow.get(el.row)!.push(el);
|
||||
byRow.get(el.row)!.push(el)
|
||||
}
|
||||
|
||||
// Sort each row by column
|
||||
for (const [, rowElements] of byRow) {
|
||||
rowElements.sort((a, b) => a.col - b.col);
|
||||
rowElements.sort((a, b) => a.col - b.col)
|
||||
}
|
||||
|
||||
return byRow;
|
||||
return byRow
|
||||
}
|
||||
|
||||
/**
|
||||
* Find element by row and col indices
|
||||
* @param useEntryCol - if true, check for entry-col override on elements
|
||||
*/
|
||||
function findElementAt(row: number, col: number, useEntryCol: boolean = false): FocusableElement | null {
|
||||
const byRow = getElementsByRow();
|
||||
const rowElements = byRow.get(row);
|
||||
if (!rowElements || rowElements.length === 0) return null;
|
||||
function findElementAt(
|
||||
row: number,
|
||||
col: number,
|
||||
useEntryCol: boolean = false,
|
||||
): FocusableElement | null {
|
||||
const byRow = getElementsByRow()
|
||||
const rowElements = byRow.get(row)
|
||||
if (!rowElements || rowElements.length === 0) return null
|
||||
|
||||
// Check if any element in this row has an entry-col override
|
||||
if (useEntryCol) {
|
||||
for (const el of rowElements) {
|
||||
const entryCol = el.element.getAttribute(ENTRY_COL_ATTR);
|
||||
const entryCol = el.element.getAttribute(ENTRY_COL_ATTR)
|
||||
if (entryCol !== null) {
|
||||
const overrideCol = parseInt(entryCol, 10);
|
||||
const entryTarget = rowElements.find(e => e.col === overrideCol);
|
||||
if (entryTarget) return entryTarget;
|
||||
const overrideCol = parseInt(entryCol, 10)
|
||||
const entryTarget = rowElements.find((e) => e.col === overrideCol)
|
||||
if (entryTarget) return entryTarget
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find exact match or nearest col
|
||||
const exact = rowElements.find(e => e.col === col);
|
||||
if (exact) return exact;
|
||||
const exact = rowElements.find((e) => e.col === col)
|
||||
if (exact) return exact
|
||||
|
||||
// Find nearest col in this row
|
||||
let nearest = rowElements[0];
|
||||
let nearestDist = Math.abs(nearest.col - col);
|
||||
let nearest = rowElements[0]
|
||||
let nearestDist = Math.abs(nearest.col - col)
|
||||
|
||||
for (const el of rowElements) {
|
||||
const dist = Math.abs(el.col - col);
|
||||
const dist = Math.abs(el.col - col)
|
||||
if (dist < nearestDist) {
|
||||
nearest = el;
|
||||
nearestDist = dist;
|
||||
nearest = el
|
||||
nearestDist = dist
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
return nearest
|
||||
}
|
||||
|
||||
function findElementClosestToLogicalViewportX(
|
||||
@@ -367,43 +371,42 @@ function findElementClosestToLogicalViewportX(
|
||||
preferredCol: number,
|
||||
metrics: { cardWidth: number; stride: number; paddingLeft: number } | null,
|
||||
): FocusableElement | null {
|
||||
const byRow = getElementsByRow();
|
||||
const rowElements = byRow.get(row);
|
||||
if (!rowElements || rowElements.length === 0) return null;
|
||||
const byRow = getElementsByRow()
|
||||
const rowElements = byRow.get(row)
|
||||
if (!rowElements || rowElements.length === 0) return null
|
||||
|
||||
let nearest: FocusableElement | null = null;
|
||||
let nearestViewportDist = Number.POSITIVE_INFINITY;
|
||||
let nearestColDist = Number.POSITIVE_INFINITY;
|
||||
let nearest: FocusableElement | null = null
|
||||
let nearestViewportDist = Number.POSITIVE_INFINITY
|
||||
let nearestColDist = Number.POSITIVE_INFINITY
|
||||
|
||||
for (const candidate of rowElements) {
|
||||
let candidateCenterX: number;
|
||||
let candidateCenterX: number
|
||||
if (metrics) {
|
||||
// Compare using global synced offset so capped rows do not skew vertical matching.
|
||||
candidateCenterX = (
|
||||
metrics.paddingLeft
|
||||
+ candidate.col * metrics.stride
|
||||
- syncedRowsCurrentOffset
|
||||
+ metrics.cardWidth / 2
|
||||
);
|
||||
candidateCenterX =
|
||||
metrics.paddingLeft +
|
||||
candidate.col * metrics.stride -
|
||||
syncedRowsCurrentOffset +
|
||||
metrics.cardWidth / 2
|
||||
} else {
|
||||
const rect = candidate.element.getBoundingClientRect();
|
||||
candidateCenterX = rect.left + rect.width / 2;
|
||||
const rect = candidate.element.getBoundingClientRect()
|
||||
candidateCenterX = rect.left + rect.width / 2
|
||||
}
|
||||
|
||||
const viewportDist = Math.abs(candidateCenterX - logicalViewportCenterX);
|
||||
const colDist = Math.abs(candidate.col - preferredCol);
|
||||
const viewportDist = Math.abs(candidateCenterX - logicalViewportCenterX)
|
||||
const colDist = Math.abs(candidate.col - preferredCol)
|
||||
|
||||
if (
|
||||
viewportDist < nearestViewportDist
|
||||
|| (Math.abs(viewportDist - nearestViewportDist) < 0.5 && colDist < nearestColDist)
|
||||
viewportDist < nearestViewportDist ||
|
||||
(Math.abs(viewportDist - nearestViewportDist) < 0.5 && colDist < nearestColDist)
|
||||
) {
|
||||
nearest = candidate;
|
||||
nearestViewportDist = viewportDist;
|
||||
nearestColDist = colDist;
|
||||
nearest = candidate
|
||||
nearestViewportDist = viewportDist
|
||||
nearestColDist = colDist
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
return nearest
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -411,70 +414,73 @@ function findElementClosestToLogicalViewportX(
|
||||
*/
|
||||
function findNextElement(
|
||||
current: HTMLElement,
|
||||
direction: 'up' | 'down' | 'left' | 'right'
|
||||
direction: "up" | "down" | "left" | "right",
|
||||
): HTMLElement | null {
|
||||
const currentRow = parseInt(current.getAttribute(ROW_ATTR) || '0', 10);
|
||||
const currentCol = parseInt(current.getAttribute(COL_ATTR) || '0', 10);
|
||||
const byRow = getElementsByRow();
|
||||
const currentRow = parseInt(current.getAttribute(ROW_ATTR) || "0", 10)
|
||||
const currentCol = parseInt(current.getAttribute(COL_ATTR) || "0", 10)
|
||||
const byRow = getElementsByRow()
|
||||
|
||||
if (direction === 'left' || direction === 'right') {
|
||||
if (direction === "left" || direction === "right") {
|
||||
// Horizontal: move within same row by col index
|
||||
desiredCol.value = null; // Reset desired col on horizontal movement
|
||||
desiredCol.value = null // Reset desired col on horizontal movement
|
||||
|
||||
const rowElements = byRow.get(currentRow);
|
||||
if (!rowElements) return null;
|
||||
const rowElements = byRow.get(currentRow)
|
||||
if (!rowElements) return null
|
||||
|
||||
const delta = direction === 'right' ? 1 : -1;
|
||||
const targetCol = currentCol + delta;
|
||||
const delta = direction === "right" ? 1 : -1
|
||||
const targetCol = currentCol + delta
|
||||
|
||||
// Find element with target col in this row
|
||||
const target = rowElements.find(e => e.col === targetCol);
|
||||
return target?.element || null;
|
||||
const target = rowElements.find((e) => e.col === targetCol)
|
||||
return target?.element || null
|
||||
} else {
|
||||
// Vertical: move to adjacent row, try to maintain column
|
||||
const sortedRows = Array.from(byRow.keys()).sort((a, b) => a - b);
|
||||
const currentRowIdx = sortedRows.indexOf(currentRow);
|
||||
const sortedRows = Array.from(byRow.keys()).sort((a, b) => a - b)
|
||||
const currentRowIdx = sortedRows.indexOf(currentRow)
|
||||
|
||||
if (currentRowIdx === -1) return null;
|
||||
if (currentRowIdx === -1) return null
|
||||
|
||||
const delta = direction === 'down' ? 1 : -1;
|
||||
const targetRowIdx = currentRowIdx + delta;
|
||||
const delta = direction === "down" ? 1 : -1
|
||||
const targetRowIdx = currentRowIdx + delta
|
||||
|
||||
if (targetRowIdx < 0 || targetRowIdx >= sortedRows.length) return null;
|
||||
if (targetRowIdx < 0 || targetRowIdx >= sortedRows.length) return null
|
||||
|
||||
const targetRow = sortedRows[targetRowIdx];
|
||||
const targetRow = sortedRows[targetRowIdx]
|
||||
|
||||
// Use desired col if set, otherwise use current col
|
||||
const targetCol = desiredCol.value ?? currentCol;
|
||||
const targetCol = desiredCol.value ?? currentCol
|
||||
|
||||
// Set desired col if not already set (first vertical move in a sequence)
|
||||
if (desiredCol.value === null) {
|
||||
desiredCol.value = currentCol;
|
||||
desiredCol.value = currentCol
|
||||
}
|
||||
|
||||
// Use entry column hook for vertical navigation when present.
|
||||
const entryTarget = findElementAt(targetRow, targetCol, true);
|
||||
const targetRowElements = byRow.get(targetRow) ?? [];
|
||||
const hasEntryOverride = targetRowElements.some(el => el.element.hasAttribute(ENTRY_COL_ATTR));
|
||||
const entryTarget = findElementAt(targetRow, targetCol, true)
|
||||
const targetRowElements = byRow.get(targetRow) ?? []
|
||||
const hasEntryOverride = targetRowElements.some((el) => el.element.hasAttribute(ENTRY_COL_ATTR))
|
||||
if (hasEntryOverride) {
|
||||
return entryTarget?.element || null;
|
||||
return entryTarget?.element || null
|
||||
}
|
||||
|
||||
const syncedRows = getSyncedRows();
|
||||
const metrics = getSyncedRowMetrics(syncedRows);
|
||||
const syncedRows = getSyncedRows()
|
||||
const metrics = getSyncedRowMetrics(syncedRows)
|
||||
const logicalCurrentCenterX = metrics
|
||||
? metrics.paddingLeft + currentCol * metrics.stride - syncedRowsCurrentOffset + metrics.cardWidth / 2
|
||||
? metrics.paddingLeft +
|
||||
currentCol * metrics.stride -
|
||||
syncedRowsCurrentOffset +
|
||||
metrics.cardWidth / 2
|
||||
: (() => {
|
||||
const currentRect = current.getBoundingClientRect();
|
||||
return currentRect.left + currentRect.width / 2;
|
||||
})();
|
||||
const currentRect = current.getBoundingClientRect()
|
||||
return currentRect.left + currentRect.width / 2
|
||||
})()
|
||||
const closestByViewport = findElementClosestToLogicalViewportX(
|
||||
targetRow,
|
||||
logicalCurrentCenterX,
|
||||
targetCol,
|
||||
metrics,
|
||||
);
|
||||
return closestByViewport?.element || entryTarget?.element || null;
|
||||
)
|
||||
return closestByViewport?.element || entryTarget?.element || null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,45 +488,45 @@ function findNextElement(
|
||||
* Focus an element and scroll it into view
|
||||
*/
|
||||
function focusElement(element: HTMLElement | null) {
|
||||
if (!element) return;
|
||||
if (!element) return
|
||||
|
||||
// Remove focus from previous element
|
||||
if (focusedElement.value && focusedElement.value !== element) {
|
||||
focusedElement.value.classList.remove('nav-focused');
|
||||
focusedElement.value.blur();
|
||||
focusedElement.value.classList.remove("nav-focused")
|
||||
focusedElement.value.blur()
|
||||
}
|
||||
|
||||
// Add focus to new element
|
||||
element.classList.add('nav-focused');
|
||||
element.focus({ preventScroll: true });
|
||||
element.classList.add("nav-focused")
|
||||
element.focus({ preventScroll: true })
|
||||
|
||||
ensureElementVisibleVertically(element);
|
||||
syncRowsToElement(element);
|
||||
ensureElementVisibleVertically(element)
|
||||
syncRowsToElement(element)
|
||||
|
||||
focusedElement.value = element;
|
||||
focusedElement.value = element
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current focus state (row, col) for saving
|
||||
*/
|
||||
function getFocusState(): { row: number; col: number } | null {
|
||||
if (!focusedElement.value) return null;
|
||||
const row = parseInt(focusedElement.value.getAttribute(ROW_ATTR) || '0', 10);
|
||||
const col = parseInt(focusedElement.value.getAttribute(COL_ATTR) || '0', 10);
|
||||
return { row, col };
|
||||
if (!focusedElement.value) return null
|
||||
const row = parseInt(focusedElement.value.getAttribute(ROW_ATTR) || "0", 10)
|
||||
const col = parseInt(focusedElement.value.getAttribute(COL_ATTR) || "0", 10)
|
||||
return { row, col }
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore focus to element with given row/col
|
||||
*/
|
||||
function restoreFocusState(state: { row: number; col: number } | null) {
|
||||
if (!state) return;
|
||||
if (!state) return
|
||||
|
||||
const target = findElementAt(state.row, state.col);
|
||||
const target = findElementAt(state.row, state.col)
|
||||
if (target) {
|
||||
setTimeout(() => {
|
||||
focusElement(target.element);
|
||||
}, 50);
|
||||
focusElement(target.element)
|
||||
}, 50)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,79 +535,79 @@ function restoreFocusState(state: { row: number; col: number } | null) {
|
||||
*/
|
||||
function focusAt(row: number, col: number, delay: number = 100) {
|
||||
setTimeout(() => {
|
||||
const target = findElementAt(row, col);
|
||||
const target = findElementAt(row, col)
|
||||
if (target) {
|
||||
focusElement(target.element);
|
||||
focusElement(target.element)
|
||||
}
|
||||
}, delay);
|
||||
}, delay)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should allow navigation from an input element
|
||||
*/
|
||||
function shouldAllowNavigationFromInput(target: HTMLElement, direction: string): boolean {
|
||||
if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA' && !target.isContentEditable) {
|
||||
return true; // Not an input, allow navigation
|
||||
if (target.tagName !== "INPUT" && target.tagName !== "TEXTAREA" && !target.isContentEditable) {
|
||||
return true // Not an input, allow navigation
|
||||
}
|
||||
|
||||
// Always allow up/down navigation from inputs
|
||||
if (direction === 'up' || direction === 'down') {
|
||||
return true;
|
||||
if (direction === "up" || direction === "down") {
|
||||
return true
|
||||
}
|
||||
|
||||
// For left/right, only capture if input is empty
|
||||
const inputEl = target as HTMLInputElement | HTMLTextAreaElement;
|
||||
const value = inputEl.value || '';
|
||||
return value.length === 0;
|
||||
const inputEl = target as HTMLInputElement | HTMLTextAreaElement
|
||||
const value = inputEl.value || ""
|
||||
return value.length === 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle keyboard navigation
|
||||
*/
|
||||
function handleKeyDown(event: KeyboardEvent) {
|
||||
const target = event.target as HTMLElement;
|
||||
const target = event.target as HTMLElement
|
||||
|
||||
const direction = {
|
||||
ArrowUp: 'up',
|
||||
ArrowDown: 'down',
|
||||
ArrowLeft: 'left',
|
||||
ArrowRight: 'right',
|
||||
}[event.key] as 'up' | 'down' | 'left' | 'right' | undefined;
|
||||
ArrowUp: "up",
|
||||
ArrowDown: "down",
|
||||
ArrowLeft: "left",
|
||||
ArrowRight: "right",
|
||||
}[event.key] as "up" | "down" | "left" | "right" | undefined
|
||||
|
||||
if (!direction) return;
|
||||
if (!direction) return
|
||||
|
||||
// Check if we should allow navigation from this element
|
||||
if (!shouldAllowNavigationFromInput(target, direction)) {
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
isNavigating.value = true;
|
||||
event.preventDefault()
|
||||
isNavigating.value = true
|
||||
|
||||
// Get current focused element or find the first one
|
||||
let current = focusedElement.value;
|
||||
let current = focusedElement.value
|
||||
|
||||
// If no element is focused, try to get the currently focused element from DOM
|
||||
if (!current) {
|
||||
const activeElement = document.activeElement as HTMLElement;
|
||||
const activeElement = document.activeElement as HTMLElement
|
||||
if (activeElement && activeElement.hasAttribute(FOCUSABLE_ATTR)) {
|
||||
current = activeElement;
|
||||
current = activeElement
|
||||
}
|
||||
}
|
||||
|
||||
// If still no current, focus the first available element
|
||||
if (!current) {
|
||||
const elements = getFocusableElements();
|
||||
const elements = getFocusableElements()
|
||||
if (elements.length > 0) {
|
||||
focusElement(elements[0].element);
|
||||
focusElement(elements[0].element)
|
||||
}
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
// Find and focus the next element using index-based navigation
|
||||
const next = findNextElement(current, direction);
|
||||
const next = findNextElement(current, direction)
|
||||
if (next) {
|
||||
focusElement(next);
|
||||
focusElement(next)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,18 +615,18 @@ function handleKeyDown(event: KeyboardEvent) {
|
||||
* Handle Enter key to activate focused element
|
||||
*/
|
||||
function handleEnterKey(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter') return;
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
|
||||
if (event.key !== "Enter") return
|
||||
if (event.defaultPrevented) return
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
|
||||
|
||||
const target = event.target as HTMLElement;
|
||||
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
|
||||
return;
|
||||
const target = event.target as HTMLElement
|
||||
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA") {
|
||||
return
|
||||
}
|
||||
|
||||
if (focusedElement.value) {
|
||||
event.preventDefault();
|
||||
focusedElement.value.click();
|
||||
event.preventDefault()
|
||||
focusedElement.value.click()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -629,40 +635,40 @@ function handleEnterKey(event: KeyboardEvent) {
|
||||
* Should be called once at app initialization
|
||||
*/
|
||||
export function installKeyboardNavigation() {
|
||||
if (handlersInstalled) return;
|
||||
handlersInstalled = true;
|
||||
if (handlersInstalled) return
|
||||
handlersInstalled = true
|
||||
|
||||
resetSyncedRows(true);
|
||||
resetSyncedRows(true)
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
document.addEventListener('keydown', handleEnterKey);
|
||||
window.addEventListener('resize', handleSyncedRowResize, { passive: true });
|
||||
document.addEventListener("keydown", handleKeyDown)
|
||||
document.addEventListener("keydown", handleEnterKey)
|
||||
window.addEventListener("resize", handleSyncedRowResize, { passive: true })
|
||||
|
||||
// Handle mouse clicks to update focus state
|
||||
document.addEventListener('click', (event) => {
|
||||
const target = event.target as HTMLElement;
|
||||
const focusable = target.closest(`[${FOCUSABLE_ATTR}]`) as HTMLElement | null;
|
||||
document.addEventListener("click", (event) => {
|
||||
const target = event.target as HTMLElement
|
||||
const focusable = target.closest(`[${FOCUSABLE_ATTR}]`) as HTMLElement | null
|
||||
if (focusable) {
|
||||
desiredCol.value = null; // Reset desired col on mouse click
|
||||
focusElement(focusable);
|
||||
desiredCol.value = null // Reset desired col on mouse click
|
||||
focusElement(focusable)
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// Handle focus events from tab navigation
|
||||
document.addEventListener('focusin', (event) => {
|
||||
const target = event.target as HTMLElement;
|
||||
document.addEventListener("focusin", (event) => {
|
||||
const target = event.target as HTMLElement
|
||||
if (target.hasAttribute(FOCUSABLE_ATTR)) {
|
||||
if (focusedElement.value && focusedElement.value !== target) {
|
||||
focusedElement.value.classList.remove('nav-focused');
|
||||
focusedElement.value.classList.remove("nav-focused")
|
||||
}
|
||||
focusedElement.value = target;
|
||||
target.classList.add('nav-focused');
|
||||
desiredCol.value = null; // Reset desired col on focus change
|
||||
syncRowsToElement(target);
|
||||
focusedElement.value = target
|
||||
target.classList.add("nav-focused")
|
||||
desiredCol.value = null // Reset desired col on focus change
|
||||
syncRowsToElement(target)
|
||||
} else {
|
||||
resetSyncedRows();
|
||||
resetSyncedRows()
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -677,7 +683,7 @@ export function useKeyboardNavigation() {
|
||||
focusAt,
|
||||
getFocusState,
|
||||
restoreFocusState,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -686,15 +692,15 @@ export function useKeyboardNavigation() {
|
||||
*/
|
||||
export function navAttrs(row: number, col: number, entryCol?: number) {
|
||||
const attrs: Record<string, string | number> = {
|
||||
[FOCUSABLE_ATTR]: 'true',
|
||||
[FOCUSABLE_ATTR]: "true",
|
||||
[ROW_ATTR]: String(row),
|
||||
[COL_ATTR]: String(col),
|
||||
tabindex: 0,
|
||||
};
|
||||
if (entryCol !== undefined) {
|
||||
attrs[ENTRY_COL_ATTR] = String(entryCol);
|
||||
}
|
||||
return attrs;
|
||||
if (entryCol !== undefined) {
|
||||
attrs[ENTRY_COL_ATTR] = String(entryCol)
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
export { FOCUSABLE_ATTR, ROW_ATTR, COL_ATTR, ENTRY_COL_ATTR };
|
||||
export { FOCUSABLE_ATTR, ROW_ATTR, COL_ATTR, ENTRY_COL_ATTR }
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import { ref, readonly, onUnmounted } from 'vue';
|
||||
import type { Movie, Series, Episode, Season, Torrent, MediaIndex, TaskInfo, WsMessage } from '../types';
|
||||
import { ref, readonly, onUnmounted } from "vue"
|
||||
import type {
|
||||
Movie,
|
||||
Series,
|
||||
Episode,
|
||||
Season,
|
||||
Torrent,
|
||||
MediaIndex,
|
||||
TaskInfo,
|
||||
WsMessage,
|
||||
} from "../types"
|
||||
|
||||
interface RootState {
|
||||
rootId: string;
|
||||
ws: WebSocket | null;
|
||||
movieMap: Map<string, Movie>;
|
||||
seriesMap: Map<string, Series>;
|
||||
connected: boolean;
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
rootId: string
|
||||
ws: WebSocket | null
|
||||
movieMap: Map<string, Movie>
|
||||
seriesMap: Map<string, Series>
|
||||
connected: boolean
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -21,57 +30,63 @@ interface RootState {
|
||||
* - "task" → background task progress
|
||||
*/
|
||||
export function useMediaWebSocket() {
|
||||
const mediaIndex = ref<MediaIndex | null>(null);
|
||||
const loading = ref(true);
|
||||
const error = ref<string | null>(null);
|
||||
const connected = ref(false);
|
||||
const tasks = ref<Map<string, TaskInfo>>(new Map());
|
||||
const mediaIndex = ref<MediaIndex | null>(null)
|
||||
const loading = ref(true)
|
||||
const error = ref<string | null>(null)
|
||||
const connected = ref(false)
|
||||
const tasks = ref<Map<string, TaskInfo>>(new Map())
|
||||
|
||||
const roots = ref<Map<string, RootState>>(new Map());
|
||||
let disposed = false;
|
||||
const roots = ref<Map<string, RootState>>(new Map())
|
||||
let disposed = false
|
||||
|
||||
function getContentHash(itemId: string): string {
|
||||
return itemId.split(':').pop() || itemId;
|
||||
return itemId.split(":").pop() || itemId
|
||||
}
|
||||
|
||||
function torrentQualityScore(t: Torrent): number {
|
||||
let score = 0;
|
||||
const res = (t.resolution || '').toLowerCase();
|
||||
if (res.includes('2160') || res.includes('4k') || res.includes('uhd')) score += 100;
|
||||
else if (res.includes('1080') || res.includes('fhd')) score += 80;
|
||||
else if (res.includes('720') || res === 'hd') score += 60;
|
||||
else if (res.includes('480') || res === 'sd') score += 40;
|
||||
else if (res.includes('360')) score += 20;
|
||||
if (t.has_dolby_vision) score += 15;
|
||||
if (t.is_hdr) score += 10;
|
||||
if (t.has_dolby_atmos) score += 5;
|
||||
return score;
|
||||
let score = 0
|
||||
const res = (t.resolution || "").toLowerCase()
|
||||
if (res.includes("2160") || res.includes("4k") || res.includes("uhd")) score += 100
|
||||
else if (res.includes("1080") || res.includes("fhd")) score += 80
|
||||
else if (res.includes("720") || res === "hd") score += 60
|
||||
else if (res.includes("480") || res === "sd") score += 40
|
||||
else if (res.includes("360")) score += 20
|
||||
if (t.has_dolby_vision) score += 15
|
||||
if (t.is_hdr) score += 10
|
||||
if (t.has_dolby_atmos) score += 5
|
||||
return score
|
||||
}
|
||||
|
||||
function annotateTorrents(torrents: { [key: string]: Torrent }, rootId: string | null): { [key: string]: Torrent } {
|
||||
function annotateTorrents(
|
||||
torrents: { [key: string]: Torrent },
|
||||
rootId: string | null,
|
||||
): { [key: string]: Torrent } {
|
||||
return Object.fromEntries(
|
||||
Object.entries(torrents || {}).map(([k, t]) => [k, { ...t, root_id: t.root_id || rootId }])
|
||||
);
|
||||
Object.entries(torrents || {}).map(([k, t]) => [k, { ...t, root_id: t.root_id || rootId }]),
|
||||
)
|
||||
}
|
||||
|
||||
function mergeTorrentDicts(a: { [key: string]: Torrent }, b: { [key: string]: Torrent }): { [key: string]: Torrent } {
|
||||
const merged: { [key: string]: Torrent } = { ...a };
|
||||
function mergeTorrentDicts(
|
||||
a: { [key: string]: Torrent },
|
||||
b: { [key: string]: Torrent },
|
||||
): { [key: string]: Torrent } {
|
||||
const merged: { [key: string]: Torrent } = { ...a }
|
||||
for (const [k, t] of Object.entries(b)) {
|
||||
const uniqueKey = merged[k] ? `${t.root_id || 'unknown'}:${k}` : k;
|
||||
merged[uniqueKey] = t;
|
||||
const uniqueKey = merged[k] ? `${t.root_id || "unknown"}:${k}` : k
|
||||
merged[uniqueKey] = t
|
||||
}
|
||||
const sorted = Object.entries(merged).sort(([, t1], [, t2]) => {
|
||||
const s1 = torrentQualityScore(t1);
|
||||
const s2 = torrentQualityScore(t2);
|
||||
if (s2 !== s1) return s2 - s1;
|
||||
return (t2.size || 0) - (t1.size || 0);
|
||||
});
|
||||
return Object.fromEntries(sorted);
|
||||
const s1 = torrentQualityScore(t1)
|
||||
const s2 = torrentQualityScore(t2)
|
||||
if (s2 !== s1) return s2 - s1
|
||||
return (t2.size || 0) - (t1.size || 0)
|
||||
})
|
||||
return Object.fromEntries(sorted)
|
||||
}
|
||||
|
||||
function mergeMovies(a: Movie, b: Movie): Movie {
|
||||
const torrentsA = annotateTorrents(a.torrents, a.root_id);
|
||||
const torrentsB = annotateTorrents(b.torrents, b.root_id);
|
||||
const torrentsA = annotateTorrents(a.torrents, a.root_id)
|
||||
const torrentsB = annotateTorrents(b.torrents, b.root_id)
|
||||
return {
|
||||
...a,
|
||||
torrents: mergeTorrentDicts(torrentsA, torrentsB),
|
||||
@@ -79,58 +94,79 @@ export function useMediaWebSocket() {
|
||||
cover_path: a.cover_path || b.cover_path,
|
||||
backdrop_path: a.backdrop_path || b.backdrop_path,
|
||||
showreel_images: a.showreel_images?.length ? a.showreel_images : b.showreel_images,
|
||||
showreel_source_sets: a.showreel_source_sets?.length ? a.showreel_source_sets : b.showreel_source_sets,
|
||||
};
|
||||
showreel_source_sets: a.showreel_source_sets?.length
|
||||
? a.showreel_source_sets
|
||||
: b.showreel_source_sets,
|
||||
}
|
||||
}
|
||||
|
||||
function mergeEpisodes(a: Episode, b: Episode, rootIdA: string | null, rootIdB: string | null): Episode {
|
||||
const torrentsA = annotateTorrents(a.torrents, rootIdA);
|
||||
const torrentsB = annotateTorrents(b.torrents, rootIdB);
|
||||
function mergeEpisodes(
|
||||
a: Episode,
|
||||
b: Episode,
|
||||
rootIdA: string | null,
|
||||
rootIdB: string | null,
|
||||
): Episode {
|
||||
const torrentsA = annotateTorrents(a.torrents, rootIdA)
|
||||
const torrentsB = annotateTorrents(b.torrents, rootIdB)
|
||||
return {
|
||||
...a,
|
||||
torrents: mergeTorrentDicts(torrentsA, torrentsB),
|
||||
reel_image: a.reel_image || b.reel_image,
|
||||
reel_sources: a.reel_sources?.length ? a.reel_sources : b.reel_sources,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function mergeSeasons(a: Season, b: Season, rootIdA: string | null, rootIdB: string | null): Season {
|
||||
const episodeMap = new Map<number, Episode>();
|
||||
function mergeSeasons(
|
||||
a: Season,
|
||||
b: Season,
|
||||
rootIdA: string | null,
|
||||
rootIdB: string | null,
|
||||
): Season {
|
||||
const episodeMap = new Map<number, Episode>()
|
||||
for (const ep of a.episodes) {
|
||||
episodeMap.set(ep.episode_number, ep);
|
||||
episodeMap.set(ep.episode_number, ep)
|
||||
}
|
||||
for (const ep of b.episodes) {
|
||||
const existing = episodeMap.get(ep.episode_number);
|
||||
const existing = episodeMap.get(ep.episode_number)
|
||||
if (existing) {
|
||||
episodeMap.set(ep.episode_number, mergeEpisodes(existing, ep, rootIdA, rootIdB));
|
||||
episodeMap.set(ep.episode_number, mergeEpisodes(existing, ep, rootIdA, rootIdB))
|
||||
} else {
|
||||
episodeMap.set(ep.episode_number, {
|
||||
...ep,
|
||||
torrents: annotateTorrents(ep.torrents, rootIdB),
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
return {
|
||||
...a,
|
||||
episodes: Array.from(episodeMap.values()).sort((a, b) => a.episode_number - b.episode_number),
|
||||
poster_path: a.poster_path || b.poster_path,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function mergeSeries(a: Series, b: Series): Series {
|
||||
const seasonMap = new Map<number, Season>();
|
||||
const seasonMap = new Map<number, Season>()
|
||||
for (const season of a.seasons || []) {
|
||||
seasonMap.set(season.season_number, { ...season, episodes: season.episodes.map(ep => ({ ...ep, torrents: annotateTorrents(ep.torrents, a.root_id) })) });
|
||||
seasonMap.set(season.season_number, {
|
||||
...season,
|
||||
episodes: season.episodes.map((ep) => ({
|
||||
...ep,
|
||||
torrents: annotateTorrents(ep.torrents, a.root_id),
|
||||
})),
|
||||
})
|
||||
}
|
||||
for (const season of b.seasons || []) {
|
||||
const existing = seasonMap.get(season.season_number);
|
||||
const existing = seasonMap.get(season.season_number)
|
||||
if (existing) {
|
||||
seasonMap.set(season.season_number, mergeSeasons(existing, season, a.root_id, b.root_id));
|
||||
seasonMap.set(season.season_number, mergeSeasons(existing, season, a.root_id, b.root_id))
|
||||
} else {
|
||||
seasonMap.set(season.season_number, {
|
||||
...season,
|
||||
episodes: season.episodes.map(ep => ({ ...ep, torrents: annotateTorrents(ep.torrents, b.root_id) })),
|
||||
});
|
||||
episodes: season.episodes.map((ep) => ({
|
||||
...ep,
|
||||
torrents: annotateTorrents(ep.torrents, b.root_id),
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
return {
|
||||
@@ -139,44 +175,41 @@ export function useMediaWebSocket() {
|
||||
info: a.info || b.info,
|
||||
cover_path: a.cover_path || b.cover_path,
|
||||
backdrop_path: a.backdrop_path || b.backdrop_path,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function mergeItemsByHash<T extends Movie | Series>(
|
||||
items: T[],
|
||||
mergeFn: (a: T, b: T) => T
|
||||
): T[] {
|
||||
const map = new Map<string, T[]>();
|
||||
function mergeItemsByHash<T extends Movie | Series>(items: T[], mergeFn: (a: T, b: T) => T): T[] {
|
||||
const map = new Map<string, T[]>()
|
||||
for (const item of items) {
|
||||
const hash = getContentHash(item.id);
|
||||
const arr = map.get(hash) || [];
|
||||
arr.push(item);
|
||||
map.set(hash, arr);
|
||||
const hash = getContentHash(item.id)
|
||||
const arr = map.get(hash) || []
|
||||
arr.push(item)
|
||||
map.set(hash, arr)
|
||||
}
|
||||
const merged: T[] = [];
|
||||
const merged: T[] = []
|
||||
for (const [, group] of map) {
|
||||
if (group.length === 1) {
|
||||
merged.push(group[0]);
|
||||
merged.push(group[0])
|
||||
} else {
|
||||
let result = group[0];
|
||||
let result = group[0]
|
||||
for (let i = 1; i < group.length; i++) {
|
||||
result = mergeFn(result, group[i]);
|
||||
result = mergeFn(result, group[i])
|
||||
}
|
||||
merged.push(result);
|
||||
merged.push(result)
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
return merged
|
||||
}
|
||||
|
||||
function buildIndex(): MediaIndex {
|
||||
const movies: Movie[] = [];
|
||||
const series: Series[] = [];
|
||||
const movies: Movie[] = []
|
||||
const series: Series[] = []
|
||||
for (const state of roots.value.values()) {
|
||||
movies.push(...state.movieMap.values());
|
||||
series.push(...state.seriesMap.values());
|
||||
movies.push(...state.movieMap.values())
|
||||
series.push(...state.seriesMap.values())
|
||||
}
|
||||
const mergedMovies = mergeItemsByHash(movies, mergeMovies);
|
||||
const mergedSeries = mergeItemsByHash(series, mergeSeries);
|
||||
const mergedMovies = mergeItemsByHash(movies, mergeMovies)
|
||||
const mergedSeries = mergeItemsByHash(series, mergeSeries)
|
||||
return {
|
||||
version: 0,
|
||||
generated_at: new Date().toISOString(),
|
||||
@@ -186,101 +219,103 @@ export function useMediaWebSocket() {
|
||||
},
|
||||
movies: mergedMovies,
|
||||
series: mergedSeries,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function updateMergedState() {
|
||||
mediaIndex.value = buildIndex();
|
||||
mediaIndex.value = buildIndex()
|
||||
// Loading is done when at least one root has connected and sent init
|
||||
let anyConnected = false;
|
||||
let anyConnected = false
|
||||
for (const state of roots.value.values()) {
|
||||
if (state.connected) {
|
||||
anyConnected = true;
|
||||
break;
|
||||
anyConnected = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (anyConnected) {
|
||||
loading.value = false;
|
||||
error.value = null;
|
||||
loading.value = false
|
||||
error.value = null
|
||||
}
|
||||
connected.value = anyConnected;
|
||||
connected.value = anyConnected
|
||||
}
|
||||
|
||||
function processJson(state: RootState, text: string) {
|
||||
const msg = JSON.parse(text) as WsMessage;
|
||||
const msg = JSON.parse(text) as WsMessage
|
||||
|
||||
switch (msg.type) {
|
||||
case 'init': {
|
||||
state.movieMap.clear();
|
||||
state.seriesMap.clear();
|
||||
for (const m of msg.data.movies) state.movieMap.set(m.id, m);
|
||||
for (const s of msg.data.series) state.seriesMap.set(s.id, s);
|
||||
updateMergedState();
|
||||
console.log(`[WS ${state.rootId}] init: ${state.movieMap.size} movies, ${state.seriesMap.size} series`);
|
||||
break;
|
||||
case "init": {
|
||||
state.movieMap.clear()
|
||||
state.seriesMap.clear()
|
||||
for (const m of msg.data.movies) state.movieMap.set(m.id, m)
|
||||
for (const s of msg.data.series) state.seriesMap.set(s.id, s)
|
||||
updateMergedState()
|
||||
console.log(
|
||||
`[WS ${state.rootId}] init: ${state.movieMap.size} movies, ${state.seriesMap.size} series`,
|
||||
)
|
||||
break
|
||||
}
|
||||
case 'upsert': {
|
||||
if (msg.kind === 'movie') {
|
||||
state.movieMap.set(msg.item.id, msg.item as Movie);
|
||||
case "upsert": {
|
||||
if (msg.kind === "movie") {
|
||||
state.movieMap.set(msg.item.id, msg.item as Movie)
|
||||
} else {
|
||||
state.seriesMap.set(msg.item.id, msg.item as Series);
|
||||
state.seriesMap.set(msg.item.id, msg.item as Series)
|
||||
}
|
||||
updateMergedState();
|
||||
break;
|
||||
updateMergedState()
|
||||
break
|
||||
}
|
||||
case 'remove': {
|
||||
if (msg.kind === 'movie') {
|
||||
state.movieMap.delete(msg.id);
|
||||
case "remove": {
|
||||
if (msg.kind === "movie") {
|
||||
state.movieMap.delete(msg.id)
|
||||
} else {
|
||||
state.seriesMap.delete(msg.id);
|
||||
state.seriesMap.delete(msg.id)
|
||||
}
|
||||
updateMergedState();
|
||||
break;
|
||||
updateMergedState()
|
||||
break
|
||||
}
|
||||
case 'task': {
|
||||
const info = msg.data;
|
||||
if (info.status === 'completed' || info.status === 'cancelled' || info.status === 'error') {
|
||||
tasks.value.set(info.id, info);
|
||||
case "task": {
|
||||
const info = msg.data
|
||||
if (info.status === "completed" || info.status === "cancelled" || info.status === "error") {
|
||||
tasks.value.set(info.id, info)
|
||||
setTimeout(() => {
|
||||
tasks.value.delete(info.id);
|
||||
tasks.value = new Map(tasks.value);
|
||||
}, 3000);
|
||||
tasks.value.delete(info.id)
|
||||
tasks.value = new Map(tasks.value)
|
||||
}, 3000)
|
||||
} else {
|
||||
tasks.value.set(info.id, info);
|
||||
tasks.value.set(info.id, info)
|
||||
}
|
||||
tasks.value = new Map(tasks.value);
|
||||
break;
|
||||
tasks.value = new Map(tasks.value)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessage(state: RootState, event: MessageEvent) {
|
||||
try {
|
||||
let text: string;
|
||||
let text: string
|
||||
if (event.data instanceof Blob) {
|
||||
event.data.text().then((t) => processJson(state, t));
|
||||
return;
|
||||
event.data.text().then((t) => processJson(state, t))
|
||||
return
|
||||
} else if (event.data instanceof ArrayBuffer) {
|
||||
text = new TextDecoder().decode(event.data);
|
||||
text = new TextDecoder().decode(event.data)
|
||||
} else {
|
||||
text = event.data as string;
|
||||
text = event.data as string
|
||||
}
|
||||
processJson(state, text);
|
||||
processJson(state, text)
|
||||
} catch (e) {
|
||||
console.error(`[WS ${state.rootId}] Failed to handle message:`, e);
|
||||
console.error(`[WS ${state.rootId}] Failed to handle message:`, e)
|
||||
}
|
||||
}
|
||||
|
||||
function connectRoot(rootId: string) {
|
||||
if (disposed) return;
|
||||
const existing = roots.value.get(rootId);
|
||||
if (disposed) return
|
||||
const existing = roots.value.get(rootId)
|
||||
if (existing?.ws) {
|
||||
// Already connecting or connected
|
||||
return;
|
||||
return
|
||||
}
|
||||
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const url = `${proto}//${location.host}/api/roots/${encodeURIComponent(rootId)}/ws`;
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:"
|
||||
const url = `${proto}//${location.host}/api/roots/${encodeURIComponent(rootId)}/ws`
|
||||
|
||||
const state: RootState = {
|
||||
rootId,
|
||||
@@ -289,103 +324,103 @@ export function useMediaWebSocket() {
|
||||
seriesMap: new Map(),
|
||||
connected: false,
|
||||
reconnectTimer: null,
|
||||
};
|
||||
roots.value.set(rootId, state);
|
||||
}
|
||||
roots.value.set(rootId, state)
|
||||
|
||||
function doConnect() {
|
||||
if (disposed) return;
|
||||
console.log(`[WS ${rootId}] Connecting to ${url}...`);
|
||||
const ws = new WebSocket(url);
|
||||
state.ws = ws;
|
||||
if (disposed) return
|
||||
console.log(`[WS ${rootId}] Connecting to ${url}...`)
|
||||
const ws = new WebSocket(url)
|
||||
state.ws = ws
|
||||
|
||||
ws.onopen = () => {
|
||||
state.connected = true;
|
||||
updateMergedState();
|
||||
console.log(`[WS ${rootId}] Connected`);
|
||||
};
|
||||
state.connected = true
|
||||
updateMergedState()
|
||||
console.log(`[WS ${rootId}] Connected`)
|
||||
}
|
||||
|
||||
ws.onmessage = (ev) => handleMessage(state, ev);
|
||||
ws.onmessage = (ev) => handleMessage(state, ev)
|
||||
|
||||
ws.onclose = (ev) => {
|
||||
state.connected = false;
|
||||
state.ws = null;
|
||||
updateMergedState();
|
||||
console.log(`[WS ${rootId}] Closed (code=${ev.code})`);
|
||||
scheduleReconnect();
|
||||
};
|
||||
state.connected = false
|
||||
state.ws = null
|
||||
updateMergedState()
|
||||
console.log(`[WS ${rootId}] Closed (code=${ev.code})`)
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
ws.onerror = (ev) => {
|
||||
console.error(`[WS ${rootId}] Error:`, ev);
|
||||
console.error(`[WS ${rootId}] Error:`, ev)
|
||||
if (!mediaIndex.value) {
|
||||
error.value = 'WebSocket connection failed';
|
||||
error.value = "WebSocket connection failed"
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (disposed) return;
|
||||
if (state.reconnectTimer) clearTimeout(state.reconnectTimer);
|
||||
if (disposed) return
|
||||
if (state.reconnectTimer) clearTimeout(state.reconnectTimer)
|
||||
state.reconnectTimer = setTimeout(() => {
|
||||
console.log(`[WS ${rootId}] Reconnecting...`);
|
||||
doConnect();
|
||||
}, 2000);
|
||||
console.log(`[WS ${rootId}] Reconnecting...`)
|
||||
doConnect()
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
doConnect();
|
||||
doConnect()
|
||||
}
|
||||
|
||||
function disconnectRoot(rootId: string) {
|
||||
const state = roots.value.get(rootId);
|
||||
if (!state) return;
|
||||
const state = roots.value.get(rootId)
|
||||
if (!state) return
|
||||
if (state.reconnectTimer) {
|
||||
clearTimeout(state.reconnectTimer);
|
||||
state.reconnectTimer = null;
|
||||
clearTimeout(state.reconnectTimer)
|
||||
state.reconnectTimer = null
|
||||
}
|
||||
if (state.ws) {
|
||||
state.ws.onclose = null;
|
||||
state.ws.close();
|
||||
state.ws = null;
|
||||
state.ws.onclose = null
|
||||
state.ws.close()
|
||||
state.ws = null
|
||||
}
|
||||
state.connected = false;
|
||||
roots.value.delete(rootId);
|
||||
updateMergedState();
|
||||
state.connected = false
|
||||
roots.value.delete(rootId)
|
||||
updateMergedState()
|
||||
}
|
||||
|
||||
function setActiveRoots(rootIds: string[]) {
|
||||
if (disposed) return;
|
||||
const desired = new Set(rootIds);
|
||||
const current = new Set(roots.value.keys());
|
||||
if (disposed) return
|
||||
const desired = new Set(rootIds)
|
||||
const current = new Set(roots.value.keys())
|
||||
|
||||
// Add new roots
|
||||
for (const rid of desired) {
|
||||
if (!current.has(rid)) {
|
||||
connectRoot(rid);
|
||||
connectRoot(rid)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove old roots
|
||||
for (const rid of current) {
|
||||
if (!desired.has(rid)) {
|
||||
disconnectRoot(rid);
|
||||
disconnectRoot(rid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
disposed = true;
|
||||
disposed = true
|
||||
for (const state of roots.value.values()) {
|
||||
if (state.reconnectTimer) {
|
||||
clearTimeout(state.reconnectTimer);
|
||||
clearTimeout(state.reconnectTimer)
|
||||
}
|
||||
if (state.ws) {
|
||||
state.ws.onclose = null;
|
||||
state.ws.close();
|
||||
state.ws.onclose = null
|
||||
state.ws.close()
|
||||
}
|
||||
}
|
||||
roots.value.clear();
|
||||
roots.value.clear()
|
||||
}
|
||||
|
||||
onUnmounted(disconnect);
|
||||
onUnmounted(disconnect)
|
||||
|
||||
return {
|
||||
mediaIndex,
|
||||
@@ -395,5 +430,5 @@ export function useMediaWebSocket() {
|
||||
tasks: readonly(tasks),
|
||||
setActiveRoots,
|
||||
disconnect,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+14
-14
@@ -1,10 +1,10 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './styles/main.css'
|
||||
import { installKeyboardNavigation } from './composables/useKeyboardNavigation'
|
||||
import { installGamepadNavigation } from './composables/useGamepadNavigation'
|
||||
import { installInputModalityTracking } from './composables/useInputModality'
|
||||
import { createApp } from "vue"
|
||||
import App from "./App.vue"
|
||||
import router from "./router"
|
||||
import "./styles/main.css"
|
||||
import { installKeyboardNavigation } from "./composables/useKeyboardNavigation"
|
||||
import { installGamepadNavigation } from "./composables/useGamepadNavigation"
|
||||
import { installInputModalityTracking } from "./composables/useInputModality"
|
||||
|
||||
// Install global keyboard navigation handlers immediately
|
||||
installInputModalityTracking()
|
||||
@@ -12,12 +12,12 @@ installKeyboardNavigation()
|
||||
installGamepadNavigation()
|
||||
|
||||
// Unregister any legacy service workers — MediaHive no longer uses a PWA/SW.
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.getRegistrations().then((registrations) => {
|
||||
for (const registration of registrations) {
|
||||
registration.unregister()
|
||||
}
|
||||
})
|
||||
if ("serviceWorker" in navigator) {
|
||||
navigator.serviceWorker.getRegistrations().then((registrations) => {
|
||||
for (const registration of registrations) {
|
||||
registration.unregister()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
createApp(App).use(router).mount('#app')
|
||||
createApp(App).use(router).mount("#app")
|
||||
|
||||
+22
-22
@@ -1,49 +1,49 @@
|
||||
import { createRouter, createWebHashHistory } from 'vue-router';
|
||||
import { defineComponent, h } from 'vue';
|
||||
import { createRouter, createWebHashHistory } from "vue-router"
|
||||
import { defineComponent, h } from "vue"
|
||||
|
||||
// Empty component - App.vue handles all rendering based on route meta
|
||||
const EmptyRouteComponent = defineComponent({
|
||||
render() {
|
||||
return h('div');
|
||||
}
|
||||
});
|
||||
return h("div")
|
||||
},
|
||||
})
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
scrollBehavior() {
|
||||
// Always scroll to top on navigation
|
||||
return { top: 0 };
|
||||
return { top: 0 }
|
||||
},
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
redirect: '/movies',
|
||||
path: "/",
|
||||
redirect: "/movies",
|
||||
},
|
||||
{
|
||||
path: '/movies',
|
||||
name: 'movies',
|
||||
path: "/movies",
|
||||
name: "movies",
|
||||
component: EmptyRouteComponent,
|
||||
meta: { view: 'movies' },
|
||||
meta: { view: "movies" },
|
||||
},
|
||||
{
|
||||
path: '/movies/:id',
|
||||
name: 'movie-detail',
|
||||
path: "/movies/:id",
|
||||
name: "movie-detail",
|
||||
component: EmptyRouteComponent,
|
||||
meta: { view: 'movies' },
|
||||
meta: { view: "movies" },
|
||||
},
|
||||
{
|
||||
path: '/series',
|
||||
name: 'series',
|
||||
path: "/series",
|
||||
name: "series",
|
||||
component: EmptyRouteComponent,
|
||||
meta: { view: 'series' },
|
||||
meta: { view: "series" },
|
||||
},
|
||||
{
|
||||
path: '/series/:id',
|
||||
name: 'series-detail',
|
||||
path: "/series/:id",
|
||||
name: "series-detail",
|
||||
component: EmptyRouteComponent,
|
||||
meta: { view: 'series' },
|
||||
meta: { view: "series" },
|
||||
},
|
||||
],
|
||||
});
|
||||
})
|
||||
|
||||
export default router;
|
||||
export default router
|
||||
|
||||
@@ -27,8 +27,9 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html, body {
|
||||
font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
|
||||
html,
|
||||
body {
|
||||
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
min-height: 100vh;
|
||||
@@ -92,7 +93,7 @@ html.mouse-active ::-webkit-scrollbar-thumb:hover {
|
||||
}
|
||||
|
||||
.header::before {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
@@ -132,11 +133,7 @@ html.mouse-active ::-webkit-scrollbar-thumb:hover {
|
||||
width: 30em;
|
||||
max-width: calc(100vw - 24px);
|
||||
opacity: 1;
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
rgba(5, 7, 10, 0.72) 0%,
|
||||
rgba(5, 7, 10, 0.5) 100%
|
||||
);
|
||||
background: linear-gradient(to bottom, rgba(5, 7, 10, 0.72) 0%, rgba(5, 7, 10, 0.5) 100%);
|
||||
backdrop-filter: blur(10px) saturate(115%);
|
||||
-webkit-backdrop-filter: blur(10px) saturate(115%);
|
||||
}
|
||||
@@ -276,12 +273,22 @@ html.mouse-active .header-settings-btn:hover {
|
||||
background-size: contain;
|
||||
background-position: right top;
|
||||
background-repeat: no-repeat;
|
||||
mask-image: linear-gradient(to left, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 60%, transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.3) 60%, transparent 100%);
|
||||
mask-image: linear-gradient(
|
||||
to left,
|
||||
rgba(0, 0, 0, 0.6) 0%,
|
||||
rgba(0, 0, 0, 0.3) 60%,
|
||||
transparent 100%
|
||||
);
|
||||
-webkit-mask-image: linear-gradient(
|
||||
to left,
|
||||
rgba(0, 0, 0, 0.6) 0%,
|
||||
rgba(0, 0, 0, 0.3) 60%,
|
||||
transparent 100%
|
||||
);
|
||||
}
|
||||
|
||||
.hero::after {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
@@ -331,7 +338,8 @@ html.mouse-active .header-settings-btn:hover {
|
||||
|
||||
/* Blinking animation for button focus */
|
||||
@keyframes btn-outline-blink {
|
||||
0%, 100% {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
50% {
|
||||
@@ -395,11 +403,15 @@ html:not(.mouse-active) .btn-secondary.nav-focused {
|
||||
}
|
||||
|
||||
.view-zoom-enter-active {
|
||||
transition: opacity 0.4s ease-out, transform 0.4s ease-out;
|
||||
transition:
|
||||
opacity 0.4s ease-out,
|
||||
transform 0.4s ease-out;
|
||||
}
|
||||
|
||||
.view-zoom-leave-active {
|
||||
transition: opacity 0.3s ease-in, transform 0.3s ease-in;
|
||||
transition:
|
||||
opacity 0.3s ease-in,
|
||||
transform 0.3s ease-in;
|
||||
}
|
||||
|
||||
.view-zoom-enter-from {
|
||||
@@ -456,7 +468,9 @@ html:not(.mouse-active) .btn-secondary.nav-focused {
|
||||
flex-shrink: 0;
|
||||
width: var(--card-width);
|
||||
cursor: pointer;
|
||||
transition: z-index 0s, box-shadow var(--transition-medium);
|
||||
transition:
|
||||
z-index 0s,
|
||||
box-shadow var(--transition-medium);
|
||||
position: relative;
|
||||
outline: none;
|
||||
}
|
||||
@@ -606,7 +620,7 @@ html.mouse-active .media-card:hover .media-card-info {
|
||||
}
|
||||
|
||||
.modal-header::after {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
|
||||
+132
-132
@@ -1,205 +1,205 @@
|
||||
// Type definitions for the media browser
|
||||
|
||||
export type CastGender = 'female' | 'male' | 'non_binary' | 'unknown';
|
||||
export type CastGender = "female" | "male" | "non_binary" | "unknown"
|
||||
|
||||
export interface CastMember {
|
||||
name: string;
|
||||
character?: string | null;
|
||||
profile_path: string | null;
|
||||
gender?: CastGender | null;
|
||||
name: string
|
||||
character?: string | null
|
||||
profile_path: string | null
|
||||
gender?: CastGender | null
|
||||
}
|
||||
|
||||
export interface SimilarMedia {
|
||||
id: number;
|
||||
title: string;
|
||||
poster_path: string | null;
|
||||
id: number
|
||||
title: string
|
||||
poster_path: string | null
|
||||
}
|
||||
|
||||
export interface Info {
|
||||
tmdb_id: number;
|
||||
title: string | null;
|
||||
original_title: string | null;
|
||||
alternative_titles: string[] | null;
|
||||
rating: number | null;
|
||||
vote_count: number | null;
|
||||
overview: string | null;
|
||||
genres: string[] | null;
|
||||
release_date: string | null;
|
||||
runtime: number | null;
|
||||
status: string | null;
|
||||
tagline: string | null;
|
||||
poster_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
similar: SimilarMedia[] | null;
|
||||
keywords: string[] | null;
|
||||
cast: CastMember[] | null;
|
||||
director: string | null;
|
||||
creators: string[] | null;
|
||||
number_of_seasons: number | null;
|
||||
number_of_episodes: number | null;
|
||||
networks: string[] | null;
|
||||
tmdb_id: number
|
||||
title: string | null
|
||||
original_title: string | null
|
||||
alternative_titles: string[] | null
|
||||
rating: number | null
|
||||
vote_count: number | null
|
||||
overview: string | null
|
||||
genres: string[] | null
|
||||
release_date: string | null
|
||||
runtime: number | null
|
||||
status: string | null
|
||||
tagline: string | null
|
||||
poster_path: string | null
|
||||
backdrop_path: string | null
|
||||
similar: SimilarMedia[] | null
|
||||
keywords: string[] | null
|
||||
cast: CastMember[] | null
|
||||
director: string | null
|
||||
creators: string[] | null
|
||||
number_of_seasons: number | null
|
||||
number_of_episodes: number | null
|
||||
networks: string[] | null
|
||||
}
|
||||
|
||||
export interface Torrent {
|
||||
title: string | null;
|
||||
playable_file: string | null;
|
||||
resolution: string | null;
|
||||
quality: string | null;
|
||||
network: string | null;
|
||||
codec: string | null;
|
||||
audio: string | null;
|
||||
audio_languages: string[] | null;
|
||||
subtitle_languages: string[] | null;
|
||||
is_hdr: boolean;
|
||||
has_dolby_vision: boolean;
|
||||
has_dolby_atmos: boolean;
|
||||
encoder: string | null;
|
||||
size: number | null;
|
||||
added_at: number | null;
|
||||
root_id?: string | null;
|
||||
title: string | null
|
||||
playable_file: string | null
|
||||
resolution: string | null
|
||||
quality: string | null
|
||||
network: string | null
|
||||
codec: string | null
|
||||
audio: string | null
|
||||
audio_languages: string[] | null
|
||||
subtitle_languages: string[] | null
|
||||
is_hdr: boolean
|
||||
has_dolby_vision: boolean
|
||||
has_dolby_atmos: boolean
|
||||
encoder: string | null
|
||||
size: number | null
|
||||
added_at: number | null
|
||||
root_id?: string | null
|
||||
}
|
||||
|
||||
export interface Movie {
|
||||
id: string;
|
||||
title: string | null;
|
||||
info: Info | null;
|
||||
year: number | null;
|
||||
newest: number | null;
|
||||
cover_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
showreel_images: string[] | null;
|
||||
showreel_source_sets: string[][] | null;
|
||||
torrents: { [key: string]: Torrent };
|
||||
root_id: string | null;
|
||||
id: string
|
||||
title: string | null
|
||||
info: Info | null
|
||||
year: number | null
|
||||
newest: number | null
|
||||
cover_path: string | null
|
||||
backdrop_path: string | null
|
||||
showreel_images: string[] | null
|
||||
showreel_source_sets: string[][] | null
|
||||
torrents: { [key: string]: Torrent }
|
||||
root_id: string | null
|
||||
}
|
||||
|
||||
export interface Episode {
|
||||
episode_number: number;
|
||||
name: string | null;
|
||||
overview: string | null;
|
||||
air_date: string | null;
|
||||
runtime: number | null;
|
||||
still_path: string | null;
|
||||
rating: number | null;
|
||||
director: string | null;
|
||||
reel_image: string | null;
|
||||
reel_sources: string[] | null;
|
||||
torrents: { [key: string]: Torrent };
|
||||
episode_number: number
|
||||
name: string | null
|
||||
overview: string | null
|
||||
air_date: string | null
|
||||
runtime: number | null
|
||||
still_path: string | null
|
||||
rating: number | null
|
||||
director: string | null
|
||||
reel_image: string | null
|
||||
reel_sources: string[] | null
|
||||
torrents: { [key: string]: Torrent }
|
||||
}
|
||||
|
||||
export interface Season {
|
||||
season_number: number;
|
||||
name: string | null;
|
||||
overview: string | null;
|
||||
air_date: string | null;
|
||||
poster_path: string | null;
|
||||
episode_count: number | null;
|
||||
episodes: Episode[];
|
||||
season_number: number
|
||||
name: string | null
|
||||
overview: string | null
|
||||
air_date: string | null
|
||||
poster_path: string | null
|
||||
episode_count: number | null
|
||||
episodes: Episode[]
|
||||
}
|
||||
|
||||
export interface Series {
|
||||
id: string;
|
||||
title: string | null;
|
||||
info: Info | null;
|
||||
alternative_titles: string[] | null;
|
||||
newest: number | null;
|
||||
cover_path: string | null;
|
||||
backdrop_path: string | null;
|
||||
seasons: Season[];
|
||||
root_id: string | null;
|
||||
id: string
|
||||
title: string | null
|
||||
info: Info | null
|
||||
alternative_titles: string[] | null
|
||||
newest: number | null
|
||||
cover_path: string | null
|
||||
backdrop_path: string | null
|
||||
seasons: Season[]
|
||||
root_id: string | null
|
||||
}
|
||||
|
||||
export interface MediaStats {
|
||||
total_movies: number;
|
||||
total_movie_versions?: number;
|
||||
total_series: number;
|
||||
total_series_episodes?: number;
|
||||
total_movies: number
|
||||
total_movie_versions?: number
|
||||
total_series: number
|
||||
total_series_episodes?: number
|
||||
}
|
||||
|
||||
export interface MediaIndex {
|
||||
version: number;
|
||||
generated_at: string;
|
||||
stats: MediaStats;
|
||||
movies: Movie[];
|
||||
series: Series[];
|
||||
version: number
|
||||
generated_at: string
|
||||
stats: MediaStats
|
||||
movies: Movie[]
|
||||
series: Series[]
|
||||
}
|
||||
|
||||
export type MediaType = 'movies' | 'series' | 'episode';
|
||||
export type MediaType = "movies" | "series" | "episode"
|
||||
|
||||
// Matched person info for search results
|
||||
export interface MatchedPerson {
|
||||
name: string;
|
||||
roles: string; // e.g., "Director", "Tony Stark", "Creator"
|
||||
highlightRoles: boolean; // true if the roles/character matched (vs the name)
|
||||
name: string
|
||||
roles: string // e.g., "Director", "Tony Stark", "Creator"
|
||||
highlightRoles: boolean // true if the roles/character matched (vs the name)
|
||||
}
|
||||
|
||||
// Matched episode info for search results
|
||||
export interface MatchedEpisode {
|
||||
name: string; // Episode name (highlighted)
|
||||
location: string; // "SN Episode M" (dimmed)
|
||||
seasonNumber: number; // For navigation to episode
|
||||
episodeNumber: number; // For navigation to episode
|
||||
name: string // Episode name (highlighted)
|
||||
location: string // "SN Episode M" (dimmed)
|
||||
seasonNumber: number // For navigation to episode
|
||||
episodeNumber: number // For navigation to episode
|
||||
}
|
||||
|
||||
// Info about why a search matched this item
|
||||
export interface SearchMatchInfo {
|
||||
// Matched people with their roles/characters
|
||||
matchedPeople?: MatchedPerson[];
|
||||
matchedPeople?: MatchedPerson[]
|
||||
// Matched episodes for series
|
||||
matchedEpisodes?: MatchedEpisode[];
|
||||
matchedEpisodes?: MatchedEpisode[]
|
||||
}
|
||||
|
||||
export interface MediaItem {
|
||||
id: string;
|
||||
title: string | null;
|
||||
year?: number | null;
|
||||
cover_path: string | null;
|
||||
showreel_images?: string[] | null;
|
||||
showreel_source_sets?: string[][] | null;
|
||||
type: MediaType;
|
||||
resolution?: string | null;
|
||||
data: Movie | Series | EpisodeWithSeries;
|
||||
root_id: string | null;
|
||||
id: string
|
||||
title: string | null
|
||||
year?: number | null
|
||||
cover_path: string | null
|
||||
showreel_images?: string[] | null
|
||||
showreel_source_sets?: string[][] | null
|
||||
type: MediaType
|
||||
resolution?: string | null
|
||||
data: Movie | Series | EpisodeWithSeries
|
||||
root_id: string | null
|
||||
// Optional search match info - only present in search results
|
||||
searchMatchInfo?: SearchMatchInfo;
|
||||
searchMatchInfo?: SearchMatchInfo
|
||||
}
|
||||
|
||||
// Episode with parent series info for standalone display
|
||||
export interface EpisodeWithSeries {
|
||||
episode: Episode;
|
||||
series: Series;
|
||||
seasonNumber: number;
|
||||
episode: Episode
|
||||
series: Series
|
||||
seasonNumber: number
|
||||
}
|
||||
|
||||
// Task progress info from background scanning
|
||||
export interface TaskInfo {
|
||||
id: string;
|
||||
status: string;
|
||||
progress: number;
|
||||
detail: string;
|
||||
id: string
|
||||
status: string
|
||||
progress: number
|
||||
detail: string
|
||||
}
|
||||
|
||||
// WebSocket message types (matching server msgspec tagged structs)
|
||||
export interface WsInitMessage {
|
||||
type: 'init';
|
||||
data: { movies: Movie[]; series: Series[] };
|
||||
type: "init"
|
||||
data: { movies: Movie[]; series: Series[] }
|
||||
}
|
||||
|
||||
export interface WsUpsertMessage {
|
||||
type: 'upsert';
|
||||
kind: 'movie' | 'series';
|
||||
item: Movie | Series;
|
||||
type: "upsert"
|
||||
kind: "movie" | "series"
|
||||
item: Movie | Series
|
||||
}
|
||||
|
||||
export interface WsRemoveMessage {
|
||||
type: 'remove';
|
||||
kind: 'movie' | 'series';
|
||||
id: string;
|
||||
type: "remove"
|
||||
kind: "movie" | "series"
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface WsTaskMessage {
|
||||
type: 'task';
|
||||
data: TaskInfo;
|
||||
type: "task"
|
||||
data: TaskInfo
|
||||
}
|
||||
|
||||
export type WsMessage = WsInitMessage | WsUpsertMessage | WsRemoveMessage | WsTaskMessage;
|
||||
export type WsMessage = WsInitMessage | WsUpsertMessage | WsRemoveMessage | WsTaskMessage
|
||||
|
||||
+309
-313
@@ -1,331 +1,327 @@
|
||||
import * as flagSvgs from 'country-flag-icons/string/3x2';
|
||||
import * as flagSvgs from "country-flag-icons/string/3x2"
|
||||
|
||||
export interface LanguageFlagEntry {
|
||||
countryCode: string;
|
||||
svg: string;
|
||||
sourceCodes: string[];
|
||||
countryCode: string
|
||||
svg: string
|
||||
sourceCodes: string[]
|
||||
}
|
||||
|
||||
const FLAGS = flagSvgs as Record<string, string>;
|
||||
const FLAGS = flagSvgs as Record<string, string>
|
||||
|
||||
const LANGUAGE_TO_COUNTRY: Record<string, string> = {
|
||||
// English
|
||||
en: 'GB',
|
||||
eng: 'GB',
|
||||
en: "GB",
|
||||
eng: "GB",
|
||||
|
||||
// Spanish (including LATAM variants collapsed to Spain flag)
|
||||
es: 'ES',
|
||||
spa: 'ES',
|
||||
esl: 'ES',
|
||||
spl: 'ES',
|
||||
'es-es': 'ES',
|
||||
'es-419': 'ES',
|
||||
'spa-la': 'ES',
|
||||
es: "ES",
|
||||
spa: "ES",
|
||||
esl: "ES",
|
||||
spl: "ES",
|
||||
"es-es": "ES",
|
||||
"es-419": "ES",
|
||||
"spa-la": "ES",
|
||||
|
||||
// Portuguese
|
||||
pt: 'PT',
|
||||
por: 'PT',
|
||||
'pt-pt': 'PT',
|
||||
'pt-br': 'BR',
|
||||
pt: "PT",
|
||||
por: "PT",
|
||||
"pt-pt": "PT",
|
||||
"pt-br": "BR",
|
||||
|
||||
// Major European languages
|
||||
fr: 'FR',
|
||||
fra: 'FR',
|
||||
fre: 'FR',
|
||||
de: 'DE',
|
||||
deu: 'DE',
|
||||
ger: 'DE',
|
||||
it: 'IT',
|
||||
ita: 'IT',
|
||||
nl: 'NL',
|
||||
nld: 'NL',
|
||||
dut: 'NL',
|
||||
sv: 'SE',
|
||||
swe: 'SE',
|
||||
no: 'NO',
|
||||
nor: 'NO',
|
||||
da: 'DK',
|
||||
dan: 'DK',
|
||||
fi: 'FI',
|
||||
fin: 'FI',
|
||||
pl: 'PL',
|
||||
पोल: 'PL',
|
||||
cs: 'CZ',
|
||||
ces: 'CZ',
|
||||
cze: 'CZ',
|
||||
hu: 'HU',
|
||||
hun: 'HU',
|
||||
ro: 'RO',
|
||||
ron: 'RO',
|
||||
rum: 'RO',
|
||||
el: 'GR',
|
||||
gre: 'GR',
|
||||
ell: 'GR',
|
||||
tr: 'TR',
|
||||
tur: 'TR',
|
||||
fr: "FR",
|
||||
fra: "FR",
|
||||
fre: "FR",
|
||||
de: "DE",
|
||||
deu: "DE",
|
||||
ger: "DE",
|
||||
it: "IT",
|
||||
ita: "IT",
|
||||
nl: "NL",
|
||||
nld: "NL",
|
||||
dut: "NL",
|
||||
sv: "SE",
|
||||
swe: "SE",
|
||||
no: "NO",
|
||||
nor: "NO",
|
||||
da: "DK",
|
||||
dan: "DK",
|
||||
fi: "FI",
|
||||
fin: "FI",
|
||||
pl: "PL",
|
||||
पोल: "PL",
|
||||
cs: "CZ",
|
||||
ces: "CZ",
|
||||
cze: "CZ",
|
||||
hu: "HU",
|
||||
hun: "HU",
|
||||
ro: "RO",
|
||||
ron: "RO",
|
||||
rum: "RO",
|
||||
el: "GR",
|
||||
gre: "GR",
|
||||
ell: "GR",
|
||||
tr: "TR",
|
||||
tur: "TR",
|
||||
|
||||
// Slavic / Eurasian
|
||||
ru: 'RU',
|
||||
rus: 'RU',
|
||||
uk: 'UA',
|
||||
ukr: 'UA',
|
||||
bg: 'BG',
|
||||
bul: 'BG',
|
||||
sr: 'RS',
|
||||
srp: 'RS',
|
||||
hr: 'HR',
|
||||
hrv: 'HR',
|
||||
sl: 'SI',
|
||||
slv: 'SI',
|
||||
sk: 'SK',
|
||||
slk: 'SK',
|
||||
slo: 'SK',
|
||||
ru: "RU",
|
||||
rus: "RU",
|
||||
uk: "UA",
|
||||
ukr: "UA",
|
||||
bg: "BG",
|
||||
bul: "BG",
|
||||
sr: "RS",
|
||||
srp: "RS",
|
||||
hr: "HR",
|
||||
hrv: "HR",
|
||||
sl: "SI",
|
||||
slv: "SI",
|
||||
sk: "SK",
|
||||
slk: "SK",
|
||||
slo: "SK",
|
||||
|
||||
// East / South / SE Asia
|
||||
ja: 'JP',
|
||||
jpn: 'JP',
|
||||
ko: 'KR',
|
||||
kor: 'KR',
|
||||
zh: 'CN',
|
||||
zho: 'CN',
|
||||
chi: 'CN',
|
||||
yue: 'HK',
|
||||
th: 'TH',
|
||||
tha: 'TH',
|
||||
vi: 'VN',
|
||||
vie: 'VN',
|
||||
id: 'ID',
|
||||
ind: 'ID',
|
||||
ms: 'MY',
|
||||
msa: 'MY',
|
||||
may: 'MY',
|
||||
hi: 'IN',
|
||||
hin: 'IN',
|
||||
ja: "JP",
|
||||
jpn: "JP",
|
||||
ko: "KR",
|
||||
kor: "KR",
|
||||
zh: "CN",
|
||||
zho: "CN",
|
||||
chi: "CN",
|
||||
yue: "HK",
|
||||
th: "TH",
|
||||
tha: "TH",
|
||||
vi: "VN",
|
||||
vie: "VN",
|
||||
id: "ID",
|
||||
ind: "ID",
|
||||
ms: "MY",
|
||||
msa: "MY",
|
||||
may: "MY",
|
||||
hi: "IN",
|
||||
hin: "IN",
|
||||
|
||||
// Middle East / Africa
|
||||
ar: 'SA',
|
||||
ara: 'SA',
|
||||
he: 'IL',
|
||||
heb: 'IL',
|
||||
fa: 'IR',
|
||||
fas: 'IR',
|
||||
per: 'IR',
|
||||
ur: 'PK',
|
||||
urd: 'PK',
|
||||
sw: 'TZ',
|
||||
swa: 'TZ',
|
||||
ar: "SA",
|
||||
ara: "SA",
|
||||
he: "IL",
|
||||
heb: "IL",
|
||||
fa: "IR",
|
||||
fas: "IR",
|
||||
per: "IR",
|
||||
ur: "PK",
|
||||
urd: "PK",
|
||||
sw: "TZ",
|
||||
swa: "TZ",
|
||||
|
||||
// Other common
|
||||
ca: 'ES',
|
||||
cat: 'ES',
|
||||
eu: 'ES',
|
||||
baq: 'ES',
|
||||
eus: 'ES',
|
||||
};
|
||||
ca: "ES",
|
||||
cat: "ES",
|
||||
eu: "ES",
|
||||
baq: "ES",
|
||||
eus: "ES",
|
||||
}
|
||||
|
||||
function normalizeLanguageCode(code: string): string {
|
||||
return code.trim().toLowerCase().replace('_', '-');
|
||||
return code.trim().toLowerCase().replace("_", "-")
|
||||
}
|
||||
|
||||
function normalizeLanguageName(name: string): string {
|
||||
return name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[_-]+/g, ' ')
|
||||
.replace(/\s+/g, ' ');
|
||||
return name.trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ")
|
||||
}
|
||||
|
||||
let _browserLanguagePreferences: string[] | null = null;
|
||||
let _browserPreferenceRanks: Map<string, number> | null = null;
|
||||
let _browserLanguagePreferences: string[] | null = null
|
||||
let _browserPreferenceRanks: Map<string, number> | null = null
|
||||
|
||||
const LANGUAGE_NAME_TO_CODE: Record<string, string> = {
|
||||
english: 'en',
|
||||
spanish: 'es',
|
||||
portuguese: 'pt',
|
||||
french: 'fr',
|
||||
german: 'de',
|
||||
italian: 'it',
|
||||
dutch: 'nl',
|
||||
swedish: 'sv',
|
||||
norwegian: 'no',
|
||||
danish: 'da',
|
||||
finnish: 'fi',
|
||||
polish: 'pl',
|
||||
czech: 'cs',
|
||||
hungarian: 'hu',
|
||||
romanian: 'ro',
|
||||
greek: 'el',
|
||||
turkish: 'tr',
|
||||
russian: 'ru',
|
||||
ukrainian: 'uk',
|
||||
bulgarian: 'bg',
|
||||
serbian: 'sr',
|
||||
croatian: 'hr',
|
||||
slovenian: 'sl',
|
||||
slovak: 'sk',
|
||||
japanese: 'ja',
|
||||
korean: 'ko',
|
||||
chinese: 'zh',
|
||||
cantonese: 'yue',
|
||||
thai: 'th',
|
||||
vietnamese: 'vi',
|
||||
indonesian: 'id',
|
||||
malay: 'ms',
|
||||
hindi: 'hi',
|
||||
arabic: 'ar',
|
||||
hebrew: 'he',
|
||||
persian: 'fa',
|
||||
urdu: 'ur',
|
||||
swahili: 'sw',
|
||||
catalan: 'ca',
|
||||
basque: 'eu',
|
||||
};
|
||||
english: "en",
|
||||
spanish: "es",
|
||||
portuguese: "pt",
|
||||
french: "fr",
|
||||
german: "de",
|
||||
italian: "it",
|
||||
dutch: "nl",
|
||||
swedish: "sv",
|
||||
norwegian: "no",
|
||||
danish: "da",
|
||||
finnish: "fi",
|
||||
polish: "pl",
|
||||
czech: "cs",
|
||||
hungarian: "hu",
|
||||
romanian: "ro",
|
||||
greek: "el",
|
||||
turkish: "tr",
|
||||
russian: "ru",
|
||||
ukrainian: "uk",
|
||||
bulgarian: "bg",
|
||||
serbian: "sr",
|
||||
croatian: "hr",
|
||||
slovenian: "sl",
|
||||
slovak: "sk",
|
||||
japanese: "ja",
|
||||
korean: "ko",
|
||||
chinese: "zh",
|
||||
cantonese: "yue",
|
||||
thai: "th",
|
||||
vietnamese: "vi",
|
||||
indonesian: "id",
|
||||
malay: "ms",
|
||||
hindi: "hi",
|
||||
arabic: "ar",
|
||||
hebrew: "he",
|
||||
persian: "fa",
|
||||
urdu: "ur",
|
||||
swahili: "sw",
|
||||
catalan: "ca",
|
||||
basque: "eu",
|
||||
}
|
||||
|
||||
function getBrowserLanguagePreferences(): string[] {
|
||||
if (_browserLanguagePreferences) return _browserLanguagePreferences;
|
||||
if (_browserLanguagePreferences) return _browserLanguagePreferences
|
||||
|
||||
const preferences: string[] = [];
|
||||
if (typeof navigator !== 'undefined') {
|
||||
const preferences: string[] = []
|
||||
if (typeof navigator !== "undefined") {
|
||||
if (Array.isArray(navigator.languages)) {
|
||||
for (const lang of navigator.languages) {
|
||||
if (typeof lang === 'string' && lang.trim()) {
|
||||
preferences.push(normalizeLanguageCode(lang));
|
||||
if (typeof lang === "string" && lang.trim()) {
|
||||
preferences.push(normalizeLanguageCode(lang))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof navigator.language === 'string' && navigator.language.trim()) {
|
||||
preferences.push(normalizeLanguageCode(navigator.language));
|
||||
if (typeof navigator.language === "string" && navigator.language.trim()) {
|
||||
preferences.push(normalizeLanguageCode(navigator.language))
|
||||
}
|
||||
}
|
||||
|
||||
const deduped = Array.from(new Set(preferences));
|
||||
_browserLanguagePreferences = deduped;
|
||||
return deduped;
|
||||
const deduped = Array.from(new Set(preferences))
|
||||
_browserLanguagePreferences = deduped
|
||||
return deduped
|
||||
}
|
||||
|
||||
function getBrowserPreferenceRanks(): Map<string, number> {
|
||||
if (_browserPreferenceRanks) return _browserPreferenceRanks;
|
||||
if (_browserPreferenceRanks) return _browserPreferenceRanks
|
||||
|
||||
const preferences = getBrowserLanguagePreferences();
|
||||
const ranks = new Map<string, number>();
|
||||
const display = new Intl.DisplayNames(['en'], { type: 'language' });
|
||||
const preferences = getBrowserLanguagePreferences()
|
||||
const ranks = new Map<string, number>()
|
||||
const display = new Intl.DisplayNames(["en"], { type: "language" })
|
||||
|
||||
for (const [index, pref] of preferences.entries()) {
|
||||
const base = pref.split('-', 1)[0];
|
||||
if (!ranks.has(pref)) ranks.set(pref, index);
|
||||
if (!ranks.has(base)) ranks.set(base, index);
|
||||
const base = pref.split("-", 1)[0]
|
||||
if (!ranks.has(pref)) ranks.set(pref, index)
|
||||
if (!ranks.has(base)) ranks.set(base, index)
|
||||
|
||||
const prefName = display.of(pref);
|
||||
const prefName = display.of(pref)
|
||||
if (prefName) {
|
||||
const key = normalizeLanguageName(prefName);
|
||||
if (!ranks.has(key)) ranks.set(key, index);
|
||||
const key = normalizeLanguageName(prefName)
|
||||
if (!ranks.has(key)) ranks.set(key, index)
|
||||
}
|
||||
const baseName = display.of(base);
|
||||
const baseName = display.of(base)
|
||||
if (baseName) {
|
||||
const key = normalizeLanguageName(baseName);
|
||||
if (!ranks.has(key)) ranks.set(key, index);
|
||||
const key = normalizeLanguageName(baseName)
|
||||
if (!ranks.has(key)) ranks.set(key, index)
|
||||
}
|
||||
}
|
||||
|
||||
_browserPreferenceRanks = ranks;
|
||||
return ranks;
|
||||
_browserPreferenceRanks = ranks
|
||||
return ranks
|
||||
}
|
||||
|
||||
function resolveLanguageIdentifier(value: string): string {
|
||||
const normalized = normalizeLanguageCode(value);
|
||||
const normalized = normalizeLanguageCode(value)
|
||||
if (/^[a-z]{2,3}(?:-[a-z0-9]{2,})?$/i.test(normalized)) {
|
||||
return normalized;
|
||||
return normalized
|
||||
}
|
||||
|
||||
const nameKey = normalizeLanguageName(value);
|
||||
const byName = LANGUAGE_NAME_TO_CODE[nameKey];
|
||||
if (byName) return byName;
|
||||
const nameKey = normalizeLanguageName(value)
|
||||
const byName = LANGUAGE_NAME_TO_CODE[nameKey]
|
||||
if (byName) return byName
|
||||
|
||||
return normalized;
|
||||
return normalized
|
||||
}
|
||||
|
||||
function getPreferenceRank(value: string, preferenceRanks: Map<string, number>): number {
|
||||
const normalized = resolveLanguageIdentifier(value);
|
||||
const exact = preferenceRanks.get(normalized);
|
||||
if (exact !== undefined) return exact;
|
||||
const normalized = resolveLanguageIdentifier(value)
|
||||
const exact = preferenceRanks.get(normalized)
|
||||
if (exact !== undefined) return exact
|
||||
|
||||
const base = normalized.split('-', 1)[0];
|
||||
const baseRank = preferenceRanks.get(base);
|
||||
if (baseRank !== undefined) return baseRank;
|
||||
const base = normalized.split("-", 1)[0]
|
||||
const baseRank = preferenceRanks.get(base)
|
||||
if (baseRank !== undefined) return baseRank
|
||||
|
||||
const nameKey = normalizeLanguageName(toLanguageName(normalized));
|
||||
const nameRank = preferenceRanks.get(nameKey);
|
||||
if (nameRank !== undefined) return nameRank;
|
||||
const nameKey = normalizeLanguageName(toLanguageName(normalized))
|
||||
const nameRank = preferenceRanks.get(nameKey)
|
||||
if (nameRank !== undefined) return nameRank
|
||||
|
||||
const rawNameRank = preferenceRanks.get(normalizeLanguageName(value));
|
||||
if (rawNameRank !== undefined) return rawNameRank;
|
||||
const rawNameRank = preferenceRanks.get(normalizeLanguageName(value))
|
||||
if (rawNameRank !== undefined) return rawNameRank
|
||||
|
||||
return Number.MAX_SAFE_INTEGER;
|
||||
return Number.MAX_SAFE_INTEGER
|
||||
}
|
||||
|
||||
export function mapLanguageToCountry(code: string): string | null {
|
||||
const normalized = resolveLanguageIdentifier(code);
|
||||
const normalized = resolveLanguageIdentifier(code)
|
||||
|
||||
const direct = LANGUAGE_TO_COUNTRY[normalized];
|
||||
if (direct) return direct;
|
||||
const direct = LANGUAGE_TO_COUNTRY[normalized]
|
||||
if (direct) return direct
|
||||
|
||||
// region-tag style code like en-us / pt-br / es-mx
|
||||
const hyphenParts = normalized.split('-');
|
||||
const hyphenParts = normalized.split("-")
|
||||
if (hyphenParts.length >= 2) {
|
||||
const region = hyphenParts[hyphenParts.length - 1];
|
||||
const region = hyphenParts[hyphenParts.length - 1]
|
||||
if (/^[a-z]{2}$/i.test(region)) {
|
||||
return region.toUpperCase();
|
||||
return region.toUpperCase()
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
export function buildLanguageFlags(codes: string[] | null | undefined): {
|
||||
flags: LanguageFlagEntry[];
|
||||
unmappedCodes: string[];
|
||||
flags: LanguageFlagEntry[]
|
||||
unmappedCodes: string[]
|
||||
} {
|
||||
if (!codes || codes.length === 0) {
|
||||
return { flags: [], unmappedCodes: [] };
|
||||
return { flags: [], unmappedCodes: [] }
|
||||
}
|
||||
|
||||
const byCountry = new Map<string, string[]>();
|
||||
const unmapped: string[] = [];
|
||||
const seenUnmapped = new Set<string>();
|
||||
const preferenceRanks = getBrowserPreferenceRanks();
|
||||
const byCountry = new Map<string, string[]>()
|
||||
const unmapped: string[] = []
|
||||
const seenUnmapped = new Set<string>()
|
||||
const preferenceRanks = getBrowserPreferenceRanks()
|
||||
|
||||
const ordered = codes
|
||||
.map((raw, index) => ({ raw, index }))
|
||||
.filter((v) => Boolean(v.raw && String(v.raw).trim()))
|
||||
.sort((a, b) => {
|
||||
const aRank = getPreferenceRank(String(a.raw), preferenceRanks);
|
||||
const bRank = getPreferenceRank(String(b.raw), preferenceRanks);
|
||||
if (aRank !== bRank) return aRank - bRank;
|
||||
return a.index - b.index;
|
||||
});
|
||||
const aRank = getPreferenceRank(String(a.raw), preferenceRanks)
|
||||
const bRank = getPreferenceRank(String(b.raw), preferenceRanks)
|
||||
if (aRank !== bRank) return aRank - bRank
|
||||
return a.index - b.index
|
||||
})
|
||||
|
||||
for (const { raw } of ordered) {
|
||||
if (!raw) continue;
|
||||
const countryCode = mapLanguageToCountry(raw);
|
||||
if (!raw) continue
|
||||
const countryCode = mapLanguageToCountry(raw)
|
||||
if (!countryCode) {
|
||||
const upper = raw.toUpperCase();
|
||||
const upper = raw.toUpperCase()
|
||||
if (!seenUnmapped.has(upper)) {
|
||||
seenUnmapped.add(upper);
|
||||
unmapped.push(upper);
|
||||
seenUnmapped.add(upper)
|
||||
unmapped.push(upper)
|
||||
}
|
||||
continue;
|
||||
continue
|
||||
}
|
||||
if (!FLAGS[countryCode]) {
|
||||
const upper = raw.toUpperCase();
|
||||
const upper = raw.toUpperCase()
|
||||
if (!seenUnmapped.has(upper)) {
|
||||
seenUnmapped.add(upper);
|
||||
unmapped.push(upper);
|
||||
seenUnmapped.add(upper)
|
||||
unmapped.push(upper)
|
||||
}
|
||||
continue;
|
||||
continue
|
||||
}
|
||||
const existing = byCountry.get(countryCode) || [];
|
||||
existing.push(raw);
|
||||
byCountry.set(countryCode, existing);
|
||||
const existing = byCountry.get(countryCode) || []
|
||||
existing.push(raw)
|
||||
byCountry.set(countryCode, existing)
|
||||
}
|
||||
|
||||
const flags: LanguageFlagEntry[] = Array.from(byCountry.entries()).map(
|
||||
@@ -333,114 +329,114 @@ export function buildLanguageFlags(codes: string[] | null | undefined): {
|
||||
countryCode,
|
||||
svg: FLAGS[countryCode],
|
||||
sourceCodes,
|
||||
})
|
||||
);
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
flags,
|
||||
unmappedCodes: unmapped,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const LANGUAGE_NAME_OVERRIDES: Record<string, string> = {
|
||||
eng: 'English',
|
||||
spa: 'Spanish',
|
||||
'spa-la': 'Spanish',
|
||||
esl: 'Spanish',
|
||||
spl: 'Spanish',
|
||||
por: 'Portuguese',
|
||||
fre: 'French',
|
||||
fra: 'French',
|
||||
ger: 'German',
|
||||
deu: 'German',
|
||||
ita: 'Italian',
|
||||
nld: 'Dutch',
|
||||
dut: 'Dutch',
|
||||
swe: 'Swedish',
|
||||
nor: 'Norwegian',
|
||||
dan: 'Danish',
|
||||
fin: 'Finnish',
|
||||
pol: 'Polish',
|
||||
ces: 'Czech',
|
||||
cze: 'Czech',
|
||||
hun: 'Hungarian',
|
||||
ron: 'Romanian',
|
||||
rum: 'Romanian',
|
||||
ell: 'Greek',
|
||||
gre: 'Greek',
|
||||
tur: 'Turkish',
|
||||
rus: 'Russian',
|
||||
ukr: 'Ukrainian',
|
||||
bul: 'Bulgarian',
|
||||
srp: 'Serbian',
|
||||
hrv: 'Croatian',
|
||||
slv: 'Slovenian',
|
||||
slk: 'Slovak',
|
||||
slo: 'Slovak',
|
||||
jpn: 'Japanese',
|
||||
kor: 'Korean',
|
||||
zho: 'Chinese',
|
||||
chi: 'Chinese',
|
||||
yue: 'Cantonese',
|
||||
tha: 'Thai',
|
||||
vie: 'Vietnamese',
|
||||
ind: 'Indonesian',
|
||||
msa: 'Malay',
|
||||
may: 'Malay',
|
||||
hin: 'Hindi',
|
||||
ara: 'Arabic',
|
||||
heb: 'Hebrew',
|
||||
fas: 'Persian',
|
||||
per: 'Persian',
|
||||
urd: 'Urdu',
|
||||
swa: 'Swahili',
|
||||
cat: 'Catalan',
|
||||
eus: 'Basque',
|
||||
baq: 'Basque',
|
||||
};
|
||||
eng: "English",
|
||||
spa: "Spanish",
|
||||
"spa-la": "Spanish",
|
||||
esl: "Spanish",
|
||||
spl: "Spanish",
|
||||
por: "Portuguese",
|
||||
fre: "French",
|
||||
fra: "French",
|
||||
ger: "German",
|
||||
deu: "German",
|
||||
ita: "Italian",
|
||||
nld: "Dutch",
|
||||
dut: "Dutch",
|
||||
swe: "Swedish",
|
||||
nor: "Norwegian",
|
||||
dan: "Danish",
|
||||
fin: "Finnish",
|
||||
pol: "Polish",
|
||||
ces: "Czech",
|
||||
cze: "Czech",
|
||||
hun: "Hungarian",
|
||||
ron: "Romanian",
|
||||
rum: "Romanian",
|
||||
ell: "Greek",
|
||||
gre: "Greek",
|
||||
tur: "Turkish",
|
||||
rus: "Russian",
|
||||
ukr: "Ukrainian",
|
||||
bul: "Bulgarian",
|
||||
srp: "Serbian",
|
||||
hrv: "Croatian",
|
||||
slv: "Slovenian",
|
||||
slk: "Slovak",
|
||||
slo: "Slovak",
|
||||
jpn: "Japanese",
|
||||
kor: "Korean",
|
||||
zho: "Chinese",
|
||||
chi: "Chinese",
|
||||
yue: "Cantonese",
|
||||
tha: "Thai",
|
||||
vie: "Vietnamese",
|
||||
ind: "Indonesian",
|
||||
msa: "Malay",
|
||||
may: "Malay",
|
||||
hin: "Hindi",
|
||||
ara: "Arabic",
|
||||
heb: "Hebrew",
|
||||
fas: "Persian",
|
||||
per: "Persian",
|
||||
urd: "Urdu",
|
||||
swa: "Swahili",
|
||||
cat: "Catalan",
|
||||
eus: "Basque",
|
||||
baq: "Basque",
|
||||
}
|
||||
|
||||
function toLanguageName(code: string): string {
|
||||
const normalized = normalizeLanguageCode(code);
|
||||
const override = LANGUAGE_NAME_OVERRIDES[normalized];
|
||||
if (override) return override;
|
||||
const normalized = normalizeLanguageCode(code)
|
||||
const override = LANGUAGE_NAME_OVERRIDES[normalized]
|
||||
if (override) return override
|
||||
|
||||
const display = new Intl.DisplayNames(['en'], { type: 'language' });
|
||||
const candidate = display.of(normalized);
|
||||
if (candidate) return candidate;
|
||||
const display = new Intl.DisplayNames(["en"], { type: "language" })
|
||||
const candidate = display.of(normalized)
|
||||
if (candidate) return candidate
|
||||
|
||||
const base = normalized.split('-', 1)[0];
|
||||
const baseOverride = LANGUAGE_NAME_OVERRIDES[base];
|
||||
if (baseOverride) return baseOverride;
|
||||
const baseCandidate = display.of(base);
|
||||
if (baseCandidate) return baseCandidate;
|
||||
const base = normalized.split("-", 1)[0]
|
||||
const baseOverride = LANGUAGE_NAME_OVERRIDES[base]
|
||||
if (baseOverride) return baseOverride
|
||||
const baseCandidate = display.of(base)
|
||||
if (baseCandidate) return baseCandidate
|
||||
|
||||
return code.toUpperCase();
|
||||
return code.toUpperCase()
|
||||
}
|
||||
|
||||
function summarizeLanguageCodes(codes: string[] | null | undefined): string {
|
||||
if (!codes || codes.length === 0) return '';
|
||||
const names: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
if (!codes || codes.length === 0) return ""
|
||||
const names: string[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const raw of codes) {
|
||||
if (!raw) continue;
|
||||
const name = toLanguageName(raw).trim();
|
||||
if (!name) continue;
|
||||
const key = name.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
names.push(name);
|
||||
if (!raw) continue
|
||||
const name = toLanguageName(raw).trim()
|
||||
if (!name) continue
|
||||
const key = name.toLowerCase()
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
names.push(name)
|
||||
}
|
||||
|
||||
return names.join(', ');
|
||||
return names.join(", ")
|
||||
}
|
||||
|
||||
export function formatAudioSubtitleSummary(
|
||||
audioCodes: string[] | null | undefined,
|
||||
subtitleCodes: string[] | null | undefined
|
||||
subtitleCodes: string[] | null | undefined,
|
||||
): string {
|
||||
const audio = summarizeLanguageCodes(audioCodes);
|
||||
const subs = summarizeLanguageCodes(subtitleCodes);
|
||||
if (audio && subs) return `${audio} / ${subs}`;
|
||||
return audio || subs;
|
||||
const audio = summarizeLanguageCodes(audioCodes)
|
||||
const subs = summarizeLanguageCodes(subtitleCodes)
|
||||
if (audio && subs) return `${audio} / ${subs}`
|
||||
return audio || subs
|
||||
}
|
||||
|
||||
Vendored
+2
-2
@@ -1,7 +1,7 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
declare module "*.vue" {
|
||||
import type { DefineComponent } from "vue"
|
||||
const component: DefineComponent<{}, {}, any>
|
||||
export default component
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user