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
Use hooks instead of classes for DatePicker (#2673)
Uku Taht66d3025b72db
diff --git a/assets/js/dashboard/datepicker.js b/assets/js/dashboard/datepicker.jsindex 32a81ed8fe..e869fef474 100644--- a/assets/js/dashboard/datepicker.js+++ b/assets/js/dashboard/datepicker.js@@ -1,4 +1,4 @@-import React, { Fragment } from "react";+import React, { Fragment, useState, useEffect, useCallback, useRef } from "react";import { withRouter } from "react-router-dom";import Flatpickr from "react-flatpickr";import { ChevronDownIcon } from '@heroicons/react/20/solid'@@ -109,31 +109,45 @@ function DatePickerArrows({site, query}) {return null}-class DatePicker extends React.Component {- constructor(props) {- super(props);- this.handleKeydown = this.handleKeydown.bind(this);- this.handleClick = this.handleClick.bind(this);- this.setCustomDate = this.setCustomDate.bind(this);- this.openCalendar = this.openCalendar.bind(this);- this.close = this.close.bind(this);- this.toggle = this.toggle.bind(this);- this.state = { mode: "menu", open: false };- }-- componentDidMount() {- document.addEventListener("keydown", this.handleKeydown);- document.addEventListener("mousedown", this.handleClick, false);- }-- componentWillUnmount() {- document.removeEventListener("keydown", this.handleKeydown);- document.removeEventListener("mousedown", this.handleClick, false);+function DisplayPeriod({query, site}) {+ if (query.period === "day") {+ if (isToday(site, query.date)) {+ return "Today";+ }+ return formatDay(query.date);+ } if (query.period === '7d') {+ return 'Last 7 days'+ } if (query.period === '30d') {+ return 'Last 30 days'+ } if (query.period === 'month') {+ if (isThisMonth(site, query.date)) {+ return 'Month to Date'+ }+ return formatMonthYYYY(query.date)+ } if (query.period === '6mo') {+ return 'Last 6 months'+ } if (query.period === '12mo') {+ return 'Last 12 months'+ } if (query.period === 'year') {+ if (isThisYear(site, query.date)) {+ return 'Year to Date'+ }+ return formatYear(query.date)+ } if (query.period === 'all') {+ return 'All time'+ } if (query.period === 'custom') {+ return `${formatDayShort(query.from)} - ${formatDayShort(query.to)}`}+ return 'Realtime'+}- handleKeydown(e) {- const { query, history } = this.props;+function DatePicker({query, site, history}) {+ const [open, setOpen] = useState(false)+ const [mode, setMode] = useState('menu')+ const dropDownNode = useRef(null)+ const calendar = useRef(null)+ const handleKeydown = useCallback((e) => {if (shouldIgnoreKeypress(e)) return trueconst newSearch = {@@ -143,7 +157,7 @@ class DatePicker extends React.Component {date: false};- const insertionDate = parseUTCDate(this.props.site.statsBegin);+ const insertionDate = parseUTCDate(site.statsBegin);if (e.key === "ArrowLeft") {const prevDate = formatISO(shiftDays(query.date, -1));@@ -161,7 +175,7 @@ class DatePicker extends React.Component {newSearch.date = prevYear;}} else if (e.key === "ArrowRight") {- const now = nowForSite(this.props.site)+ const now = nowForSite(site)const nextDate = formatISO(shiftDays(query.date, 1));const nextMonth = formatISO(shiftMonths(query.date, 1));const nextYear = formatISO(shiftMonths(query.date, 12));@@ -178,33 +192,50 @@ class DatePicker extends React.Component {}}- this.setState({open: false});+ setOpen(false);const keys = ['d', 'e', 'r', 'w', 'm', 'y', 't', 's', 'l', 'a'];- const redirects = [{date: false, period: 'day'}, {date: formatISO(shiftDays(nowForSite(this.props.site), -1)), period: 'day'}, {period: 'realtime'}, {date: false, period: '7d'}, {date: false, period: 'month'}, {date: false, period: 'year'}, {date: false, period: '30d'}, {date: false, period: '6mo'}, {date: false, period: '12mo'}, {date: false, period: 'all'}];+ const redirects = [{date: false, period: 'day'}, {date: formatISO(shiftDays(nowForSite(site), -1)), period: 'day'}, {period: 'realtime'}, {date: false, period: '7d'}, {date: false, period: 'month'}, {date: false, period: 'year'}, {date: false, period: '30d'}, {date: false, period: '6mo'}, {date: false, period: '12mo'}, {date: false, period: 'all'}];if (keys.includes(e.key.toLowerCase())) {navigateToQuery(history, query, {...newSearch, ...(redirects[keys.indexOf(e.key.toLowerCase())])});} else if (e.key.toLowerCase() === 'c') {- this.setState({mode: 'calendar', open: true}, this.openCalendar);+ setOpen(true)+ setMode('calendar')} else if (newSearch.date) {navigateToQuery(history, query, newSearch);}- }+ }, [query])- handleClick(e) {- if (this.dropDownNode && this.dropDownNode.contains(e.target)) return;+ const handleClick = useCallback((e) => {+ if (dropDownNode.current && dropDownNode.current.contains(e.target)) return;- this.setState({ open: false });- }+ setOpen(false)+ })++ useEffect(() => {+ if (mode === 'calendar' && open) {+ openCalendar()+ }+ }, [mode])- setCustomDate(dates) {+ useEffect(() => {+ document.addEventListener("keydown", handleKeydown);+ return () => { document.removeEventListener("keydown", handleKeydown); }+ }, [handleKeydown])++ useEffect(() => {+ document.addEventListener("mousedown", handleClick, false);+ return () => { document.removeEventListener("mousedown", handleClick, false); }+ }, [])++ function setCustomDate(dates) {if (dates.length === 2) {const [from, to] = datesif (formatISO(from) === formatISO(to)) {navigateToQuery(- this.props.history,- this.props.query,+ history,+ query,{period: 'day',date: formatISO(from),@@ -214,8 +245,8 @@ class DatePicker extends React.Component {)} else {navigateToQuery(- this.props.history,- this.props.query,+ history,+ query,{period: 'custom',date: false,@@ -224,59 +255,21 @@ class DatePicker extends React.Component {})}- this.close()- }- }-- timeFrameText() {- const { query, site } = this.props;-- if (query.period === "day") {- if (isToday(site, query.date)) {- return "Today";- }- return formatDay(query.date);- } if (query.period === '7d') {- return 'Last 7 days'- } if (query.period === '30d') {- return 'Last 30 days'- } if (query.period === 'month') {- if (isThisMonth(site, query.date)) {- return 'Month to Date'- }- return formatMonthYYYY(query.date)- } if (query.period === '6mo') {- return 'Last 6 months'- } if (query.period === '12mo') {- return 'Last 12 months'- } if (query.period === 'year') {- if (isThisYear(site, query.date)) {- return 'Year to Date'- }- return formatYear(query.date)- } if (query.period === 'all') {- return 'All time'- } if (query.period === 'custom') {- return `${formatDayShort(query.from)} - ${formatDayShort(query.to)}`+ setOpen(false)}- return 'Realtime'- }-- toggle() {- const newMode = this.state.mode === 'calendar' && !this.state.open ? 'menu' : this.state.mode- this.setState(prevState => ({ mode: newMode, open: !prevState.open }));}- close() {- this.setState({ open: false });+ function toggle() {+ const newMode = mode === 'calendar' && !open ? 'menu' : mode+ setOpen(!open)+ setMode(newMode)}- openCalendar() {- this.calendar && this.calendar.flatpickr.open();+ function openCalendar() {+ calendar.current && calendar.current.flatpickr.open();}- renderLink(period, text, opts = {}) {- const { query, site } = this.props;+ function renderLink(period, text, opts = {}) {let boldClass;if (query.period === "day" && period === "day") {boldClass = isToday(site, query.date) ? "font-bold" : "";@@ -303,8 +296,8 @@ class DatePicker extends React.Component {return (<QueryLinkto={{from: false, to: false, period, ...opts}}- onClick={this.close}- query={this.props.query}+ onClick={() => setOpen(false)}+ query={query}className={`${boldClass } px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900dark:hover:bg-gray-900 dark:hover:text-gray-100 flex items-center justify-between`}>@@ -314,10 +307,8 @@ class DatePicker extends React.Component {);}- renderDropDownContent() {- const { site } = this.props-- if (this.state.mode === "menu") {+ function renderDropDownContent() {+ if (mode === "menu") {return (<divid="datemenu"@@ -328,26 +319,26 @@ class DatePicker extends React.Component {font-medium text-gray-800 dark:text-gray-200 date-options"><div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">- {this.renderLink("day", "Today")}- {this.renderLink("realtime", "Realtime")}+ {renderLink("day", "Today")}+ {renderLink("realtime", "Realtime")}</div><div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">- {this.renderLink("7d", "Last 7 days")}- {this.renderLink("30d", "Last 30 days")}+ {renderLink("7d", "Last 7 days")}+ {renderLink("30d", "Last 30 days")}</div><div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">- { this.renderLink('month', 'Month to Date') }- { this.renderLink('month', 'Last month', {date: lastMonth(site)}) }+ { renderLink('month', 'Month to Date') }+ { renderLink('month', 'Last month', {date: lastMonth(site)}) }</div><div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">- {this.renderLink("year", "Year to Date")}- {this.renderLink("12mo", "Last 12 months")}+ {renderLink("year", "Year to Date")}+ {renderLink("12mo", "Last 12 months")}</div><div className="py-1 date-option-group">- {this.renderLink("all", "All time")}+ {renderLink("all", "All time")}<span- onClick={() => this.setState({mode: 'calendar'}, this.openCalendar)}- onKeyPress={() => this.setState({mode: 'calendar'}, this.openCalendar)}+ onClick={() => setMode('calendar')}+ onKeyPress={() => setMode('calendar')}className="px-4 py-2 text-sm leading-tight hover:bg-gray-100dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100cursor-pointer flex items-center justify-between"@@ -364,8 +355,8 @@ class DatePicker extends React.Component {</div></div>);- } if (this.state.mode === "calendar") {- const insertionDate = new Date(this.props.site.statsBegin);+ } if (mode === "calendar") {+ const insertionDate = new Date(site.statsBegin);const dayBeforeCreation = insertionDate - 86400000;return (<div className="h-0">@@ -378,24 +369,23 @@ class DatePicker extends React.Component {showMonths: 1,static: true,animate: true}}- ref={calendar => this.calendar = calendar}+ ref={calendar}className="invisible"- onChange={this.setCustomDate}+ onChange={setCustomDate}/></div>)}}- renderPicker() {+ function renderPicker() {return (<divclassName="w-20 sm:w-36 md:w-48 md:relative"- ref={(node) => (this.dropDownNode = node)}+ ref={dropDownNode}><div- onClick={this.toggle}- onKeyPress={this.toggle}+ onClick={toggle}className="flex items-center justify-between rounded bg-white dark:bg-gray-800 shadow px-2 md:px-3py-2 leading-tight cursor-pointer text-xs md:text-sm text-gray-800dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900"@@ -406,14 +396,13 @@ class DatePicker extends React.Component {aria-controls="datemenu"><span className="truncate mr-1 md:mr-2">- {this.props.leadingText}- <span className="font-medium">{this.timeFrameText()}</span>+ <span className="font-medium"><DisplayPeriod query={query} site={site} /></span></span><ChevronDownIcon className="hidden sm:inline-block h-4 w-4 md:h-5 md:w-5 text-gray-500" /></div><Transition- show={this.state.open}+ show={open}as={Fragment}enter="transition ease-out duration-100"enterFrom="transform opacity-0 scale-95"@@ -422,20 +411,18 @@ class DatePicker extends React.Component {leaveFrom="transform opacity-100 scale-100"leaveTo="transform opacity-0 scale-95">- {this.renderDropDownContent()}+ {renderDropDownContent()}</Transition></div>);}- render() {- return (- <div className="flex ml-auto pl-2">- <DatePickerArrows site={this.props.site} query={this.props.query} />- {this.renderPicker()}- </div>- )- }+ return (+ <div className="flex ml-auto pl-2">+ <DatePickerArrows site={site} query={query} />+ {renderPicker()}+ </div>+ )}export default withRouter(DatePicker);