Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

fix: Page layout shifts on panel load

Blue Mouseab704e8d6ffe
diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
index 8f8e643e5..aa11bf056 100644
--- a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
+++ b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
@@ -24,6 +24,7 @@ import { MetricCard } from '~/pages/Project/tabs/Traffic/MetricCards'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Loader from '~/ui/Loader'
+import { CompactNumberFlow, DurationFlow, PercentFlow } from '~/ui/NumberFlow'
import { nFormatter } from '~/utils/generic'
import CCRow from '../../View/components/CCRow'
@@ -222,7 +223,11 @@ const CaptchaView = (_props: CaptchaViewProps) => {
)
const formatNumber = (value: number, type: 'main' | 'badge') =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
const isFiniteNumber = (value: unknown): value is number =>
typeof value === 'number' && Number.isFinite(value)
const formatPercent = (
@@ -233,62 +238,85 @@ const CaptchaView = (_props: CaptchaViewProps) => {
return 'N/A'
}
- return `${type === 'badge' && value > 0 ? '+' : ''}${value.toFixed(1)}%`
+ return type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${value.toFixed(1)}%`
+ ) : (
+ <PercentFlow value={value} />
+ )
}
- const formatSeconds = (value?: number) =>
- value ? `${Number(value).toFixed(2)}s` : 'N/A'
const formatSecondsChange = (value: number) =>
`${value > 0 ? '+' : value < 0 ? '-' : ''}${Math.abs(Number(value || 0)).toFixed(2)}s`
- const summaryCards = summaryData
- ? [
- {
- label: t('project.captchaAnalytics.generated'),
- value: summaryData.generated || 0,
- change: summaryCompareData
- ? (summaryData.generated || 0) - (summaryCompareData.generated || 0)
- : undefined,
- goodChangeDirection: 'down' as const,
- valueMapper: formatNumber,
- },
- {
- label: t('project.captchaAnalytics.passed'),
- value: summaryData.passed || 0,
- change: summaryCompareData
- ? (summaryData.passed || 0) - (summaryCompareData.passed || 0)
- : undefined,
- goodChangeDirection: 'down' as const,
- valueMapper: formatNumber,
- },
- {
- label: t('project.captchaAnalytics.passRate'),
- value: summaryData.passRate as number,
- change:
- summaryCompareData &&
- isFiniteNumber(summaryData.passRate) &&
- isFiniteNumber(summaryCompareData.passRate)
- ? summaryData.passRate - summaryCompareData.passRate
- : undefined,
- goodChangeDirection: 'down' as const,
- valueMapper: formatPercent,
- },
- {
- label: t('project.captchaAnalytics.medianSolve'),
- value: summaryData.solveP50 || 0,
- change:
- summaryCompareData &&
- (summaryData.solveP50 || 0) > 0 &&
- (summaryCompareData.solveP50 || 0) > 0
- ? (summaryData.solveP50 || 0) - (summaryCompareData.solveP50 || 0)
- : undefined,
- goodChangeDirection: 'up' as const,
- valueMapper: (value: number, type: 'main' | 'badge') =>
- type === 'badge'
- ? formatSecondsChange(value)
- : formatSeconds(value),
- },
- ]
- : []
+ // Built even before the summary lands: the cards read zero and roll up to the
+ // real values, so the row holds its height rather than appearing late.
+ const summaryCards = [
+ {
+ label: t('project.captchaAnalytics.generated'),
+ value: summaryData?.generated || 0,
+ change:
+ summaryData && summaryCompareData
+ ? (summaryData.generated || 0) - (summaryCompareData.generated || 0)
+ : undefined,
+ goodChangeDirection: 'down' as const,
+ valueMapper: formatNumber,
+ },
+ {
+ label: t('project.captchaAnalytics.passed'),
+ value: summaryData?.passed || 0,
+ change:
+ summaryData && summaryCompareData
+ ? (summaryData.passed || 0) - (summaryCompareData.passed || 0)
+ : undefined,
+ goodChangeDirection: 'down' as const,
+ valueMapper: formatNumber,
+ },
+ {
+ label: t('project.captchaAnalytics.passRate'),
+ value: summaryData?.passRate as number,
+ change:
+ summaryData &&
+ summaryCompareData &&
+ isFiniteNumber(summaryData.passRate) &&
+ isFiniteNumber(summaryCompareData.passRate)
+ ? summaryData.passRate - summaryCompareData.passRate
+ : undefined,
+ goodChangeDirection: 'down' as const,
+ valueMapper: formatPercent,
+ },
+ {
+ label: t('project.captchaAnalytics.medianSolve'),
+ value: summaryData?.solveP50 || 0,
+ change:
+ summaryData &&
+ summaryCompareData &&
+ (summaryData.solveP50 || 0) > 0 &&
+ (summaryCompareData.solveP50 || 0) > 0
+ ? (summaryData.solveP50 || 0) - (summaryCompareData.solveP50 || 0)
+ : undefined,
+ goodChangeDirection: 'up' as const,
+ valueMapper: (value: number, type: 'main' | 'badge') =>
+ type === 'badge' ? (
+ formatSecondsChange(value)
+ ) : (
+ <DurationFlow value={value} showMs />
+ ),
+ },
+ ]
+
+ const summaryCardsRow = (
+ <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
+ {summaryCards.map((card) => (
+ <MetricCard
+ key={card.label}
+ label={card.label}
+ value={card.value}
+ change={card.change}
+ goodChangeDirection={card.goodChangeDirection}
+ valueMapper={card.valueMapper}
+ />
+ ))}
+ </div>
+ )
// Show waiting state if project has no captcha data yet
if (!_isEmpty(project) && !project?.isCaptchaDataExists) {
@@ -318,11 +346,15 @@ const CaptchaView = (_props: CaptchaViewProps) => {
<div>
<Filters className='mb-3' tnMapping={tnMapping} />
{isChartLoading ? (
- <div className='flex h-80 items-center justify-center overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
- <Loader className='pt-0!' />
+ // Mirrors CaptchaChart's own container so the box keeps its size once
+ // the chart takes over from the spinner.
+ <div className='overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'>
+ {summaryCardsRow}
+ <div className='mt-5 flex h-80 items-center justify-center md:mt-0'>
+ <Loader className='pt-0!' />
+ </div>
</div>
- ) : null}
- {!_isEmpty(chartData.x) ? (
+ ) : !_isEmpty(chartData.x) ? (
<CaptchaChart
chart={chartData}
timeBucket={timeBucket}
@@ -331,20 +363,7 @@ const CaptchaView = (_props: CaptchaViewProps) => {
chartType={chartTypes.line}
dataNames={dataNames}
>
- {summaryCards.length ? (
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
- {summaryCards.map((card) => (
- <MetricCard
- key={card.label}
- label={card.label}
- value={card.value}
- change={card.change}
- goodChangeDirection={card.goodChangeDirection}
- valueMapper={card.valueMapper}
- />
- ))}
- </div>
- ) : null}
+ {summaryCardsRow}
</CaptchaChart>
) : null}
<div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
index be821ad1b..fc124469c 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
@@ -84,6 +84,7 @@ import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { getRelativeDateIfPossible } from '~/utils/date'
+import { CompactNumberFlow, PercentFlow } from '~/ui/NumberFlow'
import { getLocaleDisplayName, nFormatter } from '~/utils/generic'
const calculateOptimalTicks = (
@@ -460,7 +461,7 @@ const PerErrorPanels = ({
interface StatCardProps {
icon: React.ReactNode
- value: string | number
+ value: React.ReactNode
label: string
}
@@ -1122,12 +1123,20 @@ const ErrorsViewInner = () => {
{
key: 'occurrences',
label: t('project.occurrences'),
- value: nFormatter(activeError.details.count || 0, 1),
+ value: (
+ <CompactNumberFlow
+ value={activeError.details.count || 0}
+ />
+ ),
},
{
key: 'users',
label: t('dashboard.users'),
- value: nFormatter(activeError.details.users || 0, 1),
+ value: (
+ <CompactNumberFlow
+ value={activeError.details.users || 0}
+ />
+ ),
},
{
key: 'firstSeen',
@@ -1137,6 +1146,9 @@ const ErrorsViewInner = () => {
activeError.details.first_seen,
language,
) || '-',
+ // A relative date is a sentence, not a figure β€” at the
+ // numeric card size it dwarfs the rest of the row.
+ valueClassName: 'text-xl sm:text-2xl',
},
{
key: 'lastSeen',
@@ -1146,6 +1158,7 @@ const ErrorsViewInner = () => {
activeError.details.last_seen,
language,
) || '-',
+ valueClassName: 'text-xl sm:text-2xl',
},
]}
/>
@@ -1274,22 +1287,34 @@ const ErrorsViewInner = () => {
<div className='grid w-full grid-cols-2 gap-2 lg:w-[35%]'>
<StatCard
icon={<WarningIcon className='text-red-600' />}
- value={nFormatter(overview?.stats?.totalErrors || 0, 1)}
+ value={
+ <CompactNumberFlow
+ value={overview?.stats?.totalErrors || 0}
+ />
+ }
label={t('project.totalErrors')}
/>
<StatCard
icon={<PercentIcon className='text-orange-600' />}
- value={`${overview?.stats?.errorRate || 0}%`}
+ value={<PercentFlow value={overview?.stats?.errorRate || 0} />}
label={t('project.errorRate')}
/>
<StatCard
icon={<UsersIcon className='text-blue-600' />}
- value={nFormatter(overview?.stats?.affectedUsers || 0, 1)}
+ value={
+ <CompactNumberFlow
+ value={overview?.stats?.affectedUsers || 0}
+ />
+ }
label={t('project.affectedUsers')}
/>
<StatCard
icon={<MonitorIcon className='text-purple-600' />}
- value={nFormatter(overview?.stats?.affectedSessions || 0, 1)}
+ value={
+ <CompactNumberFlow
+ value={overview?.stats?.affectedSessions || 0}
+ />
+ }
label={t('project.affectedSessions')}
/>
</div>
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index 8194b1652..f1605600b 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -77,6 +77,7 @@ import Spin from '~/ui/icons/Spin'
import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
+import { DurationFlow } from '~/ui/NumberFlow'
import ProgressRing from '~/ui/ProgressRing'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
@@ -682,7 +683,11 @@ const GoalRow = ({
weight='bold'
className='leading-none whitespace-nowrap'
>
- {formatDuration(metric?.median)}
+ {hasTiming ? (
+ <DurationFlow value={metric!.median!} />
+ ) : (
+ formatDuration(metric?.median)
+ )}
</Text>
<div className='mt-1 flex items-center gap-1.5'>
<Text as='p' size='sm' weight='semibold'>
diff --git a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
index dd3455330..fa89c731c 100644
--- a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
+++ b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
@@ -547,18 +547,20 @@ const PerformanceViewInner = ({ tnMapping }: PerformanceViewProps) => {
/>
</div>
+ {/* Always rendered: the cards read zero until the summary lands and
+ then roll up to it, so the row holds its height instead of
+ appearing late and shoving the chart and panels down. */}
+ <PerformanceMetricCards
+ overall={overall}
+ overallCompare={overallCompare}
+ />
{isChartLoading ? (
- <div className='flex h-80 items-center justify-center'>
+ // Same box as PerformanceChart below (incl. its mobile mt-5) so the
+ // chart drops straight into the spinner's place.
+ <div className='mt-5 flex h-80 items-center justify-center md:mt-0'>
<Loader className='pt-0!' />
</div>
- ) : null}
- {!_isEmpty(overall) ? (
- <PerformanceMetricCards
- overall={overall}
- overallCompare={overallCompare}
- />
- ) : null}
- {activeChartMetrics && !_isEmpty(chartData.x) ? (
+ ) : activeChartMetrics && !_isEmpty(chartData.x) ? (
<div
onContextMenu={(e) => handleChartContextMenu(e, chartData.x)}
className='relative'
diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsx
index 5ad0f1e07..856fa3387 100644
--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx
+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx
@@ -50,6 +50,7 @@ import {
getDeviceRowMapper,
} from '~/pages/Project/View/ViewProject.helpers'
import { MetricCard } from '~/pages/Project/tabs/Traffic/MetricCards'
+import { CompactNumberFlow, PercentFlow } from '~/ui/NumberFlow'
import RefRow from '~/pages/Project/tabs/Traffic/RefRow'
import CCRow from '~/pages/Project/View/components/CCRow'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
@@ -863,7 +864,11 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
}
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
<MetricCard
@@ -877,7 +882,11 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
}
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
<MetricCard
@@ -891,7 +900,11 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
type='percent'
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${value}%`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${value}%`
+ ) : (
+ <PercentFlow value={value} />
+ )
}
/>
<MetricCard
@@ -907,7 +920,11 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
}
goodChangeDirection='up'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${value}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${value}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
</div>
diff --git a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
index 048c7dda6..c8e5fadc6 100644
--- a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
+++ b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
@@ -1,193 +1,22 @@
-import NumberFlow, { NumberFlowGroup } from '@number-flow/react'
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import _isNumber from 'lodash/isNumber'
import _map from 'lodash/map'
import _round from 'lodash/round'
import { motion, type Variants } from 'motion/react'
-import React, { memo, useEffect, useState } from 'react'
+import React, { memo } from 'react'
import { useTranslation } from 'react-i18next'
-import {
- FLOW_TIMING,
- FLOW_VALUE_CLASS,
- useFlowValue,
-} from '~/hooks/useFlowValue'
import { OverallObject, OverallPerformanceObject } from '~/lib/models/Project'
import { Badge } from '~/ui/Badge'
+import { CompactNumberFlow, DurationFlow, PercentFlow } from '~/ui/NumberFlow'
import { Text } from '~/ui/Text'
import {
nFormatter,
- nFormatterSeparated,
getStringFromTime,
getTimeFromSeconds,
} from '~/utils/generic'
-const useIsHydrated = () => {
- const [isHydrated, setIsHydrated] = useState(false)
-
- useEffect(() => {
- setIsHydrated(true)
- }, [])
-
- return isHydrated
-}
-
-const StaticCompactNumber = ({ value }: { value: number }) => {
- const [num, symbol] = nFormatterSeparated(value, 1) as [number, string | null]
-
- return (
- <>
- {num}
- {symbol}
- </>
- )
-}
-
-const AnimatedCompactNumber = ({ value }: { value: number }) => {
- const flowValue = useFlowValue(value)
- const [num, symbol] = nFormatterSeparated(flowValue, 1) as [
- number,
- string | null,
- ]
-
- return (
- <NumberFlow
- className={FLOW_VALUE_CLASS}
- {...FLOW_TIMING}
- value={num}
- suffix={symbol ?? undefined}
- format={{ maximumFractionDigits: 1 }}
- willChange
- />
- )
-}
-
-const CompactNumberFlow = ({ value }: { value: number }) => {
- const isHydrated = useIsHydrated()
-
- return isHydrated ? (
- <AnimatedCompactNumber value={value} />
- ) : (
- <StaticCompactNumber value={value} />
- )
-}
-
-const AnimatedPercent = ({ value }: { value: number }) => {
- const flowValue = useFlowValue(value)
-
- return (
- <NumberFlow
- className={FLOW_VALUE_CLASS}
- {...FLOW_TIMING}
- value={flowValue}
- suffix='%'
- format={{ maximumFractionDigits: 1 }}
- willChange
- />
- )
-}
-
-const PercentFlow = ({ value }: { value: number }) => {
- const isHydrated = useIsHydrated()
- const sanitizedValue = Number.isFinite(value) ? _round(value, 1) : 0
-
- return isHydrated ? (
- <AnimatedPercent value={sanitizedValue} />
- ) : (
- <>{sanitizedValue}%</>
- )
-}
-
-const StaticDuration = ({
- value,
- showMs,
-}: {
- value?: number
- showMs?: boolean
-}) => (
- <>
- {getStringFromTime(
- getTimeFromSeconds(Number.isFinite(value) ? value : 0),
- showMs,
- )}
- </>
-)
-
-const AnimatedDuration = ({
- value,
- showMs,
-}: {
- value?: number
- showMs?: boolean
-}) => {
- const flowValue = useFlowValue(value)
- const time = getTimeFromSeconds(flowValue)
- const s = showMs ? _round(time.s + time.ms / 1000, 2) : time.s
-
- // Decide which units to render from the target value so the NumberFlow
- // elements mount once and roll from zero, instead of remounting mid-flight
- const target = getTimeFromSeconds(Number.isFinite(value) ? value : 0)
- const targetS = showMs ? _round(target.s + target.ms / 1000, 2) : target.s
- const showH = target.h > 0
- const showM = target.m > 0
- const showS = targetS > 0 || (!showH && !showM)
-
- return (
- <NumberFlowGroup>
- <>
- {target.negative ? '-' : null}
- {showH ? (
- <NumberFlow
- className={FLOW_VALUE_CLASS}
- {...FLOW_TIMING}
- value={time.h}
- suffix='h'
- willChange
- />
- ) : null}
- {showH && (showM || showS) ? ' ' : null}
- {showM ? (
- <NumberFlow
- className={FLOW_VALUE_CLASS}
- {...FLOW_TIMING}
- value={time.m}
- suffix='m'
- willChange
- />
- ) : null}
- {showM && showS ? ' ' : null}
- {showS ? (
- <NumberFlow
- className={FLOW_VALUE_CLASS}
- {...FLOW_TIMING}
- value={s}
- suffix='s'
- format={{ maximumFractionDigits: 2 }}
- willChange
- />
- ) : null}
- </>
- </NumberFlowGroup>
- )
-}
-
-const DurationFlow = ({
- value,
- showMs,
-}: {
- value?: number
- showMs?: boolean
-}) => {
- const isHydrated = useIsHydrated()
-
- return isHydrated ? (
- <AnimatedDuration value={value} showMs={showMs} />
- ) : (
- <StaticDuration value={value} showMs={showMs} />
- )
-}
-
// Entrance animation: parent containers set initial='hidden' animate='visible'
// to stagger the cards in. Standalone usage (no motion parent) stays static.
export const metricCardsContainerVariants: Variants = {
@@ -292,7 +121,9 @@ export const MetricCard: React.FC<MetricCardProps> = ({
</Text>
<div
className={cx(
- 'flex items-center whitespace-nowrap',
+ // min-h matches the change badge, so a card is the same height before
+ // its badge arrives with the data as it is after.
+ 'flex min-h-6 items-center whitespace-nowrap',
{
'space-x-2': _isNumber(change),
},
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
index d54bbd97f..ef508a509 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
@@ -312,6 +312,13 @@ const TrafficViewInner = ({
() => summaryToOverall(summaryQuery.data?.data, customEVFilterApplied),
[summaryQuery.data, customEVFilterApplied],
)
+ // The cards render before the summary arrives, and which cards they are
+ // depends on the filter (known from the URL) rather than on the response β€”
+ // without this the row would show five cards and then collapse to one.
+ const overallForCards = useMemo(
+ () => ({ ...overall, customEVFilterApplied }),
+ [overall, customEVFilterApplied],
+ )
const overallCompare = useMemo(
() =>
summaryToOverall(compareSummaryQuery.data?.data, customEVFilterApplied),
@@ -1151,53 +1158,55 @@ const TrafficViewInner = ({
<HasImportedIndicator />
</Suspense>
</div>
+ {/* Always rendered: the cards read zero until the summary lands and
+ then roll up to it, so the row holds its height instead of
+ appearing late and shoving the chart and panels down. */}
+ <motion.div
+ initial='hidden'
+ animate='visible'
+ variants={metricCardsContainerVariants}
+ className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'
+ >
+ <MetricCards
+ overall={overallForCards}
+ overallCompare={overallCompare}
+ activePeriodCompare={activePeriodCompare}
+ />
+ {!_isEmpty(customMetricsQuery.data?.data)
+ ? _map(
+ customMetricsQuery.data?.data,
+ ({ key, current, previous }) => (
+ <React.Fragment key={key}>
+ <MetricCard
+ label={t('project.metrics.xAvg', { x: key })}
+ value={current.avg}
+ change={current.avg - previous.avg}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
+ <MetricCard
+ label={t('project.metrics.xTotal', { x: key })}
+ value={current.sum}
+ change={current.sum - previous.sum}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
+ }
+ />
+ </React.Fragment>
+ ),
+ )
+ : null}
+ </motion.div>
{isChartLoading ? (
- <div className='flex h-80 items-center justify-center'>
+ // Same box as TrafficChart below (incl. its mobile mt-5) so the
+ // chart drops straight into the spinner's place.
+ <div className='mt-5 flex h-80 items-center justify-center md:mt-0'>
<Loader className='pt-0!' />
</div>
- ) : null}
- {!_isEmpty(overall) ? (
- <motion.div
- initial='hidden'
- animate='visible'
- variants={metricCardsContainerVariants}
- className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'
- >
- <MetricCards
- overall={overall}
- overallCompare={overallCompare}
- activePeriodCompare={activePeriodCompare}
- />
- {!_isEmpty(customMetricsQuery.data?.data)
- ? _map(
- customMetricsQuery.data?.data,
- ({ key, current, previous }) => (
- <React.Fragment key={key}>
- <MetricCard
- label={t('project.metrics.xAvg', { x: key })}
- value={current.avg}
- change={current.avg - previous.avg}
- goodChangeDirection='down'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
- }
- />
- <MetricCard
- label={t('project.metrics.xTotal', { x: key })}
- value={current.sum}
- change={current.sum - previous.sum}
- goodChangeDirection='down'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nLocaleFormatter(value)}`
- }
- />
- </React.Fragment>
- ),
- )
- : null}
- </motion.div>
- ) : null}
- {!checkIfAllMetricsAreDisabled && !_isEmpty(chartData.x) ? (
+ ) : !checkIfAllMetricsAreDisabled && !_isEmpty(chartData.x) ? (
<div
onContextMenu={(e) => handleChartContextMenu(e, chartData.x)}
className='relative'
diff --git a/web/app/ui/NumberFlow.tsx b/web/app/ui/NumberFlow.tsx
new file mode 100644
index 000000000..8ad529225
--- /dev/null
+++ b/web/app/ui/NumberFlow.tsx
@@ -0,0 +1,186 @@
+import NumberFlow, { NumberFlowGroup } from '@number-flow/react'
+import _round from 'lodash/round'
+import { useEffect, useState } from 'react'
+
+import {
+ FLOW_TIMING,
+ FLOW_VALUE_CLASS,
+ useFlowValue,
+} from '~/hooks/useFlowValue'
+import {
+ getStringFromTime,
+ getTimeFromSeconds,
+ nFormatterSeparated,
+} from '~/utils/generic'
+
+// NumberFlow renders nothing meaningful server-side, so every flow falls back to
+// plain text until hydration and only then starts animating.
+const useIsHydrated = () => {
+ const [isHydrated, setIsHydrated] = useState(false)
+
+ useEffect(() => {
+ setIsHydrated(true)
+ }, [])
+
+ return isHydrated
+}
+
+const StaticCompactNumber = ({ value }: { value?: number }) => {
+ const [num, symbol] = nFormatterSeparated(value, 1) as [number, string | null]
+
+ return (
+ <>
+ {num}
+ {symbol}
+ </>
+ )
+}
+
+const AnimatedCompactNumber = ({ value }: { value?: number }) => {
+ const flowValue = useFlowValue(value)
+ const [num, symbol] = nFormatterSeparated(flowValue, 1) as [
+ number,
+ string | null,
+ ]
+
+ return (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={num}
+ suffix={symbol ?? undefined}
+ format={{ maximumFractionDigits: 1 }}
+ willChange
+ />
+ )
+}
+
+/** Counts, abbreviated past a thousand (1.2k, 3.4M). */
+export const CompactNumberFlow = ({ value }: { value?: number }) => {
+ const isHydrated = useIsHydrated()
+
+ return isHydrated ? (
+ <AnimatedCompactNumber value={value} />
+ ) : (
+ <StaticCompactNumber value={value} />
+ )
+}
+
+const AnimatedPercent = ({ value }: { value: number }) => {
+ const flowValue = useFlowValue(value)
+
+ return (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={flowValue}
+ suffix='%'
+ format={{ maximumFractionDigits: 1 }}
+ willChange
+ />
+ )
+}
+
+/** Percentages, rounded to a single decimal. */
+export const PercentFlow = ({ value }: { value?: number }) => {
+ const isHydrated = useIsHydrated()
+ const sanitizedValue = Number.isFinite(value) ? _round(value as number, 1) : 0
+
+ return isHydrated ? (
+ <AnimatedPercent value={sanitizedValue} />
+ ) : (
+ <>{sanitizedValue}%</>
+ )
+}
+
+const StaticDuration = ({
+ value,
+ showMs,
+}: {
+ value?: number
+ showMs?: boolean
+}) => (
+ <>
+ {getStringFromTime(
+ getTimeFromSeconds(Number.isFinite(value) ? (value as number) : 0),
+ showMs,
+ )}
+ </>
+)
+
+const AnimatedDuration = ({
+ value,
+ showMs,
+}: {
+ value?: number
+ showMs?: boolean
+}) => {
+ const flowValue = useFlowValue(value)
+ const time = getTimeFromSeconds(flowValue)
+ const s = showMs ? _round(time.s + time.ms / 1000, 2) : time.s
+
+ // Decide which units to render from the target value so the NumberFlow
+ // elements mount once and roll from zero, instead of remounting mid-flight
+ const target = getTimeFromSeconds(
+ Number.isFinite(value) ? (value as number) : 0,
+ )
+ const targetS = showMs ? _round(target.s + target.ms / 1000, 2) : target.s
+ const showH = target.h > 0
+ const showM = target.m > 0
+ const showS = targetS > 0 || (!showH && !showM)
+
+ return (
+ <NumberFlowGroup>
+ <>
+ {target.negative ? '-' : null}
+ {showH ? (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={time.h}
+ suffix='h'
+ willChange
+ />
+ ) : null}
+ {showH && (showM || showS) ? ' ' : null}
+ {showM ? (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={time.m}
+ suffix='m'
+ willChange
+ />
+ ) : null}
+ {showM && showS ? ' ' : null}
+ {showS ? (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={s}
+ suffix='s'
+ format={{ maximumFractionDigits: 2 }}
+ willChange
+ />
+ ) : null}
+ </>
+ </NumberFlowGroup>
+ )
+}
+
+/** Durations given in seconds, rendered as h/m/s. */
+export const DurationFlow = ({
+ value,
+ showMs,
+}: {
+ value?: number
+ showMs?: boolean
+}) => {
+ const isHydrated = useIsHydrated()
+
+ return isHydrated ? (
+ <AnimatedDuration value={value} showMs={showMs} />
+ ) : (
+ <StaticDuration value={value} showMs={showMs} />
+ )
+}