Adds manual, editable, auto-suggested filters, and negated&globbed path-based filters (#1121)

* Adds manual-filters + friends

commit 308192044d726e9a6f7406e333048ab3407aa260
Merge: 39287ab a299fab
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri Jun 11 03:40:55 2021 -0500

    Merge branch 'manual-filters' into manual-filters-2

commit a299fab1fb
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri Jun 11 02:20:26 2021 -0500

    Changes to split and pattern matched function for time_on_page

commit 10f10c933a
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri Jun 11 01:53:18 2021 -0500

    Fixes a couple of minor UX issues

commit f2e5ce8eb3
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri Jun 11 01:49:10 2021 -0500

    Fixes time on page for globbed and negated page paths

commit bb18af6526
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu Jun 10 05:24:05 2021 -0500

    Close to finalized version of updated version

    Just needs some additional testing + potentially code cleanup

commit d0b7bfe3da
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri May 28 04:21:21 2021 -0500

    Real Dialyzer Fix

commit 296a76af34
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri May 28 03:44:29 2021 -0500

    Dialyzer fix

commit 91f3b44017
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 17:11:24 2021 -0500

    Changelog

commit e041f75745
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 17:09:52 2021 -0500

    Formatting

commit f689642204
Merge: e00929b 4ff25f6
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 17:08:47 2021 -0500

    Merge branch 'master' into manual-filters

commit e00929b1c5
Merge: 83887c4 806975e
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 17:01:48 2021 -0500

    Merge branch 'manual-filters' of github.com:Vigasaurus/plausible-analytics into manual-filters

commit 83887c49cc
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 16:59:32 2021 -0500

    Adds tests for suggestions, formats goals suggestion query

commit 1cb7732a08
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 16:36:31 2021 -0500

    Adds goals as auto-complete capable filter

commit 4ca39cc406
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 16:08:22 2021 -0500

    95% completed auto-complete setup

    Still needs:
    - tests
    - goals added as filter

commit 22d38c4cd8
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Thu May 27 03:47:19 2021 -0500

    80% of auto-complete filters progress

    Still needs
    - countries and screen into new format
    - re-style dropdown and background
    - drop debounce time
    - tests

commit 806975ede9
Merge: 81c5e05 1a93542
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Tue May 25 15:28:21 2021 -0500

    Merge branch 'master' into manual-filters

commit 81c5e05760
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Tue May 25 15:21:03 2021 -0500

    Makes colorings on top bar elements consistent

commit fa7f6c2268
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Tue May 25 14:58:25 2021 -0500

    Makes requested changes, adds different version of filter button

commit 7dc65b9b7a
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Sat May 22 04:29:01 2021 -0500

    Changelog

commit c684f1c76a
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Sat May 22 04:26:14 2021 -0500

    Various UI Improvements

    - Makes edit buttons full-length & properly sized
    - Adds remove filter button in edit menu

commit a632e7a8ee
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Sat May 22 03:11:50 2021 -0500

    Adds tests for exclusions and wildcards

commit eb91a7942b
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Sat May 22 03:02:23 2021 -0500

    Fixes editing UX on list view

commit 6209d72aee
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri May 21 04:01:17 2021 -0500

    Bugfix in realtime view, formatting

commit 007d44df38
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri May 21 03:23:16 2021 -0500

    Second pass - mostly everything user-facing is done

    Still needs:
    - Tests
    - Potentially negating other filters
    - Potentially some code cleanup

commit cb7b5b9fbd
Author: Vignesh Joglekar <rexvigasaurus@gmail.com>
Date:   Fri May 21 01:49:52 2021 -0500

    First pass on manual filter & path regex/negated filters

    Still needs:
    - Form structure on filter modal
    - Edit filter button
    - Filter dropdown UI improvement
    - Filter modal mount data collection
    - Tests
    - Potentially negating other filters

* Fixes an issue between the updated React version and Flatpickr not showing up

Reverting to v16 was the simplest fix without diving into the issue upstream with Flatpickr

* Resolves comments on UI and code style

Co-authored-by: Uku Taht <Uku.taht@gmail.com>
pull/1169/head
Vignesh Joglekar 6 years ago committed by GitHub
parent 883841f789
commit 30ac901141
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,7 +10,10 @@ All notable changes to this project will be documented in this file.
- To authenticate against a local postgresql via socket authentication, the environment-variables
`DATABASE_SOCKET_DIR` & `DATABASE_NAME` were added.
- Time on Page metric available in detailed Top Pages report plausible/analytics#1007
- Added `CLICKHOUSE_FLUSH_INTERVAL_MS` and `CLICKHOUSE_MAX_BUFFER_SIZE` configuration parameters
- Wildcard based page, entry page and exit page filters plausible/analytics#1067
- Exclusion filters for page, entry page and exit page filters plausible/analytics#1067
- Menu (with auto-complete) to add new and edit existing filters directly plausible/analytics#1089
- Added `CLICKHOUSE_FLUSH_INTERVAL_MS` and `CLICKHOUSE_MAX_BUFFER_SIZE` configuration parameters plausible/analytics#1073
- Ability to invite users to sites with different roles plausible/analytics#1122
### Fixed

@ -38,7 +38,6 @@
.modal__container {
background-color: #fff;
padding: 1rem 2rem;
max-width: 860px;
border-radius: 4px;
margin: 50px auto;
box-sizing: border-box;

@ -0,0 +1,97 @@
.filter-list-text:hover ~ .filter-list-edit {
display: flex;
}
.filter-list-text:hover ~ .filter-list-remove {
display: none;
}
.filter-select__control:focus-within {
box-shadow: rgb(255, 255, 255) 0px 0px 0px 0px, rgb(99, 102, 241) 0px 0px 0px 1px, rgba(0, 0, 0, 0) 0px 0px 0px 0px; /* indigo-500 */
}
.filter-select__value-container {
padding-left: 1rem !important;
}
.filter-select__control {
@apply dark:bg-gray-900 border-gray-300 dark:border-gray-700 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 pr-8;
border-radius: 0.375rem !important;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.35rem 1.35rem;
}
.filter-select__control:hover {
@apply cursor-pointer;
border-color: rgb(156, 163, 175) !important; /* gray-400 */
}
.filter-select__indicator-separator {
@apply hidden;
}
.filter-select__dropdown-indicator {
display: none !important;
}
.filter-select__input {
@apply w-full text-base sm:text-sm;
margin: 0 !important;
}
.filter-select__input input {
width: 100% !important;
box-shadow: none !important;
}
.dark .filter-select__input input {
color: rgb(209, 213, 219) !important; /* gray-300 */
}
.filter-select__value-container > :not(.filter-select__single-value) {
@apply w-full;
padding-top: 0 !important;
}
.filter-select__loading-indicator {
color: rgb(79, 70, 229) !important; /* indigo-600 */
}
.filter-select__loading-indicator > span {
height: 1.5em;
width: 1.5em;
}
.filter-select__single-value {
@apply dark:text-gray-400 text-base sm:text-sm;
}
.filter-select__menu-list {
@apply dark:bg-gray-900;
}
.filter-select__option {
@apply dark:text-gray-300;
font-size: 1rem !important;
line-height: 1.5rem !important;
cursor: pointer !important;
}
@media (min-width: 640px) {
.filter-select__option {
font-size: 0.875rem !important;
line-height: 1.25rem !important;
}
}
.filter-select__option--is-focused {
background-color: rgb(99, 102, 241) !important; /* indigo-500 */
color: white !important;
}
.dark .filter-select__option--is-focused {
background-color: rgb(79, 70, 229) !important; /* indigo-600 */
}

@ -1,4 +1,5 @@
import css from "../css/app.css"
import "../css/app.css"
import "../css/react-select.css"
import "flatpickr/dist/flatpickr.min.css"
import "./polyfills/closest"
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'

@ -161,10 +161,10 @@ class DatePicker extends React.Component {
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-200 dark:bg-gray-900" : ""
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-200 dark:bg-gray-900" : ""
disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-200 dark:hover:bg-gray-900"
}`;
return (
<div className="flex rounded shadow bg-white mr-4 cursor-pointer dark:bg-gray-800">
@ -242,7 +242,7 @@ class DatePicker extends React.Component {
onKeyPress={this.open}
className="flex items-center justify-between rounded bg-white dark:bg-gray-800 shadow px-4
pr-3 py-2 leading-tight cursor-pointer text-sm font-medium text-gray-800
dark:text-gray-200 h-full"
dark:text-gray-200 h-full hover:bg-gray-200 dark:hover:bg-gray-900"
tabIndex="0"
role="button"
aria-haspopup="true"
@ -312,7 +312,7 @@ class DatePicker extends React.Component {
to={{from: false, to: false, period, ...opts}}
onClick={this.close.bind(this)}
query={this.props.query}
className={`${boldClass } px-4 py-2 md:text-sm leading-tight hover:bg-gray-100
className={`${boldClass } px-4 py-2 md:text-sm leading-tight hover:bg-gray-200
dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 flex items-center justify-between`}
>
{text}

@ -1,6 +1,6 @@
import React from 'react';
import { withRouter } from 'react-router-dom'
import { countFilters, navigateToQuery, removeQueryParam } from './query'
import { withRouter, Link } from 'react-router-dom'
import { countFilters, formattedFilters, navigateToQuery, removeQueryParam } from './query'
import Datamap from 'datamaps'
import Transition from "../transition.js";
@ -60,7 +60,7 @@ 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
@ -70,7 +70,7 @@ class Filters extends React.Component {
}
handleResize() {
this.setState({ viewport: window.innerWidth || 639});
this.setState({ viewport: window.innerWidth || 639 });
}
handleClick(e) {
@ -102,6 +102,9 @@ 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 <span className="inline-block max-w-2xs md:max-w-xs truncate">Completed goal <b>{value}</b></span>
}
@ -111,50 +114,50 @@ class Filters extends React.Component {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">{eventName}.{metaKey} is <b>{metaValue}</b></span>
}
if (key === "source") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Source: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Source is <b>{value}</b></span>
}
if (key === "utm_medium") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM medium: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM medium is <b>{value}</b></span>
}
if (key === "utm_source") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM source: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM source is <b>{value}</b></span>
}
if (key === "utm_campaign") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM campaign: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">UTM campaign is <b>{value}</b></span>
}
if (key === "referrer") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Referrer: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Referrer is <b>{value}</b></span>
}
if (key === "screen") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Screen size: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Screen size is <b>{value}</b></span>
}
if (key === "browser") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Browser: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Browser is <b>{value}</b></span>
}
if (key === "browser_version") {
const browserName = query.filters["browser"] ? query.filters["browser"] : 'Browser'
return <span className="inline-block max-w-2xs md:max-w-xs truncate">{browserName}.Version: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">{browserName} Version is <b>{value}</b></span>
}
if (key === "os") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Operating System: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Operating System is <b>{value}</b></span>
}
if (key === "os_version") {
const osName = query.filters["os"] ? query.filters["os"] : 'OS'
return <span className="inline-block max-w-2xs md:max-w-xs truncate">{osName}.Version: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">{osName} Version is <b>{value}</b></span>
}
if (key === "country") {
const allCountries = Datamap.prototype.worldTopo.objects.world.geometries;
const selectedCountry = allCountries.find((c) => c.id === value) || {properties: {name: value}};
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Country: <b>{selectedCountry.properties.name}</b></span>
const selectedCountry = allCountries.find((c) => c.id === value) || { properties: { name: value } };
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Country is <b>{selectedCountry.properties.name}</b></span>
}
if (key === "page") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Page: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Page is{negated ? ' not' : ''} <b>{value}</b></span>
}
if (key === "entry_page") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Entry Page: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Entry Page is{negated ? ' not' : ''} <b>{value}</b></span>
}
if (key === "exit_page") {
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Exit Page: <b>{value}</b></span>
return <span className="inline-block max-w-2xs md:max-w-xs truncate">Exit Page is{negated ? ' not' : ''} <b>{value}</b></span>
}
}
@ -171,18 +174,50 @@ class Filters extends React.Component {
}
renderDropdownFilter(history, [key, value], query) {
if ('props' == key) {
return (
<div className="px-4 sm:py-2 py-3 md:text-sm leading-tight flex items-center justify-between" key={key + value}>
{this.filterText(key, value, query)}
<b title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => this.removeFilter(key, history, query)}>✕</b>
</div>
)
}
return (
<div className="px-4 sm:py-2 py-3 md:text-sm leading-tight flex items-center justify-between" key={key + value}>
{this.filterText(key, value, query)}
<b className="ml-1 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => this.removeFilter(key, history, query)}>✕</b>
<div className="px-3 md:px-4 sm:py-2 py-3 md:text-sm leading-tight flex items-center justify-between" key={key + value}>
<Link
title={`Edit filter: ${formattedFilters[key]}`}
to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${key}`, search: window.location.search }}
className="group flex w-full justify-between items-center"
>
{this.filterText(key, value, query)}
<svg className="ml-1 cursor-pointer group-hover:text-indigo-700 dark:group-hover:text-indigo-500 w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
</Link>
<b title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => this.removeFilter(key, history, query)}>✕</b>
</div>
)
}
renderListFilter(history, [key, value], query) {
return (
<span key={key} title={value} className="inline-flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded py-2 px-3 mr-2">
{this.filterText(key, value, query)} <b className="ml-1 cursor-pointer hover:text-indigo-500" onClick={() => this.removeFilter(key, history, query)}>✕</b>
<span key={key} title={value} className="flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded mr-2 items-center">
{'props' == key ? (
<span className="flex w-full h-full items-center py-2 pl-3">
{this.filterText(key, value, query)}
</span>
) : (
<>
<Link title={`Edit filter: ${formattedFilters[key]}`} className="filter-list-text flex w-full h-full items-center py-2 pl-3" to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${key}`, search: window.location.search }}>
{this.filterText(key, value, query)}
</Link>
<span className="filter-list-edit hidden h-full w-full px-2 cursor-pointer text-indigo-700 dark:text-indigo-500 items-center">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="1 1 23 23" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
</span>
</>
)}
<span title={`Remove filter: ${formattedFilters[key]}`} className="filter-list-remove flex h-full w-full px-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 items-center" onClick={() => this.removeFilter(key, history, query)}>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</span>
</span>
)
}
@ -198,11 +233,15 @@ class Filters extends React.Component {
renderDropDownContent() {
const { viewport } = this.state;
const { history, query } = this.props;
const { history, query, site } = this.props;
return (
<div className="absolute mt-2 rounded shadow-md z-10" style={{ width: viewport <= 768 ? '320px' : '350px', right: '-5px' }} ref={node => this.dropDownNode = node}>
<div className="rounded bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 font-medium text-gray-800 dark:text-gray-200 flex flex-col">
<Link to={`/${encodeURIComponent(site.domain)}/filter${window.location.search}`} className="group border-b flex border-gray-200 dark:border-gray-500 px-4 sm:py-2 py-3 md:text-sm leading-tight hover:text-indigo-700 dark:hover:text-indigo-500 hover:cursor-pointer">
<svg className="mr-2 h-4 w-4 text-gray-500 dark:text-gray-200 group-hover:text-indigo-700 dark:group-hover:text-indigo-500 hover:cursor-pointer" fill="none" stroke="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
Add Filter
</Link>
{this.appliedFilters.map((filter) => this.renderDropdownFilter(history, filter, query))}
<div className="border-t border-gray-200 dark:border-gray-500 px-4 sm:py-2 py-3 md:text-sm leading-tight hover:text-indigo-700 dark:hover:text-indigo-500 hover:cursor-pointer" onClick={() => this.clearAllFilters(history, query)}>
Clear All Filters
@ -239,11 +278,16 @@ class Filters extends React.Component {
}
renderFilterList() {
const { history, query } = this.props;
const { history, query, site } = this.props;
const { viewport } = this.state;
return (
<div id="filters">
<div id="filters" className="flex flex-grow pl-2 flex-wrap">
{(this.appliedFilters.map((filter) => this.renderListFilter(history, filter, query)))}
<Link to={`/${encodeURIComponent(site.domain)}/filter${window.location.search}`} className={`button ${viewport <= 768 ? "px-2 mr-1" : "px-3 mr-2"} py-2 cursor-pointer ml-auto text-gray-800 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-900 shadow`}>
<svg className={`${viewport <= 768 ? "mr-1" : "mr-2"} h-4 w-4 text-indigo-500`} fill="none" stroke="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
{viewport <= 768 ? "Filter" : "Add Filter"}
</Link>
</div>
);
}
@ -251,15 +295,11 @@ class Filters extends React.Component {
render() {
const { wrapped, viewport } = this.state;
if (this.appliedFilters.length > 0) {
if (wrapped === 2 || viewport <= 768) {
return this.renderDropDown();
}
return this.renderFilterList();
if (this.appliedFilters.length > 0 && (wrapped === 2 || viewport <= 768)) {
return this.renderDropDown();
}
return null;
return this.renderFilterList();
}
}

@ -34,7 +34,7 @@ class Historical extends React.Component {
<div className="flex items-center w-full mb-2 sm:mb-0">
<SiteSwitcher site={this.props.site} loggedIn={this.props.loggedIn} currentUserRole={this.props.currentUserRole} />
<CurrentVisitors timer={this.props.timer} site={this.props.site} query={this.props.query} />
<Filters query={this.props.query} history={this.props.history} />
<Filters site={this.props.site} query={this.props.query} history={this.props.history} />
</div>
<Datepicker site={this.props.site} query={this.props.query} />
</div>

@ -159,3 +159,22 @@ export function eventName(query) {
}
return 'pageviews'
}
export const formattedFilters = {
'goal': 'Goal',
'props': 'Goal properties',
'source': 'Source',
'utm_medium': 'UTM Medium',
'utm_source': 'UTM Source',
'utm_campaign': 'UTM Campaign',
'referrer': 'Referrer URL',
'screen': 'Screen size',
'browser': 'Browser',
'browser_version': 'Browser Version',
'os': 'Operating System',
'os_version': 'Operating System Version',
'country': 'Country',
'page': 'Page',
'entry_page': 'Entry Page',
'exit_page': 'Exit Page'
}

@ -33,7 +33,7 @@ class Realtime extends React.Component {
<div className="items-center justify-between w-full sm:flex">
<div className="flex items-center w-full mb-2 sm:mb-0">
<SiteSwitcher site={this.props.site} loggedIn={this.props.loggedIn} />
<Filters query={this.props.query} history={this.props.history} />
<Filters site={this.props.site} query={this.props.query} history={this.props.history} />
</div>
<Datepicker site={this.props.site} query={this.props.query} />
</div>

@ -7,6 +7,7 @@ import PagesModal from './stats/modals/pages'
import EntryPagesModal from './stats/modals/entry-pages'
import ExitPagesModal from './stats/modals/exit-pages'
import CountriesModal from './stats/modals/countries'
import FilterModal from './stats/modals/filter'
import {BrowserRouter, Switch, Route, useLocation} from "react-router-dom";
@ -50,6 +51,9 @@ export default function Router({site, loggedIn, currentUserRole}) {
<Route path="/:domain/countries">
<CountriesModal site={site} />
</Route>
<Route path={["/:domain/filter/:field", "/:domain/filter"]}>
<FilterModal site={site} />
</Route>
</Switch>
</Route>
</BrowserRouter>

@ -0,0 +1,234 @@
import React from "react";
import { withRouter, Redirect } from 'react-router-dom'
import Datamap from 'datamaps'
import AsyncSelect from 'react-select/async'
import debounce from 'lodash.debounce'
import Modal from './modal'
import { parseQuery, formattedFilters, navigateToQuery } from '../../query'
import Transition from "../../../transition";
import * as api from '../../api'
class FilterModal extends React.Component {
constructor(props) {
super(props)
this.state = {
query: parseQuery(props.location.search, props.site),
selectedFilter: "",
negated: false,
updatedValue: "",
inputValue: "",
forceReloadSuggestions: 0,
defaultOptions: []
}
this.editableGoals = Object.keys(this.state.query.filters).filter(filter => !['props'].includes(filter))
this.renderSelector = this.renderSelector.bind(this)
this.fetchSuggestions = this.fetchSuggestions.bind(this)
this.handleKeydown = this.handleKeydown.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.fieldSelectRef = React.createRef()
this.debouncedFetchSuggestions = debounce((q, callback) => this.fetchSuggestions(q, callback), 150)
}
componentDidMount() {
this.setState({ selectedFilter: this.props.match.params.field })
this.fieldSelectRef.current.focus()
document.addEventListener("keydown", this.handleKeydown)
}
componentDidUpdate(prevProps, prevState) {
const { query, selectedFilter, updatedValue, forceReloadSuggestions } = this.state
if (prevState.selectedFilter !== selectedFilter) {
const negated = !!query.filters[selectedFilter] && query.filters[selectedFilter][0] == '!' && this.negationSupported(selectedFilter)
let updatedValue = 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 === updatedValue) || { properties: { name: updatedValue } };
updatedValue = selectedCountry.properties.name
}
if (selectedFilter) this.fetchSuggestions('', (defaultOptions) => this.setState({ defaultOptions }))
this.setState({ updatedValue, inputValue: updatedValue, negated, forceReloadSuggestions: forceReloadSuggestions + 1 })
}
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeydown);
}
handleKeydown(e) {
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) return
if (e.target.tagName == 'BODY' && e.key == 'Enter') {
this.handleSubmit()
}
}
negationSupported(filter) {
return ['page', 'entry_page', 'exit_page'].includes(filter)
}
fetchSuggestions(searchQuery = "", callback) {
const { query, selectedFilter } = this.state
const updatedQuery = { ...query, filters: { ...query.filters, [selectedFilter]: null } }
if (selectedFilter == 'country') {
const matchedCountries = Datamap.prototype.worldTopo.objects.world.geometries.filter(c => c.properties.name.includes(searchQuery.trim()))
const matches = matchedCountries.map(c => c.id)
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/country`, updatedQuery, { q: matches })
.then((res) => {
const result = res.map(code => matchedCountries.filter(c => c.id == code)[0].properties.name).map(r => ({ label: r, value: r }))
callback(result)
})
} else {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/suggestions/${selectedFilter}`, updatedQuery, { q: searchQuery.trim() })
.then((res) => {
const result = res.map(r => ({ label: r, value: r }))
callback(result)
})
}
}
renderSelector(filter) {
const { updatedValue, selectedFilter, inputValue, forceReloadSuggestions, defaultOptions } = this.state;
if (!filter) return null
return (
<AsyncSelect
key={`select-${selectedFilter}-${forceReloadSuggestions}`}
defaultOptions={inputValue == "" ? defaultOptions : true}
cacheOptions
loadOptions={(q, callback) => this.debouncedFetchSuggestions(q, callback)}
placeholder='Filter value'
maxMenuHeight={250}
tabSelectsValue={false}
classNamePrefix='filter-select'
blurInputOnSelect
noOptionsMessage={() => (
<span className="text-red-500 text-md flex mt-2 px-3">
<svg className="w-10 h-10 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
<span className="">No results found in current dashboard, try removing some filters, checking your input and ensuring this {formattedFilters[selectedFilter].toLowerCase()} exists</span>
</span>
)}
loadingMessage={() => (
<span>
Loading filter suggestions
</span>
)}
value={inputValue == '' ? { label: 'Enter a filter value', value: '' } : { label: updatedValue, value: `${updatedValue } ` }}
onChange={({ value }, a) => {
this.setState({ updatedValue: value, inputValue: value, forceReloadSuggestions: forceReloadSuggestions + 1 })
}}
onInputChange={(value, { action }) => {
if (action == 'input-change') this.setState({ inputValue: value })
if (action == 'menu-close' || action == 'input-blur') this.setState(({inputValue}) => ({ updatedValue: inputValue }))
}}
inputValue={inputValue}
onBlur={() => this.setState({ forceReloadSuggestions: forceReloadSuggestions + 1 })}
/>)
}
handleSubmit() {
const { selectedFilter, negated, updatedValue } = this.state;
const validFilter = this.editableGoals.includes(selectedFilter) && updatedValue.trim()
let finalFilterValue = (this.negationSupported(selectedFilter) && negated ? '!' : '') + updatedValue.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 finalizedQuery = new URLSearchParams(window.location.search)
finalizedQuery.set(selectedFilter, finalFilterValue)
if (validFilter) {
this.setState({ finalizedQuery })
}
}
renderBody() {
const { selectedFilter, negated, updatedValue, query } = this.state;
const validFilter = this.editableGoals.includes(selectedFilter) && updatedValue.trim()
return (
<>
<h1 className="text-xl font-bold dark:text-gray-100">{query.filters[selectedFilter] ? 'Edit' : 'Add'} Filter</h1>
<div className="my-4 border-b border-gray-300"></div>
<main className="modal__content">
<form className="flex flex-col" id="filter-form" onSubmit={this.handleSubmit}>
<select
value={selectedFilter || ""}
className="my-2 block w-full py-2 pl-3 pr-10 text-base border-gray-300 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-200 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:bg-gray-900 dark:text-gray-300 cursor-pointer"
placeholder="Select a Filter"
onChange={(e) => this.setState({ selectedFilter: e.target.value })}
ref={this.fieldSelectRef}
>
<option disabled value="" className="hidden">Select a Filter</option>
{this.editableGoals.map(filter => <option key={filter} value={filter}>{formattedFilters[filter]}</option>)}
</select>
{this.negationSupported(selectedFilter) && (
<div className="my-4 flex items-center">
<label className="text-gray-700 dark:text-gray-300 text-sm cursor-pointer">
<input
type="checkbox"
className="bg-gray-100 dark:bg-gray-900 text-indigo-600 border-gray-300 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-200 mr-2 relative inline-flex flex-shrink-0 h-6 w-8 border-1 rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none"
checked={negated}
name="exclude"
onChange={(e) => this.setState({ negated: e.target.checked })}
/>
Exclude pages matching this filter
</label>
</div>
)}
{this.renderSelector(selectedFilter)}
<button
type="submit"
disabled={!validFilter}
className="button mt-4 w-2/3 mx-auto"
>
{query.filters[selectedFilter] ? 'Update' : 'Add'} Filter
</button>
{query.filters[selectedFilter] && (
<button
className="button mt-8 px-4 mx-auto flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
onClick={() => {
const finalizedQuery = new URLSearchParams(window.location.search)
finalizedQuery.delete(selectedFilter)
this.setState({ finalizedQuery })
}}
>
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
Remove Filter
</button>
)}
</form>
</main>
</>
)
}
render() {
const { finalizedQuery } = this.state;
if (finalizedQuery)
return <Redirect to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: finalizedQuery.toString() }} />
return (
<Modal site={this.props.site} maxWidth="460px">
{ this.renderBody()}
</Modal>
)
}
}
export default withRouter(FilterModal)

@ -47,7 +47,7 @@ class Modal extends React.Component {
<div className="modal is-open" onClick={this.props.onClick}>
<div className="modal__overlay">
<button className="modal__close"></button>
<div ref={this.node} className="modal__container dark:bg-gray-800">
<div ref={this.node} className="modal__container dark:bg-gray-800" style={{maxWidth: this.props.maxWidth || '860px'}}>
{this.props.children}
</div>

File diff suppressed because it is too large Load Diff

@ -22,6 +22,7 @@
"css-minimizer-webpack-plugin": "^3.0.0",
"datamaps": "^0.5.9",
"iframe-resizer": "^4.3.2",
"lodash.debounce": "^4.0.8",
"mini-css-extract-plugin": "^1.6.0",
"phoenix": "file:../deps/phoenix",
"phoenix_html": "file:../deps/phoenix_html",
@ -32,6 +33,7 @@
"react-flatpickr": "3.10.5",
"react-flip-move": "^3.0.4",
"react-router-dom": "^5.2.0",
"react-select": "^4.3.1",
"react-transition-group": "^4.4.2",
"tailwindcss": "^2.1.2",
"terser-webpack-plugin": "^5.1.2",

@ -14,6 +14,7 @@ module.exports = {
extend: {
colors: {
orange: colors.orange,
'gray-950': 'rgb(13, 18, 30)',
'gray-850': 'rgb(26, 32, 44)',
'gray-825': 'rgb(37, 47, 63)'
},
@ -30,7 +31,7 @@ module.exports = {
'9': 9,
},
maxWidth: {
'2xs': '16rem',
'2xs': '15rem',
'3xs': '12rem',
}
},

@ -257,13 +257,7 @@ defmodule Plausible.Stats.Clickhouse do
from(s in referrers, where: s.referrer_source != "")
end
referrers =
if query.filters["page"] do
page = query.filters["page"]
from(s in referrers, where: s.entry_page == ^page)
else
referrers
end
referrers = apply_page_as_entry_page(referrers, site, query)
referrers =
if include_details do
@ -326,13 +320,7 @@ defmodule Plausible.Stats.Clickhouse do
end
defp apply_page_as_entry_page(db_query, _site, query) do
page = query.filters["page"]
if is_binary(page) do
from(s in db_query, where: s.entry_page == ^page)
else
db_query
end
include_path_filter_entry(db_query, query.filters["page"])
end
def utm_mediums(site, query, limit \\ 9, page \\ 1, show_noref \\ false) do
@ -691,6 +679,55 @@ defmodule Plausible.Stats.Clickhouse do
|> Enum.into(%{})
end
def page_times_by_page_url(site, query, page_list \\ nil)
def page_times_by_page_url(site, query, _page_list = nil) do
{negated, updated_page_selection} = query.filters["page"] |> check_negated_filter()
{_, page_regex} = updated_page_selection |> convert_path_regex()
q =
from(
e in base_query_w_sessions(site, %Query{
query
| filters: Map.delete(query.filters, "page")
}),
select: {
fragment("? as p", e.pathname),
fragment("? as t", e.timestamp),
fragment("? as s", e.session_id)
},
order_by: [e.session_id, e.timestamp]
)
{base_query_raw, base_query_raw_params} = ClickhouseRepo.to_sql(:all, q)
time_query = "
SELECT
avg(ifNotFinite(avgTime, null))
FROM
(SELECT
p,
sum(td)/count(case when p2 != p then 1 end) as avgTime
FROM
(SELECT
p,
p2,
sum(t2-t) as td
FROM
(SELECT
*,
neighbor(t, 1) as t2,
neighbor(p, 1) as p2,
neighbor(s, 1) as s2
FROM (#{base_query_raw}))
WHERE s=s2 AND
#{if negated, do: "not(match(p, ?))", else: "match(p, ?)"}
GROUP BY p,p2,s)
GROUP BY p)"
time_query |> ClickhouseRepo.query(base_query_raw_params ++ [page_regex])
end
def page_times_by_page_url(site, query, page_list) do
q =
from(
@ -708,24 +745,27 @@ defmodule Plausible.Stats.Clickhouse do
{base_query_raw, base_query_raw_params} = ClickhouseRepo.to_sql(:all, q)
"SELECT
p,
sum(td)/count(case when p2 != p then 1 end) as avgTime
FROM
(SELECT
time_query = "
SELECT
p,
p2,
sum(t2-t) as td
sum(td)/count(case when p2 != p then 1 end) as avgTime
FROM
(SELECT
*,
neighbor(t, 1) as t2,
neighbor(p, 1) as p2,
neighbor(s, 1) as s2
FROM (#{base_query_raw}))
WHERE s=s2 AND p IN tuple(?)
GROUP BY p,p2,s)
GROUP BY p"
p,
p2,
sum(t2-t) as td
FROM
(SELECT
*,
neighbor(t, 1) as t2,
neighbor(p, 1) as p2,
neighbor(s, 1) as s2
FROM (#{base_query_raw}))
WHERE s=s2 AND p IN tuple(?)
GROUP BY p,p2,s)
GROUP BY p"
time_query
|> ClickhouseRepo.query(
base_query_raw_params ++ [(Enum.count(page_list) > 0 && page_list) || ["/"]]
)
@ -1156,21 +1196,9 @@ defmodule Plausible.Stats.Clickhouse do
sessions_q
end
sessions_q =
if query.filters["entry_page"] do
entry_page = query.filters["entry_page"]
from(s in sessions_q, where: s.entry_page == ^entry_page)
else
sessions_q
end
sessions_q = include_path_filter_entry(sessions_q, query.filters["entry_page"])
sessions_q =
if query.filters["exit_page"] do
exit_page = query.filters["exit_page"]
from(s in sessions_q, where: s.exit_page == ^exit_page)
else
sessions_q
end
sessions_q = include_path_filter_exit(sessions_q, query.filters["exit_page"])
q =
from(e in "events",
@ -1194,13 +1222,7 @@ defmodule Plausible.Stats.Clickhouse do
q
end
q =
if query.filters["page"] do
page = query.filters["page"]
from(e in q, where: e.pathname == ^page)
else
q
end
q = include_path_filter(q, query.filters["page"])
if query.filters["props"] do
[{key, val}] = query.filters["props"] |> Enum.into([])
@ -1350,21 +1372,9 @@ defmodule Plausible.Stats.Clickhouse do
q
end
q =
if query.filters["entry_page"] do
entry_page = query.filters["entry_page"]
from(s in q, where: s.entry_page == ^entry_page)
else
q
end
q = include_path_filter_entry(q, query.filters["entry_page"])
q =
if query.filters["exit_page"] do
exit_page = query.filters["exit_page"]
from(s in q, where: s.exit_page == ^exit_page)
else
q
end
q = include_path_filter_exit(q, query.filters["exit_page"])
if query.filters["referrer"] do
ref = query.filters["referrer"]
@ -1464,13 +1474,7 @@ defmodule Plausible.Stats.Clickhouse do
q
end
q =
if query.filters["page"] do
page = query.filters["page"]
from(e in q, where: e.pathname == ^page)
else
q
end
q = include_path_filter(q, query.filters["page"])
if query.filters["props"] do
[{key, val}] = query.filters["props"] |> Enum.into([])
@ -1550,12 +1554,9 @@ defmodule Plausible.Stats.Clickhouse do
end
if path do
if String.match?(path, ~r/\*/) do
path_regex =
"^#{path}\/?$"
|> String.replace(~r/\*\*/, ".*")
|> String.replace(~r/(?<!\.)\*/, "[^/]*")
{contains_regex, path_regex} = convert_path_regex(path)
if contains_regex do
from(e in q, where: fragment("match(?, ?)", e.pathname, ^path_regex))
else
from(e in q, where: e.pathname == ^path)
@ -1564,4 +1565,234 @@ defmodule Plausible.Stats.Clickhouse do
q
end
end
defp check_negated_filter(filter) do
negated = String.at(filter, 0) == "!"
updated_filter = if negated, do: String.slice(filter, 1..-1), else: filter
{negated, updated_filter}
end
defp convert_path_regex(path) do
contains_regex = String.match?(path, ~r/\*/)
regex =
"^#{path}\/?$"
|> String.replace(~r/\*\*/, ".*")
|> String.replace(~r/(?<!\.)\*/, "[^/]*")
{contains_regex, regex}
end
defp include_path_filter(db_query, path) do
if path do
{negated, path} = check_negated_filter(path)
{contains_regex, path_regex} = convert_path_regex(path)
if contains_regex do
if negated do
from(e in db_query, where: fragment("not(match(?, ?))", e.pathname, ^path_regex))
else
from(e in db_query, where: fragment("match(?, ?)", e.pathname, ^path_regex))
end
else
if negated do
from(e in db_query, where: e.pathname != ^path)
else
from(e in db_query, where: e.pathname == ^path)
end
end
else
db_query
end
end
defp include_path_filter_entry(db_query, path) do
if path do
{negated, path} = check_negated_filter(path)
{contains_regex, path_regex} = convert_path_regex(path)
if contains_regex do
if negated do
from(e in db_query, where: fragment("not(match(?, ?))", e.entry_page, ^path_regex))
else
from(e in db_query, where: fragment("match(?, ?)", e.entry_page, ^path_regex))
end
else
if negated do
from(e in db_query, where: e.entry_page != ^path)
else
from(e in db_query, where: e.entry_page == ^path)
end
end
else
db_query
end
end
defp include_path_filter_exit(db_query, path) do
if path do
{negated, path} = check_negated_filter(path)
{contains_regex, path_regex} = convert_path_regex(path)
if contains_regex do
if negated do
from(e in db_query, where: fragment("not(match(?, ?))", e.exit_page, ^path_regex))
else
from(e in db_query, where: fragment("match(?, ?)", e.exit_page, ^path_regex))
end
else
if negated do
from(e in db_query, where: e.exit_page != ^path)
else
from(e in db_query, where: e.exit_page == ^path)
end
end
else
db_query
end
end
def make_suggestions(site, query, "country", filter_search) do
filter_search =
String.split(filter_search, ",")
|> Enum.map(fn c -> Plausible.Stats.CountryName.to_alpha2(c) end)
q =
from(
e in base_session_query(site, query),
group_by: e.country_code,
order_by: [desc: fragment("count(*)")],
select: {e.country_code}
)
ClickhouseRepo.all(q)
|> Enum.map(fn {x} -> x end)
|> Enum.filter(fn c -> Enum.find(filter_search, false, fn x -> x == c end) end)
|> Enum.map(fn c -> Plausible.Stats.CountryName.to_alpha3(c) end)
|> Enum.slice(0..24)
end
def make_suggestions(site, _query, "goal", filter_search) do
Repo.all(from g in Plausible.Goal, where: g.domain == ^site.domain)
|> Enum.map(fn x -> if x.event_name, do: x.event_name, else: "Visit #{x.page_path}" end)
|> Enum.filter(fn goal ->
String.contains?(
String.downcase(goal),
String.downcase(filter_search)
)
end)
end
def make_suggestions(site, query, filter_name, filter_search) do
filter_search = if filter_search == nil, do: "", else: filter_search
filter_query =
if Enum.member?(["entry_page", "page", "exit_page"], filter_name),
do: "%#{String.replace(filter_search, "*", "")}%",
else: "%#{filter_search}%"
filter_name =
case filter_name do
"page" -> "pathname"
"source" -> "referrer_source"
"os" -> "operating_system"
"os_version" -> "operating_system_version"
"screen" -> "screen_size"
_ -> filter_name
end
q =
if(filter_name == "pathname",
do: base_query(site, query),
else: base_session_query(site, query)
)
|> from(
group_by: ^String.to_atom(filter_name),
order_by: [desc: fragment("count(*)")],
limit: 25
)
q =
case filter_name do
"pathname" ->
from(e in q,
select: {e.pathname},
where: fragment("? ilike ?", e.pathname, ^filter_query)
)
"entry_page" ->
from(e in q,
select: {e.entry_page},
where: fragment("? ilike ?", e.entry_page, ^filter_query)
)
"exit_page" ->
from(e in q,
select: {e.exit_page},
where: fragment("? ilike ?", e.exit_page, ^filter_query)
)
"referrer_source" ->
from(e in q,
select: {e.referrer_source},
where: fragment("? ilike ?", e.referrer_source, ^filter_query)
)
"utm_medium" ->
from(e in q,
select: {e.utm_medium},
where: fragment("? ilike ?", e.utm_medium, ^filter_query)
)
"utm_source" ->
from(e in q,
select: {e.utm_source},
where: fragment("? ilike ?", e.utm_source, ^filter_query)
)
"utm_campaign" ->
from(e in q,
select: {e.utm_campaign},
where: fragment("? ilike ?", e.utm_campaign, ^filter_query)
)
"referrer" ->
from(e in q,
select: {e.referrer},
where: fragment("? ilike ?", e.referrer, ^filter_query)
)
"browser" ->
from(e in q, select: {e.browser}, where: fragment("? ilike ?", e.browser, ^filter_query))
"browser_version" ->
from(e in q,
select: {e.browser_version},
where: fragment("? ilike ?", e.browser_version, ^filter_query)
)
"operating_system" ->
from(e in q,
select: {e.operating_system},
where: fragment("? ilike ?", e.operating_system, ^filter_query)
)
"operating_system_version" ->
from(e in q,
select: {e.operating_system_version},
where: fragment("? ilike ?", e.operating_system_version, ^filter_query)
)
"screen_size" ->
from(e in q,
select: {e.screen_size},
where: fragment("? ilike ?", e.screen_size, ^filter_query)
)
end
ClickhouseRepo.all(q)
|> Enum.map(fn {suggestion} -> suggestion end)
|> Enum.filter(fn suggestion -> suggestion != "" end)
end
end

@ -110,14 +110,12 @@ defmodule PlausibleWeb.Api.StatsController do
Task.yield_many(
[
Task.async(fn ->
{:ok, page_times} =
Stats.page_times_by_page_url(site, query, [query.filters["page"]])
{:ok, page_times} = Stats.page_times_by_page_url(site, query)
page_times
end),
Task.async(fn ->
{:ok, page_times} =
Stats.page_times_by_page_url(site, prev_query, [query.filters["page"]])
{:ok, page_times} = Stats.page_times_by_page_url(site, prev_query)
page_times
end)
@ -132,8 +130,8 @@ defmodule PlausibleWeb.Api.StatsController do
{:ok, page_times} ->
result = Enum.at(page_times.rows, 0)
result = if result, do: Enum.at(result, 1), else: nil
if result, do: {:ok, round(result)}, else: {:ok, 0}
result = if result, do: Enum.at(result, 0), else: nil
if result, do: {:ok, round(result)}, else: {nil, nil}
_ ->
response
@ -386,4 +384,11 @@ defmodule PlausibleWeb.Api.StatsController do
def handle_errors(conn, %{kind: kind, reason: reason}) do
json(conn, %{error: Exception.format_banner(kind, reason)})
end
def filter_suggestions(conn, params) do
site = conn.assigns[:site]
query = Query.from(site.timezone, params)
json(conn, Stats.make_suggestions(site, query, params["filter_name"], params["q"]))
end
end

@ -69,6 +69,7 @@ defmodule PlausibleWeb.Router do
get "/:domain/screen-sizes", StatsController, :screen_sizes
get "/:domain/conversions", StatsController, :conversions
get "/:domain/property/:prop_name", StatsController, :prop_breakdown
get "/:domain/suggestions/:filter_name", StatsController, :filter_suggestions
end
scope "/api/v1/stats", PlausibleWeb.Api do

@ -0,0 +1,133 @@
defmodule PlausibleWeb.Api.StatsController.SuggestionsTest do
use PlausibleWeb.ConnCase
import Plausible.TestUtils
describe "GET /api/stats/:domain/suggestions/:filter_name" do
setup [:create_user, :log_in, :create_site]
test "returns suggestions for pages without a query", %{conn: conn, site: site} do
conn = get(conn, "/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["/", "/register", "/contact", "/irrelevant"]
end
test "returns suggestions for pages with a query", %{conn: conn, site: site} do
conn =
get(conn, "/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01&q=re")
assert json_response(conn, 200) == ["/register", "/irrelevant"]
end
test "returns suggestions for pages without any suggestions", %{conn: conn, site: site} do
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/page?period=month&date=2019-01-01&q=/123"
)
assert json_response(conn, 200) == []
end
test "returns suggestions for goals", %{conn: conn, site: site} do
conn = get(conn, "/api/stats/#{site.domain}/suggestions/goal?period=month&date=2019-01-01")
assert json_response(conn, 200) == []
end
test "returns suggestions for sources", %{conn: conn, site: site} do
conn =
get(conn, "/api/stats/#{site.domain}/suggestions/source?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["10words", "Bing"]
end
test "returns suggestions for countries", %{conn: conn, site: site} do
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/country?period=month&date=2019-01-01&q=GBR,UKR,URY,USA"
)
assert json_response(conn, 200) == ["USA"]
end
test "returns suggestions for countries without country in search", %{conn: conn, site: site} do
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/country?period=month&date=2019-01-01&q=GBR,UKR,URY"
)
assert json_response(conn, 200) == []
end
test "returns suggestions for screen sizes", %{conn: conn, site: site} do
conn =
get(conn, "/api/stats/#{site.domain}/suggestions/screen?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["Desktop"]
end
test "returns suggestions for browsers", %{conn: conn, site: site} do
conn =
get(conn, "/api/stats/#{site.domain}/suggestions/browser?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["Chrome"]
end
test "returns suggestions for browser versions", %{conn: conn, site: site} do
filters = Jason.encode!(%{browser: "Chrome"})
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/browser_version?period=month&date=2019-01-01&filters=#{
filters
}"
)
assert json_response(conn, 200) == ["78.0"]
end
test "returns suggestions for OS", %{conn: conn, site: site} do
conn = get(conn, "/api/stats/#{site.domain}/suggestions/os?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["Mac"]
end
test "returns suggestions for OS versions", %{conn: conn, site: site} do
filters = Jason.encode!(%{os: "Mac"})
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/os_version?period=month&date=2019-01-01&filters=#{
filters
}"
)
assert json_response(conn, 200) == ["10.15"]
end
test "returns suggestions for OS versions with search", %{conn: conn, site: site} do
filters = Jason.encode!(%{os: "Mac"})
conn =
get(
conn,
"/api/stats/#{site.domain}/suggestions/os_version?period=month&date=2019-01-01&filters=#{
filters
}&q=11"
)
assert json_response(conn, 200) == []
end
test "returns suggestions for referrers", %{conn: conn, site: site} do
conn =
get(conn, "/api/stats/#{site.domain}/suggestions/referrer?period=month&date=2019-01-01")
assert json_response(conn, 200) == ["10words.com/page1"]
end
end
end
Loading…
Cancel
Save