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
Refactor: Move from class to function components in React (#4198)
RobertJoonas14cf6501c323
diff --git a/assets/js/dashboard/comparison-consumer-hoc.js b/assets/js/dashboard/comparison-consumer-hoc.jsdeleted file mode 100644index c78fcd7542..0000000000--- a/assets/js/dashboard/comparison-consumer-hoc.js+++ /dev/null@@ -1,16 +0,0 @@-import React from 'react';-import { ComparisonContext } from './comparison-context'--export const withComparisonConsumer = (WrappedComponent) => {- return class extends React.Component {- render() {- return (- <ComparisonContext.Consumer>- {({data, modifyComparison}) => (- <WrappedComponent comparison={data} modifyComparison={modifyComparison} {...this.props} />- )}- </ComparisonContext.Consumer>- );- }- }-}diff --git a/assets/js/dashboard/comparison-context.js b/assets/js/dashboard/comparison-context.jsdeleted file mode 100644index e453291f9d..0000000000--- a/assets/js/dashboard/comparison-context.js+++ /dev/null@@ -1,9 +0,0 @@-import React from 'react';--export const ComparisonContext = React.createContext({- data: {- enabled: false,- // timePeriod: '' // Saved for future update to allow for customizable compare period- },- modifyComparison: () => {}-});diff --git a/assets/js/dashboard/comparison-provider-hoc.js b/assets/js/dashboard/comparison-provider-hoc.jsdeleted file mode 100644index dbd63d3bc7..0000000000--- a/assets/js/dashboard/comparison-provider-hoc.js+++ /dev/null@@ -1,36 +0,0 @@-import React from 'react';-import { ComparisonContext } from './comparison-context'-import * as storage from './util/storage'---export const withComparisonProvider = (WrappedComponent) => {- return class extends React.Component {- constructor(props) {- super(props)- this.state = {- comparison: {- enabled: storage.getItem('comparison__enabled')=='true' || false,- // timePeriod: storage.getItem('comparison__period') || ''- }- };-- this.updateComparisonData = this.updateComparisonData.bind(this)- }-- updateComparisonData(data) {- const {enabled} = data-- storage.setItem('comparison__enabled', enabled || false)-- this.setState({comparison: data})- }-- render() {- return (- <ComparisonContext.Provider value={{data: this.state.comparison, modifyComparison: this.updateComparisonData}}>- <WrappedComponent {...this.props}/>- </ComparisonContext.Provider>- );- }- }-}diff --git a/assets/js/dashboard/filters.js b/assets/js/dashboard/filters.jsindex 4581a91f77..c675973c44 100644--- a/assets/js/dashboard/filters.js+++ b/assets/js/dashboard/filters.js@@ -1,4 +1,4 @@-import React, { Fragment, useState } from 'react';+import React, { Fragment, useEffect, useState } from 'react';import { Link, withRouter } from 'react-router-dom'import { AdjustmentsVerticalIcon, MagnifyingGlassIcon, XMarkIcon, PencilSquareIcon } from '@heroicons/react/20/solid'import classNames from 'classnames'@@ -16,6 +16,8 @@ import {getLabel} from "./util/filters"+const WRAPSTATE = { unwrapped: 0, waiting: 1, wrapped: 2 }+function removeFilter(filterIndex, history, query) {const newFilters = query.filters.filter((_filter, index) => filterIndex != index)const newLabels = cleanLabels(newFilters, query.labels)@@ -94,10 +96,10 @@ function filterDropdownOption(site, option) {)}-function DropdownContent({ history, site, query, wrapped }) {+function DropdownContent({ history, site, query, wrapState }) {const [addingFilter, setAddingFilter] = useState(false);- if (wrapped === 0 || addingFilter) {+ if (wrapState === WRAPSTATE.unwrapped || addingFilter) {let filterModals = {...FILTER_MODAL_TO_FILTER_GROUP}if (!site.propsAvailable) delete filterModals.props@@ -119,52 +121,31 @@ function DropdownContent({ history, site, query, wrapped }) {)}-class Filters extends React.Component {- constructor(props) {- super(props);-- this.state = {- wrapped: 1, // 0=unwrapped, 1=waiting to check, 2=wrapped- viewport: 1080,- };-- this.renderDropDown = this.renderDropDown.bind(this);- this.handleResize = this.handleResize.bind(this);- this.handleKeyup = this.handleKeyup.bind(this)- }-- componentDidMount() {- document.addEventListener('mousedown', this.handleClick, false);- window.addEventListener('resize', this.handleResize, false);- document.addEventListener('keyup', this.handleKeyup);-- this.handleResize();- this.rewrapFilters();- }-- componentDidUpdate(prevProps, prevState) {- const { query } = this.props;- const { viewport, wrapped } = this.state;-- if (JSON.stringify(query) !== JSON.stringify(prevProps.query) || viewport !== prevState.viewport) {- // eslint-disable-next-line react/no-did-update-set-state- this.setState({ wrapped: 1 });+function Filters(props) {+ const { history, query, site } = props+ const [wrapped, setWrapped] = useState(WRAPSTATE.waiting)+ const [viewport, setViewport] = useState(1080)++ useEffect(() => {+ window.addEventListener('resize', handleResize, false)+ document.addEventListener('keyup', handleKeyup)++ return () => {+ window.removeEventListener('resize', handleResize, false)+ document.removeEventListener("keyup", handleKeyup)}+ }, [])- if (wrapped === 1 && prevState.wrapped !== 1) {- this.rewrapFilters();- }- }+ useEffect(() => {+ setWrapped(WRAPSTATE.waiting)+ }, [query, viewport])- componentWillUnmount() {- document.removeEventListener("keyup", this.handleKeyup);- document.removeEventListener('mousedown', this.handleClick, false);- window.removeEventListener('resize', this.handleResize, false);- }+ useEffect(() => {+ if (wrapped === WRAPSTATE.waiting) { updateDisplayMode() }+ }, [wrapped])- handleKeyup(e) {- const { query, history } = this.props+ function handleKeyup(e) {if (e.ctrlKey || e.metaKey || e.altKey) returnif (e.key === 'Escape') {@@ -172,41 +153,34 @@ class Filters extends React.Component {}}- handleResize() {- this.setState({ viewport: window.innerWidth || 639 });+ function handleResize() {+ setViewport(window.innerWidth || 639)}// Checks if the filter container is wrapping items- rewrapFilters() {- const items = document.getElementById('filters');- const { wrapped, viewport } = this.state;+ function updateDisplayMode() {+ const container = document.getElementById('filters')+ const children = container && [...container.childNodes] || []// Always wrap on mobile- if (this.props.query.filters.length > 0 && viewport <= 768) {- this.setState({ wrapped: 2 })- return;+ if (query.filters.length > 0 && viewport <= 768) {+ setWrapped(WRAPSTATE.wrapped)+ return}- this.setState({ wrapped: 0 });-- // Don't rewrap if we're already properly wrapped, there are no DOM children, or there is only filter- if (wrapped !== 1 || !items || this.props.query.filters.length === 1) {- return;- };-- let prevItem = null;+ setWrapped(WRAPSTATE.unwrapped)- // For every filter DOM Node, check if its y value is higher than the previous (this indicates a wrap)- [...(items.childNodes)].forEach(item => {- const currItem = item.getBoundingClientRect();- if (prevItem && prevItem.top < currItem.top) {- this.setState({ wrapped: 2 });+ // Check for different y value between all child nodes - this indicates a wrap+ children.forEach(child => {+ const currentChildY = child.getBoundingClientRect().top+ const firstChildY = children[0].getBoundingClientRect().top+ if (currentChildY !== firstChildY) {+ setWrapped(WRAPSTATE.wrapped)}- prevItem = currItem;- });- };+ })+ }- renderListFilter(filterIndex, filter, history, query) {+ function renderListFilter(filterIndex, filter) {const text = filterText(query, filter)const [_operation, filterKey, _clauses] = filterconst type = filterKey.startsWith(EVENT_PROPS_PREFIX) ? 'props' : filterKey@@ -216,7 +190,7 @@ class Filters extends React.Component {title={`Edit filter: ${formattedFilters[type]}`}className="flex w-full h-full items-center py-2 pl-3"to={{- pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${FILTER_GROUP_TO_MODAL_TYPE[type]}`,+ pathname: `/${encodeURIComponent(site.domain)}/filter/${FILTER_GROUP_TO_MODAL_TYPE[type]}`,search: window.location.search}}>@@ -233,9 +207,9 @@ class Filters extends React.Component {)}- renderDropdownButton() {- if (this.state.wrapped === 2) {- const filterCount = this.props.query.filters.length+ function renderDropdownButton() {+ if (wrapped === WRAPSTATE.wrapped) {+ const filterCount = query.filters.lengthreturn (<><AdjustmentsVerticalIcon className="-ml-1 mr-1 h-4 w-4" aria-hidden="true" />@@ -253,20 +227,18 @@ class Filters extends React.Component {)}- trackFilterMenu() {+ function trackFilterMenu() {window.plausible && window.plausible('Filter Menu: Open', {u: `${window.location.protocol}//${window.location.hostname}/:dashboard`})}- renderDropDown() {- const { history, query, site } = this.props;-+ function renderDropDown() {return (<Menu as="div" className="md:relative ml-auto">{({ open }) => (<><div>- <Menu.Button onClick={this.trackFilterMenu} className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">- {this.renderDropdownButton()}+ <Menu.Button onClick={trackFilterMenu} className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">+ {renderDropdownButton()}</Menu.Button></div>@@ -288,7 +260,7 @@ class Filters extends React.Component {className="rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5font-medium text-gray-800 dark:text-gray-200">- <DropdownContent history={history} query={query} site={site} wrapped={this.state.wrapped} />+ <DropdownContent history={history} query={query} site={site} wrapped={wrapped} /></div></Menu.Items></Transition>@@ -298,28 +270,27 @@ class Filters extends React.Component {);}- renderFilterList() {- const { history, query } = this.props;-- if (this.state.wrapped !== 2) {+ function renderFilterList() {+ // The filters are rendered even when `wrapped === WRAPSTATE.waiting`.+ // Otherwise, if they don't exist in the DOM, we can't check whether+ // the flex-wrap is actually putting them on multiple lines.+ if (wrapped !== WRAPSTATE.wrapped) {return (<div id="filters" className="flex flex-wrap">- {query.filters.map((filter, index) => this.renderListFilter(index, filter, history, query))}+ {query.filters.map((filter, index) => renderListFilter(index, filter))}</div>- );+ )}return null}- render() {- return (- <>- {this.renderFilterList()}- {this.renderDropDown()}- </>- )- }+ return (+ <>+ {renderFilterList()}+ {renderDropDown()}+ </>+ )}export default withRouter(Filters);diff --git a/assets/js/dashboard/index.js b/assets/js/dashboard/index.jsindex b60d2f0f39..c13c233ece 100644--- a/assets/js/dashboard/index.js+++ b/assets/js/dashboard/index.js@@ -1,56 +1,58 @@-import React from 'react';+import React, { useEffect, useState } from 'react';import { withRouter } from 'react-router-dom'import Historical from './historical'import Realtime from './realtime'import {parseQuery} from './query'import * as api from './api'-import { withComparisonProvider } from './comparison-provider-hoc';export const statsBoxClass = "stats-item relative w-full mt-6 p-4 flex flex-col bg-white dark:bg-gray-825 shadow-xl rounded"-class Dashboard extends React.Component {- constructor(props) {- super(props)- this.updateLastLoadTimestamp = this.updateLastLoadTimestamp.bind(this)- this.updateImportedDataInView = this.updateImportedDataInView.bind(this)- this.state = {- query: parseQuery(props.location.search, this.props.site),- importedDataInView: false,- lastLoadTimestamp: new Date()- }- }-- componentDidMount() {- document.addEventListener('tick', this.updateLastLoadTimestamp)- }-- componentDidUpdate(prevProps) {- if (prevProps.location.search !== this.props.location.search) {- api.cancelAll()- this.setState({query: parseQuery(this.props.location.search, this.props.site)})- this.updateLastLoadTimestamp()- }- }-- updateLastLoadTimestamp() {- this.setState({lastLoadTimestamp: new Date()})- }-- updateImportedDataInView(newBoolean) {- this.setState({importedDataInView: newBoolean})- }+function Dashboard(props) {+ const { location, site, loggedIn, currentUserRole } = props+ const [query, setQuery] = useState(parseQuery(location.search, site))+ const [importedDataInView, setImportedDataInView] = useState(false)+ const [lastLoadTimestamp, setLastLoadTimestamp] = useState(new Date())+ const updateLastLoadTimestamp = () => { setLastLoadTimestamp(new Date()) }- render() {- const { site, loggedIn, currentUserRole } = this.props- const { query, lastLoadTimestamp } = this.state+ useEffect(() => {+ document.addEventListener('tick', updateLastLoadTimestamp)- if (this.state.query.period === 'realtime') {- return <Realtime site={site} loggedIn={loggedIn} currentUserRole={currentUserRole} query={query} lastLoadTimestamp={lastLoadTimestamp}/>- } else {- return <Historical site={site} loggedIn={loggedIn} currentUserRole={currentUserRole} query={query} lastLoadTimestamp={lastLoadTimestamp} importedDataInView={this.state.importedDataInView} updateImportedDataInView={this.updateImportedDataInView}/>+ return () => {+ document.removeEventListener('tick', updateLastLoadTimestamp)}+ }, [])++ useEffect(() => {+ api.cancelAll()+ setQuery(parseQuery(location.search, site))+ updateLastLoadTimestamp()+ }, [location.search])+++ if (query.period === 'realtime') {+ return (+ <Realtime+ site={site}+ loggedIn={loggedIn}+ currentUserRole={currentUserRole}+ query={query}+ lastLoadTimestamp={lastLoadTimestamp}+ />+ )+ } else {+ return (+ <Historical+ site={site}+ loggedIn={loggedIn}+ currentUserRole={currentUserRole}+ query={query}+ lastLoadTimestamp={lastLoadTimestamp}+ importedDataInView={importedDataInView}+ updateImportedDataInView={setImportedDataInView}+ />+ )}}-export default withRouter(withComparisonProvider(Dashboard))+export default withRouter(Dashboard)diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.jsindex 20d0535e13..4a61841e98 100644--- a/assets/js/dashboard/query.js+++ b/assets/js/dashboard/query.js@@ -134,29 +134,28 @@ export function filtersBackwardsCompatibilityRedirect() {}}-class QueryLink extends React.Component {- constructor(props) {- super(props)- this.onClick = this.onClick.bind(this)- }+function QueryLink(props) {+ const {query, history, to, className, children} = props- onClick(e) {+ function onClick(e) {e.preventDefault()- navigateToQuery(this.props.history, this.props.query, this.props.to)- if (this.props.onClick) this.props.onClick(e)+ navigateToQuery(history, query, to)+ if (props.onClick) {+ props.onClick(e)+ }}- render() {- const { to, ...props } = this.props- return (- <Link- {...props}- to={{ pathname: window.location.pathname, search: updatedQuery(to) }}- onClick={this.onClick}- />- )- }+ return (+ <Link+ to={{ pathname: window.location.pathname, search: updatedQuery(to) }}+ className={className}+ onClick={onClick}+ >+ {children}+ </Link>+ )}+const QueryLinkWithRouter = withRouter(QueryLink)export { QueryLinkWithRouter as QueryLink };diff --git a/assets/js/dashboard/realtime.js b/assets/js/dashboard/realtime.jsindex 5ca924f5dc..9eb83e8db5 100644--- a/assets/js/dashboard/realtime.js+++ b/assets/js/dashboard/realtime.js@@ -12,43 +12,42 @@ import Behaviours from './stats/behaviours'import { withPinnedHeader } from './pinned-header-hoc';import { statsBoxClass } from './index';-class Realtime extends React.Component {- render() {- const navClass = this.props.site.embedded ? 'relative' : 'sticky'+function Realtime(props) {+ const {site, query, history, stuck, loggedIn, currentUserRole, lastLoadTimestamp} = props+ const navClass = site.embedded ? 'relative' : 'sticky'- return (- <div className="mb-12">- <div id="stats-container-top"></div>- <div className={`${navClass} top-0 sm:py-3 py-2 z-10 ${this.props.stuck && !this.props.site.embedded ? 'fullwidth-shadow bg-gray-50 dark:bg-gray-850' : ''}`}>- <div className="items-center w-full flex">- <div className="flex items-center w-full">- <SiteSwitcher site={this.props.site} loggedIn={this.props.loggedIn} currentUserRole={this.props.currentUserRole} />- <Filters className="flex" site={this.props.site} query={this.props.query} history={this.props.history} />- </div>- <Datepicker site={this.props.site} query={this.props.query} />+ return (+ <div className="mb-12">+ <div id="stats-container-top"></div>+ <div className={`${navClass} top-0 sm:py-3 py-2 z-10 ${stuck && !site.embedded ? 'fullwidth-shadow bg-gray-50 dark:bg-gray-850' : ''}`}>+ <div className="items-center w-full flex">+ <div className="flex items-center w-full">+ <SiteSwitcher site={site} loggedIn={loggedIn} currentUserRole={currentUserRole} />+ <Filters className="flex" site={site} query={query} history={history} /></div>+ <Datepicker site={site} query={query} /></div>- <VisitorGraph site={this.props.site} query={this.props.query} lastLoadTimestamp={this.props.lastLoadTimestamp} />- <div className="w-full md:flex">- <div className={ statsBoxClass }>- <Sources site={this.props.site} query={this.props.query} />- </div>- <div className={ statsBoxClass }>- <Pages site={this.props.site} query={this.props.query} />- </div>+ </div>+ <VisitorGraph site={site} query={query} lastLoadTimestamp={lastLoadTimestamp} />+ <div className="w-full md:flex">+ <div className={ statsBoxClass }>+ <Sources site={site} query={query} /></div>- <div className="w-full md:flex">- <div className={ statsBoxClass }>- <Locations site={this.props.site} query={this.props.query} />- </div>- <div className={ statsBoxClass }>- <Devices site={this.props.site} query={this.props.query} />- </div>+ <div className={ statsBoxClass }>+ <Pages site={site} query={query} />+ </div>+ </div>+ <div className="w-full md:flex">+ <div className={ statsBoxClass }>+ <Locations site={site} query={query} />+ </div>+ <div className={ statsBoxClass }>+ <Devices site={site} query={query} /></div>- <Behaviours site={this.props.site} query={this.props.query} currentUserRole={this.props.currentUserRole} /></div>- )- }+ <Behaviours site={site} query={query} currentUserRole={currentUserRole} />+ </div>+ )}export default withPinnedHeader(Realtime, '#stats-container-top');diff --git a/assets/js/dashboard/stats/current-visitors.js b/assets/js/dashboard/stats/current-visitors.jsindex d19d396782..036a10fd94 100644--- a/assets/js/dashboard/stats/current-visitors.js+++ b/assets/js/dashboard/stats/current-visitors.js@@ -1,57 +1,52 @@-import React from 'react';+import React, { useCallback, useEffect, useState } from 'react';import { Link } from 'react-router-dom'import * as api from '../api'import * as url from '../util/url'import { Tooltip } from '../util/tooltip';import { SecondsSinceLastLoad } from '../util/seconds-since-last-load';-export default class CurrentVisitors extends React.Component {- constructor(props) {- super(props)- this.state = {currentVisitors: null}- this.updateCount = this.updateCount.bind(this)- }+export default function CurrentVisitors(props) {+ const { site, query, lastLoadTimestamp, tooltipBoundary } = props+ const [currentVisitors, setCurrentVisitors] = useState(null)- componentDidMount() {- this.updateCount()- document.addEventListener('tick', this.updateCount)- }+ const updateCount = useCallback(() => {+ api.get(`/api/stats/${encodeURIComponent(site.domain)}/current-visitors`)+ .then((res) => setCurrentVisitors(res))+ }, [])- componentWillUnmount() {- document.removeEventListener('tick', this.updateCount)- }+ useEffect(() => {+ document.addEventListener('tick', updateCount)- updateCount() {- return api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/current-visitors`)- .then((res) => this.setState({currentVisitors: res}))- }+ return () => {+ document.removeEventListener('tick', updateCount)+ }+ }, [])++ useEffect(() => {+ updateCount()+ }, [query])- tooltipInfo() {+ function tooltipInfo() {return (<div>- <p className="whitespace-nowrap text-small">Last updated <SecondsSinceLastLoad lastLoadTimestamp={this.props.lastLoadTimestamp} />s ago</p>+ <p className="whitespace-nowrap text-small">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp} />s ago</p><p className="whitespace-nowrap font-normal text-xs">Click to view realtime dashboard</p></div>)}- render() {- if (this.props.query.filters.length >= 1) { return null }- const { currentVisitors } = this.state;-- if (currentVisitors !== null) {- return (- <Tooltip info={this.tooltipInfo()} boundary={this.props.tooltipBoundary}>- <Link to={url.setQuery('period', 'realtime')} className="block ml-1 md:ml-2 mr-auto text-xs md:text-sm font-bold text-gray-500 dark:text-gray-300">- <svg className="inline w-2 mr-1 md:mr-2 text-green-500 fill-current" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">- <circle cx="8" cy="8" r="8" />- </svg>- {currentVisitors} <span className="hidden sm:inline-block">current visitor{currentVisitors === 1 ? '' : 's'}</span>- </Link>- </Tooltip>- )- }-+ if (currentVisitors !== null && query.filters.length === 0) {+ return (+ <Tooltip info={tooltipInfo()} boundary={tooltipBoundary}>+ <Link to={url.setQuery('period', 'realtime')} className="block ml-1 md:ml-2 mr-auto text-xs md:text-sm font-bold text-gray-500 dark:text-gray-300">+ <svg className="inline w-2 mr-1 md:mr-2 text-green-500 fill-current" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">+ <circle cx="8" cy="8" r="8" />+ </svg>+ {currentVisitors} <span className="hidden sm:inline-block">current visitor{currentVisitors === 1 ? '' : 's'}</span>+ </Link>+ </Tooltip>+ )+ } else {return null}}