diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 63be6723d..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve Plausible Analytics -title: '' -labels: '' -assignees: '' - ---- - -### Precheck - -Please note that this tracker is only for bugs. Do not use the issue tracker for help, support or feature requests. - -[Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact us](https://plausible.io/contact). - -Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new). - -Have an issue with your self-hosted install? You can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support). Thanks! - -## Prerequisites -- [ ] I have searched open and closed issues to make sure that the bug has not yet been reported. - -## Bug report -**Describe the bug** -A clear and concise description of what the bug is. - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots (If applicable)** -If applicable, add screenshots to help explain your problem. - -**Environment (If applicable):** - - OS: [e.g. macos] - - Browser [e.g. safari, firefox] - - Version [e.g. 78] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml new file mode 100644 index 000000000..20aa25101 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yaml @@ -0,0 +1,67 @@ +name: "🐛 Bug Report" +description: Create a report to help us improve Plausible Analytics +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + + Please note that this tracker is only for bugs. Do not use the issue tracker for help, support or feature requests. + + [Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact us](https://plausible.io/contact). + + Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new). + + Have an issue with your self-hosted install? You can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support). + + **Thanks!** + - type: checkboxes + attributes: + label: Past Issues Searched + options: + - label: >- + I have searched open and closed issues to make sure that the bug has + not yet been reported + required: true + - type: checkboxes + attributes: + label: Issue is a Bug Report + options: + - label: >- + This is a bug report and not a feature request, nor asking for self-hosted support + required: true + - type: textarea + id: bug-description + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is + placeholder: Tell us what happened! + validations: + required: true + - type: textarea + id: bug-expectation + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen + placeholder: Tell us what you expected + validations: + required: true + - type: textarea + id: bug-screenshots + attributes: + label: Screenshots + description: 'If applicable, add screenshots to help explain your problem' + placeholder: Insert screenshots here + - type: textarea + attributes: + label: Environment + description: | + examples: + - **OS**: MacOS + - **Browser**: Firefox + - **Browser Version**: 88 + value: | + - OS: + - Browser: + - Browser Version: + render: markdown diff --git a/.gitlab/build-scripts/docker-entrypoint.sh b/.gitlab/build-scripts/docker-entrypoint.sh index 0ab3e8ff2..b693040f9 100755 --- a/.gitlab/build-scripts/docker-entrypoint.sh +++ b/.gitlab/build-scripts/docker-entrypoint.sh @@ -1,10 +1,10 @@ #!/bin/sh set -e -if [[ "$1" = 'run' ]]; then +if [ "$1" = 'run' ]; then exec /app/bin/plausible start -elif [[ "$1" = 'db' ]]; then +elif [ "$1" = 'db' ]; then exec /app/"$2".sh else exec "$@" diff --git a/.gitlab/build-scripts/docker.gitlab.sh b/.gitlab/build-scripts/docker.gitlab.sh index 4cc663ca0..51395c8b1 100644 --- a/.gitlab/build-scripts/docker.gitlab.sh +++ b/.gitlab/build-scripts/docker.gitlab.sh @@ -23,10 +23,10 @@ function docker_build_image() { /kaniko/executor \ --cache=true \ - --context ${CI_PROJECT_DIR} \ - --dockerfile ${CI_PROJECT_DIR}/Dockerfile \ - --destination ${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-${CI_COMMIT_SHORT_SHA} \ - --destination ${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-latest \ + --context "${CI_PROJECT_DIR}" \ + --dockerfile "${CI_PROJECT_DIR}"/Dockerfile \ + --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-${CI_COMMIT_SHORT_SHA}" \ + --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-latest" \ \ "$@" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 47a5baffc..d894db377 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,3 +26,8 @@ repos: - eslint-plugin-jsx-a11y@6.4.1 - eslint-plugin-react@7.21.5 - eslint-plugin-react-hooks@4.2.0 + + - repo: https://gitlab.com/jvenom/elixir-pre-commit-hooks + rev: v1.0.0 + hooks: + - id: mix-format diff --git a/CHANGELOG.md b/CHANGELOG.md index 297b56373..2eb5dd0f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ All notable changes to this project will be documented in this file. - UI fix for details button overlapping content on mobile plausible/analytics#1114 - UI fix for the main graph on mobile overlapping its tick items on both axis - UI fixes for text not showing properly in bars across multiple lines. This hides the totals on <768px and only shows the uniques and % to accommodate the goals text too. +- Turn off autocomplete for name and password inputs in the _New shared link_ form. ### Removed - Removes AppSignal monitoring package diff --git a/README.md b/README.md index 3063db09f..83bc423bf 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ We are dedicated to making web analytics more privacy-friendly. Our mission is t ### Why Plausible? -Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 3,000+ paying subscribers to deliver their website and business insights: +Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 4,000+ paying subscribers to deliver their website and business insights: - **Clutter Free**: Plausible Analytics provides [simple web analytics](https://plausible.io/simple-web-analytics) and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary. - **GDPR/CCPA/PECR compliant**: Measure traffic, not individuals. No personal data or IP addresses are ever stored in our database. We don't use cookies or any other persistent idenfitiers. [Read more about our data policy](https://plausible.io/data-policy) diff --git a/assets/.eslintrc.json b/assets/.eslintrc.json index 7ee18d54e..e25d18b46 100644 --- a/assets/.eslintrc.json +++ b/assets/.eslintrc.json @@ -5,7 +5,7 @@ "extends": ["airbnb", "prettier"], "plugins": ["prettier"], "rules": { - "max-len": [2, {"code": 100}], + "max-len": [0, {"code": 120}], "prettier/prettier": [2], "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "react/destructuring-assignment": [0], @@ -13,6 +13,9 @@ "max-classes-per-file": [0], "react/jsx-one-expression-per-line": [0], "react/self-closing-comp": [0], - "no-unused-expressions": [1, { "allowShortCircuit": true }] + "no-unused-expressions": [1, { "allowShortCircuit": true }], + "no-unused-vars": [2, { "varsIgnorePattern": "^_", "argsIgnorePattern": "^_" }], + "jsx-a11y/click-events-have-key-events": [0], + "jsx-a11y/no-static-element-interactions": [0] } } diff --git a/assets/css/app.css b/assets/css/app.css index e3e0d7660..e1af8c8d8 100644 --- a/assets/css/app.css +++ b/assets/css/app.css @@ -315,3 +315,16 @@ iframe[hidden] { .pagination-link[disabled] { @apply cursor-default bg-gray-100 dark:bg-gray-300 pointer-events-none; } + +.flatpickr-calendar.static.open { + top: 12px; +} + +@media (max-width: 768px) { + .flatpickr-wrapper { + position: absolute!important; + right: 0!important; + left: 0!important; + } +} + diff --git a/assets/js/dashboard/components/search-select.js b/assets/js/dashboard/components/search-select.js index 24ec5e2b3..766140af8 100644 --- a/assets/js/dashboard/components/search-select.js +++ b/assets/js/dashboard/components/search-select.js @@ -2,6 +2,7 @@ import React, {useState, useCallback} from 'react' import {useCombobox} from 'downshift' import classNames from 'classnames' import debounce from 'debounce-promise' +import { ChevronDownIcon } from '@heroicons/react/solid' function selectInputText(e) { e.target.select() @@ -27,7 +28,6 @@ function Spinner() { export default function SearchSelect(props) { const [items, setItems] = useState([]) const [loading, setLoading] = useState(false) - const [initialLoadComplete, setInitialLoadComplete] = useState(false) function fetchOptions({inputValue, isOpen}) { setLoading(isOpen) @@ -60,11 +60,9 @@ export default function SearchSelect(props) { props.onInput(changes.inputValue) }, initialSelectedItem: props.initialSelectedItem, - onIsOpenChange: ({inputValue}) => { - if (!initialLoadComplete) { - fetchOptions({inputValue: inputValue, isOpen: true}).then(() => { - setInitialLoadComplete(true) - }) + onIsOpenChange: ({isOpen, inputValue}) => { + if (isOpen) { + fetchOptions({inputValue, isOpen}) } } }) @@ -79,11 +77,11 @@ export default function SearchSelect(props) { } return ( -
+
- { !loading && } + { !loading && } { loading && }
diff --git a/assets/js/dashboard/datepicker.js b/assets/js/dashboard/datepicker.js index c5b4a897f..51042f294 100644 --- a/assets/js/dashboard/datepicker.js +++ b/assets/js/dashboard/datepicker.js @@ -1,6 +1,8 @@ -import React from "react"; +import React, { Fragment } from "react"; import { withRouter } from "react-router-dom"; import Flatpickr from "react-flatpickr"; +import { ChevronDownIcon } from '@heroicons/react/solid' +import { Transition } from '@headlessui/react' import { shiftDays, shiftMonths, @@ -17,16 +19,97 @@ import { isBefore, isAfter, } from "./date"; -import Transition from "../transition"; import { navigateToQuery, QueryLink, QueryButton } from "./query"; +function renderArrow(query, site, period, prevDate, nextDate) { + const insertionDate = parseUTCDate(site.insertedAt); + const disabledLeft = isBefore( + parseUTCDate(prevDate), + insertionDate, + period + ); + const disabledRight = isAfter( + parseUTCDate(nextDate), + nowForSite(site), + period + ); + + const leftClasses = `flex items-center px-2 border-r border-gray-300 rounded-l + dark:border-gray-500 dark:text-gray-100 ${ + disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900" + }`; + const rightClasses = `flex items-center px-2 rounded-r dark:text-gray-100 ${ + disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900" + }`; + return ( +
+ + + + + + + + + + +
+ ); +} + +function DatePickerArrows({site, query}) { + if (query.period === "month") { + const prevDate = formatISO(shiftMonths(query.date, -1)); + const nextDate = formatISO(shiftMonths(query.date, 1)); + + return renderArrow(query, site, "month", prevDate, nextDate); + } if (query.period === "day") { + const prevDate = formatISO(shiftDays(query.date, -1)); + const nextDate = formatISO(shiftDays(query.date, 1)); + + return renderArrow(query, site, "day", prevDate, nextDate); + } + + 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.open = this.open.bind(this); + this.close = this.close.bind(this); + this.toggle = this.toggle.bind(this); this.state = { mode: "menu", open: false }; } @@ -44,7 +127,7 @@ class DatePicker extends React.Component { const { query, history } = this.props; if (e.target.tagName === 'INPUT') return true; - if (e.ctrlKey || e.metaKey || e.altKey || e.isComposing || e.keyCode === 229) return; + if (e.ctrlKey || e.metaKey || e.altKey || e.isComposing || e.keyCode === 229) return true; const newSearch = { period: false, @@ -106,8 +189,6 @@ class DatePicker extends React.Component { if (keys.includes(e.key.toLowerCase())) { navigateToQuery(history, query, {...newSearch, ...(redirects[keys.indexOf(e.key.toLowerCase())])}); - } else if (e.key.toLowerCase() === 'f') { - return history.push({pathname: `/${encodeURIComponent(this.props.site.domain)}/filter`, search: window.location.search}) } else if (e.key.toLowerCase() === 'c') { this.setState({mode: 'calendar', open: true}, this.openCalendar); } else if (newSearch.date) { @@ -121,6 +202,36 @@ class DatePicker extends React.Component { this.setState({ open: false }); } + setCustomDate(dates) { + if (dates.length === 2) { + const [from, to] = dates + if (formatISO(from) === formatISO(to)) { + navigateToQuery( + this.props.history, + this.props.query, + { + period: 'day', + date: formatISO(from), + from: false, + to: false, + } + ) + } else { + navigateToQuery( + this.props.history, + this.props.query, + { + period: 'custom', + date: false, + from: formatISO(from), + to: formatISO(to), + } + ) + } + this.close() + } + } + timeFrameText() { const { query, site } = this.props; @@ -148,143 +259,19 @@ class DatePicker extends React.Component { return 'Realtime' } - renderArrow(period, prevDate, nextDate) { - const insertionDate = parseUTCDate(this.props.site.insertedAt); - const disabledLeft = isBefore( - parseUTCDate(prevDate), - insertionDate, - period - ); - const disabledRight = isAfter( - parseUTCDate(nextDate), - nowForSite(this.props.site), - period - ); - - const leftClasses = `flex items-center px-2 border-r border-gray-300 rounded-l - dark:border-gray-500 dark:text-gray-100 ${ - disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-200 dark:hover:bg-gray-900" - }`; - const rightClasses = `flex items-center px-2 rounded-r dark:text-gray-100 ${ - disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-200 dark:hover:bg-gray-900" - }`; - return ( -
- - - - - - - - - - -
- ); - } - - renderArrows() { - const { query } = this.props; - - if (query.period === "month") { - const prevDate = formatISO(shiftMonths(query.date, -1)); - const nextDate = formatISO(shiftMonths(query.date, 1)); - - return this.renderArrow("month", prevDate, nextDate); - } if (query.period === "day") { - const prevDate = formatISO(shiftDays(query.date, -1)); - const nextDate = formatISO(shiftDays(query.date, 1)); - - return this.renderArrow("day", prevDate, nextDate); - } - } - - open() { - this.setState({ mode: "menu", open: true }); - } - - renderDropDown() { - return ( -
(this.dropDownNode = node)} - > - - - - {this.renderDropDownContent()} - -
- ); + 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 }); } + openCalendar() { + this.calendar && this.calendar.flatpickr.open(); + } + renderLink(period, text, opts = {}) { const { query, site } = this.props; let boldClass; @@ -312,9 +299,9 @@ class DatePicker extends React.Component { return ( {text} @@ -328,11 +315,10 @@ class DatePicker extends React.Component { return (
@@ -359,7 +345,7 @@ class DatePicker extends React.Component { this.setState({mode: 'calendar'}, this.openCalendar)} onKeyPress={() => this.setState({mode: 'calendar'}, this.openCalendar)} - className="px-4 py-2 md:text-sm leading-tight hover:bg-gray-100 + className="px-4 py-2 text-sm leading-tight hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer flex items-center justify-between" tabIndex="0" @@ -379,64 +365,73 @@ class DatePicker extends React.Component { const insertionDate = new Date(this.props.site.insertedAt); const dayBeforeCreation = insertionDate - 86400000; return ( - this.calendar = calendar} - className="invisible" - onChange={this.setCustomDate.bind(this)} - /> +
+ this.calendar = calendar} + className="invisible" + onChange={this.setCustomDate} + /> +
) } } - setCustomDate(dates) { - if (dates.length === 2) { - const [from, to] = dates - if (formatISO(from) === formatISO(to)) { - navigateToQuery( - this.props.history, - this.props.query, - { - period: 'day', - date: formatISO(from), - from: false, - to: false, - } - ) - } else { - navigateToQuery( - this.props.history, - this.props.query, - { - period: 'custom', - date: false, - from: formatISO(from), - to: formatISO(to), - } - ) - } - this.close() - } - } + renderPicker() { + return ( +
(this.dropDownNode = node)} + > + - openCalendar() { - this.calendar && this.calendar.flatpickr.open(); + + {this.renderDropDownContent()} + +
+ ); } render() { return ( -
- { this.renderArrows() } - { this.renderDropDown() } +
+ + {this.renderPicker()}
- ); + ) } } diff --git a/assets/js/dashboard/filters.js b/assets/js/dashboard/filters.js index 6189f7dd2..492dbecc1 100644 --- a/assets/js/dashboard/filters.js +++ b/assets/js/dashboard/filters.js @@ -1,29 +1,178 @@ -import React from 'react'; -import { withRouter, Link } from 'react-router-dom' -import { countFilters, formattedFilters, navigateToQuery } from './query' +import React, { Fragment, useState } from 'react'; +import { Link, withRouter } from 'react-router-dom' +import { AdjustmentsIcon, PlusIcon, XIcon, PencilIcon } from '@heroicons/react/solid' +import classNames from 'classnames' import Datamap from 'datamaps' -import Transition from "../transition.js"; +import { Menu, Transition } from '@headlessui/react' + +import { appliedFilters, navigateToQuery, formattedFilters } from './query' +import { FILTER_GROUPS, formatFilterGroup, filterGroupForFilter } from './stats/modals/filter' + +function removeFilter(key, history, query) { + const newOpts = { + [key]: false + } + if (key === 'goal') { newOpts.props = false } + navigateToQuery( + history, + query, + newOpts + ) +} + +function clearAllFilters(history, query) { + const newOpts = Object.keys(query.filters).reduce((acc, red) => ({ ...acc, [red]: false }), {}); + navigateToQuery( + history, + query, + newOpts + ); +} + +function filterText(key, value, query) { + if (key === "goal") { + return <>Completed goal {value} + } + if (key === "props") { + const [metaKey, metaValue] = Object.entries(value)[0] + const eventName = query.filters.goal ? query.filters.goal : 'event' + return <>{eventName}.{metaKey} is {metaValue} + } + if (key === "source") { + return <>Source: {value} + } + if (key === "utm_medium") { + return <>UTM medium: {value} + } + if (key === "utm_source") { + return <>UTM source: {value} + } + if (key === "utm_campaign") { + return <>UTM campaign: {value} + } + if (key === "referrer") { + return <>Referrer: {value} + } + if (key === "screen") { + return <>Screen size: {value} + } + if (key === "browser") { + return <>Browser: {value} + } + if (key === "browser_version") { + const browserName = query.filters.browser ? query.filters.browser : 'Browser' + return <>{browserName}.Version: {value} + } + if (key === "os") { + return <>Operating System: {value} + } + if (key === "os_version") { + const osName = query.filters.os ? query.filters.os : 'OS' + return <>{osName}.Version: {value} + } + if (key === "country") { + const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; + const selectedCountry = allCountries.find((c) => c.id === value) || {properties: {name: value}}; + return <>Country: {selectedCountry.properties.name} + } + if (key === "page") { + return <>Page: {value} + } + if (key === "entry_page") { + return <>Entry Page: {value} + } + if (key === "exit_page") { + return <>Exit Page: {value} + } + + throw new Error(`Unknown filter: ${key}`) +} + +function renderDropdownFilter(site, history, [key, value], query) { + if (key === 'props') { + return ( + +
+ {filterText(key, value, query)} + removeFilter(key, history, query)}> + + +
+
+ ) + } + + return ( + +
+ + {filterText(key, value, query)} + + + removeFilter(key, history, query)}> + + +
+
+ ) +} + +function filterDropdownOption(site, option) { + return ( + + {({ active }) => ( + + {formatFilterGroup(option)} + + )} + + ) +} + +function DropdownContent({history, site, query, wrapped}) { + const [addingFilter, setAddingFilter] = useState(false); + + if (wrapped === 0 || addingFilter) { + return Object.keys(FILTER_GROUPS).map((option) => filterDropdownOption(site, option)) + } + + return ( + <> +
setAddingFilter(true)}> + + Add filter +
+ {appliedFilters(query).map((filter) => renderDropdownFilter(site, history, filter, query))} + +
clearAllFilters(history, query)}> + Clear All Filters +
+
+ + ) +} class Filters extends React.Component { constructor(props) { super(props); this.state = { - dropdownOpen: false, wrapped: 1, // 0=unwrapped, 1=waiting to check, 2=wrapped - viewport: 1080 + viewport: 1080, }; - this.appliedFilters = Object.keys(props.query.filters) - .map((key) => [key, props.query.filters[key]]) - .filter(([key, value]) => !!value); - this.renderDropDown = this.renderDropDown.bind(this); - this.renderDropDownContent = this.renderDropDownContent.bind(this); - this.handleClick = this.handleClick.bind(this); this.handleResize = this.handleResize.bind(this); - this.rewrapFilters = this.rewrapFilters.bind(this); - this.renderFilterList = this.renderFilterList.bind(this); this.handleKeyup = this.handleKeyup.bind(this) } @@ -32,19 +181,16 @@ class Filters extends React.Component { window.addEventListener('resize', this.handleResize, false); document.addEventListener('keyup', this.handleKeyup); - this.rewrapFilters(); this.handleResize(); + this.rewrapFilters(); } componentDidUpdate(prevProps, prevState) { const { query } = this.props; const { viewport, wrapped } = this.state; - this.appliedFilters = Object.keys(query.filters) - .map((key) => [key, query.filters[key]]) - .filter(([key, value]) => !!value) - 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 }); } @@ -60,40 +206,42 @@ class Filters extends React.Component { } handleKeyup(e) { - const { query, history } = this.props + const {query, history} = this.props if (e.ctrlKey || e.metaKey || e.altKey) return if (e.key === 'Escape') { - this.clearAllFilters(history, query) + clearAllFilters(history, query) } } handleResize() { - this.setState({ viewport: window.innerWidth || 639 }); + this.setState({ viewport: window.innerWidth || 639}); } - handleClick(e) { - if (this.dropDownNode && this.dropDownNode.contains(e.target)) return; - - this.setState({ dropdownOpen: false }); - }; - // Checks if the filter container is wrapping items rewrapFilters() { - let currItem, prevItem, items = document.getElementById('filters'); - const { wrapped } = this.state; + const items = document.getElementById('filters'); + const { wrapped, viewport } = this.state; + + // Always wrap on mobile + if (appliedFilters(this.props.query).length > 0 && viewport <= 768) { + this.setState({ wrapped: 2 }) + 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.appliedFilters.length === 1) { + if (wrapped !== 1 || !items || appliedFilters(this.props.query).length === 1) { return; }; + let prevItem = null; + // For every filter DOM Node, check if its y value is higher than the previous (this indicates a wrap) [...(items.childNodes)].forEach(item => { - currItem = item.getBoundingClientRect(); + const currItem = item.getBoundingClientRect(); if (prevItem && prevItem.top < currItem.top) { this.setState({ wrapped: 2 }); } @@ -101,206 +249,108 @@ class Filters extends React.Component { }); }; - filterText(key, value, query) { - const negated = value[0] == '!' && ['page', 'entry_page', 'exit_page'].includes(key) - value = negated ? value.slice(1) : value - - if (key === "goal") { - return Completed goal {value} - } - if (key === "props") { - const [metaKey, metaValue] = Object.entries(value)[0] - const eventName = query.filters["goal"] ? query.filters["goal"] : 'event' - return {eventName}.{metaKey} is {metaValue} - } - if (key === "source") { - return Source is {value} - } - if (key === "utm_medium") { - return UTM medium is {value} - } - if (key === "utm_source") { - return UTM source is {value} - } - if (key === "utm_campaign") { - return UTM campaign is {value} - } - if (key === "referrer") { - return Referrer URL is {value} - } - if (key === "screen") { - return Screen size is {value} - } - if (key === "browser") { - return Browser is {value} - } - if (key === "browser_version") { - const browserName = query.filters["browser"] ? query.filters["browser"] : 'Browser' - return {browserName} Version is {value} - } - if (key === "os") { - return Operating System is {value} - } - if (key === "os_version") { - const osName = query.filters["os"] ? query.filters["os"] : 'OS' - return {osName} Version is {value} - } - if (key === "country") { - const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; - const selectedCountry = allCountries.find((c) => c.id === value) || { properties: { name: value } }; - return Country is {selectedCountry.properties.name} - } - if (key === "page") { - return Page is{negated ? ' not' : ''} {value} - } - if (key === "entry_page") { - return Entry Page is{negated ? ' not' : ''} {value} - } - if (key === "exit_page") { - return Exit Page is{negated ? ' not' : ''} {value} - } - } - - removeFilter(key, history, query) { - const newOpts = { - [key]: false - } - if (key === 'goal') { newOpts.props = false } - navigateToQuery( - history, - query, - newOpts - ) - } - - renderDropdownFilter(history, [key, value], query) { - if ('props' == key) { - return ( -
- {this.filterText(key, value, query)} - this.removeFilter(key, history, query)}>✕ -
- ) - } - - return ( -
- - {this.filterText(key, value, query)} - - - this.removeFilter(key, history, query)}>✕ -
- ) - } - renderListFilter(history, [key, value], query) { return ( - {'props' == key ? ( + {key === 'props' ? ( - {this.filterText(key, value, query)} + {filterText(key, value, query)} ) : ( <> - - {this.filterText(key, value, query)} + + {filterText(key, value, query)} - - - )} - this.removeFilter(key, history, query)}> - + removeFilter(key, history, query)}> + ) } - clearAllFilters(history, query) { - const newOpts = Object.keys(query.filters).reduce((acc, red) => ({ ...acc, [red]: false }), {}); - navigateToQuery( - history, - query, - newOpts - ); - } - - renderDropDownContent() { - const { viewport } = this.state; - const { history, query, site } = this.props; + renderDropdownButton() { + if (this.state.wrapped === 2) { + const filterCount = appliedFilters(this.props.query).length + return ( + <> +
) } + + return null } render() { @@ -29,12 +31,12 @@ class Historical extends React.Component { return (
-
-
-
+
+
+
- +
diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.js index b5c30d25c..2a77b084e 100644 --- a/assets/js/dashboard/query.js +++ b/assets/js/dashboard/query.js @@ -44,13 +44,10 @@ export function parseQuery(querystring, site) { } } -export function countFilters(query) { - let count = 0; - for (const filter of Object.values(query.filters)) { - if (filter) count++; - } - - return count; +export function appliedFilters(query) { + return Object.keys(query.filters) + .map((key) => [key, query.filters[key]]) + .filter(([key, value]) => !!value); } function generateQueryString(data) { diff --git a/assets/js/dashboard/realtime.js b/assets/js/dashboard/realtime.js index 33ce0dbad..9b021bfe4 100644 --- a/assets/js/dashboard/realtime.js +++ b/assets/js/dashboard/realtime.js @@ -3,10 +3,9 @@ import React from 'react'; import Datepicker from './datepicker' import SiteSwitcher from './site-switcher' import Filters from './filters' -import CurrentVisitors from './stats/current-visitors' import VisitorGraph from './stats/visitor-graph' import Sources from './stats/sources' -import Pages from './stats/pages/' +import Pages from './stats/pages' import Countries from './stats/countries' import Devices from './stats/devices' import Conversions from './stats/conversions' @@ -21,6 +20,8 @@ class Realtime extends React.Component {
) } + + return null } render() { @@ -29,11 +30,11 @@ class Realtime extends React.Component { return (
-
-
-
- - +
+
+
+ +
diff --git a/assets/js/dashboard/router.js b/assets/js/dashboard/router.js index 65acf670c..d04ec388a 100644 --- a/assets/js/dashboard/router.js +++ b/assets/js/dashboard/router.js @@ -51,7 +51,7 @@ export default function Router({site, loggedIn, currentUserRole}) { - + diff --git a/assets/js/dashboard/site-switcher.js b/assets/js/dashboard/site-switcher.js index 33beb26a5..130d8da5b 100644 --- a/assets/js/dashboard/site-switcher.js +++ b/assets/js/dashboard/site-switcher.js @@ -1,5 +1,5 @@ import React from 'react'; -import Transition from "../transition.js"; +import { Transition } from '@headlessui/react' export default class SiteSwitcher extends React.Component { constructor() { @@ -126,7 +126,7 @@ export default class SiteSwitcher extends React.Component { renderArrow() { if (this.props.loggedIn) { return ( - + ) @@ -137,10 +137,10 @@ export default class SiteSwitcher extends React.Component { const hoverClass = this.props.loggedIn ? 'hover:text-gray-500 dark:hover:text-gray-200 focus:border-blue-300 focus:ring ' : 'cursor-default' return ( -
- diff --git a/assets/js/dashboard/stats/current-visitors.js b/assets/js/dashboard/stats/current-visitors.js index cd71f998a..5cc497976 100644 --- a/assets/js/dashboard/stats/current-visitors.js +++ b/assets/js/dashboard/stats/current-visitors.js @@ -1,7 +1,7 @@ import React from 'react'; -import * as api from '../api' import { Link } from 'react-router-dom' -import { countFilters } from '../query'; +import * as api from '../api' +import { appliedFilters } from '../query'; export default class CurrentVisitors extends React.Component { constructor(props) { @@ -20,7 +20,7 @@ export default class CurrentVisitors extends React.Component { } render() { - if (countFilters(this.props.query) !== 0) { return null } + if (appliedFilters(this.props.query).length >= 1) { return null } const query = new URLSearchParams(window.location.search) query.set('period', 'realtime') @@ -28,15 +28,15 @@ export default class CurrentVisitors extends React.Component { const { currentVisitors } = this.state; if (currentVisitors !== null) { return ( - - - + + + - {currentVisitors} current visitor{currentVisitors === 1 ? '' : 's'} + {currentVisitors} current visitor{currentVisitors === 1 ? '' : 's'} ) - } else { - return null } + + return null } } diff --git a/assets/js/dashboard/stats/modals/filter.js b/assets/js/dashboard/stats/modals/filter.js index e082598c3..8ec0b1d23 100644 --- a/assets/js/dashboard/stats/modals/filter.js +++ b/assets/js/dashboard/stats/modals/filter.js @@ -1,65 +1,84 @@ -import React from "react"; -import { withRouter, Redirect } from 'react-router-dom' - +import React, { Fragment } from "react"; +import { withRouter } from 'react-router-dom' +import classNames from 'classnames' import Datamap from 'datamaps' +import { Menu, Transition } from '@headlessui/react' +import { ChevronDownIcon } from '@heroicons/react/solid' + import SearchSelect from '../../components/search-select' import Modal from './modal' -import { parseQuery, formattedFilters, navigateToQuery } from '../../query' -import Transition from "../../../transition"; +import { parseQuery, formattedFilters } from '../../query' import * as api from '../../api' +import {apiPath, sitePath} from '../../url' + +export const FILTER_GROUPS = { + 'page': ['page'], + 'source': ['source', 'referrer'], + 'country': ['country'], + 'screen': ['screen'], + 'browser': ['browser', 'browser_version'], + 'os': ['os', 'os_version'], + 'utm': ['utm_medium', 'utm_source', 'utm_campaign'], + 'entry_page': ['entry_page'], + 'exit_page': ['exit_page'], + 'goal': ['goal'] +} -function getFilterValue(selectedFilter, query) { - const negated = !!query.filters[selectedFilter] && query.filters[selectedFilter][0] === '!' - let filterValue = negated ? query.filters[selectedFilter].slice(1) : (query.filters[selectedFilter] || "") - - if (selectedFilter == 'country') { - const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; - const selectedCountry = allCountries.find((c) => c.id === filterValue) || { properties: { name: filterValue } }; - filterValue = selectedCountry.properties.name - } +function getCountryName(ISOCode) { + const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; + const selectedCountry = allCountries.find((c) => c.id === ISOCode); + return selectedCountry && selectedCountry.properties.name +} - return {filterValue, negated} +function getFormState(filterGroup, query) { + return FILTER_GROUPS[filterGroup].reduce((result, filter) => { + let filterValue = query.filters[filter] || '' + const type = filterValue[0] === '!' ? 'is_not' : 'is' + if (filter === 'country') filterValue = getCountryName(filterValue) + return Object.assign(result, {[filter]: {value: filterValue, type}}) + }, {}) } function withIndefiniteArticle(word) { if (word.startsWith('UTM')) { - return 'a ' + word - } else if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) { - return 'an ' + word - } else { - return 'a ' + word + return `a ${ word}` + } if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) { + return `an ${ word}` } + return `a ${ word}` + } -const SECONDARY_FILTERS = { - 'browser': 'browser_version', - 'os': 'os_version', - 'source': 'referrer', +export function formatFilterGroup(filterGroup) { + if (filterGroup === 'utm') { + return 'UTM tags' + } + return formattedFilters[filterGroup] + } -const SECONDARY_TO_PRIMARY = Object.keys(SECONDARY_FILTERS) - .reduce((res, key) => Object.assign(res, {[SECONDARY_FILTERS[key]]: key}), {}); +export function filterGroupForFilter(filter) { + const map = Object.entries(FILTER_GROUPS).reduce((filterToGroupMap, [group, filtersInGroup]) => { + const filtersToAdd = {} + filtersInGroup.forEach((filterInGroup) => { + filtersToAdd[filterInGroup] = group + }) + + return { ...filterToGroupMap, ...filtersToAdd} + }, {}) -function getVersionFilter(forFilter) { - return SECONDARY_FILTERS[forFilter] + + return map[filter] || filter } class FilterModal extends React.Component { constructor(props) { super(props) const query = parseQuery(props.location.search, props.site) - let selectedFilter = this.props.match.params.field || 'page' - let secondaryFilter; - - if (Object.values(SECONDARY_FILTERS).includes(selectedFilter)) { - selectedFilter = SECONDARY_TO_PRIMARY[selectedFilter] - } - secondaryFilter = SECONDARY_FILTERS[selectedFilter] + const selectedFilterGroup = this.props.match.params.field || 'page' + const formState = getFormState(selectedFilterGroup, query) - this.state = Object.assign({selectedFilter, query}, getFilterValue(selectedFilter, query), {secondaryFilterValue: query.filters[secondaryFilter] || ''}) - - this.handleKeydown = this.handleKeydown.bind(this) - this.handleSubmit = this.handleSubmit.bind(this) + this.state = {selectedFilterGroup, query, formState} } componentDidMount() { @@ -71,176 +90,200 @@ class FilterModal extends React.Component { } handleKeydown(e) { - if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) return + if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) { + return + } - if (e.target.tagName == 'BODY' && e.key == 'Enter') { + if (e.target.tagName === 'BODY' && e.key === 'Enter') { this.handleSubmit() } } - negationSupported(filter) { - return ['page', 'entry_page', 'exit_page'].includes(filter) - } + handleSubmit() { + const { formState } = this.state; - fetchOptions(input) { - const {query, selectedFilter} = this.state - const updatedQuery = { ...query, filters: { ...query.filters, [selectedFilter]: null } } + const filters = Object.entries(formState).reduce((res, [filterKey, {type, value}]) => { + let finalFilterValue = (type === 'is_not' ? '!' : '') + value.trim() - if (selectedFilter === 'country') { - const matchedCountries = Datamap.prototype.worldTopo.objects.world.geometries.filter(c => c.properties.name.toLowerCase().includes(input.trim().toLowerCase())) - const matches = matchedCountries.map(c => c.id) + if (filterKey === 'country') { + const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; + const selectedCountry = allCountries.find((c) => c.properties.name === finalFilterValue) || { id: finalFilterValue }; + finalFilterValue = selectedCountry.id + } - return api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/country`, updatedQuery, { q: matches }) - .then((res) => { - return res.map(code => matchedCountries.filter(c => c.id == code)[0].properties.name) - }) - } else { - return api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/${selectedFilter}`, updatedQuery, { q: input.trim() }) - } - } + res.push({filter: filterKey, value: finalFilterValue}) + return res + }, []) - onInput(val) { - this.setState({filterValue: val}) + this.selectFiltersAndCloseModal(filters) } - renderSearchSelector() { - const {selectedFilter, filterValue} = this.state - - return ( - - ) + onInput(filterName) { + return (val) => { + this.setState(prevState => ({formState: Object.assign(prevState.formState, { + [filterName]: Object.assign(prevState.formState[filterName], {value: val}) + })})) + } } - fetchSecondaryOptions(filterName) { - const {query, selectedFilter} = this.state + setFilterType(filterName, newType) { + this.setState(prevState => ({formState: Object.assign(prevState.formState, { + [filterName]: Object.assign(prevState.formState[filterName], {type: newType}) + })})) + } + fetchOptions(filter) { return (input) => { - const {filterValue} = this.state - const updatedQuery = { ...query, filters: { ...query.filters, [selectedFilter]: filterValue, [filterName]: null } } + const {query, formState} = this.state + const formFilters = Object.fromEntries( + Object.entries(formState).map(([k, v]) => [k, v.value]) + ) + const updatedQuery = {...query, filters: { ...query.filters, ...formFilters, [filter]: null }} + + if (filter === 'country') { + const matchedCountries = Datamap.prototype.worldTopo.objects.world.geometries.filter(c => c.properties.name.toLowerCase().includes(input.trim().toLowerCase())) + const matches = matchedCountries.map(c => c.id) + + return api.get(apiPath(this.props.site, '/suggestions/country'), updatedQuery, { q: matches }) + .then((res) => res.map(code => matchedCountries.filter(c => c.id === code)[0].properties.name)) + } + return api.get(apiPath(this.props.site, `/suggestions/${filter}`), updatedQuery, { q: input.trim() }) - return api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/${filterName}`, updatedQuery, { q: input.trim() }) } } - onSecondaryInput(val) { - this.setState({secondaryFilterValue: val}) + selectedFilterType(filter) { + return this.state.formState[filter].type } - renderVersionSelector() { - const {selectedFilter, filterValue, secondaryFilterValue} = this.state - const secondaryFilter = SECONDARY_FILTERS[selectedFilter] - - if (secondaryFilter) { - return ( - - ) - } + isDisabled() { + return Object.entries(this.state.formState).every(([_key, {value: val}]) => !val) } selectFiltersAndCloseModal(filters) { const queryString = new URLSearchParams(window.location.search) - for (const entry of filters) { + filters.forEach((entry) => { if (entry.value) { queryString.set(entry.filter, entry.value) } else { queryString.delete(entry.filter) } - } + }) - this.props.history.replace({pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: queryString.toString()}) + this.props.history.replace({pathname: sitePath(this.props.site), search: queryString.toString()}) } - handleSubmit() { - const { selectedFilter, negated, filterValue, secondaryFilterValue } = this.state; - - let finalFilterValue = (this.negationSupported(selectedFilter) && negated ? '!' : '') + filterValue.trim() - if (selectedFilter == 'country') { - const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; - const selectedCountry = allCountries.find((c) => c.properties.name === finalFilterValue) || { id: finalFilterValue }; - finalFilterValue = selectedCountry.id - } - - const filters = [{filter: selectedFilter, value: finalFilterValue}] - - const secondaryFilter = SECONDARY_FILTERS[selectedFilter] + renderFilterInputs() { + return FILTER_GROUPS[this.state.selectedFilterGroup].map((filter) => ( +
+
{ formattedFilters[filter] }
+
+ { this.renderFilterTypeSelector(filter) } + + +
+ +
+ )) + } - if (secondaryFilter) { - filters.push({filter: secondaryFilter, value: secondaryFilterValue.trim()}) - } + renderFilterTypeSelector(filterName) { + return ( + + {({ open }) => ( + <> +
+ + { this.selectedFilterType(filterName) } + +
- this.selectFiltersAndCloseModal(filters) + + +
+ + {({ active }) => ( + this.setFilterType(filterName, 'is')} + className={classNames( + active ? 'bg-gray-100 text-gray-900' : 'text-gray-700', + 'cursor-pointer block px-4 py-2 text-sm' + )} + > + is + + )} + + + {({ active }) => ( + this.setFilterType(filterName, 'is_not')} + className={classNames( + active ? 'bg-gray-100 text-gray-900' : 'text-gray-700', + 'cursor-pointer block px-4 py-2 text-sm' + )} + > + is not + + )} + +
+
+
+ + )} +
+ ) } - updateSelectedFilter(e) { - this.setState(Object.assign({selectedFilter: e.target.value}, getFilterValue(e.target.value, this.state.query))) - } renderBody() { - const { selectedFilter, negated, filterValue, secondaryFilterValue, query } = this.state; - const editableFilters = Object.keys(this.state.query.filters).filter(filter => !['props'].concat(Object.values(SECONDARY_FILTERS)).includes(filter)) + const { selectedFilterGroup, query } = this.state; return ( <> -

{query.filters[selectedFilter] || query.filters[SECONDARY_FILTERS[selectedFilter]] ? 'Edit' : 'Add'} Filter

+

Filter by {formatFilterGroup(selectedFilterGroup)}

-
+
-
- - - {this.negationSupported(selectedFilter) && ( -
- -
- )} - - {this.renderSearchSelector()} - {this.renderVersionSelector()} + + {this.renderFilterInputs()}
- {query.filters[selectedFilter] && ( + {query.filters[selectedFilterGroup] && (