refactor(admin): share the GitHub release history between desktop and phone

useGithubReleases holds the paged fetch, the prerelease filter, the expanded rows and the date format, and parseReleaseNotes splits a release body into the blocks both panels draw. The phone keeps its page walk past hidden prereleases through the fillPages option, its repository link and its own inline link scan; the desktop keeps one page per load.
This commit is contained in:
Maurice
2026-10-09 10:12:17 +02:00
parent 67f20829f7
commit 81decb843d
6 changed files with 475 additions and 241 deletions
@@ -1,24 +1,11 @@
import { useState, useEffect, type ReactNode } from 'react'
import { type ReactNode } from 'react'
import { Tag, Calendar, ExternalLink, ChevronDown, ChevronUp, Loader2, Heart, Coffee, Bug, Lightbulb, BookOpen } from 'lucide-react'
import { getLocaleForLanguage, useTranslation } from '../../../i18n'
import apiClient from '../../../api/client'
import { useTranslation } from '../../../i18n'
import { useGithubReleases } from '../../../components/Admin/useGithubReleases'
import { escapeReleaseHtml as escapeHtml, parseReleaseNotes } from '../../../utils/releaseNotes'
import { MAdminButton, MAdminCard } from './MAdminUi'
const REPO = 'mauriceboe/TREK'
const PER_PAGE = 10
const MAX_PAGES_PER_LOAD = 5
interface GithubRelease {
id: number
prerelease: boolean
tag_name: string
name: string | null
body: string | null
published_at: string | null
created_at: string
author: { login: string } | null
[key: string]: unknown
}
// Support / community link cards (design: brand-tinted icon tile + title/sub).
// Brand hex stays as content identity; every surface/border uses --m-* tokens.
@@ -31,94 +18,15 @@ interface LinkCard {
}
export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelease?: boolean }) {
const { t, language } = useTranslation()
const [releases, setReleases] = useState<GithubRelease[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [expanded, setExpanded] = useState<Record<number, boolean>>({})
const [page, setPage] = useState(1)
const [hasMore, setHasMore] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const isShown = (release: GithubRelease) => isPrerelease || !release.prerelease
const fetchPage = async (pageNum: number) => {
try {
const res = await apiClient.get(`/admin/github-releases`, { params: { per_page: PER_PAGE, page: pageNum } })
return Array.isArray(res.data) ? res.data as GithubRelease[] : []
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Unknown error')
return null
}
}
// Keep pulling pages until at least one release survives the prerelease filter,
// otherwise a page of nothing but prereleases leaves an empty timeline behind a
// "Load more" button. MAX_PAGES_PER_LOAD bounds the walk.
const loadFrom = async (startPage: number, append: boolean) => {
const collected: GithubRelease[] = []
let pageNum = startPage
let more = true
for (let i = 0; i < MAX_PAGES_PER_LOAD; i++) {
const data = await fetchPage(pageNum)
if (!data) return
collected.push(...data)
more = data.length === PER_PAGE
if (!more || collected.some(isShown)) break
pageNum += 1
}
setReleases(prev => append ? [...prev, ...collected] : collected)
setHasMore(more)
setPage(pageNum)
setError(null)
}
useEffect(() => {
setLoading(true)
void loadFrom(1, false).finally(() => setLoading(false))
}, [])
const handleLoadMore = async () => {
setLoadingMore(true)
await loadFrom(page + 1, true)
setLoadingMore(false)
}
const toggleExpand = (id: number) => {
setExpanded(prev => ({ ...prev, [id]: !prev[id] }))
}
const formatDate = (dateStr: string) => {
const d = new Date(dateStr)
return d.toLocaleDateString(getLocaleForLanguage(language), { day: 'numeric', month: 'short', year: 'numeric' })
}
const { t } = useTranslation()
const {
releases, shownReleases, loading, error, expanded, toggleExpand, hasMore, loadingMore, handleLoadMore, formatDate,
} = useGithubReleases({ isPrerelease, fillPages: true })
// Simple markdown-to-html for release notes (handles headers, bold, lists, links)
const renderBody = (body: string | null) => {
if (!body) return null
const lines = body.split('\n')
const elements: ReactNode[] = []
let listItems: string[] = []
const flushList = () => {
if (listItems.length > 0) {
elements.push(
<ul key={`ul-${elements.length}`} className="space-y-1 my-2">
{listItems.map((item, i) => (
<li key={i} className="flex gap-2 text-xs text-m-muted">
<span className="mt-1.5 w-1 h-1 rounded-full flex-shrink-0" style={{ background: 'var(--m-faint)' }} />
<span dangerouslySetInnerHTML={{ __html: inlineFormat(item) }} />
</li>
))}
</ul>
)
listItems = []
}
}
const escapeHtml = (str: string) => str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
// `[label](url)` → anchor, exactly as /\[([^\]]+)\]\(([^)]+)\)/g did. Written as a
// scan because that pattern backtracks from both ends: `[^\]]` matches `[` and
// `[^)]` matches `(`, so a run of either made the engine retry the whole match from
@@ -162,37 +70,39 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
)
}
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) { flushList(); continue }
if (trimmed.startsWith('### ')) {
flushList()
elements.push(
<h4 key={elements.length} className="text-xs font-semibold mt-3 mb-1 text-m-ink">
{trimmed.slice(4)}
</h4>
)
} else if (trimmed.startsWith('## ')) {
flushList()
elements.push(
<h3 key={elements.length} className="text-sm font-semibold mt-3 mb-1 text-m-ink">
{trimmed.slice(3)}
</h3>
)
} else if (/^[-*] /.test(trimmed)) {
listItems.push(trimmed.slice(2))
} else {
flushList()
elements.push(
<p key={elements.length} className="text-xs my-1 text-m-muted"
dangerouslySetInnerHTML={{ __html: inlineFormat(trimmed) }}
/>
return parseReleaseNotes(body).map((block, idx) => {
if (block.kind === 'ul') {
return (
<ul key={`ul-${idx}`} className="space-y-1 my-2">
{block.items.map((item, i) => (
<li key={i} className="flex gap-2 text-xs text-m-muted">
<span className="mt-1.5 w-1 h-1 rounded-full flex-shrink-0" style={{ background: 'var(--m-faint)' }} />
<span dangerouslySetInnerHTML={{ __html: inlineFormat(item) }} />
</li>
))}
</ul>
)
}
}
flushList()
return elements
if (block.kind === 'h4') {
return (
<h4 key={idx} className="text-xs font-semibold mt-3 mb-1 text-m-ink">
{block.text}
</h4>
)
}
if (block.kind === 'h3') {
return (
<h3 key={idx} className="text-sm font-semibold mt-3 mb-1 text-m-ink">
{block.text}
</h3>
)
}
return (
<p key={idx} className="text-xs my-1 text-m-muted"
dangerouslySetInnerHTML={{ __html: inlineFormat(block.text) }}
/>
)
})
}
const discordIcon = (
@@ -208,8 +118,6 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
{ href: 'https://github.com/mauriceboe/TREK/wiki', color: '#6366f1', icon: <BookOpen size={18} className="text-[#6366f1]" />, title: 'Wiki', sub: t('settings.about.wikiHint') },
]
const shownReleases = releases.filter(isShown)
return (
<div className="space-y-3">
{/* Support / community cards */}