Restyle the status page in Cottage's brand

The page (pages/, components/, styles/) is rewritten in Cottage's brand, replacing Mantine.
- Brand files: tokens, fonts and component CSS copied from Hearth; logo, pod row, status
  pill and banner ported from the brand handbook.
- Themes: light by default, dark when the OS asks.
- Services: grouped; each has a status pill, uptime and 90 daily bars (30 on phones).
- Bars: each bar has a text label, keyboard navigation and a day card.
- Response-time chart: optional, drawn in brand colours.
- Notices: colour-coded posted notices and planned maintenance.
- Incident history: by month, with the brand's empty state.

The check worker, D1 storage, types and Terraform are untouched, so upstream merges stay
clean. uptime.config.ts lists Cottage's services (website, dashboard, apps in US East).
`npm run dev` shows sample data (?sample=outage|maintenance|empty) since there's no D1.

Deploys are gated on the CLOUDFLARE_DEPLOY repository variable until launch, Wrangler
telemetry is off, and a Check workflow lints, type-checks and builds every pull request.
Removed upstream's issue-translation workflow, funding file and translations.
This commit is contained in:
Michael Kinder committed 2026-11-21 14:04:00 -05:00
1 parent 8035521268
commit fdc16007e3
54 files changed
+2197 -2705

No files matched your search

-160
View File
@@ -1,160 +0,0 @@
import { MonitorState, MonitorTarget } from '@/types/config'
import { getColor } from '@/util/color'
import { Box, Tooltip, Modal } from '@mantine/core'
import { useResizeObserver } from '@mantine/hooks'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
const moment = require('moment')
require('moment-precise-range-plugin')
export default function DetailBar({
monitor,
state,
}: {
monitor: MonitorTarget
state: MonitorState
}) {
const { t } = useTranslation('common')
const [barRef, barRect] = useResizeObserver()
const [modalOpened, setModalOpened] = useState(false)
const [modalTitle, setModalTitle] = useState('')
const [modelContent, setModelContent] = useState(<div />)
const overlapLen = (x1: number, x2: number, y1: number, y2: number) => {
return Math.max(0, Math.min(x2, y2) - Math.max(x1, y1))
}
const uptimePercentBars = []
const currentTime = Math.round(Date.now() / 1000)
const montiorStartTime = state.incident[monitor.id][0].start[0]
const todayStart = new Date()
todayStart.setHours(0, 0, 0, 0)
for (let i = 89; i >= 0; i--) {
const dayStart = Math.round(todayStart.getTime() / 1000) - i * 86400
const dayEnd = dayStart + 86400
const dayMonitorTime = overlapLen(dayStart, dayEnd, montiorStartTime, currentTime)
let dayDownTime = 0
let incidentReasons: string[] = []
for (let incident of state.incident[monitor.id]) {
const incidentStart = incident.start[0]
const incidentEnd = incident.end ?? currentTime
const overlap = overlapLen(dayStart, dayEnd, incidentStart, incidentEnd)
dayDownTime += overlap
// Incident history for the day
if (overlap > 0) {
for (let i = 0; i < incident.error.length; i++) {
let partStart = incident.start[i]
let partEnd =
i === incident.error.length - 1 ? incident.end ?? currentTime : incident.start[i + 1]
partStart = Math.max(partStart, dayStart)
partEnd = Math.min(partEnd, dayEnd)
if (overlapLen(dayStart, dayEnd, partStart, partEnd) > 0) {
const startStr = new Date(partStart * 1000).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})
const endStr = new Date(partEnd * 1000).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})
incidentReasons.push(`[${startStr}-${endStr}] ${incident.error[i]}`)
}
}
}
}
const dayPercent = (((dayMonitorTime - dayDownTime) / dayMonitorTime) * 100).toPrecision(4)
uptimePercentBars.push(
<Tooltip
multiline
key={i}
events={{ hover: true, focus: false, touch: true }}
label={
Number.isNaN(Number(dayPercent)) ? (
t('No Data')
) : (
<>
<div>
{t('percent at date', {
percent: dayPercent,
date: new Date(dayStart * 1000).toLocaleDateString(),
})}
</div>
{dayDownTime > 0 && (
<div>
{t('Down for', {
duration: moment.preciseDiff(moment(0), moment(dayDownTime * 1000)),
})}
</div>
)}
</>
)
}
>
<div
style={{
height: '20px',
width: '7px',
background: getColor(dayPercent, false),
borderRadius: '2px',
marginLeft: '1px',
marginRight: '1px',
}}
onClick={() => {
if (dayDownTime > 0) {
setModalTitle(
t('incidents at', {
name: monitor.name,
date: new Date(dayStart * 1000).toLocaleDateString(),
})
)
setModelContent(
<>
{incidentReasons.map((reason, index) => (
<div key={index}>{reason}</div>
))}
</>
)
setModalOpened(true)
}
}}
/>
</Tooltip>
)
}
return (
<>
<Modal
opened={modalOpened}
onClose={() => setModalOpened(false)}
title={modalTitle}
size={'40em'}
>
{modelContent}
</Modal>
<Box
style={{
display: 'flex',
flexWrap: 'nowrap',
marginTop: '10px',
marginBottom: '5px',
}}
visibleFrom="540"
ref={barRef}
>
{uptimePercentBars.slice(Math.floor(Math.max(9 * 90 - barRect.width, 0) / 9), 90)}
</Box>
</>
)
}
-102
View File
@@ -1,102 +0,0 @@
import { Line } from 'react-chartjs-2'
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip as ChartTooltip,
Legend,
TimeScale,
} from 'chart.js'
import 'chartjs-adapter-moment'
import { MonitorState, MonitorTarget } from '@/types/config'
import { codeToCountry } from '@/util/iata'
import { useTranslation } from 'react-i18next'
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
ChartTooltip,
Legend,
TimeScale
)
export default function DetailChart({
monitor,
state,
}: {
monitor: MonitorTarget
state: MonitorState
}) {
const { t } = useTranslation('common')
const latencyData = state.latency[monitor.id].map((point) => ({
x: point.time * 1000,
y: point.ping,
loc: point.loc,
}))
let data = {
datasets: [
{
data: latencyData,
borderColor: 'rgb(112, 119, 140)',
borderWidth: 2,
radius: 0,
cubicInterpolationMode: 'monotone' as const,
tension: 0.4,
},
],
}
let options = {
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'index' as const,
intersect: false,
},
animation: {
duration: 0,
},
plugins: {
tooltip: {
callbacks: {
label: (item: any) => {
if (item.parsed.y) {
return `${item.parsed.y}ms (${codeToCountry(item.raw.loc)})`
}
},
},
},
legend: {
display: false,
},
title: {
display: true,
text: t('Response times'),
align: 'start' as const,
},
},
scales: {
x: {
type: 'time' as const,
ticks: {
source: 'auto' as const,
maxRotation: 0,
autoSkip: true,
},
},
},
}
return (
<div style={{ height: '150px' }}>
<Line options={options} data={data} />
</div>
)
}
+27 -9
View File
@@ -1,14 +1,32 @@
import { Divider } from '@mantine/core'
import { pageConfig } from '@/uptime.config'
import { Logo } from './brand'
// The site footer from the brand handbook, trimmed for a single-purpose page.
export default function Footer() {
const defaultFooter =
'<p style="text-align: center; font-size: 12px; margin-top: 10px;"> Open-source monitoring and status page powered by <a href="https://github.com/lyc8503/UptimeFlare" target="_blank">UptimeFlare</a>, made with ❤ by <a href="https://github.com/lyc8503" target="_blank">lyc8503</a>. </p>'
return (
<>
<Divider mt="lg" />
<div dangerouslySetInnerHTML={{ __html: pageConfig.customFooter ?? defaultFooter }} />
</>
<footer className="st-footer">
<div className="st-container st-container--narrow">
<div className="st-footer__top">
<a href="https://cottage.host" className="st-footer__brand" aria-label="Cottage home">
<Logo variant="mono" size={32} />
</a>
<p className="st-footer__about">
Cottage runs open-source apps for you, kept warm. This page checks our services every
minute from Cloudflare&rsquo;s network.
</p>
</div>
<div className="st-footer__bottom">
<span>&copy; {new Date().getFullYear()} Cottage Host</span>
<a href="https://cottage.host">cottage.host</a>
{/* an API route, not a page */}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
<a href="/api/data">Status API</a>
<span>
Built on{' '}
<a href="https://github.com/lyc8503/UptimeFlare">UptimeFlare</a>, open source (
<a href="https://github.com/cottage-host/status">our copy</a>)
</span>
</div>
</div>
</footer>
)
}
+33 -46
View File
@@ -1,53 +1,40 @@
import { Container, Group, Image } from '@mantine/core'
import classes from '@/styles/Header.module.css'
import Link from 'next/link'
import { pageConfig } from '@/uptime.config'
import { PageConfigLink } from '@/types/config'
import { useTranslation } from 'react-i18next'
export default function Header({ style }: { style?: React.CSSProperties }) {
const { t } = useTranslation('common')
const linkToElement = (link: PageConfigLink, i: number) => {
return (
<a
key={i}
href={link.link}
target={link.link.startsWith('/') ? undefined : '_blank'}
className={classes.link}
data-active={link.highlight}
>
{link.label}
</a>
)
}
const links = [{ label: t('Incidents'), link: '/incidents' }, ...(pageConfig.links || [])]
import { Logo } from './brand'
// The site header from the brand handbook (SiteHeader): lockup left, nav, actions right.
export default function Header({ current }: { current: 'status' | 'incidents' }) {
const nav = [
{ key: 'status', label: 'Current status', href: '/' },
{ key: 'incidents', label: 'Incident history', href: '/incidents' },
]
return (
<header className={classes.header} style={style}>
<Container size="md" className={classes.inner}>
<div>
<a
href={location.pathname == '/' ? 'https://github.com/lyc8503/UptimeFlare' : '/'}
target={location.pathname == '/' ? '_blank' : undefined}
>
<Image
src={pageConfig.logo ?? '/logo.svg'}
h={56}
w={{ base: 140, sm: 190 }}
fit="contain"
alt="logo"
/>
</a>
<header className="ct-site-header">
<div className="ct-site-header__inner st-header">
<Link href="/" className="ct-site-header__home st-header__home" aria-label="Cottage status, home">
<Logo size={32} />
<span className="st-header__tag">Status</span>
</Link>
<nav className="st-header__nav" aria-label="Status pages">
{nav.map((l) => (
<Link
key={l.key}
href={l.href}
className={`ct-site-header__link${current === l.key ? ' is-current' : ''}`}
aria-current={current === l.key ? 'page' : undefined}
>
{l.label}
</Link>
))}
</nav>
<div className="ct-site-header__actions st-header__actions">
{(pageConfig.links || []).map((l) => (
<a key={l.link} href={l.link} className={`ct-btn ct-btn--sm ${l.highlight ? 'ct-btn--secondary' : 'ct-btn--quiet'}`}>
{l.label}
</a>
))}
</div>
<Group gap={5} visibleFrom="sm">
{links?.map(linkToElement)}
</Group>
<Group gap={5} hiddenFrom="sm">
{links?.filter((link) => link.highlight || link.link.startsWith('/')).map(linkToElement)}
</Group>
</Container>
</div>
</header>
)
}
+100
View File
@@ -0,0 +1,100 @@
import { useEffect, useState } from 'react'
import { Line } from 'react-chartjs-2'
import {
Chart as ChartJS,
LinearScale,
PointElement,
LineElement,
Tooltip,
Filler,
} from 'chart.js'
import { MonitorState, MonitorTarget } from '@/types/config'
import { codeToCountry } from '@/util/iata'
import { formatTime } from '@/util/status'
ChartJS.register(LinearScale, PointElement, LineElement, Tooltip, Filler)
// Chart.js draws on a canvas, so read the brand tokens from CSS (and again if the theme changes).
function useTokens() {
const read = () => {
const s = getComputedStyle(document.documentElement)
const v = (n: string) => s.getPropertyValue(n).trim()
return { moss: v('--moss'), mossSoft: v('--moss-soft'), line: v('--line'), muted: v('--ink-muted'), ink: v('--ink'), raised: v('--paper-raised'), strong: v('--line-strong') }
}
const [t, setT] = useState(read)
useEffect(() => {
const obs = new MutationObserver(() => setT(read()))
obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
return () => obs.disconnect()
}, [])
return t
}
export default function LatencyChart({ monitor, state }: { monitor: MonitorTarget; state: MonitorState }) {
const t = useTokens()
const points = (state.latency[monitor.id] || []).map((p) => ({ x: p.time, y: p.ping, loc: p.loc }))
const font = { family: getComputedStyle(document.body).fontFamily, size: 12 }
return (
<div className="st-chart">
<Line
aria-label={`Response times for ${monitor.name} over the last 12 hours`}
role="img"
data={{
datasets: [
{
data: points,
borderColor: t.moss,
backgroundColor: t.mossSoft,
fill: 'origin',
borderWidth: 2,
pointRadius: 0,
pointHoverRadius: 3,
cubicInterpolationMode: 'monotone',
},
],
}}
options={{
responsive: true,
maintainAspectRatio: false,
animation: false,
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: t.raised,
titleColor: t.ink,
bodyColor: t.muted,
borderColor: t.strong,
borderWidth: 1,
padding: 10,
displayColors: false,
titleFont: { ...font, weight: 'bold' },
bodyFont: font,
callbacks: {
title: (items) => formatTime(items[0].parsed.x as number),
label: (item) => `${item.parsed.y} ms from ${codeToCountry((item.raw as any).loc)}`,
},
},
},
scales: {
x: {
type: 'linear',
min: points[0]?.x,
max: points[points.length - 1]?.x,
border: { display: false },
grid: { display: false },
ticks: { color: t.muted, font, maxTicksLimit: 7, callback: (v) => formatTime(Number(v)) },
},
y: {
beginAtZero: true,
border: { display: false },
grid: { color: t.line },
ticks: { color: t.muted, font, maxTicksLimit: 4, callback: (v) => `${v} ms` },
},
},
}}
/>
</div>
)
}
-95
View File
@@ -1,95 +0,0 @@
import { Alert, List, Text, useMantineTheme } from '@mantine/core'
import { useMediaQuery } from '@mantine/hooks'
import { IconAlertTriangle } from '@tabler/icons-react'
import { MaintenanceConfig, MonitorTarget } from '@/types/config'
import { pageConfig } from '@/uptime.config'
import { useTranslation } from 'react-i18next'
export default function MaintenanceAlert({
maintenance,
style,
upcoming = false,
}: {
maintenance: Omit<MaintenanceConfig, 'monitors'> & { monitors?: (MonitorTarget | undefined)[] }
style?: React.CSSProperties
upcoming?: boolean
}) {
const { t } = useTranslation('common')
const theme = useMantineTheme()
const isDesktop = useMediaQuery(`(min-width: ${theme.breakpoints.sm})`)
return (
<Alert
icon={<IconAlertTriangle />}
title={
<span
style={{
fontSize: '1rem',
fontWeight: 700,
}}
>
{(upcoming ? t('Upcoming') : '') + (maintenance.title || t('Scheduled Maintenance'))}
</span>
}
color={
upcoming ? pageConfig.maintenances?.upcomingColor ?? 'gray' : maintenance.color || 'yellow'
}
withCloseButton={false}
style={{ margin: '16px auto 0 auto', ...style }}
>
{/* Date range in top right (desktop) or inline (mobile) */}
<div
style={{
...{
top: 10,
fontSize: '0.85rem',
borderRadius: 6,
},
...(isDesktop
? {
position: 'absolute',
right: 10,
padding: '2px 8px',
textAlign: 'right',
}
: { marginBottom: 4 }),
}}
>
<div
style={{
display: 'grid',
gridTemplateColumns: 'auto 1fr',
gridColumnGap: '3px',
}}
>
<div style={{ textAlign: 'right', fontWeight: 'bold' }}>
{upcoming ? t('Scheduled for') : t('From')}
</div>
<div>{new Date(maintenance.start).toLocaleString()}</div>
<div style={{ textAlign: 'right', fontWeight: 'bold' }}>
{upcoming ? t('Expected end') : t('To')}
</div>
<div>
{maintenance.end
? new Date(maintenance.end).toLocaleString()
: t('Until further notice')}
</div>
</div>
</div>
<Text style={{ paddingTop: '3px', whiteSpace: 'pre-line' }}>{maintenance.body}</Text>
{maintenance.monitors && maintenance.monitors.length > 0 && (
<>
<Text mt="xs">
<b>{t('Affected components')}</b>
</Text>
<List size="sm" withPadding>
{maintenance.monitors.map((comp, compIdx) => (
<List.Item key={compIdx}>{comp?.name ?? t('MONITOR ID NOT FOUND')}</List.Item>
))}
</List>
</>
)}
</Alert>
)
}
-104
View File
@@ -1,104 +0,0 @@
import { Text, Tooltip } from '@mantine/core'
import { MonitorState, MonitorTarget } from '@/types/config'
import { IconAlertCircle, IconAlertTriangle, IconCircleCheck } from '@tabler/icons-react'
import DetailChart from './DetailChart'
import DetailBar from './DetailBar'
import { getColor } from '@/util/color'
import { maintenances } from '@/uptime.config'
import { useTranslation } from 'react-i18next'
export default function MonitorDetail({
monitor,
state,
}: {
monitor: MonitorTarget
state: MonitorState
}) {
const { t } = useTranslation('common')
if (!state.latency[monitor.id])
return (
<>
<Text mt="sm" fw={700}>
{monitor.name}
</Text>
<Text mt="sm" fw={700}>
{t('No data available')}
</Text>
</>
)
let statusIcon =
state.incident[monitor.id].slice(-1)[0].end === null ? (
<IconAlertCircle
style={{ width: '1.25em', height: '1.25em', color: '#b91c1c', marginRight: '3px' }}
/>
) : (
<IconCircleCheck
style={{ width: '1.25em', height: '1.25em', color: '#059669', marginRight: '3px' }}
/>
)
// Hide real status icon if monitor is in maintenance
const now = new Date()
const hasMaintenance = maintenances
.filter((m) => now >= new Date(m.start) && (!m.end || now <= new Date(m.end)))
.find((maintenance) => maintenance.monitors?.includes(monitor.id))
if (hasMaintenance)
statusIcon = (
<IconAlertTriangle
style={{
width: '1.25em',
height: '1.25em',
color: '#fab005',
marginRight: '3px',
}}
/>
)
let totalTime = Date.now() / 1000 - state.incident[monitor.id][0].start[0]
let downTime = 0
for (let incident of state.incident[monitor.id]) {
downTime += (incident.end ?? Date.now() / 1000) - incident.start[0]
}
const uptimePercent = (((totalTime - downTime) / totalTime) * 100).toPrecision(4)
// Conditionally render monitor name with or without hyperlink based on monitor.url presence
const monitorNameElement = (
<Text mt="sm" fw={700} style={{ display: 'inline-flex', alignItems: 'center' }}>
{monitor.statusPageLink ? (
<a
href={monitor.statusPageLink}
target="_blank"
style={{ display: 'inline-flex', alignItems: 'center', color: 'inherit' }}
>
{statusIcon} {monitor.name}
</a>
) : (
<>
{statusIcon} {monitor.name}
</>
)}
</Text>
)
return (
<>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
{monitor.tooltip ? (
<Tooltip label={monitor.tooltip}>{monitorNameElement}</Tooltip>
) : (
monitorNameElement
)}
<Text mt="sm" fw={700} style={{ display: 'inline', color: getColor(uptimePercent, true) }}>
{t('Overall', { percent: uptimePercent })}
</Text>
</div>
<DetailBar monitor={monitor} state={state} />
{!monitor.hideLatencyChart && <DetailChart monitor={monitor} state={state} />}
</>
)
}
+97 -116
View File
@@ -1,133 +1,114 @@
import { MonitorState, MonitorTarget } from '@/types/config'
import { Accordion, Card, Center, Text } from '@mantine/core'
import MonitorDetail from './MonitorDetail'
import { useState } from 'react'
import { MaintenanceConfig, MonitorState, MonitorTarget } from '@/types/config'
import { pageConfig } from '@/uptime.config'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { formatPercent, monitorStatus, uptimePercent } from '@/util/status'
import { StatusPill } from './brand'
import UptimeBars from './UptimeBars'
import LatencyChart from './LatencyChart'
function countDownCount(state: MonitorState, ids: string[]) {
let downCount = 0
for (let id of ids) {
if (state.incident[id] === undefined || state.incident[id].length === 0) {
continue
}
function MonitorRow({
monitor,
state,
maintenances,
}: {
monitor: MonitorTarget
state: MonitorState
maintenances: MaintenanceConfig[]
}) {
const [open, setOpen] = useState(false)
const status = monitorStatus(state, maintenances, monitor.id)
const uptime = uptimePercent(state, monitor.id)
const hasLatency = !monitor.hideLatencyChart && (state.latency[monitor.id]?.length ?? 0) > 0
const chartId = `chart-${monitor.id}`
if (state.incident[id].slice(-1)[0].end === null) {
downCount++
}
}
return downCount
}
function getStatusTextColor(state: MonitorState, ids: string[]) {
let downCount = countDownCount(state, ids)
if (downCount === 0) {
return '#059669'
} else if (downCount === ids.length) {
return '#df484a'
} else {
return '#f29030'
}
return (
<li className="st-monitor">
<div className="st-monitor__head">
<div className="st-monitor__titles">
<h3 className="st-monitor__name">
{monitor.statusPageLink ? <a href={monitor.statusPageLink}>{monitor.name}</a> : monitor.name}
</h3>
{monitor.tooltip && <p className="st-monitor__desc">{monitor.tooltip}</p>}
</div>
<div className="st-monitor__meta">
{uptime !== null && (
<span className="st-monitor__uptime">
<strong>{formatPercent(uptime)}</strong> uptime
</span>
)}
<StatusPill status={status} />
</div>
</div>
{state.incident[monitor.id] ? (
<UptimeBars monitor={monitor} state={state} />
) : (
<p className="st-monitor__nodata">No checks have run for this service yet.</p>
)}
{hasLatency && (
<>
<button
type="button"
className="st-disclosure"
aria-expanded={open}
aria-controls={chartId}
onClick={() => setOpen(!open)}
>
<svg viewBox="0 0 16 16" width={16} height={16} aria-hidden className={open ? 'is-open' : ''}>
<path d="M6 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" />
</svg>
Response times, last 12 hours
</button>
{open && (
<div id={chartId}>
<LatencyChart monitor={monitor} state={state} />
</div>
)}
</>
)}
</li>
)
}
export default function MonitorList({
monitors,
state,
maintenances,
}: {
monitors: MonitorTarget[]
state: MonitorState
maintenances: MaintenanceConfig[]
}) {
const { t } = useTranslation('common')
const group = pageConfig.group
const groupedMonitor = group && Object.keys(group).length > 0
let content
// Load expanded groups from localStorage
const savedExpandedGroups = localStorage.getItem('expandedGroups')
const expandedInitial = savedExpandedGroups
? JSON.parse(savedExpandedGroups)
: Object.keys(group || {})
const [expandedGroups, setExpandedGroups] = useState<string[]>(expandedInitial)
useEffect(() => {
localStorage.setItem('expandedGroups', JSON.stringify(expandedGroups))
}, [expandedGroups])
if (groupedMonitor) {
// Grouped monitors
content = (
<Accordion
multiple
defaultValue={Object.keys(group)}
variant="contained"
value={expandedGroups}
onChange={(values) => setExpandedGroups(values)}
>
{Object.keys(group).map((groupName) => (
<Accordion.Item key={groupName} value={groupName}>
<Accordion.Control>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
width: '100%',
alignItems: 'center',
}}
>
<div>{groupName}</div>
<Text
fw={500}
style={{
display: 'inline',
paddingRight: '5px',
color: getStatusTextColor(state, group[groupName]),
}}
>
{group[groupName].length - countDownCount(state, group[groupName])}/
{group[groupName].length} {t('Operational')}
</Text>
</div>
</Accordion.Control>
<Accordion.Panel>
{monitors
.filter((monitor) => group[groupName].includes(monitor.id))
.sort((a, b) => group[groupName].indexOf(a.id) - group[groupName].indexOf(b.id))
.map((monitor) => (
<div key={monitor.id}>
<Card.Section ml="xs" mr="xs">
<MonitorDetail monitor={monitor} state={state} />
</Card.Section>
</div>
))}
</Accordion.Panel>
</Accordion.Item>
))}
</Accordion>
)
} else {
// Ungrouped monitors
content = monitors.map((monitor) => (
<div key={monitor.id}>
<Card.Section ml="xs" mr="xs">
<MonitorDetail monitor={monitor} state={state} />
</Card.Section>
</div>
))
}
const groups: [string, MonitorTarget[]][] =
group && Object.keys(group).length > 0
? Object.entries(group).map(([name, ids]) => [
name,
ids.map((id) => monitors.find((m) => m.id === id)).filter(Boolean) as MonitorTarget[],
])
: [['Services', monitors]]
return (
<Center>
<Card
shadow="sm"
padding="lg"
radius="md"
ml="md"
mr="md"
mt="xl"
withBorder={!groupedMonitor}
style={{ width: groupedMonitor ? '897px' : '865px' }}
>
{content}
</Card>
</Center>
<div className="st-groups">
{groups.map(([name, list]) => {
const ok = list.filter((m) => monitorStatus(state, maintenances, m.id) === 'operational').length
return (
<section key={name} className="st-group" aria-labelledby={`g-${name}`}>
<div className="st-group__head">
<h2 id={`g-${name}`} className="st-group__name">
{name}
</h2>
<span className="st-group__count">
{ok} of {list.length} operational
</span>
</div>
<ul className="st-group__list">
{list.map((m) => (
<MonitorRow key={m.id} monitor={m} state={state} maintenances={maintenances} />
))}
</ul>
</section>
)
})}
</div>
)
}
-31
View File
@@ -1,31 +0,0 @@
import { Alert, Text } from '@mantine/core'
import { IconInfoCircle } from '@tabler/icons-react'
import { useTranslation } from 'react-i18next'
export default function NoIncidentsAlert({ style }: { style?: React.CSSProperties }) {
const { t } = useTranslation('common')
return (
<Alert
icon={<IconInfoCircle />}
title={
<span
style={{
fontSize: '1rem',
fontWeight: 700,
}}
>
{t('No incidents in this month')}
</span>
}
color="gray"
withCloseButton={false}
style={{
position: 'relative',
margin: '16px auto 0 auto',
...style,
}}
>
<Text>{t('There are no incidents for this month')}</Text>
</Alert>
)
}
+35
View File
@@ -0,0 +1,35 @@
import { MaintenanceConfig, MonitorTarget } from '@/types/config'
import { formatDateTime, noticeTone } from '@/util/status'
import { Banner } from './brand'
function when(n: MaintenanceConfig) {
const now = new Date()
const start = formatDateTime(n.start)
const end = n.end ? formatDateTime(n.end) : null
if (new Date(n.start) > now) return end ? `Planned for ${start} to ${end}` : `Planned for ${start}`
if (!n.end || new Date(n.end) > now) return end ? `Since ${start}, expected to end ${end}` : `Since ${start}`
return `${start} to ${end}`
}
// A posted notice (incident update or maintenance) from `maintenances` in uptime.config.ts.
export default function Notice({
notice,
monitors,
upcoming = false,
}: {
notice: MaintenanceConfig
monitors: MonitorTarget[]
upcoming?: boolean
}) {
const affected = (notice.monitors || []).map(
(id) => monitors.find((m) => m.id === id)?.name ?? id
)
const tone = upcoming ? 'info' : noticeTone(notice.color)
return (
<Banner tone={tone as any} title={notice.title || (upcoming ? 'Planned maintenance' : 'Maintenance')}>
<p className="st-notice__when">{when(notice)}</p>
<p className="st-notice__body">{notice.body}</p>
{affected.length > 0 && <p className="st-notice__affected">Affects: {affected.join(', ')}</p>}
</Banner>
)
}
+78 -114
View File
@@ -1,137 +1,101 @@
import { MaintenanceConfig, MonitorTarget } from '@/types/config'
import { Center, Container, Title, Collapse, Button, Box } from '@mantine/core'
import { IconCircleCheck, IconAlertCircle, IconPlus, IconMinus } from '@tabler/icons-react'
import { useEffect, useState } from 'react'
import MaintenanceAlert from './MaintenanceAlert'
import { pageConfig } from '@/uptime.config'
import { useTranslation } from 'react-i18next'
import { MaintenanceConfig, MonitorState, MonitorTarget } from '@/types/config'
import { activeNotices, overallSummary, upcomingNotices } from '@/util/status'
import { PodRow, StatusIcon } from './brand'
import Notice from './Notice'
function useWindowVisibility() {
const [isVisible, setIsVisible] = useState(true)
function useNow() {
const [now, setNow] = useState(() => Math.round(Date.now() / 1000))
useEffect(() => {
const handleVisibilityChange = () => setIsVisible(document.visibilityState === 'visible')
document.addEventListener('visibilitychange', handleVisibilityChange)
return () => document.removeEventListener('visibilitychange', handleVisibilityChange)
const t = setInterval(() => {
if (document.visibilityState === 'visible') setNow(Math.round(Date.now() / 1000))
}, 1000)
return () => clearInterval(t)
}, [])
return isVisible
return now
}
function ago(seconds: number) {
if (seconds < 5) return 'just now'
if (seconds < 90) return `${seconds} seconds ago`
return `${Math.round(seconds / 60)} minutes ago`
}
export default function OverallStatus({
state,
maintenances,
monitors,
maintenances,
}: {
state: { overallUp: number; overallDown: number; lastUpdate: number }
maintenances: MaintenanceConfig[]
state: MonitorState
monitors: MonitorTarget[]
maintenances: MaintenanceConfig[]
}) {
const { t } = useTranslation('common')
let group = pageConfig.group
let groupedMonitor = (group && Object.keys(group).length > 0) || false
let statusString = ''
let icon = <IconAlertCircle style={{ width: 64, height: 64, color: '#b91c1c' }} />
if (state.overallUp === 0 && state.overallDown === 0) {
statusString = t('No data yet')
} else if (state.overallUp === 0) {
statusString = t('All systems not operational')
} else if (state.overallDown === 0) {
statusString = t('All systems operational')
icon = <IconCircleCheck style={{ width: 64, height: 64, color: '#059669' }} />
} else {
statusString = t('Some systems not operational', {
down: state.overallDown,
total: state.overallUp + state.overallDown,
})
}
const [openTime] = useState(Math.round(Date.now() / 1000))
const [currentTime, setCurrentTime] = useState(Math.round(Date.now() / 1000))
const isWindowVisible = useWindowVisibility()
const [expandUpcoming, setExpandUpcoming] = useState(false)
const now = useNow()
const [openedAt] = useState(now)
const [showUpcoming, setShowUpcoming] = useState(false)
// Reload when the data is more than five minutes old (the worker writes every minute).
useEffect(() => {
const interval = setInterval(() => {
if (!isWindowVisible) return
if (currentTime - state.lastUpdate > 300 && currentTime - openTime > 30) {
window.location.reload()
}
setCurrentTime(Math.round(Date.now() / 1000))
}, 1000)
return () => clearInterval(interval)
})
if (state.lastUpdate > 0 && now - state.lastUpdate > 300 && now - openedAt > 30) {
window.location.reload()
}
}, [now, state.lastUpdate, openedAt])
const now = new Date()
const activeMaintenances: (Omit<MaintenanceConfig, 'monitors'> & {
monitors?: MonitorTarget[]
})[] = maintenances
.filter((m) => now >= new Date(m.start) && (!m.end || now <= new Date(m.end)))
.map((maintenance) => ({
...maintenance,
monitors: maintenance.monitors?.map(
(monitorId) => monitors.find((mon) => monitorId === mon.id)!
),
}))
const upcomingMaintenances: (Omit<MaintenanceConfig, 'monitors'> & {
monitors?: (MonitorTarget | undefined)[]
})[] = maintenances
.filter((m) => now < new Date(m.start))
.map((maintenance) => ({
...maintenance,
monitors: maintenance.monitors?.map(
(monitorId) => monitors.find((mon) => monitorId === mon.id)!
),
}))
const summary = overallSummary(state, monitors, maintenances)
const active = activeNotices(maintenances)
const upcoming = upcomingNotices(maintenances)
const shape = summary.tone === 'success' ? 'dot' : summary.tone === 'neutral' ? 'ring' : summary.title.startsWith('Maintenance') ? 'spin' : 'tri'
return (
<Container size="md" mt="xl">
<Center>{icon}</Center>
<Title mt="sm" style={{ textAlign: 'center' }} order={1}>
{statusString}
</Title>
<Title mt="sm" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
{t('Last updated on', {
date: new Date(state.lastUpdate * 1000).toLocaleString(),
seconds: currentTime - state.lastUpdate,
})}
</Title>
{/* Upcoming Maintenance */}
{upcomingMaintenances.length > 0 && (
<>
<Title mt="4px" style={{ textAlign: 'center', color: '#70778c' }} order={5}>
{t('upcoming maintenance', { count: upcomingMaintenances.length })}{' '}
<span
style={{ textDecoration: 'underline', cursor: 'pointer' }}
onClick={() => setExpandUpcoming(!expandUpcoming)}
>
{expandUpcoming ? t('Hide') : t('Show')}
<section className="st-hero" aria-labelledby="st-summary">
<PodRow count={5} size={28} />
<h1 id="st-summary" className="ct-h1 st-hero__title">
<span className={`st-hero__icon st-tone--${summary.tone}`}>
<StatusIcon shape={shape} />
</span>
{summary.title}
</h1>
<p className="st-hero__lede">
{state.lastUpdate > 0 ? (
<>
Last checked {ago(now - state.lastUpdate)}
<span className="st-hero__sep" aria-hidden>
·
</span>
</Title>
checks run every minute
</>
) : (
'The first checks run within a minute of deploying.'
)}
</p>
<Collapse in={expandUpcoming}>
{upcomingMaintenances.map((maintenance, idx) => (
<MaintenanceAlert
key={`upcoming-${idx}`}
maintenance={maintenance}
style={{ maxWidth: groupedMonitor ? '897px' : '865px' }}
upcoming
/>
))}
</Collapse>
</>
{active.length > 0 && (
<div className="st-notices">
{active.map((n, i) => (
<Notice key={`a${i}`} notice={n} monitors={monitors} />
))}
</div>
)}
{/* Active Maintenance */}
{activeMaintenances.map((maintenance, idx) => (
<MaintenanceAlert
key={`active-${idx}`}
maintenance={maintenance}
style={{ maxWidth: groupedMonitor ? '897px' : '865px' }}
/>
))}
</Container>
{upcoming.length > 0 && (
<div className="st-upcoming">
<button
type="button"
className="ct-btn ct-btn--quiet ct-btn--sm"
aria-expanded={showUpcoming}
onClick={() => setShowUpcoming(!showUpcoming)}
>
{showUpcoming ? 'Hide' : 'Show'} planned maintenance ({upcoming.length})
</button>
{showUpcoming && (
<div className="st-notices">
{upcoming.map((n, i) => (
<Notice key={`u${i}`} notice={n} monitors={monitors} upcoming />
))}
</div>
)}
</div>
)}
</section>
)
}
+105
View File
@@ -0,0 +1,105 @@
import { useRef, useState } from 'react'
import { MonitorState, MonitorTarget } from '@/types/config'
import { Day, DAYS, dailyHistory, dayTone, formatDate, formatDuration, formatPercent, formatTime } from '@/util/status'
// 90 daily bars. Each bar is a button: hover or focus shows the day, and arrow keys move
// between days, so the history isn't colour-only or mouse-only.
export default function UptimeBars({ monitor, state }: { monitor: MonitorTarget; state: MonitorState }) {
const days = dailyHistory(state, monitor.id)
const [active, setActive] = useState<{ i: number; side: React.CSSProperties } | null>(null)
const refs = useRef<(HTMLButtonElement | null)[]>([])
const badDays = days.filter((d) => d.downSeconds > 0).length
// anchor the card to the bar, opening away from the nearer edge
const show = (i: number, el: HTMLElement) => {
const row = el.parentElement!.getBoundingClientRect()
const bar = el.getBoundingClientRect()
const x = bar.left - row.left
setActive({ i, side: x < row.width / 2 ? { left: x } : { right: row.right - bar.right } })
}
const move = (i: number) => {
const j = Math.max(0, Math.min(DAYS - 1, i))
const el = refs.current[j]
// on phones the oldest 60 bars are hidden: don't move focus onto them
if (el && el.offsetParent !== null) el.focus()
}
return (
<div className="st-bars-wrap">
<div
className="st-bars"
role="group"
aria-label={`${monitor.name}, last ${DAYS} days: ${badDays === 0 ? 'no downtime' : `downtime on ${badDays} day${badDays === 1 ? '' : 's'}`}`}
onMouseLeave={() => setActive(null)}
>
{days.map((d, i) => (
<button
key={d.start}
ref={(el) => {
refs.current[i] = el
}}
type="button"
className={`st-bar st-bar--${dayTone(d)}`}
aria-label={dayLabel(d)}
tabIndex={i === DAYS - 1 ? 0 : -1}
onMouseEnter={(e) => show(i, e.currentTarget)}
onFocus={(e) => show(i, e.currentTarget)}
onBlur={() => setActive(null)}
onKeyDown={(e) => {
if (e.key === 'ArrowLeft') move(i - 1)
else if (e.key === 'ArrowRight') move(i + 1)
else if (e.key === 'Home') move(0)
else if (e.key === 'End') move(DAYS - 1)
else return
e.preventDefault()
}}
/>
))}
{active !== null && <DayCard day={days[active.i]} side={active.side} />}
</div>
<div className="st-bars__axis" aria-hidden>
<span className="st-bars__from--long">{DAYS} days ago</span>
<span className="st-bars__from--short">30 days ago</span>
<span>Today</span>
</div>
</div>
)
}
function dayLabel(d: Day) {
const date = formatDate(d.start, true)
if (d.percent === null) return `${date}: not monitored yet`
if (d.downSeconds === 0) return `${date}: no downtime`
return `${date}: down for ${formatDuration(d.downSeconds)}, ${formatPercent(d.percent)} up`
}
function DayCard({ day, side }: { day: Day; side: React.CSSProperties }) {
return (
<div className="st-daycard" style={side} role="status">
<p className="st-daycard__date">{formatDate(day.start, true)}</p>
{day.percent === null ? (
<p className="st-daycard__line">Not monitored yet</p>
) : day.downSeconds === 0 ? (
<p className="st-daycard__line">No downtime</p>
) : (
<>
<p className="st-daycard__line">
Down for {formatDuration(day.downSeconds)} · {formatPercent(day.percent)} up
</p>
<ul className="st-daycard__events">
{day.events.slice(0, 4).map((ev, i) => (
<li key={i}>
<span className="ct-mono st-daycard__time">
{formatTime(ev.from)}–{formatTime(ev.to)}
</span>{' '}
{ev.error}
</li>
))}
{day.events.length > 4 && <li>and {day.events.length - 4} more</li>}
</ul>
</>
)}
</div>
)
}
+203
View File
@@ -0,0 +1,203 @@
// Cottage brand components, ported from the brand handbook's components/bundle.js so they match
// the app exactly. Styles: styles/brand/bundle.css (copied verbatim from Hearth).
import type { ReactNode } from 'react'
const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(' ')
function Mark({ size, mono }: { size: number; mono?: boolean }) {
const cls = cx('ct-logo__mark', mono && 'ct-logo__mark--mono')
if (size <= 24) {
return (
<svg className={cls} viewBox="0 0 16 16" width={size} height={size} aria-hidden focusable="false">
<path className="ct-logo__roof" d="M1.75 7.25 8 2.5l6.25 4.75" fill="none" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" />
<rect className="ct-logo__pod" x={1} y={9.5} width={4} height={5.5} rx={1} />
<rect className="ct-logo__pod ct-logo__pod--lit" x={6} y={9.5} width={4} height={5.5} rx={1} />
<rect className="ct-logo__pod" x={11} y={9.5} width={4} height={5.5} rx={1} />
</svg>
)
}
return (
<svg className={cls} viewBox="0 0 64 64" width={size} height={size} aria-hidden focusable="false">
<rect className="ct-logo__pod" x={43} y={7} width={8} height={19} rx={2} />
<path className="ct-logo__roof" d="M8 31 32 13 56 31" fill="none" strokeWidth={8} strokeLinecap="round" strokeLinejoin="round" />
<rect className="ct-logo__pod" x={5} y={40} width={14} height={17} rx={3.5} />
<rect className="ct-logo__pod ct-logo__pod--lit" x={25} y={40} width={14} height={17} rx={3.5} />
<rect className="ct-logo__pod" x={45} y={40} width={14} height={17} rx={3.5} />
</svg>
)
}
export function Logo({
variant = 'lockup',
size = 32,
label = 'Cottage',
}: {
variant?: 'lockup' | 'mark' | 'mono'
size?: number
label?: string
}) {
if (variant !== 'lockup') {
return (
<span className="ct-logo" role="img" aria-label={label}>
<Mark size={size} mono={variant === 'mono'} />
</span>
)
}
return (
<span className="ct-logo ct-logo--lockup" role="img" aria-label={label} style={{ gap: Math.round(size * 0.22) }}>
<Mark size={size} />
<span className="ct-logo__word" style={{ fontSize: Math.round(size * 0.79) }} aria-hidden>
cottage
</span>
</span>
)
}
export function PodRow({
count = 5,
lit,
size = 32,
roof = false,
empty = false,
}: {
count?: number
lit?: number
size?: number
roof?: boolean
empty?: boolean
}) {
const litIdx = lit == null ? Math.floor(count / 2) : lit
const W = count * 20 - 6
const pad = 4
const rise = roof ? Math.min(0.75 * (W / 2 - 3), 18) : 0
const podTop = roof ? 9 + rise + 8 : pad
const vbW = W + pad * 2
const vbH = podTop + 17 + pad
const eave = podTop - 9
return (
<svg className="ct-podrow" viewBox={`0 0 ${vbW} ${vbH}`} height={size} width={Math.round((size * vbW) / vbH)} aria-hidden>
{roof && (
<path
className="ct-podrow__roof"
d={`M${pad + 3} ${eave} ${pad + W / 2} ${eave - rise} ${pad + W - 3} ${eave}`}
fill="none"
strokeWidth={6}
strokeLinecap="round"
strokeLinejoin="round"
/>
)}
{Array.from({ length: count }, (_, i) => {
const state = i === litIdx ? 'lit' : empty ? 'empty' : 'full'
const e = state === 'empty'
return (
<rect
key={i}
className={`ct-pod ct-pod--${state}`}
x={pad + i * 20 + (e ? 0.75 : 0)}
y={podTop + (e ? 0.75 : 0)}
width={e ? 12.5 : 14}
height={e ? 15.5 : 17}
rx={3.5}
/>
)
})}
</svg>
)
}
export type Shape = 'dot' | 'ring' | 'spin' | 'pause' | 'tri'
export function StatusIcon({ shape }: { shape: Shape }) {
if (shape === 'dot')
return (
<svg viewBox="0 0 12 12" width={10} height={10} aria-hidden>
<circle cx={6} cy={6} r={4} fill="currentColor" />
</svg>
)
if (shape === 'ring')
return (
<svg viewBox="0 0 12 12" width={10} height={10} aria-hidden>
<circle cx={6} cy={6} r={3.75} fill="none" stroke="currentColor" strokeWidth={1.75} />
</svg>
)
if (shape === 'spin')
return (
<svg viewBox="0 0 12 12" width={10} height={10} className="ct-spin" aria-hidden>
<path d="M6 1.5a4.5 4.5 0 1 1-4.5 4.5" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" />
</svg>
)
if (shape === 'pause')
return (
<svg viewBox="0 0 12 12" width={10} height={10} aria-hidden>
<rect x={2.5} y={2} width={2.5} height={8} rx={0.75} fill="currentColor" />
<rect x={7} y={2} width={2.5} height={8} rx={0.75} fill="currentColor" />
</svg>
)
return (
<svg viewBox="0 0 12 12" width={11} height={11} aria-hidden>
<path d="M6 1.2 11 10.5H1Z" fill="currentColor" />
<rect x={5.3} y={4.4} width={1.4} height={3.2} rx={0.5} fill="var(--paper-raised)" />
<rect x={5.3} y={8.3} width={1.4} height={1.3} rx={0.5} fill="var(--paper-raised)" />
</svg>
)
}
const STATUS = {
operational: { label: 'Operational', tone: 'success', shape: 'dot' },
degraded: { label: 'Degraded', tone: 'warning', shape: 'tri' },
maintenance: { label: 'Maintenance', tone: 'warning', shape: 'spin' },
outage: { label: 'Outage', tone: 'danger', shape: 'tri' },
unknown: { label: 'No data', tone: 'neutral', shape: 'ring' },
} as const
export function StatusPill({ status }: { status: keyof typeof STATUS }) {
const s = STATUS[status]
return (
<span className={`ct-pill ct-pill--${s.tone}`}>
<StatusIcon shape={s.shape} />
{s.label}
</span>
)
}
const BANNER_ICON = {
info: 'M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15Zm0 6.5v5M10 6.5v.5',
success: 'M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM6.8 10.2l2.2 2.2 4.2-4.6',
warning: 'M10 3 18 16.5H2ZM10 8.2v3.6M10 14v.3',
danger: 'M10 2.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15ZM7.3 7.3l5.4 5.4M12.7 7.3l-5.4 5.4',
}
export function Banner({
tone = 'info',
title,
children,
aside,
}: {
tone?: keyof typeof BANNER_ICON
title?: ReactNode
children?: ReactNode
aside?: ReactNode
}) {
return (
<div className={`ct-banner ct-banner--${tone}`} role={tone === 'danger' || tone === 'warning' ? 'alert' : 'status'}>
<svg className="ct-banner__icon" viewBox="0 0 20 20" width={20} height={20} aria-hidden>
<path d={BANNER_ICON[tone]} fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" />
</svg>
<div className="ct-banner__body">
{title && <p className="ct-banner__title">{title}</p>}
{children && <div className="ct-banner__text">{children}</div>}
</div>
{aside && <div className="ct-banner__action">{aside}</div>}
</div>
)
}
export function EmptyState({ title, children }: { title: string; children?: ReactNode }) {
return (
<section className="ct-empty">
<PodRow count={3} roof empty lit={-1} size={48} />
<h2 className="ct-empty__title">{title}</h2>
{children && <p className="ct-empty__text">{children}</p>}
</section>
)
}