重构前端

This commit is contained in:
sky22333
2026-07-12 01:19:44 +08:00
parent 26b45c98bf
commit 79f23d13ad
42 changed files with 3641 additions and 3353 deletions

14
web/src/App.vue Normal file
View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import { RouterView } from 'vue-router'
import AppShell from '@/components/AppShell.vue'
</script>
<template>
<AppShell>
<RouterView v-slot="{ Component, route }">
<Transition name="page">
<component :is="Component" :key="route.path" />
</Transition>
</RouterView>
</AppShell>
</template>

137
web/src/api.ts Normal file
View File

@@ -0,0 +1,137 @@
class ApiError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.name = 'ApiError'
this.status = status
}
}
async function parseError(res: Response): Promise<string> {
const contentType = res.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) {
try {
const data = (await res.json()) as { error?: string; message?: string }
return data.error || data.message || `请求失败 (${res.status})`
} catch {
return `请求失败 (${res.status})`
}
}
try {
const text = await res.text()
return text || `请求失败 (${res.status})`
} catch {
return `请求失败 (${res.status})`
}
}
async function getJSON<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, {
...init,
headers: {
Accept: 'application/json',
...(init?.headers || {}),
},
cache: 'no-store',
})
if (!res.ok) throw new ApiError(await parseError(res), res.status)
return (await res.json()) as T
}
export interface PrepareDownloadResponse {
download_url: string
}
export interface ImageInfoResponse {
success: boolean
}
export interface Repository {
repo_name?: string
short_description?: string
is_official?: boolean
star_count?: number
pull_count?: number
namespace?: string
}
export interface SearchResponse {
count: number
results: Repository[]
}
export interface TagInfo {
name: string
last_updated?: string
full_size?: number
images?: Array<{
architecture?: string
os?: string
variant?: string
size?: number
}>
}
export interface TagPageResult {
tags: TagInfo[]
has_more: boolean
}
export function prepareSingleDownload(params: {
image: string
platform?: string
compressed: boolean
}) {
const q = new URLSearchParams()
q.set('image', params.image)
q.set('mode', 'prepare')
q.set('compressed', String(params.compressed))
if (params.platform?.trim()) q.set('platform', params.platform.trim())
return getJSON<PrepareDownloadResponse>(`/api/image/download?${q}`)
}
export function fetchImageInfo(image: string) {
const q = new URLSearchParams({ image })
return getJSON<ImageInfoResponse>(`/api/image/info?${q}`)
}
export function prepareBatchDownload(body: {
images: string[]
platform?: string
useCompressedLayers: boolean
}) {
return getJSON<PrepareDownloadResponse>('/api/image/batch?mode=prepare', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
export function searchImages(q: string, page: number, pageSize = 25) {
const params = new URLSearchParams({
q,
page: String(page),
page_size: String(pageSize),
})
return getJSON<SearchResponse>(`/api/search?${params}`)
}
export function fetchTags(namespace: string, name: string, page: number, pageSize = 100) {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
})
return getJSON<TagPageResult>(
`/api/tags/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}?${params}`,
)
}
export function triggerDownload(url: string) {
const link = document.createElement('a')
link.href = url
link.style.display = 'none'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}

View File

@@ -0,0 +1,120 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { Container, Github, Menu, Rocket, Search, X, Zap } from 'lucide-vue-next'
import Button from '@/components/ui/Button.vue'
import ThemeToggle from '@/components/ThemeToggle.vue'
const STORAGE_KEY = 'theme'
const route = useRoute()
const isDark = ref(false)
const menuOpen = ref(false)
const links = [
{ to: '/', label: 'GitHub 加速', icon: Rocket },
{ to: '/images', label: '离线镜像', icon: Container },
{ to: '/search', label: '镜像搜索', icon: Search },
] as const
const currentPath = computed(() => route.path)
function applyTheme(dark: boolean) {
isDark.value = dark
document.documentElement.classList.toggle('dark', dark)
localStorage.setItem(STORAGE_KEY, dark ? 'dark' : 'light')
}
function toggleTheme() {
applyTheme(!isDark.value)
}
function closeMenu() {
menuOpen.value = false
}
onMounted(() => {
const saved = localStorage.getItem(STORAGE_KEY)
if (saved === 'dark' || saved === 'light') {
applyTheme(saved === 'dark')
} else {
applyTheme(window.matchMedia('(prefers-color-scheme: dark)').matches)
}
})
</script>
<template>
<div class="shell-atmosphere flex min-h-screen flex-col text-foreground">
<header class="sticky top-0 z-50 border-b border-border/50 bg-background/70 backdrop-blur-xl">
<div class="mx-auto flex h-[4.25rem] max-w-6xl items-center justify-between gap-3 px-5 sm:px-8">
<RouterLink
to="/"
class="flex items-center gap-3 font-display text-lg font-semibold tracking-tight transition-opacity hover:opacity-80"
@click="closeMenu"
>
<span class="brand-mark flex size-9 items-center justify-center rounded-lg">
<Zap class="size-[18px]" />
</span>
<span>HubProxy</span>
</RouterLink>
<nav class="hidden items-center gap-1.5 md:flex">
<RouterLink
v-for="link in links"
:key="link.to"
:to="link.to"
class="inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-[15px] transition-colors duration-150"
:class="currentPath === link.to ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
>
<component :is="link.icon" class="size-4" />
{{ link.label }}
</RouterLink>
<ThemeToggle :is-dark="isDark" button-class="ml-1" @toggle="toggleTheme" />
</nav>
<div class="flex items-center gap-0.5 md:hidden">
<ThemeToggle :is-dark="isDark" @toggle="toggleTheme" />
<Button variant="ghost" size="icon" aria-label="菜单" @click="menuOpen = !menuOpen">
<Transition name="fade" mode="out-in">
<X v-if="menuOpen" key="x" class="size-4" />
<Menu v-else key="menu" class="size-4" />
</Transition>
</Button>
</div>
</div>
<Transition name="menu">
<div v-if="menuOpen" class="border-t border-border px-5 py-2 md:hidden">
<div class="flex flex-col gap-1">
<RouterLink
v-for="link in links"
:key="link.to"
:to="link.to"
class="inline-flex items-center gap-2 rounded-full px-3.5 py-2 text-[15px] transition-colors"
:class="currentPath === link.to ? 'bg-primary text-primary-foreground' : 'text-muted-foreground'"
@click="closeMenu"
>
<component :is="link.icon" class="size-4" />
{{ link.label }}
</RouterLink>
</div>
</div>
</Transition>
</header>
<main class="mx-auto w-full max-w-6xl flex-1 px-5 py-10 text-base sm:px-8 sm:py-16">
<slot />
</main>
<footer class="flex justify-center pb-10 pt-2">
<a
href="https://github.com/sky22333/hubproxy"
target="_blank"
rel="noopener noreferrer"
aria-label="GitHub"
class="text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<Github class="size-5" />
</a>
</footer>
</div>
</template>

View File

@@ -0,0 +1,19 @@
<script setup lang="ts">
defineProps<{
eyebrow: string
title: string
subtitle: string
gradient?: boolean
}>()
</script>
<template>
<header class="page-hero">
<p class="eyebrow">{{ eyebrow }}</p>
<h1 class="display-title" :class="{ 'gradient-text': gradient }">{{ title }}</h1>
<p class="mx-auto max-w-xl text-lg text-muted-foreground sm:text-xl">
{{ subtitle }}
</p>
<slot />
</header>
</template>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { Moon, Sun } from 'lucide-vue-next'
import Button from '@/components/ui/Button.vue'
import { cn } from '@/lib/utils'
defineProps<{
isDark: boolean
buttonClass?: HTMLAttributes['class']
}>()
const emit = defineEmits<{ toggle: [] }>()
</script>
<template>
<Button
variant="ghost"
size="icon"
aria-label="切换主题"
:class="cn(buttonClass)"
@click="emit('toggle')"
>
<Transition name="fade" mode="out-in">
<Sun v-if="isDark" key="sun" class="size-4" />
<Moon v-else key="moon" class="size-4" />
</Transition>
</Button>
</template>

View File

@@ -0,0 +1,45 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = withDefaults(
defineProps<{
variant?: 'default' | 'secondary' | 'outline' | 'ghost'
size?: 'default' | 'sm' | 'icon'
disabled?: boolean
class?: HTMLAttributes['class']
}>(),
{
variant: 'default',
size: 'default',
},
)
const variants: Record<NonNullable<typeof props.variant>, string> = {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
outline: 'border border-input bg-transparent hover:bg-accent hover:text-accent-foreground',
ghost: 'hover:bg-accent hover:text-accent-foreground text-muted-foreground',
}
const sizes: Record<NonNullable<typeof props.size>, string> = {
default: 'h-11 px-5 text-base',
sm: 'h-9 px-3 text-sm',
icon: 'size-11',
}
</script>
<template>
<button
type="button"
:disabled="disabled"
:class="cn(
'inline-flex items-center justify-center gap-1.5 rounded-lg font-medium outline-none transition-[opacity,transform,background-color,color] duration-150 ease-out active:scale-[0.98] focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50',
variants[variant],
sizes[size],
props.class,
)"
>
<slot />
</button>
</template>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const model = defineModel<string>({ default: '' })
const props = defineProps<{
class?: HTMLAttributes['class']
type?: string
id?: string
placeholder?: string
disabled?: boolean
}>()
</script>
<template>
<input
:id="id"
v-model="model"
:type="type || 'text'"
:placeholder="placeholder"
:disabled="disabled"
:class="cn(
'h-11 w-full rounded-lg border border-input bg-transparent px-3.5 text-base outline-none transition-[border-color,box-shadow] duration-150 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:opacity-50',
props.class,
)"
>
</template>

View File

@@ -0,0 +1,40 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const checked = defineModel<boolean>('checked', { default: false })
const props = defineProps<{
id?: string
class?: HTMLAttributes['class']
disabled?: boolean
}>()
function toggle() {
if (props.disabled) return
checked.value = !checked.value
}
</script>
<template>
<button
:id="id"
type="button"
role="switch"
:aria-checked="checked"
:disabled="disabled"
:class="cn(
'relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border border-transparent transition-colors duration-150 outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:opacity-50',
checked ? 'bg-primary' : 'bg-muted',
props.class,
)"
@click="toggle"
>
<span
:class="cn(
'pointer-events-none block size-4 rounded-full bg-background shadow-sm transition-transform duration-150 ease-out',
checked ? 'translate-x-[16px]' : 'translate-x-0.5',
)"
/>
</button>
</template>

View File

@@ -0,0 +1,26 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const model = defineModel<string>({ default: '' })
const props = defineProps<{
class?: HTMLAttributes['class']
id?: string
placeholder?: string
disabled?: boolean
}>()
</script>
<template>
<textarea
:id="id"
v-model="model"
:placeholder="placeholder"
:disabled="disabled"
:class="cn(
'min-h-36 w-full rounded-lg border border-input bg-transparent px-3.5 py-3 text-base outline-none transition-[border-color,box-shadow] duration-150 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40 disabled:opacity-50',
props.class,
)"
/>
</template>

View File

@@ -0,0 +1,29 @@
@font-face {
font-family: 'Syne';
font-style: normal;
font-display: swap;
font-weight: 600;
src: url('@fontsource/syne/files/syne-greek-600-normal.woff2') format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Syne';
font-style: normal;
font-display: swap;
font-weight: 600;
src: url('@fontsource/syne/files/syne-latin-ext-600-normal.woff2') format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304,
U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0,
U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Syne';
font-style: normal;
font-display: swap;
font-weight: 600;
src: url('@fontsource/syne/files/syne-latin-600-normal.woff2') format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304,
U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

80
web/src/lib/utils.ts Normal file
View File

@@ -0,0 +1,80 @@
import type { ClassValue } from 'clsx'
import { clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function formatNumber(num: number): string {
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)}B+`
if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M+`
if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K+`
return String(num)
}
export function formatSize(bytes?: number): string {
if (bytes == null || bytes <= 0) return ''
const units = ['B', 'KB', 'MB', 'GB']
let size = bytes
let i = 0
while (size >= 1024 && i < units.length - 1) {
size /= 1024
i++
}
return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`
}
export function formatArchs(
images?: Array<{ architecture?: string; os?: string; variant?: string }>,
): string[] {
if (!images?.length) return []
const seen = new Set<string>()
const out: string[] = []
for (const img of images) {
const arch = img.architecture?.trim()
if (!arch || arch === 'unknown') continue
const os = img.os?.trim()
let label = os && os !== 'unknown' ? `${os}/${arch}` : arch
if (img.variant) label += `/${img.variant}`
if (seen.has(label)) continue
seen.add(label)
out.push(label)
}
return out
}
export function formatTimeAgo(dateString?: string): string {
if (!dateString) return '未知时间'
const date = new Date(dateString)
if (Number.isNaN(date.getTime())) return '未知时间'
const diffMs = Math.abs(Date.now() - date.getTime())
const minutes = Math.floor(diffMs / 60_000)
const hours = Math.floor(diffMs / 3_600_000)
const days = Math.floor(diffMs / 86_400_000)
const months = Math.floor(days / 30)
const years = Math.floor(days / 365)
if (minutes < 1) return '刚刚'
if (minutes < 60) return `${minutes}分钟前`
if (hours < 24) return `${hours}小时前`
if (days < 7) return `${days}天前`
if (days < 30) return `${Math.floor(days / 7)}周前`
if (months < 12) return `${months}个月前`
if (years < 1) return '近1年'
return `${years}年前`
}
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text)
return true
} catch {
return false
}
}
export function errorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback
}

10
web/src/main.ts Normal file
View File

@@ -0,0 +1,10 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual'
}
createApp(App).use(router).mount('#app')

178
web/src/pages/HomePage.vue Normal file
View File

@@ -0,0 +1,178 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Check, Clipboard, Container, Link2, Rocket, Sparkles } from 'lucide-vue-next'
import Button from '@/components/ui/Button.vue'
import Input from '@/components/ui/Input.vue'
import PageHero from '@/components/PageHero.vue'
import { copyText } from '@/lib/utils'
const input = ref('')
const output = ref('')
const error = ref('')
const copied = ref(false)
const host = computed(() => window.location.host)
const features = [
{ icon: Rocket, label: 'GitHub 加速' },
{ icon: Container, label: 'Docker 镜像' },
{ icon: Sparkles, label: 'Hugging Face' },
] as const
const dockerExamples = computed(() => [
{
id: 'official',
label: '官方镜像',
original: 'docker pull nginx',
accelerated: `docker pull ${host.value}/nginx`,
},
{
id: 'user',
label: '用户镜像',
original: 'docker pull user/app:tag',
accelerated: `docker pull ${host.value}/user/app:tag`,
},
{
id: 'ghcr',
label: 'GHCR',
original: 'docker pull ghcr.io/org/app',
accelerated: `docker pull ${host.value}/ghcr.io/org/app`,
},
])
const allowedHosts = [
'github.com/',
'raw.githubusercontent.com/',
'gist.githubusercontent.com/',
'huggingface.co/',
'cdn-lfs.hf.co/',
]
function formatLink() {
error.value = ''
copied.value = false
const link = input.value.trim()
if (!link) {
error.value = '请输入有效的链接'
output.value = ''
return
}
if (link.startsWith('https://') || link.startsWith('http://')) {
output.value = `https://${host.value}/${link}`
return
}
if (allowedHosts.some((prefix) => link.startsWith(prefix))) {
output.value = `https://${host.value}/https://${link}`
return
}
error.value = '请输入有效的 GitHub / Hugging Face 链接'
output.value = ''
}
async function onCopy() {
if (!output.value) return
copied.value = await copyText(output.value)
}
function onOpen() {
if (!output.value) return
window.open(output.value, '_blank', 'noopener,noreferrer')
}
</script>
<template>
<div class="mx-auto max-w-3xl">
<PageHero
eyebrow="面向开发者和运维人员的加速服务"
title="HubProxy"
subtitle="GitHub 文件加速 · Docker 镜像加速 · Hugging Face 资源"
gradient
>
<div class="flex flex-wrap justify-center gap-2 pt-2">
<span
v-for="item in features"
:key="item.label"
class="feature-pill"
>
<component :is="item.icon" class="size-4" />
{{ item.label }}
</span>
</div>
</PageHero>
<section class="surface-panel field-block">
<div class="flex flex-col gap-3 sm:flex-row">
<Input
v-model="input"
class="sm:flex-1"
placeholder="粘贴 GitHub / Hugging Face 原始链接"
@keyup.enter="formatLink"
/>
<Button @click="formatLink">获取加速链接</Button>
</div>
<Transition name="fade" mode="out-in">
<p v-if="error" key="error" class="text-center text-destructive">{{ error }}</p>
<div v-else-if="output" key="output" class="space-y-4 pt-2">
<div class="flex items-center justify-center gap-2 font-medium text-primary">
<Check class="size-4" />
加速链接已生成
</div>
<p class="break-all rounded-lg border border-border bg-muted/40 px-4 py-3.5 font-mono">
{{ output }}
</p>
<div class="flex flex-wrap justify-center gap-2">
<Button variant="secondary" size="sm" @click="onCopy">
<Clipboard class="size-4" />
{{ copied ? '已复制' : '复制链接' }}
</Button>
<Button variant="secondary" size="sm" @click="onOpen">
<Link2 class="size-4" />
打开链接
</Button>
</div>
</div>
</Transition>
</section>
<section class="space-y-6 pt-12">
<div class="space-y-1 text-center">
<h2 class="text-sm font-semibold tracking-[0.16em] text-muted-foreground uppercase">
Docker 镜像加速
</h2>
<p class="text-muted-foreground">
在镜像名前加上本站域名一行命令即可加速拉取
</p>
</div>
<div class="terminal-block">
<div class="terminal-header">
<span class="terminal-dot" />
<span class="terminal-dot" />
<span class="terminal-dot" />
<span class="ml-2 text-xs text-muted-foreground">shell</span>
</div>
<div class="terminal-body">
<div
v-for="item in dockerExamples"
:key="item.id"
class="terminal-example"
>
<span class="example-tag">{{ item.label }}</span>
<p class="font-mono leading-relaxed">
<span class="text-muted-foreground">$ </span>
<span class="text-muted-foreground/70 line-through decoration-muted-foreground/40">{{ item.original }}</span>
</p>
<p class="font-mono leading-relaxed">
<span class="text-muted-foreground">$ </span>
<span class="text-primary">{{ item.accelerated }}</span>
</p>
</div>
</div>
</div>
</section>
</div>
</template>

View File

@@ -0,0 +1,176 @@
<script setup lang="ts">
import { ref } from 'vue'
import { Loader2 } from 'lucide-vue-next'
import {
fetchImageInfo,
prepareBatchDownload,
prepareSingleDownload,
triggerDownload,
} from '@/api'
import { errorMessage } from '@/lib/utils'
import Button from '@/components/ui/Button.vue'
import Input from '@/components/ui/Input.vue'
import PageHero from '@/components/PageHero.vue'
import Switch from '@/components/ui/Switch.vue'
import Textarea from '@/components/ui/Textarea.vue'
const singleImage = ref('')
const singlePlatform = ref('linux/amd64')
const singleCompressed = ref(true)
const singleStatus = ref('')
const singleError = ref('')
const singleLoading = ref(false)
const batchText = ref('')
const batchPlatform = ref('linux/amd64')
const batchCompressed = ref(true)
const batchStatus = ref('')
const batchError = ref('')
const batchLoading = ref(false)
async function preflight(images: string[]) {
for (const image of [...new Set(images)]) {
await fetchImageInfo(image)
}
}
async function onSingleSubmit() {
singleError.value = ''
singleStatus.value = ''
const image = singleImage.value.trim()
if (!image) {
singleError.value = '请输入镜像名称'
return
}
singleLoading.value = true
singleStatus.value = '正在准备下载...'
try {
await preflight([image])
const data = await prepareSingleDownload({
image,
platform: singlePlatform.value,
compressed: singleCompressed.value,
})
if (!data.download_url) throw new Error('下载地址生成失败')
triggerDownload(data.download_url)
const platformText = singlePlatform.value.trim()
? ` (${singlePlatform.value.trim()})`
: ''
singleStatus.value = `开始下载 ${image}${platformText}`
} catch (e) {
singleStatus.value = ''
singleError.value = errorMessage(e, '下载失败')
} finally {
singleLoading.value = false
}
}
async function onBatchSubmit() {
batchError.value = ''
batchStatus.value = ''
const images = batchText.value
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
if (images.length === 0) {
batchError.value = '请输入镜像列表'
return
}
batchLoading.value = true
batchStatus.value = '正在准备批量下载...'
try {
await preflight(images)
const data = await prepareBatchDownload({
images,
platform: batchPlatform.value,
useCompressedLayers: batchCompressed.value,
})
if (!data.download_url) throw new Error('下载地址生成失败')
triggerDownload(data.download_url)
batchStatus.value = `开始下载 ${images.length} 个镜像`
} catch (e) {
batchStatus.value = ''
batchError.value = errorMessage(e, '下载失败')
} finally {
batchLoading.value = false
}
}
</script>
<template>
<div class="mx-auto max-w-3xl">
<PageHero
eyebrow="Offline Image"
title="离线镜像"
subtitle="流式下载,兼容 docker load支持多架构。"
/>
<section class="field-block">
<h2 class="text-center text-sm font-semibold tracking-[0.16em] text-muted-foreground uppercase">
单镜像
</h2>
<Transition name="fade" mode="out-in">
<p v-if="singleError" key="error" class="text-center text-destructive">{{ singleError }}</p>
<p v-else-if="singleStatus" key="status" class="flex items-center justify-center gap-2 text-muted-foreground">
<Loader2 v-if="singleLoading" class="size-4 animate-spin" />
{{ singleStatus }}
</p>
</Transition>
<label class="block space-y-1.5">
<span>镜像名称</span>
<Input v-model="singleImage" placeholder="nginx 或 user/app:tag" />
</label>
<label class="block space-y-1.5">
<span>目标架构可选</span>
<Input v-model="singlePlatform" placeholder="linux/amd64" />
</label>
<div class="flex items-center justify-between py-1">
<span>压缩层</span>
<Switch v-model:checked="singleCompressed" />
</div>
<Button class="w-full" :disabled="singleLoading" @click="onSingleSubmit">
<Loader2 v-if="singleLoading" class="size-4 animate-spin" />
{{ singleLoading ? '准备中...' : '立即下载' }}
</Button>
</section>
<section class="section-gap field-block">
<h2 class="text-center text-sm font-semibold tracking-[0.16em] text-muted-foreground uppercase">
批量下载
</h2>
<Transition name="fade" mode="out-in">
<p v-if="batchError" key="error" class="text-center text-destructive">{{ batchError }}</p>
<p v-else-if="batchStatus" key="status" class="flex items-center justify-center gap-2 text-muted-foreground">
<Loader2 v-if="batchLoading" class="size-4 animate-spin" />
{{ batchStatus }}
</p>
</Transition>
<label class="block space-y-1.5">
<span>镜像列表</span>
<Textarea
v-model="batchText"
placeholder="alpine&#10;redis:alpine&#10;user/app:1.0"
/>
</label>
<label class="block space-y-1.5">
<span>目标架构可选</span>
<Input v-model="batchPlatform" placeholder="linux/amd64" />
</label>
<div class="flex items-center justify-between py-1">
<span>压缩层</span>
<Switch v-model:checked="batchCompressed" />
</div>
<Button class="w-full" :disabled="batchLoading" @click="onBatchSubmit">
<Loader2 v-if="batchLoading" class="size-4 animate-spin" />
{{ batchLoading ? '准备中...' : '批量下载' }}
</Button>
</section>
</div>
</template>

View File

@@ -0,0 +1,400 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ChevronLeft, ChevronRight, Copy, Loader2, Search } from 'lucide-vue-next'
import {
fetchTags,
searchImages,
type Repository,
type TagInfo,
} from '@/api'
import { copyText, errorMessage, formatArchs, formatNumber, formatSize, formatTimeAgo } from '@/lib/utils'
import Button from '@/components/ui/Button.vue'
import Input from '@/components/ui/Input.vue'
import PageHero from '@/components/PageHero.vue'
interface RepoView {
raw: Repository
displayName: string
namespace: string
name: string
fullRepoName: string
}
const route = useRoute()
const router = useRouter()
const query = ref('')
const searching = ref(false)
const searchError = ref('')
const results = ref<RepoView[]>([])
const resultCount = ref(0)
const resultsPage = ref(1)
const pageSize = 25
const selected = ref<RepoView | null>(null)
const tagsLoading = ref(false)
const tagsError = ref('')
const tags = ref<TagInfo[]>([])
const tagFilter = ref('')
const tagsPage = ref(1)
const tagsHasMore = ref(false)
const copyHint = ref('')
const host = computed(() => window.location.host)
const hasResults = computed(() => results.value.length > 0)
const totalPages = computed(() => Math.max(1, Math.ceil(resultCount.value / pageSize)))
const hasMoreResults = computed(() => resultsPage.value < totalPages.value)
const filteredTags = computed(() => {
const q = tagFilter.value.trim().toLowerCase()
if (!q) return tags.value
const exact: TagInfo[] = []
const starts: TagInfo[] = []
const includes: TagInfo[] = []
for (const tag of tags.value) {
const name = tag.name.toLowerCase()
if (name === q) exact.push(tag)
else if (name.startsWith(q)) starts.push(tag)
else if (name.includes(q)) includes.push(tag)
}
return [...exact, ...starts, ...includes]
})
const displayTags = computed(() =>
filteredTags.value.map((tag) => ({
tag,
archs: formatArchs(tag.images),
size: formatSize(tag.full_size),
})),
)
function toRepoView(item: Repository): RepoView | null {
const rawName = item.repo_name || ''
const namespace =
item.namespace ||
(item.is_official ? 'library' : rawName.includes('/') ? rawName.split('/')[0] : '')
const name = rawName.replace(/^library\//, '').includes('/')
? rawName.split('/').pop() || ''
: rawName.replace(/^library\//, '')
if (!namespace || !name) return null
const displayName = item.is_official
? name
: item.namespace
? `${item.namespace}/${name}`
: rawName.includes('/')
? rawName
: `${namespace}/${name}`
return {
raw: item,
displayName,
namespace,
name,
fullRepoName: item.is_official ? name : `${namespace}/${name}`,
}
}
async function runSearch(q: string, page = 1) {
const trimmed = q.trim()
if (!trimmed) {
searchError.value = '请输入搜索关键词'
return
}
searching.value = true
searchError.value = ''
results.value = []
selected.value = null
tags.value = []
tagsError.value = ''
tagFilter.value = ''
try {
let searchQuery = trimmed
let targetRepo = ''
if (trimmed.includes('/')) {
const [ns] = trimmed.split('/')
searchQuery = ns
targetRepo = trimmed.toLowerCase()
}
const data = await searchImages(searchQuery, page, pageSize)
const views = (data.results || [])
.map(toRepoView)
.filter((v): v is RepoView => v !== null)
views.sort((a, b) => {
if (targetRepo) {
const aMatch =
a.displayName.toLowerCase() === targetRepo ||
a.fullRepoName.toLowerCase() === targetRepo
const bMatch =
b.displayName.toLowerCase() === targetRepo ||
b.fullRepoName.toLowerCase() === targetRepo
if (aMatch && !bMatch) return -1
if (!aMatch && bMatch) return 1
}
if (!!a.raw.is_official !== !!b.raw.is_official) {
return a.raw.is_official ? -1 : 1
}
return (b.raw.pull_count || 0) - (a.raw.pull_count || 0)
})
results.value = views
resultCount.value = data.count ?? views.length
resultsPage.value = page
if (views.length === 0) searchError.value = '未找到相关镜像'
} catch (e) {
searchError.value = errorMessage(e, '搜索失败')
} finally {
searching.value = false
}
}
async function onSearch() {
const q = query.value.trim()
await router.replace({ path: '/search', query: q ? { q } : {} })
await runSearch(q, 1)
}
async function loadResultsPage(page: number) {
if (page < 1 || page > totalPages.value || searching.value) return
await runSearch(query.value, page)
window.scrollTo(0, 0)
}
async function loadTagPage(repo: RepoView, page: number) {
selected.value = repo
tagsLoading.value = true
tagsError.value = ''
tagsPage.value = page
if (page === 1) tagFilter.value = ''
try {
const data = await fetchTags(repo.namespace, repo.name, page, 100)
tags.value = data.tags || []
tagsHasMore.value = !!data.has_more
if (tags.value.length === 0) tagsError.value = '该镜像暂无可用标签'
} catch (e) {
tags.value = []
tagsError.value = errorMessage(e, '加载标签失败')
} finally {
tagsLoading.value = false
}
}
function backToResults() {
selected.value = null
tags.value = []
tagsError.value = ''
tagFilter.value = ''
}
async function copyPull(tagName?: string) {
if (!selected.value) return
const image = tagName
? `${host.value}/${selected.value.fullRepoName}:${tagName}`
: `${host.value}/${selected.value.fullRepoName}`
const refName = `docker pull ${image}`
const ok = await copyText(refName)
copyHint.value = ok ? `已复制 ${refName}` : '复制失败'
setTimeout(() => {
if (copyHint.value.includes(refName) || copyHint.value === '复制失败') copyHint.value = ''
}, 2000)
}
watch(
() => route.query.q,
async (q) => {
const next = typeof q === 'string' ? q : ''
if (next === query.value) return
query.value = next
if (next) await runSearch(next, 1)
},
{ immediate: true },
)
</script>
<template>
<div>
<PageHero
eyebrow="Docker Hub"
title="镜像搜索"
subtitle="检索官方与社区镜像,查看标签与架构,一键复制拉取命令。"
/>
<Transition name="fade" mode="out-in">
<div v-if="!selected" key="search" class="mx-auto max-w-3xl space-y-6">
<div class="flex flex-col gap-3 sm:flex-row">
<Input
v-model="query"
class="sm:flex-1"
placeholder="例如 nginx、redis、library/ubuntu"
@keydown.enter="onSearch"
/>
<Button :disabled="searching" @click="onSearch">
<Loader2 v-if="searching" class="size-4 animate-spin" />
<Search v-else class="size-4" />
{{ searching ? '搜索中...' : '搜索' }}
</Button>
</div>
<p
v-if="searchError"
class="text-center text-destructive"
>
{{ searchError }}
</p>
<div v-if="searching" class="space-y-3">
<div v-for="i in 3" :key="i" class="h-16 animate-pulse rounded-xl bg-muted" />
</div>
<div v-else-if="hasResults" class="space-y-2">
<p class="text-center text-muted-foreground">
{{ resultCount }} 条结果
<template v-if="totalPages > 1"> · {{ resultsPage }} / {{ totalPages }} </template>
</p>
<div class="divide-y divide-border border-y border-border">
<button
v-for="item in results"
:key="`${item.namespace}/${item.name}`"
type="button"
class="w-full py-4 text-left transition-colors duration-150 hover:text-primary"
@click="loadTagPage(item, 1)"
>
<div class="mb-1 flex flex-wrap items-center gap-2">
<span class="text-base font-medium">{{ item.displayName }}</span>
<span
v-if="item.raw.is_official"
class="rounded-full bg-primary/12 px-2 py-0.5 text-[11px] text-primary"
>官方</span>
<span
v-if="item.raw.star_count"
class="text-xs text-muted-foreground"
> {{ formatNumber(item.raw.star_count) }}</span>
<span
v-if="item.raw.pull_count"
class="text-xs text-muted-foreground"
> {{ formatNumber(item.raw.pull_count) }}</span>
</div>
<p class="line-clamp-2 text-muted-foreground">
{{ item.raw.short_description || '暂无描述' }}
</p>
</button>
</div>
<div v-if="totalPages > 1" class="flex items-center justify-center gap-1.5 pt-2">
<Button
variant="outline"
size="sm"
:disabled="searching || resultsPage <= 1"
@click="loadResultsPage(resultsPage - 1)"
>
<ChevronLeft class="size-4" />
</Button>
<span class="min-w-14 text-center text-muted-foreground"> {{ resultsPage }} </span>
<Button
variant="outline"
size="sm"
:disabled="searching || !hasMoreResults"
@click="loadResultsPage(resultsPage + 1)"
>
<ChevronRight class="size-4" />
</Button>
</div>
</div>
</div>
<div v-else key="tags" class="mx-auto max-w-3xl space-y-6">
<button
type="button"
class="text-muted-foreground transition-colors hover:text-primary"
@click="backToResults"
>
返回搜索结果
</button>
<div class="space-y-2 text-center">
<div class="flex flex-wrap items-center justify-center gap-2">
<h2 class="text-2xl font-semibold tracking-tight sm:text-3xl">{{ selected.fullRepoName }}</h2>
<span
v-if="selected.raw.is_official"
class="rounded-full bg-primary/12 px-2 py-0.5 text-[11px] text-primary"
>官方</span>
</div>
<p class="text-base text-muted-foreground">
{{ selected.raw.short_description || '暂无描述' }}
</p>
<Transition name="fade">
<p v-if="copyHint" class="text-muted-foreground">{{ copyHint }}</p>
</Transition>
</div>
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
<Input v-model="tagFilter" class="sm:flex-1" placeholder="筛选当前页标签..." />
<div class="flex items-center gap-1.5">
<Button
variant="outline"
size="sm"
:disabled="tagsLoading || tagsPage <= 1"
@click="loadTagPage(selected, tagsPage - 1)"
>
<ChevronLeft class="size-4" />
</Button>
<span class="min-w-14 text-center text-muted-foreground"> {{ tagsPage }} </span>
<Button
variant="outline"
size="sm"
:disabled="tagsLoading || !tagsHasMore"
@click="loadTagPage(selected, tagsPage + 1)"
>
<ChevronRight class="size-4" />
</Button>
<Button variant="outline" size="sm" @click="copyPull()">
<Copy class="size-4" />
复制
</Button>
</div>
</div>
<p v-if="tagsError" class="text-center text-destructive">{{ tagsError }}</p>
<div v-else-if="tagsLoading" class="space-y-3">
<div v-for="i in 5" :key="i" class="h-14 animate-pulse rounded-xl bg-muted" />
</div>
<p v-else-if="displayTags.length === 0" class="text-center text-muted-foreground">
没有匹配的标签
</p>
<div v-else class="divide-y divide-border border-y border-border">
<div
v-for="{ tag, archs, size } in displayTags"
:key="tag.name"
class="flex items-start justify-between gap-3 py-4"
>
<div class="min-w-0 space-y-1.5">
<p class="truncate text-base font-medium">{{ tag.name }}</p>
<p class="text-xs text-muted-foreground">
<template v-if="size">{{ size }} · </template>
{{ formatTimeAgo(tag.last_updated) }}
</p>
<div v-if="archs.length" class="flex flex-wrap gap-1.5">
<span
v-for="arch in archs"
:key="arch"
class="rounded-full bg-primary/10 px-2 py-0.5 font-mono text-[11px] text-primary"
>{{ arch }}</span>
</div>
</div>
<Button variant="outline" size="sm" class="shrink-0" @click="copyPull(tag.name)">
<Copy class="size-4" />
复制
</Button>
</div>
</div>
</div>
</Transition>
</div>
</template>

37
web/src/router/index.ts Normal file
View File

@@ -0,0 +1,37 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/pages/HomePage.vue'
import ImagesPage from '@/pages/ImagesPage.vue'
import SearchPage from '@/pages/SearchPage.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
component: HomePage,
meta: { title: 'GitHub 加速' },
},
{
path: '/images',
component: ImagesPage,
meta: { title: '离线镜像下载' },
},
{
path: '/search',
component: SearchPage,
meta: { title: '镜像搜索' },
},
],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) return savedPosition
if (to.path !== from.path) return { top: 0, left: 0 }
return false
},
})
router.afterEach((to) => {
const title = (to.meta.title as string) || 'HubProxy'
document.title = `${title} · HubProxy`
})
export default router

233
web/src/style.css Normal file
View File

@@ -0,0 +1,233 @@
@import "tailwindcss";
@import "@fontsource-variable/manrope";
@import "./fonts/syne-600.woff2.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-sans: "Manrope Variable", "Manrope", ui-sans-serif, system-ui, sans-serif;
--font-display: "Syne", "Manrope Variable", ui-sans-serif, system-ui, sans-serif;
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--radius-lg: var(--radius);
}
:root {
--radius: 0.75rem;
--background: oklch(0.985 0.004 260);
--foreground: oklch(0.2 0.02 260);
--primary: oklch(0.46 0.14 264);
--primary-foreground: oklch(0.99 0.005 264);
--secondary: oklch(0.945 0.012 260);
--secondary-foreground: oklch(0.28 0.03 260);
--muted: oklch(0.955 0.008 260);
--muted-foreground: oklch(0.48 0.025 260);
--accent: oklch(0.94 0.015 260);
--accent-foreground: oklch(0.26 0.03 260);
--destructive: oklch(0.55 0.2 25);
--border: oklch(0.9 0.01 260);
--input: oklch(0.9 0.01 260);
--ring: oklch(0.46 0.14 264);
}
.dark {
--background: oklch(0.16 0.015 260);
--foreground: oklch(0.96 0.008 260);
--primary: oklch(0.72 0.11 264);
--primary-foreground: oklch(0.16 0.02 260);
--secondary: oklch(0.24 0.02 260);
--secondary-foreground: oklch(0.94 0.008 260);
--muted: oklch(0.24 0.02 260);
--muted-foreground: oklch(0.68 0.025 260);
--accent: oklch(0.26 0.025 260);
--accent-foreground: oklch(0.94 0.008 260);
--destructive: oklch(0.65 0.17 22);
--border: oklch(1 0 0 / 11%);
--input: oklch(1 0 0 / 14%);
--ring: oklch(0.72 0.11 264);
}
@layer base {
* {
@apply border-border;
}
html {
scrollbar-width: none;
-ms-overflow-style: none;
}
html::-webkit-scrollbar {
display: none;
}
body {
@apply bg-background text-foreground font-sans antialiased;
}
}
@layer components {
.shell-atmosphere {
position: relative;
isolation: isolate;
overflow-x: clip;
}
.shell-atmosphere::before {
content: "";
pointer-events: none;
position: fixed;
inset: 0;
z-index: -2;
background:
radial-gradient(ellipse 70% 45% at 50% -15%, oklch(0.72 0.06 264 / 0.12), transparent 60%),
linear-gradient(180deg, var(--background), oklch(0.975 0.006 260));
}
.dark .shell-atmosphere::before {
background:
radial-gradient(ellipse 65% 40% at 50% -10%, oklch(0.45 0.08 264 / 0.18), transparent 55%),
linear-gradient(180deg, var(--background), oklch(0.14 0.015 260));
}
.brand-mark {
@apply bg-primary/10 text-primary dark:bg-primary/15;
}
.eyebrow {
@apply mb-3 text-[11px] font-semibold tracking-[0.22em] text-primary uppercase;
}
.page-hero {
@apply relative mb-14 space-y-4 pb-12 text-center sm:mb-16 sm:pb-14;
}
.page-hero::after {
content: "";
position: absolute;
left: 50%;
bottom: 0;
width: min(8rem, 32%);
height: 2px;
transform: translateX(-50%);
border-radius: 999px;
background: var(--border);
}
.display-title {
font-family: var(--font-display);
@apply text-5xl font-semibold tracking-tight sm:text-6xl;
}
.gradient-text {
background: linear-gradient(135deg, var(--foreground) 30%, var(--primary) 100%);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.feature-pill {
@apply inline-flex items-center gap-2 rounded-full border border-border bg-background/60 px-3.5 py-1.5 text-sm text-muted-foreground backdrop-blur-sm;
}
.surface-panel {
@apply rounded-xl border border-border/80 bg-background/50 p-5 backdrop-blur-sm;
}
.terminal-block {
@apply overflow-hidden rounded-xl border border-border/80 bg-background/50 backdrop-blur-sm;
}
.terminal-header {
@apply flex items-center gap-1.5 border-b border-border/70 px-4 py-2.5;
}
.terminal-dot {
@apply size-2 rounded-full bg-border;
}
.terminal-body {
@apply space-y-0 px-4 py-3;
}
.terminal-example {
@apply space-y-1 py-3;
}
.terminal-example + .terminal-example {
@apply border-t border-border/60;
}
.example-tag {
@apply mb-1 inline-block rounded-md bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary;
}
.section-gap {
@apply space-y-8 border-t border-border pt-12;
}
.field-block {
@apply space-y-4;
}
}
.page-enter-active {
transition: opacity 150ms cubic-bezier(0.22, 1, 0.36, 1);
}
.page-enter-from {
opacity: 0;
}
.fade-enter-active,
.fade-leave-active {
transition:
opacity 180ms cubic-bezier(0.22, 1, 0.36, 1),
transform 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
transform: translateY(4px);
}
.menu-enter-active,
.menu-leave-active {
transition:
opacity 160ms cubic-bezier(0.22, 1, 0.36, 1),
transform 160ms cubic-bezier(0.22, 1, 0.36, 1);
}
.menu-enter-from,
.menu-leave-to {
opacity: 0;
transform: translateY(-4px);
}
@media (prefers-reduced-motion: reduce) {
.page-enter-active,
.fade-enter-active,
.fade-leave-active,
.menu-enter-active,
.menu-leave-active {
transition: none !important;
}
.page-enter-from,
.fade-enter-from,
.fade-leave-to,
.menu-enter-from,
.menu-leave-to {
opacity: 1;
transform: none;
}
}