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
Reapply Filters component refactor + fix regression (#4213)
RobertJoonasf6360b8241c1
diff --git a/assets/js/dashboard/custom-hooks.js b/assets/js/dashboard/custom-hooks.jsnew file mode 100644index 0000000000..adb955f15c--- /dev/null+++ b/assets/js/dashboard/custom-hooks.js@@ -0,0 +1,15 @@+import { useEffect, useRef } from 'react';++// A custom hook that behaves like `useEffect`, but+// the function does not run on the initial render.+export function useMountedEffect(fn, deps) {+ const mounted = useRef(false)++ useEffect(() => {+ if (mounted.current) {+ fn()+ } else {+ mounted.current = true+ }+ }, deps)+}\ No newline at end of filediff --git a/assets/js/dashboard/filters.js b/assets/js/dashboard/filters.jsindex 4581a91f77..db2a57c364 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)@@ -97,7 +99,7 @@ function filterDropdownOption(site, option) {function DropdownContent({ history, site, query, wrapped }) {const [addingFilter, setAddingFilter] = useState(false);- if (wrapped === 0 || addingFilter) {+ if (wrapped === 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 c13c233ece..ca755c3443 100644--- a/assets/js/dashboard/index.js+++ b/assets/js/dashboard/index.js@@ -1,6 +1,7 @@import React, { useEffect, useState } from 'react';import { withRouter } from 'react-router-dom'+import { useMountedEffect } from './custom-hooks';import Historical from './historical'import Realtime from './realtime'import {parseQuery} from './query'@@ -23,7 +24,7 @@ function Dashboard(props) {}}, [])- useEffect(() => {+ useMountedEffect(() => {api.cancelAll()setQuery(parseQuery(location.search, site))updateLastLoadTimestamp()