📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Refactor charts
Blue Mouse44c415bac5a9
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex a817d78a3..dc037cf27 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -1131,7 +1131,6 @@ const getSettingsError = (bar: {linearGradient: true,},- bindto: '#errorChart',}}@@ -1296,7 +1295,6 @@ const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t`},},- bindto: '#funnelChart',}}@@ -1758,7 +1756,6 @@ export {typeNameMapping,noRegionPeriods,getSettings,- getColumns,onCSVExportClick,CHART_METRICS_MAPPING,CHART_METRICS_MAPPING_PERF,diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex 47fa6bded..0eff6374f 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -1,5 +1,4 @@import SwetrixSDK from '@swetrix/sdk'-import billboard, { Chart } from 'billboard.js'import cx from 'clsx'import dayjs from 'dayjs'import { AnimatePresence, motion } from 'framer-motion'@@ -155,12 +154,14 @@ import ProjectAlertsView from '../Alerts/View'import AddAViewModal from './components/AddAViewModal'import CCRow from './components/CCRow'+import { ChartManagerProvider } from './components/ChartManager'import CustomEventsSubmenu from './components/CustomEventsSubmenu'import CustomMetrics from './components/CustomMetrics'import { ErrorChart } from './components/ErrorChart'import { ErrorDetails } from './components/ErrorDetails'import { Errors } from './components/Errors'import Filters from './components/Filters'+import { FunnelChart } from './components/FunnelChart'import FunnelsList from './components/FunnelsList'const InteractiveMap = lazy(() => import('./components/InteractiveMap'))import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'@@ -170,12 +171,14 @@ import NoErrorDetails from './components/NoErrorDetails'import NoEvents from './components/NoEvents'import NoSessionDetails from './components/NoSessionDetails'import { Pageflow } from './components/Pageflow'+import { PerformanceChart } from './components/PerformanceChart'import RefRow from './components/RefRow'import SearchFilters, { getFiltersUrlParams } from './components/SearchFilters'import { SessionChart } from './components/SessionChart'import { SessionDetails } from './components/SessionDetails'import { Sessions } from './components/Sessions'import TBPeriodSelector from './components/TBPeriodSelector'+import { TrafficChart } from './components/TrafficChart'import UserFlow from './components/UserFlow'import WaitingForAnError from './components/WaitingForAnError'import WaitingForAnEvent from './components/WaitingForAnEvent'@@ -197,12 +200,8 @@ import {panelIconMapping,typeNameMapping,noRegionPeriods,- getSettings,- getColumns,CHART_METRICS_MAPPING,CHART_METRICS_MAPPING_PERF,- getSettingsPerf,- getSettingsFunnels,SHORTCUTS_TABS_LISTENERS,SHORTCUTS_TABS_MAP,SHORTCUTS_GENERAL_LISTENERS,@@ -301,7 +300,7 @@ const ChartTypeSwitcher = ({)}-const ViewProject = () => {+const ViewProjectContent = () => {const { id, project, preferences, updatePreferences, extensions, mergeProject, allowedToManage, liveVisitors } =useCurrentProject()const projectPassword = useProjectPassword(id)@@ -359,8 +358,7 @@ const ViewProject = () => {// @ts-expect-errorconst [chartData, setChartData] = useState<TrafficLogResponse['chart'] & { [key: string]: number[] }>({})- const [mainChart, setMainChart] = useState<Chart | null>(null)- const prevY2NeededRef = useRef<boolean>(false)+ // prevY2NeededRef removed - no longer needed with new chart managementconst [dataLoading, setDataLoading] = useState(false)const [activeChartMetrics, setActiveChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({[CHART_METRICS_MAPPING.unique]: true,@@ -514,7 +512,7 @@ const ViewProject = () => {}, [searchParams])const prevActivePSIDRef = useRef<string | null>(activePSID)const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(null)- const [sessionChartInstance, setSessionChartInstance] = useState<Chart | null>(null)+ const [sessionChartInstance, _setSessionChartInstance] = useState<any>(null)// errorsconst [errorsSkip, setErrorsSkip] = useState(0)@@ -1289,47 +1287,6 @@ const ViewProject = () => {updatePreferences({customEvents: events,})-- // If no actual series selected (only trendlines without base series), skip rendering- const prospectiveColumns = getColumns(chartData as any, activeChartMetrics, dataChartCompare as any)- if (prospectiveColumns.length <= 1 && _isEmpty(customEventsChartData)) {- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(null)- return- }-- const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)- const bbSettings = getSettings(- chartData,- timeBucket,- activeChartMetrics,- applyRegions,- timeFormat,- rotateXAxis,- chartType,- events,- undefined,- onMainChartZoom,- shouldEnableZoom,- )- if (checkIfAllMetricsAreDisabled) {- try {- mainChart?.destroy()- } catch {- /* ignore destroy errors */- }- setMainChart(null)- } else {- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNames)- return generate- })- }} catch (reason) {console.error('[ERROR] Failed to load custom events:', reason)} finally {@@ -1544,21 +1501,6 @@ const ViewProject = () => {if (_isEmpty(params)) {setIsPanelsDataEmpty(true)} else {- const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)- const bbSettings = getSettings(- chart as any,- newTimebucket,- activeChartMetrics,- applyRegions,- timeFormat,- rotateXAxis,- chartType,- customEventsChart,- // @ts-expect-error- dataCompare?.chart,- onMainChartZoom,- shouldEnableZoom,- )setChartData(chart as any)setPanelsData({@@ -1569,23 +1511,6 @@ const ViewProject = () => {meta,})- if (activeTab === PROJECT_TABS.traffic) {- if (checkIfAllMetricsAreDisabled) {- try {- mainChart?.destroy()- } catch {- /* ignore destroy errors */- }- setMainChart(null)- } else {- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNames)- return generate- })- }- }-setIsPanelsDataEmpty(false)}@@ -1974,17 +1899,6 @@ const ViewProject = () => {setIsPanelsDataEmptyPerf(true)} else {const { chart: chartPerf } = dataPerf- const bbSettings = getSettingsPerf(- chartPerf,- timeBucket,- activeChartMetricsPerf,- rotateXAxis,- chartType,- timeFormat,- dataCompare?.chart,- onMainChartZoom,- shouldEnableZoom,- )setChartDataPerf(chartPerf)setPanelsDataPerf({@@ -1992,14 +1906,6 @@ const ViewProject = () => {data: dataPerf.params,})- if (activeTab === PROJECT_TABS.performance) {- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNamesPerf)- return generate- })- }-setIsPanelsDataEmptyPerf(false)}@@ -2040,24 +1946,11 @@ const ViewProject = () => {setFunnelAnalytics({ funnel, totalPageviews })- const bbSettings = getSettingsFunnels(funnel, totalPageviews, t)-// Unhide the wrapper first, then mount the chart on the next ticksetAnalyticsLoading(false)setDataLoading(false)await new Promise((resolve) => setTimeout(resolve, 1))-- if (activeTab === PROJECT_TABS.funnels) {- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names({- dropoff: t('project.dropoff'),- events: t('project.visitors'),- })- return generate- })- }} catch (reason) {setAnalyticsLoading(false)setDataLoading(false)@@ -2217,156 +2110,6 @@ const ViewProject = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [activeTab, errorOptions, dateRange, filters, id, period, projectPassword, timezone, authLoading, project])- useEffect(() => {- if (authLoading || !project) {- return- }-- if (activeTab === PROJECT_TABS.traffic) {- if (_isEmpty(chartData)) {- return- }-- if (isActiveCompare && _isEmpty(dataChartCompare)) {- return- }- if (checkIfAllMetricsAreDisabled) {- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(null)- return- }-- // If no actual series selected (only 'x' or only trendlines without base series), hide chart- const prospectiveColumns = getColumns(chartData as any, activeChartMetrics, dataChartCompare as any)- if (prospectiveColumns.length <= 1 && _isEmpty(customEventsChartData)) {- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(null)- return- }-- const y2Needed = !!activeChartMetrics.bounce || !!activeChartMetrics.sessionDuration- const shouldRegen = !mainChart || prevY2NeededRef.current !== y2Needed-- if (shouldRegen) {- const applyRegions = !_includes(noRegionPeriods, activePeriod?.period)- const bbSettings = getSettings(- chartData,- timeBucket,- activeChartMetrics,- applyRegions,- timeFormat,- rotateXAxis,- chartType,- customEventsChartData,- dataChartCompare,- onMainChartZoom,- shouldEnableZoom,- )-- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNames)- return generate- })- prevY2NeededRef.current = y2Needed- return- }-- // Update existing chart with new/removed series for smooth animation- try {- mainChart?.load({- columns: getColumns(chartData as any, activeChartMetrics, dataChartCompare as any),- })- } catch {- /* ignore */- }-- const unloadIds: string[] = []- const hasCompare = !_isEmpty(dataChartCompare)-- if (!activeChartMetrics.views) {- unloadIds.push('total')- if (hasCompare) unloadIds.push('totalCompare')- }- if (!activeChartMetrics.unique) {- unloadIds.push('unique')- if (hasCompare) unloadIds.push('uniqueCompare')- }- if (!activeChartMetrics.viewsPerUnique) {- unloadIds.push('viewsPerUnique')- }- if (!activeChartMetrics.trendlines) {- unloadIds.push('trendlineUnique', 'trendlineTotal')- }- if (!activeChartMetrics.bounce) {- unloadIds.push('bounce')- }- if (!activeChartMetrics.sessionDuration) {- unloadIds.push('sessionDuration')- if (hasCompare) unloadIds.push('sessionDurationCompare')- }-- if (unloadIds.length && mainChart) {- try {- mainChart.unload({ ids: unloadIds })- } catch {- /* ignore */- }- }- }-- if (activeTab === PROJECT_TABS.performance) {- if (_isEmpty(chartDataPerf)) {- return- }-- if (isActiveCompare && _isEmpty(dataChartPerfCompare)) {- return- }-- const bbSettings = getSettingsPerf(- chartDataPerf,- timeBucket,- activeChartMetricsPerf,- rotateXAxis,- chartType,- timeFormat,- dataChartPerfCompare,- onMainChartZoom,- shouldEnableZoom,- )-- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNamesPerf)- return generate- })- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- authLoading,- project,- activeChartMetrics,- chartData,- chartDataPerf,- activeChartMetricsPerf,- dataChartCompare,- checkIfAllMetricsAreDisabled,- ])-useEffect(() => {let sdk: SwetrixSDK | null = null@@ -2639,62 +2382,6 @@ const ViewProject = () => {const setChartTypeOnClick = (type: keyof typeof chartTypes) => {setItem('chartType', type)setChartType(type)-- if (activeTab === PROJECT_TABS.traffic) {- if (checkIfAllMetricsAreDisabled) {- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(null)- return- }- const bbSettings = getSettings(- chartData,- timeBucket,- activeChartMetrics,- !_includes(noRegionPeriods, activePeriod?.period),- timeFormat,- rotateXAxis,- type,- customEventsChartData,- dataChartCompare,- onMainChartZoom,- shouldEnableZoom,- )-- try {- mainChart?.destroy()- } catch {- /* ignore */- }- setMainChart(() => {- const generate = billboard.generate(bbSettings)- generate.data.names(dataNames)- return generate- })- }-- if (activeTab === PROJECT_TABS.performance) {- const bbPerfSettings = getSettingsPerf(- chartDataPerf,- timeBucket,- activeChartMetricsPerf,- rotateXAxis,- type,- timeFormat,- dataChartPerfCompare,- onMainChartZoom,- shouldEnableZoom,- )-- setMainChart(() => {- const generate = billboard.generate(bbPerfSettings)- generate.data.names(dataNamesPerf)- return generate- })- }}const resetDateRange = () => {@@ -3531,7 +3218,6 @@ const ViewProject = () => {chartType={chartType}dataNames={dataNames}onZoom={setZoomedTimeRange}- onChartReady={setSessionChartInstance}/>{zoomedTimeRange ? (<button@@ -3920,12 +3606,23 @@ const ViewProject = () => {: null}</div>) : null}- <div- className={cx('mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible', {- hidden: checkIfAllMetricsAreDisabled,- })}- id='dataChart'- />+ {!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (+ <TrafficChart+ chartData={chartData}+ timeBucket={timeBucket}+ activeChartMetrics={activeChartMetrics}+ applyRegions={!_includes(noRegionPeriods, activePeriod?.period)}+ timeFormat={timeFormat}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ customEventsChartData={customEventsChartData}+ dataChartCompare={dataChartCompare}+ onZoom={onMainChartZoom}+ enableZoom={shouldEnableZoom}+ dataNames={dataNames}+ className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'+ />+ ) : null}</div>{!isPanelsDataEmpty ? <Filters tnMapping={tnMapping} /> : null}<CustomMetrics@@ -4236,12 +3933,21 @@ const ViewProject = () => {activePeriodCompare={activePeriodCompare}/>) : null}- <div- className={cx('mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible', {- hidden: checkIfAllMetricsAreDisabled,- })}- id='dataChart'- />+ {!checkIfAllMetricsAreDisabled && !_isEmpty(chartDataPerf) ? (+ <PerformanceChart+ chart={chartDataPerf}+ timeBucket={timeBucket}+ activeChartMetrics={activeChartMetricsPerf}+ rotateXAxis={rotateXAxis}+ chartType={chartType}+ timeFormat={timeFormat}+ compareChart={dataChartPerfCompare}+ onZoom={onMainChartZoom}+ enableZoom={shouldEnableZoom}+ dataNames={dataNamesPerf}+ className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'+ />+ ) : null}</div>{!isPanelsDataEmptyPerf ? <Filters tnMapping={tnMapping} /> : null}<div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>@@ -4446,7 +4152,14 @@ const ViewProject = () => {</p></>) : null}- <div className='mt-5 h-80 [&_svg]:!overflow-visible' id='funnelChart' />+ {funnelAnalytics?.funnel ? (+ <FunnelChart+ funnel={funnelAnalytics.funnel}+ totalPageviews={funnelAnalytics.totalPageviews}+ t={t}+ className='mt-5 h-80 [&_svg]:!overflow-visible'+ />+ ) : null}</div>) : null}</motion.div>@@ -4589,4 +4302,12 @@ const ViewProject = () => {)}+const ViewProject = () => {+ return (+ <ChartManagerProvider>+ <ViewProjectContent />+ </ChartManagerProvider>+ )+}+export default ViewProjectdiff --git a/web/app/pages/Project/View/components/ChartManager.tsx b/web/app/pages/Project/View/components/ChartManager.tsxnew file mode 100644index 000000000..bcd587a86--- /dev/null+++ b/web/app/pages/Project/View/components/ChartManager.tsx@@ -0,0 +1,77 @@+import { Chart } from 'billboard.js'+import React, { createContext, useContext, useRef, useCallback, ReactNode } from 'react'++interface ChartManagerContextType {+ registerChart: (id: string, chart: Chart | null) => void+ unregisterChart: (id: string) => void+ getChart: (id: string) => Chart | null+ destroyChart: (id: string) => void+ destroyAllCharts: () => void+}++const ChartManagerContext = createContext<ChartManagerContextType | null>(null)++export const useChartManager = () => {+ const context = useContext(ChartManagerContext)+ if (!context) {+ throw new Error('useChartManager must be used within a ChartManagerProvider')+ }+ return context+}++interface ChartManagerProviderProps {+ children: ReactNode+}++export const ChartManagerProvider = ({ children }: ChartManagerProviderProps) => {+ const chartsRef = useRef<Map<string, Chart>>(new Map())++ const registerChart = useCallback((id: string, chart: Chart | null) => {+ if (chart) {+ chartsRef.current.set(id, chart)+ } else {+ chartsRef.current.delete(id)+ }+ }, [])++ const unregisterChart = useCallback((id: string) => {+ chartsRef.current.delete(id)+ }, [])++ const getChart = useCallback((id: string) => {+ return chartsRef.current.get(id) || null+ }, [])++ const destroyChart = useCallback((id: string) => {+ const chart = chartsRef.current.get(id)+ if (chart) {+ try {+ chart.destroy()+ } catch {+ // ignore destroy errors+ }+ chartsRef.current.delete(id)+ }+ }, [])++ const destroyAllCharts = useCallback(() => {+ chartsRef.current.forEach((chart) => {+ try {+ chart.destroy()+ } catch {+ // ignore destroy errors+ }+ })+ chartsRef.current.clear()+ }, [])++ const value: ChartManagerContextType = {+ registerChart,+ unregisterChart,+ getChart,+ destroyChart,+ destroyAllCharts,+ }++ return <ChartManagerContext.Provider value={value}>{children}</ChartManagerContext.Provider>+}diff --git a/web/app/pages/Project/View/components/ErrorChart.tsx b/web/app/pages/Project/View/components/ErrorChart.tsxindex a45e089c3..2aed3a2fe 100644--- a/web/app/pages/Project/View/components/ErrorChart.tsx+++ b/web/app/pages/Project/View/components/ErrorChart.tsx@@ -1,8 +1,10 @@-import billboard, { type ChartOptions } from 'billboard.js'-import { useEffect } from 'react'+import { ChartOptions } from 'billboard.js'+import React, { useMemo } from 'react'import { getSettingsError } from '../ViewProject.helpers'+import { MainChart } from './MainChart'+interface ErrorChartProps {chart?: {x: string[]@@ -13,19 +15,36 @@ interface ErrorChartProps {rotateXAxis: booleanchartType: stringdataNames: any+ className?: string}-export const ErrorChart = ({ chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames }: ErrorChartProps) => {- useEffect(() => {- const bbSettings: ChartOptions = getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType)+export const ErrorChart = ({+ chart,+ timeBucket,+ timeFormat,+ rotateXAxis,+ chartType,+ dataNames,+ className,+}: ErrorChartProps) => {+ const options: ChartOptions = useMemo(() => {+ return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType)+ }, [chart, timeBucket, timeFormat, rotateXAxis, chartType])- const generate = billboard.generate(bbSettings)- generate.data.names(dataNames)- }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames])+ const deps = useMemo(+ () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],+ [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames],+ )return (<div className='overflow-hidden rounded-lg border border-gray-300 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>- <div className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible' id='errorChart' />+ <MainChart+ chartId='error-chart'+ options={options}+ dataNames={dataNames}+ className={className || 'mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'}+ deps={deps}+ /></div>)}diff --git a/web/app/pages/Project/View/components/FunnelChart.tsx b/web/app/pages/Project/View/components/FunnelChart.tsxnew file mode 100644index 000000000..75cefb40b--- /dev/null+++ b/web/app/pages/Project/View/components/FunnelChart.tsx@@ -0,0 +1,33 @@+import { ChartOptions } from 'billboard.js'+import React, { useMemo } from 'react'++import { AnalyticsFunnel } from '~/lib/models/Project'++import { getSettingsFunnels } from '../ViewProject.helpers'++import { MainChart } from './MainChart'++interface FunnelChartProps {+ funnel: AnalyticsFunnel[]+ totalPageviews: number+ t: any+ className?: string+}++export const FunnelChart = ({ funnel, totalPageviews, t, className }: FunnelChartProps) => {+ const options: ChartOptions = useMemo(() => {+ return getSettingsFunnels(funnel, totalPageviews, t)+ }, [funnel, totalPageviews, t])++ const dataNames = useMemo(+ () => ({+ dropoff: t('project.dropoff'),+ events: t('project.visitors'),+ }),+ [t],+ )++ const deps = useMemo(() => [funnel, totalPageviews, t], [funnel, totalPageviews, t])++ return <MainChart chartId='funnel-chart' options={options} dataNames={dataNames} className={className} deps={deps} />+}diff --git a/web/app/pages/Project/View/components/MainChart.tsx b/web/app/pages/Project/View/components/MainChart.tsxnew file mode 100644index 000000000..fc74554fd--- /dev/null+++ b/web/app/pages/Project/View/components/MainChart.tsx@@ -0,0 +1,42 @@+import { ChartOptions } from 'billboard.js'+import React, { useEffect, useRef, useMemo } from 'react'++import BillboardChart from '~/ui/BillboardChart'++import { useChartManager } from './ChartManager'++interface MainChartProps {+ chartId: string+ options: ChartOptions+ dataNames?: Record<string, string>+ className?: string+ deps?: any[]+}++export const MainChart = ({ chartId, options, dataNames, className, deps }: MainChartProps) => {+ const { registerChart, unregisterChart } = useChartManager()+ const chartRef = useRef<any>(null)++ const mergedDeps = useMemo(() => deps || [options, dataNames], [deps, options, dataNames])++ const handleChartReady = (chart: any) => {+ chartRef.current = chart+ registerChart(chartId, chart)+ }++ useEffect(() => {+ return () => {+ unregisterChart(chartId)+ }+ }, [chartId, unregisterChart])++ return (+ <BillboardChart+ options={options}+ dataNames={dataNames}+ className={className}+ onReady={handleChartReady}+ deps={mergedDeps}+ />+ )+}diff --git a/web/app/pages/Project/View/components/PerformanceChart.tsx b/web/app/pages/Project/View/components/PerformanceChart.tsxnew file mode 100644index 000000000..9e7ef5348--- /dev/null+++ b/web/app/pages/Project/View/components/PerformanceChart.tsx@@ -0,0 +1,57 @@+import { ChartOptions } from 'billboard.js'+import React, { useMemo } from 'react'++import { getSettingsPerf } from '../ViewProject.helpers'++import { MainChart } from './MainChart'++interface PerformanceChartProps {+ chart: Record<string, string[]>+ timeBucket: string+ activeChartMetrics: string+ rotateXAxis: boolean+ chartType: string+ timeFormat: string+ compareChart?: Record<string, string[]>+ onZoom?: (domain: [Date, Date] | null) => void+ enableZoom?: boolean+ dataNames: Record<string, string>+ className?: string+}++export const PerformanceChart = ({+ chart,+ timeBucket,+ activeChartMetrics,+ rotateXAxis,+ chartType,+ timeFormat,+ compareChart,+ onZoom,+ enableZoom,+ dataNames,+ className,+}: PerformanceChartProps) => {+ const options: ChartOptions = useMemo(() => {+ return getSettingsPerf(+ chart,+ timeBucket,+ activeChartMetrics,+ rotateXAxis,+ chartType,+ timeFormat,+ compareChart,+ onZoom,+ enableZoom,+ )+ }, [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom])++ const deps = useMemo(+ () => [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom],+ [chart, timeBucket, activeChartMetrics, rotateXAxis, chartType, timeFormat, compareChart, onZoom, enableZoom],+ )++ return (+ <MainChart chartId='performance-chart' options={options} dataNames={dataNames} className={className} deps={deps} />+ )+}diff --git a/web/app/pages/Project/View/components/SessionChart.tsx b/web/app/pages/Project/View/components/SessionChart.tsxindex 91c024dd5..8bda12985 100644--- a/web/app/pages/Project/View/components/SessionChart.tsx+++ b/web/app/pages/Project/View/components/SessionChart.tsx@@ -1,8 +1,10 @@-import billboard, { type ChartOptions, type Chart } from 'billboard.js'-import { useEffect, useRef } from 'react'+import { ChartOptions } from 'billboard.js'+import React, { useMemo } from 'react'import { getSettingsSession } from '../ViewProject.helpers'+import { MainChart } from './MainChart'+interface SessionChartProps {chart?: {x: string[]@@ -16,7 +18,7 @@ interface SessionChartProps {chartType: stringdataNames: anyonZoom?: (domain: [Date, Date] | null) => void- onChartReady?: (chart: Chart | null) => void+ className?: string}export const SessionChart = ({@@ -27,44 +29,24 @@ export const SessionChart = ({chartType,dataNames,onZoom,- onChartReady,+ className,}: SessionChartProps) => {- const chartRef = useRef<Chart | null>(null)-- useEffect(() => {- const bbSettings: ChartOptions = getSettingsSession(- chart,- timeBucket as string,- timeFormat,- rotateXAxis,- chartType,- onZoom,- )-- if (chartRef.current) {- chartRef.current.destroy()- }-- const generate = billboard.generate(bbSettings)- chartRef.current = generate- generate.data.names(dataNames)-- if (onChartReady) {- onChartReady(generate)- }-- return () => {- if (!generate) {- return- }-- generate.destroy()- chartRef.current = null- if (onChartReady) {- onChartReady(null)- }- }- }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, onZoom, onChartReady])-- return <div className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible' id='sessionChart' />+ const options: ChartOptions = useMemo(() => {+ return getSettingsSession(chart, timeBucket as string, timeFormat, rotateXAxis, chartType, onZoom)+ }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, onZoom])++ const deps = useMemo(+ () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, onZoom],+ [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, onZoom],+ )++ return (+ <MainChart+ chartId='session-chart'+ options={options}+ dataNames={dataNames}+ className={className || 'mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible'}+ deps={deps}+ />+ )}diff --git a/web/app/pages/Project/View/components/TrafficChart.tsx b/web/app/pages/Project/View/components/TrafficChart.tsxnew file mode 100644index 000000000..e4abe0514--- /dev/null+++ b/web/app/pages/Project/View/components/TrafficChart.tsx@@ -0,0 +1,97 @@+import { ChartOptions } from 'billboard.js'+import React, { useMemo } from 'react'++import { getSettings } from '../ViewProject.helpers'++import { MainChart } from './MainChart'++interface TrafficChartProps {+ chartData: any+ timeBucket: string+ activeChartMetrics: Record<string, boolean>+ applyRegions: boolean+ timeFormat: string+ rotateXAxis: boolean+ chartType: string+ customEventsChartData?: Record<string, string[]>+ dataChartCompare?: any+ onZoom?: (domain: [Date, Date] | null) => void+ enableZoom?: boolean+ dataNames: Record<string, string>+ className?: string+}++export const TrafficChart = ({+ chartData,+ timeBucket,+ activeChartMetrics,+ applyRegions,+ timeFormat,+ rotateXAxis,+ chartType,+ customEventsChartData,+ dataChartCompare,+ onZoom,+ enableZoom,+ dataNames,+ className,+}: TrafficChartProps) => {+ const options: ChartOptions = useMemo(() => {+ return getSettings(+ chartData,+ timeBucket,+ activeChartMetrics,+ applyRegions,+ timeFormat,+ rotateXAxis,+ chartType,+ customEventsChartData,+ dataChartCompare,+ onZoom,+ enableZoom,+ )+ }, [+ chartData,+ timeBucket,+ activeChartMetrics,+ applyRegions,+ timeFormat,+ rotateXAxis,+ chartType,+ customEventsChartData,+ dataChartCompare,+ onZoom,+ enableZoom,+ ])++ const deps = useMemo(+ () => [+ chartData,+ timeBucket,+ activeChartMetrics,+ applyRegions,+ timeFormat,+ rotateXAxis,+ chartType,+ customEventsChartData,+ dataChartCompare,+ onZoom,+ enableZoom,+ ],+ [+ chartData,+ timeBucket,+ activeChartMetrics,+ applyRegions,+ timeFormat,+ rotateXAxis,+ chartType,+ customEventsChartData,+ dataChartCompare,+ onZoom,+ enableZoom,+ ],+ )++ return <MainChart chartId='traffic-chart' options={options} dataNames={dataNames} className={className} deps={deps} />+}diff --git a/web/app/ui/BillboardChart.tsx b/web/app/ui/BillboardChart.tsxnew file mode 100644index 000000000..62094e43e--- /dev/null+++ b/web/app/ui/BillboardChart.tsx@@ -0,0 +1,63 @@+import billboard, { type Chart, type ChartOptions } from 'billboard.js'+import React, { useEffect, useMemo, useRef } from 'react'++interface BillboardChartProps {+ options: ChartOptions+ dataNames?: Record<string, string>+ className?: string+ onReady?: (chart: Chart | null) => void+ deps?: any[]+}++const BillboardChart = ({ options, dataNames, className, onReady, deps }: BillboardChartProps) => {+ const containerRef = useRef<HTMLDivElement | null>(null)+ const chartRef = useRef<Chart | null>(null)++ const mergedDeps = useMemo(() => deps || [options, dataNames], [deps, options, dataNames])++ useEffect(() => {+ if (!containerRef.current) {+ return+ }++ if (chartRef.current) {+ try {+ chartRef.current.destroy()+ } catch {+ // ignore+ }+ chartRef.current = null+ if (onReady) onReady(null)+ }++ const opts: ChartOptions = { ...options, bindto: containerRef.current as unknown as HTMLElement }+ const chart = billboard.generate(opts)+ chartRef.current = chart++ if (dataNames) {+ try {+ chart.data.names(dataNames)+ } catch {+ // ignore+ }+ }++ if (onReady) onReady(chart)++ return () => {+ if (!chartRef.current) return+ try {+ chartRef.current.destroy()+ } catch {+ // ignore+ }+ chartRef.current = null+ if (onReady) onReady(null)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, mergedDeps)++ return <div ref={containerRef} className={className} />+}++export default BillboardChart