refactor(dry-F2): centralize shared UI primitives (relative-time, toast, download-status)

- utils/date.js: add formatRelative(iso, {future,nullText}); migrate 6 sites
  (SourceRow, SubscriptionsTab, SourceHealthDot, SchedulerStatusBar +
  thin adapters in BackupRunsTable/SystemActivityTab for their '—' null text).
  PostCard (30d->absolute) and CredentialCard (mo/y buckets) intentionally
  keep bespoke formatters.
- utils/toast.js: toast(opts) wraps the globalThis.window?.__fcToast?.(...)
  incantation; migrate 63 call sites across 24 files.
- utils/downloadStatus.js: single source for the download-event status enum
  -> label/color/icon; collapse the 3 duplicate maps (DownloadStatChips,
  DownloadsFilterPopover, DownloadEventRow).

Net -33 lines. Platform metadata was already centralized in platformColor.js.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-28 11:20:07 -04:00
parent 2358cedf3e
commit eebc8e2413
34 changed files with 166 additions and 170 deletions
@@ -20,6 +20,7 @@
</template>
<script setup>
import { toast } from '../../utils/toast.js'
import { ref, watch } from 'vue'
import { useSourcesStore } from '../../stores/sources.js'
@@ -44,7 +45,7 @@ async function submit() {
busy.value = true
try {
const { artist, created } = await store.findOrCreateArtist(name.value.trim())
globalThis.window?.__fcToast?.({
toast({
text: created ? 'Artist created' : 'Artist already exists',
type: 'success',
})
@@ -98,6 +98,7 @@
</template>
<script setup>
import { toast } from '../../utils/toast.js'
import { computed, ref } from 'vue'
import PlatformChip from './PlatformChip.vue'
import { useCredentialsStore } from '../../stores/credentials.js'
@@ -126,11 +127,11 @@ async function onVerify() {
const res = await credsStore.verify(props.platform.key)
verifyResult.value = res
const type = res.valid === true ? 'success' : (res.valid === false ? 'error' : 'info')
window.__fcToast?.({ text: `${props.platform.name}: ${res.reason}`, type })
toast({ text: `${props.platform.name}: ${res.reason}`, type })
if (res.valid === true) emit('verified')
} catch (e) {
verifyResult.value = { valid: false, reason: e.message }
window.__fcToast?.({ text: `Verify failed: ${e.message}`, type: 'error' })
toast({ text: `Verify failed: ${e.message}`, type: 'error' })
} finally {
verifying.value = false
}
@@ -1,38 +1,30 @@
<template>
<div class="fc-dl-stats">
<v-chip
v-for="s in STAT_DEFS" :key="s.key"
v-for="s in STAT_DEFS" :key="s.value"
:color="s.color"
:variant="activeStatus === s.key ? 'elevated' : 'tonal'"
:variant="activeStatus === s.value ? 'elevated' : 'tonal'"
:prepend-icon="s.icon"
size="default"
:class="{ 'fc-dl-stats__active': activeStatus === s.key }"
@click="$emit('select', activeStatus === s.key ? null : s.key)"
:class="{ 'fc-dl-stats__active': activeStatus === s.value }"
@click="$emit('select', activeStatus === s.value ? null : s.value)"
>
{{ s.label }}
<strong class="ms-1">{{ stats[s.key] ?? 0 }}</strong>
<strong class="ms-1">{{ stats[s.value] ?? 0 }}</strong>
</v-chip>
</div>
</template>
<script setup>
import { DOWNLOAD_STATUSES as STAT_DEFS } from '../../utils/downloadStatus.js'
defineProps({
stats: { type: Object, required: true },
// The currently-active status filter key (pending|running|ok|error|
// The currently-active status filter value (pending|running|ok|error|
// skipped) or null. Highlights the matching chip.
activeStatus: { type: String, default: null },
})
defineEmits(['select'])
// status keys come straight from the backend ENUM
// (pending|running|ok|error|skipped); display order + icons are UI-only.
const STAT_DEFS = [
{ key: 'pending', label: 'Queued', color: 'grey', icon: 'mdi-clock-outline' },
{ key: 'running', label: 'Running', color: 'info', icon: 'mdi-progress-clock' },
{ key: 'ok', label: 'Completed', color: 'success', icon: 'mdi-check-circle' },
{ key: 'error', label: 'Failed', color: 'error', icon: 'mdi-alert-circle' },
{ key: 'skipped', label: 'Skipped', color: 'warning', icon: 'mdi-skip-next' },
]
</script>
<style scoped>
@@ -68,6 +68,7 @@
import { computed, reactive, ref, watch } from 'vue'
import { useSourcesStore } from '../../stores/sources.js'
import { DOWNLOAD_STATUSES, downloadStatusLabel } from '../../utils/downloadStatus.js'
const props = defineProps({
modelValue: { type: Object, required: true },
@@ -76,14 +77,7 @@ const emit = defineEmits(['update:modelValue'])
const sourcesStore = useSourcesStore()
const STATUS_OPTIONS = [
{ title: 'Queued', value: 'pending' },
{ title: 'Running', value: 'running' },
{ title: 'Completed', value: 'ok' },
{ title: 'Failed', value: 'error' },
{ title: 'Skipped', value: 'skipped' },
]
const STATUS_LABEL = Object.fromEntries(STATUS_OPTIONS.map((o) => [o.value, o.title]))
const STATUS_OPTIONS = DOWNLOAD_STATUSES.map((s) => ({ title: s.label, value: s.value }))
const open = ref(false)
const local = reactive({
@@ -122,7 +116,7 @@ function onArtistPick(id) {
const activePills = computed(() => {
const out = []
if (local.status) out.push({ key: 'status', label: `Status: ${STATUS_LABEL[local.status] || local.status}` })
if (local.status) out.push({ key: 'status', label: `Status: ${downloadStatusLabel(local.status)}` })
if (local.artist_id) out.push({ key: 'artist_id', label: `Artist: ${local.artist_name || `#${local.artist_id}`}` })
if (local.from_date) out.push({ key: 'from_date', label: `From ${local.from_date}` })
if (local.to_date) out.push({ key: 'to_date', label: `To ${local.to_date}` })
@@ -113,6 +113,7 @@
</template>
<script setup>
import { toast } from '../../utils/toast.js'
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
@@ -167,12 +168,12 @@ async function refresh() {
async function onRetrySource(source) {
try {
await sourcesStore.checkNow(source.id)
globalThis.window?.__fcToast?.({ text: `Retry queued for ${source.artist_name || source.platform}`, type: 'success' })
toast({ text: `Retry queued for ${source.artist_name || source.platform}`, type: 'success' })
} catch (e) {
if (e?.body?.download_event_id) {
globalThis.window?.__fcToast?.({ text: 'Already running — see below', type: 'info' })
toast({ text: 'Already running — see below', type: 'info' })
} else {
globalThis.window?.__fcToast?.({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
toast({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
}
} finally {
await Promise.all([store.loadFailing(), store.loadStats(24), store.loadFirst()])
@@ -199,7 +200,7 @@ async function onRetryAll(sources) {
const parts = []
if (ok) parts.push(`${ok} queued`)
if (conflict) parts.push(`${conflict} already running`)
globalThis.window?.__fcToast?.({ text: parts.join(', ') || 'Nothing to retry', type: 'info' })
toast({ text: parts.join(', ') || 'Nothing to retry', type: 'info' })
}
// Live auto-refresh: while any download is queued or running, poll the
@@ -31,6 +31,7 @@
</template>
<script setup>
import { toast } from '../../utils/toast.js'
import { useImportStore } from '../../stores/import.js'
const emit = defineEmits(['refresh'])
@@ -39,10 +40,10 @@ const importStore = useImportStore()
async function onRetry() {
try {
await importStore.retryFailed()
globalThis.window?.__fcToast?.({ text: 'Retry queued', type: 'success' })
toast({ text: 'Retry queued', type: 'success' })
emit('refresh')
} catch (e) {
globalThis.window?.__fcToast?.({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
toast({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
}
}
@@ -50,13 +51,13 @@ async function onClear() {
try {
const body = await importStore.clearStuck()
const n = body?.cleared ?? 0
globalThis.window?.__fcToast?.({
toast({
text: n ? `Cleared ${n} stuck task${n === 1 ? '' : 's'}` : 'Nothing stuck',
type: 'success',
})
emit('refresh')
} catch (e) {
globalThis.window?.__fcToast?.({ text: `Clear failed: ${e?.detail || e?.message || e}`, type: 'error' })
toast({ text: `Clear failed: ${e?.detail || e?.message || e}`, type: 'error' })
}
}
</script>
@@ -24,6 +24,7 @@
<script setup>
import { computed } from 'vue'
import { formatRelative } from '../../utils/date.js'
const props = defineProps({
// { last_tick_at, next_due_at, due_now, auto_sources } | null
@@ -45,16 +46,8 @@ const health = computed(() => {
return tickAgeMs.value <= STALE_MS ? 'ok' : 'stale'
})
function rel(ms) {
const s = Math.max(0, Math.floor(ms / 1000))
if (s < 60) return `${s}s ago`
if (s < 3600) return `${Math.floor(s / 60)}m ago`
if (s < 86400) return `${Math.floor(s / 3600)}h ago`
return `${Math.floor(s / 86400)}d ago`
}
const lastRanLabel = computed(() =>
tickAgeMs.value == null ? 'never' : rel(tickAgeMs.value),
formatRelative(props.status?.last_tick_at, { nullText: 'never' }),
)
const nextLabel = computed(() => {
@@ -22,6 +22,7 @@
<script setup>
import { computed } from 'vue'
import { formatRelative } from '../../utils/date.js'
const props = defineProps({
source: { type: Object, required: true },
@@ -38,28 +39,13 @@ const level = computed(() => {
const ariaLabel = computed(() => `source health: ${level.value}`)
function relativeTime(iso) {
if (!iso) return 'Never'
const then = new Date(iso).getTime()
const now = Date.now()
const diff = Math.abs(now - then) / 1000
if (diff < 60) return `${Math.floor(diff)}s`
if (diff < 3600) return `${Math.floor(diff / 60)}m`
if (diff < 86400) return `${Math.floor(diff / 3600)}h`
return `${Math.floor(diff / 86400)}d`
}
const lastCheckedText = computed(() => formatRelative(props.source.last_checked_at))
const lastCheckedText = computed(() => {
if (!props.source.last_checked_at) return 'Never'
return `${relativeTime(props.source.last_checked_at)} ago`
})
const nextCheckText = computed(() => {
if (!props.source.next_check_at) return null
const due = new Date(props.source.next_check_at).getTime()
if (due <= Date.now()) return 'imminent'
return `in ~${relativeTime(props.source.next_check_at)}`
})
const nextCheckText = computed(() =>
props.source.next_check_at
? formatRelative(props.source.next_check_at, { future: true })
: null,
)
const truncatedError = computed(() => {
const e = props.source.last_error || ''
@@ -62,6 +62,7 @@
<script setup>
import SourceHealthDot from './SourceHealthDot.vue'
import { formatRelative } from '../../utils/date.js'
const props = defineProps({
source: { type: Object, required: true },
@@ -73,23 +74,6 @@ const emit = defineEmits(['edit', 'remove', 'toggle', 'check'])
function onToggleEnabled(value) {
emit('toggle', { source: props.source, enabled: value })
}
function formatRelative(iso, opts = {}) {
if (!iso) return opts.future ? '—' : 'Never'
const then = new Date(iso).getTime()
const now = Date.now()
const diff = (then - now) / 1000 // seconds; positive = future, negative = past
const abs = Math.abs(diff)
let body
if (abs < 60) body = `${Math.floor(abs)}s`
else if (abs < 3600) body = `${Math.floor(abs / 60)}m`
else if (abs < 86400) body = `${Math.floor(abs / 3600)}h`
else body = `${Math.floor(abs / 86400)}d`
if (opts.future) return diff <= 0 ? 'imminent' : `in ${body}`
return `${body} ago`
}
</script>
<style scoped>
@@ -199,6 +199,7 @@
</template>
<script setup>
import { toast } from '../../utils/toast.js'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSourcesStore } from '../../stores/sources.js'
@@ -210,6 +211,7 @@ import SourceFormDialog from './SourceFormDialog.vue'
import ArtistCreateDialog from './ArtistCreateDialog.vue'
import PlatformChip from './PlatformChip.vue'
import SchedulerStatusBar from './SchedulerStatusBar.vue'
import { formatRelative } from '../../utils/date.js'
const ITEMS_PER_PAGE_OPTIONS = [
{ value: 25, title: '25' },
@@ -365,16 +367,6 @@ function pickWorstSource(sources, threshold) {
return sources.reduce((worst, s) => (level(s) > level(worst) ? s : worst), sources[0])
}
function formatRelative(iso) {
if (!iso) return 'Never'
const then = new Date(iso).getTime()
const diff = (Date.now() - then) / 1000
if (diff < 60) return `${Math.floor(diff)}s ago`
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
return `${Math.floor(diff / 86400)}d ago`
}
function onRowClick(_evt, { item }) {
const key = item.key
const idx = expanded.value.indexOf(key)
@@ -419,19 +411,19 @@ function onArtistCreated(artist) {
async function onCheck(source) {
try {
const body = await store.checkNow(source.id)
globalThis.window?.__fcToast?.({
toast({
text: `Check enqueued (event #${body.download_event_id})`,
type: 'success',
})
} catch (e) {
if (e?.body?.download_event_id) {
globalThis.window?.__fcToast?.({
toast({
text: 'Already running — see Downloads',
type: 'info',
})
router.push({ path: '/subscriptions', query: { tab: 'downloads', source_id: source.id } })
} else {
globalThis.window?.__fcToast?.({
toast({
text: `Check failed: ${e?.detail || e?.message || e}`,
type: 'error',
})
@@ -454,7 +446,7 @@ async function checkAll(group) {
const parts = []
if (ok) parts.push(`${ok} queued`)
if (conflict) parts.push(`${conflict} already running`)
globalThis.window?.__fcToast?.({
toast({
text: parts.join(', ') || 'Nothing to check (no enabled sources)',
type: 'info',
})
@@ -481,7 +473,7 @@ async function bulkSetEnabled(enabled) {
}
}
await refresh()
globalThis.window?.__fcToast?.({
toast({
text: `${changed} source${changed === 1 ? '' : 's'} ${enabled ? 'enabled' : 'disabled'}`,
type: 'success',
})
@@ -504,7 +496,7 @@ async function bulkDelete() {
}
}
await refresh()
globalThis.window?.__fcToast?.({
toast({
text: `${deleted} source${deleted === 1 ? '' : 's'} deleted`,
type: 'success',
})