feat: add mirror help pages and interactive Debian configuration

This commit is contained in:
2026-11-02 00:33:40 +08:00
parent 8ec5e4e324
commit 70e9f9b884
24 changed files with 691 additions and 18 deletions
+8
View File
@@ -47,6 +47,14 @@ go -C backend build -o ../.local/mirrorouc .
默认监听 `127.0.0.1:8081`,可通过 `-listen` 修改。首页为 `/`,公告页为 `/announcements`,管理后台为 `/admin`,同步状态页为 `/status`。数据库与上传文件保存在 `data/`,更新时保留该目录。
镜像使用帮助位于 `/help/<源名>/`,在后台“镜像与任务”的“展示信息”中使用 Markdown 编辑。所有界面语言使用同一份中文帮助文章;未填写文章的镜像不显示帮助按钮。
帮助正文可插入交互式 Debian 配置块,`format` 使用 `list`(传统格式)或 `deb822`:
```mirror-config
{"type":"debian","format":"list"}
```
镜像目录与下载由已有的 Web 服务器提供,路径为 `/mirrors/<源名>/`。自定义目录页的 Fancyindex 模板随前端构建生成在 `dist/fancy-index/` 中。
需要本机监控采集或受限配置写入时,可按需对接 `backend/tools/` 中的工具。更多启动参数可通过 `./mirrorouc -help` 查看。
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"errors"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
)
type helpArticle struct {
Name string `json:"name"`
Description Localized `json:"description"`
Website string `json:"website"`
BrowseURL string `json:"browseUrl"`
Body string `json:"body,omitempty"`
}
func publishedHelp(meta MirrorMetadata) bool {
return meta.Visible && strings.TrimSpace(meta.Help) != ""
}
func helpContent(meta MirrorMetadata, body bool) helpArticle {
article := helpArticle{Name: meta.Name, Description: meta.Description, Website: meta.Website, BrowseURL: "/mirrors/" + meta.Name + "/"}
if body {
article.Body = meta.Help
}
return article
}
func (a *App) findHelp(name string) (MirrorMetadata, error) {
var meta MirrorMetadata
if !validName(name) {
return meta, errMissing
}
record, err := a.record("mirrors", name)
if err != nil {
return meta, err
}
if err := decodeData(record.Data, &meta); err != nil {
return meta, err
}
if meta.Name != name || !publishedHelp(meta) {
return meta, errMissing
}
return meta, nil
}
func (a *App) helpIndex(w http.ResponseWriter, r *http.Request) {
records, err := a.records("mirrors")
if err != nil {
a.internal(w, err)
return
}
articles := []helpArticle{}
for _, record := range records {
var meta MirrorMetadata
if decodeData(record.Data, &meta) == nil && validName(meta.Name) && meta.Name == record.ID && publishedHelp(meta) {
articles = append(articles, helpContent(meta, false))
}
}
sort.Slice(articles, func(i, j int) bool { return articles[i].Name < articles[j].Name })
respond(w, 200, articles)
}
func (a *App) helpArticle(w http.ResponseWriter, r *http.Request) {
meta, err := a.findHelp(r.PathValue("name"))
if errors.Is(err, errMissing) {
fail(w, 404, "NOT_FOUND")
return
}
if err != nil {
a.internal(w, err)
return
}
respond(w, 200, helpContent(meta, true))
}
func (a *App) helpPage(w http.ResponseWriter, r *http.Request) {
path := strings.TrimSuffix(r.URL.Path, "/")
index := filepath.Join(a.cfg.Static, "index.html")
w.Header().Set("Cache-Control", "no-cache")
if path == "/help" {
http.ServeFile(w, r, index)
return
}
_, err := a.findHelp(strings.TrimPrefix(path, "/help/"))
if err == nil {
http.ServeFile(w, r, index)
return
}
if !errors.Is(err, errMissing) {
a.internal(w, err)
return
}
// Return the application for a friendly error page while retaining a real 404.
raw, err := os.ReadFile(index)
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusNotFound)
if r.Method != http.MethodHead {
w.Write(raw)
}
}
+88
View File
@@ -0,0 +1,88 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func TestPublishedHelpAndDeepLinks(t *testing.T) {
c := fixture(t)
article := MirrorMetadata{Name: "alpine", Description: Localized{"zh-CN": "软件仓库"}, Help: "## 配置软件源\n\n```sh\napk update\n```", Category: "os", Visible: true, Website: "https://alpinelinux.org/"}
for _, meta := range []MirrorMetadata{
article,
{Name: "hidden", Help: "private draft", Category: "os", Visible: false},
{Name: "empty", Help: " \n\t", Category: "os", Visible: true},
} {
if _, err := c.app.saveRecord("mirrors", meta.Name, meta, 0); err != nil {
t.Fatal(err)
}
}
// Reading saved help does not depend on a successful live tunasync poll.
c.app.jobsMu.Lock()
c.app.jobs = nil
c.app.jobsError = "MANAGER_UNAVAILABLE"
c.app.jobsMu.Unlock()
response := c.call("GET", "/api/v1/help", nil, false)
status(t, response, 200)
var index []helpArticle
if err := json.Unmarshal(response.Body.Bytes(), &index); err != nil || len(index) != 1 || index[0].Name != "alpine" || index[0].Body != "" {
t.Fatal("help index leaked hidden content or included unpublished articles")
}
response = c.call("GET", "/api/v1/help/alpine", nil, false)
status(t, response, 200)
var result helpArticle
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Body != article.Help || result.BrowseURL != "/mirrors/alpine/" {
t.Fatal("help endpoint did not preserve the shared Chinese Markdown")
}
for _, name := range []string{"hidden", "empty", "missing", "bad%2Fname"} {
status(t, c.call("GET", "/api/v1/help/"+name, nil, false), 404)
}
const html = "<!doctype html><title>MirrorOUC help</title>"
if err := os.WriteFile(filepath.Join(c.app.cfg.Static, "index.html"), []byte(html), 0600); err != nil {
t.Fatal(err)
}
for _, path := range []string{"/help", "/help/", "/help/alpine", "/help/alpine/"} {
response = c.call("GET", path, nil, false)
status(t, response, 200)
if response.Body.String() != html {
t.Fatal("refreshing a help deep link did not serve the application")
}
status(t, c.call("HEAD", path, nil, false), 200)
}
for _, path := range []string{"/help/hidden/", "/help/empty/", "/help/missing/", "/help/alpine/extra"} {
response = c.call("GET", path, nil, false)
status(t, response, 404)
if response.Body.String() != html || !strings.HasPrefix(response.Header().Get("Content-Type"), "text/html") {
t.Fatal("missing help should retain a real 404 and display the application error page")
}
response = c.call("HEAD", path, nil, false)
status(t, response, 404)
if response.Body.Len() != 0 {
t.Fatal("HEAD returned a response body")
}
}
status(t, c.call("POST", "/help/alpine/", nil, false), 405)
status(t, c.call("GET", "/helpful", nil, false), 404)
}
func TestHelpPublicationUsesMirrorEditorAndPermissions(t *testing.T) {
c := fixture(t)
meta := MirrorMetadata{Name: "alpine", Help: "## 安装\n\n中文说明。", Category: "os", Visible: true}
c.login("admin")
status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 0, "data": meta}, true), 200)
status(t, c.call("GET", "/api/v1/help/alpine", nil, false), 200)
c.login("editor")
status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 1, "data": meta}, true), 403)
c.login("admin")
meta.Help = ""
status(t, c.call("PUT", "/api/v1/admin/records/mirrors/alpine", map[string]any{"revision": 1, "data": meta}, true), 200)
status(t, c.call("GET", "/api/v1/help/alpine", nil, false), 404)
response := c.call("GET", "/api/v1/help", nil, false)
status(t, response, 200)
if strings.TrimSpace(response.Body.String()) != "[]" {
t.Fatal("clearing help did not remove its public entry")
}
}
+6
View File
@@ -104,6 +104,8 @@ func (a *App) handler() http.Handler {
})
mux.HandleFunc("GET /api/v1/public", a.public)
mux.HandleFunc("GET /api/v1/announcements", a.announcements)
mux.HandleFunc("GET /api/v1/help", a.helpIndex)
mux.HandleFunc("GET /api/v1/help/{name}", a.helpArticle)
mux.HandleFunc("GET /api/v1/monitoring", a.monitoring)
mux.HandleFunc("GET /api/v1/job-speeds", a.jobSpeeds)
mux.HandleFunc("POST /api/v1/auth/login", a.login)
@@ -141,6 +143,10 @@ func (a *App) handler() http.Handler {
return
}
path := r.URL.Path
if path == "/help" || strings.HasPrefix(path, "/help/") {
a.helpPage(w, r)
return
}
if path == "/" || path == "/status" || path == "/status/" || path == "/announcements" || path == "/announcements/" || path == "/admin" || strings.HasPrefix(path, "/admin/") {
http.ServeFile(w, r, filepath.Join(a.cfg.Static, "index.html"))
return
+2
View File
@@ -12,6 +12,8 @@
"preview": "vite preview --host 127.0.0.1",
"check:i18n": "node scripts/check-locales.ts",
"check:monitoring": "node scripts/check-monitoring.ts",
"check:help": "node scripts/check-help.ts",
"check:debian": "node scripts/check-debian-sources.ts",
"check:directory": "node scripts/check-directory.ts"
},
"dependencies": {
+53
View File
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict'
import { marked } from 'marked'
import { debianReleases, debianSources, type DebianSourceOptions } from '../src/debian-sources.ts'
import { helpBlocks } from '../src/help-content.ts'
const origin = 'https://mirrors.example.edu'
const base: DebianSourceOptions = { origin, release: 'trixie', format: 'list', sources: false, nonFree: true, securityMirror: false }
const defaultList = debianSources(base)
assert.ok(defaultList.includes('deb https://mirrors.example.edu/mirrors/debian/ trixie main contrib non-free non-free-firmware\n'))
assert.ok(defaultList.includes('deb https://security.debian.org/debian-security trixie-security'))
assert.ok(defaultList.includes('# deb-src https://mirrors.example.edu/mirrors/debian/ trixie '))
let cases = 0
for (const release of debianReleases) for (const format of ['list', 'deb822'] as const) for (const sources of [false, true]) for (const nonFree of [false, true]) for (const securityMirror of [false, true]) {
const value = debianSources({ origin, release: release.id, format, sources, nonFree, securityMirror })
assert.ok(!/undefined|NaN|trusted=yes|allow-insecure|testing-security|sid-security/.test(value))
assert.equal(value.includes('non-free-firmware'), nonFree && release.firmware)
assert.equal(value.includes('contrib non-free'), nonFree)
assert.equal(value.includes(`${release.id}-updates`), release.stable)
assert.equal(value.includes(`${release.id}-backports`), release.backports)
assert.equal(value.includes(`${release.id}-security`), release.stable)
if (release.stable) {
assert.equal(value.includes('https://mirrors.example.edu/mirrors/debian-security/'), securityMirror)
assert.equal(value.includes('https://security.debian.org/debian-security'), !securityMirror)
}
if (format === 'list') {
assert.equal(value.split('\n').some(line => line.startsWith('deb-src ')), sources)
assert.ok(value.split('\n').every(line => !line || /^(?:# )?deb(?:-src)? https:\/\/\S+ \S+ main(?: contrib non-free(?: non-free-firmware)?)?$/.test(line)))
} else {
for (const stanza of value.trim().split('\n\n')) {
const fields = Object.fromEntries(stanza.split('\n').map(line => line.split(/: (.*)/s).slice(0, 2)))
assert.equal(fields.Types, sources ? 'deb deb-src' : 'deb')
assert.equal(fields['Signed-By'], '/usr/share/keyrings/debian-archive-keyring.gpg')
assert.ok(fields.URIs && fields.Suites && fields.Components)
}
}
cases++
}
assert.ok(debianSources({ ...base, origin: 'http://100.69.2.2:8080/path?ignored=true' }).includes('http://100.69.2.2:8080/mirrors/debian/'))
assert.throws(() => debianSources({ ...base, origin: 'javascript:alert(1)' }))
assert.throws(() => debianSources({ ...base, origin: 'https://secret:password@example.edu' }))
assert.throws(() => debianSources({ ...base, release: 'unknown' as DebianSourceOptions['release'] }))
const fence = (data: string) => '```mirror-config\n' + data + '\n```\n'
const source = '## 配置\n\n[Debian][official]\n\n' + fence('{"type":"debian","format":"list"}') + '\n## 新格式\n\n' + fence('{"type":"debian","format":"deb822"}') + '\n[official]: https://www.debian.org/\n'
const blocks = helpBlocks(source)
assert.deepEqual(blocks.filter(block => block.kind === 'debian'), [{ kind: 'debian', format: 'list' }, { kind: 'debian', format: 'deb822' }])
assert.ok(blocks.filter(block => block.kind === 'markdown').map(block => marked.parser(block.tokens)).join('').includes('href="https://www.debian.org/"'), 'Reference-style Markdown links must survive widget insertion')
for (const data of ['not JSON', '{"type":"shell","format":"list"}', '{"type":"debian","format":"other"}', '{"type":"debian","format":"list","script":"alert(1)"}', 'null']) {
assert.ok(helpBlocks(fence(data)).every(block => block.kind === 'markdown'), 'Invalid or unsupported blocks must remain ordinary Markdown code')
}
assert.ok(helpBlocks('````markdown\n' + fence('{"type":"debian","format":"list"}') + '````\n').every(block => block.kind === 'markdown'), 'A quoted code example must not instantiate a live widget')
console.log(`Debian help check passed: ${cases} option combinations, release-specific suites, official security defaults, DEB822 fields, widget parsing and Markdown links.`)
+13
View File
@@ -0,0 +1,13 @@
import assert from 'node:assert/strict'
import { helpRoute, helpUrl } from '../src/help.ts'
for (const name of ['ubuntu', 'debian-cd', 'AOSP', 'gcc.git', 'archlinuxcn', 'test+repo']) {
const url = helpUrl(name)
assert.deepEqual(helpRoute(url), { active: true, name, invalid: false })
assert.deepEqual(helpRoute(url.slice(0, -1)), { active: true, name, invalid: false })
}
for (const path of ['/help', '/help/']) assert.deepEqual(helpRoute(path), { active: true, name: null, invalid: false })
for (const path of ['/', '/helpful', '/announcements']) assert.equal(helpRoute(path).active, false)
for (const path of ['/help/../', '/help/ubuntu/extra', '/help/%2fsecret', '/help/%zz', '/help/%252fsecret']) assert.equal(helpRoute(path).invalid, true)
assert.equal(helpUrl('a/b?c#d'), '/help/a%2Fb%3Fc%23d/')
console.log('Help check passed: index and deep links, case-sensitive names, encoded identifiers and malformed paths.')
+16 -12
View File
@@ -2,7 +2,7 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
ArrowRight, ArrowUpRight, BookOpen, Check,
ArrowRight, ArrowUpRight, CircleHelp, Check,
ExternalLink, Menu, Monitor, Moon,
Search, Sun, X,
} from 'lucide-vue-next'
@@ -11,10 +11,11 @@ import LanguagePicker from './components/LanguagePicker.vue'
import StatusPage from './components/StatusPage.vue'
import AdminPage from './components/AdminPage.vue'
import AnnouncementsPage from './components/AnnouncementsPage.vue'
import MarkdownContent from './components/MarkdownContent.vue'
import HelpPage from './components/HelpPage.vue'
import DownloadList from './components/DownloadList.vue'
import { content } from './api'
import { announcementUrl } from './announcements'
import { helpRoute, helpUrl } from './help'
import { usePublicData } from './usePublicData'
import { useMirrorFormats } from './useMirrorFormats'
import { type Mirror } from './data'
@@ -42,6 +43,8 @@ const themes: Theme[] = ['light', 'dark', 'system']
const themeIcons = { light: Sun, dark: Moon, system: Monitor }
const isStatusPage = window.location.pathname.replace(/\/$/, '') === '/status'
const isAnnouncementsPage = window.location.pathname.replace(/\/$/, '') === '/announcements'
const help = helpRoute(window.location.pathname)
const isHelpPage = help.active
const navigation = [
{ key: 'mirrors', href: '/', active: !isStatusPage && !isAdminPage && !isAnnouncementsPage },
{ key: 'news', href: '/announcements', active: isAnnouncementsPage },
@@ -61,7 +64,8 @@ watch(locale, (value) => {
}, { immediate: true })
watch([locale, site], () => {
const siteTitle = site.value ? `MirrorOUC · ${content(site.value.name, locale.value)}` : t('common.pageTitle')
document.title = isAnnouncementsPage ? `${t('announcements.title')} · ${siteTitle}` : siteTitle
const pageTitle = isHelpPage ? (help.name && !help.invalid ? t('mirrors.helpFor', { name: help.name }) : t('mirrors.helpTitle')) : isAnnouncementsPage ? t('announcements.title') : ''
document.title = pageTitle ? `${pageTitle} · ${siteTitle}` : siteTitle
}, { immediate: true })
function selectTheme(value: Theme) { theme.value = value; themeOpen.value = false }
@@ -93,13 +97,13 @@ function nextLabel(mirror: Mirror) {
}
function resetSearch() { search.value = ''; searchInput.value?.focus() }
type Modal = 'help' | 'about' | 'downloads' | 'mirror'
type Modal = 'about' | 'downloads' | 'mirror'
const dialog = ref<HTMLDialogElement>()
const modal = ref<Modal | null>(null)
const selectedMirror = ref<Mirror | null>(null)
const modalTitle = computed(() => {
if (modal.value === 'mirror') return selectedMirror.value?.name || ''
const keys = { help: 'mirrors.helpTitle', about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' }
const keys = { about: 'common.aboutTitle', downloads: 'announcements.downloadsTitle' }
return modal.value && modal.value in keys ? t(keys[modal.value as keyof typeof keys]) : ''
})
async function openModal(value: Modal, mirror?: Mirror) {
@@ -117,7 +121,7 @@ watch(modal, value => { document.body.classList.toggle('dialog-open', value !==
function onKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') { themeOpen.value = false; mobileOpen.value = false }
const target = event.target as HTMLElement
if (!isAdminPage && !isAnnouncementsPage && !dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey))
if (!isAdminPage && !isAnnouncementsPage && !isHelpPage && !dialog.value?.open && ((event.key === 'k' && (event.ctrlKey || event.metaKey))
|| (event.key === '/' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) && !target.isContentEditable))) {
event.preventDefault()
if (isStatusPage) statusPage.value?.focusSearch()
@@ -155,7 +159,7 @@ onBeforeUnmount(() => {
</script>
<template>
<a class="skip-link" :href="isAdminPage ? '#administration' : isStatusPage ? '#site-status' : isAnnouncementsPage ? '#announcements' : '#mirrors'">{{ t(isAdminPage ? 'common.skipAdmin' : isStatusPage ? 'common.skipStatus' : isAnnouncementsPage ? 'common.skipAnnouncements' : 'common.skip') }}</a>
<a class="skip-link" :href="isAdminPage ? '#administration' : isStatusPage ? '#site-status' : isAnnouncementsPage ? '#announcements' : isHelpPage ? '#mirror-help' : '#mirrors'">{{ t(isAdminPage ? 'common.skipAdmin' : isStatusPage ? 'common.skipStatus' : isAnnouncementsPage ? 'common.skipAnnouncements' : isHelpPage ? 'common.skipHelp' : 'common.skip') }}</a>
<header class="site-header">
<a href="/" class="brand" :aria-label="content(site?.name, locale) || t('common.siteName')">
<span class="brand-logo"><img :src="brandLogo" alt="" width="2000" height="433" /></span>
@@ -180,9 +184,10 @@ onBeforeUnmount(() => {
</header>
<main class="page-width">
<p v-if="!isAdminPage && !isAnnouncementsPage && (loading || source.stale)" class="data-notice" role="status">{{ t(loading ? 'common.loading' : source.updatedAt ? 'common.stale' : 'common.unavailable') }}</p>
<p v-if="!isAdminPage && !isAnnouncementsPage && !isHelpPage && (loading || source.stale)" class="data-notice" role="status">{{ t(loading ? 'common.loading' : source.updatedAt ? 'common.stale' : 'common.unavailable') }}</p>
<AdminPage v-if="isAdminPage" />
<AnnouncementsPage v-else-if="isAnnouncementsPage" />
<HelpPage v-else-if="isHelpPage" :name="help.name" :invalid="help.invalid" />
<StatusPage v-else-if="isStatusPage" ref="statusPage" :mirrors="mirrors" :now="now" :cycle="boardCycle" :show-next-sync="showNextSync" @mirror="openModal('mirror', $event)" />
<div v-else class="main-grid">
<section id="mirrors" class="mirror-section" tabindex="-1">
@@ -203,7 +208,7 @@ onBeforeUnmount(() => {
<td class="name-cell">
<div class="mirror-name-group">
<a class="mirror-name-button" :aria-label="t('mirrors.browse', { name: mirror.name })" :title="description(mirror)" :href="mirror.browseUrl">{{ mirror.name }}</a>
<button v-if="mirror.help?.trim()" class="help-button" :aria-label="t('mirrors.helpFor', { name: mirror.name })" :title="t('mirrors.helpFor', { name: mirror.name })" @click="openModal('mirror', mirror)"><BookOpen :size="14" /></button>
<a v-if="mirror.help?.trim()" class="help-button" :href="helpUrl(mirror.name)" :aria-label="t('mirrors.helpFor', { name: mirror.name })" :title="t('mirrors.helpFor', { name: mirror.name })"><CircleHelp :size="22" :stroke-width="1.7" aria-hidden="true" /></a>
</div>
</td>
<td class="time-cell" :title="fullTime(showNextSync ? mirror.nextSync : mirror.lastSuccess)"><RollingText :value="showNextSync ? tableNextTime(mirror) : relativeTime(mirror.lastSuccess)" :cycle="boardCycle" :candidates="timeCandidates" :reserve="[relativeTime(mirror.lastSuccess), tableNextTime(mirror)]" /></td>
@@ -232,7 +237,7 @@ onBeforeUnmount(() => {
<section v-if="site?.relatedLinks?.length" class="side-section useful-links">
<div class="side-heading"><h2>{{ t('announcements.links') }}</h2></div>
<template v-for="(link, index) in site.relatedLinks" :key="index">
<button v-if="link.kind === 'help'" @click="openModal('help')">{{ content(link.title, locale) }}</button>
<a v-if="link.kind === 'help'" href="/help/">{{ content(link.title, locale) }}</a>
<a v-else :href="link.url" :target="link.url.startsWith('/') ? undefined : '_blank'" rel="noopener noreferrer">{{ content(link.title, locale) }}</a>
</template>
</section>
@@ -281,8 +286,7 @@ onBeforeUnmount(() => {
<dialog id="content-dialog" ref="dialog" class="content-dialog" :class="{ 'download-dialog': modal === 'downloads' }" aria-labelledby="dialog-title" @close="onDialogClose" @click="($event.target === $event.currentTarget) && closeModal()">
<div class="dialog-inner"><div class="dialog-heading"><h2 id="dialog-title">{{ modalTitle }}</h2><button class="icon-button" :aria-label="t('common.close')" autofocus @click="closeModal"><X :size="21" /></button></div>
<div class="dialog-content">
<template v-if="modal === 'mirror' && selectedMirror"><p class="dialog-lead">{{ description(selectedMirror) }}</p><div class="mirror-facts"><span>{{ t('mirrors.columns.status') }}</span><span>{{ t(`mirrors.status.${selectedMirror.status}`) }}</span><span>{{ t('mirrors.columns.updated') }}</span><span>{{ relativeTime(selectedMirror.lastSuccess) }}</span><span>{{ t('mirrors.columns.next') }}</span><span>{{ nextLabel(selectedMirror) }}</span></div><MarkdownContent v-if="selectedMirror.help" :source="selectedMirror.help" lang="zh-CN" /><p v-else class="dialog-hint">{{ t('common.noHelp') }}</p><div class="dialog-actions"><a class="text-button" :href="selectedMirror.browseUrl">{{ t('common.openDirectory') }}<ArrowRight :size="15" /></a><a v-if="selectedMirror.website" :href="selectedMirror.website" target="_blank" rel="noopener noreferrer" class="text-button">{{ t('mirrors.official') }}<ExternalLink :size="14" /></a></div></template>
<template v-else-if="modal === 'help'"><p class="dialog-lead">{{ t('mirrors.helpIntro') }}</p><div class="help-grid"><button v-for="mirror in mirrors" :key="mirror.name" @click="openModal('mirror', mirror)"><span class="distro-mark" :style="{ '--distro-color': mirror.color }" aria-hidden="true">{{ mirror.mark }}</span><span>{{ mirror.name }}</span><ArrowRight :size="15" /></button></div></template>
<template v-if="modal === 'mirror' && selectedMirror"><p class="dialog-lead">{{ description(selectedMirror) }}</p><div class="mirror-facts"><span>{{ t('mirrors.columns.status') }}</span><span>{{ t(`mirrors.status.${selectedMirror.status}`) }}</span><span>{{ t('mirrors.columns.updated') }}</span><span>{{ relativeTime(selectedMirror.lastSuccess) }}</span><span>{{ t('mirrors.columns.next') }}</span><span>{{ nextLabel(selectedMirror) }}</span></div><div class="dialog-actions"><a v-if="selectedMirror.help?.trim()" class="text-button" :href="helpUrl(selectedMirror.name)">{{ t('mirrors.helpTitle') }}<CircleHelp :size="18" /></a><a class="text-button" :href="selectedMirror.browseUrl">{{ t('common.openDirectory') }}<ArrowRight :size="15" /></a><a v-if="selectedMirror.website" :href="selectedMirror.website" target="_blank" rel="noopener noreferrer" class="text-button">{{ t('mirrors.official') }}<ExternalLink :size="14" /></a></div></template>
<DownloadList v-else-if="modal === 'downloads'" :items="distributions" />
<template v-else-if="modal === 'about'"><img class="about-seal" :src="site?.avatar || '/assets/ouc-seal.png'" alt="" width="80" height="80" /><p class="article-body">{{ t('common.aboutBody') }}</p><div class="about-links"><a href="https://www.itouc.cn/" target="_blank" rel="noopener noreferrer">{{ t('common.studio') }}<ArrowUpRight :size="15" /></a><a href="https://github.com/tuna/tunasync" target="_blank" rel="noopener noreferrer">{{ t('common.source') }} · tunasync<ArrowUpRight :size="15" /></a></div></template>
</div>
+2
View File
@@ -10,6 +10,8 @@ export interface SiteSettings {
}
export interface AnnouncementContent { title: string; body: string; published: boolean; pinned: boolean; date: string }
export interface MirrorMetadata { name: string; description: Localized; help: string; category: string; visible: boolean; website: string }
export interface HelpSummary { name: string; description: Localized; website: string; browseUrl: string }
export interface HelpArticle extends HelpSummary { body: string }
export interface ContentRecord<T> { id: string; data: T; revision: number; updatedAt: number }
export interface AdminSession { username: string; role: 'admin' | 'editor'; csrf: string }
export interface SyncJob { name: string; worker: string; status: string; last_update: string; last_started: string; last_ended: string; next_schedule: string; upstream: string; size: string; error_msg: string }
+15 -1
View File
@@ -4,8 +4,10 @@ import { useI18n } from 'vue-i18n'
import { api, ApiError, jsonBody, setSession, type AdminSession, type AdminUser, type AnnouncementContent, type AuditPage, type ConfigVersion, type ContentRecord, type MirrorMetadata, type Overview, type SiteSettings, type SyncConfig, type SyncConfigMirror, type SyncJob } from '../api'
import { supportedLocales } from '../locales'
import { announcementUrl } from '../announcements'
import { helpUrl } from '../help'
import MarkdownContent from './MarkdownContent.vue'
import DownloadCatalogEditor from './DownloadCatalogEditor.vue'
import MirrorHelpContent from './MirrorHelpContent.vue'
const { t, te, d, n } = useI18n({ useScope: 'global' })
const session = ref<AdminSession | null>(null)
@@ -33,6 +35,7 @@ const articlePublished = computed(() => articlesEditor.value?.data.published ??
const sortedArticles = computed(() => [...articles.value].sort((a, b) => Number(b.data.pinned) - Number(a.data.pinned) || Date.parse(b.data.date) - Date.parse(a.data.date)))
const articleDate = computed(() => articlesEditor.value?.data.date ? new Intl.DateTimeFormat('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone: 'Asia/Shanghai' }).format(new Date(articlesEditor.value.data.date)) : '')
const mirrorEditor = ref<ContentRecord<MirrorMetadata> | null>(null)
const publishedMirrorHelp = computed(() => metadata.value.some(row => row.id === mirrorEditor.value?.id && row.data.visible && row.data.help?.trim()))
const editLocale = ref('zh-CN')
const logs = ref<{ name: string; text: string } | null>(null)
const config = ref<SyncConfig | null>(null)
@@ -206,7 +209,18 @@ onBeforeUnmount(() => clearInterval(poll))
<template v-if="tab === 'mirrors'">
<input v-model="search" class="admin-search" type="search" :placeholder="t('admin.search')" :aria-label="t('admin.search')" />
<div class="admin-table-wrap jobs-table"><table><thead><tr><th>{{ t('admin.name') }}</th><th>{{ t('admin.status') }}</th><th>{{ t('admin.size') }}</th><th>{{ t('admin.actions') }}</th></tr></thead><tbody><tr v-for="job in jobs" :key="job.name" :data-status="jobStatus(job.status)"><th>{{ job.name }}</th><td>{{ t(`mirrors.status.${jobStatus(job.status)}`) }}</td><td>{{ jobSize(job.size) }}</td><td><div class="row-actions"><button @click="editMirror(job)">{{ t('admin.edit') }}</button><button :disabled="busy" @click="run(() => showLogs(job.name))">{{ t('admin.logs') }}</button><button v-for="action in ['start','stop','restart','disable']" :key="action" :disabled="busy" @click="command(job, action)">{{ t(`admin.${action}`) }}</button></div></td></tr></tbody></table></div>
<form v-if="mirrorEditor" class="admin-editor admin-form" @submit.prevent="run(saveMirror)"><div class="admin-toolbar"><h3>{{ mirrorEditor.id }} · {{ t('admin.metadata') }}</h3><button type="button" @click="mirrorEditor = null">{{ t('admin.close') }}</button></div><label>{{ t('admin.descriptionLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label><label>{{ t('admin.description') }}<textarea v-model="mirrorEditor.data.description[editLocale]" rows="2" /></label><label>{{ t('admin.helpChinese') }}<textarea v-model="mirrorEditor.data.help" lang="zh-CN" rows="10" /></label><MarkdownContent :source="mirrorEditor.data.help" lang="zh-CN" /><label>{{ t('admin.website') }}<input v-model="mirrorEditor.data.website" type="url" /></label><label>{{ t('admin.category') }}<select v-model="mirrorEditor.data.category"><option v-for="value in ['os','language','other']" :key="value" :value="value">{{ t(`admin.${value}`) }}</option></select></label><label class="check"><input v-model="mirrorEditor.data.visible" type="checkbox" />{{ t('admin.visible') }}</label><button class="primary" :disabled="busy">{{ t('admin.save') }}</button></form>
<form v-if="mirrorEditor" class="admin-editor admin-form" @submit.prevent="run(saveMirror)">
<div class="admin-toolbar"><h3>{{ mirrorEditor.id }} · {{ t('admin.metadata') }}</h3><button type="button" @click="mirrorEditor = null">{{ t('admin.close') }}</button></div>
<label>{{ t('admin.descriptionLanguage') }}<select v-model="editLocale"><option v-for="language in supportedLocales" :key="language" :value="language">{{ t('common.languageName', {}, { locale: language }) }}</option></select></label>
<label>{{ t('admin.description') }}<textarea v-model="mirrorEditor.data.description[editLocale]" rows="2" /></label>
<label>{{ t('admin.helpChinese') }}<textarea v-model="mirrorEditor.data.help" lang="zh-CN" rows="14" /></label>
<details v-if="mirrorEditor.data.help.trim()" class="mirror-help-preview"><summary>{{ t('admin.preview') }}</summary><MirrorHelpContent :source="mirrorEditor.data.help" /></details>
<a v-if="publishedMirrorHelp" class="admin-public-link" :href="helpUrl(mirrorEditor.id)" target="_blank" rel="noopener noreferrer">{{ t('admin.viewHelp') }}</a>
<label>{{ t('admin.website') }}<input v-model="mirrorEditor.data.website" type="url" /></label>
<label>{{ t('admin.category') }}<select v-model="mirrorEditor.data.category"><option v-for="value in ['os','language','other']" :key="value" :value="value">{{ t(`admin.${value}`) }}</option></select></label>
<label class="check"><input v-model="mirrorEditor.data.visible" type="checkbox" />{{ t('admin.visible') }}</label>
<button class="primary" :disabled="busy">{{ t('admin.save') }}</button>
</form>
<section v-if="logs" class="admin-editor"><div class="admin-toolbar"><h3>{{ logs.name }} · {{ t('admin.logs') }}</h3><div class="admin-actions"><button :disabled="busy" @click="run(() => showLogs(logs!.name))">{{ t('admin.refresh') }}</button><button @click="logs = null">{{ t('admin.close') }}</button></div></div><p>{{ t('admin.logTail') }}</p><pre class="admin-log">{{ logs.text }}</pre></section>
</template>
<template v-if="tab === 'announcements'">
+91
View File
@@ -0,0 +1,91 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, useId, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Check, Copy } from 'lucide-vue-next'
import { debianReleases, debianSources, type DebianFormat, type DebianRelease } from '../debian-sources'
import { copyText } from '../copy-text'
const props = defineProps<{ format: DebianFormat }>()
const { t } = useI18n()
const id = useId()
const release = ref<DebianRelease>('trixie')
const sources = ref(false)
const nonFree = ref(true)
const securityMirror = ref(false)
const selection = computed(() => debianReleases.find(entry => entry.id === release.value)!)
const code = computed(() => debianSources({ origin: window.location.origin, release: release.value, format: props.format, sources: sources.value, nonFree: nonFree.value, securityMirror: securityMirror.value }))
const file = computed(() => props.format === 'list' ? '/etc/apt/sources.list' : '/etc/apt/sources.list.d/debian.sources')
const copied = ref(false)
const copyFailed = ref(false)
let reset: ReturnType<typeof setTimeout> | undefined
let revision = 0
let disposed = false
function resetCopy() { revision++; copied.value = false; copyFailed.value = false; clearTimeout(reset) }
watch(code, resetCopy)
watch(selection, value => { if (!value.stable) securityMirror.value = false })
async function copy() {
const current = ++revision
clearTimeout(reset)
try {
await copyText(code.value)
if (disposed || current !== revision) return
copied.value = true
copyFailed.value = false
} catch {
if (disposed || current !== revision) return
copied.value = false
copyFailed.value = true
}
reset = setTimeout(resetCopy, 2500)
}
onBeforeUnmount(() => { disposed = true; clearTimeout(reset) })
</script>
<template>
<section class="debian-sources" :data-format="format" :aria-label="t('mirrors.debian.generator', { format: format === 'list' ? t('mirrors.debian.traditional') : 'DEB822' })">
<div class="source-controls">
<label class="source-control source-version"><span>{{ t('mirrors.debian.version') }}</span><select v-model="release"><option v-for="entry in debianReleases" :key="entry.id" :value="entry.id">{{ entry.version ? t('mirrors.debian.release', { version: entry.version, codename: entry.id }) : entry.id }}</option></select></label>
<label class="source-control"><span>{{ t('mirrors.debian.sources') }}</span><input v-model="sources" type="checkbox" role="switch" /><span class="source-toggle" aria-hidden="true" /></label>
<label class="source-control"><span>{{ t('mirrors.debian.nonFree') }}</span><input v-model="nonFree" type="checkbox" role="switch" /><span class="source-toggle" aria-hidden="true" /></label>
<label class="source-control" :class="{ 'source-disabled': !selection.stable }"><span>{{ t('mirrors.debian.securityMirror') }}</span><input v-model="securityMirror" type="checkbox" role="switch" :disabled="!selection.stable" :aria-describedby="!selection.stable ? `${id}-branch` : undefined" /><span class="source-toggle" aria-hidden="true" /></label>
</div>
<p v-if="!selection.stable" :id="`${id}-branch`" class="source-note">{{ t('mirrors.debian.rollingNotice') }}</p>
<div class="source-code">
<div class="source-code-heading"><span>{{ file }}</span><button type="button" :aria-label="t(copied ? 'common.copied' : 'common.copy')" :title="t(copied ? 'common.copied' : 'common.copy')" @click="copy"><Check v-if="copied" :size="18" aria-hidden="true" /><Copy v-else :size="18" aria-hidden="true" /></button></div>
<pre tabindex="0" :aria-label="t('mirrors.debian.generated')"><code>{{ code }}</code></pre>
</div>
<p class="copy-status" :class="{ 'sr-only': !copyFailed }" role="status">{{ copyFailed ? t('common.copyFailed') : copied ? t('common.copied') : '' }}</p>
</section>
</template>
<style scoped>
.debian-sources { min-width: 0; margin: 20px 0 30px; }
.source-controls { display: grid; grid-template-columns: minmax(180px, 1.35fr) repeat(3, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
.source-control { position: relative; display: flex; flex-direction: column; justify-content: space-between; align-items: flex-start; gap: 8px; min-width: 0; min-height: 70px; margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 4px; color: var(--ink); font-size: 13px; line-height: 1.5; cursor: pointer; }
.source-control > span:first-child { color: var(--ink-2); }
.source-control select { width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; background: var(--paper); color: var(--ink); font: inherit; font-size: 15px; cursor: pointer; }
.source-control input { position: absolute; width: 1px; height: 1px; margin: 0; opacity: 0; }
.source-toggle { position: relative; width: 32px; height: 18px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface); }
.source-toggle::after { position: absolute; top: 3px; left: 3px; width: 10px; height: 10px; border-radius: 50%; background: var(--ink-2); content: ''; transition: transform 120ms; }
.source-control input:checked + .source-toggle { border-color: var(--blue); background: var(--blue); }
.source-control input:checked + .source-toggle::after { background: var(--on-accent); transform: translateX(14px); }
.source-control input:focus-visible + .source-toggle { outline: 2px solid var(--blue); outline-offset: 3px; }
.source-disabled { opacity: .55; cursor: default; }
.source-note, .copy-status { margin: 10px 0; color: var(--ink); font-size: 14px; line-height: 1.7; }
.source-code { min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 4px; background: var(--surface); }
.source-code-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 7px 10px 0 14px; color: var(--ink-2); font: 12px/1.5 ui-monospace, Consolas, monospace; }
.source-code-heading > span { min-width: 0; overflow-wrap: anywhere; }
.source-code-heading button { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 3px; color: var(--ink); }
.source-code-heading button:hover { color: var(--blue); background: var(--blue-soft); }
.source-code pre { max-width: 100%; overflow: auto; margin: 0; padding: 6px 14px 16px; color: var(--ink); font: 13px/1.85 ui-monospace, 'Cascadia Code', Consolas, monospace; white-space: pre; }
@media (max-width: 1100px) { .source-controls { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) {
.source-controls { gap: 10px; }
.source-control { min-height: 80px; padding: 10px; }
.source-control select { min-height: 28px; font-size: 14px; }
.source-code-heading button { width: 44px; height: 44px; }
.source-code pre { font-size: 12px; }
}
@media (max-width: 360px) { .source-controls { grid-template-columns: minmax(0, 1fr); } }
@media (prefers-reduced-motion: reduce) { .source-toggle::after { transition: none; } }
</style>
+115
View File
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { api, ApiError, content, type HelpArticle, type HelpSummary } from '../api'
import { helpUrl } from '../help'
import MirrorHelpContent from './MirrorHelpContent.vue'
const props = defineProps<{ name: string | null; invalid: boolean }>()
const { t, locale } = useI18n()
const guides = ref<HelpSummary[]>([])
const article = ref<HelpArticle | null>(null)
const loading = ref(true)
const failed = ref(false)
const navigationFailed = ref(false)
const notFound = ref(props.invalid)
const title = computed(() => props.name && !props.invalid ? t('mirrors.helpFor', { name: props.name }) : t('mirrors.helpTitle'))
let controller: AbortController | undefined
async function load() {
controller?.abort()
const request = new AbortController()
controller = request
loading.value = true
failed.value = false
navigationFailed.value = false
const [index, detail] = await Promise.allSettled([
api<HelpSummary[]>('/help', { signal: request.signal }),
props.name && !props.invalid ? api<HelpArticle>(`/help/${encodeURIComponent(props.name)}`, { signal: request.signal }) : Promise.resolve(null),
])
if (request.signal.aborted) return
if (index.status === 'fulfilled') guides.value = index.value
else navigationFailed.value = true
if (detail.status === 'fulfilled') { article.value = detail.value; notFound.value = props.invalid }
else if (detail.reason instanceof ApiError && detail.reason.status === 404) { article.value = null; notFound.value = true }
else failed.value = true
if (!props.name && navigationFailed.value && !props.invalid) failed.value = true
loading.value = false
}
function selectGuide(event: Event) {
const name = (event.target as HTMLSelectElement).value
window.location.assign(name ? helpUrl(name) : '/help/')
}
onMounted(() => { void load() })
onBeforeUnmount(() => controller?.abort())
</script>
<template>
<section id="mirror-help" class="help-page" tabindex="-1" :aria-busy="loading">
<div class="help-layout">
<aside class="help-sidebar">
<nav class="help-navigation" :aria-label="t('mirrors.guides.navigation')">
<a href="/help/" :aria-current="!name && !invalid ? 'page' : undefined">{{ t('mirrors.helpTitle') }}</a>
<a v-for="guide in guides" :key="guide.name" :href="helpUrl(guide.name)" :aria-current="guide.name === name ? 'page' : undefined">{{ guide.name }}</a>
</nav>
<label class="help-mobile-select">{{ t('mirrors.guides.choose') }}<select :value="name || ''" @change="selectGuide"><option value="">{{ t('mirrors.guides.all') }}</option><option v-if="name && !guides.some(guide => guide.name === name)" :value="name">{{ name }}</option><option v-for="guide in guides" :key="guide.name" :value="guide.name">{{ guide.name }}</option></select></label>
<button v-if="navigationFailed && !failed" class="help-retry" @click="load">{{ t('mirrors.guides.retry') }}</button>
</aside>
<div class="help-content">
<h1>{{ title }}</h1>
<p v-if="loading" role="status">{{ t('mirrors.guides.loading') }}</p>
<div v-else-if="failed" class="help-message" role="alert"><p>{{ t('mirrors.guides.failed') }}</p><button class="help-retry" @click="load">{{ t('mirrors.guides.retry') }}</button></div>
<div v-else-if="notFound" class="help-message"><p>{{ t('mirrors.guides.notFound') }}</p><a href="/help/">{{ t('mirrors.guides.all') }}</a></div>
<article v-else-if="article" class="help-article">
<p v-if="content(article.description, locale)" class="help-description">{{ content(article.description, locale) }}</p>
<div class="help-actions"><a :href="article.browseUrl">{{ t('common.openDirectory') }}</a><a v-if="article.website" :href="article.website" target="_blank" rel="noopener noreferrer">{{ t('mirrors.official') }}</a></div>
<MirrorHelpContent :source="article.body" />
</article>
<div v-else class="help-index">
<p>{{ t('mirrors.helpIntro') }}</p>
<p v-if="!guides.length">{{ t('mirrors.guides.empty') }}</p>
<ul v-else><li v-for="guide in guides" :key="guide.name"><a :href="helpUrl(guide.name)">{{ guide.name }}</a><span v-if="content(guide.description, locale)">{{ content(guide.description, locale) }}</span></li></ul>
</div>
</div>
</div>
</section>
</template>
<style scoped>
.help-page { min-height: 50vh; padding: 32px 0 80px; }
.help-layout { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 48px; align-items: start; }
.help-sidebar { position: sticky; top: 24px; min-width: 0; }
.help-navigation { display: grid; gap: 3px; max-height: calc(100dvh - 48px); overflow: auto; padding-right: 6px; }
.help-navigation a { display: block; padding: 10px 13px; color: var(--blue); font-size: 15px; line-height: 1.5; overflow-wrap: anywhere; }
.help-navigation a:hover { background: var(--blue-soft); }
.help-navigation [aria-current='page'] { background: var(--blue); color: var(--on-accent); font-weight: 600; border-radius: 2px; }
.help-content { min-width: 0; max-width: 940px; overflow-wrap: anywhere; }
h1 { margin: 0 0 20px; color: var(--ink); font-size: 36px; line-height: 1.35; font-weight: 600; }
.help-description { margin: 0 0 12px; color: var(--ink); font-size: 16px; line-height: 1.8; }
.help-actions { display: flex; flex-wrap: wrap; gap: 8px 24px; margin-bottom: 28px; }
.help-actions a, .help-message a, .help-index a { color: var(--blue); font-size: 15px; line-height: 1.8; text-underline-offset: 4px; }
.help-actions a:hover, .help-message a:hover, .help-index a:hover { text-decoration: underline; }
.help-article :deep(.markdown-content) { font-size: 16px; line-height: 1.9; }
.help-article :deep(.markdown-content h2) { margin-top: 1.6em; font-size: 26px; }
.help-article :deep(.markdown-content h3) { font-size: 20px; }
.help-article :deep(.markdown-content pre) { font-size: 13px; line-height: 1.8; }
.help-index p, .help-message p { margin: 0 0 22px; font-size: 16px; line-height: 1.9; }
.help-index ul { display: grid; gap: 16px; padding: 0; margin: 28px 0 0; list-style: none; }
.help-index li { display: grid; grid-template-columns: minmax(140px, 210px) minmax(0, 1fr); gap: 12px; align-items: baseline; font-size: 15px; line-height: 1.8; }
.help-index li > a { font-weight: 600; }
.help-retry { padding: 8px 14px; border: 1px solid var(--blue); border-radius: 3px; color: var(--blue); font-size: 14px; }
.help-mobile-select { display: none; }
@media (max-width: 760px) {
.help-page { padding: 16px 0 48px; }
.help-layout { grid-template-columns: minmax(0, 1fr); gap: 28px; }
.help-sidebar { position: static; }
.help-navigation { display: none; }
.help-mobile-select { display: grid; gap: 8px; font-size: 14px; color: var(--ink); }
.help-mobile-select select { width: 100%; min-width: 0; min-height: 44px; padding: 9px 12px; border: 1px solid var(--line); border-radius: 3px; background: var(--paper); color: var(--ink); font: inherit; font-size: 16px; }
h1 { font-size: 28px; }
.help-actions a, .help-message a { display: inline-flex; align-items: center; min-height: 44px; }
.help-actions { margin-bottom: 18px; }
.help-article :deep(.markdown-content h2) { font-size: 23px; }
.help-index li { grid-template-columns: minmax(0, 1fr); gap: 0; }
}
</style>
+3 -3
View File
@@ -1,9 +1,9 @@
<script setup lang="ts">
import { computed } from 'vue'
import { marked } from 'marked'
import { marked, type TokensList } from 'marked'
import DOMPurify from 'dompurify'
const props = defineProps<{ source: string }>()
const html = computed(() => DOMPurify.sanitize(marked.parse(props.source, { async: false, breaks: false }), {
const props = defineProps<{ source?: string; tokens?: TokensList }>()
const html = computed(() => DOMPurify.sanitize(props.tokens ? marked.parser(props.tokens) : marked.parse(props.source || '', { async: false, breaks: false }), {
ALLOWED_TAGS: ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong', 'em', 'del', 'blockquote', 'pre', 'code', 'ul', 'ol', 'li', 'a', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'img'],
ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'start'],
ALLOW_DATA_ATTR: false,
+18
View File
@@ -0,0 +1,18 @@
<script setup lang="ts">
import { computed } from 'vue'
import { helpBlocks } from '../help-content'
import DebianSources from './DebianSources.vue'
import MarkdownContent from './MarkdownContent.vue'
const props = defineProps<{ source: string }>()
const blocks = computed(() => helpBlocks(props.source))
</script>
<template>
<div class="mirror-help-content" lang="zh-CN">
<template v-for="(block, index) in blocks" :key="index">
<DebianSources v-if="block.kind === 'debian'" :format="block.format" />
<MarkdownContent v-else :tokens="block.tokens" />
</template>
</div>
</template>
+18
View File
@@ -0,0 +1,18 @@
export async function copyText(text: string) {
if (navigator.clipboard?.writeText) {
try { await navigator.clipboard.writeText(text); return } catch { /* Try the user-gesture fallback on HTTP previews and restricted browsers. */ }
}
const focused = document.activeElement
const field = document.createElement('textarea')
field.value = text
field.readOnly = true
field.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0'
document.body.appendChild(field)
try {
field.select()
if (!document.execCommand('copy')) throw new Error('Copy failed')
} finally {
field.remove()
if (focused instanceof HTMLElement) focused.focus({ preventScroll: true })
}
}
+43
View File
@@ -0,0 +1,43 @@
export const debianReleases = [
{ id: 'trixie', version: '13', stable: true, firmware: true, backports: true },
{ id: 'bookworm', version: '12', stable: true, firmware: true, backports: false },
{ id: 'bullseye', version: '11', stable: true, firmware: false, backports: false },
{ id: 'testing', version: '', stable: false, firmware: true, backports: false },
{ id: 'sid', version: '', stable: false, firmware: true, backports: false },
] as const
export type DebianRelease = typeof debianReleases[number]['id']
export type DebianFormat = 'list' | 'deb822'
export interface DebianSourceOptions {
origin: string
release: DebianRelease
format: DebianFormat
sources: boolean
nonFree: boolean
securityMirror: boolean
}
export function debianSources(options: DebianSourceOptions) {
const release = debianReleases.find(entry => entry.id === options.release)
if (!release || !['list', 'deb822'].includes(options.format)) throw new Error('Invalid Debian configuration')
const origin = new URL(options.origin)
if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password) throw new Error('Invalid mirror origin')
const mirror = `${origin.origin}/mirrors/debian/`
const security = options.securityMirror ? `${origin.origin}/mirrors/debian-security/` : 'https://security.debian.org/debian-security'
const components = ['main', ...(options.nonFree ? ['contrib', 'non-free', ...(release.firmware ? ['non-free-firmware'] : [])] : [])].join(' ')
const suites = [release.id, ...(release.stable ? [`${release.id}-updates`] : []), ...(release.backports ? [`${release.id}-backports`] : [])]
const groups = [{ uri: mirror, suites }, ...(release.stable ? [{ uri: security, suites: [`${release.id}-security`] }] : [])]
if (options.format === 'deb822') {
return groups.map(group => [
`Types: ${options.sources ? 'deb deb-src' : 'deb'}`,
`URIs: ${group.uri}`,
`Suites: ${group.suites.join(' ')}`,
`Components: ${components}`,
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg',
].join('\n')).join('\n\n') + '\n'
}
return groups.flatMap(group => group.suites.map(suite => [
`deb ${group.uri} ${suite} ${components}`,
`${options.sources ? '' : '# '}deb-src ${group.uri} ${suite} ${components}`,
].join('\n'))).join('\n\n') + '\n'
}
+28
View File
@@ -0,0 +1,28 @@
import { marked, type Token, type TokensList } from 'marked'
import type { DebianFormat } from './debian-sources'
export type HelpBlock = { kind: 'markdown'; tokens: TokensList } | { kind: 'debian'; format: DebianFormat }
// Only an allowlisted data block can create a widget; Markdown never executes scripts.
export function helpBlocks(source: string): HelpBlock[] {
const document = marked.lexer(source)
const blocks: HelpBlock[] = []
let pending: Token[] = []
const flush = () => {
if (pending.length) blocks.push({ kind: 'markdown', tokens: Object.assign(pending, { links: document.links }) })
pending = []
}
for (const token of document) {
let format: DebianFormat | undefined
if (token.type === 'code' && token.lang === 'mirror-config' && token.text.length <= 2048) {
try {
const value: unknown = JSON.parse(token.text)
if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => key === 'type' || key === 'format') && 'type' in value && value.type === 'debian' && 'format' in value && (value.format === 'list' || value.format === 'deb822')) format = value.format
} catch { /* Invalid blocks remain visible as ordinary code for the author to correct. */ }
}
if (format) { flush(); blocks.push({ kind: 'debian', format }) }
else pending.push(token)
}
flush()
return blocks
}
+13
View File
@@ -0,0 +1,13 @@
const mirrorName = /^[a-zA-Z0-9][a-zA-Z0-9_.+-]{0,127}$/
export const helpUrl = (name: string) => `/help/${encodeURIComponent(name)}/`
export function helpRoute(path: string) {
const normalized = path.replace(/\/$/, '')
if (normalized === '/help') return { active: true, name: null, invalid: false }
if (!normalized.startsWith('/help/')) return { active: false, name: null, invalid: false }
let name: string
try { name = decodeURIComponent(normalized.slice('/help/'.length)) }
catch { return { active: true, name: null, invalid: true } }
return { active: true, name, invalid: !mirrorName.test(name) }
}
+1
View File
@@ -1,4 +1,5 @@
const pairs = {
viewHelp: ['查看帮助页', 'View usage guide'],
downloadProjects: ['软件项目', 'Software projects'], addDownloadProject: ['添加软件', 'Add software'], removeDownloadProject: ['移除软件', 'Remove software'], softwareName: ['软件名称', 'Software name'],
downloadDescription: ['软件说明(中文,Markdown)', 'Description (Chinese, Markdown)'], downloadFiles: ['下载链接', 'Download links'], downloadLabel: ['链接名称(版本 / 架构)', 'Link label (version / architecture)'], addDownloadFile: ['添加下载链接', 'Add download link'], saveDownloads: ['保存下载配置', 'Save download catalog'],
downloadFileEntry: ['下载链接 {index}', 'Download link {index}'], downloadProjectCount: ['共 {count} 个软件', '{count} projects'], unnamedDownload: ['未命名软件 {index}', 'Untitled project {index}'], noDownloadProjects: ['暂无软件,点击“添加软件”开始配置。', 'No projects yet. Select “Add software” to get started.'],
+1
View File
@@ -1,4 +1,5 @@
export default {
skipHelp: 'Skip to mirror usage guide',
skipAnnouncements: 'Skip to announcements',
skipAdmin: 'Skip to administration',
loading: 'Loading mirrors…',
+21
View File
@@ -63,6 +63,27 @@ export default {
"exampleHint": "This layout example uses the reserved example.invalid domain and cannot be used as a software repository.",
"official": "Official project website",
"helpTitle": "Using the mirrors",
"debian": {
"generator": "{format} repository configuration",
"traditional": "Traditional format",
"version": "Debian release",
"release": "Debian {version} ({codename})",
"sources": "Enable source packages",
"nonFree": "Include non-free packages",
"securityMirror": "Use mirror for security updates",
"generated": "Generated repository configuration",
"rollingNotice": "testing and sid use their own branch without separate security, updates or backports repositories."
},
"guides": {
"navigation": "Mirror usage guide navigation",
"choose": "Choose a mirror guide",
"all": "All guides",
"loading": "Loading usage guide…",
"failed": "The usage guide could not be loaded.",
"retry": "Reload",
"notFound": "No published usage guide is available for this mirror.",
"empty": "No usage guides have been published yet."
},
"helpIntro": "Choose a mirror to view its introduction and configuration example.",
"statusTitle": "Sync jobs",
"statusIntro": "Demo jobs change status periodically. The last successful sync is tracked separately from the current status.",
+1
View File
@@ -1,4 +1,5 @@
export default {
skipHelp: '跳转到镜像使用帮助',
skipAdmin: '跳转到站点管理',
skipAnnouncements: '跳转到站点公告',
loading: '正在加载镜像数据…',
+21
View File
@@ -63,6 +63,27 @@ export default {
"exampleHint": "以下配置仅演示排版,使用 example.invalid 保留域名,不可用于实际软件源配置。",
"official": "项目官方网站",
"helpTitle": "使用帮助",
"debian": {
"generator": "{format} 软件源配置",
"traditional": "传统格式",
"version": "Debian 版本",
"release": "Debian {version} ({codename})",
"sources": "启用源码源",
"nonFree": "使用非自由软件源",
"securityMirror": "强制安全更新使用镜像",
"generated": "生成的软件源配置",
"rollingNotice": "testing 和 sid 仅配置对应分支,不添加独立的安全更新、updates 或 backports 源。"
},
"guides": {
"navigation": "镜像使用帮助目录",
"choose": "选择镜像帮助",
"all": "全部帮助",
"loading": "正在加载使用帮助…",
"failed": "暂时无法加载使用帮助。",
"retry": "重新加载",
"notFound": "此镜像暂无已发布的使用帮助。",
"empty": "暂无已发布的使用帮助。"
},
"helpIntro": "选择软件源,查看项目介绍与配置示例。",
"statusTitle": "同步任务",
"statusIntro": "演示任务会定期切换状态。最近成功时间与当前同步状态分别记录。",
+6 -2
View File
@@ -106,7 +106,10 @@ h2 { margin: 0; font-size: 19px; font-weight: 600; letter-spacing: -.04em; }
.status-list > div[data-status='failed'] { background: var(--red-soft); }
.mirror-table :is(.time-cell, .metric-cell) { font-variant-numeric: tabular-nums; }
.mirror-table .roll-frame { display: grid; width: 100%; max-width: 100%; }
.help-button { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; border-radius: 5px; color: var(--ink-3); }.help-button:hover { color: var(--blue); background: var(--blue-soft); }
.help-button { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 28px; height: 28px; border: 0; border-radius: 50%; background: transparent; color: var(--blue); transition: color 120ms, background-color 120ms; }
.help-button svg { display: block; }
.help-button:hover { background: var(--blue-soft); color: var(--accent-hover); }
.help-button:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
.roll-frame { display: inline-grid; min-width: 0; max-width: 100%; vertical-align: middle; line-height: 1.5; }
.roll-stage { position: relative; display: grid; min-width: 0; overflow: hidden; }
.roll-sizer { grid-area: 1 / 1; min-width: 0; visibility: hidden; white-space: nowrap; overflow: hidden; }
@@ -225,7 +228,8 @@ h2 { margin: 0; font-size: 19px; font-weight: 600; letter-spacing: -.04em; }
.mirror-table th:first-child { width: 44%; }
.mirror-table th:nth-child(2), .mirror-table th:nth-child(3) { width: 28%; }
.mirror-name-button { min-height: 44px; font-size: 14px; }
.mirror-name-group .help-button { display: none; }
.mirror-name-group { gap: 4px; }
.mirror-name-group .help-button { width: 32px; height: 32px; }
.mirror-table .time-cell { line-height: 1.5; }
.sidebar { display: flex; align-items: stretch; gap: 20px; }
.side-heading { margin-bottom: 6px; }