Files
console/app.js
T

273 lines
9.1 KiB
JavaScript

/* 工作区控制台 · 前端逻辑(无依赖) */
const KIND = {
site: { label: '网站', cls: 'site' },
repo: { label: '仓库', cls: 'repo' },
plugin: { label: '插件', cls: 'plugin' },
mirror: { label: '镜像', cls: 'mirror' },
dir: { label: '目录', cls: 'dir' },
file: { label: '文件', cls: 'dir' },
}
const state = {
data: null,
q: '',
kind: 'all',
dirty: false,
sort: 'size',
desc: true,
}
const $ = (sel) => document.querySelector(sel)
const el = (tag, attrs = {}, ...kids) => {
const n = document.createElement(tag)
for (const [k, v] of Object.entries(attrs)) {
if (k === 'class') n.className = v
else if (k === 'html') n.innerHTML = v
else if (k === 'text') n.textContent = v
else if (k.startsWith('on')) n.addEventListener(k.slice(2), v)
else n.setAttribute(k, v)
}
for (const kid of kids.flat()) if (kid != null) n.append(kid.nodeType ? kid : document.createTextNode(kid))
return n
}
const ago = (iso) => {
const diff = Date.now() - new Date(iso).getTime()
if (diff < 60e3) return '刚刚'
if (diff < 36e5) return `${Math.floor(diff / 60e3)} 分钟前`
if (diff < 864e5) return `${Math.floor(diff / 36e5)} 小时前`
if (diff < 30 * 864e5) return `${Math.floor(diff / 864e5)} 天前`
return new Date(iso).toLocaleDateString('zh-CN')
}
async function copy(text) {
try {
await navigator.clipboard.writeText(text)
toast(`已复制:${text.length > 34 ? text.slice(0, 34) + '…' : text}`)
} catch {
toast('复制失败,手动选一下文本吧', true)
}
}
let toastTimer = null
function toast(msg, bad = false) {
let t = $('#toast')
if (!t) {
t = el('div', { id: 'toast', class: 'toast' })
document.body.append(t)
}
t.textContent = msg
t.classList.toggle('bad', bad)
t.classList.add('show')
clearTimeout(toastTimer)
toastTimer = setTimeout(() => t.classList.remove('show'), 2200)
}
function renderStats() {
const t = state.data.totals
const box = $('#stats')
box.replaceChildren(
stat(t.projects, '项目'),
stat(t.size, '占用'),
stat(String(t.files), '文件'),
stat(String(t.dirty), '有改动', t.dirty ? 'warn' : '')
)
function stat(value, label, tone = '') {
return el('div', { class: `stat ${tone}` }, el('b', { text: String(value) }), el('span', { text: label }))
}
}
function renderServices() {
const grid = $('#svcGrid')
const list = state.data.services || []
const up = list.filter((s) => s.ok).length
const known = list.filter((s) => s.ok !== null).length
$('#svcHint').textContent = known ? `${up}/${known} 在线 · 扫描时探测` : '点开直接用'
grid.replaceChildren(
...list.map((s) => {
const dotCls = s.ok === null ? 'idle' : s.ok ? 'ok' : 'bad'
const status = s.ok === null ? '未探测' : s.ok ? `${s.ms} ms` : '连不上'
return el(
'a',
{ class: 'svc', href: s.url, target: '_blank', rel: 'noopener' },
el('div', { class: 'svc-top' },
el('span', { class: `dot ${dotCls}` }),
el('b', { text: s.name }),
el('em', { text: `:${s.port}` })
),
el('p', { text: s.desc }),
el('span', { class: `svc-ms ${dotCls}`, text: status })
)
})
)
}
function renderChips() {
const counts = { all: state.data.entries.length }
for (const e of state.data.entries) counts[e.kind] = (counts[e.kind] || 0) + 1
const chips = $('#chips')
const make = (key, label) =>
el('button', {
class: `chip ${state.kind === key ? 'on' : ''}`,
type: 'button',
onclick: () => {
state.kind = key
renderChips()
renderGrid()
},
}, label, el('b', { text: String(counts[key] || 0) }))
chips.replaceChildren(
make('all', '全部'),
...['site', 'repo', 'plugin', 'mirror', 'dir'].filter((k) => counts[k]).map((k) => make(k, KIND[k].label)),
el('button', {
class: `chip ${state.dirty ? 'on warn' : ''}`,
type: 'button',
onclick: () => {
state.dirty = !state.dirty
renderChips()
renderGrid()
},
}, '有改动', el('b', { text: String(state.data.totals.dirty) }))
)
}
function filtered() {
const q = state.q.trim().toLowerCase()
let list = state.data.entries.filter((e) => {
if (state.kind !== 'all' && e.kind !== state.kind) return false
if (state.dirty && !e.git?.dirty) return false
if (!q) return true
return [e.name, e.title, e.desc, e.git?.branch, e.git?.repo].join(' ').toLowerCase().includes(q)
})
const dir = state.desc ? -1 : 1
list = list.sort((a, b) => {
if (state.sort === 'name') return a.name.localeCompare(b.name) * dir
if (state.sort === 'time') return (new Date(a.mtime) - new Date(b.mtime)) * dir
return (a.bytes - b.bytes) * dir
})
return list
}
function renderGrid() {
const list = filtered()
const max = Math.max(1, ...state.data.entries.map((e) => e.bytes))
const grid = $('#grid')
$('#empty').hidden = list.length > 0
grid.replaceChildren(...list.map((e) => card(e, max)))
}
function card(e, max) {
const kind = KIND[e.kind] || KIND.dir
const pct = Math.max(2, Math.round((e.bytes / max) * 100))
const g = e.git
const meta = el('div', { class: 'meta' },
el('span', { text: e.size }),
el('span', { text: `${e.files} 个文件` }),
el('span', { text: ago(e.mtime) })
)
const gitRow = g
? el('div', { class: 'git' },
el('span', { class: 'branch', text: `⎇ ${g.branch}` }),
el('span', { class: 'sha', text: g.sha }),
el('span', { class: 'subject', text: g.subject, title: g.subject }),
g.dirty ? el('span', { class: 'dirty', text: `有改动 ${g.changes}` }) : null
)
: el('div', { class: 'git muted' }, el('span', { text: '未纳入 git' }))
const acts = el('div', { class: 'acts' })
if (e.url) acts.append(el('a', { class: 'btn primary', href: e.url, target: '_blank', rel: 'noopener', text: `打开 :${e.port}` }))
if (g?.webRepo) acts.append(el('a', { class: 'btn', href: g.webRepo, target: '_blank', rel: 'noopener', text: 'Gitea 仓库' }))
acts.append(el('button', { class: 'btn ghost', type: 'button', title: '复制本地路径', text: '路径', onclick: () => copy(`${state.data.root}/${e.name}`) }))
if (g) acts.append(el('button', { class: 'btn ghost', type: 'button', title: '复制 git 命令', text: 'git', onclick: () => copy(`cd ${state.data.root}/${e.name} && git status`) }))
return el('article', { class: 'card' },
el('div', { class: 'card-head' },
el('h3', { text: e.name }),
el('span', { class: `kind ${kind.cls}`, text: kind.label })
),
e.title || e.desc
? el('p', { class: 'desc', text: e.title && e.title !== e.name ? e.title : e.desc || '' })
: null,
el('div', { class: 'bar' }, el('i', { style: `width:${pct}%` })),
meta,
gitRow,
e.ext?.length ? el('div', { class: 'ext' }, ...e.ext.map((x) => el('span', { text: x }))) : null,
acts
)
}
function bind() {
$('#q').addEventListener('input', (ev) => {
state.q = ev.target.value
renderGrid()
})
$('#sort').addEventListener('change', (ev) => {
state.sort = ev.target.value
renderGrid()
})
$('#dirBtn').addEventListener('click', () => {
state.desc = !state.desc
$('#dirBtn').textContent = state.desc ? '↓' : '↑'
renderGrid()
})
const openHelp = () => {
$('#help').hidden = false
document.body.classList.add('locked')
}
const closeHelp = () => {
$('#help').hidden = true
document.body.classList.remove('locked')
}
$('#helpBtn').addEventListener('click', openHelp)
$('#helpLink').addEventListener('click', (ev) => {
ev.preventDefault()
openHelp()
})
$('#help').addEventListener('click', (ev) => {
if (ev.target.dataset.close !== undefined) closeHelp()
})
$('#themeBtn').addEventListener('click', toggleTheme)
document.addEventListener('keydown', (ev) => {
if (ev.key === '/' && document.activeElement !== $('#q')) {
ev.preventDefault()
$('#q').focus()
} else if (ev.key === 'Escape') {
closeHelp()
} else if (ev.key === 't' && document.activeElement !== $('#q')) {
toggleTheme()
}
})
}
function toggleTheme() {
const root = document.documentElement
const next = root.dataset.theme === 'light' ? 'dark' : 'light'
root.dataset.theme = next
try {
localStorage.setItem('console.theme', next)
} catch {}
$('#themeBtn').textContent = next === 'light' ? '☀' : '☾'
}
async function main() {
$('#themeBtn').textContent = document.documentElement.dataset.theme === 'light' ? '☀' : '☾'
try {
const res = await fetch('manifest.json', { cache: 'no-store' })
if (!res.ok) throw new Error(res.status)
state.data = await res.json()
} catch (err) {
$('#sub').textContent = '读不到 manifest.json —— 先跑一次 publish.sh'
$('#grid').replaceChildren(el('p', { class: 'empty', text: `加载失败:${err.message}` }))
return
}
const d = state.data
$('#sub').textContent = `${d.totals.projects} 项 · ${d.totals.size} · ${d.totals.files} 个文件`
$('#stamp').textContent = `扫描于 ${new Date(d.scannedAt).toLocaleString('zh-CN')} · 根目录 ${d.root}`
renderStats()
renderServices()
renderChips()
renderGrid()
bind()
}
main()