Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
React (#17)
Uku Tahte8f20e67cc91
diff --git a/assets/.babelrc b/assets/.babelrcindex ce33b24d4d..fd6b16f520 100644--- a/assets/.babelrc+++ b/assets/.babelrc@@ -1,5 +1,6 @@{"presets": [- "@babel/preset-env"+ "@babel/preset-env",+ "@babel/preset-react"]}diff --git a/assets/css/app.css b/assets/css/app.cssindex c938d3d031..3077eab3c8 100644--- a/assets/css/app.css+++ b/assets/css/app.css@@ -63,19 +63,25 @@ blockquote {@tailwind utilities;-#main-graph {- height: 250px;+.main-graph {+ height: 310px;}-@screen sm {- #main-graph {- height: 300px;+@screen md {+ .main-graph {+ height: 360px;}}-@screen md {- #main-graph {- height: 460px;+@screen lg {+ .main-graph {+ height: 440px;+ }+}++@screen xl {+ .main-graph {+ height: 480px;}}diff --git a/assets/css/modal.css b/assets/css/modal.cssindex c8cdc787b2..79bdcf0bfa 100644--- a/assets/css/modal.css+++ b/assets/css/modal.css@@ -43,13 +43,15 @@}.modal__close {- background: transparent;- border: 0;- font-size: 20px;+ position: fixed;+ color: #b8c2cc;+ font-size: 48px;font-weight: bold;+ top: 12px;+ right: 24px;}-.modal__header .modal__close:before { content: "\2715"; }+.modal__close:before { content: "\2715"; }.modal__content {margin-top: 2rem;diff --git a/assets/js/app.js b/assets/js/app.jsindex 43f0918c2e..bbfed39f07 100644--- a/assets/js/app.js+++ b/assets/js/app.js@@ -1,6 +1,5 @@import css from "../css/app.css"import "./polyfills/closest"-import "./stats"import "phoenix_html"const triggers = document.querySelectorAll('[data-dropdown-trigger]')@@ -13,6 +12,14 @@ for (const trigger of triggers) {}if (triggers.length > 0) {+ document.addEventListener('click', function(e) {+ const dropdown = e.target.closest('[data-dropdown]')++ if (dropdown && e.target.tagName === 'A') {+ dropdown.classList.add('hidden')+ }+ })+document.addEventListener('click', function(e) {const clickedInDropdown = e.target.closest('[data-dropdown]')diff --git a/assets/js/dashboard/api.js b/assets/js/dashboard/api.jsnew file mode 100644index 0000000000..493bec9e17--- /dev/null+++ b/assets/js/dashboard/api.js@@ -0,0 +1,19 @@+import {formatISO} from './date'++function serialize(obj) {+ var str = [];+ for (var p in obj)+ if (obj.hasOwnProperty(p)) {+ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));+ }+ return str.join("&");+}++export function get(url, query, ...extraQuery) {+ query = Object.assign({}, query, {+ date: query.date ? formatISO(query.date) : undefined+ }, ...extraQuery)++ url = url + `?${serialize(query)}`+ return fetch(url).then(res => res.json())+}diff --git a/assets/js/dashboard/date.js b/assets/js/dashboard/date.jsnew file mode 100644index 0000000000..0bbf0f9fb9--- /dev/null+++ b/assets/js/dashboard/date.js@@ -0,0 +1,46 @@+// https://stackoverflow.com/a/50130338+export function formatISO(date) {+ return new Date(date.getTime() - (date.getTimezoneOffset() * 60000))+ .toISOString()+ .split("T")[0];+}++export function shiftMonths(date, months) {+ const newDate = new Date(date.getTime())+ newDate.setMonth(newDate.getMonth() + months)+ return newDate+}++export function shiftDays(date, days) {+ const newDate = new Date(date.getTime())+ newDate.setDate(newDate.getDate() + days)+ return newDate+}++const MONTHS = [+ "January", "February", "March",+ "April", "May", "June", "July",+ "August", "September", "October",+ "November", "December"+]++export function formatMonthYYYY(date) {+ return `${MONTHS[date.getMonth()]} ${date.getFullYear()}`;+}++export function formatMonth(date) {+ return `${MONTHS[date.getMonth()]}`;+}++export function formatDay(date) {+ return `${date.getDate()} ${formatMonth(date)}`;+}++// https://stackoverflow.com/a/11124448+export function newDateInOffset(offset) {+ return new Date(new Date().getTime() + offset * 1000)+}++export function isToday(site, date) {+ return formatISO(date) === formatISO(newDateInOffset(site.offset))+}diff --git a/assets/js/dashboard/datepicker.js b/assets/js/dashboard/datepicker.jsnew file mode 100644index 0000000000..72fd04278d--- /dev/null+++ b/assets/js/dashboard/datepicker.js@@ -0,0 +1,128 @@+import React from 'react';+import { withRouter } from 'react-router-dom'+import { Link } from 'react-router-dom'+import {shiftDays, shiftMonths, formatDay, formatMonthYYYY, formatISO, isToday} from './date'++class DatePicker extends React.Component {+ constructor(props) {+ super(props)+ this.handleKeyup = this.handleKeyup.bind(this)+ }++ componentDidMount() {+ document.addEventListener("keyup", this.handleKeyup);+ }++ componentWillUnmount() {+ document.removeEventListener("keyup", this.handleKeyup);+ }++ handleKeyup(e) {+ const {query, history} = this.props++ if (e.key === 'ArrowLeft') {+ if (query.period === 'day') {+ const prevDate = formatISO(shiftDays(query.date, -1))+ history.push('?period=day&date=' + prevDate)+ } else if (query.period === 'month') {+ const prevMonth = formatISO(shiftMonths(query.date, -1))+ history.push('?period=month&date=' + prevMonth)+ }+ } else if (e.key === 'ArrowRight') {+ if (query.period === 'day') {+ const nextDate = formatISO(shiftDays(query.date, 1))+ history.push('?period=day&date=' + nextDate)+ } else if (query.period === 'month') {+ const nextMonth = formatISO(shiftMonths(query.date, 1))+ history.push('?period=month&date=' + nextMonth)+ }+ }+ }++ timeFrameText() {+ const {query, site} = this.props++ if (query.period === 'day') {+ if (isToday(site, query.date)) {+ return 'Today'+ } else {+ return formatDay(query.date)+ }+ } else if (query.period === '7d') {+ return 'Last 7 days'+ } else if (query.period === '30d') {+ return 'Last 30 days'+ } else if (query.period === 'month') {+ return formatMonthYYYY(query.date)+ } else if (query.period === '3mo') {+ return 'Last 3 months'+ } else if (query.period === '6mo') {+ return 'Last 6 months'+ }+ }++ renderArrow(period, prevDate, nextDate) {+ return (+ <div className="flex rounded shadow bg-white mr-4 cursor-pointer">+ <Link to={`/${this.props.site.domain}?period=${period}&date=${prevDate}`} className="flex items-center px-2 border-r border-grey-light">+ <svg className="fill-current h-4 w-4" style={{transform: 'translateY(-2px)'}}>+ <use xlinkHref="#feather-chevron-left" />+ </svg>+ </Link>+ <Link to={`/${this.props.site.domain}?period=${period}&date=${nextDate}`} className="flex items-center px-2">+ <svg className="fill-current h-4 w-4" style={{transform: 'translateY(-2px)'}}>+ <use xlinkHref="#feather-chevron-right" />+ </svg>+ </Link>+ </div>+ )+ }++ 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)+ } else if (query.period === 'day') {+ const prevDate = formatISO(shiftDays(query.date, -1))+ const nextDate = formatISO(shiftDays(query.date, 1))++ return this.renderArrow('day', prevDate, nextDate)+ }+ }++ renderDropDown() {+ return (+ <div className="relative" style={{height: '35.5px', width: '190px'}}>+ <div data-dropdown-trigger className="flex items-center justify-between hover:bg-grey-lighter rounded bg-white shadow px-4 pr-3 py-2 leading-tight cursor-pointer text-sm font-bold text-grey-darker h-full">+ <span className="mr-2">{this.timeFrameText()}</span>+ <svg className="text-pink fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">+ <use xlinkHref="#feather-chevron-down" />+ </svg>+ </div>++ <div data-dropdown style={{top: '42px', right: '0px', width: '225px'}} className="dropdown-content hidden absolute pin-r bg-white border border-grey-light rounded shadow z-10 font-bold text-sm text-grey-darker">+ <Link to={`/${this.props.site.domain}?period=day`} className="block p-2 hover:bg-grey-lighter">Today</Link>+ <Link to={`/${this.props.site.domain}?period=7d`} className="block p-2 hover:bg-grey-lighter">Last 7 days</Link>+ <Link to={`/${this.props.site.domain}?period=30d`} className="block p-2 hover:bg-grey-lighter">Last 30 days</Link>+ <Link to={`/${this.props.site.domain}?period=3mo`} className="block p-2 hover:bg-grey-lighter">Last 3 months</Link>+ <Link to={`/${this.props.site.domain}?period=6mo`} className="block p-2 hover:bg-grey-lighter">Last 6 months</Link>+ </div>+ </div>+ )+ }++ render() {+ return (+ <div className="flex justify-between sm:justify-between">+ { this.renderArrows() }+ { this.renderDropDown() }+ </div>+ )+ }+}++export default withRouter(DatePicker)diff --git a/assets/js/dashboard/index.js b/assets/js/dashboard/index.jsnew file mode 100644index 0000000000..06b8f8d57b--- /dev/null+++ b/assets/js/dashboard/index.js@@ -0,0 +1,66 @@+import React from 'react';+import { withRouter } from 'react-router-dom'++import Datepicker from './datepicker'+import CurrentVisitors from './stats/current-visitors'+import VisitorGraph from './stats/visitor-graph'+import Referrers from './stats/referrers'+import Pages from './stats/pages'+import Countries from './stats/countries'+import Browsers from './stats/browsers'+import OperatingSystems from './stats/operating-systems'+import ScreenSizes from './stats/screen-sizes'+import Conversions from './stats/conversions'+import {parseQuery} from './query'++class Stats extends React.Component {+ constructor(props) {+ super(props)+ this.state = {query: parseQuery(props.location.search, this.props.site)}+ }++ componentDidUpdate(prevProps) {+ if (prevProps.location.search !== this.props.location.search) {+ this.setState({query: parseQuery(this.props.location.search, this.props.site)})+ }+ }++ renderConversions() {+ if (this.props.site.hasGoals) {+ return (+ <div className="w-full block md:flex items-start justify-between mt-6">+ <Conversions site={this.props.site} query={this.state.query} />+ </div>+ )+ }+ }++ render() {+ return (+ <div className="mb-12">+ <div className="w-full sm:flex justify-between items-center">+ <div className="w-full flex items-center">+ <h2 className="text-left mr-8">Analytics for <a href="//{this.props.domain}" target="_blank">{this.props.site.domain}</a></h2>+ <CurrentVisitors site={this.props.site} />+ </div>+ <Datepicker site={this.props.site} query={this.state.query} />+ </div>+ <VisitorGraph site={this.props.site} query={this.state.query} />+ <div className="w-full block md:flex items-start justify-between mt-6">+ <Referrers site={this.props.site} query={this.state.query} />+ <Pages site={this.props.site} query={this.state.query} />+ <Countries site={this.props.site} query={this.state.query} />+ </div>+ <div className="w-full block md:flex items-start justify-between mt-6">+ <Browsers site={this.props.site} query={this.state.query} />+ <OperatingSystems site={this.props.site} query={this.state.query} />+ <ScreenSizes site={this.props.site} query={this.state.query} />+ </div>++ { this.renderConversions() }+ </div>+ )+ }+}++export default withRouter(Stats)diff --git a/assets/js/dashboard/mount.js b/assets/js/dashboard/mount.jsnew file mode 100644index 0000000000..b041d4cb29--- /dev/null+++ b/assets/js/dashboard/mount.js@@ -0,0 +1,16 @@+import React from 'react';+import ReactDOM from 'react-dom';++import Router from './router'++const container = document.getElementById('stats-react-container')++if (container) {+ const site = {+ domain: container.dataset.domain,+ offset: container.dataset.offset,+ hasGoals: container.dataset.hasGoals === 'true'+ }++ ReactDOM.render(<Router site={site} />, container);+}diff --git a/assets/js/dashboard/number-formatter.js b/assets/js/dashboard/number-formatter.jsnew file mode 100644index 0000000000..7d76c5768d--- /dev/null+++ b/assets/js/dashboard/number-formatter.js@@ -0,0 +1,24 @@+const THOUSAND = 1000+const HUNDRED_THOUSAND = 100000+const MILLION = 1000000+const HUNDRED_MILLION = 100000000++export default function numberFormatter(num) {+ if (num >= THOUSAND && num < MILLION) {+ const thousands = num / THOUSAND+ if (thousands === Math.floor(thousands) || num >= HUNDRED_THOUSAND) {+ return Math.floor(thousands) + 'k'+ } else {+ return (Math.floor(thousands * 10) / 10) + 'k'+ }+ } else if (num >= MILLION && num < HUNDRED_MILLION) {+ const millions = num / MILLION+ if (millions === Math.floor(millions)) {+ return Math.floor(millions) + 'm'+ } else {+ return (Math.floor(millions * 10) / 10) + 'm'+ }+ } else {+ return num+ }+}diff --git a/assets/js/dashboard/query.js b/assets/js/dashboard/query.jsnew file mode 100644index 0000000000..7a7156c235--- /dev/null+++ b/assets/js/dashboard/query.js@@ -0,0 +1,49 @@+import {formatDay, formatMonthYYYY, newDateInOffset} from './date'++function parseQueryString(queryString) {+ var query = {};+ var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');+ for (var i = 0; i < pairs.length; i++) {+ var pair = pairs[i].split('=');+ query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');+ }+ return query;+}++const PERIODS = ['day', 'month', '7d', '30d', '3mo', '6mo']++export function parseQuery(querystring, site) {+ let {period, date} = parseQueryString(querystring)+ const periodKey = 'period__' + site.domain++ if (PERIODS.includes(period)) {+ window.localStorage[periodKey] = period+ } else {+ if (window.localStorage[periodKey]) {+ period = window.localStorage[periodKey]+ } else {+ period = '6mo'+ }+ }++ return {+ period: period,+ date: date ? new Date(date) : newDateInOffset(site.offset)+ }+}++export function toHuman(query) {+ if (query.period === 'day') {+ return `on ${formatDay(query.date)}`+ } else if (query.period === 'month') {+ return `in ${formatMonthYYYY(query.date)}`+ } else if (query.period === '7d') {+ return 'in the last 7 days'+ } else if (query.period === '30d') {+ return 'in the last 30 days'+ } else if (query.period === '3mo') {+ return 'in the last 3 months'+ } else if (query.period === '6mo') {+ return 'in the last 6 months'+ }+}diff --git a/assets/js/dashboard/router.js b/assets/js/dashboard/router.jsnew file mode 100644index 0000000000..5bcc110e16--- /dev/null+++ b/assets/js/dashboard/router.js@@ -0,0 +1,49 @@+import React from 'react';+import Dash from './index'+import Modal from './stats/modals/modal'+import ReferrersModal from './stats/modals/referrers'+import ReferrersDrilldownModal from './stats/modals/referrer-drilldown'+import GoogleKeywordsModal from './stats/modals/google-keywords'+import PagesModal from './stats/modals/pages'+import CountriesModal from './stats/modals/countries'+import BrowsersModal from './stats/modals/browsers'+import OperatingSystemsModal from './stats/modals/operating-systems'++import {+ BrowserRouter,+ Switch,+ Route+} from "react-router-dom";++export default function Router({site}) {+ return (+ <BrowserRouter>+ <Route path="/:domain">+ <Dash site={site} />+ <Switch>+ <Route exact path="/:domain/referrers">+ <ReferrersModal site={site} />+ </Route>+ <Route exact path="/:domain/referrers/Google">+ <GoogleKeywordsModal site={site} />+ </Route>+ <Route exact path="/:domain/referrers/:referrer">+ <ReferrersDrilldownModal site={site} />+ </Route>+ <Route path="/:domain/pages">+ <PagesModal site={site} />+ </Route>+ <Route path="/:domain/countries">+ <CountriesModal site={site} />+ </Route>+ <Route path="/:domain/browsers">+ <BrowsersModal site={site} />+ </Route>+ <Route path="/:domain/operating-systems">+ <OperatingSystemsModal site={site} />+ </Route>+ </Switch>+ </Route>+ </BrowserRouter>+ );+}diff --git a/assets/js/dashboard/stats/bar.js b/assets/js/dashboard/stats/bar.jsnew file mode 100644index 0000000000..2f5238e35a--- /dev/null+++ b/assets/js/dashboard/stats/bar.js@@ -0,0 +1,22 @@+import React from 'react';++function barWidth(count, all) {+ let maxVal = all[0].count;++ for (const entry of all) {+ if (entry.count > maxVal) maxVal = entry.count+ }++ return count / maxVal * 100+}++export default function Bar({count, all, color}) {+ color = color ? color : "blue"+ const width = barWidth(count, all)++ return (+ <div className="bar">+ <div className={`bar__fill bg-${color}`} style={{width: width + '%'}}></div>+ </div>+ )+}diff --git a/assets/js/dashboard/stats/browsers.js b/assets/js/dashboard/stats/browsers.jsnew file mode 100644index 0000000000..cf0feeba9a--- /dev/null+++ b/assets/js/dashboard/stats/browsers.js@@ -0,0 +1,64 @@+import React from 'react';++import Bar from './bar'+import MoreLink from './more-link'+import * as api from '../api'++export default class Browsers extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchBrowsers()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, browsers: null})+ this.fetchBrowsers()+ }+ }++ fetchBrowsers() {+ api.get(`/api/stats/${this.props.site.domain}/browsers`, this.props.query)+ .then((res) => this.setState({loading: false, browsers: res}))+ }++ renderBrowser(browser) {+ return (+ <React.Fragment key={browser.name}>+ <div className="flex items-center justify-between my-2">+ <span className="truncate" style={{maxWidth: '80%'}}>{browser.name}</span>+ <span tooltip={`${browser.count} visitors`}>{browser.percentage}%</span>+ </div>+ <Bar count={browser.count} all={this.state.browsers} color="red" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.browsers) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Browsers</h2>+ <div className="text-grey-darker mt-1">by visitors</div>+ </div>++ <div className="mt-8">+ { this.state.browsers.map(this.renderBrowser.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.browsers} endpoint="browsers" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/conversions.js b/assets/js/dashboard/stats/conversions.jsnew file mode 100644index 0000000000..120d6cb388--- /dev/null+++ b/assets/js/dashboard/stats/conversions.js@@ -0,0 +1,65 @@+import React from 'react';++import Bar from './bar'+import MoreLink from './more-link'+import numberFormatter from '../number-formatter'+import * as api from '../api'++export default class Conversions extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchConversions()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, goals: null})+ this.fetchConversions()+ }+ }++ fetchConversions() {+ api.get(`/api/stats/${this.props.site.domain}/conversions`, this.props.query)+ .then((res) => this.setState({loading: false, goals: res}))+ }++ renderGoal(goal) {+ return (+ <React.Fragment key={goal.name}>+ <div className="flex items-center justify-between my-2">+ <span className="truncate" style={{maxWidth: '80%'}}>{ goal.name }</span>+ <span>{numberFormatter(goal.count)}</span>+ </div>+ <Bar count={goal.count} all={this.state.goals} color="indigo" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.goals) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Goal Conversions</h2>+ <div className="text-grey-darker mt-1">by visitors</div>+ </div>++ <div className="mt-8">+ { this.state.goals.map(this.renderGoal.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.goals} endpoint="conversions" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/countries.js b/assets/js/dashboard/stats/countries.jsnew file mode 100644index 0000000000..c2dea60f8a--- /dev/null+++ b/assets/js/dashboard/stats/countries.js@@ -0,0 +1,66 @@+import React from 'react';++import Bar from './bar'+import MoreLink from './more-link'+import * as api from '../api'++export default class Countries extends React.Component {+ constructor(props) {+ super(props)+ this.state = {+ loading: true+ }+ }++ componentDidMount() {+ this.fetchCountries()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, countries: null})+ this.fetchCountries()+ }+ }++ fetchCountries() {+ api.get(`/api/stats/${this.props.site.domain}/countries`, this.props.query)+ .then((res) => this.setState({loading: false, countries: res}))+ }++ renderCountry(country) {+ return (+ <React.Fragment key={country.name}>+ <div className="flex items-center justify-between my-2">+ <span className="truncate" style={{maxWidth: '80%'}}>{country.name}</span>+ <span tooltip={`${country.count} visitors`}>{country.percentage}%</span>+ </div>+ <Bar count={country.count} all={this.state.countries} color="indigo" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.countries) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Top Countries</h2>+ <div className="text-grey-darker mt-1">by visitors</div>+ </div>++ <div className="mt-8">+ { this.state.countries.map(this.renderCountry.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.countries} endpoint="countries" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/current-visitors.js b/assets/js/dashboard/stats/current-visitors.jsnew file mode 100644index 0000000000..e1b1c64183--- /dev/null+++ b/assets/js/dashboard/stats/current-visitors.js@@ -0,0 +1,41 @@+import React from 'react';++const THIRTY_SECONDS = 30000++export default class CurrentVisitors extends React.Component {+ constructor(props) {+ super(props)+ this.state = {currentVisitors: null}+ }++ componentDidMount() {+ this.updateCount().then(() => {+ this.intervalId = setInterval(this.updateCount.bind(this), THIRTY_SECONDS)+ })+ }++ componentWillUnMount() {+ clearInverval(this.intervalId)+ }++ updateCount() {+ return fetch(`/api/stats/${this.props.site.domain}/current-visitors`)+ .then(res => res.json())+ .then((res) => this.setState({currentVisitors: res}))+ }++ render() {+ if (this.state.currentVisitors !== null) {+ return (+ <div className="text-sm font-bold text-grey-darker mt-2 mt-0">+ <svg className="w-2 mr-1 fill-current text-green" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">+ <circle cx="8" cy="8" r="8"/>+ </svg>+ <span> {this.state.currentVisitors}</span> current visitors+ </div>+ )+ } else {+ return null+ }+ }+}diff --git a/assets/js/dashboard/stats/modals/browsers.js b/assets/js/dashboard/stats/modals/browsers.jsnew file mode 100644index 0000000000..5058d2a752--- /dev/null+++ b/assets/js/dashboard/stats/modals/browsers.js@@ -0,0 +1,68 @@+import React from "react";+import { withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery} from '../../query'++class BrowsersModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ const query = parseQuery(this.props.location.search, this.props.site)++ api.get(`/api/stats/${this.props.site.domain}/browsers`, query, {limit: 100})+ .then((res) => this.setState({loading: false, browsers: res}))+ }++ renderBrowser(browser) {+ return (+ <React.Fragment key={browser.name}>+ <div className="flex items-center justify-between my-2">+ <span>{browser.name}</span>+ <span>{browser.percentage}%</span>+ </div>+ <Bar count={browser.count} all={this.state.browsers} color="red" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.browsers) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <h1>Top browsers</h1>+ </header>+ <div className="text-grey-darker text-lg ml-1 mt-1">by visitors</div>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content">+ <div className="mt-8">+ { this.state.browsers.map(this.renderBrowser.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(BrowsersModal)diff --git a/assets/js/dashboard/stats/modals/countries.js b/assets/js/dashboard/stats/modals/countries.jsnew file mode 100644index 0000000000..b5918e5bf6--- /dev/null+++ b/assets/js/dashboard/stats/modals/countries.js@@ -0,0 +1,68 @@+import React from "react";+import { withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery} from '../../query'++class CountriesModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ const query = parseQuery(this.props.location.search, this.props.site)++ api.get(`/api/stats/${this.props.site.domain}/countries`, query, {limit: 100})+ .then((res) => this.setState({loading: false, countries: res}))+ }++ renderCountry(country) {+ return (+ <React.Fragment key={country.name}>+ <div className="flex items-center justify-between my-2">+ <span>{country.name}</span>+ <span tooltip={`${country.count} visitors`}>{country.percentage}%</span>+ </div>+ <Bar count={country.count} all={this.state.countries} color="indigo" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.countries) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <h1>Top countries</h1>+ </header>+ <div className="text-grey-darker text-lg ml-1 mt-1">by visitors</div>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content">+ <div className="mt-8">+ { this.state.countries.map(this.renderCountry.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(CountriesModal)diff --git a/assets/js/dashboard/stats/modals/google-keywords.js b/assets/js/dashboard/stats/modals/google-keywords.jsnew file mode 100644index 0000000000..7502494741--- /dev/null+++ b/assets/js/dashboard/stats/modals/google-keywords.js@@ -0,0 +1,117 @@+import React from "react";+import { Link, withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery, toHuman} from '../../query'+import RocketIcon from './rocket-icon'++class GoogleKeywordsModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {+ loading: true,+ query: parseQuery(props.location.search, props.site)+ }+ }++ componentDidMount() {+ api.get(`/api/stats/${this.props.site.domain}/referrers/Google`, this.state.query, {limit: 100})+ .then((res) => this.setState({+ loading: false,+ searchTerms: res.search_terms,+ totalVisitors: res.total_visitors,+ notConfigured: res.not_configured,+ isOwner: res.is_owner+ }))+ }++ renderTerm(term) {+ return (+ <React.Fragment key={term.name}>+ <div className="flex items-center justify-between my-2">+ <a className="hover:underline truncate" target="_blank" style={{maxWidth: '80%'}} href={'//' + term.name}>{ term.name }</a>+ <span>{numberFormatter(term.count)}</span>+ </div>+ <Bar count={term.count} all={this.state.searchTerms} color="blue" />+ </React.Fragment>+ )+ }++ renderKeywords() {+ if (this.state.notConfigured) {+ if (this.state.isOwner) {+ return (+ <div className="text-center text-grey-darker mt-6">+ <RocketIcon />+ <div className="text-lg">The site is not connected to Google Search Kewyords</div>+ <div className="text-lg">Configure the integration to view search terms</div>+ <a href={`/${this.props.site.domain}/settings#google-auth`} className="button mt-4">Connect with Google</a>+ </div>+ )+ } else {+ return (+ <div className="text-center text-grey-darker mt-6">+ <RocketIcon />+ <div className="text-lg">The site is not connected to Google Search Kewyords</div>+ <div className="text-lg">Cannot show search terms</div>+ </div>+ )+ }+ } else if (this.state.searchTerms.length > 0) {+ return (+ <div className="mt-4">+ { this.state.searchTerms.map(this.renderTerm.bind(this)) }+ </div>+ )+ } else {+ return (+ <div className="text-center text-grey-darker mt-6">+ <RocketIcon />+ <div className="text-lg">Could not find any search terms for this period</div>+ </div>+ )+ }+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else {+ return (+ <React.Fragment>+ <header className="modal__header">+ <Link to={`/${this.props.site.domain}/referrers${window.location.search}`} className="font-bold text-grey-darker hover:underline">← All referrers</Link>+ </header>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content mt-0">+ <h1>{this.state.totalVisitors} new visitors from Google</h1>+ <h1 className="text-grey-darker" style={{transform: 'translateY(-1rem)'}}>{toHuman(this.state.query)}</h1>++ <div className="flex items-center justify-between py-2 border-b border-b-grey text-sm font-bold text-grey-darker">+ <span>Search term</span>+ <span>Visitors</span>+ </div>++ { this.renderKeywords() }+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(GoogleKeywordsModal)diff --git a/assets/js/dashboard/stats/modals/modal.js b/assets/js/dashboard/stats/modals/modal.jsnew file mode 100644index 0000000000..5a81f3a9ab--- /dev/null+++ b/assets/js/dashboard/stats/modals/modal.js@@ -0,0 +1,61 @@+import React from "react";+import { createPortal } from "react-dom";+import { withRouter } from 'react-router-dom';++class Modal extends React.Component {+ constructor(props) {+ super(props)+ this.node = React.createRef()+ this.handleClickOutside = this.handleClickOutside.bind(this)+ this.handleKeyup = this.handleKeyup.bind(this)+ }++ componentDidMount() {+ document.body.style.overflow = 'hidden';+ document.body.style.height = '100vh';+ document.addEventListener("mousedown", this.handleClickOutside);+ document.addEventListener("keyup", this.handleKeyup);+ }++ componentWillUnmount() {+ document.body.style.overflow = 'unset';+ document.body.style.height = 'unset';+ document.removeEventListener("mousedown", this.handleClickOutside);+ document.removeEventListener("keyup", this.handleKeyup);+ }++ handleClickOutside(e) {+ if (this.node.current.contains(e.target)) {+ return;+ }++ this.close()+ }++ handleKeyup(e) {+ if (e.code === 'Escape') {+ this.close()+ }+ }++ close() {+ this.props.history.push(`/${this.props.site.domain}${this.props.location.search}`)+ }++ render() {+ return createPortal(+ <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">+ {this.props.children}+ </div>+ </div>+ </div>,+ document.getElementById("modal_root"),+ );+ }+}+++export default withRouter(Modal)diff --git a/assets/js/dashboard/stats/modals/operating-systems.js b/assets/js/dashboard/stats/modals/operating-systems.jsnew file mode 100644index 0000000000..2a097cb6e6--- /dev/null+++ b/assets/js/dashboard/stats/modals/operating-systems.js@@ -0,0 +1,68 @@+import React from "react";+import { withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery} from '../../query'++class OperatingSystemsModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ const query = parseQuery(this.props.location.search, this.props.site)++ api.get(`/api/stats/${this.props.site.domain}/operating-systems`, query, {limit: 100})+ .then((res) => this.setState({loading: false, systems: res}))+ }++ renderSystem(system) {+ return (+ <React.Fragment key={system.name}>+ <div className="flex items-center justify-between my-2">+ <span>{system.name}</span>+ <span>{system.percentage}%</span>+ </div>+ <Bar count={system.count} all={this.state.systems} color="blue" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.systems) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <h1>Operating Systems</h1>+ </header>+ <div className="text-grey-darker text-lg ml-1 mt-1">by visitors</div>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content">+ <div className="mt-8">+ { this.state.systems.map(this.renderSystem.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(OperatingSystemsModal)diff --git a/assets/js/dashboard/stats/modals/pages.js b/assets/js/dashboard/stats/modals/pages.jsnew file mode 100644index 0000000000..0029a935ac--- /dev/null+++ b/assets/js/dashboard/stats/modals/pages.js@@ -0,0 +1,68 @@+import React from "react";+import { withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery} from '../../query'++class PagesModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ const query = parseQuery(this.props.location.search, this.props.site)++ api.get(`/api/stats/${this.props.site.domain}/pages`, query, {limit: 100})+ .then((res) => this.setState({loading: false, pages: res}))+ }++ renderPage(page) {+ return (+ <React.Fragment key={page.name}>+ <div className="flex items-center justify-between my-2">+ <span>{ page.name }</span>+ <span>{numberFormatter(page.count)}</span>+ </div>+ <Bar count={page.count} all={this.state.pages} color="orange" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.pages) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <h1>Top pages</h1>+ </header>+ <div className="text-grey-darker text-lg ml-1 mt-1">by pageviews</div>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content">+ <div className="mt-8">+ { this.state.pages.map(this.renderPage.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(PagesModal)diff --git a/assets/js/dashboard/stats/modals/referrer-drilldown.js b/assets/js/dashboard/stats/modals/referrer-drilldown.jsnew file mode 100644index 0000000000..1dfcf82ff0--- /dev/null+++ b/assets/js/dashboard/stats/modals/referrer-drilldown.js@@ -0,0 +1,71 @@+import React from "react";+import { Link, withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery, toHuman} from '../../query'++class ReferrerDrilldownModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {+ loading: true,+ query: parseQuery(props.location.search, props.site)+ }+ }++ componentDidMount() {+ api.get(`/api/stats/${this.props.site.domain}/referrers/${this.props.match.params.referrer}`, this.state.query, {limit: 100})+ .then((res) => this.setState({loading: false, referrers: res.referrers, totalVisitors: res.total_visitors}))+ }++ renderReferrer(referrer) {+ return (+ <React.Fragment key={referrer.name}>+ <div className="flex items-center justify-between my-2">+ <a className="hover:underline truncate" target="_blank" style={{maxWidth: '80%'}} href={'//' + referrer.name}>{ referrer.name }</a>+ <span>{numberFormatter(referrer.count)}</span>+ </div>+ <Bar count={referrer.count} all={this.state.referrers} color="blue" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.referrers) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <Link to={`/${this.props.site.domain}/referrers${window.location.search}`} className="font-bold text-grey-darker hover:underline">← All referrers</Link>+ </header>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content mt-0">+ <h1>{this.state.totalVisitors} new visitors from {this.props.match.params.referrer}</h1>+ <h1 className="text-grey-darker" style={{transform: 'translateY(-1rem)'}}>{toHuman(this.state.query)}</h1>++ <div className="mt-4">+ { this.state.referrers.map(this.renderReferrer.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(ReferrerDrilldownModal)diff --git a/assets/js/dashboard/stats/modals/referrers.js b/assets/js/dashboard/stats/modals/referrers.jsnew file mode 100644index 0000000000..84cc9630eb--- /dev/null+++ b/assets/js/dashboard/stats/modals/referrers.js@@ -0,0 +1,68 @@+import React from "react";+import { Link, withRouter } from 'react-router-dom'++import Modal from './modal'+import * as api from '../../api'+import numberFormatter from '../../number-formatter'+import Bar from '../bar'+import {parseQuery} from '../../query'++class ReferrersModal extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ const query = parseQuery(this.props.location.search, this.props.site)++ api.get(`/api/stats/${this.props.site.domain}/referrers`, query, {limit: 100})+ .then((res) => this.setState({loading: false, referrers: res}))+ }++ renderReferrer(referrer) {+ return (+ <React.Fragment key={referrer.name}>+ <div className="flex items-center justify-between my-2">+ <Link className="hover:underline truncate" style={{maxWidth: '80%'}} to={`/${this.props.site.domain}/referrers/${referrer.name}${window.location.search}`}>{ referrer.name }</Link>+ <span>{numberFormatter(referrer.count)}</span>+ </div>+ <Bar count={referrer.count} all={this.state.referrers} color="blue" />+ </React.Fragment>+ )+ }++ renderBody() {+ if (this.state.loading) {+ return (+ <div className="loading my-32 mx-auto"><div></div></div>+ )+ } else if (this.state.referrers) {+ return (+ <React.Fragment>+ <header className="modal__header">+ <h1>Referrers</h1>+ </header>+ <div className="text-grey-darker text-lg ml-1 mt-1">by new visitors</div>++ <div className="my-4 border-b border-grey-light"></div>+ <main className="modal__content">+ <div className="mt-8">+ { this.state.referrers.map(this.renderReferrer.bind(this)) }+ </div>+ </main>+ </React.Fragment>+ )+ }+ }++ render() {+ return (+ <Modal site={this.props.site}>+ { this.renderBody() }+ </Modal>+ )+ }+}++export default withRouter(ReferrersModal)diff --git a/assets/js/dashboard/stats/modals/rocket-icon.js b/assets/js/dashboard/stats/modals/rocket-icon.jsnew file mode 100644index 0000000000..08b5942eb0--- /dev/null+++ b/assets/js/dashboard/stats/modals/rocket-icon.js@@ -0,0 +1,7 @@+import React from 'react'++export default function RocketIcon() {+ return (+ <svg className="fill-current" xmlns="http://www.w3.org/2000/svg" width="100" height="100" version="1.1" x="0px" y="0px" viewBox="0 0 100 125" style={{enableBackground: 'new 0 0 100 100'}} xmlSpace="preserve"><g><path d="M35.6830368,38.7263184c2.7299805,0,4.9511719-2.2211914,4.9511719-4.9511719s-2.2211914-4.9511719-4.9511719-4.9511719 c-2.7304688,0-4.9516602,2.2211914-4.9516602,4.9511719S32.9525681,38.7263184,35.6830368,38.7263184z M35.6830368,30.8239746 c1.6274414,0,2.9511719,1.3237305,2.9511719,2.9511719s-1.3237305,2.9511719-2.9511719,2.9511719 s-2.9516602-1.3237305-2.9516602-2.9511719S34.0555954,30.8239746,35.6830368,30.8239746z"/><path d="M43.4540329,27.4133301c2.1630859,0,3.9228516-1.7597656,3.9228516-3.9228516s-1.7597656-3.9228516-3.9228516-3.9228516 c-2.1625977,0-3.9223633,1.7597656-3.9223633,3.9228516S41.2914352,27.4133301,43.4540329,27.4133301z M43.4540329,21.567627 c1.0600586,0,1.9228516,0.862793,1.9228516,1.9228516s-0.862793,1.9228516-1.9228516,1.9228516 s-1.9223633-0.862793-1.9223633-1.9228516S42.3939743,21.567627,43.4540329,21.567627z"/><path d="M80.2762985,41.4973145c3.6635742,0,6.6445313-2.980957,6.6445313-6.6445313s-2.980957-6.6445313-6.6445313-6.6445313 c-3.6640625,0-6.6450195,2.980957-6.6450195,6.6445313S76.612236,41.4973145,80.2762985,41.4973145z M80.2762985,30.208252 c2.5610352,0,4.6445313,2.0834961,4.6445313,4.6445313s-2.0834961,4.6445313-4.6445313,4.6445313 s-4.6450195-2.0834961-4.6450195-4.6445313S77.7152634,30.208252,80.2762985,30.208252z"/><path d="M86.4340134,28.1555176c1.9663086,0,3.565918-1.5996094,3.565918-3.565918s-1.5996094-3.565918-3.565918-3.565918 c-1.9658203,0-3.5654297,1.5996094-3.5654297,3.565918S84.4681931,28.1555176,86.4340134,28.1555176z M86.4340134,23.0236816 c0.8632813,0,1.565918,0.7026367,1.565918,1.565918s-0.7026367,1.565918-1.565918,1.565918 s-1.5654297-0.7026367-1.5654297-1.565918S85.5707321,23.0236816,86.4340134,23.0236816z"/><path d="M79.9183884,48.1384277l-0.5896606,0.1737061c0.1333618-0.4435425,0.2112427-0.9072266,0.2112427-1.3841553 c0-0.4707031-0.0678711-0.9375-0.2045898-1.3950195c-0.78125-2.5327148-3.4887695-3.9741211-6.0366211-3.2119141 l-1.7001953,0.5170898c-0.3798828,0.1108398-0.7299805,0.1855469-1.0664063,0.2265625 c-0.003479,0.0004272-0.006897,0.000061-0.010376,0.0004883c-0.0266113,0.0028076-0.0534058-0.0014648-0.0794678,0.00354 c-0.6416626,0.0675659-1.277771,0.0505981-1.8896484-0.0645752l-4.8505859-0.8999023 c-3.8491211-0.7124023-7.8662109-0.4970703-11.6201172,0.6259766l-11.3138428,3.4025879 c-0.0564575-0.0429077-0.1116943-0.0877075-0.1778564-0.1184082l-13.7036133-6.3583984 c-0.230957-0.1069336-0.4951172-0.121582-0.7353516-0.0419922l-8.2226563,2.7250977 c-0.309082,0.1025391-0.5488281,0.3486328-0.6425781,0.6601563c-0.0942383,0.3110352-0.03125,0.6489258,0.1694336,0.9052734 l5.8516235,7.4795532l-2.1152954,0.6361694c-0.2539063,0.0761719-0.4672852,0.2504883-0.5927734,0.4838867 c-0.1254883,0.2338867-0.1533203,0.5078125-0.0766602,0.7617188l0.3309326,1.0892944 c-0.2720337,0.0733643-0.5426636,0.1504517-0.8016357,0.250061c-4.4667969,1.7197266-6.3505859,7.1894531-6.4287109,7.4213867 c-0.1542969,0.4580078,0.0415039,0.9609375,0.4648438,1.1943359c0.1640625,0.0908203,3.1762695,1.7246094,6.574707,1.7246094 c1.0532227,0,2.144043-0.1572266,3.1977539-0.5654297c0.0115356-0.0044556,0.022644-0.010437,0.0341797-0.0149536 l0.0750732,0.2472534l-1.4403076,0.4239502c-0.2548828,0.0751953-0.4692383,0.2485352-0.5961914,0.4819336 s-0.1557617,0.5073242-0.0800781,0.762207l0.2781982,0.9320679c-1.5239868-0.0391846-2.9415283,0.1781616-4.2181396,0.6724243 c-5.4560547,2.1005859-7.7651367,8.8061523-7.8608398,9.090332c-0.1176758,0.3505859-0.0327148,0.7373047,0.2211914,1.0058594 c0.2539063,0.269043,0.6376953,0.3745117,0.9916992,0.2773438c1.5864258-0.4365234,3.1904297-0.6772461,4.7919922-0.7211914 l-1.0683594,1.046875c-0.269043,0.2631836-0.3671875,0.6552734-0.2543945,1.0141602s0.4174805,0.6240234,0.7880859,0.6865234 c0.0708008,0.0117188,0.9082031,0.1474609,2.121582,0.1474609c1.3310547,0,3.1152344-0.1635742,4.8369141-0.8339844 c0.9935913-0.385376,1.942627-0.9547729,2.8378296-1.6859131l0.4258423,1.4300537 c0.1289063,0.434082,0.5268555,0.715332,0.9580078,0.715332c0.09375,0,0.1889648-0.0136719,0.2832031-0.0415039l3.6088257-1.064209 c0.5294189,0.4693604,1.2138062,0.7355957,1.9185181,0.7355957c0.2729492,0,0.5488281-0.0395508,0.8183594-0.1206055 l2.612793-0.7680664c0.6903687-0.1968994,1.2542114-0.6436157,1.6234131-1.2183228 c0.3770752,0.1716309,0.7831421,0.2798462,1.2032471,0.2798462c0.2666016,0,0.5361328-0.0366211,0.8007813-0.1132813 l2.6342773-0.7744141c0.6880493-0.2131348,1.241272-0.6553345,1.6037598-1.2210083 c0.3721924,0.1687622,0.7717285,0.2756958,1.1843262,0.2756958c0.2724609,0,0.5478516-0.0395508,0.8178711-0.1206055 l2.612793-0.7675781c0.980957-0.2804565,1.713623-1.0597534,1.9748535-2.0108032l33.9655762-10.0023804 c3.3706055-1.003418,5.6347656-4.0170898,5.6347656-7.4985352c0-0.7524414-0.1083984-1.4975586-0.3222656-2.2167969 C88.4432907,49.2814941,84.0643845,46.9157715,79.9183884,48.1384277z M26.4042282,41.6369629l10.9301758,5.0717773 l-12.3256836,3.6044922l-5.1030273-6.5224609L26.4042282,41.6369629z M63.3373337,44.0710449l2.6757202,0.4962769 l-6.4960327,2.1526489c-0.3745117,0.121582-0.7783203-0.0761719-0.9013672-0.4448242l-0.8479614-2.5335693 C59.6291428,43.6253662,61.5039597,43.730957,63.3373337,44.0710449z M52.6566696,44.645752 c1.0076294-0.3015137,2.0372925-0.5230713,3.0765381-0.6818237l0.9859619,2.9459839 c0.3779297,1.1303711,1.4384766,1.847168,2.5737305,1.8466797c0.2832031,0,0.5708008-0.0444336,0.8535156-0.1381836 l10.8579102-3.5981445c0.0090942-0.0029907,0.0158081-0.0096436,0.0247192-0.0128784 c0.3674316-0.0574341,0.7401123-0.1351929,1.1417847-0.2532349l1.7055664-0.5185547 c1.4975586-0.4467773,3.0883789,0.3989258,3.5454102,1.878418c0.078125,0.2631836,0.1181641,0.5371094,0.1181641,0.8139648 c0,0.8886719-0.4160156,1.7143555-1.1201172,2.2368164l-28.8650513,8.5059814l-0.8562622,0.2522583 c-0.2514038-0.196106-0.5341187-0.3519897-0.8377686-0.4598999c-0.0093384-0.0098267-0.0202637-0.0175781-0.0297241-0.0272827 c-0.038208-0.0392456-0.079895-0.0735474-0.1200562-0.1102905c-0.0634155-0.0580444-0.1269531-0.1153564-0.1948242-0.1671143 c-0.0471191-0.0359497-0.0963745-0.067749-0.1453857-0.1005859c-0.0665283-0.0444946-0.1335449-0.0876465-0.2033081-0.1263428 c-0.0535278-0.0297241-0.1080322-0.0564575-0.163269-0.0827026c-0.0698853-0.0332031-0.1405029-0.0636597-0.2127686-0.0911255 c-0.0580444-0.0220947-0.1160889-0.0426025-0.1754761-0.0609131c-0.0736694-0.0227051-0.1481323-0.0411987-0.2234497-0.0580444 c-0.0602417-0.0134888-0.1199341-0.0269775-0.1810303-0.0365601c-0.0789795-0.0123901-0.1585693-0.0187988-0.2385254-0.0245972 c-0.0588379-0.0043335-0.1170044-0.0105591-0.1762085-0.0112305c-0.0892334-0.0009766-0.1785889,0.0061035-0.2682495,0.0134888 c-0.0505371,0.0042114-0.1008911,0.0043335-0.1514893,0.0112305c-0.1401367,0.019043-0.2800293,0.0469971-0.4185791,0.0874023 l-2.6254883,0.7714844c-0.1715088,0.0514526-0.335022,0.1169434-0.4894409,0.1948242 c-0.1483154,0.0748291-0.2871094,0.1623535-0.4178467,0.258667c-0.0053711,0.0039673-0.0119019,0.0066528-0.0172729,0.0106812 c-0.1115723,0.083374-0.2116089,0.1785278-0.3088379,0.2757568c-0.020752,0.020752-0.0458374,0.0375366-0.0658569,0.0588379 c-0.0830688,0.0883789-0.1534424,0.1865234-0.2243042,0.2841187c-0.0264282,0.036377-0.0588379,0.0684204-0.0834961,0.105957 c-0.0002441,0.0003662-0.0006104,0.0007324-0.0008545,0.0010986c-0.008728-0.0039673-0.0183105-0.0056763-0.0270996-0.0095215 c-0.0830688-0.0366821-0.1703491-0.0613403-0.2565308-0.0900269c-0.0712891-0.0236816-0.1404419-0.0530396-0.213501-0.0710449 c-0.0961914-0.0238037-0.1952515-0.0338135-0.2938232-0.0474854c-0.0670166-0.0093384-0.1325073-0.0254517-0.2003174-0.0299683 c-0.1109619-0.0073853-0.2233276,0.0008545-0.3355103,0.0066528c-0.0574341,0.0029907-0.1143188-0.0018921-0.171875,0.0046387 c-0.1697998,0.0193481-0.3398438,0.0536499-0.5081787,0.1049194l-2.6225586,0.7709961 c-0.1702271,0.0504761-0.3327026,0.1159668-0.4865723,0.194458c-0.0361938,0.0184937-0.0670166,0.0443115-0.1022339,0.064209 c-0.114624,0.0647583-0.2285767,0.1306152-0.3320923,0.2097778c-0.0396729,0.0302734-0.0722656,0.0681152-0.1102295,0.1004028 c-0.0912476,0.0775757-0.1833496,0.1543579-0.263916,0.2424927c-0.0459595,0.0502319-0.0822754,0.1082764-0.1245728,0.1616211 c-0.0603638,0.0762329-0.1253662,0.1488647-0.1779175,0.230957c-0.4283447-0.1953125-0.90625-0.2789307-1.394104-0.2468872 c-0.0344849,0.0022583-0.0682373-0.0021362-0.1028442,0.0013428c-0.1741333,0.0176392-0.3493042,0.0509033-0.5236816,0.100708 l-2.6259766,0.7719727c-0.1636353,0.0493164-0.3181763,0.1143799-0.4664307,0.1885986 c-0.0487671,0.0244141-0.0928955,0.0542603-0.1398315,0.0811157c-0.0963745,0.0551758-0.1904907,0.1124878-0.2788086,0.1773682 c-0.0499268,0.0366821-0.0962524,0.0762939-0.1435547,0.1159058c-0.0778809,0.0652466-0.1521606,0.1329956-0.2223511,0.2055054 c-0.0435181,0.0449219-0.0854492,0.09021-0.1258545,0.1376343c-0.0662231,0.0778198-0.1264648,0.1592407-0.18396,0.2432251 c-0.03302,0.0482788-0.0672607,0.0950928-0.09729,0.1452026c-0.0593262,0.098999-0.1095581,0.2024536-0.1566162,0.3079224 c-0.0180054,0.0402222-0.0400391,0.078186-0.0561523,0.1193237c-0.0580444,0.1479492-0.1044922,0.300354-0.137207,0.4569702 c-0.007019,0.0336914-0.0078735,0.0687256-0.0136719,0.1027222c-0.0180664,0.1057129-0.0368042,0.2113647-0.0427246,0.3195801 l-0.2138062-0.7027588c0.012085-0.1270142,0.0072021-0.2562256-0.0317993-0.3841553l-1.1140137-3.6674194l-0.322998-1.0791626 c-0.0026855-0.0089111-0.0092773-0.015564-0.012207-0.024353l-0.9248047-3.0444946 c-0.0401001-0.1308594-0.1096802-0.2437134-0.1931763-0.3440552l-0.2487183-0.8175659L52.6566696,44.645752z M22.3425827,59.2571411l0.0478516,0.1574097c-0.1259155,0.0722656-0.2521362,0.1400757-0.3763428,0.1901855 c-0.253418,0.0957031-0.5390625,0.1601563-0.8525391,0.1923828c0.2495117-0.1816406,0.5009766-0.3227539,0.7504883-0.4189453 C22.0441818,59.3267212,22.1913376,59.2897949,22.3425827,59.2571411z M23.1390915,62.5144043 c-2.6728516,1.0361328-5.8369141-0.0449219-7.2880859-0.668457c0.6430664-1.4326172,2.2358398-4.3408203,4.9189453-5.3740234 c0.213562-0.0823975,0.4368286-0.1488037,0.6634521-0.2074585l0.3309937,1.0894775 c-0.1945801,0.0488892-0.3952637,0.0895996-0.5745239,0.1589966c-1.090332,0.421875-2.1020508,1.2758789-3.0068359,2.5380859 c-0.1958008,0.2734375-0.2412109,0.6269531-0.1206055,0.940918s0.3911133,0.5463867,0.7197266,0.6186523 c0.6391602,0.1396484,1.2744141,0.2109375,1.8881836,0.2109375c0.7543945,0,1.4448242-0.1166992,2.0698242-0.3535156 c0.0811157-0.0325317,0.1576538-0.0828857,0.2376709-0.1199341l0.3328857,1.0957642 C23.2537155,62.4679565,23.1967697,62.4923706,23.1390915,62.5144043z M23.5314255,72.725647l0.0012207,0.0040894 c-0.5898438,0.7407227-1.1948242,1.3237305-1.8076172,1.7416992c-0.5957031-0.9111328-1.5537109-1.5366211-2.6308594-1.7211914 c0.199707-0.1118164,0.4003906-0.2060547,0.6015625-0.2827148c1.0146484-0.387207,2.3012695-0.4477539,3.6938477-0.2143555 L23.5314255,72.725647z M21.756279,77.7346191c-1.2910156,0.5024414-2.6557617,0.6630859-3.7475586,0.6904297l1.1201172-1.0976563 c0.2788086-0.2729492,0.3730469-0.6831055,0.2421875-1.050293s-0.4633789-0.625-0.8515625-0.6601563 c-0.6420898-0.0581055-1.2861328-0.0869141-1.9301758-0.0869141c-1.2963867,0-2.5947266,0.1171875-3.8862305,0.3515625 c0.9746094-1.9414063,2.9125977-4.96875,5.9301758-6.1308594c1.1391602-0.440918,2.434082-0.6181641,3.8476563-0.5322266 l0.2842407,0.9488525c-1.3863525-0.1206055-2.680603,0.0112915-3.7837524,0.4320068 c-1.2207031,0.4672852-2.3857422,1.3544922-3.4614258,2.6357422c-0.2607422,0.3105469-0.3085938,0.7480469-0.1201172,1.1069336 c0.1879883,0.3588867,0.5737305,0.5717773,0.9785156,0.5317383l1.8959961-0.1762695 c0.0302734-0.003418,0.0610352-0.0043945,0.0913086-0.0043945c0.784668,0.0019531,1.4975586,0.4169922,1.831543,1.1416016 c0.0463867,0.0922852,0.0771484,0.1743164,0.097168,0.2583008c0.0678711,0.2875977,0.2592773,0.5307617,0.5229492,0.6635742 c0.1416016,0.0712891,0.2958984,0.1069336,0.4501953,0.1069336c0.1342773,0,0.2685547-0.0268555,0.3945313-0.0810547 c0.8795776-0.3776855,1.7250366-1.0009155,2.534668-1.8171997l0.3041992,1.0198364 C23.6381149,76.7746582,22.7172165,77.3615723,21.756279,77.7346191z M25.7430954,72.3293457 c-0.0053711-0.0239258-0.0117188-0.0478516-0.0185547-0.0712891l-1.6694336-5.5859375l0.6426392-0.1890869 c0.1815186,0.1630859,0.4124756,0.2652588,0.6615601,0.2652588c0.0947266,0,0.190918-0.0136719,0.2866211-0.0424805 l0.7924194-0.2364502l2.1046753,7.0847168l1.0675659,3.6032104l-2.2332153,0.6588745L25.7430954,72.3293457z M35.3881149,76.8781738l-2.6269531,0.7719727c-0.3734741,0.1134644-0.7839355-0.0386963-0.998291-0.3710938 c-0.0044556-0.0070801-0.0038452-0.0159912-0.0085449-0.0229492c-0.0307617-0.0463867-0.0595703-0.1108398-0.0820313-0.1914063 l-1.4168701-4.7697754l-2.2486572-7.5876465l-0.2172852-0.7382813c-0.0527344-0.4150391,0.2158203-0.8164063,0.6328125-0.9418945 l2.6118164-0.7680664c0.4311523-0.1245117,0.8818359,0.0771484,1.0400391,0.4121094l3.5966187,12.0499268l0.3242798,1.0936279 c0.0015259,0.0049438,0.0045166,0.0084229,0.0061035,0.0133667l0.0114746,0.0383911 c0.0001221,0.0003052,0.0003662,0.001709,0.0004883,0.0020752c0.0063477,0.031189,0.0131836,0.0750122,0.0131836,0.145874 c0,0.0057373,0.0036621,0.0105591,0.0037842,0.0162964C36.0345993,76.4204712,35.773613,76.7678833,35.3881149,76.8781738z M41.6283493,75.0583496l-2.6157227,0.7685547c-0.3842773,0.1107788-0.7797852-0.0397949-1.0014038-0.3787842 c-0.0003052-0.0004883-0.0002441-0.0010986-0.0005493-0.0015869c-0.0240479-0.0377808-0.0378418-0.0718384-0.053833-0.1066895 c-0.0119019-0.026001-0.0247803-0.0489502-0.0344238-0.0758057c-0.0065308-0.0221558-0.0131226-0.0442505-0.0206299-0.06604 c-0.001709-0.005127-0.0059204-0.0084839-0.0077515-0.0136108l-3.7139282-12.5259399l-0.1210938-0.4052734 c-0.0109863-0.0336914-0.0181274-0.0585327-0.0230103-0.0740356c-0.0022583-0.0072632-0.005188-0.0172729-0.0057983-0.0172729 c-0.0004883,0-0.0004883,0.0014648-0.0004883,0.0048828c-0.0610352-0.4277344,0.2119141-0.8452148,0.6318359-0.9697266 l2.6289063-0.7724609c0.40625-0.125,0.8422852,0.0654297,1.034668,0.4501953 c0.0029297,0.0058594,0.0058594,0.0112305,0.0087891,0.0170898c0.0043945,0.0102539,0.0087891,0.0205078,0.0131836,0.0302734 c0.015625,0.034668,0.0341797,0.0708008,0.0463867,0.1069336l3.8374023,12.9326172 c0.0012207,0.0040894,0.0032349,0.0079956,0.0044556,0.012085l0.0062866,0.0211182 c0.0129395,0.0390625,0.0126953,0.0739746,0.0166626,0.107666c0.0024414,0.0253906,0.0077515,0.0415649,0.0077515,0.0773926 c0,0.0050049,0.0032349,0.0092163,0.0032959,0.0142212C42.2725143,74.5970459,42.0161667,74.9381714,41.6283493,75.0583496z M48.509697,72.3605957c0.0048828,0.3955078-0.2558594,0.7475586-0.6416016,0.8579102l-2.6264648,0.7714844 c-0.3828125,0.1132813-0.7822266-0.0351563-0.9838867-0.3564453c-0.0009155-0.0015259-0.0010376-0.0028076-0.0019531-0.0043335 c-0.003479-0.0057983-0.0027466-0.0128784-0.0063477-0.0186157c-0.0113525-0.0181274-0.015686-0.0336304-0.0253296-0.0511475 c-0.026001-0.0504761-0.0529175-0.1010132-0.0684204-0.1506348c-0.0031128-0.0101929-0.0059204-0.0204468-0.0092773-0.0306396 c-0.0010376-0.0032349-0.0037231-0.0053711-0.0047607-0.008606l-3.7252197-12.5631714l-0.1323242-0.456543 c-0.0039063-0.0375977-0.0102539-0.074707-0.0185547-0.1113281c-0.0249023-0.3901367,0.2368164-0.7514648,0.6362305-0.8710938 l2.6176758-0.7695313c0.3603516-0.1015625,0.7441406,0.0283203,0.9614258,0.3271484 c0.0151367,0.0214844,0.0566406,0.078125,0.0737305,0.0981445c0.0341797,0.0678711,0.0683594,0.1425781,0.0791016,0.1674805 l3.8598633,13.0180664c0.0068359,0.0180664,0.0161133,0.0527344,0.0161133,0.1391602 C48.509697,72.3522949,48.509697,72.3562012,48.509697,72.3605957z M83.7972946,61.208252L50.2455368,71.088623 L46.943779,59.935791l33.5390625-9.8789063c3.0947266-0.909668,6.3588867,0.8496094,7.2783203,3.9257813 c0.1582031,0.5327148,0.2387695,1.0859375,0.2387695,1.6450195C87.9999313,58.2175293,86.3099899,60.4602051,83.7972946,61.208252z "/><path d="M82.1522751,50.5427246c-0.4902344,0-0.9799805,0.0712891-1.456543,0.2124023 c-0.5292969,0.1572266-0.831543,0.7133789-0.6748047,1.2431641c0.1572266,0.5292969,0.7143555,0.8310547,1.2431641,0.6748047 c1.6289063-0.4804688,3.3920898,0.496582,3.8676758,2.0874023c0.1293945,0.4335938,0.5273438,0.7138672,0.9575195,0.7138672 c0.0952148,0,0.1914063-0.0136719,0.2871094-0.0424805c0.5288086-0.1582031,0.8295898-0.715332,0.6713867-1.2446289 C86.4061813,52.0412598,84.3929977,50.5427246,82.1522751,50.5427246z"/><path d="M78.2572556,51.4729004l-2.8793945,0.847168c-0.5297852,0.15625-0.8330078,0.7119141-0.6772461,1.2416992 c0.128418,0.4355469,0.5268555,0.7182617,0.9589844,0.7182617c0.09375,0,0.1884766-0.0136719,0.2827148-0.0410156 l2.8793945-0.847168c0.5297852-0.15625,0.8330078-0.7119141,0.6772461-1.2416992 C79.3427048,51.6203613,78.784111,51.3190918,78.2572556,51.4729004z"/><path d="M72.7758102,53.0856934l-23.9584961,7.0512695c-0.5297852,0.15625-0.8330078,0.7119141-0.6772461,1.2416992 c0.128418,0.4355469,0.5268555,0.7182617,0.9589844,0.7182617c0.09375,0,0.1884766-0.0136719,0.2827148-0.0410156 l23.9584961-7.0512695c0.5297852-0.15625,0.8330078-0.7119141,0.6772461-1.2416992 C73.8607712,53.232666,73.303154,52.932373,72.7758102,53.0856934z"/></g></svg>+ )+}diff --git a/assets/js/dashboard/stats/more-link.js b/assets/js/dashboard/stats/more-link.jsnew file mode 100644index 0000000000..c34c9bd26c--- /dev/null+++ b/assets/js/dashboard/stats/more-link.js@@ -0,0 +1,17 @@+import React from 'react';+import { Link } from 'react-router-dom'++export default function MoreLink({site, list, endpoint}) {+ if (list.length >= 5) {+ return (+ <div className="text-center">+ <Link to={`/${site.domain}/${endpoint}${window.location.search}`}className="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">+ <svg className="feather mr-1"><use xlinkHref="#feather-maximize" /></svg>+ MORE+ </Link>+ </div>+ )+ } else {+ return null+ }+}diff --git a/assets/js/dashboard/stats/operating-systems.js b/assets/js/dashboard/stats/operating-systems.jsnew file mode 100644index 0000000000..3cc1ce5837--- /dev/null+++ b/assets/js/dashboard/stats/operating-systems.js@@ -0,0 +1,64 @@+import React from 'react';++import Bar from './bar'+import MoreLink from './more-link'+import * as api from '../api'++export default class OperatingSystems extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchOperatingSystems()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, systems: null})+ this.fetchOperatingSystems()+ }+ }++ fetchOperatingSystems() {+ api.get(`/api/stats/${this.props.site.domain}/operating-systems`, this.props.query)+ .then((res) => this.setState({loading: false, systems: res}))+ }++ renderSystem(system) {+ return (+ <React.Fragment key={system.name}>+ <div className="flex items-center justify-between my-2">+ <span className="truncate" style={{maxWidth: '80%'}}>{system.name}</span>+ <span tooltip={`${system.count} visitors`}>{system.percentage}%</span>+ </div>+ <Bar count={system.count} all={this.state.systems} color="blue" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.systems) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Operating Systems</h2>+ <div className="text-grey-darker mt-1">by visitors</div>+ </div>++ <div className="mt-8">+ { this.state.systems.map(this.renderSystem.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.systems} endpoint="operating-systems" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/pages.js b/assets/js/dashboard/stats/pages.jsnew file mode 100644index 0000000000..540fec7dd7--- /dev/null+++ b/assets/js/dashboard/stats/pages.js@@ -0,0 +1,67 @@+import React from 'react';++import Bar from './bar'+import MoreLink from './more-link'+import numberFormatter from '../number-formatter'+import * as api from '../api'++export default class Pages extends React.Component {+ constructor(props) {+ super(props)+ this.state = {+ loading: true+ }+ }++ componentDidMount() {+ this.fetchPages()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, pages: null})+ this.fetchPages()+ }+ }++ fetchPages() {+ api.get(`/api/stats/${this.props.site.domain}/pages`, this.props.query)+ .then((res) => this.setState({loading: false, pages: res}))+ }++ renderPage(page) {+ return (+ <React.Fragment key={page.name}>+ <div className="flex items-center justify-between my-2">+ <span className="truncate" style={{maxWidth: '80%'}}>{page.name}</span>+ <span>{numberFormatter(page.count)}</span>+ </div>+ <Bar count={page.count} all={this.state.pages} color="orange" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.pages) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Top Pages</h2>+ <div className="text-grey-darker mt-1">by pageviews</div>+ </div>++ <div className="mt-8">+ { this.state.pages.map(this.renderPage.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.pages} endpoint="pages" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/referrers.js b/assets/js/dashboard/stats/referrers.jsnew file mode 100644index 0000000000..c2b073ba21--- /dev/null+++ b/assets/js/dashboard/stats/referrers.js@@ -0,0 +1,66 @@+import React from 'react';+import { Link } from 'react-router-dom'++import Bar from './bar'+import MoreLink from './more-link'+import numberFormatter from '../number-formatter'+import * as api from '../api'++export default class Referrers extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchReferrers()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, referrers: null})+ this.fetchReferrers()+ }+ }++ fetchReferrers() {+ api.get(`/api/stats/${this.props.site.domain}/referrers`, this.props.query)+ .then((res) => this.setState({loading: false, referrers: res}))+ }++ renderReferrer(referrer) {+ return (+ <React.Fragment key={referrer.name}>+ <div className="flex items-center justify-between my-2">+ <Link className="hover:underline truncate" style={{maxWidth: '80%'}} to={`/${this.props.site.domain}/referrers/${referrer.name}${window.location.search}`}>{ referrer.name }</Link>+ <span>{numberFormatter(referrer.count)}</span>+ </div>+ <Bar count={referrer.count} all={this.state.referrers} color="blue" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.referrers) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Top Referrers</h2>+ <div className="text-grey-darker mt-1">by new visitors</div>+ </div>++ <div className="mt-8">+ { this.state.referrers.map(this.renderReferrer.bind(this)) }+ </div>+ <MoreLink site={this.props.site} list={this.state.referrers} endpoint="referrers" />+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/screen-sizes.js b/assets/js/dashboard/stats/screen-sizes.jsnew file mode 100644index 0000000000..c3ea74d187--- /dev/null+++ b/assets/js/dashboard/stats/screen-sizes.js@@ -0,0 +1,92 @@+import React from 'react';++import Bar from './bar'+import * as api from '../api'++const EXPLANATION = {+ 'Mobile': 'up to 576px',+ 'Tablet': '576px to 992px',+ 'Laptop': '992px to 1440px',+ 'Desktop': 'above 1440px',+}++function iconFor(screenSize) {+ if (screenSize === 'Mobile') {+ return (+ <svg width="16px" height="16px" style={{transform: 'translateY(3px)'}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-smartphone"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12" y2="18"/></svg>+ )+ } else if (screenSize === 'Tablet') {+ return (+ <svg width="16px" height="16px" style={{transform: 'translateY(3px)'}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-tablet"><rect x="4" y="2" width="16" height="20" rx="2" ry="2" transform="rotate(180 12 12)"/><line x1="12" y1="18" x2="12" y2="18"/></svg>+ )+ } else if (screenSize === 'Laptop') {+ return (+ <svg width="16px" height="16px" style={{transform: 'translateY(3px)'}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-laptop"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="2" y1="20" x2="22" y2="20"/></svg>+ )+ } else if (screenSize === 'Desktop') {+ return (+ <svg width="16px" height="16px" style={{transform: 'translateY(3px)'}} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-monitor"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>+ )+ }+}++export default class ScreenSizes extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchScreenSizes()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, sizes: null})+ this.fetchScreenSizes()+ }+ }++ fetchScreenSizes() {+ api.get(`/api/stats/${this.props.site.domain}/screen-sizes`, this.props.query)+ .then((res) => this.setState({loading: false, sizes: res}))+ }++ renderScreenSize(size) {+ return (+ <React.Fragment key={size.name}>+ <div className="flex items-center justify-between my-2">+ <span tooltip={EXPLANATION[size.name]}>+ { iconFor(size.name) }+ <span className="ml-1">{size.name}</span>+ </span>+ <span tooltip={`${size.count} visitors`}>{size.percentage}%</span>+ </div>+ <Bar count={size.count} all={this.state.sizes} color="teal" />+ </React.Fragment>+ )+ }++ render() {+ if (this.state.loading) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="loading my-32 mx-auto"><div></div></div>+ </div>+ )+ } else if (this.state.sizes) {+ return (+ <div className="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">+ <div className="text-center">+ <h2>Screen Sizes</h2>+ <div className="text-grey-darker mt-1">by visitors</div>+ </div>++ <div className="mt-8">+ { this.state.sizes.map(this.renderScreenSize.bind(this)) }+ </div>+ </div>+ )+ }+ }+}diff --git a/assets/js/dashboard/stats/visitor-graph.js b/assets/js/dashboard/stats/visitor-graph.jsnew file mode 100644index 0000000000..cefde53c08--- /dev/null+++ b/assets/js/dashboard/stats/visitor-graph.js@@ -0,0 +1,266 @@+import React from 'react';+import { withRouter } from 'react-router-dom'+import numberFormatter from '../number-formatter'+import { isToday, shiftMonths, formatMonth } from '../date'+import * as api from '../api'++function dataSets(graphData, ctx) {+ var gradient = ctx.createLinearGradient(0, 0, 0, 300);+ gradient.addColorStop(0, 'rgba(101,116,205, 0.2)');+ gradient.addColorStop(1, 'rgba(101,116,205, 0)');++ if (graphData.present_index) {+ var dashedPart = graphData.plot.slice(graphData.present_index - 1);+ var dashedPlot = (new Array(graphData.plot.length - dashedPart.length)).concat(dashedPart)+ for(var i = graphData.present_index; i < graphData.plot.length; i++) {+ graphData.plot[i] = undefined+ }++ return [{+ label: 'Visitors',+ data: graphData.plot,+ borderWidth: 3,+ borderColor: 'rgba(101,116,205)',+ pointBackgroundColor: 'rgba(101,116,205)',+ backgroundColor: gradient,+ },+ {+ label: 'Visitors',+ data: dashedPlot,+ borderWidth: 3,+ borderDash: [5, 10],+ borderColor: 'rgba(101,116,205)',+ pointBackgroundColor: 'rgba(101,116,205)',+ backgroundColor: gradient,+ }]+ } else {+ return [{+ label: 'Visitors',+ data: graphData.plot,+ borderWidth: 3,+ borderColor: 'rgba(101,116,205)',+ pointBackgroundColor: 'rgba(101,116,205)',+ backgroundColor: gradient,+ }]+ }+}++const MONTHS = [+ "January", "February", "March",+ "April", "May", "June", "July",+ "August", "September", "October",+ "November", "December"+]++function dateFormatter(graphData) {+ return function(isoDate) {+ const date = new Date(isoDate)++ if (graphData.interval === 'month') {+ return MONTHS[date.getUTCMonth()];+ } else if (graphData.interval === 'date') {+ return date.getUTCDate() + ' ' + MONTHS[date.getUTCMonth()];+ } else if (graphData.interval === 'hour') {+ var hours = date.getHours(); // Not sure why getUTCHours doesn't work here+ var ampm = hours >= 12 ? 'pm' : 'am';+ hours = hours % 12;+ hours = hours ? hours : 12; // the hour '0' should be '12'+ return hours + ampm;+ }+ }+}++class LineGraph extends React.Component {+ componentDidMount() {+ const {graphData} = this.props+ const ctx = document.getElementById("main-graph-canvas").getContext('2d');++ this.chart = new Chart(ctx, {+ type: 'line',+ data: {+ labels: graphData.labels,+ datasets: dataSets(graphData, ctx)+ },+ options: {+ animation: false,+ legend: {display: false},+ responsive: true,+ elements: {line: {tension: 0.1}, point: {radius: 0}},+ onClick: this.onClick.bind(this),+ tooltips: {+ mode: 'index',+ intersect: false,+ xPadding: 10,+ yPadding: 10,+ titleFontSize: 16,+ footerFontSize: 14,+ footerFontColor: '#e6e8ff',+ backgroundColor: 'rgba(25, 30, 56)',+ callbacks: {+ title: function(dataPoints) {+ var data = dataPoints[0]+ if (graphData.interval === 'month') {+ return data.yLabel.toLocaleString() + ' visitors in ' + data.xLabel+ } else if (graphData.interval === 'date') {+ return data.yLabel.toLocaleString() + ' visitors on ' + data.xLabel+ } else if (graphData.interval === 'hour') {+ return data.yLabel.toLocaleString() + ' visitors at ' + data.xLabel+ }+ },+ label: function() {},+ afterBody: function(dataPoints) {+ if (graphData.interval === 'month') {+ return 'Click to view month'+ } else if (graphData.interval === 'date') {+ return 'Click to view day'+ }+ }+ }+ },+ scales: {+ yAxes: [{+ ticks: {+ callback: numberFormatter,+ beginAtZero: true,+ autoSkip: true,+ maxTicksLimit: 8,+ },+ gridLines: {+ zeroLineColor: 'transparent',+ drawBorder: false,+ }+ }],+ xAxes: [{+ gridLines: {+ display: false,+ },+ ticks: {+ autoSkip: true,+ maxTicksLimit: 8,+ callback: dateFormatter(graphData),+ }+ }]+ }+ }+ });+ }++ onClick(e) {+ const element = this.chart.getElementsAtEventForMode(e, 'index', {intersect: false})[0]+ const date = element._chart.config.data.labels[element._index]+ if (this.props.graphData.interval === 'month') {+ this.props.history.push('?period=month&date=' + date)+ } else if (this.props.graphData.interval === 'date') {+ this.props.history.push('?period=day&date=' + date)+ }+ }++ comparisonTimeframe() {+ const {query, site} = this.props++ if (query.period === 'day') {+ if (isToday(site, query.date)) {+ return 'yesterday'+ } else {+ return 'previous day'+ }+ } else if (query.period === 'month') {+ return formatMonth(shiftMonths(query.date, -1))+ } else if (query.period === '7d') {+ return 'last week'+ } else if (query.period === '30d') {+ return 'last month'+ } else if (query.period === '3mo') {+ return 'previous 3 months'+ } else if (query.period === '6mo') {+ return 'previous 6 months'+ }+ }++ renderComparison(comparison) {+ const formattedComparison = numberFormatter(Math.abs(comparison))++ if (comparison > 0) {+ return <span className="py-1 text-xs text-grey-darker"><span className="text-green-dark">↑</span> {formattedComparison}% from {this.comparisonTimeframe()}</span>+ } else if (comparison < 0) {+ return <span className="py-1 text-xs text-grey-darker"><span className="text-red-light">↓</span> {formattedComparison}% from {this.comparisonTimeframe()}</span>+ } else if (comparison === 0) {+ return <span className="py-1 text-xs text-grey-darker">〰 same as {this.comparisonTimeframe()}</span>+ }+ }++ render() {+ const {graphData} = this.props+ const extraClass = graphData.interval === 'hour' ? '' : 'cursor-pointer'++ return (+ <React.Fragment>+ <div className="border-b border-grey-light flex p-4">+ <div className="border-r border-grey-light pl-2 w-52">+ <div className="text-grey-dark text-xs font-bold tracking-wide">UNIQUE VISITORS</div>+ <div className="my-1 flex items-end justify-between">+ <b className="text-2xl" title={graphData.unique_visitors.toLocaleString()}>{numberFormatter(graphData.unique_visitors)}</b>+ </div>+ {this.renderComparison(graphData.change_visitors)}+ </div>+ <div className="pl-8 w-60">+ <div className="text-grey-dark text-xs font-bold tracking-wide">TOTAL PAGEVIEWS</div>+ <div className="my-1 flex items-end justify-between">+ <b className="text-2xl" title={graphData.pageviews.toLocaleString()}>{numberFormatter(graphData.pageviews)}</b>+ </div>+ {this.renderComparison(graphData.change_pageviews)}+ </div>+ </div>+ <div className="p-4">+ <canvas id="main-graph-canvas" className={'mt-4 ' + extraClass} width="1054" height="342"></canvas>+ </div>+ </React.Fragment>+ )+ }+}++LineGraph = withRouter(LineGraph)++export default class VisitorGraph extends React.Component {+ constructor(props) {+ super(props)+ this.state = {loading: true}+ }++ componentDidMount() {+ this.fetchGraphData()+ }++ componentDidUpdate(prevProps) {+ if (this.props.query !== prevProps.query) {+ this.setState({loading: true, graphData: null})+ this.fetchGraphData()+ }+ }++ fetchGraphData() {+ api.get(`/api/stats/${this.props.site.domain}/main-graph`, this.props.query)+ .then((res) => {+ this.setState({loading: false, graphData: res})+ return res+ })+ }++ renderInner() {+ if (this.state.loading) {+ return (+ <div className="loading pt-24 sm:pt-32 md:pt-48 mx-auto"><div></div></div>+ )+ } else if (this.state.graphData) {+ return <LineGraph graphData={this.state.graphData} site={this.props.site} query={this.props.query} />+ }+ }++ render() {+ return (+ <div className="w-full bg-white shadow-md rounded mt-6 main-graph">+ { this.renderInner() }+ </div>+ )+ }+}diff --git a/assets/js/stats/index.js b/assets/js/stats/index.jsdeleted file mode 100644index 743a14c230..0000000000--- a/assets/js/stats/index.js+++ /dev/null@@ -1,146 +0,0 @@-import Router from './router'-import * as m from './modal'-import {renderMainGraph, renderComparisons} from './main-graph'--const SPINNER = `-<div class="loading my-48 mx-auto"><div></div></div>-`--function delayAtLeast(promise, time) {- const delayed = new Promise((resolve) => setTimeout(resolve, time))- return Promise.all([promise, delayed]).then(function(val) { return val[0] })-}--function fetchModal(modal, path) {- const promise = fetch(path)- m.setModalBody(modal, SPINNER)-- delayAtLeast(promise, 200)- .then(function(res) {- return res.text()- }).then(function(res) {- m.setModalBody(modal, res)- router.updateLinkHandlers()- })-}--const router = new Router()--function showModal(domain, endpoint) {- m.showModal({- onShow: function(modal) {- fetchModal(modal, endpoint + window.location.search)- },- onClose: function() {- router.navigate('/' + domain + window.location.search)- }- })-}--router- .on('/:domain/referrers/:referrer', function(params) {- showModal(params.domain, `/api/${params.domain}/referrers/${params.referrer}`)- })- .on('/:domain/referrers', function(params) {- showModal(params.domain, `/api/${params.domain}/referrers`)- })- .on('/:domain/pages', function(params) {- showModal(params.domain, `/api/${params.domain}/pages`)- })- .on('/:domain/countries', function(params) {- showModal(params.domain, `/api/${params.domain}/countries`)- })- .on('/:domain/operating-systems', function(params) {- showModal(params.domain, `/api/${params.domain}/operating-systems`)- })- .on('/:domain/browsers', function(params) {- showModal(params.domain, `/api/${params.domain}/browsers`)- })- .on('/:domain', function() {- m.ensureModalClosed()- })- .resolve();--const domainEl = document.querySelector('[data-site-domain]')-if (domainEl) {- const domain = domainEl.getAttribute('data-site-domain')-- const promises = []-- promises.push(- fetch(`/stats/${domain}/main-graph${location.search}`)- .then(res => res.json())- .then(res => renderMainGraph(res))- .then(graphData => fetch(`/api/${domain}/compare${location.search || '?'}&pageviews=${graphData.pageviews}&unique_visitors=${graphData.unique_visitors}`))- .then(res => res.json())- .then(res => renderComparisons(res))- )-- promises.push(- fetch(`/stats/${domain}/referrers${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('referrer-stats').innerHTML = res- router.updateLinkHandlers()- })- )-- promises.push(- fetch(`/stats/${domain}/pages${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('pages-stats').innerHTML = res- router.updateLinkHandlers()- })- )-- promises.push(- fetch(`/stats/${domain}/countries${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('countries-stats').innerHTML = res- router.updateLinkHandlers()- })- )-- Promise.all(promises).then(() => {- fetch(`/stats/${domain}/screen-sizes${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('screen-sizes-stats').innerHTML = res- router.updateLinkHandlers()- })-- fetch(`/stats/${domain}/operating-systems${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('operating-systems-stats').innerHTML = res- router.updateLinkHandlers()- })-- fetch(`/stats/${domain}/browsers${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('browsers-stats').innerHTML = res- router.updateLinkHandlers()- })-- if (document.getElementById('conversion-stats')) {- fetch(`/stats/${domain}/conversions${location.search}`)- .then(res => res.text())- .then((res) => {- document.getElementById('conversion-stats').innerHTML = res- router.updateLinkHandlers()- })- }- })-- setInterval(function() {- fetch(`/api/${domain}/current-visitors`)- .then(res => res.json())- .then((res) => {- console.log(res)- document.getElementById('current-visitors').innerHTML = res- })- }, 10000)-}diff --git a/assets/js/stats/main-graph.js b/assets/js/stats/main-graph.jsdeleted file mode 100644index fbb0dfb194..0000000000--- a/assets/js/stats/main-graph.js+++ /dev/null@@ -1,242 +0,0 @@-export function renderMainGraph(graphData) {- const extraClass = graphData.interval === 'hour' ? '' : 'cursor-pointer'-- const TEMPLATE = `- <div class="border-b border-grey-light flex p-4">- <div class="border-r border-grey-light pl-2 pr-10">- <div class="text-grey-dark text-sm font-bold tracking-wide">UNIQUE VISITORS</div>- <div class="mt-2 flex items-center justify-between" id="visitors">- <b class="text-2xl" title="${graphData.unique_visitors.toLocaleString()}">${numberFormatter(graphData.unique_visitors)}</b>- </div>- </div>- <div class="px-10">- <div class="text-grey-dark text-sm font-bold tracking-wide">TOTAL PAGEVIEWS</div>- <div class="mt-2 flex items-center justify-between" id="pageviews">- <b class="text-2xl" title="${graphData.pageviews.toLocaleString()}">${numberFormatter(graphData.pageviews)}</b>- </div>- </div>- </div>- <div class="p-4">- <canvas id="main-graph-canvas" class="mt-4 ${extraClass}" width="1054" height="329"></canvas>- </div>- `-- const mainGraphDiv = document.getElementById('main-graph')- mainGraphDiv.innerHTML = TEMPLATE- drawGraph(graphData)- return graphData-}--export function renderComparisons(comparisons) {- const visitorsDiv = document.getElementById('visitors')- const pageviewsDiv = document.getElementById('pageviews')-- if (comparisons.change_pageviews && comparisons.change_visitors) {- const formattedChangeVisitors = numberFormatter(Math.abs(comparisons.change_visitors))-- if (comparisons.change_visitors >= 0) {- visitorsDiv.innerHTML +=`- <span class="bg-green-lightest text-green-dark px-2 py-1 text-xs font-bold rounded">↑ ${formattedChangeVisitors}%</span>- `- } else if (comparisons.change_visitors < 0) {- visitorsDiv.innerHTML +=`- <span class="bg-red-lightest text-red-dark px-2 py-1 text-xs font-bold rounded">↓ ${formattedChangeVisitors}%</span>- `- }-- const formattedChangePageviews = numberFormatter(Math.abs(comparisons.change_pageviews))-- if (comparisons.change_pageviews >= 0) {- pageviewsDiv.innerHTML +=`- <span class="bg-green-lightest text-green-dark px-2 py-1 text-xs font-bold rounded">↑ ${formattedChangePageviews}%</span>- `- } else if (comparisons.change_pageviews < 0) {- pageviewsDiv.innerHTML +=`- <span class="bg-red-lightest text-red-dark px-2 py-1 text-xs font-bold rounded">↓ ${formattedChangePageviews}%</span>- `- }- } else {- visitorsDiv.innerHTML +=`- <span class="bg-grey-lightest text-grey-dark px-2 py-1 text-xs font-bold rounded">N/A</span>- `- pageviewsDiv.innerHTML +=`- <span class="bg-grey-lightest text-grey-dark px-2 py-1 text-xs font-bold rounded">N/A</span>- `- }-}--function dataSets(graphData, ctx) {- var gradient = ctx.createLinearGradient(0, 0, 0, 300);- gradient.addColorStop(0, 'rgba(101,116,205, 0.2)');- gradient.addColorStop(1, 'rgba(101,116,205, 0)');-- if (graphData.present_index) {- var dashedPart = graphData.plot.slice(graphData.present_index - 1);- var dashedPlot = (new Array(graphData.plot.length - dashedPart.length)).concat(dashedPart)- for(var i = graphData.present_index; i < graphData.plot.length; i++) {- graphData.plot[i] = undefined- }-- return [{- label: 'Visitors',- data: graphData.plot,- borderWidth: 3,- borderColor: 'rgba(101,116,205)',- pointBackgroundColor: 'rgba(101,116,205)',- backgroundColor: gradient,- },- {- label: 'Visitors',- data: dashedPlot,- borderWidth: 3,- borderDash: [5, 10],- borderColor: 'rgba(101,116,205)',- pointBackgroundColor: 'rgba(101,116,205)',- backgroundColor: gradient,- }]- } else {- return [{- label: 'Visitors',- data: graphData.plot,- borderWidth: 3,- borderColor: 'rgba(101,116,205)',- pointBackgroundColor: 'rgba(101,116,205)',- backgroundColor: gradient,- }]- }-}--function drawGraph(graphData) {- var ctx = document.getElementById("main-graph-canvas").getContext('2d');-- new Chart(ctx, {- type: 'line',- data: {- labels: graphData.labels,- datasets: dataSets(graphData, ctx)- },- options: {- animation: false,- legend: {display: false},- responsive: true,- elements: {line: {tension: 0.1}, point: {radius: 0}},- onClick: onClick(graphData),- tooltips: {- mode: 'index',- intersect: false,- xPadding: 10,- yPadding: 10,- titleFontSize: 16,- footerFontSize: 14,- footerFontColor: '#e6e8ff',- backgroundColor: 'rgba(25, 30, 56)',- callbacks: {- title: function(dataPoints) {- var data = dataPoints[0]- if (graphData.interval === 'month') {- return data.yLabel.toLocaleString() + ' visitors in ' + data.xLabel- } else if (graphData.interval === 'date') {- return data.yLabel.toLocaleString() + ' visitors on ' + data.xLabel- } else if (graphData.interval === 'hour') {- return data.yLabel.toLocaleString() + ' visitors at ' + data.xLabel- }- },- label: function() {},- afterBody: function(dataPoints) {- if (graphData.interval === 'month') {- return 'Click to view month'- } else if (graphData.interval === 'date') {- return 'Click to view day'- }- }- }- },- scales: {- yAxes: [{- ticks: {- callback: numberFormatter,- beginAtZero: true,- autoSkip: true,- maxTicksLimit: 8,- },- gridLines: {- zeroLineColor: 'transparent',- drawBorder: false,- }- }],- xAxes: [{- gridLines: {- display: false,- },- ticks: {- autoSkip: true,- maxTicksLimit: 8,- callback: dateFormatter(graphData),- }- }]- }- }- });-}--const THOUSAND = 1000-const HUNDRED_THOUSAND = 100000-const MILLION = 1000000-const HUNDRED_MILLION = 100000000--function numberFormatter(num) {- if (num >= THOUSAND && num < MILLION) {- const thousands = num / THOUSAND- if (thousands === Math.floor(thousands) || num >= HUNDRED_THOUSAND) {- return Math.floor(thousands) + 'k'- } else {- return (Math.floor(thousands * 10) / 10) + 'k'- }- } else if (num >= MILLION && num < HUNDRED_MILLION) {- const millions = num / MILLION- if (millions === Math.floor(millions)) {- return Math.floor(millions) + 'm'- } else {- return (Math.floor(millions * 10) / 10) + 'm'- }- } else {- return num- }-}--const MONTHS = [- "January", "February", "March",- "April", "May", "June", "July",- "August", "September", "October",- "November", "December"-]--function dateFormatter(graphData) {- return function(isoDate) {- const date = new Date(isoDate)-- if (graphData.interval === 'month') {- return MONTHS[date.getUTCMonth()];- } else if (graphData.interval === 'date') {- return date.getUTCDate() + ' ' + MONTHS[date.getUTCMonth()];- } else if (graphData.interval === 'hour') {- var hours = date.getHours(); // Not sure why getUTCHours doesn't work here- var ampm = hours >= 12 ? 'pm' : 'am';- hours = hours % 12;- hours = hours ? hours : 12; // the hour '0' should be '12'- return hours + ampm;- }- }-}--function onClick(graphData) {- return function(e) {- const element = this.getElementsAtEventForMode(e, 'index', {intersect: false})[0]- const date = element._chart.config.data.labels[element._index]- if (graphData.interval === 'month') {- document.location = '?period=month&date=' + date- } else if (graphData.interval === 'date') {- document.location = '?period=day&date=' + date- }- }-}diff --git a/assets/js/stats/modal.js b/assets/js/stats/modal.jsdeleted file mode 100644index 7dfaf4277c..0000000000--- a/assets/js/stats/modal.js+++ /dev/null@@ -1,47 +0,0 @@-const SPINNER = `-<div class="loading my-48 mx-auto"><div></div></div>-`--const EMPTY_MODAL = `-<div class="modal micromodal-slide" id="stats-modal" aria-hidden="true">- <div class="modal__overlay" tabindex="-1" data-micromodal-close>- <div class="modal__container"></div>- </div>-</div>-`--let el, instance;--export function showModal(callbacks) {- if (!el) {- const modal = document.createElement('div')- modal.innerHTML = EMPTY_MODAL- document.body.append(modal)- el = modal- }-- MicroModal.show('stats-modal', {- disableFocus: true,- disableScroll: true,- onShow: function(modal, e) {- instance = this- callbacks.onShow(modal)- },- onClose: function(modal) {- setModalBody(modal, '')- callbacks.onClose(modal)- }- })-}--export function setModalBody(modal, body) {- modal.children[0].children[0].innerHTML = body-}--export function ensureModalClosed() {- if (instance) {- const currentOnClose = instance.onClose- instance.onClose = function() {}- MicroModal.close('stats-modal')- }-}diff --git a/assets/js/stats/router.js b/assets/js/stats/router.jsdeleted file mode 100644index 3b11fcedf1..0000000000--- a/assets/js/stats/router.js+++ /dev/null@@ -1,81 +0,0 @@-const PARAMETER_REGEXP = /([:*])(\w+)/g;-const REPLACE_VARIABLE_REGEXP = '([^\/]+)';--export default class Router {- constructor() {- this.routes = []- this.updateLinkHandlers()- window.addEventListener('popstate', this.resolve.bind(this));- }-- on(path, handler) {- const {regex, paramNames} = this._generateRouteRegex(path)- this.routes.push({regex, paramNames, handler})- return this- }-- resolve() {- const match = this._matchRoute()- if (match) {- match.route.handler(match.params)- }- return this- }-- navigate(to) {- history.pushState({}, '', to)- this.resolve()- }-- updateLinkHandlers() {- const self = this- const links = document.querySelectorAll('[data-pushstate]')-- for (const link of links) {- if (!link.hasListenerAttached) {- link.addEventListener('click', function (e) {- if (e.ctrlKey || e.metaKey) {- return false;- }-- e.preventDefault();- const location = link.getAttribute('href');;- self.navigate(location.replace(/\/+$/, '').replace(/^\/+/, '/'));- })-- link.hasListenerAttached = true;- }- }- }-- _matchRoute() {- const currentPath = window.location.pathname-- for (const route of this.routes) {- const match = currentPath.replace(/^\/+/, '/').match(route.regex)-- if (match) {- const params = this._extractParams(match, route.paramNames)- return {route, params}- }- }- }-- _generateRouteRegex(path) {- const paramNames = []- const regex = path.replace(PARAMETER_REGEXP, function (full, dots, name) {- paramNames.push(name);- return REPLACE_VARIABLE_REGEXP;- })- return {regex: new RegExp(regex), paramNames}- }-- _extractParams(match, paramNames) {- return match.slice(1, match.length).reduce(function(params, value, index) {- if (params === null) params = {};- params[paramNames[index]] = decodeURIComponent(value);- return params;- }, null);- }-}-diff --git a/assets/package-lock.json b/assets/package-lock.jsonindex 97982eae9c..6400473e41 100644--- a/assets/package-lock.json+++ b/assets/package-lock.json@@ -65,6 +65,29 @@"@babel/types": "^7.0.0"}},+ "@babel/helper-builder-react-jsx": {+ "version": "7.7.0",+ "resolved": "https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.7.0.tgz",+ "integrity": "sha512-LSln3cexwInTMYYoFeVLKnYPPMfWNJ8PubTBs3hkh7wCu9iBaqq1OOyW+xGmEdLxT1nhsl+9SJ+h2oUDYz0l2A==",+ "dev": true,+ "requires": {+ "@babel/types": "^7.7.0",+ "esutils": "^2.0.0"+ },+ "dependencies": {+ "@babel/types": {+ "version": "7.7.1",+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.7.1.tgz",+ "integrity": "sha512-kN/XdANDab9x1z5gcjDc9ePpxexkt+1EQ2MQUiM4XnMvQfvp87/+6kY4Ko2maLXH+tei/DgJ/ybFITeqqRwDiA==",+ "dev": true,+ "requires": {+ "esutils": "^2.0.2",+ "lodash": "^4.17.13",+ "to-fast-properties": "^2.0.0"+ }+ }+ }+ },"@babel/helper-call-delegate": {"version": "7.4.4","resolved": "https://registry.npmjs.org/@babel/helper-call-delegate/-/helper-call-delegate-7.4.4.tgz",@@ -355,6 +378,15 @@"@babel/helper-plugin-utils": "^7.0.0"}},+ "@babel/plugin-syntax-jsx": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.2.0.tgz",+ "integrity": "sha512-VyN4QANJkRW6lDBmENzRszvZf3/4AXaj9YR7GwrWeeN9tEBPuXbmDYVU9bYBN0D70zCWVwUy0HWq2553VCb6Hw==",+ "dev": true,+ "requires": {+ "@babel/helper-plugin-utils": "^7.0.0"+ }+ },"@babel/plugin-syntax-object-rest-spread": {"version": "7.2.0","resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz",@@ -605,6 +637,46 @@"@babel/helper-plugin-utils": "^7.0.0"}},+ "@babel/plugin-transform-react-display-name": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.2.0.tgz",+ "integrity": "sha512-Htf/tPa5haZvRMiNSQSFifK12gtr/8vwfr+A9y69uF0QcU77AVu4K7MiHEkTxF7lQoHOL0F9ErqgfNEAKgXj7A==",+ "dev": true,+ "requires": {+ "@babel/helper-plugin-utils": "^7.0.0"+ }+ },+ "@babel/plugin-transform-react-jsx": {+ "version": "7.7.0",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.7.0.tgz",+ "integrity": "sha512-mXhBtyVB1Ujfy+0L6934jeJcSXj/VCg6whZzEcgiiZHNS0PGC7vUCsZDQCxxztkpIdF+dY1fUMcjAgEOC3ZOMQ==",+ "dev": true,+ "requires": {+ "@babel/helper-builder-react-jsx": "^7.7.0",+ "@babel/helper-plugin-utils": "^7.0.0",+ "@babel/plugin-syntax-jsx": "^7.2.0"+ }+ },+ "@babel/plugin-transform-react-jsx-self": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.2.0.tgz",+ "integrity": "sha512-v6S5L/myicZEy+jr6ielB0OR8h+EH/1QFx/YJ7c7Ua+7lqsjj/vW6fD5FR9hB/6y7mGbfT4vAURn3xqBxsUcdg==",+ "dev": true,+ "requires": {+ "@babel/helper-plugin-utils": "^7.0.0",+ "@babel/plugin-syntax-jsx": "^7.2.0"+ }+ },+ "@babel/plugin-transform-react-jsx-source": {+ "version": "7.5.0",+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.5.0.tgz",+ "integrity": "sha512-58Q+Jsy4IDCZx7kqEZuSDdam/1oW8OdDX8f+Loo6xyxdfg1yF0GE2XNJQSTZCaMol93+FBzpWiPEwtbMloAcPg==",+ "dev": true,+ "requires": {+ "@babel/helper-plugin-utils": "^7.0.0",+ "@babel/plugin-syntax-jsx": "^7.2.0"+ }+ },"@babel/plugin-transform-regenerator": {"version": "7.4.5","resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.4.5.tgz",@@ -739,6 +811,34 @@"semver": "^5.5.0"}},+ "@babel/preset-react": {+ "version": "7.7.0",+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.7.0.tgz",+ "integrity": "sha512-IXXgSUYBPHUGhUkH+89TR6faMcBtuMW0h5OHbMuVbL3/5wK2g6a2M2BBpkLa+Kw0sAHiZ9dNVgqJMDP/O4GRBA==",+ "dev": true,+ "requires": {+ "@babel/helper-plugin-utils": "^7.0.0",+ "@babel/plugin-transform-react-display-name": "^7.0.0",+ "@babel/plugin-transform-react-jsx": "^7.7.0",+ "@babel/plugin-transform-react-jsx-self": "^7.0.0",+ "@babel/plugin-transform-react-jsx-source": "^7.0.0"+ }+ },+ "@babel/runtime": {+ "version": "7.7.2",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.7.2.tgz",+ "integrity": "sha512-JONRbXbTXc9WQE2mAZd1p0Z3DZ/6vaQIkgYMSTP3KjRCyd7rCZCcfhCyX+YjwcKxcZ82UrxbRD358bpExNgrjw==",+ "requires": {+ "regenerator-runtime": "^0.13.2"+ },+ "dependencies": {+ "regenerator-runtime": {+ "version": "0.13.3",+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz",+ "integrity": "sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw=="+ }+ }+ },"@babel/template": {"version": "7.4.4","resolved": "https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz",@@ -1132,7 +1232,7 @@},"util": {"version": "0.10.3",- "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz",+ "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz","integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=","dev": true,"requires": {@@ -3975,6 +4075,11 @@"integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==","dev": true},+ "gud": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/gud/-/gud-1.0.0.tgz",+ "integrity": "sha512-zGEOVKFM5sVPPrYs7J5/hYEw2Pof8KCyOwyhG8sAF26mCAeUFAcYPu1mwB7hhpIP29zOIBaDqwuHdLp0jvZXjw=="+ },"has": {"version": "1.0.3","resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",@@ -4062,6 +4167,19 @@"integrity": "sha512-l9sfDFsuqtOqKDsQdqrMRk0U85RZc0RtOR9yPI7mRVOa4FsR/BVnZ0shmQRM96Ji99kYZP/7hn1cedc1+ApsTQ==","dev": true},+ "history": {+ "version": "4.10.1",+ "resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz",+ "integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==",+ "requires": {+ "@babel/runtime": "^7.1.2",+ "loose-envify": "^1.2.0",+ "resolve-pathname": "^3.0.0",+ "tiny-invariant": "^1.0.2",+ "tiny-warning": "^1.0.0",+ "value-equal": "^1.0.1"+ }+ },"hmac-drbg": {"version": "1.0.1","resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz",@@ -4073,6 +4191,14 @@"minimalistic-crypto-utils": "^1.0.1"}},+ "hoist-non-react-statics": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.0.tgz",+ "integrity": "sha512-0XsbTXxgiaCDYDIWFcwkmerZPSwywfUqYmwT4jzewKTQSWoE6FCMoUVOeBJWK3E/CrWbxRG3m5GzY4lnIwGRBA==",+ "requires": {+ "react-is": "^16.7.0"+ }+ },"homedir-polyfill": {"version": "1.0.3","resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz",@@ -4552,8 +4678,7 @@"js-tokens": {"version": "4.0.0","resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",- "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",- "dev": true+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="},"js-yaml": {"version": "3.13.1",@@ -4645,7 +4770,7 @@"dependencies": {"json5": {"version": "0.5.1",- "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz",+ "resolved": "http://registry.npmjs.org/json5/-/json5-0.5.1.tgz","integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=","dev": true}@@ -4689,7 +4814,6 @@"version": "1.4.0","resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz","integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "dev": true,"requires": {"js-tokens": "^3.0.0 || ^4.0.0"}@@ -4818,6 +4942,16 @@"integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==","dev": true},+ "mini-create-react-context": {+ "version": "0.3.2",+ "resolved": "https://registry.npmjs.org/mini-create-react-context/-/mini-create-react-context-0.3.2.tgz",+ "integrity": "sha512-2v+OeetEyliMt5VHMXsBhABoJ0/M4RCe7fatd/fBy6SMiKazUSEt3gxxypfnk2SHMkdBYvorHRoQxuGoiwbzAw==",+ "requires": {+ "@babel/runtime": "^7.4.0",+ "gud": "^1.0.0",+ "tiny-warning": "^1.0.2"+ }+ },"mini-css-extract-plugin": {"version": "0.8.0","resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-0.8.0.tgz",@@ -5076,8 +5210,7 @@"object-assign": {"version": "4.1.1","resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",- "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",- "dev": true+ "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="},"object-copy": {"version": "0.1.0",@@ -5335,6 +5468,21 @@"integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==","dev": true},+ "path-to-regexp": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz",+ "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==",+ "requires": {+ "isarray": "0.0.1"+ },+ "dependencies": {+ "isarray": {+ "version": "0.0.1",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",+ "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="+ }+ }+ },"path-type": {"version": "3.0.0","resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz",@@ -5430,7 +5578,7 @@},"chalk": {"version": "1.1.3",- "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",+ "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz","integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=","dev": true,"requires": {@@ -7681,6 +7829,16 @@"integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=","dev": true},+ "prop-types": {+ "version": "15.7.2",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",+ "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",+ "requires": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.8.1"+ }+ },"prr": {"version": "1.0.1","resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz",@@ -7787,6 +7945,63 @@"safe-buffer": "^5.1.0"}},+ "react": {+ "version": "16.11.0",+ "resolved": "https://registry.npmjs.org/react/-/react-16.11.0.tgz",+ "integrity": "sha512-M5Y8yITaLmU0ynd0r1Yvfq98Rmll6q8AxaEe88c8e7LxO8fZ2cNgmFt0aGAS9wzf1Ao32NKXtCl+/tVVtkxq6g==",+ "requires": {+ "loose-envify": "^1.1.0",+ "object-assign": "^4.1.1",+ "prop-types": "^15.6.2"+ }+ },+ "react-dom": {+ "version": "16.11.0",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.11.0.tgz",+ "integrity": "sha512-nrRyIUE1e7j8PaXSPtyRKtz+2y9ubW/ghNgqKFHHAHaeP0fpF5uXR+sq8IMRHC+ZUxw7W9NyCDTBtwWxvkb0iA==",+ "requires": {+ "loose-envify": "^1.1.0",+ "object-assign": "^4.1.1",+ "prop-types": "^15.6.2",+ "scheduler": "^0.17.0"+ }+ },+ "react-is": {+ "version": "16.11.0",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.11.0.tgz",+ "integrity": "sha512-gbBVYR2p8mnriqAwWx9LbuUrShnAuSCNnuPGyc7GJrMVQtPDAh8iLpv7FRuMPFb56KkaVZIYSz1PrjI9q0QPCw=="+ },+ "react-router": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/react-router/-/react-router-5.1.2.tgz",+ "integrity": "sha512-yjEuMFy1ONK246B+rsa0cUam5OeAQ8pyclRDgpxuSCrAlJ1qN9uZ5IgyKC7gQg0w8OM50NXHEegPh/ks9YuR2A==",+ "requires": {+ "@babel/runtime": "^7.1.2",+ "history": "^4.9.0",+ "hoist-non-react-statics": "^3.1.0",+ "loose-envify": "^1.3.1",+ "mini-create-react-context": "^0.3.0",+ "path-to-regexp": "^1.7.0",+ "prop-types": "^15.6.2",+ "react-is": "^16.6.0",+ "tiny-invariant": "^1.0.2",+ "tiny-warning": "^1.0.0"+ }+ },+ "react-router-dom": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.1.2.tgz",+ "integrity": "sha512-7BPHAaIwWpZS074UKaw1FjVdZBSVWEk8IuDXdB+OkLb8vd/WRQIpA4ag9WQk61aEfQs47wHyjWUoUGGZxpQXew==",+ "requires": {+ "@babel/runtime": "^7.1.2",+ "history": "^4.9.0",+ "loose-envify": "^1.3.1",+ "prop-types": "^15.6.2",+ "react-router": "5.1.2",+ "tiny-invariant": "^1.0.2",+ "tiny-warning": "^1.0.0"+ }+ },"read-file-stdin": {"version": "0.2.1","resolved": "https://registry.npmjs.org/read-file-stdin/-/read-file-stdin-0.2.1.tgz",@@ -7899,7 +8114,7 @@"dependencies": {"jsesc": {"version": "0.5.0",- "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz",+ "resolved": "http://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz","integrity": "sha1-597mbjXW/Bb3EP6R1c9p9w8IkR0=","dev": true}@@ -7988,6 +8203,11 @@"integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=","dev": true},+ "resolve-pathname": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/resolve-pathname/-/resolve-pathname-3.0.0.tgz",+ "integrity": "sha512-C7rARubxI8bXFNB/hqcp/4iUeIXJhJZvFPFPiSPRnhU5UPxzMFIl+2E6yY6c4k9giDJAhtV+enfA+G89N6Csng=="+ },"resolve-url": {"version": "0.2.1","resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz",@@ -8061,6 +8281,15 @@"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==","dev": true},+ "scheduler": {+ "version": "0.17.0",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.17.0.tgz",+ "integrity": "sha512-7rro8Io3tnCPuY4la/NuI5F2yfESpnfZyT6TtkXnSWVkcu0BCDJ+8gk5ozUaFaxpIyNuWAPXrH0yFcSi28fnDA==",+ "requires": {+ "loose-envify": "^1.1.0",+ "object-assign": "^4.1.1"+ }+ },"schema-utils": {"version": "1.0.0","resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz",@@ -8493,7 +8722,7 @@},"strip-ansi": {"version": "3.0.1",- "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",+ "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz","integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=","dev": true,"requires": {@@ -8855,6 +9084,16 @@"integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=","dev": true},+ "tiny-invariant": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.0.6.tgz",+ "integrity": "sha512-FOyLWWVjG+aC0UqG76V53yAWdXfH8bO6FNmyZOuUrzDzK8DI3/JRY25UD7+g49JWM1LXwymsKERB+DzI0dTEQA=="+ },+ "tiny-warning": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tiny-warning/-/tiny-warning-1.0.3.tgz",+ "integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA=="+ },"to-arraybuffer": {"version": "1.0.1","resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",@@ -9217,6 +9456,11 @@"integrity": "sha512-CNmdbwQMBjwr9Gsmohvm0pbL954tJrNzf6gWL3K+QMQf00PF7ERGrEiLgjuU3mKreLC2MeGhUsNV9ybTbLgd3w==","dev": true},+ "value-equal": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/value-equal/-/value-equal-1.0.1.tgz",+ "integrity": "sha512-NOJ6JZCAWr0zlxZt+xqCHNTEKOsrks2HQd4MqhP1qy4z1SkbEP467eNx6TgDKXMvUOb+OENfJCZwM+16n7fRfw=="+ },"vendors": {"version": "1.0.2","resolved": "https://registry.npmjs.org/vendors/-/vendors-1.0.2.tgz",diff --git a/assets/package.json b/assets/package.jsonindex 790f105332..2a4bd84e34 100644--- a/assets/package.json+++ b/assets/package.json@@ -8,11 +8,15 @@"dependencies": {"autoprefixer": "^9.6.1","phoenix": "file:../deps/phoenix",- "phoenix_html": "file:../deps/phoenix_html"+ "phoenix_html": "file:../deps/phoenix_html",+ "react": "^16.11.0",+ "react-dom": "^16.11.0",+ "react-router-dom": "^5.1.2"},"devDependencies": {"@babel/core": "^7.5.5","@babel/preset-env": "^7.5.5",+ "@babel/preset-react": "^7.7.0","babel-loader": "^8.0.6","copy-webpack-plugin": "^5.0.4","css-loader": "^3.2.0",diff --git a/assets/tailwind.js b/assets/tailwind.jsindex 8ba7b17834..0e12dc19e6 100644--- a/assets/tailwind.js+++ b/assets/tailwind.js@@ -483,6 +483,8 @@ module.exports = {'24': '6rem','32': '8rem','48': '12rem',+ '52': '13rem',+ '60': '15rem','64': '16rem','1/2': '50%','31percent': '31%',diff --git a/assets/webpack.config.js b/assets/webpack.config.jsindex bce37233a4..440c89afd5 100644--- a/assets/webpack.config.js+++ b/assets/webpack.config.js@@ -15,6 +15,7 @@ module.exports = (env, options) => ({},entry: {'app': ['./js/app.js'],+ 'dashboard': ['./js/dashboard/mount.js'],'p': ['./js/p.js'],'analytics': ['./js/plausible.js'],'plausible': ['./js/plausible.js']@@ -26,7 +27,7 @@ module.exports = (env, options) => ({module: {rules: [{- test: /\.js$/,+ test: /\.(js|jsx)$/,exclude: /node_modules/,use: {loader: 'babel-loader'diff --git a/config/config.exs b/config/config.exsindex 59d738f8cd..8e2254dca6 100644--- a/config/config.exs+++ b/config/config.exs@@ -14,7 +14,10 @@ config :plausible,config :plausible, PlausibleWeb.Endpoint,url: [host: "localhost"],secret_key_base: "/NJrhNtbyCVAsTyvtk1ZYCwfm981Vpo/0XrVwjJvemDaKC/vsvBRevLwsc6u8RCg",- render_errors: [view: PlausibleWeb.ErrorView, accepts: ~w(html json)],+ render_errors: [+ view: PlausibleWeb.ErrorView,+ accepts: ~w(html json)+ ],pubsub: [name: Plausible.PubSub, adapter: Phoenix.PubSub.PG2]config :sentry,diff --git a/config/dev.exs b/config/dev.exsindex 887d713988..e1fb676a4b 100644--- a/config/dev.exs+++ b/config/dev.exs@@ -45,6 +45,6 @@ config :plausible, Plausible.Repo,config :plausible, Plausible.Mailer,adapter: Bamboo.LocalAdapter-if File.exists?("dev.secret.exs") do+if File.exists?("config/dev.secret.exs") doimport_config "dev.secret.exs"enddiff --git a/lib/plausible/google/api.ex b/lib/plausible/google/api.exindex 6a6f2f7d1a..39c77bc75a 100644--- a/lib/plausible/google/api.ex+++ b/lib/plausible/google/api.ex@@ -39,7 +39,7 @@ defmodule Plausible.Google.Api do200 ->terms = (Jason.decode!(res.body)["rows"] || [])|> Enum.filter(fn row -> row["clicks"] > 0 end)- |> Enum.map(fn row -> {row["keys"], round(row["clicks"])} end)+ |> Enum.map(fn row -> %{name: row["keys"], count: round(row["clicks"])} end){:ok, terms}401 ->diff --git a/lib/plausible/stats/query.ex b/lib/plausible/stats/query.exindex 5d596b8d83..c5b779ace0 100644--- a/lib/plausible/stats/query.ex+++ b/lib/plausible/stats/query.ex@@ -62,20 +62,19 @@ defmodule Plausible.Stats.Query do}end- def from(_tz, %{"period" => "month", "date" => month_start}) do- start_date = Date.from_iso8601!(month_start) |> Timex.beginning_of_month- end_date = Timex.end_of_month(start_date)+ def from(tz, %{"period" => "30d"}) do+ end_date = today(tz)+ start_date = end_date |> Timex.shift(days: -30)%__MODULE__{- period: "month",+ period: "30d",date_range: Date.range(start_date, end_date),- step_type: "date",- steps: Timex.diff(start_date, end_date, :days)+ step_type: "date"}end- def from(tz, %{"period" => "month"}) do- start_date = today(tz) |> Timex.beginning_of_month+ def from(_tz, %{"period" => "month", "date" => month_start}) do+ start_date = Date.from_iso8601!(month_start) |> Timex.beginning_of_monthend_date = Timex.end_of_month(start_date)%__MODULE__{diff --git a/lib/plausible/stats/stats.ex b/lib/plausible/stats/stats.exindex 2186cbb506..3ad3709daa 100644--- a/lib/plausible/stats/stats.ex+++ b/lib/plausible/stats/stats.ex@@ -5,13 +5,17 @@ defmodule Plausible.Stats dodef compare_pageviews_and_visitors(site, query, {pageviews, visitors}) doquery = Query.shift_back(query){old_pageviews, old_visitors} = pageviews_and_visitors(site, query)- if old_visitors > 0 do- {- round((pageviews - old_pageviews) / old_pageviews * 100),- round((visitors - old_visitors) / old_visitors * 100),- }- else- {nil, nil}+ cond do+ old_pageviews == 0 and pageviews > 0 ->+ {100, 100}+ old_pageviews == 0 and pageviews == 0 ->+ {0, 0}+ true ->+ {+ round((pageviews - old_pageviews) / old_pageviews * 100),+ round((visitors - old_visitors) / old_visitors * 100),+ }+endend@@ -92,7 +96,7 @@ defmodule Plausible.Stats dodef top_referrers(site, query, limit \\ 5) doRepo.all(from e in base_query(site, query),- select: {e.referrer_source, count(e.referrer_source)},+ select: %{name: e.referrer_source, count: count(e.referrer_source)},group_by: e.referrer_source,where: e.new_visitor == true and not is_nil(e.referrer_source),order_by: [desc: 2],@@ -101,7 +105,8 @@ defmodule Plausible.Stats doenddef visitors_from_referrer(site, query, referrer) do- Repo.one(from e in base_query(site, query),+ Repo.one(+ from e in base_query(site, query),select: count(e),where: e.new_visitor == true and e.referrer_source == ^referrer)@@ -109,7 +114,7 @@ defmodule Plausible.Stats dodef referrer_drilldown(site, query, referrer) doRepo.all(from e in base_query(site, query),- select: {e.referrer, count(e)},+ select: %{name: e.referrer, count: count(e)},group_by: e.referrer,where: e.new_visitor == true and e.referrer_source == ^referrer,order_by: [desc: 2],@@ -119,7 +124,7 @@ defmodule Plausible.Stats dodef top_pages(site, query, limit \\ 5) doRepo.all(from e in base_query(site, query),- select: {e.pathname, count(e.pathname)},+ select: %{name: e.pathname, count: count(e.pathname)},group_by: e.pathname,order_by: [desc: count(e.pathname)],limit: ^limit@@ -129,7 +134,7 @@ defmodule Plausible.Stats do@available_screen_sizes ["Desktop", "Laptop", "Tablet", "Mobile"]def top_screen_sizes(site, query) do- sizes = Repo.all(from e in base_query(site, query),+ Repo.all(from e in base_query(site, query),select: {e.screen_size, count(e.screen_size)},group_by: e.screen_size,where: e.new_visitor == true and not is_nil(e.screen_size)@@ -144,11 +149,17 @@ defmodule Plausible.Stats dodefp add_percentages(stat_list) dototal = Enum.reduce(stat_list, 0, fn {_, count}, total -> total + count end)- Enum.map(stat_list, fn {stat, count} -> {stat, count, round(count / total * 100)} end)+ Enum.map(stat_list, fn {stat, count} ->+ %{+ name: stat,+ count: count,+ percentage: round(count / total * 100)+ }+ end)enddef countries(site, query, limit \\ 5) do- countries = Repo.all(from e in base_query(site, query),+ Repo.all(from e in base_query(site, query),select: {e.country_code, count(e.country_code)},group_by: e.country_code,where: e.new_visitor == true and not is_nil(e.country_code),@@ -216,7 +227,7 @@ defmodule Plausible.Stats dowhere: e.timestamp >= ^first_datetime and e.timestamp < ^last_datetime,where: e.name in ^events,group_by: e.name,- select: {e.name, count(e.user_id, :distinct)}+ select: %{name: e.name, count: count(e.user_id, :distinct)})else[]@@ -241,7 +252,7 @@ defmodule Plausible.Stats dowhere: e.name == "pageview",where: e.pathname in ^pages,group_by: e.pathname,- select: {fragment("concat('Visit ', ?)", e.pathname), count(e.user_id, :distinct)}+ select: %{name: fragment("concat('Visit ', ?)", e.pathname), count: count(e.user_id, :distinct)})else[]@@ -249,7 +260,7 @@ defmodule Plausible.Stats doenddefp sort_conversions(conversions) do- Enum.sort_by(conversions, fn {_, count} -> -count end)+ Enum.sort_by(conversions, fn conversion -> -conversion[:count] end)enddefp base_query(site, query) dodiff --git a/lib/plausible_web/controllers/api/stats_controller.ex b/lib/plausible_web/controllers/api/stats_controller.exnew file mode 100644index 0000000000..8ac28b86b5--- /dev/null+++ b/lib/plausible_web/controllers/api/stats_controller.ex@@ -0,0 +1,168 @@+defmodule PlausibleWeb.Api.StatsController do+ use PlausibleWeb, :controller+ use Plausible.Repo+ alias Plausible.Stats+ plug :authorize++ def main_graph(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ plot_task = Task.async(fn -> Stats.calculate_plot(site, query) end)+ {pageviews, visitors} = Stats.pageviews_and_visitors(site, query)+ {change_pageviews, change_visitors} = Stats.compare_pageviews_and_visitors(site, query, {pageviews, visitors})+ {plot, labels, present_index} = Task.await(plot_task)++ json(conn, %{+ plot: plot,+ labels: labels,+ present_index: present_index,+ pageviews: pageviews,+ unique_visitors: visitors,+ change_pageviews: change_pageviews,+ change_visitors: change_visitors,+ interval: query.step_type+ })+ end++ def referrers(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.top_referrers(site, query, params["limit"] || 5))+ end++ def referrer_drilldown(conn, %{"referrer" => "Google"} = params) do+ site = conn.assigns[:site] |> Repo.preload(:google_auth)+ query = Stats.Query.from(site.timezone, params)++ search_terms = if site.google_auth && site.google_auth.property do+ Plausible.Google.Api.fetch_stats(site.google_auth, query)+ end++ case search_terms do+ nil ->+ total_visitors = Stats.visitors_from_referrer(site, query, "Google")+ user_id = get_session(conn, :current_user_id)+ is_owner = user_id && Plausible.Sites.is_owner?(user_id, site)+ json(conn, %{not_configured: true, is_owner: is_owner, total_visitors: total_visitors})+ {:ok, terms} ->+ total_visitors = Stats.visitors_from_referrer(site, query, "Google")+ json(conn, %{search_terms: terms, total_visitors: total_visitors})+ {:error, e} ->+ put_status(conn, 500)+ |> json(%{error: e})+ end+ end++ def referrer_drilldown(conn, %{"referrer" => referrer} = params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ referrers = Stats.referrer_drilldown(site, query, referrer)+ total_visitors = Stats.visitors_from_referrer(site, query, referrer)+ json(conn, %{referrers: referrers, total_visitors: total_visitors})+ end++ def pages(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.top_pages(site, query, params["limit"] || 5))+ end++ def countries(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.countries(site, query, parse_integer(params["limit"]) || 5))+ end++ def browsers(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.browsers(site, query, parse_integer(params["limit"]) || 5))+ end++ def operating_systems(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.operating_systems(site, query, parse_integer(params["limit"]) || 5))+ end++ def screen_sizes(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.top_screen_sizes(site, query))+ end++ def conversions(conn, params) do+ site = conn.assigns[:site]+ query = Stats.Query.from(site.timezone, params)++ json(conn, Stats.goal_conversions(site, query))+ end++ def current_visitors(conn, _) do+ json(conn, Stats.current_visitors(conn.assigns[:site]))+ end++ defp parse_integer(nil), do: nil++ defp parse_integer(nr) do+ case Integer.parse(nr) do+ {number, ""} -> number+ _ -> nil+ end+ end++ @doc """+ When the stats dashboard is loaded we make > 8 API calls. Instead of hitting the DB to authorize each+ request we 'memoize' the fact that the current user has access to the site stats. It is invalidated+ every 30 minutes and we hit the DB again to make sure their access hasn't been revoked.+ """+ def authorize(conn, _opts) do+ site_session_key = "authorized_site__" <> conn.params["domain"]+ user_id = get_session(conn, :current_user_id)++ case get_session(conn, site_session_key) do+ nil ->+ verify_access_via_db(conn, user_id, site_session_key)+ site_session ->+ if site_session[:valid_until] > DateTime.to_unix(Timex.now()) do+ assign(conn, :site, %Plausible.Site{+ id: site_session[:id],+ domain: site_session[:domain],+ timezone: site_session[:timezone]+ })+ else+ verify_access_via_db(conn, user_id, site_session_key)+ end+ end+ end++ defp verify_access_via_db(conn, user_id, site_session_key) do+ site = Repo.get_by(Plausible.Site, domain: conn.params["domain"])++ if !site do+ send_resp(conn, 401, "") |> halt+ else+ can_access = site.public || (user_id && Plausible.Sites.is_owner?(user_id, site))++ if !can_access do+ send_resp(conn, 401, "") |> halt+ else+ put_session(conn, site_session_key, %{+ id: site.id,+ domain: site.domain,+ timezone: site.timezone,+ valid_until: Timex.now() |> Timex.shift(minutes: 30) |> DateTime.to_unix()+ })+ |> assign(:site, site)+ end+ end+ end+enddiff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.exindex e23ae749aa..82b7cbe49e 100644--- a/lib/plausible_web/controllers/stats_controller.ex+++ b/lib/plausible_web/controllers/stats_controller.ex@@ -1,12 +1,6 @@defmodule PlausibleWeb.StatsController douse PlausibleWeb, :controlleruse Plausible.Repo- alias Plausible.Stats-- defp referrer_link(site, {name, count}, query) do- link = "/#{site.domain}/referrers/#{name}" <> PlausibleWeb.StatsView.query_params(query)- {{:link, name, link}, count}- enddef stats(conn, %{"website" => website}) dosite = Repo.get_by(Plausible.Site, domain: website)@@ -21,9 +15,6 @@ defmodule PlausibleWeb.StatsController doPlausible.Tracking.event(conn, "Site Analytics: Open", %{demo: site.domain == "plausible.io"})- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- current_visitors = Stats.current_visitors(site)has_goals = user && Plausible.Sites.has_goals?(site)conn@@ -32,8 +23,6 @@ defmodule PlausibleWeb.StatsController do|> render("stats.html",site: site,has_goals: has_goals,- query: query,- current_visitors: current_visitors,title: "Plausible · " <> site.domain,offer_email_report: offer_email_report)@@ -48,283 +37,6 @@ defmodule PlausibleWeb.StatsController doendend- def browsers_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "browsers_preview.html",- browsers: Stats.browsers(site, query),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def operating_systems_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "operating_systems_preview.html",- operating_systems: Stats.operating_systems(site, query),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def screen_sizes_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "screen_sizes_preview.html",- top_screen_sizes: Stats.top_screen_sizes(site, query),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def referrers_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "referrers_preview.html",- top_referrers: Stats.top_referrers(site, query) |> Enum.map(&(referrer_link(site, &1, query))),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def pages_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "pages_preview.html",- top_pages: Stats.top_pages(site, query),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def countries_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- if site && current_user_can_access?(conn, site) do- render(conn,- "countries_preview.html",- top_countries: Stats.countries(site, query),- site: site,- query: query,- layout: false- )- else- render_error(conn, 404)- end- end-- def main_graph(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)-- plot_task = Task.async(fn -> Stats.calculate_plot(site, query) end)- {pageviews, visitors} = Stats.pageviews_and_visitors(site, query)- {plot, labels, present_index} = Task.await(plot_task)-- json(conn, %{- plot: plot,- labels: labels,- present_index: present_index,- pageviews: pageviews,- unique_visitors: visitors,- interval: query.step_type- })- end-- def compare(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- {pageviews, ""} = Integer.parse(conn.params["pageviews"])- {unique_visitors, ""} = Integer.parse(conn.params["unique_visitors"])-- if site && current_user_can_access?(conn, site) do- {change_pageviews, change_visitors} = Stats.compare_pageviews_and_visitors(site, query, {pageviews, unique_visitors})-- json(conn, %{- change_pageviews: change_pageviews,- change_visitors: change_visitors- })- end- end-- def referrers(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- referrers = Stats.top_referrers(site, query, 100)-- render(conn, "referrers.html", layout: false, site: site, top_referrers: referrers, query: query)- else- render_error(conn, 404)- end- end-- def referrer_drilldown(conn, %{"domain" => domain, "referrer" => "Google"}) do- site = Repo.get_by(Plausible.Site, domain: domain)- |> Repo.preload(:google_auth)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- total_visitors = Stats.visitors_from_referrer(site, query, "Google")- search_terms = if site.google_auth && site.google_auth.property do- Plausible.Google.Api.fetch_stats(site.google_auth, query)- end-- render(conn, "google_referrer.html",- layout: false,- site: site,- search_terms: search_terms,- total_visitors: total_visitors,- query: query- )- else- render_error(conn, 404)- end- end-- def referrer_drilldown(conn, %{"domain" => domain, "referrer" => referrer}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- referrers = Stats.referrer_drilldown(site, query, referrer)- total_visitors = Stats.visitors_from_referrer(site, query, referrer)-- render(conn, "referrer_drilldown.html", layout: false, site: site, referrers: referrers, referrer: referrer, total_visitors: total_visitors, query: query)- else- render_error(conn, 404)- end- end-- def pages(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- pages = Stats.top_pages(site, query, 100)-- render(conn, "pages.html", layout: false, site: site, top_pages: pages)- else- render_error(conn, 404)- end- end-- def countries(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- countries = Stats.countries(site, query, 100)-- render(conn, "countries.html", layout: false, site: site, countries: countries)- else- render_error(conn, 404)- end- end-- def operating_systems(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- operating_systems = Stats.operating_systems(site, query, 100)-- render(conn, "operating_systems.html", layout: false, site: site, operating_systems: operating_systems)- else- render_error(conn, 404)- end- end-- def browsers(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- browsers = Stats.browsers(site, query, 100)-- render(conn, "browsers.html", layout: false, site: site, browsers: browsers)- else- render_error(conn, 404)- end- end-- def current_visitors(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- json(conn, Stats.current_visitors(site))- else- render_error(conn, 404)- end- end-- def conversions_preview(conn, %{"domain" => domain}) do- site = Repo.get_by(Plausible.Site, domain: domain)-- if site && current_user_can_access?(conn, site) do- {conn, params} = fetch_period(conn, site)- query = Stats.Query.from(site.timezone, params)- goals = Stats.goal_conversions(site, query)-- render(conn, "conversions_preview.html", layout: false, query: query, site: site, goals: goals)- else- render_error(conn, 404)- end- end-defp current_user_can_access?(_conn, %Plausible.Site{public: true}) dotrueend@@ -335,21 +47,5 @@ defmodule PlausibleWeb.StatsController douser -> Plausible.Sites.is_owner?(user.id, site)endend-- defp fetch_period(conn, site) do- case conn.params["period"] do- p when p in ["day", "month", "7d", "3mo", "6mo"] ->- saved_periods = get_session(conn, :saved_periods) || %{}- {put_session(conn, :saved_periods, Map.merge(saved_periods, %{site.domain => p})), conn.params}- _ ->- saved_period = (get_session(conn, :saved_periods) || %{})[site.domain]-- if saved_period do- {conn, %{"period" => saved_period}}- else- {conn, conn.params}- end- end- end-end+diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex e687bac0ec..2466b6d541 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -22,10 +22,30 @@ defmodule PlausibleWeb.Router doplug PlausibleWeb.AuthPlugend+ pipeline :stats_api do+ plug :accepts, ["json"]+ plug :fetch_session+ end+if Mix.env == :dev doforward "/sent-emails", Bamboo.SentEmailViewerPlugend+ scope "/api/stats", PlausibleWeb.Api do+ pipe_through :stats_api++ get "/:domain/current-visitors", StatsController, :current_visitors+ get "/:domain/main-graph", StatsController, :main_graph+ get "/:domain/referrers", StatsController, :referrers+ get "/:domain/referrers/:referrer", StatsController, :referrer_drilldown+ get "/:domain/pages", StatsController, :pages+ get "/:domain/countries", StatsController, :countries+ get "/:domain/browsers", StatsController, :browsers+ get "/:domain/operating-systems", StatsController, :operating_systems+ get "/:domain/screen-sizes", StatsController, :screen_sizes+ get "/:domain/conversions", StatsController, :conversions+ end+scope "/api", PlausibleWeb dopipe_through :apidiff --git a/lib/plausible_web/templates/layout/_svg_icons.html.eex b/lib/plausible_web/templates/layout/_svg_icons.html.eexindex 75f0d5750f..f8ce728800 100644--- a/lib/plausible_web/templates/layout/_svg_icons.html.eex+++ b/lib/plausible_web/templates/layout/_svg_icons.html.eex@@ -20,5 +20,7 @@<symbol id="feather-x-circle" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></symbol>+ <symbol id="feather-maximize" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></symbol>+</defs></svg>diff --git a/lib/plausible_web/templates/layout/app.html.eex b/lib/plausible_web/templates/layout/app.html.eexindex e39a8321c1..7f93147e88 100644--- a/lib/plausible_web/templates/layout/app.html.eex+++ b/lib/plausible_web/templates/layout/app.html.eex@@ -70,7 +70,6 @@<%= render @view_module, @view_template, assigns %></main><%= render("_footer.html", assigns) %>- <script src="https://cdn.jsdelivr.net/npm/micromodal/dist/micromodal.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script><script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script></body>diff --git a/lib/plausible_web/templates/stats/_bar_graph.html.eex b/lib/plausible_web/templates/stats/_bar_graph.html.eexdeleted file mode 100644index 2d5373db33..0000000000--- a/lib/plausible_web/templates/stats/_bar_graph.html.eex+++ /dev/null@@ -1,29 +0,0 @@-<div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4">- <div class="text-center">- <h2><%= @title %></h2>- <div class="text-grey-darker mt-1">by <%= @by %></div>- </div>-- <div class="mt-8">- <%= for {key, count} <- @list do %>- <div class="flex items-center justify-between my-2">- <%= case key do %>- <% {:link, name, to} -> %>- <%= link(name, to: to, "data-pushstate": true, class: "hover:underline") %>- <% key -> %>- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <% end %>- <span><%= count %></span>- </div>- <%= bar(count, @list, @color) %>- <% end %>- </div>- <%= if Enum.count(@list) >= 5 do %>- <div class="text-center">- <a href="<%= assigns[:link] || "/referrers" %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>- <% end %>-</div>diff --git a/lib/plausible_web/templates/stats/_graph.html.eex b/lib/plausible_web/templates/stats/_graph.html.eexdeleted file mode 100644index b55ea083e3..0000000000--- a/lib/plausible_web/templates/stats/_graph.html.eex+++ /dev/null@@ -1,134 +0,0 @@-<div class="w-full bg-white shadow-md rounded mt-6">- <div class="border-b border-grey-light p-4 font-medium">- <span><%= @pageviews %> Pageviews</span> • <span><%= @unique_visitors %> Unique visitors</span>- </div>- <div class="p-4">- <canvas id="main-graph" class="mt-4" width="1054" height="329"></canvas>- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>- <script>- var plot = [<%= Enum.join(@plot, ",") %>];- var dashedPart = plot.slice(-2);- var dashedPlot = (new Array(plot.length - 2)).concat(dashedPart)- plot[plot.length - 1] = undefined- var labels = [<%= raw Enum.map(@labels, fn l -> "'#{l}'" end) |> Enum.join(", ") %>]- var ctx = document.getElementById("main-graph").getContext('2d');- var gradient = ctx.createLinearGradient(0, 0, 0, 300);- gradient.addColorStop(0, 'rgba(101,116,205, 0.2)');- gradient.addColorStop(1, 'rgba(101,116,205, 0)');-- new Chart(ctx, {- type: 'line',- data: {- labels: labels,- datasets: [- {- label: 'Visitors',- data: plot,- borderWidth: 3,- borderColor: 'rgba(101,116,205)',- pointBackgroundColor: 'rgba(101,116,205)',- backgroundColor: gradient,- },- {- label: 'Visitors',- data: dashedPlot,- borderWidth: 3,- borderDash: [10, 15],- borderColor: 'rgba(101,116,205)',- pointBackgroundColor: 'rgba(101,116,205)',- backgroundColor: gradient,- }- ]- },- options: {- legend: {display: false},- responsive: true,- elements: {line: {tension: 0.1}, point: {radius: 0}},- tooltips: {- enabled: false,- mode: 'index',- intersect: false,- custom: drawTooltip- },- hover: {- mode: 'index',- intersect: false- },- scales: {- yAxes: [{- ticks: {- callback: labelFormatter,- beginAtZero: true,- autoSkip: true,- maxTicksLimit: 8,- },- gridLines: {- zeroLineColor: 'transparent',- drawBorder: false,- }- }],- xAxes: [{- gridLines: {- display: false,- },- ticks: {- autoSkip: true,- maxTicksLimit: 8,- }- }]- }- }- });--function labelFormatter(num) {- if (num > 999 && num < 100000) {- return (num / 1000) + 'k'- } else {- return num- }-}--function drawTooltip(tooltipModel) {- var tooltipEl = document.getElementById('chartjs-tooltip');-- // Create element on first render- if (!tooltipEl) {- tooltipEl = document.createElement('div');- tooltipEl.id = 'chartjs-tooltip';- tooltipEl.innerHTML = '<table></table>';- document.body.appendChild(tooltipEl);- }-- // Hide if no tooltip- if (tooltipModel.opacity === 0) {- tooltipEl.style.opacity = 0;- return;- }-- var data = tooltipModel.dataPoints[0]-- // Set Text- if (tooltipModel.body) {- var innerHtml = '<thead>';- innerHtml += '<tr><th>' + data.yLabel.toLocaleString() + ' visitors' + '</th></tr>';- innerHtml += '</thead><tbody>';-- innerHtml += '<tr><td>' + data.xLabel + '</td></tr>';- innerHtml += '</tbody>';-- var tableRoot = tooltipEl.querySelector('table');- tableRoot.innerHTML = innerHtml;- }-- // `this` will be the overall tooltip- var position = this._chart.canvas.getBoundingClientRect();-- // Display, position, and set styles for font- tooltipEl.style.opacity = 1;- tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';- tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';- tooltipEl.classList.add('bg-indigo-darkest', 'text-white', 'rounded', 'text-center', 'p-3', 'text-sm');-}- </script>- </div>-</div>diff --git a/lib/plausible_web/templates/stats/browsers.html.eex b/lib/plausible_web/templates/stats/browsers.html.eexdeleted file mode 100644index 8051218be4..0000000000--- a/lib/plausible_web/templates/stats/browsers.html.eex+++ /dev/null@@ -1,17 +0,0 @@-<header class="modal__header">- <h1>Browsers</h1>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="text-grey-darker text-lg ml-1 mt-1">by visitors</div>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content" id="modal-1-content">- <div class="mt-8">- <%= for {browser, count, percentage} <- @browsers do %>- <div class="flex items-center justify-between my-2">- <span><%= browser %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @browsers, :red) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/browsers_preview.html.eex b/lib/plausible_web/templates/stats/browsers_preview.html.eexdeleted file mode 100644index e0f61b633b..0000000000--- a/lib/plausible_web/templates/stats/browsers_preview.html.eex+++ /dev/null@@ -1,22 +0,0 @@-<div class="text-center">- <h2>Browsers</h2>- <div class="text-grey-darker mt-1">by visitors</div>-</div>--<div class="mt-8">- <%= for {key, count, percentage} <- @browsers do %>- <div class="flex items-center justify-between my-2">- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @browsers, :red) %>- <% end %>-</div>-<%= if Enum.count(@browsers) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/browsers<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/conversions_preview.html.eex b/lib/plausible_web/templates/stats/conversions_preview.html.eexdeleted file mode 100644index 883e39dd21..0000000000--- a/lib/plausible_web/templates/stats/conversions_preview.html.eex+++ /dev/null@@ -1,27 +0,0 @@-<div class="text-center">- <h2>Conversions</h2>- <div class="text-grey-darker mt-1">by unique visitors</div>-</div>--<div class="mt-8">- <%= if Enum.count(@goals) > 0 do %>- <%= for {key, count} <- @goals do %>- <div class="flex items-center justify-between my-2">- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @goals, :indigo) %>- <% end %>- <% else %>- <div class="text-center">No conversions for this period</div>- <div class="text-center mt-2"><%= link("Manage goals", to: "/#{@site.domain}/goals", class: "text-indigo") %></div>- <% end %>-</div>-<%= if Enum.count(@goals) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/conversions<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/countries.html.eex b/lib/plausible_web/templates/stats/countries.html.eexdeleted file mode 100644index ebaf7f9075..0000000000--- a/lib/plausible_web/templates/stats/countries.html.eex+++ /dev/null@@ -1,17 +0,0 @@-<header class="modal__header">- <h1>Top Countries</h1>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="text-grey-darker text-lg ml-1 mt-1">by visitors</div>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content">- <div class="mt-8">- <%= for {country, count, percentage} <- @countries do %>- <div class="flex items-center justify-between my-2">- <span><%= country %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @countries, :indigo) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/countries_preview.html.eex b/lib/plausible_web/templates/stats/countries_preview.html.eexdeleted file mode 100644index 730b43bec2..0000000000--- a/lib/plausible_web/templates/stats/countries_preview.html.eex+++ /dev/null@@ -1,22 +0,0 @@-<div class="text-center">- <h2>Top Countries</h2>- <div class="text-grey-darker mt-1">by visitors</div>-</div>--<div class="mt-8">- <%= for {key, count, percentage} <- @top_countries do %>- <div class="flex items-center justify-between my-2">- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @top_countries, :indigo) %>- <% end %>-</div>-<%= if Enum.count(@top_countries) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/countries<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/google_referrer.html.eex b/lib/plausible_web/templates/stats/google_referrer.html.eexdeleted file mode 100644index ff702118a7..0000000000--- a/lib/plausible_web/templates/stats/google_referrer.html.eex+++ /dev/null@@ -1,42 +0,0 @@-<header class="modal__header">- <a href="/<%= @site.domain %>/referrers" data-pushstate><div class="font-bold text-grey-darker">← All referrers</div></a>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content mt-0">- <h1><%= @total_visitors %> new visitors from Google</h1>- <h1 class="text-grey-darker" style="transform: translateY(-1rem);"><%= timeframe_to_human(@query) %></h1>- <%= case @search_terms do %>- <% {:ok, []} -> %>- <div class="flex items-center justify-between py-2 border-b border-b-grey text-sm font-bold text-grey-darker">- <span>Search term</span>- <span>Visitors</span>- </div>- <div class="text-center text-grey-darker mt-6">- <svg class="fill-current" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" version="1.1" x="0px" y="0px" viewBox="0 0 100 125" style="enable-background:new 0 0 100 100;" xml:space="preserve"><g><path d="M35.6830368,38.7263184c2.7299805,0,4.9511719-2.2211914,4.9511719-4.9511719s-2.2211914-4.9511719-4.9511719-4.9511719 c-2.7304688,0-4.9516602,2.2211914-4.9516602,4.9511719S32.9525681,38.7263184,35.6830368,38.7263184z M35.6830368,30.8239746 c1.6274414,0,2.9511719,1.3237305,2.9511719,2.9511719s-1.3237305,2.9511719-2.9511719,2.9511719 s-2.9516602-1.3237305-2.9516602-2.9511719S34.0555954,30.8239746,35.6830368,30.8239746z"/><path d="M43.4540329,27.4133301c2.1630859,0,3.9228516-1.7597656,3.9228516-3.9228516s-1.7597656-3.9228516-3.9228516-3.9228516 c-2.1625977,0-3.9223633,1.7597656-3.9223633,3.9228516S41.2914352,27.4133301,43.4540329,27.4133301z M43.4540329,21.567627 c1.0600586,0,1.9228516,0.862793,1.9228516,1.9228516s-0.862793,1.9228516-1.9228516,1.9228516 s-1.9223633-0.862793-1.9223633-1.9228516S42.3939743,21.567627,43.4540329,21.567627z"/><path d="M80.2762985,41.4973145c3.6635742,0,6.6445313-2.980957,6.6445313-6.6445313s-2.980957-6.6445313-6.6445313-6.6445313 c-3.6640625,0-6.6450195,2.980957-6.6450195,6.6445313S76.612236,41.4973145,80.2762985,41.4973145z M80.2762985,30.208252 c2.5610352,0,4.6445313,2.0834961,4.6445313,4.6445313s-2.0834961,4.6445313-4.6445313,4.6445313 s-4.6450195-2.0834961-4.6450195-4.6445313S77.7152634,30.208252,80.2762985,30.208252z"/><path d="M86.4340134,28.1555176c1.9663086,0,3.565918-1.5996094,3.565918-3.565918s-1.5996094-3.565918-3.565918-3.565918 c-1.9658203,0-3.5654297,1.5996094-3.5654297,3.565918S84.4681931,28.1555176,86.4340134,28.1555176z M86.4340134,23.0236816 c0.8632813,0,1.565918,0.7026367,1.565918,1.565918s-0.7026367,1.565918-1.565918,1.565918 s-1.5654297-0.7026367-1.5654297-1.565918S85.5707321,23.0236816,86.4340134,23.0236816z"/><path d="M79.9183884,48.1384277l-0.5896606,0.1737061c0.1333618-0.4435425,0.2112427-0.9072266,0.2112427-1.3841553 c0-0.4707031-0.0678711-0.9375-0.2045898-1.3950195c-0.78125-2.5327148-3.4887695-3.9741211-6.0366211-3.2119141 l-1.7001953,0.5170898c-0.3798828,0.1108398-0.7299805,0.1855469-1.0664063,0.2265625 c-0.003479,0.0004272-0.006897,0.000061-0.010376,0.0004883c-0.0266113,0.0028076-0.0534058-0.0014648-0.0794678,0.00354 c-0.6416626,0.0675659-1.277771,0.0505981-1.8896484-0.0645752l-4.8505859-0.8999023 c-3.8491211-0.7124023-7.8662109-0.4970703-11.6201172,0.6259766l-11.3138428,3.4025879 c-0.0564575-0.0429077-0.1116943-0.0877075-0.1778564-0.1184082l-13.7036133-6.3583984 c-0.230957-0.1069336-0.4951172-0.121582-0.7353516-0.0419922l-8.2226563,2.7250977 c-0.309082,0.1025391-0.5488281,0.3486328-0.6425781,0.6601563c-0.0942383,0.3110352-0.03125,0.6489258,0.1694336,0.9052734 l5.8516235,7.4795532l-2.1152954,0.6361694c-0.2539063,0.0761719-0.4672852,0.2504883-0.5927734,0.4838867 c-0.1254883,0.2338867-0.1533203,0.5078125-0.0766602,0.7617188l0.3309326,1.0892944 c-0.2720337,0.0733643-0.5426636,0.1504517-0.8016357,0.250061c-4.4667969,1.7197266-6.3505859,7.1894531-6.4287109,7.4213867 c-0.1542969,0.4580078,0.0415039,0.9609375,0.4648438,1.1943359c0.1640625,0.0908203,3.1762695,1.7246094,6.574707,1.7246094 c1.0532227,0,2.144043-0.1572266,3.1977539-0.5654297c0.0115356-0.0044556,0.022644-0.010437,0.0341797-0.0149536 l0.0750732,0.2472534l-1.4403076,0.4239502c-0.2548828,0.0751953-0.4692383,0.2485352-0.5961914,0.4819336 s-0.1557617,0.5073242-0.0800781,0.762207l0.2781982,0.9320679c-1.5239868-0.0391846-2.9415283,0.1781616-4.2181396,0.6724243 c-5.4560547,2.1005859-7.7651367,8.8061523-7.8608398,9.090332c-0.1176758,0.3505859-0.0327148,0.7373047,0.2211914,1.0058594 c0.2539063,0.269043,0.6376953,0.3745117,0.9916992,0.2773438c1.5864258-0.4365234,3.1904297-0.6772461,4.7919922-0.7211914 l-1.0683594,1.046875c-0.269043,0.2631836-0.3671875,0.6552734-0.2543945,1.0141602s0.4174805,0.6240234,0.7880859,0.6865234 c0.0708008,0.0117188,0.9082031,0.1474609,2.121582,0.1474609c1.3310547,0,3.1152344-0.1635742,4.8369141-0.8339844 c0.9935913-0.385376,1.942627-0.9547729,2.8378296-1.6859131l0.4258423,1.4300537 c0.1289063,0.434082,0.5268555,0.715332,0.9580078,0.715332c0.09375,0,0.1889648-0.0136719,0.2832031-0.0415039l3.6088257-1.064209 c0.5294189,0.4693604,1.2138062,0.7355957,1.9185181,0.7355957c0.2729492,0,0.5488281-0.0395508,0.8183594-0.1206055 l2.612793-0.7680664c0.6903687-0.1968994,1.2542114-0.6436157,1.6234131-1.2183228 c0.3770752,0.1716309,0.7831421,0.2798462,1.2032471,0.2798462c0.2666016,0,0.5361328-0.0366211,0.8007813-0.1132813 l2.6342773-0.7744141c0.6880493-0.2131348,1.241272-0.6553345,1.6037598-1.2210083 c0.3721924,0.1687622,0.7717285,0.2756958,1.1843262,0.2756958c0.2724609,0,0.5478516-0.0395508,0.8178711-0.1206055 l2.612793-0.7675781c0.980957-0.2804565,1.713623-1.0597534,1.9748535-2.0108032l33.9655762-10.0023804 c3.3706055-1.003418,5.6347656-4.0170898,5.6347656-7.4985352c0-0.7524414-0.1083984-1.4975586-0.3222656-2.2167969 C88.4432907,49.2814941,84.0643845,46.9157715,79.9183884,48.1384277z M26.4042282,41.6369629l10.9301758,5.0717773 l-12.3256836,3.6044922l-5.1030273-6.5224609L26.4042282,41.6369629z M63.3373337,44.0710449l2.6757202,0.4962769 l-6.4960327,2.1526489c-0.3745117,0.121582-0.7783203-0.0761719-0.9013672-0.4448242l-0.8479614-2.5335693 C59.6291428,43.6253662,61.5039597,43.730957,63.3373337,44.0710449z M52.6566696,44.645752 c1.0076294-0.3015137,2.0372925-0.5230713,3.0765381-0.6818237l0.9859619,2.9459839 c0.3779297,1.1303711,1.4384766,1.847168,2.5737305,1.8466797c0.2832031,0,0.5708008-0.0444336,0.8535156-0.1381836 l10.8579102-3.5981445c0.0090942-0.0029907,0.0158081-0.0096436,0.0247192-0.0128784 c0.3674316-0.0574341,0.7401123-0.1351929,1.1417847-0.2532349l1.7055664-0.5185547 c1.4975586-0.4467773,3.0883789,0.3989258,3.5454102,1.878418c0.078125,0.2631836,0.1181641,0.5371094,0.1181641,0.8139648 c0,0.8886719-0.4160156,1.7143555-1.1201172,2.2368164l-28.8650513,8.5059814l-0.8562622,0.2522583 c-0.2514038-0.196106-0.5341187-0.3519897-0.8377686-0.4598999c-0.0093384-0.0098267-0.0202637-0.0175781-0.0297241-0.0272827 c-0.038208-0.0392456-0.079895-0.0735474-0.1200562-0.1102905c-0.0634155-0.0580444-0.1269531-0.1153564-0.1948242-0.1671143 c-0.0471191-0.0359497-0.0963745-0.067749-0.1453857-0.1005859c-0.0665283-0.0444946-0.1335449-0.0876465-0.2033081-0.1263428 c-0.0535278-0.0297241-0.1080322-0.0564575-0.163269-0.0827026c-0.0698853-0.0332031-0.1405029-0.0636597-0.2127686-0.0911255 c-0.0580444-0.0220947-0.1160889-0.0426025-0.1754761-0.0609131c-0.0736694-0.0227051-0.1481323-0.0411987-0.2234497-0.0580444 c-0.0602417-0.0134888-0.1199341-0.0269775-0.1810303-0.0365601c-0.0789795-0.0123901-0.1585693-0.0187988-0.2385254-0.0245972 c-0.0588379-0.0043335-0.1170044-0.0105591-0.1762085-0.0112305c-0.0892334-0.0009766-0.1785889,0.0061035-0.2682495,0.0134888 c-0.0505371,0.0042114-0.1008911,0.0043335-0.1514893,0.0112305c-0.1401367,0.019043-0.2800293,0.0469971-0.4185791,0.0874023 l-2.6254883,0.7714844c-0.1715088,0.0514526-0.335022,0.1169434-0.4894409,0.1948242 c-0.1483154,0.0748291-0.2871094,0.1623535-0.4178467,0.258667c-0.0053711,0.0039673-0.0119019,0.0066528-0.0172729,0.0106812 c-0.1115723,0.083374-0.2116089,0.1785278-0.3088379,0.2757568c-0.020752,0.020752-0.0458374,0.0375366-0.0658569,0.0588379 c-0.0830688,0.0883789-0.1534424,0.1865234-0.2243042,0.2841187c-0.0264282,0.036377-0.0588379,0.0684204-0.0834961,0.105957 c-0.0002441,0.0003662-0.0006104,0.0007324-0.0008545,0.0010986c-0.008728-0.0039673-0.0183105-0.0056763-0.0270996-0.0095215 c-0.0830688-0.0366821-0.1703491-0.0613403-0.2565308-0.0900269c-0.0712891-0.0236816-0.1404419-0.0530396-0.213501-0.0710449 c-0.0961914-0.0238037-0.1952515-0.0338135-0.2938232-0.0474854c-0.0670166-0.0093384-0.1325073-0.0254517-0.2003174-0.0299683 c-0.1109619-0.0073853-0.2233276,0.0008545-0.3355103,0.0066528c-0.0574341,0.0029907-0.1143188-0.0018921-0.171875,0.0046387 c-0.1697998,0.0193481-0.3398438,0.0536499-0.5081787,0.1049194l-2.6225586,0.7709961 c-0.1702271,0.0504761-0.3327026,0.1159668-0.4865723,0.194458c-0.0361938,0.0184937-0.0670166,0.0443115-0.1022339,0.064209 c-0.114624,0.0647583-0.2285767,0.1306152-0.3320923,0.2097778c-0.0396729,0.0302734-0.0722656,0.0681152-0.1102295,0.1004028 c-0.0912476,0.0775757-0.1833496,0.1543579-0.263916,0.2424927c-0.0459595,0.0502319-0.0822754,0.1082764-0.1245728,0.1616211 c-0.0603638,0.0762329-0.1253662,0.1488647-0.1779175,0.230957c-0.4283447-0.1953125-0.90625-0.2789307-1.394104-0.2468872 c-0.0344849,0.0022583-0.0682373-0.0021362-0.1028442,0.0013428c-0.1741333,0.0176392-0.3493042,0.0509033-0.5236816,0.100708 l-2.6259766,0.7719727c-0.1636353,0.0493164-0.3181763,0.1143799-0.4664307,0.1885986 c-0.0487671,0.0244141-0.0928955,0.0542603-0.1398315,0.0811157c-0.0963745,0.0551758-0.1904907,0.1124878-0.2788086,0.1773682 c-0.0499268,0.0366821-0.0962524,0.0762939-0.1435547,0.1159058c-0.0778809,0.0652466-0.1521606,0.1329956-0.2223511,0.2055054 c-0.0435181,0.0449219-0.0854492,0.09021-0.1258545,0.1376343c-0.0662231,0.0778198-0.1264648,0.1592407-0.18396,0.2432251 c-0.03302,0.0482788-0.0672607,0.0950928-0.09729,0.1452026c-0.0593262,0.098999-0.1095581,0.2024536-0.1566162,0.3079224 c-0.0180054,0.0402222-0.0400391,0.078186-0.0561523,0.1193237c-0.0580444,0.1479492-0.1044922,0.300354-0.137207,0.4569702 c-0.007019,0.0336914-0.0078735,0.0687256-0.0136719,0.1027222c-0.0180664,0.1057129-0.0368042,0.2113647-0.0427246,0.3195801 l-0.2138062-0.7027588c0.012085-0.1270142,0.0072021-0.2562256-0.0317993-0.3841553l-1.1140137-3.6674194l-0.322998-1.0791626 c-0.0026855-0.0089111-0.0092773-0.015564-0.012207-0.024353l-0.9248047-3.0444946 c-0.0401001-0.1308594-0.1096802-0.2437134-0.1931763-0.3440552l-0.2487183-0.8175659L52.6566696,44.645752z M22.3425827,59.2571411l0.0478516,0.1574097c-0.1259155,0.0722656-0.2521362,0.1400757-0.3763428,0.1901855 c-0.253418,0.0957031-0.5390625,0.1601563-0.8525391,0.1923828c0.2495117-0.1816406,0.5009766-0.3227539,0.7504883-0.4189453 C22.0441818,59.3267212,22.1913376,59.2897949,22.3425827,59.2571411z M23.1390915,62.5144043 c-2.6728516,1.0361328-5.8369141-0.0449219-7.2880859-0.668457c0.6430664-1.4326172,2.2358398-4.3408203,4.9189453-5.3740234 c0.213562-0.0823975,0.4368286-0.1488037,0.6634521-0.2074585l0.3309937,1.0894775 c-0.1945801,0.0488892-0.3952637,0.0895996-0.5745239,0.1589966c-1.090332,0.421875-2.1020508,1.2758789-3.0068359,2.5380859 c-0.1958008,0.2734375-0.2412109,0.6269531-0.1206055,0.940918s0.3911133,0.5463867,0.7197266,0.6186523 c0.6391602,0.1396484,1.2744141,0.2109375,1.8881836,0.2109375c0.7543945,0,1.4448242-0.1166992,2.0698242-0.3535156 c0.0811157-0.0325317,0.1576538-0.0828857,0.2376709-0.1199341l0.3328857,1.0957642 C23.2537155,62.4679565,23.1967697,62.4923706,23.1390915,62.5144043z M23.5314255,72.725647l0.0012207,0.0040894 c-0.5898438,0.7407227-1.1948242,1.3237305-1.8076172,1.7416992c-0.5957031-0.9111328-1.5537109-1.5366211-2.6308594-1.7211914 c0.199707-0.1118164,0.4003906-0.2060547,0.6015625-0.2827148c1.0146484-0.387207,2.3012695-0.4477539,3.6938477-0.2143555 L23.5314255,72.725647z M21.756279,77.7346191c-1.2910156,0.5024414-2.6557617,0.6630859-3.7475586,0.6904297l1.1201172-1.0976563 c0.2788086-0.2729492,0.3730469-0.6831055,0.2421875-1.050293s-0.4633789-0.625-0.8515625-0.6601563 c-0.6420898-0.0581055-1.2861328-0.0869141-1.9301758-0.0869141c-1.2963867,0-2.5947266,0.1171875-3.8862305,0.3515625 c0.9746094-1.9414063,2.9125977-4.96875,5.9301758-6.1308594c1.1391602-0.440918,2.434082-0.6181641,3.8476563-0.5322266 l0.2842407,0.9488525c-1.3863525-0.1206055-2.680603,0.0112915-3.7837524,0.4320068 c-1.2207031,0.4672852-2.3857422,1.3544922-3.4614258,2.6357422c-0.2607422,0.3105469-0.3085938,0.7480469-0.1201172,1.1069336 c0.1879883,0.3588867,0.5737305,0.5717773,0.9785156,0.5317383l1.8959961-0.1762695 c0.0302734-0.003418,0.0610352-0.0043945,0.0913086-0.0043945c0.784668,0.0019531,1.4975586,0.4169922,1.831543,1.1416016 c0.0463867,0.0922852,0.0771484,0.1743164,0.097168,0.2583008c0.0678711,0.2875977,0.2592773,0.5307617,0.5229492,0.6635742 c0.1416016,0.0712891,0.2958984,0.1069336,0.4501953,0.1069336c0.1342773,0,0.2685547-0.0268555,0.3945313-0.0810547 c0.8795776-0.3776855,1.7250366-1.0009155,2.534668-1.8171997l0.3041992,1.0198364 C23.6381149,76.7746582,22.7172165,77.3615723,21.756279,77.7346191z M25.7430954,72.3293457 c-0.0053711-0.0239258-0.0117188-0.0478516-0.0185547-0.0712891l-1.6694336-5.5859375l0.6426392-0.1890869 c0.1815186,0.1630859,0.4124756,0.2652588,0.6615601,0.2652588c0.0947266,0,0.190918-0.0136719,0.2866211-0.0424805 l0.7924194-0.2364502l2.1046753,7.0847168l1.0675659,3.6032104l-2.2332153,0.6588745L25.7430954,72.3293457z M35.3881149,76.8781738l-2.6269531,0.7719727c-0.3734741,0.1134644-0.7839355-0.0386963-0.998291-0.3710938 c-0.0044556-0.0070801-0.0038452-0.0159912-0.0085449-0.0229492c-0.0307617-0.0463867-0.0595703-0.1108398-0.0820313-0.1914063 l-1.4168701-4.7697754l-2.2486572-7.5876465l-0.2172852-0.7382813c-0.0527344-0.4150391,0.2158203-0.8164063,0.6328125-0.9418945 l2.6118164-0.7680664c0.4311523-0.1245117,0.8818359,0.0771484,1.0400391,0.4121094l3.5966187,12.0499268l0.3242798,1.0936279 c0.0015259,0.0049438,0.0045166,0.0084229,0.0061035,0.0133667l0.0114746,0.0383911 c0.0001221,0.0003052,0.0003662,0.001709,0.0004883,0.0020752c0.0063477,0.031189,0.0131836,0.0750122,0.0131836,0.145874 c0,0.0057373,0.0036621,0.0105591,0.0037842,0.0162964C36.0345993,76.4204712,35.773613,76.7678833,35.3881149,76.8781738z M41.6283493,75.0583496l-2.6157227,0.7685547c-0.3842773,0.1107788-0.7797852-0.0397949-1.0014038-0.3787842 c-0.0003052-0.0004883-0.0002441-0.0010986-0.0005493-0.0015869c-0.0240479-0.0377808-0.0378418-0.0718384-0.053833-0.1066895 c-0.0119019-0.026001-0.0247803-0.0489502-0.0344238-0.0758057c-0.0065308-0.0221558-0.0131226-0.0442505-0.0206299-0.06604 c-0.001709-0.005127-0.0059204-0.0084839-0.0077515-0.0136108l-3.7139282-12.5259399l-0.1210938-0.4052734 c-0.0109863-0.0336914-0.0181274-0.0585327-0.0230103-0.0740356c-0.0022583-0.0072632-0.005188-0.0172729-0.0057983-0.0172729 c-0.0004883,0-0.0004883,0.0014648-0.0004883,0.0048828c-0.0610352-0.4277344,0.2119141-0.8452148,0.6318359-0.9697266 l2.6289063-0.7724609c0.40625-0.125,0.8422852,0.0654297,1.034668,0.4501953 c0.0029297,0.0058594,0.0058594,0.0112305,0.0087891,0.0170898c0.0043945,0.0102539,0.0087891,0.0205078,0.0131836,0.0302734 c0.015625,0.034668,0.0341797,0.0708008,0.0463867,0.1069336l3.8374023,12.9326172 c0.0012207,0.0040894,0.0032349,0.0079956,0.0044556,0.012085l0.0062866,0.0211182 c0.0129395,0.0390625,0.0126953,0.0739746,0.0166626,0.107666c0.0024414,0.0253906,0.0077515,0.0415649,0.0077515,0.0773926 c0,0.0050049,0.0032349,0.0092163,0.0032959,0.0142212C42.2725143,74.5970459,42.0161667,74.9381714,41.6283493,75.0583496z M48.509697,72.3605957c0.0048828,0.3955078-0.2558594,0.7475586-0.6416016,0.8579102l-2.6264648,0.7714844 c-0.3828125,0.1132813-0.7822266-0.0351563-0.9838867-0.3564453c-0.0009155-0.0015259-0.0010376-0.0028076-0.0019531-0.0043335 c-0.003479-0.0057983-0.0027466-0.0128784-0.0063477-0.0186157c-0.0113525-0.0181274-0.015686-0.0336304-0.0253296-0.0511475 c-0.026001-0.0504761-0.0529175-0.1010132-0.0684204-0.1506348c-0.0031128-0.0101929-0.0059204-0.0204468-0.0092773-0.0306396 c-0.0010376-0.0032349-0.0037231-0.0053711-0.0047607-0.008606l-3.7252197-12.5631714l-0.1323242-0.456543 c-0.0039063-0.0375977-0.0102539-0.074707-0.0185547-0.1113281c-0.0249023-0.3901367,0.2368164-0.7514648,0.6362305-0.8710938 l2.6176758-0.7695313c0.3603516-0.1015625,0.7441406,0.0283203,0.9614258,0.3271484 c0.0151367,0.0214844,0.0566406,0.078125,0.0737305,0.0981445c0.0341797,0.0678711,0.0683594,0.1425781,0.0791016,0.1674805 l3.8598633,13.0180664c0.0068359,0.0180664,0.0161133,0.0527344,0.0161133,0.1391602 C48.509697,72.3522949,48.509697,72.3562012,48.509697,72.3605957z M83.7972946,61.208252L50.2455368,71.088623 L46.943779,59.935791l33.5390625-9.8789063c3.0947266-0.909668,6.3588867,0.8496094,7.2783203,3.9257813 c0.1582031,0.5327148,0.2387695,1.0859375,0.2387695,1.6450195C87.9999313,58.2175293,86.3099899,60.4602051,83.7972946,61.208252z "/><path d="M82.1522751,50.5427246c-0.4902344,0-0.9799805,0.0712891-1.456543,0.2124023 c-0.5292969,0.1572266-0.831543,0.7133789-0.6748047,1.2431641c0.1572266,0.5292969,0.7143555,0.8310547,1.2431641,0.6748047 c1.6289063-0.4804688,3.3920898,0.496582,3.8676758,2.0874023c0.1293945,0.4335938,0.5273438,0.7138672,0.9575195,0.7138672 c0.0952148,0,0.1914063-0.0136719,0.2871094-0.0424805c0.5288086-0.1582031,0.8295898-0.715332,0.6713867-1.2446289 C86.4061813,52.0412598,84.3929977,50.5427246,82.1522751,50.5427246z"/><path d="M78.2572556,51.4729004l-2.8793945,0.847168c-0.5297852,0.15625-0.8330078,0.7119141-0.6772461,1.2416992 c0.128418,0.4355469,0.5268555,0.7182617,0.9589844,0.7182617c0.09375,0,0.1884766-0.0136719,0.2827148-0.0410156 l2.8793945-0.847168c0.5297852-0.15625,0.8330078-0.7119141,0.6772461-1.2416992 C79.3427048,51.6203613,78.784111,51.3190918,78.2572556,51.4729004z"/><path d="M72.7758102,53.0856934l-23.9584961,7.0512695c-0.5297852,0.15625-0.8330078,0.7119141-0.6772461,1.2416992 c0.128418,0.4355469,0.5268555,0.7182617,0.9589844,0.7182617c0.09375,0,0.1884766-0.0136719,0.2827148-0.0410156 l23.9584961-7.0512695c0.5297852-0.15625,0.8330078-0.7119141,0.6772461-1.2416992 C73.8607712,53.232666,73.303154,52.932373,72.7758102,53.0856934z"/></g></svg>- <div class="text-lg">Could not find any search terms for this period</div>- </div>- <% {:ok, search_terms} -> %>- <div class="flex items-center justify-between py-2 border-b border-b-grey text-sm font-bold text-grey-darker">- <span>Search term</span>- <span>Visitors</span>- </div>- <%= for {term, count} <- search_terms do %>- <div class="flex items-center justify-between my-2">- <span><%= term %></span>- <span><%= count %></span>- </div>- <%= bar(count, search_terms) %>- <% end %>- <% {:error, msg} -> %>- <div>Unable to show search terms. Google Search Console API returned the following error:</div>- <div class="mt-4 p-4 rounded bg-grey-lightest"><%= msg %></div>- <% nil -> %>- <%= if @conn.assigns[:current_user] && Plausible.Sites.is_owner?(@conn.assigns[:current_user].id, @site) do %>- <div>- You can link your Google account to see the search terms that lead to your website.- </div>- <%= link("Connect with Google", to: "/#{@site.domain}/settings#google-auth", class: "button mt-4") %>- <% end %>- <% end %>-</main>diff --git a/lib/plausible_web/templates/stats/operating_systems.html.eex b/lib/plausible_web/templates/stats/operating_systems.html.eexdeleted file mode 100644index 51b1c0b1e2..0000000000--- a/lib/plausible_web/templates/stats/operating_systems.html.eex+++ /dev/null@@ -1,17 +0,0 @@-<header class="modal__header">- <h1>Operating Systems</h1>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="text-grey-darker text-lg ml-1 mt-1">by visitors</div>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content">- <div class="mt-8">- <%= for {os, count, percentage} <- @operating_systems do %>- <div class="flex items-center justify-between my-2">- <span><%= os %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @operating_systems, :blue) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/operating_systems_preview.html.eex b/lib/plausible_web/templates/stats/operating_systems_preview.html.eexdeleted file mode 100644index db2e75e9d7..0000000000--- a/lib/plausible_web/templates/stats/operating_systems_preview.html.eex+++ /dev/null@@ -1,22 +0,0 @@-<div class="text-center">- <h2>Operating Systems</h2>- <div class="text-grey-darker mt-1">by visitors</div>-</div>--<div class="mt-8">- <%= for {key, count, percentage} <- @operating_systems do %>- <div class="flex items-center justify-between my-2">- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @operating_systems, :blue) %>- <% end %>-</div>-<%= if Enum.count(@operating_systems) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/operating-systems<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/pages.html.eex b/lib/plausible_web/templates/stats/pages.html.eexdeleted file mode 100644index e2a2dfbc26..0000000000--- a/lib/plausible_web/templates/stats/pages.html.eex+++ /dev/null@@ -1,17 +0,0 @@-<header class="modal__header">- <h1>Top Pages</h1>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="text-grey-darker text-lg ml-1 mt-1">by pageviews</div>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content" id="modal-1-content">- <div class="mt-8">- <%= for {page, count} <- @top_pages do %>- <div class="flex items-center justify-between my-2">- <span><%= page %></span>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @top_pages, :orange) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/pages_preview.html.eex b/lib/plausible_web/templates/stats/pages_preview.html.eexdeleted file mode 100644index 70898df29d..0000000000--- a/lib/plausible_web/templates/stats/pages_preview.html.eex+++ /dev/null@@ -1,22 +0,0 @@-<div class="text-center">- <h2>Top Pages</h2>- <div class="text-grey-darker mt-1">by pageviews</div>-</div>--<div class="mt-8">- <%= for {key, count} <- @top_pages do %>- <div class="flex items-center justify-between my-2">- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @top_pages, :orange) %>- <% end %>-</div>-<%= if Enum.count(@top_pages) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/pages<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/referrer_drilldown.html.eex b/lib/plausible_web/templates/stats/referrer_drilldown.html.eexdeleted file mode 100644index 02f3d2c597..0000000000--- a/lib/plausible_web/templates/stats/referrer_drilldown.html.eex+++ /dev/null@@ -1,22 +0,0 @@-<header class="modal__header">- <%= link("← All referrers", to: "/#{@site.domain}/referrers" <> query_params(@query), "data-pushstate": true, class: "font-bold text-grey-darker hover:underline") %>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content mt-0">- <h1><%= @total_visitors %> new visitors from <%= @referrer %></h1>- <h1 class="text-grey-darker" style="transform: translateY(-1rem);"><%= timeframe_to_human(@query) %></h1>- <div class="mt-4">- <%= for {one_referrer, count} <- @referrers do %>- <div class="flex items-center justify-between my-2">- <%= if one_referrer do %>- <span><%= link(one_referrer, to: "//" <> one_referrer, target: "_blank", class: "hover:underline") %></span>- <% else %>- <span>unknown</span>- <% end %>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @referrers) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/referrers.html.eex b/lib/plausible_web/templates/stats/referrers.html.eexdeleted file mode 100644index 4af892957d..0000000000--- a/lib/plausible_web/templates/stats/referrers.html.eex+++ /dev/null@@ -1,17 +0,0 @@-<header class="modal__header">- <h1>Referrers</h1>- <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>-</header>-<div class="text-grey-darker text-lg ml-1 mt-1">by new visitors</div>-<div class="my-4 border-b border-grey-light"></div>-<main class="modal__content">- <div class="mt-8">- <%= for {referrer, count} <- @top_referrers do %>- <div class="flex items-center justify-between my-2">- <%= link(referrer, to: "/#{@site.domain}/referrers/#{referrer}" <> query_params(@query), "data-pushstate": true, class: "hover:underline") %>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @top_referrers) %>- <% end %>- </div>-</main>diff --git a/lib/plausible_web/templates/stats/referrers_preview.html.eex b/lib/plausible_web/templates/stats/referrers_preview.html.eexdeleted file mode 100644index 9bc431b6b2..0000000000--- a/lib/plausible_web/templates/stats/referrers_preview.html.eex+++ /dev/null@@ -1,27 +0,0 @@-<div class="text-center">- <h2>Top Referrers</h2>- <div class="text-grey-darker mt-1">by new visitors</div>-</div>--<div class="mt-8">- <%= for {key, count} <- @top_referrers do %>- <div class="flex items-center justify-between my-2">- <%= case key do %>- <% {:link, name, to} -> %>- <%= link(name, to: to, "data-pushstate": true, class: "hover:underline") %>- <% key -> %>- <span class="truncate" style="max-width: 80%;"><%= key %></span>- <% end %>- <span title="<%= count %>"><%= large_number_format(count) %></span>- </div>- <%= bar(count, @top_referrers, :blue) %>- <% end %>-</div>-<%= if Enum.count(@top_referrers) >= 5 do %>- <div class="text-center">- <a href="/<%= @site.domain %>/referrers<%= query_params(@query) %>" data-pushstate class="font-bold text-sm text-grey-dark hover:text-red transition tracking-wide">- <svg style="fill: #8795a1;" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-maximize"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>- MORE- </a>- </div>-<% end %>diff --git a/lib/plausible_web/templates/stats/screen_sizes_preview.html.eex b/lib/plausible_web/templates/stats/screen_sizes_preview.html.eexdeleted file mode 100644index 20f7a715b6..0000000000--- a/lib/plausible_web/templates/stats/screen_sizes_preview.html.eex+++ /dev/null@@ -1,16 +0,0 @@-<div class="text-center">- <h2>Screen Sizes</h2>- <div class="text-grey-darker mt-1">by visitors</div>-</div>-<div class="mt-8">- <%= for {screen_size, count, percentage} <- @top_screen_sizes do %>- <div class="flex items-center justify-between my-2">- <span tooltip="<%= explanation_for(screen_size) %>">- <%= icon_for(screen_size) %>- <span class="ml-1 cursor-default"><%= screen_size %></span>- </span>- <span tooltip="<%= count %> visitors"><%= percentage %>%</span>- </div>- <%= bar(count, @top_screen_sizes, :teal) %>- <% end %>-</div>diff --git a/lib/plausible_web/templates/stats/stats.html.eex b/lib/plausible_web/templates/stats/stats.html.eexindex 87083b0b73..bc63fd612d 100644--- a/lib/plausible_web/templates/stats/stats.html.eex+++ b/lib/plausible_web/templates/stats/stats.html.eex@@ -3,109 +3,9 @@<div class="text-center bg-blue-lighter text-blue-darkest text-sm font-bold px-4 w-full rounded transition" style="top: 91px" role="alert"><%= link("Click here to enable weekly email reports →", to: "/#{@site.domain}/settings#email-reports", class: "py-2 block") %></div>- <% end %> <div class="pt-12"></div>- <div class="w-full sm:flex justify-between items-center">- <div class="w-full flex items-center">- <h2 class="text-left mr-8">Analytics for <%= link(@site.domain, to: "//" <> @site.domain, target: "_blank") %></h2>- <div class="text-sm font-bold text-grey-darker mt-2 mt-0">- <svg class="w-2 mr-1 fill-current text-green" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">- <circle cx="8" cy="8" r="8"/>- </svg>- <span id="current-visitors"><%= @current_visitors %></span> current visitors- </div>- </div>- <div class="mt-6 md:mt-0">- <div class="flex justify-between sm:justify-between">- <%= if @query.period == "month" do %>- <div class="flex rounded shadow bg-white mr-4 cursor-pointer">- <%= link(to: "/#{@site.domain}?period=month&date=#{@query.date_range.first |> Timex.shift(months: -1) |> Timex.format!("{ISOdate}")}", class: "flex items-center px-2 border-r border-grey-light") do %>- <svg class="fill-current h-4 w-4" style="transform: translateY(-2px);">- <use xlink:href="#feather-chevron-left" />- </svg>- <% end %>- <%= link(to: "/#{@site.domain}?period=month&date=#{@query.date_range.first |> Timex.shift(months: 1) |> Timex.format!("{ISOdate}")}", class: "flex items-center px-2") do %>- <svg class="fill-current h-4 w-4" style="transform: translateY(-2px);">- <use xlink:href="#feather-chevron-right" />- </svg>- <% end %>- </div>- <% end %>-- <%= if @query.period == "day" do %>- <div class="flex rounded shadow bg-white mr-4 cursor-pointer">- <%= link(to: "/#{@site.domain}?period=day&date=#{@query.date_range.first |> Timex.shift(days: -1) |> Timex.format!("{ISOdate}")}", class: "flex items-center px-2 border-r border-grey-light") do %>- <svg class="fill-current h-4 w-4" style="transform: translateY(-2px);">- <use xlink:href="#feather-chevron-left" />- </svg>- <% end %>- <%= link(to: "/#{@site.domain}?period=day&date=#{@query.date_range.first |> Timex.shift(days: 1) |> Timex.format!("{ISOdate}")}", class: "flex items-center px-2") do %>- <svg class="fill-current h-4 w-4" style="transform: translateY(-2px);">- <use xlink:href="#feather-chevron-right" />- </svg>- <% end %>- </div>- <% end %>-- <div class="relative" style="height: 35.5px; width: 190px;">- <div data-dropdown-trigger class="flex items-center justify-between hover:bg-grey-lighter rounded bg-white shadow px-4 pr-3 py-2 leading-tight cursor-pointer text-sm font-bold text-grey-darker h-full">- <span class="mr-2"><%= timeframe_text(@site, @query) %></span>- <svg class="text-pink fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">- <use xlink:href="#feather-chevron-down" />- </svg>- </div>-- <div data-dropdown style="top: 42px; right: 0px; width: 225px;" class="dropdown-content hidden absolute pin-r bg-white border border-grey-light rounded shadow z-10 font-bold text-sm text-grey-darker">- <%= link("Today", to: "/#{@site.domain}?period=day", class: "block p-2 hover:bg-grey-lighter") %>- <%= link("Last 7 days", to: "/#{@site.domain}?period=7d", class: "block px-2 py-3 hover:bg-grey-lighter") %>- <%= link("This month", to: "/#{@site.domain}?period=month", class: "block p-2 hover:bg-grey-lighter") %>- <%= link("Last month", to: "/#{@site.domain}?period=month&date=#{last_month(@site) |> Timex.format!("{ISOdate}")}", class: "block p-2 hover:bg-grey-lighter") %>- <%= link("Last 3 months", to: "/#{@site.domain}?period=3mo", class: "block p-2 hover:bg-grey-lighter") %>- <%= link("Last 6 months", to: "/#{@site.domain}?period=6mo", class: "block p-2 hover:bg-grey-lighter") %>- </div>- </div>- </div>- <div class="hidden block relative w-full sm:w-48" style="padding: 1px 0;">- <input type="text" id="custom-daterange-trigger" class="bg-white cursor-default w-full appearance-none border border-grey-light rounded shadow py-2 px-4 text-grey-darker text-sm font-bold leading-tight appearance-none focus:outline-none focus:border-grey hover:border-grey" placeholder="Select date range" />- <div class="pointer-events-none absolute pin-y pin-r flex items-center px-2 text-pink">- <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"/></svg>- </div>- </div>- </div>- </div>-- <div class="w-full bg-white shadow-md rounded mt-6" id="main-graph">- <div class="loading pt-24 sm:pt-32 md:pt-48 mx-auto"><div></div></div>- </div>-- <div class="w-full block md:flex items-start justify-between mt-6">- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="referrer-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="pages-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="countries-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- </div>-- <div class="w-full block md:flex items-start justify-between mt-6">- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="browsers-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="operating-systems-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="screen-sizes-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- </div>-- <%= if @has_goals do %>- <div class="w-full block md:flex items-start justify-between mt-6">- <div class="w-full md:w-31percent bg-white shadow-md rounded mt-4 p-4" id="conversion-stats">- <div class="loading my-32 mx-auto"><div></div></div>- </div>- </div><% end %>+ <div class="pt-12"></div>+ <div id="stats-react-container" data-domain="<%= @site.domain %>" data-offset="<%= Timex.Timezone.total_offset(Timex.Timezone.get(@site.timezone)) %>" data-has-goals="<%= @has_goals %>"></div>+ <div id="modal_root"></div>+ <script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/dashboard.js") %>"></script></div>diff --git a/lib/plausible_web/views/error_view.ex b/lib/plausible_web/views/error_view.exindex c704b404a8..7ef22ebf34 100644--- a/lib/plausible_web/views/error_view.ex+++ b/lib/plausible_web/views/error_view.ex@@ -1,6 +1,19 @@defmodule PlausibleWeb.ErrorView douse PlausibleWeb, :view+ def render("500.json", assigns) do+ message = if assigns[:reason] do+ assigns[:reason].message+ else+ "Something went wrong"+ end++ %{+ status: 500,+ message: message+ }+ end+def render("404.html", assigns) dorender("error.html", Map.merge(%{layout: false,diff --git a/lib/plausible_web/views/stats_view.ex b/lib/plausible_web/views/stats_view.exindex 4385a3bda3..c40e2ef706 100644--- a/lib/plausible_web/views/stats_view.ex+++ b/lib/plausible_web/views/stats_view.ex@@ -30,79 +30,6 @@ defmodule PlausibleWeb.StatsView do"""end- def timeframe_to_human(query) do- case query.period do- "day" ->- "on #{Timex.format!(query.date_range.first, "{Mfull} {D}")}"- "month" ->- "in #{Timex.format!(query.date_range.first, "{Mfull} {YYYY}")}"- "7d" ->- "in the last 7 days"- "3mo" ->- "in the last 3 months"- "6mo" ->- "in the last 6 months"- end- end-- def query_params(query) do- case query.period do- "day" ->- date = Date.to_iso8601(query.date_range.first)- "?period=day&date=#{date}"- "month" ->- date = Date.to_iso8601(query.date_range.first)- "?period=month&date=#{date}"- "7d" ->- "?period=7d"- "3mo" ->- "?period=3mo"- "6mo" ->- "?period=6mo"- end- end-- def today(site) do- Timex.now(site.timezone)- |> DateTime.to_date- end-- def this_month(site) do- Timex.now(site.timezone)- |> DateTime.to_date- |> Timex.beginning_of_month- end-- def last_month(site) do- this_month(site)- |> Timex.shift(months: -1)- end-- def timeframe_text(site, query) do- case query.period do- "6mo" ->- "Last 6 months"- "3mo" ->- "Last 3 months"- "month" ->- if query.date_range.first == this_month(site) do- "This month"- else- Timex.format!(query.date_range.first, "{Mfull} {YYYY}")- end- "7d" ->- "Last 7 days"- "day" ->- if query.date_range.first == today(site) do- "Today"- else- Timex.format!(query.date_range.first, "{D} {Mfull} {YYYY}")- end- _ ->- "wat"- end- end-defp bar_width(count, all) domax = Enum.max_by(all, fn{_, count} -> count@@ -111,44 +38,4 @@ defmodule PlausibleWeb.StatsView docount / max * 100end-- def icon_for("Mobile") do- ~E"""- <svg width="16px" height="16px" style="transform: translateY(3px)" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-smartphone"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12" y2="18"/></svg>- """- end-- def icon_for("Tablet") do- ~E"""- <svg width="16px" height="16px" style="transform: translateY(3px)" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-tablet"><rect x="4" y="2" width="16" height="20" rx="2" ry="2" transform="rotate(180 12 12)"/><line x1="12" y1="18" x2="12" y2="18"/></svg>- """- end-- def icon_for("Laptop") do- ~E"""- <svg width="16px" height="16px" style="transform: translateY(3px)" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-laptop"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="2" y1="20" x2="22" y2="20"/></svg>- """- end-- def icon_for("Desktop") do- ~E"""- <svg width="16px" height="16px" style="transform: translateY(3px)" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-monitor"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>- """- end-- def explanation_for("Mobile") do- "up to 576px"- end-- def explanation_for("Tablet") do- "576px to 992px"- end-- def explanation_for("Laptop") do- "992px to 1440px"- end-- def explanation_for("Desktop") do- "above 1440px"- endenddiff --git a/test/plausible/stats/query_test.exs b/test/plausible/stats/query_test.exsindex d365b6fffc..7422d1e611 100644--- a/test/plausible/stats/query_test.exs+++ b/test/plausible/stats/query_test.exs@@ -12,6 +12,15 @@ defmodule Plausible.Stats.QueryTest doassert q.step_type == "hour"end+ test "day fromat defaults to today" do+ q = Query.from(@tz, %{"period" => "day"})++ assert q.date_range.first == Timex.today()+ assert q.date_range.last == Timex.today()+ assert q.step_type == "hour"+ end++test "parses month format" doq = Query.from(@tz, %{"period" => "month", "date" => "2019-01-01"})diff --git a/test/plausible/stats/stats_test.exs b/test/plausible/stats/stats_test.exsdeleted file mode 100644index 2af11c42b3..0000000000--- a/test/plausible/stats/stats_test.exs+++ /dev/null@@ -1,393 +0,0 @@-defmodule Plausible.StatsTest do- use Plausible.DataCase- alias Plausible.Stats- @user_id UUID.uuid4()-- describe "compare_pageviews_and_visitors" do- test "comparisons are nil when no historical data" do- site = insert(:site)- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})- res = Stats.compare_pageviews_and_visitors(site, query, {10, 10})-- assert res == {nil, nil}- end-- test "comparisons show percent change with historical data" do- site = insert(:site)- insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-02"})- {change_pageviews, change_visitors} = Stats.compare_pageviews_and_visitors(site, query, {3, 2})-- assert change_pageviews == 50- assert change_visitors == 100- end- end-- describe "visitors_from_referrer" do- test "queries for new visitors from a referrer source" do- site = insert(:site)- insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: false, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, referrer_source: "Bing", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.visitors_from_referrer(site, query, "Google") == 2- end- end-- describe "top_pages" do- test "shows top 5 pages by pageviews" do- site = insert(:site)- insert(:pageview, hostname: site.domain, pathname: "/", timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, pathname: "/", timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, pathname: "/hello", timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.top_pages(site, query) == [- {"/", 2},- {"/hello", 1}- ]- end- end-- describe "top_screen_sizes" do- test "shows top screen sizes by new visitors and percentages" do- site = insert(:site)- insert(:pageview, hostname: site.domain, screen_size: "desktop", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, screen_size: "desktop", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, screen_size: "mobile", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.top_screen_sizes(site, query) == [- {"mobile", 1, 33},- {"desktop", 2, 67}- ]- end- end-- describe "countries" do- test "shows top countries by new visitors and percentages" do- site = insert(:site)- insert(:pageview, hostname: site.domain, country_code: "EE", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, country_code: "EE", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, country_code: "GB", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.countries(site, query) == [- {"Estonia", 2, 67},- {"United Kingdom", 1, 33}- ]- end- end-- describe "browsers" do- test "shows top browsers by new visitors" do- site = insert(:site)- insert(:pageview, hostname: site.domain, browser: "Chrome", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, browser: "Chrome", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, browser: "Safari", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.browsers(site, query) == [- {"Chrome", 2, 67},- {"Safari", 1, 33}- ]- end- end-- describe "operating_systems" do- test "shows top operating systems by new visitors" do- site = insert(:site)- insert(:pageview, hostname: site.domain, operating_system: "Mac", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])- insert(:pageview, hostname: site.domain, operating_system: "Windows", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- insert(:pageview, hostname: site.domain, operating_system: "Windows", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- assert Stats.operating_systems(site, query) == [- {"Windows", 2, 67},- {"Mac", 1, 33}- ]- end- end-- describe "pageviews_and_visitors" do- test "counts unique visitors" do- site = insert(:site)- insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 00:00:00])- insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 23:59:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})- {pageviews, visitors} = Stats.pageviews_and_visitors(site, query)-- assert pageviews == 2- assert visitors == 1- end-- test "does not count custom events" do- site = insert(:site)- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])- insert(:event, name: "Custom", hostname: site.domain, timestamp: ~N[2019-01-01 23:59:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})- {pageviews, visitors} = Stats.pageviews_and_visitors(site, query)-- assert pageviews == 1- assert visitors == 1- end- end-- describe "calculate_plot" do- test "displays pageviews for a day" do- site = insert(:site)- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 23:59:00])-- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- {plot, _labels, _index} = Stats.calculate_plot(site, query)-- zeroes = Stream.repeatedly(fn -> 0 end) |> Stream.take(22) |> Enum.into([])-- assert Enum.count(plot) == 24- assert plot == [1] ++ zeroes ++ [1]- end-- test "displays hourly stats in configured timezone" do- site = insert(:site, timezone: "CET") # UTC+1- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00]) # Timestamp is in UTC-- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- {plot, _labels, _index} = Stats.calculate_plot(site, query)-- zeroes = Stream.repeatedly(fn -> 0 end) |> Stream.take(22) |> Enum.into([])-- assert plot == [0, 1] ++ zeroes # Expecting pageview to show at 1am CET- end-- test "displays pageviews for a month" do- site = insert(:site)- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 12:00:00])- insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-31 12:00:00])-- query = Stats.Query.from(site.timezone, %{"period" => "month", "date" => "2019-01-01"})- {plot, _labels, _index} = Stats.calculate_plot(site, query)-- assert Enum.count(plot) == 31- assert List.first(plot) == 1- assert List.last(plot) == 1- end-- test "displays pageviews for a 3 months" do- site = insert(:site)- insert(:pageview, hostname: site.domain)- insert(:pageview, hostname: site.domain, timestamp: months_ago(2))-- query = Stats.Query.from(site.timezone, %{"period" => "3mo"})- {plot, _labels, _index} = Stats.calculate_plot(site, query)-- assert Enum.count(plot) == 3- assert plot == [1, 0, 1]- end- end-- describe "labels" do- test "shows last 30 days" do- site = insert(:site)-- query = %Stats.Query{- date_range: Date.range(~D[2019-01-01], ~D[2019-01-31]),- step_type: "date"- }-- {_plot, labels, _index} = Stats.calculate_plot(site, query)-- assert List.first(labels) == "2019-01-01"- assert List.last(labels) == "2019-01-31"- end-- test "shows last 7 days" do- site = insert(:site)- query = %Stats.Query{- date_range: Date.range(~D[2019-01-01], ~D[2019-01-08]),- step_type: "date"- }-- {_plot, labels, _index} = Stats.calculate_plot(site, query)-- assert List.first(labels) == "2019-01-01"- assert List.last(labels) == "2019-01-08"- end-- test "shows last 24 hours" do- site = insert(:site)- query = %Stats.Query{- period: "day",- date_range: Date.range(~D[2019-01-31], ~D[2019-01-31]),- step_type: "hour"- }-- {_plot, labels, _index} = Stats.calculate_plot(site, query)-- assert List.first(labels) == "2019-01-31T00:00:00"- assert List.last(labels) == "2019-01-31T23:00:00"- end- end-- describe "referrer_drilldown" do- test "shows grouped counts of referrers" do- site = insert(:site)-- insert(:pageview, %{- hostname: site.domain,- referrer: "10words.io/somepage",- referrer_source: "10words",- new_visitor: true- })-- insert(:pageview, %{- hostname: site.domain,- referrer: "10words.io/somepage",- referrer_source: "10words",- new_visitor: true- })-- insert(:pageview, %{- hostname: site.domain,- referrer: "10words.io/some_other_page",- referrer_source: "10words",- new_visitor: true- })-- query = Stats.Query.from("UTC", %{"period" => "day"})- drilldown = Stats.referrer_drilldown(site, query, "10words")-- assert {"10words.io/somepage", 2} in drilldown- assert {"10words.io/some_other_page", 1} in drilldown- end-- test "counts nil values as a group" do- site = insert(:site)-- insert(:pageview, %{- hostname: site.domain,- referrer: nil,- referrer_source: "10words",- new_visitor: true- })-- insert(:pageview, %{- hostname: site.domain,- referrer: nil,- referrer_source: "10words",- new_visitor: true- })-- query = Stats.Query.from("UTC", %{"period" => "day"})- drilldown = Stats.referrer_drilldown(site, query, "10words")-- assert {nil, 2} in drilldown- end- end-- describe "current_visitors" do- test "counts user ids seen in the last 5 minutes" do- site = insert(:site)-- insert(:pageview, %{- hostname: site.domain,- user_id: UUID.uuid4(),- })-- insert(:pageview, %{- hostname: site.domain,- user_id: UUID.uuid4(),- timestamp: Timex.now() |> Timex.shift(minutes: -4)- })-- insert(:pageview, %{- hostname: site.domain,- user_id: UUID.uuid4(),- timestamp: Timex.now() |> Timex.shift(minutes: -6)- })-- assert Stats.current_visitors(site) == 2- end-- test "counts unique user ids" do- site = insert(:site)- id = UUID.uuid4()-- insert(:pageview, %{- hostname: site.domain,- user_id: id,- })-- insert(:pageview, %{- hostname: site.domain,- user_id: id,- })-- assert Stats.current_visitors(site) == 1- end- end-- describe "goal_conversions" do- test "shows custom event conversions" do- site = insert(:site)- insert(:goal, %{domain: site.domain, event_name: "Register"})- insert(:goal, %{domain: site.domain, event_name: "Newsletter signup"})- insert(:event, name: "Register", hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "Register", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "Newsletter signup", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "Irrelevant", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- conversions = Stats.goal_conversions(site, query)-- assert conversions == [- {"Register", 2},- {"Newsletter signup", 1}- ]- end-- test "shows pageview conversions" do- site = insert(:site)- insert(:goal, %{domain: site.domain, page_path: "/success"})- insert(:goal, %{domain: site.domain, page_path: "/register"})- insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "pageview", pathname: "/register", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "pageview", pathname: "/irrelevant", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- conversions = Stats.goal_conversions(site, query)-- assert conversions == [- {"Visit /success", 2},- {"Visit /register", 1}- ]- end-- test "shows mixed conversions in order of occurence" do- site = insert(:site)- insert(:goal, %{domain: site.domain, page_path: "/success"})- insert(:goal, %{domain: site.domain, event_name: "Signup"})- insert(:event, name: "Signup", hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, user_id: UUID.uuid4(), timestamp: ~N[2019-01-01 01:00:00])- query = Stats.Query.from(site.timezone, %{"period" => "day", "date" => "2019-01-01"})-- conversions = Stats.goal_conversions(site, query)-- assert conversions == [- {"Visit /success", 2},- {"Signup", 1}- ]- end- end-- defp months_ago(months) do- Timex.now() |> Timex.shift(months: -months)- end-enddiff --git a/test/plausible_web/controllers/api/stats_controller/authorization_test.exs b/test/plausible_web/controllers/api/stats_controller/authorization_test.exsnew file mode 100644index 0000000000..815014e2c8--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/authorization_test.exs@@ -0,0 +1,61 @@+defmodule PlausibleWeb.Api.StatsController.AuthorizationTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "API authorization - as anonymous user" do+ test "Sends 401 unauthorized for a site that doesn't exist", %{conn: conn} do+ conn = init_session(conn)+ conn = get(conn, "/api/stats/fake-site.com/main-graph")++ assert conn.status == 401+ end++ test "Sends 401 unauthorized for private site", %{conn: conn} do+ conn = init_session(conn)+ site = insert(:site, public: false)+ conn = get(conn, "/api/stats/#{site.domain}/main-graph")++ assert conn.status == 401+ end++ test "returns stats for public site", %{conn: conn} do+ conn = init_session(conn)+ site = insert(:site, public: true)+ conn = get(conn, "/api/stats/#{site.domain}/main-graph")++ assert %{"unique_visitors" => _any} = json_response(conn, 200)+ end+ end++ describe "API authorization - as logged in user" do+ setup [:create_user, :log_in]++ test "Sends 401 unauthorized for a site that doesn't exist", %{conn: conn} do+ conn = init_session(conn)+ conn = get(conn, "/api/stats/fake-site.com/main-graph")++ assert conn.status == 401+ end++ test "Sends 401 unauthorized when user does not have access to site", %{conn: conn} do+ site = insert(:site)+ conn = get(conn, "/api/stats/#{site.domain}/main-graph")++ assert conn.status == 401+ end++ test "returns stats for public site", %{conn: conn} do+ site = insert(:site, public: true)+ conn = get(conn, "/api/stats/#{site.domain}/main-graph")++ assert %{"unique_visitors" => _any} = json_response(conn, 200)+ end++ test "returns stats for a private site that the user owns", %{conn: conn, user: user} do+ site = insert(:site, public: false, members: [user])+ conn = get(conn, "/api/stats/#{site.domain}/main-graph")++ assert %{"unique_visitors" => _any} = json_response(conn, 200)+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/browsers_test.exs b/test/plausible_web/controllers/api/stats_controller/browsers_test.exsnew file mode 100644index 0000000000..4445b5b139--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/browsers_test.exs@@ -0,0 +1,21 @@+defmodule PlausibleWeb.Api.StatsController.BrowsersTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/browsers" do+ setup [:create_user, :log_in, :create_site]++ test "returns top browsers by new visitors", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, browser: "Chrome", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, browser: "Chrome", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, browser: "Firefox", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/browsers?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Chrome", "count" => 2, "percentage" => 67},+ %{"name" => "Firefox", "count" => 1, "percentage" => 33},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/conversions_test.exs b/test/plausible_web/controllers/api/stats_controller/conversions_test.exsnew file mode 100644index 0000000000..318d77621a--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/conversions_test.exs@@ -0,0 +1,57 @@+defmodule PlausibleWeb.Api.StatsController.ConversionsTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/conversions" do+ setup [:create_user, :log_in, :create_site]++ test "returns custom event conversions", %{conn: conn, site: site} do+ insert(:goal, %{domain: site.domain, event_name: "Register"})+ insert(:goal, %{domain: site.domain, event_name: "Newsletter signup"})+ insert(:event, name: "Register", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "Register", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "Newsletter signup", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "Irrelevant", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/conversions?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Register", "count" => 2},+ %{"name" => "Newsletter signup", "count" => 1},+ ]+ end++ test "returns pageview conversions", %{conn: conn, site: site} do+ insert(:goal, %{domain: site.domain, page_path: "/success"})+ insert(:goal, %{domain: site.domain, page_path: "/register"})++ insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "pageview", pathname: "/register", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "pageview", pathname: "/irrelevant", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/conversions?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Visit /success", "count" => 2},+ %{"name" => "Visit /register", "count" => 1},+ ]+ end++ test "returns mixed conversions in ordered by count", %{conn: conn, site: site} do+ insert(:goal, %{domain: site.domain, page_path: "/success"})+ insert(:goal, %{domain: site.domain, event_name: "Signup"})++ insert(:event, name: "Signup", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:event, name: "pageview", pathname: "/success", hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/conversions?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Visit /success", "count" => 2},+ %{"name" => "Signup", "count" => 1},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/countries_test.exs b/test/plausible_web/controllers/api/stats_controller/countries_test.exsnew file mode 100644index 0000000000..1fc4947105--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/countries_test.exs@@ -0,0 +1,21 @@+defmodule PlausibleWeb.Api.StatsController.CountriesTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/countries" do+ setup [:create_user, :log_in, :create_site]++ test "returns top countries by new visitors", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, country_code: "EE", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, country_code: "EE", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, country_code: "GB", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/countries?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Estonia", "count" => 2, "percentage" => 67},+ %{"name" => "United Kingdom", "count" => 1, "percentage" => 33},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/current_visitors_test.exs b/test/plausible_web/controllers/api/stats_controller/current_visitors_test.exsnew file mode 100644index 0000000000..f8fedc2033--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/current_visitors_test.exs@@ -0,0 +1,19 @@+defmodule PlausibleWeb.Api.StatsController.CurrentVisitorsTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/current-visitors" do+ setup [:create_user, :log_in, :create_site]++ test "returns unique users in the last 5 minutes", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain)+ event2 = insert(:pageview, hostname: site.domain, timestamp: Timex.now() |> Timex.shift(minutes: -3))+ insert(:pageview, hostname: site.domain, user_id: event2.user_id, timestamp: Timex.now() |> Timex.shift(minutes: -4))+ insert(:pageview, hostname: site.domain, timestamp: Timex.now() |> Timex.shift(minutes: -6))++ conn = get(conn, "/api/stats/#{site.domain}/current-visitors?period=day&date=2019-01-01")++ assert json_response(conn, 200) == 2+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exsnew file mode 100644index 0000000000..0a76932620--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/main_graph_test.exs@@ -0,0 +1,161 @@+defmodule PlausibleWeb.Api.StatsController.MainGraphTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils+ @user_id UUID.uuid4()++ describe "GET /api/stats/main-graph - plot" do+ setup [:create_user, :log_in, :create_site]++ test "displays pageviews for a day", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 23:59:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"plot" => plot} = json_response(conn, 200)++ zeroes = Stream.repeatedly(fn -> 0 end) |> Stream.take(22) |> Enum.into([])++ assert Enum.count(plot) == 24+ assert plot == [1] ++ zeroes ++ [1]+ end++ test "displays hourly stats in configured timezone", %{conn: conn, user: user} do+ site = insert(:site, members: [user], timezone: "CET") # UTC+1+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00]) # Timestamp is in UTC++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"plot" => plot} = json_response(conn, 200)++ zeroes = Stream.repeatedly(fn -> 0 end) |> Stream.take(22) |> Enum.into([])++ assert plot == [0, 1] ++ zeroes # Expecting pageview to show at 1am CET+ end++ test "displays pageviews for a month", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 12:00:00])+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-31 12:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=month&date=2019-01-01")++ assert %{"plot" => plot} = json_response(conn, 200)++ assert Enum.count(plot) == 31+ assert List.first(plot) == 1+ assert List.last(plot) == 1+ end++ test "displays pageviews for 3 months", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain)+ insert(:pageview, hostname: site.domain, timestamp: months_ago(2))++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=3mo")++ assert %{"plot" => plot} = json_response(conn, 200)++ assert plot == [1, 0, 1]+ end++ # TODO: missing 6 months, 7 days, 30 days+ end++ describe "GET /api/stats/main-graph - labels" do+ setup [:create_user, :log_in, :create_site]++ test "shows last 30 days", %{conn: conn, site: site} do+ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=30d")+ assert %{"labels" => labels} = json_response(conn, 200)++ {:ok, first} = Timex.today() |> Timex.shift(days: -30) |> Timex.format("{ISOdate}")+ {:ok, last} = Timex.today() |> Timex.format("{ISOdate}")+ assert List.first(labels) == first+ assert List.last(labels) == last+ end++ test "shows last 7 days", %{conn: conn, site: site} do+ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=7d")+ assert %{"labels" => labels} = json_response(conn, 200)++ {:ok, first} = Timex.today() |> Timex.shift(days: -7) |> Timex.format("{ISOdate}")+ {:ok, last} = Timex.today() |> Timex.format("{ISOdate}")+ assert List.first(labels) == first+ assert List.last(labels) == last+ end+ end++ describe "GET /api/stats/main-graph - unique visitors" do+ setup [:create_user, :log_in, :create_site]++ test "counts distinct user ids", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 00:00:00])+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 23:59:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"unique_visitors" => 1} = json_response(conn, 200)+ end++ test "does not count custom events", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])+ insert(:event, name: "Custom", hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"unique_visitors" => 1} = json_response(conn, 200)+ end+ end++ describe "GET /api/stats/main-graph - pageviews" do+ setup [:create_user, :log_in, :create_site]++ test "counts total pageviews even from same user ids", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 00:00:00])+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 23:59:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"pageviews" => 2} = json_response(conn, 200)+ end++ test "does not count custom events", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])+ insert(:event, name: "Custom", hostname: site.domain, timestamp: ~N[2019-01-01 00:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-01")++ assert %{"unique_visitors" => 1} = json_response(conn, 200)+ end+ end++ describe "GET /api/stats/main-graph - comparisons" do+ setup [:create_user, :log_in, :create_site]++ test "compares unique users with previous time period", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, user_id: @user_id, timestamp: ~N[2019-01-01 02:00:00])++ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-02 01:00:00])+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-02 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-02")++ assert %{"change_visitors" => 100} = json_response(conn, 200)+ end++ test "compares pageviews with previous time period", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-01 02:00:00])++ insert(:pageview, hostname: site.domain, timestamp: ~N[2019-01-02 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/main-graph?period=day&date=2019-01-02")++ assert %{"change_pageviews" => -50} = json_response(conn, 200)+ end+ end++ defp months_ago(months) do+ Timex.now() |> Timex.shift(months: -months)+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/operating_systems_test.exs b/test/plausible_web/controllers/api/stats_controller/operating_systems_test.exsnew file mode 100644index 0000000000..00f4f6cbc3--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/operating_systems_test.exs@@ -0,0 +1,21 @@+defmodule PlausibleWeb.Api.StatsController.OperatingSystemsTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/operating_systems" do+ setup [:create_user, :log_in, :create_site]++ test "returns operating systems by new visitors", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, operating_system: "Mac", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, operating_system: "Mac", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, operating_system: "Android", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/operating-systems?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Mac", "count" => 2, "percentage" => 67},+ %{"name" => "Android", "count" => 1, "percentage" => 33},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/pages_test.exs b/test/plausible_web/controllers/api/stats_controller/pages_test.exsnew file mode 100644index 0000000000..b6d9d0a827--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/pages_test.exs@@ -0,0 +1,21 @@+defmodule PlausibleWeb.Api.StatsController.PagesTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/pages" do+ setup [:create_user, :log_in, :create_site]++ test "returns top pages sources by pageviews", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, pathname: "/", timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, pathname: "/", timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, pathname: "/contact", timestamp: ~N[2019-01-01 01:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/pages?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "/", "count" => 2},+ %{"name" => "/contact", "count" => 1},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/referrers_test.exs b/test/plausible_web/controllers/api/stats_controller/referrers_test.exsnew file mode 100644index 0000000000..361645a214--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/referrers_test.exs@@ -0,0 +1,62 @@+defmodule PlausibleWeb.Api.StatsController.ReferrersTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/referrers" do+ setup [:create_user, :log_in, :create_site]++ test "returns top referrer sources by new visitors", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: false, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, referrer_source: "Google", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, referrer_source: "Bing", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/referrers?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Google", "count" => 2},+ %{"name" => "Bing", "count" => 1},+ ]+ end+ end++ describe "GET /api/stats/:domain/referrer-drilldown" do+ setup [:create_user, :log_in, :create_site]++ test "returns top referrers for a particular source", %{conn: conn, site: site} do+ insert(:pageview, %{+ hostname: site.domain,+ referrer: "10words.io/somepage",+ referrer_source: "10words",+ new_visitor: true,+ timestamp: ~N[2019-01-01 01:00:00]+ })++ insert(:pageview, %{+ hostname: site.domain,+ referrer: "10words.io/somepage",+ referrer_source: "10words",+ new_visitor: true,+ timestamp: ~N[2019-01-01 01:00:00]+ })++ insert(:pageview, %{+ hostname: site.domain,+ referrer: "10words.io/some_other_page",+ referrer_source: "10words",+ new_visitor: true,+ timestamp: ~N[2019-01-01 01:00:00]+ })++ conn = get(conn, "/api/stats/#{site.domain}/referrers/10words?period=day&date=2019-01-01")++ assert json_response(conn, 200) == %{+ "total_visitors" => 3,+ "referrers" => [+ %{"name" => "10words.io/somepage", "count" => 2},+ %{"name" => "10words.io/some_other_page", "count" => 1},+ ]+ }+ end+ end+enddiff --git a/test/plausible_web/controllers/api/stats_controller/screen_sizes_test.exs b/test/plausible_web/controllers/api/stats_controller/screen_sizes_test.exsnew file mode 100644index 0000000000..fd09b400e8--- /dev/null+++ b/test/plausible_web/controllers/api/stats_controller/screen_sizes_test.exs@@ -0,0 +1,21 @@+defmodule PlausibleWeb.Api.StatsController.ScreenSizesTest do+ use PlausibleWeb.ConnCase+ import Plausible.TestUtils++ describe "GET /api/stats/:domain/browsers" do+ setup [:create_user, :log_in, :create_site]++ test "returns screen sizes by new visitors", %{conn: conn, site: site} do+ insert(:pageview, hostname: site.domain, screen_size: "Desktop", new_visitor: true, timestamp: ~N[2019-01-01 01:00:00])+ insert(:pageview, hostname: site.domain, screen_size: "Desktop", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])+ insert(:pageview, hostname: site.domain, screen_size: "Mobile", new_visitor: true, timestamp: ~N[2019-01-01 02:00:00])++ conn = get(conn, "/api/stats/#{site.domain}/screen-sizes?period=day&date=2019-01-01")++ assert json_response(conn, 200) == [+ %{"name" => "Desktop", "count" => 2, "percentage" => 67},+ %{"name" => "Mobile", "count" => 1, "percentage" => 33},+ ]+ end+ end+enddiff --git a/test/plausible_web/controllers/stats_controller_test.exs b/test/plausible_web/controllers/stats_controller_test.exsindex e874f9deec..90bfa8075f 100644--- a/test/plausible_web/controllers/stats_controller_test.exs+++ b/test/plausible_web/controllers/stats_controller_test.exs@@ -9,7 +9,7 @@ defmodule PlausibleWeb.StatsControllerTest doinsert(:pageview, hostname: "public-site.io")conn = get(conn, "/public-site.io")- assert html_response(conn, 200) =~ "Analytics for"+ assert html_response(conn, 200) =~ "stats-react-container"endtest "can not view stats of a private website", %{conn: conn} do@@ -27,7 +27,7 @@ defmodule PlausibleWeb.StatsControllerTest doinsert(:pageview, hostname: site.domain)conn = get(conn, "/" <> site.domain)- assert html_response(conn, 200) =~ "Analytics for"+ assert html_response(conn, 200) =~ "stats-react-container"endtest "can not view stats of someone else's website", %{conn: conn} dodiff --git a/test/support/test_utils.ex b/test/support/test_utils.exindex bd33993981..3804a5879c 100644--- a/test/support/test_utils.ex+++ b/test/support/test_utils.ex@@ -7,12 +7,18 @@ defmodule Plausible.TestUtils doenddef create_site(%{user: user}) do- site = Factory.insert(:site)- Plausible.Site.Membership.changeset(%Plausible.Site.Membership{}, %{site_id: site.id, user_id: user.id}) |> Repo.insert!+ site = Factory.insert(:site, members: [user]){:ok, site: site}enddef log_in(%{user: user, conn: conn}) do+ conn = init_session(conn)+ |> Plug.Conn.put_session(:current_user_id, user.id)++ {:ok, conn: conn}+ end++ def init_session(conn) doopts =Plug.Session.init(store: :cookie,@@ -23,12 +29,8 @@ defmodule Plausible.TestUtils doencrypt: false)- conn =- conn+ conn|> Plug.Session.call(opts)|> Plug.Conn.fetch_session()- |> Plug.Conn.put_session(:current_user_id, user.id)-- {:ok, conn: conn}endend