feat: video player (#225)
* init Signed-off-by: Innei <i@innei.in> * feat: player Signed-off-by: Innei <i@innei.in> * feat: player button Signed-off-by: Innei <i@innei.in> * feat: video player done Signed-off-by: Innei <i@innei.in> * fix: test global scope Signed-off-by: Innei <i@innei.in> * fix: test Signed-off-by: Innei <i@innei.in> * update Signed-off-by: Innei <i@innei.in> * fix: color in light mode Signed-off-by: Innei <i@innei.in> * fix: unify button Signed-off-by: Innei <i@innei.in> --------- Signed-off-by: Innei <i@innei.in>
This commit is contained in:
@@ -23,6 +23,7 @@ export default defineConfig(
|
||||
},
|
||||
rules: {
|
||||
"unicorn/prefer-math-trunc": "off",
|
||||
"@eslint-react/no-clone-element": 0,
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
{
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none"><path fill="#fff" fill-opacity=".01" d="M24 0v24H0V0z"/><path stroke="#10161F" stroke-linecap="round" stroke-width="2" d="M3.5 8v-.5a4 4 0 0 1 4-4H8M3.5 16v.5a4 4 0 0 0 4 4H8M20.5 8v-.5a4 4 0 0 0-4-4H16M20.5 16v.5a4 4 0 0 1-4 4H16"/></svg>
|
||||
|
After Width: | Height: | Size: 314 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none"><path fill="#fff" fill-opacity=".01" d="M24 0v24H0V0z"/><path stroke="#10161F" stroke-linecap="round" stroke-width="2" d="M8 3.5V4a4 4 0 0 1-4 4h-.5m17 0H20a4 4 0 0 1-4-4v-.5m0 17V20a4 4 0 0 1 4-4h.5m-17 0H4a4 4 0 0 1 4 4v.5"/></svg>
|
||||
|
After Width: | Height: | Size: 308 B |
@@ -6,6 +6,11 @@ import { enableMapSet } from "immer"
|
||||
globalThis.window = {
|
||||
location: new URL("https://example.com"),
|
||||
__dbIsReady: true,
|
||||
}
|
||||
|
||||
if (!globalThis.navigator) {
|
||||
globalThis.navigator = {
|
||||
onLine: true,
|
||||
}
|
||||
}
|
||||
enableMapSet()
|
||||
|
||||
+28
-1
@@ -1,7 +1,9 @@
|
||||
import { getRendererHandlers } from "@egoist/tipc/main"
|
||||
import { callGlobalContextMethod } from "@shared/bridge"
|
||||
import type { BrowserWindow } from "electron"
|
||||
import { clipboard } from "electron"
|
||||
import { clipboard, dialog } from "electron"
|
||||
|
||||
import { downloadFile } from "../lib/download"
|
||||
import { cleanAuthSessionToken, cleanUser } from "../lib/user"
|
||||
import type { RendererHandlers } from "../renderer-handlers"
|
||||
import { quitAndInstall } from "../updater"
|
||||
@@ -109,6 +111,31 @@ export const appRoute = {
|
||||
webContents.stopFindInPage("keepSelection")
|
||||
},
|
||||
),
|
||||
|
||||
download: t.procedure
|
||||
.input<string>()
|
||||
.action(async ({ input, context: { sender } }) => {
|
||||
const result = await dialog.showSaveDialog({
|
||||
defaultPath: input.split("/").pop(),
|
||||
})
|
||||
if (result.canceled) return
|
||||
|
||||
// return result.filePath;
|
||||
await downloadFile(input, result.filePath).catch((err) => {
|
||||
const senderWindow = (sender as Sender).getOwnerBrowserWindow()
|
||||
if (!senderWindow) return
|
||||
callGlobalContextMethod(senderWindow, "toast.error", [
|
||||
"Download failed!",
|
||||
])
|
||||
throw err
|
||||
})
|
||||
|
||||
const senderWindow = (sender as Sender).getOwnerBrowserWindow()
|
||||
if (!senderWindow) return
|
||||
callGlobalContextMethod(senderWindow, "toast.success", [
|
||||
"Download success!",
|
||||
])
|
||||
}),
|
||||
}
|
||||
interface Sender extends Electron.WebContents {
|
||||
getOwnerBrowserWindow: () => Electron.BrowserWindow | null
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { callGlobalContextMethod } from "@shared/bridge"
|
||||
import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron"
|
||||
import { dialog, Menu, ShareMenu } from "electron"
|
||||
|
||||
import { downloadFile } from "../lib/download"
|
||||
import { getMainWindow } from "../window"
|
||||
import { t } from "./_instance"
|
||||
|
||||
type MenuItem = ActionMenuItem | { type: "separator" }
|
||||
@@ -87,23 +84,4 @@ export const menuRoute = {
|
||||
},
|
||||
})
|
||||
}),
|
||||
|
||||
saveImage: t.procedure.input<string>().action(async ({ input }) => {
|
||||
const result = await dialog.showSaveDialog({
|
||||
defaultPath: input.split("/").pop(),
|
||||
})
|
||||
if (result.canceled) return
|
||||
|
||||
// return result.filePath;
|
||||
await downloadFile(input, result.filePath).catch((err) => {
|
||||
const mainWindow = getMainWindow()
|
||||
if (!mainWindow) return
|
||||
callGlobalContextMethod(mainWindow, "toast.error", ["Download failed!"])
|
||||
throw err
|
||||
})
|
||||
|
||||
const mainWindow = getMainWindow()
|
||||
if (!mainWindow) return
|
||||
callGlobalContextMethod(mainWindow, "toast.success", ["Download success!"])
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import { tipcClient } from "@renderer/lib/client"
|
||||
import { nextFrame } from "@renderer/lib/dom"
|
||||
import { getProxyUrl } from "@renderer/lib/img-proxy"
|
||||
import { showNativeMenu } from "@renderer/lib/native-menu"
|
||||
import { cn } from "@renderer/lib/utils"
|
||||
import { saveImageDimensionsToDb } from "@renderer/store/image/db"
|
||||
import { useForceUpdate } from "framer-motion"
|
||||
import type { FC, ImgHTMLAttributes, VideoHTMLAttributes } from "react"
|
||||
import { memo, useMemo, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { usePreviewMedia } from "./media/hooks"
|
||||
import type { VideoPlayerRef } from "./media/VideoPlayer"
|
||||
import { VideoPlayer } from "./media/VideoPlayer"
|
||||
|
||||
const failedList = new Set<string | undefined>()
|
||||
|
||||
@@ -164,18 +168,7 @@ const MediaImpl: FC<MediaProps> = ({
|
||||
)}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{previewImageUrl ? (
|
||||
<img src={previewImageUrl} className="size-full object-cover" />
|
||||
) : (
|
||||
<video
|
||||
src={src}
|
||||
muted
|
||||
className="relative size-full object-cover"
|
||||
/>
|
||||
)}
|
||||
<div className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-3xl text-white/80">
|
||||
<i className="i-mgc-play-cute-fi" />
|
||||
</div>
|
||||
<VideoPreview src={src!} previewImageUrl={previewImageUrl} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -199,7 +192,9 @@ const MediaImpl: FC<MediaProps> = ({
|
||||
type,
|
||||
])
|
||||
|
||||
if (hidden && showFallback) { return <FallbackMedia {...props} /> }
|
||||
if (hidden && showFallback) {
|
||||
return <FallbackMedia {...props} />
|
||||
}
|
||||
return (
|
||||
<div className={cn("overflow-hidden rounded", className)} style={style}>
|
||||
{InnerContent}
|
||||
@@ -245,3 +240,52 @@ const FallbackMedia: FC<MediaProps> = ({
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
const VideoPreview: FC<{
|
||||
src: string
|
||||
previewImageUrl?: string
|
||||
}> = ({ src, previewImageUrl }) => {
|
||||
const [isInitVideoPlayer, setIsInitVideoPlayer] = useState(!previewImageUrl)
|
||||
|
||||
const [videoRef, setVideoRef] = useState<VideoPlayerRef | null>(null)
|
||||
const isPaused = videoRef?.getState().paused
|
||||
const [forceUpdate] = useForceUpdate()
|
||||
return (
|
||||
<div
|
||||
onMouseEnter={() => {
|
||||
videoRef?.controls.play()?.then(forceUpdate)
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
videoRef?.controls.pause()
|
||||
nextFrame(forceUpdate)
|
||||
}}
|
||||
>
|
||||
{isInitVideoPlayer ? (
|
||||
<img
|
||||
src={previewImageUrl}
|
||||
className="size-full object-cover"
|
||||
onMouseEnter={() => {
|
||||
setIsInitVideoPlayer(true)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<VideoPlayer
|
||||
controls={false}
|
||||
src={src}
|
||||
ref={setVideoRef}
|
||||
muted
|
||||
className="relative size-full object-cover"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-3xl text-white/80 duration-200",
|
||||
isPaused ? "opacity-100" : "opacity-0",
|
||||
)}
|
||||
>
|
||||
<i className="i-mgc-play-cute-fi" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
import * as Slider from "@radix-ui/react-slider"
|
||||
import { IconScaleTransition } from "@renderer/components/ux/transition/icon"
|
||||
import { useRefValue } from "@renderer/hooks/common"
|
||||
import type { HTMLMediaState } from "@renderer/hooks/common/factory/createHTMLMediaHook"
|
||||
import { useVideo } from "@renderer/hooks/common/useVideo"
|
||||
import { nextFrame, stopPropagation } from "@renderer/lib/dom"
|
||||
import { cn } from "@renderer/lib/utils"
|
||||
import { m, useDragControls, useSpring } from "framer-motion"
|
||||
import type { PropsWithChildren } from "react"
|
||||
import {
|
||||
forwardRef,
|
||||
memo,
|
||||
startTransition,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react"
|
||||
import { useHotkeys } from "react-hotkeys-hook"
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useContextSelector,
|
||||
} from "use-context-selector"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { softSpringPreset } from "../constants/spring"
|
||||
import { KbdCombined } from "../kbd/Kbd"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../tooltip"
|
||||
import { VolumeSlider } from "./VolumeSlider"
|
||||
|
||||
type VideoPlayerProps = {
|
||||
src: string
|
||||
} & React.VideoHTMLAttributes<HTMLVideoElement> &
|
||||
PropsWithChildren
|
||||
export type VideoPlayerRef = {
|
||||
getElement: () => HTMLVideoElement | null
|
||||
|
||||
getState: () => HTMLMediaState
|
||||
controls: {
|
||||
play: () => Promise<void> | undefined
|
||||
pause: () => void
|
||||
seek: (time: number) => void
|
||||
volume: (volume: number) => void
|
||||
mute: () => void
|
||||
unmute: () => void
|
||||
}
|
||||
|
||||
wrapperRef: React.RefObject<HTMLDivElement>
|
||||
}
|
||||
|
||||
interface VideoPlayerContextValue {
|
||||
state: HTMLMediaState
|
||||
controls: VideoPlayerRef["controls"]
|
||||
wrapperRef: React.RefObject<HTMLDivElement>
|
||||
src: string
|
||||
}
|
||||
const VideoPlayerContext = createContext<VideoPlayerContextValue>(null!)
|
||||
export const VideoPlayer = forwardRef<VideoPlayerRef, VideoPlayerProps>(
|
||||
({ src, className, ...rest }, ref) => {
|
||||
const [clickToStatus, setClickToStatus] = useState(
|
||||
null as "play" | "pause" | null,
|
||||
)
|
||||
|
||||
const scaleValue = useSpring(1, softSpringPreset)
|
||||
const opacityValue = useSpring(0, softSpringPreset)
|
||||
const handleClick = useEventCallback((e?: any) => {
|
||||
if (!rest.controls) return
|
||||
e?.stopPropagation()
|
||||
|
||||
if (state.playing) {
|
||||
controls.pause()
|
||||
setClickToStatus("pause")
|
||||
} else {
|
||||
controls.play()
|
||||
setClickToStatus("play")
|
||||
}
|
||||
|
||||
opacityValue.jump(1)
|
||||
scaleValue.jump(1)
|
||||
|
||||
nextFrame(() => {
|
||||
scaleValue.set(1.3)
|
||||
opacityValue.set(0)
|
||||
})
|
||||
})
|
||||
|
||||
const [element, state, controls, videoRef] = useVideo({
|
||||
src,
|
||||
className,
|
||||
playsInline: true,
|
||||
...rest,
|
||||
controls: false,
|
||||
onClick(e) {
|
||||
rest.onClick?.(e)
|
||||
handleClick(e)
|
||||
},
|
||||
})
|
||||
|
||||
useHotkeys("space", (e) => {
|
||||
e.preventDefault()
|
||||
handleClick()
|
||||
})
|
||||
|
||||
const stateRef = useRefValue(state)
|
||||
const memoedControls = useState(controls)[0]
|
||||
const wrapperRef = useRef<HTMLDivElement>(null)
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
getElement: () => videoRef.current,
|
||||
getState: () => stateRef.current,
|
||||
controls: memoedControls,
|
||||
wrapperRef,
|
||||
}),
|
||||
|
||||
[stateRef, videoRef, memoedControls],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="center relative size-full" ref={wrapperRef}>
|
||||
{element}
|
||||
|
||||
<div className="center pointer-events-none absolute inset-0">
|
||||
<m.div
|
||||
className="center flex size-20 rounded-full bg-black p-3"
|
||||
style={{ scale: scaleValue, opacity: opacityValue }}
|
||||
>
|
||||
<i
|
||||
className={cn(
|
||||
"size-8 text-white",
|
||||
clickToStatus === "play" ?
|
||||
"i-mgc-play-cute-fi" :
|
||||
"i-mgc-pause-cute-fi",
|
||||
)}
|
||||
/>
|
||||
</m.div>
|
||||
</div>
|
||||
|
||||
<VideoPlayerContext.Provider
|
||||
value={useMemo(
|
||||
() => ({ state, controls, wrapperRef, src }),
|
||||
[state, controls, src],
|
||||
)}
|
||||
>
|
||||
{rest.controls && <ControlBar />}
|
||||
</VideoPlayerContext.Provider>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
const ControlBar = memo(() => {
|
||||
const controls = useContextSelector(VideoPlayerContext, (v) => v.controls)
|
||||
const isPaused = useContextSelector(
|
||||
VideoPlayerContext,
|
||||
(v) => v.state.paused,
|
||||
)
|
||||
const dragControls = useDragControls()
|
||||
|
||||
return (
|
||||
<m.div
|
||||
onClick={stopPropagation}
|
||||
drag
|
||||
dragListener={false}
|
||||
dragControls={dragControls}
|
||||
dragElastic={0}
|
||||
dragMomentum={false}
|
||||
dragConstraints={{ current: document.documentElement }}
|
||||
className={cn(
|
||||
"absolute inset-x-2 bottom-2 h-8 rounded-2xl border bg-zinc-100/90 backdrop-blur-xl dark:border-transparent dark:bg-neutral-700/90",
|
||||
"flex items-center gap-3 px-3",
|
||||
"mx-auto max-w-[80vw]",
|
||||
)}
|
||||
>
|
||||
{/* Drag Area */}
|
||||
<div
|
||||
onPointerDownCapture={dragControls.start.bind(dragControls)}
|
||||
className="absolute inset-0 z-[1]"
|
||||
/>
|
||||
|
||||
<ActionIcon
|
||||
shortcut="Space"
|
||||
label={isPaused ? "Play" : "Pause"}
|
||||
className="center relative flex"
|
||||
onClick={() => {
|
||||
if (isPaused) {
|
||||
controls.play()
|
||||
} else {
|
||||
controls.pause()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
<IconScaleTransition
|
||||
status={isPaused ? "init" : "done"}
|
||||
icon1="i-mgc-play-cute-fi"
|
||||
icon2="i-mgc-pause-cute-fi"
|
||||
/>
|
||||
</span>
|
||||
</ActionIcon>
|
||||
|
||||
{/* Progress bar */}
|
||||
<PlayProgressBar />
|
||||
|
||||
{/* Right Action */}
|
||||
<m.div className="relative z-[1] flex items-center gap-1">
|
||||
<VolumeControl />
|
||||
<DownloadVideo />
|
||||
<FullScreenControl />
|
||||
</m.div>
|
||||
</m.div>
|
||||
)
|
||||
})
|
||||
|
||||
const FullScreenControl = () => {
|
||||
const ref = useContextSelector(VideoPlayerContext, (v) => v.wrapperRef)
|
||||
const [isFullScreen, setIsFullScreen] = useState(false)
|
||||
return (
|
||||
<ActionIcon
|
||||
label="Full Screen"
|
||||
shortcut="f"
|
||||
labelDelayDuration={1}
|
||||
onClick={() => {
|
||||
if (!ref.current) return
|
||||
|
||||
if (isFullScreen) {
|
||||
document.exitFullscreen()
|
||||
} else {
|
||||
ref.current.requestFullscreen()
|
||||
}
|
||||
|
||||
setIsFullScreen((v) => !v)
|
||||
}}
|
||||
>
|
||||
{isFullScreen ? (
|
||||
<i className="i-mgc-fullscreen-exit-cute-re" />
|
||||
) : (
|
||||
<i className="i-mgc-fullscreen-cute-re" />
|
||||
)}
|
||||
</ActionIcon>
|
||||
)
|
||||
}
|
||||
|
||||
const DownloadVideo = () => {
|
||||
const src = useContextSelector(VideoPlayerContext, (v) => v.src)
|
||||
const [isDownloading, setIsDownloading] = useState(false)
|
||||
const download = useEventCallback(() => {
|
||||
setIsDownloading(true)
|
||||
fetch(src)
|
||||
.then((res) => res.blob())
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = src.split("/").pop()!
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
setIsDownloading(false)
|
||||
})
|
||||
})
|
||||
|
||||
return (
|
||||
<ActionIcon
|
||||
shortcut="d"
|
||||
label="Download"
|
||||
labelDelayDuration={1}
|
||||
onClick={download}
|
||||
>
|
||||
{isDownloading ? (
|
||||
<i className="i-mgc-loading-3-cute-re animate-spin" />
|
||||
) : (
|
||||
<i className="i-mgc-download-2-cute-re" />
|
||||
)}
|
||||
</ActionIcon>
|
||||
)
|
||||
}
|
||||
const VolumeControl = () => {
|
||||
const hasAudio = useContextSelector(
|
||||
VideoPlayerContext,
|
||||
(v) => v.state.hasAudio,
|
||||
)
|
||||
|
||||
const controls = useContextSelector(VideoPlayerContext, (v) => v.controls)
|
||||
const volume = useContextSelector(VideoPlayerContext, (v) => v.state.volume)
|
||||
const muted = useContextSelector(VideoPlayerContext, (v) => v.state.muted)
|
||||
if (!hasAudio) return null
|
||||
return (
|
||||
<ActionIcon
|
||||
label={<VolumeSlider onVolumeChange={controls.volume} volume={volume} />}
|
||||
onClick={() => {
|
||||
if (muted) {
|
||||
controls.unmute()
|
||||
} else {
|
||||
controls.mute()
|
||||
}
|
||||
}}
|
||||
labelDelayDuration={1}
|
||||
>
|
||||
{muted ? (
|
||||
<i className="i-mgc-volume-mute-cute-re" />
|
||||
) : (
|
||||
<i className="i-mgc-volume-cute-re" />
|
||||
)}
|
||||
</ActionIcon>
|
||||
)
|
||||
}
|
||||
|
||||
const PlayProgressBar = () => {
|
||||
const { state, controls } = useContext(VideoPlayerContext)
|
||||
const [currentDragging, setCurrentDragging] = useState(false)
|
||||
const [dragTime, setDragTime] = useState(0)
|
||||
|
||||
useHotkeys("left", (e) => {
|
||||
e.preventDefault()
|
||||
controls.seek(state.time - 5)
|
||||
})
|
||||
|
||||
useHotkeys("right", (e) => {
|
||||
e.preventDefault()
|
||||
controls.seek(state.time + 5)
|
||||
})
|
||||
return (
|
||||
<Slider.Root
|
||||
className="relative z-[1] flex size-full items-center transition-all duration-200 ease-in-out"
|
||||
min={0}
|
||||
max={state.duration}
|
||||
step={0.01}
|
||||
value={[currentDragging ? dragTime : state.time]}
|
||||
onPointerDown={() => {
|
||||
if (state.playing) {
|
||||
controls.pause()
|
||||
}
|
||||
setDragTime(state.time)
|
||||
setCurrentDragging(true)
|
||||
}}
|
||||
onValueChange={(value) => {
|
||||
setDragTime(value[0])
|
||||
startTransition(() => {
|
||||
controls.seek(value[0])
|
||||
})
|
||||
}}
|
||||
onValueCommit={() => {
|
||||
controls.play()
|
||||
setCurrentDragging(false)
|
||||
controls.seek(dragTime)
|
||||
}}
|
||||
>
|
||||
<Slider.Track className="relative h-1 w-full grow rounded bg-white dark:bg-neutral-800">
|
||||
<Slider.Range className="absolute h-1 rounded bg-zinc-500/40 dark:bg-neutral-600" />
|
||||
</Slider.Track>
|
||||
|
||||
{/* indicator */}
|
||||
<Slider.Thumb
|
||||
className="block h-3 w-[3px] rounded-[1px] bg-zinc-500 dark:bg-zinc-400"
|
||||
aria-label="Progress"
|
||||
/>
|
||||
</Slider.Root>
|
||||
)
|
||||
}
|
||||
|
||||
const ActionIcon = ({
|
||||
className,
|
||||
onClick,
|
||||
label,
|
||||
labelDelayDuration = 700,
|
||||
children,
|
||||
shortcut,
|
||||
}: {
|
||||
className?: string
|
||||
onClick?: () => void
|
||||
label: React.ReactNode
|
||||
labelDelayDuration?: number
|
||||
children?: React.ReactNode
|
||||
shortcut?: string
|
||||
}) => {
|
||||
useHotkeys(
|
||||
shortcut || "",
|
||||
(e) => {
|
||||
e.preventDefault()
|
||||
onClick?.()
|
||||
},
|
||||
{
|
||||
enabled: !!shortcut,
|
||||
},
|
||||
)
|
||||
return (
|
||||
<Tooltip delayDuration={labelDelayDuration}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="center relative z-[1] size-6 rounded-md hover:bg-theme-button-hover"
|
||||
onClick={onClick}
|
||||
>
|
||||
{children || <i className={className} />}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="flex items-center gap-1 bg-theme-modal-background">
|
||||
{label}
|
||||
{shortcut && <KbdCombined>{shortcut}</KbdCombined>}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as Slider from "@radix-ui/react-slider"
|
||||
import type { FC } from "react"
|
||||
|
||||
export const VolumeSlider: FC<{
|
||||
volume: number
|
||||
onVolumeChange: (volume: number) => void
|
||||
}> = ({ onVolumeChange, volume }) => (
|
||||
<Slider.Root
|
||||
className="relative flex h-16 w-1 flex-col items-center overflow-hidden rounded p-1"
|
||||
max={1}
|
||||
step={0.01}
|
||||
orientation="vertical"
|
||||
value={[volume ?? 0.8]}
|
||||
onValueChange={(values) => {
|
||||
onVolumeChange?.(values[0])
|
||||
}}
|
||||
>
|
||||
<Slider.Track className="relative w-1 grow rounded bg-zinc-500">
|
||||
<Slider.Range className="absolute w-full rounded bg-black dark:bg-white" />
|
||||
</Slider.Track>
|
||||
<Slider.Thumb
|
||||
className="block rounded bg-black dark:bg-white"
|
||||
aria-label="Volume"
|
||||
/>
|
||||
</Slider.Root>
|
||||
)
|
||||
@@ -15,7 +15,7 @@ export const usePreviewMedia = () => {
|
||||
<PreviewMediaContent initialIndex={initialIndex} media={media} />
|
||||
</div>
|
||||
),
|
||||
title: "Image",
|
||||
title: "Media Preview",
|
||||
overlay: true,
|
||||
CustomModalComponent: NoopChildren,
|
||||
clickOutsideToDismiss: true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { m } from "@renderer/components/common/Motion"
|
||||
import { COPY_MAP } from "@renderer/constants"
|
||||
import { COPY_MAP, isElectronBuild } from "@renderer/constants"
|
||||
import { tipcClient } from "@renderer/lib/client"
|
||||
import { stopPropagation } from "@renderer/lib/dom"
|
||||
import { replaceImgUrlIfNeed } from "@renderer/lib/img-proxy"
|
||||
@@ -13,14 +13,19 @@ import { Swiper, SwiperSlide } from "swiper/react"
|
||||
import { ActionButton, MotionButtonBase } from "../button"
|
||||
import { microReboundPreset } from "../constants/spring"
|
||||
import { useCurrentModal } from "../modal"
|
||||
import { VideoPlayer } from "./VideoPlayer"
|
||||
|
||||
const Wrapper: Component<{
|
||||
src: string
|
||||
}> = ({ children, src }) => {
|
||||
showActions?: boolean
|
||||
}> = ({ children, src, showActions }) => {
|
||||
const { dismiss } = useCurrentModal()
|
||||
|
||||
return (
|
||||
<div className="center relative size-full p-12" onClick={dismiss}>
|
||||
{isElectronBuild && (
|
||||
<div className="drag-region fixed inset-x-0 top-0 h-8" />
|
||||
)}
|
||||
<m.div
|
||||
className="center size-full"
|
||||
initial={{ scale: 0.94, opacity: 0 }}
|
||||
@@ -44,24 +49,28 @@ const Wrapper: Component<{
|
||||
>
|
||||
<i className="i-mgc-close-cute-re" />
|
||||
</button>
|
||||
{!!window.electron && (
|
||||
<ActionButton
|
||||
tooltip="Download"
|
||||
onClick={() => {
|
||||
tipcClient?.saveImage(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-download-2-cute-re" />
|
||||
</ActionButton>
|
||||
{showActions && (
|
||||
<Fragment>
|
||||
{!!window.electron && (
|
||||
<ActionButton
|
||||
tooltip="Download"
|
||||
onClick={() => {
|
||||
tipcClient?.download(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-download-2-cute-re" />
|
||||
</ActionButton>
|
||||
)}
|
||||
<ActionButton
|
||||
tooltip={COPY_MAP.OpenInBrowser()}
|
||||
onClick={() => {
|
||||
window.open(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-external-link-cute-re" />
|
||||
</ActionButton>
|
||||
</Fragment>
|
||||
)}
|
||||
<ActionButton
|
||||
tooltip={COPY_MAP.OpenInBrowser()}
|
||||
onClick={() => {
|
||||
window.open(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-external-link-cute-re" />
|
||||
</ActionButton>
|
||||
</m.div>
|
||||
</div>
|
||||
)
|
||||
@@ -96,7 +105,7 @@ export const PreviewMediaContent: FC<{
|
||||
label: "Save image as...",
|
||||
type: "text",
|
||||
click: () => {
|
||||
tipcClient?.saveImage(image)
|
||||
tipcClient?.download(image)
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -108,10 +117,11 @@ export const PreviewMediaContent: FC<{
|
||||
if (media.length === 0) return null
|
||||
if (media.length === 1) {
|
||||
const src = media[0].url
|
||||
const { type } = media[0]
|
||||
return (
|
||||
<Wrapper src={src}>
|
||||
{media[0].type === "video" ? (
|
||||
<video
|
||||
<Wrapper src={src} showActions={type !== "video"}>
|
||||
{type === "video" ? (
|
||||
<VideoPlayer
|
||||
src={src}
|
||||
controls
|
||||
autoPlay
|
||||
@@ -131,8 +141,12 @@ export const PreviewMediaContent: FC<{
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Wrapper src={currentMedia.url}>
|
||||
<Wrapper
|
||||
src={currentMedia.url}
|
||||
showActions={currentMedia.type !== "video"}
|
||||
>
|
||||
<Swiper
|
||||
|
||||
loop
|
||||
initialSlide={initialIndex}
|
||||
scrollbar={{
|
||||
@@ -157,7 +171,7 @@ export const PreviewMediaContent: FC<{
|
||||
className="center !flex"
|
||||
>
|
||||
{med.type === "video" ? (
|
||||
<video
|
||||
<VideoPlayer
|
||||
src={med.url}
|
||||
controls
|
||||
className="max-h-full max-w-full object-contain"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { AnimatePresence, m } from "framer-motion"
|
||||
|
||||
export const IconScaleTransition = ({
|
||||
icon1,
|
||||
icon2,
|
||||
status,
|
||||
}: {
|
||||
status: "init" | "done"
|
||||
|
||||
icon1: string
|
||||
icon2: string
|
||||
}) => (
|
||||
<AnimatePresence mode="popLayout">
|
||||
{status === "init" ? (
|
||||
<m.i
|
||||
className={icon1}
|
||||
key="1"
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
exit={{ scale: 0 }}
|
||||
/>
|
||||
) : (
|
||||
<m.i
|
||||
className={icon2}
|
||||
key="2"
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
exit={{ scale: 0 }}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* @see https://github.com/streamich/react-use/blob/master/src/factory/createHTMLMediaHook.ts
|
||||
*/
|
||||
import * as React from "react"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { useSetState } from "../useSetState"
|
||||
|
||||
function parseTimeRanges(ranges: TimeRanges) {
|
||||
const result: { start: number, end: number }[] = []
|
||||
|
||||
for (let i = 0; i < ranges.length; i++) {
|
||||
result.push({
|
||||
start: ranges.start(i),
|
||||
end: ranges.end(i),
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
export interface HTMLMediaProps
|
||||
extends React.AudioHTMLAttributes<any>,
|
||||
React.VideoHTMLAttributes<any> {
|
||||
src: string
|
||||
}
|
||||
|
||||
export interface HTMLMediaState {
|
||||
buffered: any[]
|
||||
duration: number
|
||||
paused: boolean
|
||||
muted: boolean
|
||||
time: number
|
||||
volume: number
|
||||
playing: boolean
|
||||
|
||||
hasAudio: boolean
|
||||
}
|
||||
|
||||
export interface HTMLMediaControls {
|
||||
play: () => Promise<void> | void
|
||||
pause: () => void
|
||||
mute: () => void
|
||||
unmute: () => void
|
||||
volume: (volume: number) => void
|
||||
seek: (time: number) => void
|
||||
}
|
||||
|
||||
type MediaPropsWithRef<T> = HTMLMediaProps & {
|
||||
ref?: React.MutableRefObject<T | null>
|
||||
}
|
||||
|
||||
export default function createHTMLMediaHook<
|
||||
T extends HTMLAudioElement | HTMLVideoElement,
|
||||
>(tag: "audio" | "video") {
|
||||
return (elOrProps: HTMLMediaProps | React.ReactElement<HTMLMediaProps>) => {
|
||||
let element: React.ReactElement<MediaPropsWithRef<T>> | undefined
|
||||
let props: MediaPropsWithRef<T>
|
||||
|
||||
if (React.isValidElement(elOrProps)) {
|
||||
element = elOrProps
|
||||
props = element.props
|
||||
} else {
|
||||
props = elOrProps
|
||||
}
|
||||
|
||||
const [state, setState] = useSetState<HTMLMediaState>({
|
||||
buffered: [],
|
||||
time: 0,
|
||||
duration: 0,
|
||||
paused: true,
|
||||
muted: false,
|
||||
volume: 1,
|
||||
playing: false,
|
||||
hasAudio: false,
|
||||
})
|
||||
const getState = useEventCallback(() => state)
|
||||
const ref = useRef<T | null>(null)
|
||||
|
||||
const wrapEvent = (userEvent, proxyEvent?) => (event) => {
|
||||
try {
|
||||
proxyEvent && proxyEvent(event)
|
||||
} finally {
|
||||
userEvent && userEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
const onPlay = () => setState({ paused: false })
|
||||
const onPlaying = () => setState({ playing: true })
|
||||
const onWaiting = () => setState({ playing: false })
|
||||
const onPause = () => setState({ paused: true, playing: false })
|
||||
const onVolumeChange = () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
setState({
|
||||
muted: el.muted,
|
||||
volume: el.volume,
|
||||
})
|
||||
}
|
||||
const onDurationChange = () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
const { duration, buffered } = el
|
||||
setState({
|
||||
duration,
|
||||
buffered: parseTimeRanges(buffered),
|
||||
})
|
||||
}
|
||||
const onTimeUpdate = () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
setState({ time: el.currentTime })
|
||||
}
|
||||
const onProgress = () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
setState({ buffered: parseTimeRanges(el.buffered) })
|
||||
}
|
||||
const onLoadedData = () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
// @ts-expect-error
|
||||
setState({ hasAudio: !!el.mozHasAudio || !!el.webkitAudioDecodedByteCount || !!el.audioTracks })
|
||||
}
|
||||
|
||||
if (element) {
|
||||
element = React.cloneElement(element, {
|
||||
controls: false,
|
||||
...props,
|
||||
ref,
|
||||
onPlay: wrapEvent(props.onPlay, onPlay),
|
||||
onPlaying: wrapEvent(props.onPlaying, onPlaying),
|
||||
onWaiting: wrapEvent(props.onWaiting, onWaiting),
|
||||
onPause: wrapEvent(props.onPause, onPause),
|
||||
onVolumeChange: wrapEvent(props.onVolumeChange, onVolumeChange),
|
||||
onDurationChange: wrapEvent(props.onDurationChange, onDurationChange),
|
||||
onTimeUpdate: wrapEvent(props.onTimeUpdate, onTimeUpdate),
|
||||
onProgress: wrapEvent(props.onProgress, onProgress),
|
||||
onLoadedData: wrapEvent(props.onLoadedData, onLoadedData),
|
||||
})
|
||||
} else {
|
||||
element = React.createElement(tag, {
|
||||
controls: false,
|
||||
...props,
|
||||
ref,
|
||||
onPlay: wrapEvent(props.onPlay, onPlay),
|
||||
onPlaying: wrapEvent(props.onPlaying, onPlaying),
|
||||
onWaiting: wrapEvent(props.onWaiting, onWaiting),
|
||||
onPause: wrapEvent(props.onPause, onPause),
|
||||
onVolumeChange: wrapEvent(props.onVolumeChange, onVolumeChange),
|
||||
onDurationChange: wrapEvent(props.onDurationChange, onDurationChange),
|
||||
onTimeUpdate: wrapEvent(props.onTimeUpdate, onTimeUpdate),
|
||||
onProgress: wrapEvent(props.onProgress, onProgress),
|
||||
onLoadedData: wrapEvent(props.onLoadedData, onLoadedData),
|
||||
} as any) // TODO: fix this typing.
|
||||
}
|
||||
|
||||
// Some browsers return `Promise` on `.play()` and may throw errors
|
||||
// if one tries to execute another `.play()` or `.pause()` while that
|
||||
// promise is resolving. So we prevent that with this lock.
|
||||
// See: https://bugs.chromium.org/p/chromium/issues/detail?id=593273
|
||||
let lockPlay = false
|
||||
|
||||
const controls = React.useState(() => ({
|
||||
play: () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!lockPlay) {
|
||||
const promise = el.play()
|
||||
const isPromise = typeof promise === "object"
|
||||
|
||||
if (isPromise) {
|
||||
lockPlay = true
|
||||
const resetLock = () => {
|
||||
lockPlay = false
|
||||
}
|
||||
promise.then(resetLock, resetLock)
|
||||
}
|
||||
|
||||
return promise
|
||||
}
|
||||
return
|
||||
},
|
||||
pause: () => {
|
||||
const el = ref.current
|
||||
if (el && !lockPlay) {
|
||||
return el.pause()
|
||||
}
|
||||
},
|
||||
seek: (time: number) => {
|
||||
const state = getState()
|
||||
const el = ref.current
|
||||
if (!el || state.duration === undefined) {
|
||||
return
|
||||
}
|
||||
time = Math.min(state.duration, Math.max(0, time))
|
||||
el.currentTime = time
|
||||
},
|
||||
volume: (volume: number) => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
volume = Math.min(1, Math.max(0, volume))
|
||||
el.volume = volume
|
||||
setState({ volume })
|
||||
},
|
||||
mute: () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
el.muted = true
|
||||
},
|
||||
unmute: () => {
|
||||
const el = ref.current
|
||||
if (!el) {
|
||||
return
|
||||
}
|
||||
el.muted = false
|
||||
},
|
||||
}))[0]
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current!
|
||||
|
||||
if (!el) {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (tag === "audio") {
|
||||
console.error(
|
||||
"useAudio() ref to <audio> element is empty at mount. " +
|
||||
"It seem you have not rendered the audio element, which it " +
|
||||
"returns as the first argument const [audio] = useAudio(...).",
|
||||
)
|
||||
} else if (tag === "video") {
|
||||
console.error(
|
||||
"useVideo() ref to <video> element is empty at mount. " +
|
||||
"It seem you have not rendered the video element, which it " +
|
||||
"returns as the first argument const [video] = useVideo(...).",
|
||||
)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
setState({
|
||||
volume: el.volume,
|
||||
muted: el.muted,
|
||||
paused: el.paused,
|
||||
})
|
||||
|
||||
// Start media, if autoPlay requested.
|
||||
if (props.autoPlay && el.paused) {
|
||||
controls.play()
|
||||
}
|
||||
}, [props.src])
|
||||
|
||||
return [element, state, controls, ref] as const
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* @see https://github.com/streamich/react-use/blob/master/src/useSetState.ts
|
||||
*/
|
||||
import { useCallback, useState } from "react"
|
||||
|
||||
export const useSetState = <T extends object>(
|
||||
initialState: T = {} as T,
|
||||
): [T, (patch: Partial<T> | ((prevState: T) => Partial<T>)) => void] => {
|
||||
const [state, set] = useState<T>(initialState)
|
||||
const setState = useCallback((patch) => {
|
||||
set((prevState) =>
|
||||
Object.assign({}, prevState, patch instanceof Function ? patch(prevState) : patch),
|
||||
)
|
||||
}, [])
|
||||
|
||||
return [state, setState]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import createHTMLMediaHook from "./factory/createHTMLMediaHook"
|
||||
|
||||
export const useVideo = createHTMLMediaHook<HTMLVideoElement>("video")
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SwipeMedia } from "@renderer/components/ui/media/swipe-media"
|
||||
import { SwipeMedia } from "@renderer/components/ui/media/SwipeMedia"
|
||||
import { ReactVirtuosoItemPlaceholder } from "@renderer/components/ui/placeholder"
|
||||
import { Skeleton } from "@renderer/components/ui/skeleton"
|
||||
import { useRouteParamsSelector } from "@renderer/hooks/biz/useRouteParams"
|
||||
@@ -54,7 +54,7 @@ export function PictureItem({
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="center aspect-square w-full flex-col gap-1 bg-muted text-xs text-muted-foreground">
|
||||
<div className="center aspect-square w-full flex-col gap-1 rounded-md bg-muted text-xs text-muted-foreground">
|
||||
<i className="i-mgc-sad-cute-re size-6" />
|
||||
No media available
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from "@renderer/atoms/player"
|
||||
import { FeedIcon } from "@renderer/components/feed-icon"
|
||||
import { microReboundPreset } from "@renderer/components/ui/constants/spring"
|
||||
import { VolumeSlider } from "@renderer/components/ui/media/VolumeSlider"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -190,7 +191,7 @@ const CornerPlayerImpl = () => {
|
||||
"i-mgc-volume-cute-re",
|
||||
)}
|
||||
onClick={() => Player.toggleMute()}
|
||||
label={<VolumeSlider />}
|
||||
label={<CornerPlayerVolumeSlider />}
|
||||
labelDelayDuration={0}
|
||||
/>
|
||||
<ActionIcon
|
||||
@@ -300,27 +301,10 @@ const ActionIcon = ({
|
||||
</Tooltip>
|
||||
)
|
||||
|
||||
const VolumeSlider = () => {
|
||||
const CornerPlayerVolumeSlider = () => {
|
||||
const volume = usePlayerAtomSelector((v) => v.volume)
|
||||
|
||||
return (
|
||||
<Slider.Root
|
||||
className="relative flex h-16 w-1 flex-col items-center overflow-hidden rounded p-1"
|
||||
max={1}
|
||||
step={0.01}
|
||||
orientation="vertical"
|
||||
value={[volume ?? 0.8]}
|
||||
onValueChange={(value) => Player.setVolume(value[0])}
|
||||
>
|
||||
<Slider.Track className="relative w-1 grow rounded bg-zinc-500">
|
||||
<Slider.Range className="absolute w-full rounded bg-black dark:bg-white" />
|
||||
</Slider.Track>
|
||||
<Slider.Thumb
|
||||
className="block rounded bg-black dark:bg-white"
|
||||
aria-label="Volume"
|
||||
/>
|
||||
</Slider.Root>
|
||||
)
|
||||
return <VolumeSlider volume={volume!} onVolumeChange={Player.setVolume.bind(Player)} />
|
||||
}
|
||||
|
||||
const PlaybackRateSelector = () => {
|
||||
|
||||
Reference in New Issue
Block a user