Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Dashboard loading state UX improvements (#6480)
RobertJoonas7c6fd4a034dc
diff --git a/assets/js/dashboard/stats/devices/index.tsx b/assets/js/dashboard/stats/devices/index.tsxindex 6c985079d6..fc9f812f2b 100644--- a/assets/js/dashboard/stats/devices/index.tsx+++ b/assets/js/dashboard/stats/devices/index.tsx@@ -100,6 +100,7 @@ export function Devices() {/></ReportHeader><IndexBreakdown+ key={reportKey}metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}diff --git a/assets/js/dashboard/stats/locations/index.tsx b/assets/js/dashboard/stats/locations/index.tsxindex 501ebf00db..026e455745 100644--- a/assets/js/dashboard/stats/locations/index.tsx+++ b/assets/js/dashboard/stats/locations/index.tsx@@ -213,6 +213,7 @@ export function Locations() {/>) : (<IndexBreakdown+ key={tab}metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}diff --git a/assets/js/dashboard/stats/locations/map.tsx b/assets/js/dashboard/stats/locations/map.tsxindex 2f52fff787..724c4e47e5 100644--- a/assets/js/dashboard/stats/locations/map.tsx+++ b/assets/js/dashboard/stats/locations/map.tsx@@ -1,6 +1,4 @@-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import * as d3 from 'd3'-import classNames from 'classnames'+import React, { useCallback, useEffect, useMemo, useState } from 'react'import {replaceFilterByPrefix,cleanLabels,@@ -8,37 +6,22 @@ import {isRealTimeDashboard} from '../../util/filters'import { useAppNavigate } from '../../navigation/use-app-navigate'-import { numberShortFormatter } from '../../util/number-formatter'import { useSiteContext } from '../../site-context'import { useDashboardStateContext } from '../../dashboard-state-context'-import { UIMode, useTheme } from '../../theme-context'import { MIN_HEIGHT } from '../reports/index-breakdown'-import { MapTooltip } from './map-tooltip'import { GeolocationNotice } from './geolocation-notice'import { DashboardState } from '../../dashboard-state'import { useQueryApi } from '../../hooks/use-query-api'import { QueryApiResponse } from '../../api'-import {- COUNTRIES_BY_TWO_LETTER_CODE,- parseWorldTopoJsonToGeoJsonFeatures,- WorldJsonCountryData-} from './countries'+import { COUNTRIES_BY_TWO_LETTER_CODE } from './countries'import {BREAKDOWN_REPORTS,BreakdownReportKey} from '../reports/reports-config'+import LazyLoader from '../../components/lazy-loader'+import { CountryData, MetricLabel, WorldMapSvg } from './world-map-svg'-const width = 475-const height = 335--type CountryData = {- alpha_3: string- name: string- visitors: number- code: string-}--function getMetricLabel(dashboardState: DashboardState) {+function getMetricLabel(dashboardState: DashboardState): MetricLabel {if (hasConversionGoalFilter(dashboardState)) {return { singular: 'Conversion', plural: 'Conversions' }}@@ -56,36 +39,38 @@ const WorldMap = ({onDataReady: (response: QueryApiResponse) => void}) => {const navigate = useAppNavigate()- const { mode } = useTheme()const site = useSiteContext()const { dashboardState } = useDashboardStateContext()- const svgRef = useRef<SVGSVGElement | null>(null)- const [tooltip, setTooltip] = useState<{- x: number- y: number- hoveredCountryAlpha3Code: string | null- }>({ x: 0, y: 0, hoveredCountryAlpha3Code: null })+ const [visible, setVisible] = useState(false)const metricLabel = useMemo(() => getMetricLabel(dashboardState),[dashboardState])- const { apiState } = useQueryApi(site, [- 'visit:country',- {- dashboardState,- reportParams: {- metrics: ['visitors'],- dimensions: BREAKDOWN_REPORTS[BreakdownReportKey.countries].dimensions,- alwaysOnFilters:- BREAKDOWN_REPORTS[BreakdownReportKey.countries].alwaysOnFilters,- order_by: [['visitors', 'desc']],- pagination: { limit: 300, offset: 0 }+ const { apiState, isRealtimeSilentUpdate } = useQueryApi(+ site,+ [+ 'visit:country',+ {+ dashboardState,+ reportParams: {+ metrics: ['visitors'],+ dimensions:+ BREAKDOWN_REPORTS[BreakdownReportKey.countries].dimensions,+ alwaysOnFilters:+ BREAKDOWN_REPORTS[BreakdownReportKey.countries].alwaysOnFilters,+ order_by: [['visitors', 'desc']],+ pagination: { limit: 300, offset: 0 }+ }}- }- ])- const { data, isFetching, isError } = apiState+ ],+ { enabled: visible }+ )+ const { data, isPending, isPlaceholderData, isError } = apiState++ const isLoading =+ isPending || isError || (isPlaceholderData && !isRealtimeSilentUpdate)useEffect(() => {if (data) {@@ -115,221 +100,45 @@ const WorldMap = ({}, [data])const onCountryClick = useCallback(- (d: WorldJsonCountryData) => {- const country = dataByAlpha3Code.get(d.properties.a3)- const clickable = country && country.visitors- if (clickable) {- const filters = replaceFilterByPrefix(dashboardState, 'country', [- 'is',- 'country',- [country.code]- ])- const labels = cleanLabels(filters, dashboardState.labels, 'country', {- [country.code]: country.name- })- onCountrySelect()- navigate({- search: (searchRecord) => ({ ...searchRecord, filters, labels })- })- }- },- [navigate, dashboardState, dataByAlpha3Code, onCountrySelect]- )-- useEffect(() => {- if (!svgRef.current) {- return- }-- const { svg, countriesSelection } = drawInteractiveCountries(svgRef.current)- const highlightSelection = drawHighlightedCountryOutline(svgRef.current)-- countriesSelection- .on('mouseover', function (event, country) {- const [x, y] = d3.pointer(event, svg.node()?.parentNode)- setTooltip({ x, y, hoveredCountryAlpha3Code: country.properties.a3 })-- highlightSelection- .attr('d', this.getAttribute('d'))- .attr('class', hoveredOutlineClass)- })-- .on('mousemove', function (event) {- const [x, y] = d3.pointer(event, svg.node()?.parentNode)- setTooltip((currentState) => ({ ...currentState, x, y }))- })-- .on('mouseout', function () {- setTooltip({ x: 0, y: 0, hoveredCountryAlpha3Code: null })- highlightSelection.attr('d', null).attr('class', initialOutlineClass)+ (country: CountryData) => {+ const filters = replaceFilterByPrefix(dashboardState, 'country', [+ 'is',+ 'country',+ [country.code]+ ])+ const labels = cleanLabels(filters, dashboardState.labels, 'country', {+ [country.code]: country.name})-- return () => {- svg.selectAll('*').remove()- }- }, [])-- useEffect(() => {- if (svgRef.current) {- const palette = colorScales[mode]-- const getColorForValue = d3- .scaleLinear<string>()- .domain([0, maxValue])- .range(palette)-- colorInCountriesWithValues(- svgRef.current,- getColorForValue,- dataByAlpha3Code- ).on('click', (_event, countryPath) => {- onCountryClick(countryPath as unknown as WorldJsonCountryData)+ onCountrySelect()+ navigate({+ search: (searchRecord) => ({ ...searchRecord, filters, labels })})- }- }, [mode, maxValue, dataByAlpha3Code, onCountryClick])-- const hoveredCountryData = tooltip.hoveredCountryAlpha3Code- ? dataByAlpha3Code.get(tooltip.hoveredCountryAlpha3Code)- : undefined+ },+ [navigate, dashboardState, onCountrySelect]+ )return (- <div- className="flex flex-col justify-center items-center relative"- style={{ minHeight: MIN_HEIGHT }}- >+ <LazyLoader onVisible={() => setVisible(true)}><div- className="relative flex justify-center items-center mt-4 w-full"- style={{ height: height, maxWidth: width }}+ className="flex flex-col justify-center items-center relative"+ style={{ minHeight: MIN_HEIGHT }}>- <svg- ref={svgRef}- viewBox={`0 0 ${width} ${height}`}- className="w-full"- />- {!!hoveredCountryData && (- <MapTooltip- x={tooltip.x}- y={tooltip.y}- name={hoveredCountryData.name}- value={numberShortFormatter(hoveredCountryData.visitors)}- label={- hoveredCountryData.visitors === 1- ? metricLabel.singular- : metricLabel.plural- }+ {isLoading ? (+ <div className="mx-auto loading">+ <div />+ </div>+ ) : (+ <WorldMapSvg+ maxValue={maxValue}+ dataByAlpha3Code={dataByAlpha3Code}+ metricLabel={metricLabel}+ onCountryClick={onCountryClick}/>)}- {isFetching ||- (isError && (- <div className="absolute inset-0 flex justify-center items-center">- <div className="loading">- <div />- </div>- </div>- ))}+ {site.isDbip && <GeolocationNotice />}</div>- {site.isDbip && <GeolocationNotice />}- </div>+ </LazyLoader>)}-const colorScales = {- [UIMode.dark]: ['#2a276d', '#6366f1'], // custom color between indigo-900 and indigo-950, indigo-500- [UIMode.light]: ['#e0e7ff', '#818cf8'] // indigo-100, indigo-400-}--const countryElementClass = 'country'-const countrySelector = `path.${countryElementClass}`-const initialStroke = classNames(- 'stroke-white',- 'dark:stroke-gray-900',- 'stroke-1px'-)-const hoveredStroke = classNames(- 'stroke-[1.5px]',- 'stroke-indigo-400',- 'dark:stroke-indigo-500'-)--const countryClass = classNames(- countryElementClass,- initialStroke,- 'transition-colors',- 'stroke-1',- 'fill-gray-150',- 'dark:fill-gray-750'-)--const sharedOutlineClass = classNames(- 'transition-colors',- 'fill-none',- 'pointer-events-none'-)--const initialOutlineClass = classNames(- sharedOutlineClass,- initialStroke,- 'opacity-0'-)-const hoveredOutlineClass = classNames(sharedOutlineClass, hoveredStroke)--/**- * Used to color the countries- * @returns the svg elements represeting countries- */-function colorInCountriesWithValues(- element: SVGSVGElement,- getColorForValue: d3.ScaleLinear<string, string, never>,- dataByCountryCode: Map<string, CountryData>-) {- const svg = d3.select(element)-- return svg- .selectAll<SVGPathElement, WorldJsonCountryData>(countrySelector)- .style('fill', (countryPath) => {- const country = dataByCountryCode.get(countryPath.properties.a3)- if (!country?.visitors) {- return null- }- return getColorForValue(country.visitors)- })- .style('cursor', (countryPath) => {- const country = dataByCountryCode.get(countryPath.properties.a3)- if (!country?.visitors) {- return null- }- return 'pointer'- })-}--function drawHighlightedCountryOutline(element: SVGSVGElement) {- return d3.select(element).append('path').attr('class', initialOutlineClass)-}--function drawInteractiveCountries(element: SVGSVGElement) {- const path = setupProjetionPath()- const data = parseWorldTopoJsonToGeoJsonFeatures()- const svg = d3.select(element)-- const countriesSelection = svg- .selectAll(countrySelector)- .data(data)- .enter()- .append('path')- .attr('class', countryClass)- .attr('d', path as never)-- return { svg, countriesSelection }-}--function setupProjetionPath() {- const projection = d3- .geoMercator()- .scale(75)- .translate([width / 2, height / 1.5])-- const path = d3.geoPath().projection(projection)- return path-}-export default WorldMapdiff --git a/assets/js/dashboard/stats/locations/world-map-svg.tsx b/assets/js/dashboard/stats/locations/world-map-svg.tsxnew file mode 100644index 0000000000..f53395933e--- /dev/null+++ b/assets/js/dashboard/stats/locations/world-map-svg.tsx@@ -0,0 +1,234 @@+import React, { useEffect, useRef, useState } from 'react'+import * as d3 from 'd3'+import classNames from 'classnames'+import { numberShortFormatter } from '../../util/number-formatter'+import { UIMode, useTheme } from '../../theme-context'+import { MapTooltip } from './map-tooltip'+import {+ parseWorldTopoJsonToGeoJsonFeatures,+ WorldJsonCountryData+} from './countries'+import { FADE_IN_CLASSNAME } from '../reports/index-breakdown'++const MAP_CONTAINER_WIDTH = 475+const MAP_CONTAINER_HEIGHT = 335++export type CountryData = {+ alpha_3: string+ name: string+ visitors: number+ code: string+}++export type MetricLabel = { singular: string; plural: string }++export function WorldMapSvg({+ maxValue,+ dataByAlpha3Code,+ metricLabel,+ onCountryClick+}: {+ maxValue: number+ dataByAlpha3Code: Map<string, CountryData>+ metricLabel: MetricLabel+ onCountryClick: (country: CountryData) => void+}) {+ const { mode } = useTheme()+ const svgRef = useRef<SVGSVGElement | null>(null)+ const [tooltip, setTooltip] = useState<{+ x: number+ y: number+ hoveredCountryAlpha3Code: string | null+ }>({ x: 0, y: 0, hoveredCountryAlpha3Code: null })++ useEffect(() => {+ if (!svgRef.current) {+ return+ }++ const { svg, countriesSelection } = drawInteractiveCountries(svgRef.current)+ const highlightSelection = drawHighlightedCountryOutline(svgRef.current)++ countriesSelection+ .on('mouseover', function (event, country) {+ const [x, y] = d3.pointer(event, svg.node()?.parentNode)+ setTooltip({ x, y, hoveredCountryAlpha3Code: country.properties.a3 })++ highlightSelection+ .attr('d', this.getAttribute('d'))+ .attr('class', hoveredOutlineClass)+ })++ .on('mousemove', function (event) {+ const [x, y] = d3.pointer(event, svg.node()?.parentNode)+ setTooltip((currentState) => ({ ...currentState, x, y }))+ })++ .on('mouseout', function () {+ setTooltip({ x: 0, y: 0, hoveredCountryAlpha3Code: null })+ highlightSelection.attr('d', null).attr('class', initialOutlineClass)+ })++ return () => {+ svg.selectAll('*').remove()+ }+ }, [])++ useEffect(() => {+ if (!svgRef.current) {+ return+ }++ const palette = colorScales[mode]++ const getColorForValue = d3+ .scaleLinear<string>()+ .domain([0, maxValue])+ .range(palette)++ colorInCountriesWithValues(+ svgRef.current,+ getColorForValue,+ dataByAlpha3Code+ ).on('click', (_event, countryPath) => {+ const country = dataByAlpha3Code.get(+ (countryPath as unknown as WorldJsonCountryData).properties.a3+ )+ if (country?.visitors) {+ onCountryClick(country)+ }+ })+ }, [mode, maxValue, dataByAlpha3Code, onCountryClick])++ const hoveredCountryData = tooltip.hoveredCountryAlpha3Code+ ? dataByAlpha3Code.get(tooltip.hoveredCountryAlpha3Code)+ : undefined++ return (+ <div+ className="relative flex justify-center items-center mt-4 w-full"+ style={{+ height: MAP_CONTAINER_HEIGHT,+ maxWidth: MAP_CONTAINER_WIDTH+ }}+ >+ <svg+ ref={svgRef}+ viewBox={`0 0 ${MAP_CONTAINER_WIDTH} ${MAP_CONTAINER_HEIGHT}`}+ className={classNames('w-full', FADE_IN_CLASSNAME)}+ />+ {!!hoveredCountryData && (+ <MapTooltip+ x={tooltip.x}+ y={tooltip.y}+ name={hoveredCountryData.name}+ value={numberShortFormatter(hoveredCountryData.visitors)}+ label={+ hoveredCountryData.visitors === 1+ ? metricLabel.singular+ : metricLabel.plural+ }+ />+ )}+ </div>+ )+}++const colorScales = {+ [UIMode.dark]: ['#2a276d', '#6366f1'], // custom color between indigo-900 and indigo-950, indigo-500+ [UIMode.light]: ['#e0e7ff', '#818cf8'] // indigo-100, indigo-400+}++const countryElementClass = 'country'+const countrySelector = `path.${countryElementClass}`+const initialStroke = classNames(+ 'stroke-white',+ 'dark:stroke-gray-900',+ 'stroke-1px'+)+const hoveredStroke = classNames(+ 'stroke-[1.5px]',+ 'stroke-indigo-400',+ 'dark:stroke-indigo-500'+)++const countryClass = classNames(+ countryElementClass,+ initialStroke,+ 'transition-colors',+ 'stroke-1',+ 'fill-gray-150',+ 'dark:fill-gray-750'+)++const sharedOutlineClass = classNames(+ 'transition-colors',+ 'fill-none',+ 'pointer-events-none'+)++const initialOutlineClass = classNames(+ sharedOutlineClass,+ initialStroke,+ 'opacity-0'+)+const hoveredOutlineClass = classNames(sharedOutlineClass, hoveredStroke)++/**+ * Used to color the countries+ * @returns the svg elements represeting countries+ */+function colorInCountriesWithValues(+ element: SVGSVGElement,+ getColorForValue: d3.ScaleLinear<string, string, never>,+ dataByCountryCode: Map<string, CountryData>+) {+ const svg = d3.select(element)++ return svg+ .selectAll<SVGPathElement, WorldJsonCountryData>(countrySelector)+ .style('fill', (countryPath) => {+ const country = dataByCountryCode.get(countryPath.properties.a3)+ if (!country?.visitors) {+ return null+ }+ return getColorForValue(country.visitors)+ })+ .style('cursor', (countryPath) => {+ const country = dataByCountryCode.get(countryPath.properties.a3)+ if (!country?.visitors) {+ return null+ }+ return 'pointer'+ })+}++function drawHighlightedCountryOutline(element: SVGSVGElement) {+ return d3.select(element).append('path').attr('class', initialOutlineClass)+}++function drawInteractiveCountries(element: SVGSVGElement) {+ const path = setupProjectionPath()+ const data = parseWorldTopoJsonToGeoJsonFeatures()+ const svg = d3.select(element)++ const countriesSelection = svg+ .selectAll(countrySelector)+ .data(data)+ .enter()+ .append('path')+ .attr('class', countryClass)+ .attr('d', path as never)++ return { svg, countriesSelection }+}++function setupProjectionPath() {+ const projection = d3+ .geoMercator()+ .scale(75)+ .translate([MAP_CONTAINER_WIDTH / 2, MAP_CONTAINER_HEIGHT / 1.5])++ const path = d3.geoPath().projection(projection)+ return path+}diff --git a/assets/js/dashboard/stats/reports/index-breakdown.tsx b/assets/js/dashboard/stats/reports/index-breakdown.tsxindex 4625a7ec60..d21069ba9a 100644--- a/assets/js/dashboard/stats/reports/index-breakdown.tsx+++ b/assets/js/dashboard/stats/reports/index-breakdown.tsx@@ -41,6 +41,8 @@ import {const MAX_ITEMS = 9export const MIN_HEIGHT = 356+export const FADE_IN_CLASSNAME =+ 'opacity-100 transition-opacity duration-300 starting:opacity-0'const ROW_HEIGHT = 32const ROW_GAP_HEIGHT = 4const DATA_CONTAINER_HEIGHT =@@ -472,6 +474,7 @@ export function IndexBreakdownRenderer<TRow>({if (!columns || isPending || (isPlaceholderData && !isRealtimeSilentUpdate)) {return (<div+ key="loading"className="w-full flex flex-col justify-center"style={{ minHeight: `${MIN_HEIGHT}px` }}>@@ -485,6 +488,7 @@ export function IndexBreakdownRenderer<TRow>({if (rows.length === 0) {return (<div+ key="empty"className="w-full h-full flex flex-col justify-center"style={{ minHeight: `${MIN_HEIGHT}px` }}>@@ -496,7 +500,10 @@ export function IndexBreakdownRenderer<TRow>({}return (- <div className="h-full flex flex-col opacity-100 transition-opacity duration-300 starting:opacity-0">+ <div+ key="data"+ className={classNames('h-full flex flex-col', FADE_IN_CLASSNAME)}+ ><divstyle={{ height: ROW_HEIGHT }}className="pt-3 w-full text-xs font-medium text-gray-500 dark:text-gray-400 flex items-center"diff --git a/assets/js/dashboard/stats/sources/index.tsx b/assets/js/dashboard/stats/sources/index.tsxindex 087e0fe546..c1c849b16b 100644--- a/assets/js/dashboard/stats/sources/index.tsx+++ b/assets/js/dashboard/stats/sources/index.tsx@@ -208,6 +208,7 @@ export default function Sources() {return (<IndexBreakdown+ key={currentReportKey}metrics={metrics}dimensions={reportConfig.dimensions}dimensionLabel={reportConfig.dimensionLabel}