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!

Add number animations to metric cards & some smaller secondary ones

Blue Mouse12810d662761
diff --git a/web/app/hooks/useFlowValue.ts b/web/app/hooks/useFlowValue.ts
new file mode 100644
index 000000000..7a8b83f22
--- /dev/null
+++ b/web/app/hooks/useFlowValue.ts
@@ -0,0 +1,36 @@
+import { useEffect, useState } from 'react'
+
+/**
+ * NumberFlow pads digits vertically to mask the rolling animation: ~0.125em
+ * (`round(nearest, 0.25em / 2, 1px)`) is added twice per side β€” on
+ * `.number__inner` and again via `.digit__num` raising the inner line box.
+ * Cancel both with a negative margin (same expression, so it matches at any
+ * zoom level) to keep plain-text line metrics.
+ */
+export const FLOW_VALUE_CLASS = 'my-[calc(-2*round(nearest,0.125em,1px))]'
+
+/**
+ * number-flow defaults to 900ms digit spins / 450ms fades β€” marketing pace.
+ * Dashboard numbers change dozens of times a day, so keep them crisp.
+ */
+export const FLOW_TIMING = {
+ transformTiming: { duration: 550, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' },
+ spinTiming: { duration: 550, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' },
+ opacityTiming: { duration: 350, easing: 'ease-out' },
+}
+
+/**
+ * NumberFlow only animates value *changes*, not the initial render.
+ * Starting from zero and updating to the real value right after mount
+ * makes the number roll in on page load as well.
+ */
+export const useFlowValue = (value?: number) => {
+ const target = Number.isFinite(value) ? (value as number) : 0
+ const [flowValue, setFlowValue] = useState(0)
+
+ useEffect(() => {
+ setFlowValue(target)
+ }, [target])
+
+ return flowValue
+}
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 27076f83f..72ed85119 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -1577,10 +1577,16 @@ const ViewProjectContent = () => {
<AnimatePresence mode='wait'>
<motion.div
key={activeTab}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: 0.15 }}
+ initial={{ opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{
+ opacity: 0,
+ transition: { duration: 0.1 },
+ }}
+ transition={{
+ duration: 0.15,
+ ease: [0.23, 1, 0.32, 1],
+ }}
>
{activeTab === PROJECT_TABS.ai ? (
<Suspense fallback={<Loader />}>
diff --git a/web/app/pages/Project/View/components/Filters.tsx b/web/app/pages/Project/View/components/Filters.tsx
index e927cd2ad..4c8542f4d 100644
--- a/web/app/pages/Project/View/components/Filters.tsx
+++ b/web/app/pages/Project/View/components/Filters.tsx
@@ -4,6 +4,7 @@ import _replace from 'lodash/replace'
import _startsWith from 'lodash/startsWith'
import _truncate from 'lodash/truncate'
import { FunnelIcon, XIcon } from '@phosphor-icons/react'
+import { AnimatePresence, motion } from 'motion/react'
import { memo, MouseEvent, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from '~/ui/Link'
@@ -312,30 +313,49 @@ const Filters = ({ tnMapping, className }: FiltersProps) => {
<div className='flex min-w-0 flex-1 items-center gap-1'>
<FunnelIcon className='size-5 shrink-0 text-gray-500 dark:text-gray-400' />
<div className='flex flex-wrap'>
- {_map(supported, (props) => {
- const { column, filter, isExclusive, isContains } = props
- const key = `${column}-${filter}-${isExclusive}-${isContains}`
-
- return (
- <Filter
- key={key}
- tnMapping={tnMapping}
- canChangeExclusive
- removable
- {...props}
- />
- )
- })}
- {_map(unsupported, (props) => {
- const { column, filter, isExclusive, isContains } = props
- const key = `unsupported-${column}-${filter}-${isExclusive}-${isContains}`
-
- return (
- <span key={key} className='opacity-60'>
- <Filter tnMapping={tnMapping} removable {...props} />
- </span>
- )
- })}
+ <AnimatePresence mode='popLayout' initial={false}>
+ {_map(supported, (props) => {
+ const { column, filter, isExclusive, isContains } = props
+ const key = `${column}-${filter}-${isExclusive}-${isContains}`
+
+ return (
+ <motion.span
+ key={key}
+ layout
+ initial={{ opacity: 0, scale: 0.92 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.92 }}
+ transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}
+ className='inline-flex'
+ >
+ <Filter
+ tnMapping={tnMapping}
+ canChangeExclusive
+ removable
+ {...props}
+ />
+ </motion.span>
+ )
+ })}
+ {_map(unsupported, (props) => {
+ const { column, filter, isExclusive, isContains } = props
+ const key = `unsupported-${column}-${filter}-${isExclusive}-${isContains}`
+
+ return (
+ <motion.span
+ key={key}
+ layout
+ initial={{ opacity: 0, scale: 0.92 }}
+ animate={{ opacity: 0.6, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.92 }}
+ transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}
+ className='inline-flex'
+ >
+ <Filter tnMapping={tnMapping} removable {...props} />
+ </motion.span>
+ )
+ })}
+ </AnimatePresence>
</div>
{unsupported.length > 0 ? (
<span className='ml-1 shrink-0 rounded-md bg-amber-50 px-1.5 py-0.5 text-[11px] font-medium text-amber-700 ring-1 ring-amber-200 ring-inset dark:bg-amber-500/10 dark:text-amber-300 dark:ring-amber-400/20'>
diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
index dc332294b..3b58957ce 100644
--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
@@ -1,3 +1,4 @@
+import NumberFlow from '@number-flow/react'
import { CaretDownIcon, XIcon } from '@phosphor-icons/react'
import _map from 'lodash/map'
import React, { useState } from 'react'
@@ -7,6 +8,11 @@ import { Link } from '~/ui/Link'
import type { LiveVisitorInfo } from '~/api/api.server'
import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'
+import {
+ FLOW_TIMING,
+ FLOW_VALUE_CLASS,
+ useFlowValue,
+} from '~/hooks/useFlowValue'
import { PROJECT_TABS } from '~/lib/constants'
import Flag from '~/ui/Flag'
import PulsatingCircle from '~/ui/icons/PulsatingCircle'
@@ -25,6 +31,14 @@ const LiveVisitorsDropdown = () => {
const [isLoading, setIsLoading] = useState(true)
const [liveInfo, setLiveInfo] = useState<LiveVisitorInfo[]>([])
const { fetchLiveVisitorsInfo } = useLiveVisitorsProxy()
+ const flowLiveVisitors = useFlowValue(liveVisitors)
+
+ // The translation interpolates the amount into the sentence, so split it
+ // around the placeholder to render the number with NumberFlow.
+ const [liveVisitorsLabelStart, liveVisitorsLabelEnd] = t(
+ 'dashboard.xLiveVisitors',
+ { amount: '__amount__' },
+ ).split('__amount__')
const getLiveVisitors = async () => {
setIsLoading(true)
@@ -67,9 +81,14 @@ const LiveVisitorsDropdown = () => {
>
<PulsatingCircle className='mr-1.5' type='small' />
<span>
- {t('dashboard.xLiveVisitors', {
- amount: liveVisitors,
- })}{' '}
+ {liveVisitorsLabelStart}
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={flowLiveVisitors}
+ willChange
+ />
+ {liveVisitorsLabelEnd}{' '}
</span>
<CaretDownIcon
className={cn(
diff --git a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
index 3d0238e6f..db108a9c4 100644
--- a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
+++ b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
@@ -1,20 +1,139 @@
+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 } 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 { Text } from '~/ui/Text'
import {
nFormatter,
+ nFormatterSeparated,
getStringFromTime,
getTimeFromSeconds,
} from '~/utils/generic'
+// Animated counterparts of nFormatter / percent / getStringFromTime, so the
+// main metric values roll smoothly on load and when the period changes.
+const CompactNumberFlow = ({ 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 PercentFlow = ({ value }: { value: number }) => {
+ const flowValue = useFlowValue(value)
+
+ return (
+ <NumberFlow
+ className={FLOW_VALUE_CLASS}
+ {...FLOW_TIMING}
+ value={flowValue}
+ suffix='%'
+ format={{ maximumFractionDigits: 1 }}
+ willChange
+ />
+ )
+}
+
+const DurationFlow = ({
+ 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>
+ )
+}
+
+// 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 = {
+ visible: {
+ transition: { staggerChildren: 0.04 },
+ },
+}
+
+const metricCardVariants: Variants = {
+ hidden: { opacity: 0, y: 8 },
+ visible: {
+ opacity: 1,
+ y: 0,
+ transition: { duration: 0.2, ease: [0.23, 1, 0.32, 1] },
+ },
+}
+
interface MetricCardProps {
label: string
value: React.ReactNode
@@ -89,7 +208,10 @@ export const MetricCard: React.FC<MetricCardProps> = ({
valueMapper,
classes,
}) => (
- <div className={cx('flex flex-col', classes?.container)}>
+ <motion.div
+ variants={metricCardVariants}
+ className={cx('flex flex-col', classes?.container)}
+ >
<Text
size='4xl'
weight='bold'
@@ -116,7 +238,7 @@ export const MetricCard: React.FC<MetricCardProps> = ({
valueMapper={valueMapper}
/>
</div>
- </div>
+ </motion.div>
)
interface MetricCardsProps {
@@ -163,7 +285,11 @@ export const MetricCards = memo(
type='percent'
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
)
@@ -178,7 +304,11 @@ export const MetricCards = memo(
type='percent'
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
<MetricCard
@@ -188,7 +318,11 @@ export const MetricCards = memo(
type='percent'
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
<MetricCard
@@ -198,7 +332,11 @@ export const MetricCards = memo(
type='percent'
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ ) : (
+ <CompactNumberFlow value={value} />
+ )
}
/>
<MetricCard
@@ -208,7 +346,11 @@ export const MetricCards = memo(
type='percent'
goodChangeDirection='up'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${value}%`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${value}%`
+ ) : (
+ <PercentFlow value={value} />
+ )
}
/>
<MetricCard
@@ -217,7 +359,11 @@ export const MetricCards = memo(
change={sdurChange}
goodChangeDirection='down'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value))}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value))}`
+ ) : (
+ <DurationFlow value={value} />
+ )
}
/>
</>
@@ -251,14 +397,23 @@ export const PerformanceMetricCards = memo(
}
return (
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
+ <motion.div
+ initial='hidden'
+ animate='visible'
+ variants={metricCardsContainerVariants}
+ className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'
+ >
<MetricCard
label={t('dashboard.frontend')}
value={overall.current?.frontend}
change={frontendChange}
goodChangeDirection='up'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ ) : (
+ <DurationFlow value={value} showMs />
+ )
}
/>
<MetricCard
@@ -267,7 +422,11 @@ export const PerformanceMetricCards = memo(
change={backendChange}
goodChangeDirection='up'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ ) : (
+ <DurationFlow value={value} showMs />
+ )
}
/>
<MetricCard
@@ -276,10 +435,14 @@ export const PerformanceMetricCards = memo(
change={networkChange}
goodChangeDirection='up'
valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ type === 'badge' ? (
+ `${value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
+ ) : (
+ <DurationFlow value={value} showMs />
+ )
}
/>
- </div>
+ </motion.div>
)
},
)
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
index 2477cb4e2..4b59670b2 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
@@ -22,7 +22,7 @@ import React, {
type ReactNode,
} from 'react'
import { createPortal } from 'react-dom'
-import { useIsPresent } from 'motion/react'
+import { motion, useIsPresent } from 'motion/react'
import { useTranslation } from 'react-i18next'
import {
useNavigate,
@@ -52,6 +52,7 @@ import { MapLoader } from '~/pages/Project/View/components/MapLoader'
import {
MetricCard,
MetricCards,
+ metricCardsContainerVariants,
} from '~/pages/Project/tabs/Traffic/MetricCards'
import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'
import RefRow from '~/pages/Project/tabs/Traffic/RefRow'
@@ -243,11 +244,7 @@ function TrafficDataResolver({
previousDataRef.current = currentData
}
- return (
- <>
- {children(currentData)}
- </>
- )
+ return <>{children(currentData)}</>
}
function HasImportedIndicator() {
@@ -1064,7 +1061,12 @@ const TrafficViewInner = ({
</Suspense>
</div>
{!_isEmpty(overall) ? (
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
+ <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}
@@ -1094,7 +1096,7 @@ const TrafficViewInner = ({
</React.Fragment>
))
: null}
- </div>
+ </motion.div>
) : null}
{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
<div
diff --git a/web/app/root.tsx b/web/app/root.tsx
index 43421644a..76d2ff2be 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -7,6 +7,7 @@ import {
import BillboardCss from 'billboard.js/dist/billboard.min.css?url'
import cx from 'clsx'
import _replace from 'lodash/replace'
+import { MotionConfig } from 'motion/react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type {
@@ -457,7 +458,10 @@ const Body = () => {
initialUser={user}
initialTotalMonthlyEvents={totalMonthlyEvents}
>
- <AppWrapper />
+ {/* Drops transform-based motion (keeps opacity) for prefers-reduced-motion users */}
+ <MotionConfig reducedMotion='user'>
+ <AppWrapper />
+ </MotionConfig>
</AuthProvider>
<ScrollRestoration />
<ExternalScripts />