Compare commits
7 Commits
master
...
sentry-fro
| Author | SHA1 | Date |
|---|---|---|
|
|
129fc86891 | 4 years ago |
|
|
4a393aa8e5 | 4 years ago |
|
|
a36af1d5e9 | 4 years ago |
|
|
d14c265ae2 | 4 years ago |
|
|
1f25f81aaa | 4 years ago |
|
|
3f79ee75d3 | 4 years ago |
|
|
5dc9d0fb33 | 4 years ago |
@ -1,205 +0,0 @@
|
||||
# This file contains the configuration for Credo and you are probably reading
|
||||
# this after creating it with `mix credo.gen.config`.
|
||||
#
|
||||
# If you find anything wrong or unclear in this file, please report an
|
||||
# issue on GitHub: https://github.com/rrrene/credo/issues
|
||||
#
|
||||
%{
|
||||
#
|
||||
# You can have as many configs as you like in the `configs:` field.
|
||||
configs: [
|
||||
%{
|
||||
#
|
||||
# Run any config using `mix credo -C <name>`. If no config name is given
|
||||
# "default" is used.
|
||||
#
|
||||
name: "default",
|
||||
#
|
||||
# These are the files included in the analysis:
|
||||
files: %{
|
||||
#
|
||||
# You can give explicit globs or simply directories.
|
||||
# In the latter case `**/*.{ex,exs}` will be used.
|
||||
#
|
||||
included: [
|
||||
"lib/",
|
||||
"test/",
|
||||
"extra/"
|
||||
],
|
||||
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
|
||||
},
|
||||
#
|
||||
# Load and configure plugins here:
|
||||
#
|
||||
plugins: [],
|
||||
#
|
||||
# If you create your own checks, you must specify the source files for
|
||||
# them here, so they can be loaded by Credo before running the analysis.
|
||||
#
|
||||
requires: [],
|
||||
#
|
||||
# If you want to enforce a style guide and need a more traditional linting
|
||||
# experience, you can change `strict` to `true` below:
|
||||
#
|
||||
strict: false,
|
||||
#
|
||||
# To modify the timeout for parsing files, change this value:
|
||||
#
|
||||
parse_timeout: 5000,
|
||||
#
|
||||
# If you want to use uncolored output by default, you can change `color`
|
||||
# to `false` below:
|
||||
#
|
||||
color: true,
|
||||
#
|
||||
# You can customize the parameters of any check by adding a second element
|
||||
# to the tuple.
|
||||
#
|
||||
# To disable a check put `false` as second element:
|
||||
#
|
||||
# {Credo.Check.Design.DuplicatedCode, false}
|
||||
#
|
||||
checks: %{
|
||||
enabled: [
|
||||
#
|
||||
## Consistency Checks
|
||||
#
|
||||
{Credo.Check.Consistency.ExceptionNames, []},
|
||||
{Credo.Check.Consistency.LineEndings, []},
|
||||
{Credo.Check.Consistency.ParameterPatternMatching, []},
|
||||
{Credo.Check.Consistency.SpaceAroundOperators, []},
|
||||
{Credo.Check.Consistency.SpaceInParentheses, []},
|
||||
{Credo.Check.Consistency.TabsOrSpaces, []},
|
||||
|
||||
#
|
||||
## Design Checks
|
||||
#
|
||||
# You can customize the priority of any check
|
||||
# Priority values are: `low, normal, high, higher`
|
||||
#
|
||||
{Credo.Check.Design.AliasUsage,
|
||||
[priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]},
|
||||
# You can also customize the exit_status of each check.
|
||||
# If you don't want TODO comments to cause `mix credo` to fail, just
|
||||
# set this value to 0 (zero).
|
||||
#
|
||||
{Credo.Check.Design.TagTODO, [exit_status: 2]},
|
||||
{Credo.Check.Design.TagFIXME, []},
|
||||
|
||||
#
|
||||
## Readability Checks
|
||||
#
|
||||
{Credo.Check.Readability.AliasOrder, []},
|
||||
{Credo.Check.Readability.FunctionNames, []},
|
||||
{Credo.Check.Readability.LargeNumbers, []},
|
||||
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
|
||||
{Credo.Check.Readability.ModuleAttributeNames, []},
|
||||
{Credo.Check.Readability.ModuleDoc, []},
|
||||
{Credo.Check.Readability.ModuleNames, []},
|
||||
{Credo.Check.Readability.ParenthesesInCondition, []},
|
||||
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
|
||||
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
|
||||
{Credo.Check.Readability.PredicateFunctionNames, []},
|
||||
{Credo.Check.Readability.PreferImplicitTry, []},
|
||||
{Credo.Check.Readability.RedundantBlankLines, []},
|
||||
{Credo.Check.Readability.Semicolons, []},
|
||||
{Credo.Check.Readability.SpaceAfterCommas, []},
|
||||
{Credo.Check.Readability.StringSigils, []},
|
||||
{Credo.Check.Readability.TrailingBlankLine, []},
|
||||
{Credo.Check.Readability.TrailingWhiteSpace, []},
|
||||
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
|
||||
{Credo.Check.Readability.VariableNames, []},
|
||||
{Credo.Check.Readability.WithSingleClause, []},
|
||||
|
||||
#
|
||||
## Refactoring Opportunities
|
||||
#
|
||||
{Credo.Check.Refactor.Apply, []},
|
||||
{Credo.Check.Refactor.CondStatements, []},
|
||||
{Credo.Check.Refactor.CyclomaticComplexity, false},
|
||||
{Credo.Check.Refactor.FunctionArity, []},
|
||||
{Credo.Check.Refactor.LongQuoteBlocks, []},
|
||||
{Credo.Check.Refactor.MatchInCondition, []},
|
||||
{Credo.Check.Refactor.MapJoin, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsWithElse, false},
|
||||
{Credo.Check.Refactor.Nesting, []},
|
||||
{Credo.Check.Refactor.UnlessWithElse, []},
|
||||
{Credo.Check.Refactor.WithClauses, []},
|
||||
{Credo.Check.Refactor.FilterFilter, []},
|
||||
{Credo.Check.Refactor.RejectReject, []},
|
||||
{Credo.Check.Refactor.RedundantWithClauseResult, []},
|
||||
|
||||
#
|
||||
## Warnings
|
||||
#
|
||||
{Credo.Check.Warning.ApplicationConfigInModuleAttribute, []},
|
||||
{Credo.Check.Warning.BoolOperationOnSameValues, []},
|
||||
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
|
||||
{Credo.Check.Warning.IExPry, []},
|
||||
{Credo.Check.Warning.IoInspect, []},
|
||||
{Credo.Check.Warning.OperationOnSameValues, []},
|
||||
{Credo.Check.Warning.OperationWithConstantResult, []},
|
||||
{Credo.Check.Warning.RaiseInsideRescue, []},
|
||||
{Credo.Check.Warning.SpecWithStruct, []},
|
||||
{Credo.Check.Warning.WrongTestFileExtension, []},
|
||||
{Credo.Check.Warning.UnusedEnumOperation, []},
|
||||
{Credo.Check.Warning.UnusedFileOperation, []},
|
||||
{Credo.Check.Warning.UnusedKeywordOperation, []},
|
||||
{Credo.Check.Warning.UnusedListOperation, []},
|
||||
{Credo.Check.Warning.UnusedPathOperation, []},
|
||||
{Credo.Check.Warning.UnusedRegexOperation, []},
|
||||
{Credo.Check.Warning.UnusedStringOperation, []},
|
||||
{Credo.Check.Warning.UnusedTupleOperation, []},
|
||||
{Credo.Check.Warning.UnsafeExec, []}
|
||||
],
|
||||
disabled: [
|
||||
#
|
||||
# Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`)
|
||||
|
||||
#
|
||||
# Controversial and experimental checks (opt-in, just move the check to `:enabled`
|
||||
# and be sure to use `mix credo --strict` to see low priority checks)
|
||||
#
|
||||
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
|
||||
{Credo.Check.Consistency.UnusedVariableNames, []},
|
||||
{Credo.Check.Design.DuplicatedCode, []},
|
||||
{Credo.Check.Design.SkipTestWithoutComment, []},
|
||||
{Credo.Check.Readability.AliasAs, []},
|
||||
{Credo.Check.Readability.BlockPipe, []},
|
||||
{Credo.Check.Readability.ImplTrue, []},
|
||||
{Credo.Check.Readability.MultiAlias, []},
|
||||
{Credo.Check.Readability.NestedFunctionCalls, []},
|
||||
{Credo.Check.Readability.SeparateAliasRequire, []},
|
||||
{Credo.Check.Readability.SingleFunctionToBlockPipe, []},
|
||||
{Credo.Check.Readability.SinglePipe, []},
|
||||
{Credo.Check.Readability.Specs, []},
|
||||
{Credo.Check.Readability.StrictModuleLayout, []},
|
||||
{Credo.Check.Readability.WithCustomTaggedTuple, []},
|
||||
{Credo.Check.Refactor.ABCSize, []},
|
||||
{Credo.Check.Refactor.AppendSingleItem, []},
|
||||
{Credo.Check.Refactor.DoubleBooleanNegation, []},
|
||||
{Credo.Check.Refactor.FilterReject, []},
|
||||
{Credo.Check.Refactor.IoPuts, []},
|
||||
{Credo.Check.Refactor.MapMap, []},
|
||||
{Credo.Check.Refactor.ModuleDependencies, []},
|
||||
{Credo.Check.Refactor.NegatedIsNil, []},
|
||||
{Credo.Check.Refactor.PipeChainStart, []},
|
||||
{Credo.Check.Refactor.RejectFilter, []},
|
||||
{Credo.Check.Refactor.VariableRebinding, []},
|
||||
{Credo.Check.Warning.LazyLogging, []},
|
||||
{Credo.Check.Warning.LeakyEnvironment, []},
|
||||
{Credo.Check.Warning.MapGetUnsafePass, []},
|
||||
{Credo.Check.Warning.MixEnv, []},
|
||||
{Credo.Check.Warning.UnsafeToAtom, []}
|
||||
|
||||
# {Credo.Check.Refactor.MapInto, []},
|
||||
|
||||
#
|
||||
# Custom checks can be created using `mix credo.gen.check`.
|
||||
#
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
# This file excludes paths from the Docker build context.
|
||||
#
|
||||
# By default, Docker's build context includes all files (and folders) in the
|
||||
# current directory. Even if a file isn't copied into the container it is still sent to
|
||||
# the Docker daemon.
|
||||
#
|
||||
# There are multiple reasons to exclude files from the build context:
|
||||
#
|
||||
# 1. Prevent nested folders from being copied into the container (ex: exclude
|
||||
# /assets/node_modules when copying /assets)
|
||||
# 2. Reduce the size of the build context and improve build time (ex. /build, /deps, /doc)
|
||||
# 3. Avoid sending files containing sensitive information
|
||||
#
|
||||
# More information on using .dockerignore is available here:
|
||||
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
|
||||
|
||||
.dockerignore
|
||||
|
||||
# Ignore git, but keep git HEAD and refs to access current commit hash if needed:
|
||||
#
|
||||
# $ cat .git/HEAD | awk '{print ".git/"$2}' | xargs cat
|
||||
# d0b8727759e1e0e7aa3d41707d12376e373d5ecc
|
||||
.git
|
||||
!.git/HEAD
|
||||
!.git/refs
|
||||
|
||||
# Common development/test artifacts
|
||||
/cover/
|
||||
/doc/
|
||||
/test/
|
||||
/tmp/
|
||||
.elixir_ls
|
||||
plausible-report.xml
|
||||
.env
|
||||
.idea
|
||||
*.iml
|
||||
*.log
|
||||
*.code-workspace
|
||||
.vscode
|
||||
|
||||
# Mix artifacts
|
||||
/_build/
|
||||
/deps/
|
||||
*.ez
|
||||
|
||||
# Generated on crash by the VM
|
||||
erl_crash.dump
|
||||
|
||||
# If NPM crashes, it generates a log, let's ignore it too.
|
||||
npm-debug.log
|
||||
|
||||
# Static artifacts - These should be fetched and built inside the Docker image
|
||||
/assets/node_modules/
|
||||
/tracker/node_modules/
|
||||
/priv/static/cache_manifest.json
|
||||
/priv/static/css
|
||||
/priv/static/js
|
||||
/priv/version.json
|
||||
|
||||
# Auto-generated tracker files
|
||||
/priv/tracker/js/*.js
|
||||
|
||||
# Dializer
|
||||
/priv/plts/*.plt
|
||||
/priv/plts/*.plt.hash
|
||||
|
||||
# Geolocation databases
|
||||
/priv/geodb/*.mmdb
|
||||
/priv/geodb/*.mmdb.gz
|
||||
|
||||
# Docker volumes
|
||||
.clickhouse_db_vol*
|
||||
plausible_db*
|
||||
@ -1,6 +1,5 @@
|
||||
[
|
||||
plugins: [Phoenix.LiveView.HTMLFormatter],
|
||||
import_deps: [:ecto, :ecto_sql, :phoenix],
|
||||
subdirectories: ["priv/*/migrations"],
|
||||
inputs: ["*.{heex,ex,exs}", "{config,lib,test,extra}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
|
||||
import_deps: [:ecto, :phoenix],
|
||||
inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"],
|
||||
subdirectories: ["priv/*/migrations"]
|
||||
]
|
||||
|
||||
@ -1,67 +0,0 @@
|
||||
name: Build Private Images GHCR
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master, stable]
|
||||
tags: ['r*']
|
||||
pull_request:
|
||||
types: [synchronize, labeled]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'deploy-to-staging') }}
|
||||
runs-on: buildjet-16vcpu-ubuntu-2204
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5.0.0
|
||||
with:
|
||||
images: ghcr.io/plausible/analytics/ee
|
||||
tags: |
|
||||
type=ref,event=pr
|
||||
type=ref,event=branch
|
||||
type=ref,event=tag
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
MIX_ENV=prod
|
||||
BUILD_METADATA=${{ steps.meta.outputs.json }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
- name: Notify team on failure
|
||||
if: ${{ failure() }}
|
||||
uses: fjogeleit/http-request-action@v1
|
||||
with:
|
||||
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
|
||||
method: 'POST'
|
||||
customHeaders: '{"Content-Type": "application/json"}'
|
||||
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-private-images.yml\">Build failed</a>"}'
|
||||
@ -1,68 +0,0 @@
|
||||
name: Build Public Images GHCR
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: buildjet-16vcpu-ubuntu-2204
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/plausible/community-edition
|
||||
tags: |
|
||||
type=semver,pattern={{version}},prefix=v
|
||||
type=semver,pattern={{major}}.{{minor}},prefix=v
|
||||
type=semver,pattern={{major}},prefix=v
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64, linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
MIX_ENV=small
|
||||
BUILD_METADATA=${{ steps.meta.outputs.json }}
|
||||
ERL_FLAGS=+JPperf true
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
- name: Notify team on failure
|
||||
if: ${{ failure() }}
|
||||
uses: fjogeleit/http-request-action@v1
|
||||
with:
|
||||
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
|
||||
method: 'POST'
|
||||
customHeaders: '{"Content-Type": "application/json"}'
|
||||
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-public-images.yml\">Build failed</a>"}'
|
||||
@ -1,28 +0,0 @@
|
||||
name: Validate migrations
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'priv/repo/migrations/**'
|
||||
- 'priv/ingest_repo/migrations/**'
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: App code does not change at the same time
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: changes
|
||||
with:
|
||||
list-files: json
|
||||
filters: |
|
||||
lib:
|
||||
- 'lib/**'
|
||||
- 'extra/**'
|
||||
- 'config/**'
|
||||
|
||||
- if: steps.changes.outputs.lib == 'true'
|
||||
run: |
|
||||
echo "::error file=${{ fromJSON(steps.changes.outputs.lib_files)[0] }}::Code and migrations shouldn't be changed at the same time"
|
||||
exit 1
|
||||
@ -1,19 +0,0 @@
|
||||
alias Plausible.{Repo, ClickhouseRepo, IngestRepo}
|
||||
alias Plausible.{Site, Sites, Goal, Goals, Stats}
|
||||
|
||||
import_if_available(Ecto.Query)
|
||||
import_if_available(Plausible.Factory)
|
||||
|
||||
Logger.configure(level: :warning)
|
||||
|
||||
IO.puts(
|
||||
IO.ANSI.cyan() <>
|
||||
~S[
|
||||
.*$$$$$$s.
|
||||
*$$$$$$$$$$$,
|
||||
:$$SSS#######S *$$$$/. $$ ** $$ l$:
|
||||
,$$SSS#######. $$ ,$:$$ $$$$$ .S* $: $$@$* $% $$$$@s :$: s$@$s
|
||||
.**$$$#####` $@$$$$' $l s-' $:.@* $| '$@s. $% $$ \$ :$:,$$ *$:
|
||||
,***/` #$ `$$ %$$%$$ *$$$#`.*sss$ $% $#$$$' %$ *$sss,
|
||||
,$$'] <> IO.ANSI.reset() <> "\n\n"
|
||||
)
|
||||
@ -1,3 +1,4 @@
|
||||
erlang 26.2.1
|
||||
elixir 1.16.0-otp-26
|
||||
nodejs 21.0.0
|
||||
elixir 1.13.4-otp-24
|
||||
erlang 24.3.3
|
||||
nodejs 16.3.0
|
||||
python 3.9.12
|
||||
|
||||
@ -0,0 +1,6 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
"@babel/preset-react"
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
{
|
||||
"baseDir": "../priv/",
|
||||
"reportOutput": ["github"],
|
||||
"files": [
|
||||
{
|
||||
"path": "static/js/*.js"
|
||||
},
|
||||
{
|
||||
"path": "static/css/app.css"
|
||||
},
|
||||
{
|
||||
"path": "tracker/js/plausible.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,196 +0,0 @@
|
||||
import React, { Fragment } from 'react'
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import { navigateToQuery } from './query'
|
||||
import { Menu, Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import classNames from 'classnames'
|
||||
import * as storage from './util/storage'
|
||||
import Flatpickr from 'react-flatpickr'
|
||||
import { parseNaiveDate, formatISO, formatDateRange } from './util/date.js'
|
||||
|
||||
const COMPARISON_MODES = {
|
||||
'off': 'Disable comparison',
|
||||
'previous_period': 'Previous period',
|
||||
'year_over_year': 'Year over year',
|
||||
'custom': 'Custom period',
|
||||
}
|
||||
|
||||
const DEFAULT_COMPARISON_MODE = 'previous_period'
|
||||
|
||||
export const COMPARISON_DISABLED_PERIODS = ['realtime', 'all']
|
||||
|
||||
export const getStoredMatchDayOfWeek = function(domain) {
|
||||
return storage.getItem(`comparison_match_day_of_week__${domain}`) || 'true'
|
||||
}
|
||||
|
||||
export const getStoredComparisonMode = function(domain) {
|
||||
const mode = storage.getItem(`comparison_mode__${domain}`)
|
||||
if (Object.keys(COMPARISON_MODES).includes(mode)) {
|
||||
return mode
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const storeComparisonMode = function(domain, mode) {
|
||||
if (mode == "custom") return
|
||||
storage.setItem(`comparison_mode__${domain}`, mode)
|
||||
}
|
||||
|
||||
export const isComparisonEnabled = function(mode) {
|
||||
return mode && mode !== "off"
|
||||
}
|
||||
|
||||
export const toggleComparisons = function(history, query, site) {
|
||||
if (COMPARISON_DISABLED_PERIODS.includes(query.period)) return
|
||||
|
||||
if (isComparisonEnabled(query.comparison)) {
|
||||
storeComparisonMode(site.domain, "off")
|
||||
navigateToQuery(history, query, { comparison: "off" })
|
||||
} else {
|
||||
const storedMode = getStoredComparisonMode(site.domain)
|
||||
const newMode = isComparisonEnabled(storedMode) ? storedMode : DEFAULT_COMPARISON_MODE
|
||||
|
||||
storeComparisonMode(site.domain, newMode)
|
||||
navigateToQuery(history, query, { comparison: newMode })
|
||||
}
|
||||
}
|
||||
|
||||
function ComparisonModeOption({ label, value, isCurrentlySelected, updateMode, setUiMode }) {
|
||||
const click = () => {
|
||||
if (value == "custom") {
|
||||
setUiMode("datepicker")
|
||||
} else {
|
||||
updateMode(value)
|
||||
}
|
||||
}
|
||||
|
||||
const render = ({ active }) => {
|
||||
const buttonClass = classNames("px-4 py-2 w-full text-left text-sm dark:text-white", {
|
||||
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": active,
|
||||
"font-medium": !isCurrentlySelected,
|
||||
"font-bold": isCurrentlySelected,
|
||||
})
|
||||
|
||||
return <button className={buttonClass}>{ label }</button>
|
||||
}
|
||||
|
||||
const disabled = isCurrentlySelected && value !== "custom"
|
||||
|
||||
return (
|
||||
<Menu.Item key={value} onClick={click} disabled={disabled}>
|
||||
{ render }
|
||||
</Menu.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function MatchDayOfWeekInput({ history, query, site }) {
|
||||
const click = (matchDayOfWeek) => {
|
||||
storage.setItem(`comparison_match_day_of_week__${site.domain}`, matchDayOfWeek.toString())
|
||||
navigateToQuery(history, query, { match_day_of_week: matchDayOfWeek.toString() })
|
||||
}
|
||||
|
||||
const buttonClass = (hover, selected) =>
|
||||
classNames("px-4 py-2 w-full text-left text-sm dark:text-white cursor-pointer", {
|
||||
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": hover,
|
||||
"font-medium": !selected,
|
||||
"font-bold": selected,
|
||||
})
|
||||
|
||||
return <>
|
||||
<Menu.Item key="match_day_of_week" onClick={() => click(true)}>
|
||||
{({ active }) => (
|
||||
<button className={buttonClass(active, query.match_day_of_week)}>Match day of the week</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
|
||||
<Menu.Item key="match_exact_date" onClick={() => click(false)}>
|
||||
{({ active }) => (
|
||||
<button className={buttonClass(active, !query.match_day_of_week)}>Match exact date</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</>
|
||||
}
|
||||
|
||||
const ComparisonInput = function({ site, query, history }) {
|
||||
if (COMPARISON_DISABLED_PERIODS.includes(query.period)) return null
|
||||
if (!isComparisonEnabled(query.comparison)) return null
|
||||
|
||||
const updateMode = (mode, from = null, to = null) => {
|
||||
storeComparisonMode(site.domain, mode)
|
||||
navigateToQuery(history, query, { comparison: mode, compare_from: from, compare_to: to })
|
||||
}
|
||||
|
||||
const buildLabel = (site, query) => {
|
||||
if (query.comparison == "custom") {
|
||||
return formatDateRange(site, query.compare_from, query.compare_to)
|
||||
} else {
|
||||
return COMPARISON_MODES[query.comparison]
|
||||
}
|
||||
}
|
||||
|
||||
const calendar = React.useRef(null)
|
||||
|
||||
const [uiMode, setUiMode] = React.useState("menu")
|
||||
React.useEffect(() => {
|
||||
if (uiMode == "datepicker") {
|
||||
setTimeout(() => calendar.current.flatpickr.open(), 100)
|
||||
}
|
||||
}, [uiMode])
|
||||
|
||||
const flatpickrOptions = {
|
||||
mode: 'range',
|
||||
showMonths: 1,
|
||||
maxDate: 'today',
|
||||
minDate: site.statsBegin,
|
||||
animate: true,
|
||||
static: true,
|
||||
onClose: ([from, to], _dateStr, _instance) => {
|
||||
setUiMode("menu")
|
||||
|
||||
if (from && to) {
|
||||
[from, to] = [parseNaiveDate(from), parseNaiveDate(to)]
|
||||
updateMode("custom", formatISO(from), formatISO(to))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="hidden md:block pl-2 text-sm font-medium text-gray-800 dark:text-gray-200">vs.</span>
|
||||
<div className="flex">
|
||||
<div className="min-w-32 md:w-48 md:relative">
|
||||
<Menu as="div" className="relative inline-block pl-2 w-full">
|
||||
<Menu.Button className="bg-white text-gray-800 text-xs md:text-sm font-medium dark:bg-gray-800 dark:hover:bg-gray-900 dark:text-gray-200 hover:bg-gray-200 flex md:px-3 px-2 py-2 items-center justify-between leading-tight rounded shadow cursor-pointer w-full truncate">
|
||||
<span className="truncate">{ buildLabel(site, query) }</span>
|
||||
<ChevronDownIcon className="hidden sm:inline-block h-4 w-4 md:h-5 md:w-5 text-gray-500 ml-2" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95">
|
||||
<Menu.Items className="py-1 text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10" static>
|
||||
{ Object.keys(COMPARISON_MODES).map((key) => ComparisonModeOption({ label: COMPARISON_MODES[key], value: key, isCurrentlySelected: key == query.comparison, updateMode, setUiMode })) }
|
||||
{ query.comparison !== "custom" && <span>
|
||||
<hr className="my-1" />
|
||||
<MatchDayOfWeekInput query={query} history={history} site={site} />
|
||||
</span>}
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
|
||||
{ uiMode == "datepicker" &&
|
||||
<div className="h-0 md:absolute">
|
||||
<Flatpickr ref={calendar} options={flatpickrOptions} className="invisible" />
|
||||
</div> }
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(ComparisonInput)
|
||||
@ -1,295 +0,0 @@
|
||||
import React, { Fragment, useState, useCallback, useEffect, useRef } from 'react'
|
||||
import { Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import debounce from 'debounce-promise'
|
||||
import classNames from 'classnames'
|
||||
|
||||
function Option({isHighlighted, onClick, onMouseEnter, text, id}) {
|
||||
const className = classNames('relative cursor-pointer select-none py-2 px-3', {
|
||||
'text-gray-900 dark:text-gray-300': !isHighlighted,
|
||||
'bg-indigo-600 text-white': isHighlighted,
|
||||
})
|
||||
|
||||
return (
|
||||
<li
|
||||
className={className}
|
||||
id={id}
|
||||
onClick={onClick}
|
||||
onMouseEnter={onMouseEnter}
|
||||
>
|
||||
<span className="block truncate">{text}</span>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
function scrollTo(wrapper, id) {
|
||||
if (wrapper) {
|
||||
const el = wrapper.querySelector('#' + id)
|
||||
|
||||
if (el) {
|
||||
el.scrollIntoView({block: 'center'})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function optionId(index) {
|
||||
return `plausible-combobox-option-${index}`
|
||||
}
|
||||
|
||||
export default function PlausibleCombobox(props) {
|
||||
const [options, setOptions] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [isOpen, setOpen] = useState(false)
|
||||
const [input, setInput] = useState('')
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||
const searchRef = useRef(null)
|
||||
const containerRef = useRef(null)
|
||||
const listRef = useRef(null)
|
||||
|
||||
const visibleOptions = [...options]
|
||||
if (props.freeChoice && input.length > 0 && options.every(option => option.value !== input)) {
|
||||
visibleOptions.push({value: input, label: input, freeChoice: true})
|
||||
}
|
||||
|
||||
function highLight(index) {
|
||||
let newIndex = index
|
||||
|
||||
if (index < 0) {
|
||||
newIndex = visibleOptions.length - 1
|
||||
} else if (index >= visibleOptions.length) {
|
||||
newIndex = 0
|
||||
}
|
||||
|
||||
setHighlightedIndex(newIndex)
|
||||
scrollTo(listRef.current, optionId(newIndex))
|
||||
}
|
||||
|
||||
function onKeyDown(e) {
|
||||
if (e.key === 'Enter') {
|
||||
if (!isOpen || loading || visibleOptions.length === 0) return null
|
||||
selectOption(visibleOptions[highlightedIndex])
|
||||
e.preventDefault()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
if (!isOpen || loading) return null
|
||||
setOpen(false)
|
||||
searchRef.current?.focus()
|
||||
e.preventDefault()
|
||||
}
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (isOpen) {
|
||||
highLight(highlightedIndex + 1)
|
||||
} else {
|
||||
setOpen(true)
|
||||
}
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
if (isOpen) {
|
||||
highLight(highlightedIndex - 1)
|
||||
} else {
|
||||
setOpen(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isOptionDisabled(option) {
|
||||
const optionAlreadySelected = props.values.some((val) => val.value === option.value)
|
||||
const optionDisabled = (props.disabledOptions || []).some((val) => val?.value === option.value)
|
||||
return optionAlreadySelected || optionDisabled
|
||||
}
|
||||
|
||||
function fetchOptions(query) {
|
||||
setLoading(true)
|
||||
setOpen(true)
|
||||
|
||||
return props.fetchOptions(query).then((loadedOptions) => {
|
||||
setLoading(false)
|
||||
setHighlightedIndex(0)
|
||||
setOptions(loadedOptions)
|
||||
})
|
||||
}
|
||||
|
||||
const debouncedFetchOptions = useCallback(debounce(fetchOptions, 200), [fetchOptions])
|
||||
|
||||
function onInput(e) {
|
||||
const newInput = e.target.value
|
||||
setInput(newInput)
|
||||
debouncedFetchOptions(newInput)
|
||||
}
|
||||
|
||||
function toggleOpen() {
|
||||
if (!isOpen) {
|
||||
fetchOptions(input)
|
||||
searchRef.current.focus()
|
||||
} else {
|
||||
setInput('')
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
function selectOption(option) {
|
||||
if (props.singleOption) {
|
||||
props.onSelect([option])
|
||||
} else {
|
||||
searchRef.current.focus()
|
||||
props.onSelect([...props.values, option])
|
||||
}
|
||||
|
||||
setOpen(false)
|
||||
setInput('')
|
||||
}
|
||||
|
||||
function removeOption(option, e) {
|
||||
e.stopPropagation()
|
||||
const newValues = props.values.filter((val) => val.value !== option.value)
|
||||
props.onSelect(newValues)
|
||||
searchRef.current.focus()
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const handleClick = useCallback((e) => {
|
||||
if (containerRef.current && containerRef.current.contains(e.target)) { return }
|
||||
|
||||
setInput('')
|
||||
setOpen(false)
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener("mousedown", handleClick, false)
|
||||
return () => { document.removeEventListener("mousedown", handleClick, false) }
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (props.singleOption && props.values.length === 0 && props.autoFocus) {
|
||||
searchRef.current.focus()
|
||||
}
|
||||
}, [props.values.length === 0, props.singleOption, props.autoFocus])
|
||||
|
||||
const searchBoxClass = 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm'
|
||||
|
||||
const containerClass = classNames('relative w-full', {
|
||||
[props.className]: !!props.className,
|
||||
'opacity-30 cursor-default pointer-events-none': props.isDisabled
|
||||
})
|
||||
|
||||
function renderSingleOptionContent() {
|
||||
const itemSelected = props.values.length === 1
|
||||
const placeholder = itemSelected ? '' : props.placeholder
|
||||
|
||||
return (
|
||||
<div className='flex items-center truncate'>
|
||||
{ itemSelected && renderSingleSelectedItem() }
|
||||
<input
|
||||
className={searchBoxClass}
|
||||
ref={searchRef}
|
||||
value={input}
|
||||
style={{backgroundColor: "inherit"}}
|
||||
placeholder={placeholder}
|
||||
type="text"
|
||||
onChange={onInput}>
|
||||
</input>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderSingleSelectedItem() {
|
||||
if (input === '') {
|
||||
return (
|
||||
<span className="dark:text-gray-300 text-sm w-0">
|
||||
{props.values[0].label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function renderMultiOptionContent() {
|
||||
return (
|
||||
<>
|
||||
{ props.values.map((value) => {
|
||||
return (
|
||||
<div key={value.value} className="bg-indigo-100 dark:bg-indigo-600 flex justify-between w-full rounded-sm px-2 py-0.5 m-0.5 text-sm">
|
||||
<span className='break-all'>{value.label}</span>
|
||||
<span onClick={(e) => removeOption(value, e)} className="cursor-pointer font-bold ml-1">×</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
<input className={searchBoxClass} ref={searchRef} value={input} style={{backgroundColor: "inherit"}} placeholder={props.placeholder} type="text" onChange={onInput}></input>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function renderDropDownContent() {
|
||||
const matchesFound = visibleOptions.length > 0 && visibleOptions.some(option => !isOptionDisabled(option))
|
||||
|
||||
if (loading) {
|
||||
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Loading options...</div>
|
||||
}
|
||||
|
||||
if (matchesFound) {
|
||||
return visibleOptions
|
||||
.filter(option => !isOptionDisabled(option))
|
||||
.map((option, i) => {
|
||||
const text = option.freeChoice ? `Filter by '${option.label}'` : option.label
|
||||
|
||||
return (
|
||||
<Option
|
||||
key={option.value}
|
||||
id={optionId(i)}
|
||||
isHighlighted={highlightedIndex === i}
|
||||
onClick={() => selectOption(option)}
|
||||
onMouseEnter={() => setHighlightedIndex(i)}
|
||||
text={text}
|
||||
/>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (props.freeChoice) {
|
||||
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Start typing to apply filter</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">
|
||||
No matches found in the current dashboard. Try selecting a different time range or searching for something different
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const defaultBoxClass = 'pl-2 pr-8 py-1 w-full dark:bg-gray-900 dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-700 focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500'
|
||||
const boxClass = classNames(props.boxClass || defaultBoxClass, {
|
||||
'border-indigo-500 ring-1 ring-indigo-500': isOpen,
|
||||
})
|
||||
|
||||
return (
|
||||
<div onKeyDown={onKeyDown} ref={containerRef} className={containerClass}>
|
||||
<div onClick={toggleOpen} className={boxClass }>
|
||||
{props.singleOption && renderSingleOptionContent()}
|
||||
{!props.singleOption && renderMultiOptionContent()}
|
||||
<div className="cursor-pointer absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
{!loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" />}
|
||||
{loading && <Spinner />}
|
||||
</div>
|
||||
</div>
|
||||
{isOpen && <Transition
|
||||
as={Fragment}
|
||||
leave="transition ease-in duration-100"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
show={isOpen}
|
||||
>
|
||||
<ul ref={listRef} className="z-50 absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm dark:bg-gray-900">
|
||||
{ renderDropDownContent() }
|
||||
</ul>
|
||||
</Transition>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Spinner() {
|
||||
return (
|
||||
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
import React, { Fragment } from "react";
|
||||
|
||||
import { FILTER_OPERATIONS } from "../util/filters";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import { isFreeChoiceFilter, supportsIsNot } from "../util/filters";
|
||||
import classNames from "classnames";
|
||||
|
||||
export default function FilterTypeSelector(props) {
|
||||
const filterName = props.forFilter
|
||||
|
||||
function renderTypeItem(type, shouldDisplay) {
|
||||
return (
|
||||
shouldDisplay && (
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={() => props.onSelect(type)}
|
||||
className={classNames("cursor-pointer block px-4 py-2 text-sm", {
|
||||
"bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100": active,
|
||||
"text-gray-700 dark:text-gray-200": !active
|
||||
}
|
||||
)}
|
||||
>
|
||||
{type}
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const containerClass = classNames("w-full", {
|
||||
'opacity-20 cursor-default pointer-events-none': props.isDisabled
|
||||
})
|
||||
|
||||
return (
|
||||
<div className={containerClass}>
|
||||
<Menu as="div" className="relative inline-block text-left w-full">
|
||||
{({ open }) => (
|
||||
<>
|
||||
<div className="w-full">
|
||||
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
|
||||
{props.selectedType}
|
||||
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
show={open}
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
static
|
||||
className="z-10 origin-top-left absolute left-0 mt-2 w-full rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
>
|
||||
<div className="py-1">
|
||||
{renderTypeItem(FILTER_OPERATIONS.is, true)}
|
||||
{renderTypeItem(FILTER_OPERATIONS.isNot, supportsIsNot(filterName))}
|
||||
{renderTypeItem(FILTER_OPERATIONS.contains, isFreeChoiceFilter(filterName))}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,22 +1,40 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import React from 'react';
|
||||
|
||||
export default function LazyLoader(props) {
|
||||
const [hasBecomeVisibleYet, setHasBecomeVisibleYet] = useState(false)
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && !hasBecomeVisibleYet) {
|
||||
setHasBecomeVisibleYet(true)
|
||||
props.onVisible && props.onVisible()
|
||||
export default class extends React.Component {
|
||||
componentDidMount() {
|
||||
if ('IntersectionObserver' in window) {
|
||||
this.attachObserver()
|
||||
} else {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
}
|
||||
}, [inView])
|
||||
}
|
||||
|
||||
attachObserver() {
|
||||
this.observer = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting) {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
this.observer.unobserve(this.element);
|
||||
}
|
||||
}, {
|
||||
threshold: 0
|
||||
});
|
||||
|
||||
this.observer.observe(this.element);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.observer && this.observer.unobserve(this.element);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={ref}>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
ref={(el) => { this.element = el }}
|
||||
className={this.props.className}
|
||||
style={this.props.style}
|
||||
>
|
||||
{this.props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,56 +0,0 @@
|
||||
import React from "react"
|
||||
import { sectionTitles } from "../stats/behaviours"
|
||||
import * as api from '../api'
|
||||
|
||||
export function FeatureSetupNotice({ site, feature, title, info, callToAction, onHideAction }) {
|
||||
const sectionTitle = sectionTitles[feature]
|
||||
|
||||
const requestHideSection = () => {
|
||||
if (window.confirm(`Are you sure you want to hide ${sectionTitle}? You can make it visible again in your site settings later.`)) {
|
||||
api.put(`/api/${encodeURIComponent(site.domain)}/disable-feature`, { feature: feature })
|
||||
.then(response => {
|
||||
if (response.ok) { onHideAction() }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function renderCallToAction() {
|
||||
return (
|
||||
<a href={callToAction.link} className="ml-2 sm:ml-4 button px-2 sm:px-4">
|
||||
<p className="flex flex-col justify-center text-xs sm:text-sm">{callToAction.action}</p>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="ml-2 w-5 h-5">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75" />
|
||||
</svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
function renderHideButton() {
|
||||
return (
|
||||
<button
|
||||
onClick={requestHideSection}
|
||||
className="inline-block px-2 sm:px-4 py-2 border border-gray-300 dark:border-gray-500 leading-5 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition ease-in-out duration-150">
|
||||
Hide this report
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="sm:mx-32 mt-6 mb-3" >
|
||||
<div className="py-3">
|
||||
<div className="text-center mt-2 text-gray-800 dark:text-gray-200">
|
||||
{title}
|
||||
</div>
|
||||
|
||||
<div className="text-justify mt-4 font-small text-sm text-gray-500 dark:text-gray-200">
|
||||
{info}
|
||||
</div>
|
||||
|
||||
<div className="text-xs sm:text-sm flex my-6 justify-center">
|
||||
{renderHideButton()}
|
||||
{renderCallToAction()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
/* eslint react/jsx-props-no-spreading: 0 */
|
||||
import React, {useState, useCallback} from 'react'
|
||||
import {useCombobox} from 'downshift'
|
||||
import classNames from 'classnames'
|
||||
import debounce from 'debounce-promise'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
function selectInputText(e) {
|
||||
e.target.select()
|
||||
}
|
||||
|
||||
function Spinner() {
|
||||
return (
|
||||
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SearchSelect(props) {
|
||||
const [items, setItems] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
function fetchOptions({inputValue, isOpen}) {
|
||||
setLoading(isOpen)
|
||||
|
||||
return props.fetchOptions(inputValue || '').then((loadedItems) => {
|
||||
setLoading(false)
|
||||
setItems(loadedItems)
|
||||
})
|
||||
}
|
||||
|
||||
const debouncedFetchOptions = useCallback(debounce(fetchOptions, 200), [])
|
||||
|
||||
const {
|
||||
isOpen,
|
||||
inputValue,
|
||||
getToggleButtonProps,
|
||||
getMenuProps,
|
||||
getInputProps,
|
||||
getComboboxProps,
|
||||
highlightedIndex,
|
||||
getItemProps,
|
||||
closeMenu,
|
||||
} = useCombobox({
|
||||
items,
|
||||
itemToString: (item) => item.hasOwnProperty('name') ? item.name : item,
|
||||
onInputValueChange: (changes) => {
|
||||
debouncedFetchOptions(changes)
|
||||
props.onInput(changes.inputValue)
|
||||
if (changes.inputValue === '') {
|
||||
props.onSelect({name: '', code: ''})
|
||||
}
|
||||
},
|
||||
onSelectedItemChange: (changes) => {
|
||||
props.onSelect(changes.selectedItem)
|
||||
},
|
||||
initialSelectedItem: props.initialSelectedItem,
|
||||
onIsOpenChange: (state) => {
|
||||
if (state.isOpen) {
|
||||
fetchOptions(state)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function keydown(e) {
|
||||
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) return
|
||||
|
||||
if (e.key === 'Enter' && isOpen && highlightedIndex === -1) {
|
||||
closeMenu()
|
||||
e.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ml-2 relative w-full">
|
||||
<div className="relative rounded-md shadow-sm" {...getToggleButtonProps()} {...getComboboxProps()}>
|
||||
<input {...getInputProps({onKeyDown: keydown})} onFocus={selectInputText} placeholder={props.placeholder} type="text" className={classNames('w-full pr-10 border-gray-300 dark:border-gray-700 hover:border-gray-400 dark:hover:border-gray-200 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 text-sm rounded-md dark:bg-gray-900 dark:text-gray-300 block', {'cursor-pointer': inputValue === '' && !isOpen})} />
|
||||
<div className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
|
||||
{ !loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" /> }
|
||||
{ loading && <Spinner /> }
|
||||
</div>
|
||||
</div>
|
||||
<div {...getMenuProps()}>
|
||||
{ isOpen && (
|
||||
<ul className="absolute z-10 mt-1 w-full bg-white dark:bg-gray-900 shadow-lg max-h-60 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm">
|
||||
{ !loading && items.length === 0 &&
|
||||
<li className="text-gray-500 select-none py-2 px-3">No matches found in the current dashboard. Try selecting a different time range or searching for something different</li> }
|
||||
{ loading && items.length === 0 &&
|
||||
<li className="text-gray-500 select-none py-2 px-3">Loading options...</li> }
|
||||
|
||||
{
|
||||
items.map((item, index) => (
|
||||
<li
|
||||
className={classNames("cursor-pointer select-none relative py-2 pl-3 pr-9", {'text-white bg-indigo-600': highlightedIndex === index, 'text-gray-900 dark:text-gray-100': highlightedIndex !== index})}
|
||||
key={`${item.name ? item.name : item}`}
|
||||
{...getItemProps({ item, index })}
|
||||
>
|
||||
{item.name ? item.name : item}
|
||||
</li>
|
||||
))
|
||||
}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
Plausible copyright notice
|
||||
|
||||
This software is Copyright 2024 Plausible Insights OÜ
|
||||
|
||||
This repository is provided for informational purposes only, and no rights to use, distribute or otherwise exploit this software are granted to you. Our other repositories include software that is offered under the Affero GPL, but this repository is not. If you wish to discuss a license, or our hosted service that uses the software, please contact us at hello@plausible.io
|
||||
@ -1,85 +0,0 @@
|
||||
export default function FunnelTooltip(palette, funnel) {
|
||||
return (context) => {
|
||||
const tooltipModel = context.tooltip
|
||||
const dataIndex = tooltipModel.dataPoints[0].dataIndex
|
||||
const offset = document.getElementById("funnel").getBoundingClientRect()
|
||||
let tooltipEl = document.getElementById('chartjs-tooltip')
|
||||
|
||||
if (!tooltipEl) {
|
||||
tooltipEl = document.createElement('div')
|
||||
tooltipEl.id = 'chartjs-tooltip'
|
||||
tooltipEl.style.display = 'none'
|
||||
tooltipEl.style.opacity = 0
|
||||
document.body.appendChild(tooltipEl)
|
||||
}
|
||||
|
||||
if (tooltipEl && offset && window.innerWidth < 768) {
|
||||
tooltipEl.style.top = offset.y + offset.height + window.scrollY + 15 + 'px'
|
||||
tooltipEl.style.left = offset.x + 'px'
|
||||
tooltipEl.style.right = null
|
||||
tooltipEl.style.opacity = 1
|
||||
}
|
||||
|
||||
if (tooltipModel.opacity === 0) {
|
||||
tooltipEl.style.display = 'none'
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if (tooltipModel.body) {
|
||||
const currentStep = funnel.steps[dataIndex]
|
||||
const previousStep = (dataIndex > 0) ? funnel.steps[dataIndex - 1] : null
|
||||
|
||||
tooltipEl.innerHTML = `
|
||||
<aside class="text-gray-100 flex flex-col">
|
||||
<div class="flex justify-between items-center border-b-2 border-gray-700 pb-2">
|
||||
<span class="font-semibold mr-4 text-lg">${previousStep ? `<span class="mr-2">${previousStep.label}</span>` : ""}
|
||||
<span class="text-gray-500 mr-2">→</span>
|
||||
${tooltipModel.title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<table class="min-w-full mt-2">
|
||||
<tr>
|
||||
<th>
|
||||
<span class="flex items-center mr-4">
|
||||
<div class="w-3 h-3 mr-1 rounded-full ${palette.visitorsLegendClass}"></div>
|
||||
<span>
|
||||
${dataIndex == 0 ? "Entered the funnel" : "Visitors"}
|
||||
</span>
|
||||
</span>
|
||||
</th>
|
||||
<td class="text-right font-bold px-4">
|
||||
<span>
|
||||
${dataIndex == 0 ? funnel.entering_visitors.toLocaleString() : currentStep.visitors.toLocaleString()}
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-right text-sm">
|
||||
<span>
|
||||
${dataIndex == 0 ? funnel.entering_visitors_percentage : currentStep.conversion_rate_step}%
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>
|
||||
<span class="flex items-center">
|
||||
<div class="w-3 h-3 mr-1 rounded-full ${palette.dropoffLegendClass}"></div>
|
||||
<span>
|
||||
${dataIndex == 0 ? "Never entered the funnel" : "Dropoff"}
|
||||
</span>
|
||||
</span>
|
||||
</th>
|
||||
<td class="text-right font-bold px-4">
|
||||
<span>${dataIndex == 0 ? funnel.never_entering_visitors.toLocaleString() : currentStep.dropoff.toLocaleString()}</span>
|
||||
</td >
|
||||
<td class="text-right text-sm">
|
||||
<span>${dataIndex == 0 ? funnel.never_entering_visitors_percentage : currentStep.dropoff_percentage}%</span>
|
||||
</td>
|
||||
</tr >
|
||||
</table >
|
||||
</aside >
|
||||
`
|
||||
}
|
||||
tooltipEl.style.display = null
|
||||
}
|
||||
}
|
||||
@ -1,358 +0,0 @@
|
||||
import React, { useEffect, useState, useRef } from 'react'
|
||||
import FlipMove from 'react-flip-move';
|
||||
import Chart from 'chart.js/auto'
|
||||
import FunnelTooltip from './funnel-tooltip.js'
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels'
|
||||
import numberFormatter from '../util/number-formatter'
|
||||
import Bar from '../stats/bar'
|
||||
|
||||
import RocketIcon from '../stats/modals/rocket-icon'
|
||||
|
||||
import * as api from '../api'
|
||||
import LazyLoader from '../components/lazy-loader'
|
||||
|
||||
|
||||
export default function Funnel(props) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [visible, setVisible] = useState(false)
|
||||
const [error, setError] = useState(undefined)
|
||||
const [funnel, setFunnel] = useState(null)
|
||||
const [isSmallScreen, setSmallScreen] = useState(false)
|
||||
const chartRef = useRef(null)
|
||||
const canvasRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
setLoading(true)
|
||||
fetchFunnel()
|
||||
.then((res) => {
|
||||
setFunnel(res)
|
||||
setError(undefined)
|
||||
})
|
||||
.catch((error) => {
|
||||
setError(error)
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
if (chartRef.current) {
|
||||
chartRef.current.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [props.query, props.funnelName, visible, isSmallScreen])
|
||||
|
||||
useEffect(() => {
|
||||
if (canvasRef.current && funnel && visible && !isSmallScreen) {
|
||||
initialiseChart()
|
||||
}
|
||||
}, [funnel, visible])
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQuery = window.matchMedia('(max-width: 768px)')
|
||||
setSmallScreen(mediaQuery.matches)
|
||||
const handleScreenChange = (e) => {
|
||||
setSmallScreen(e.matches);
|
||||
}
|
||||
mediaQuery.addEventListener("change", handleScreenChange);
|
||||
return () => {
|
||||
mediaQuery.removeEventListener("change", handleScreenChange)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const isDarkMode = () => {
|
||||
return document.querySelector('html').classList.contains('dark') || false
|
||||
}
|
||||
|
||||
const getPalette = () => {
|
||||
if (isDarkMode()) {
|
||||
return {
|
||||
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
|
||||
dataLabelTextColor: 'rgb(243, 244, 246)',
|
||||
visitorsBackground: 'rgb(99, 102, 241)',
|
||||
dropoffBackground: '#2F3949',
|
||||
dropoffStripes: 'rgb(25, 30, 56)',
|
||||
stepNameLegendColor: 'rgb(228, 228, 231)',
|
||||
visitorsLegendClass: 'bg-indigo-500',
|
||||
dropoffLegendClass: 'bg-gray-600',
|
||||
smallBarClass: 'bg-indigo-500'
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
|
||||
dataLabelTextColor: 'rgb(243, 244, 246)',
|
||||
visitorsBackground: 'rgb(99, 102, 241)',
|
||||
dropoffBackground: 'rgb(224, 231, 255)',
|
||||
dropoffStripes: 'rgb(255, 255, 255)',
|
||||
stepNameLegendColor: 'rgb(12, 24, 39)',
|
||||
visitorsLegendClass: 'bg-indigo-500',
|
||||
dropoffLegendClass: 'bg-indigo-100',
|
||||
smallBarClass: 'bg-indigo-300'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const formatDataLabel = (visitors, ctx) => {
|
||||
if (ctx.dataset.label === 'Visitors') {
|
||||
const conversionRate = funnel.steps[ctx.dataIndex].conversion_rate
|
||||
return `${conversionRate}% \n(${numberFormatter(visitors)} Visitors)`
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const calcOffset = (ctx) => {
|
||||
const conversionRate = parseFloat(funnel.steps[ctx.dataIndex].conversion_rate)
|
||||
if (conversionRate > 90) {
|
||||
return -64
|
||||
} else if (conversionRate > 20) {
|
||||
return -28
|
||||
} else {
|
||||
return 8
|
||||
}
|
||||
}
|
||||
|
||||
const getFunnel = () => {
|
||||
return props.site.funnels.find((funnel) => funnel.name === props.funnelName)
|
||||
}
|
||||
|
||||
const fetchFunnel = async () => {
|
||||
const funnelMeta = getFunnel()
|
||||
if (typeof funnelMeta === 'undefined') {
|
||||
throw new Error('Could not fetch the funnel. Perhaps it was deleted?')
|
||||
} else {
|
||||
return api.get(`/api/stats/${encodeURIComponent(props.site.domain)}/funnels/${funnelMeta.id}`, props.query)
|
||||
}
|
||||
}
|
||||
|
||||
const initialiseChart = () => {
|
||||
if (chartRef.current) {
|
||||
chartRef.current.destroy()
|
||||
}
|
||||
|
||||
const palette = getPalette()
|
||||
|
||||
const createDiagonalPattern = (color1, color2) => {
|
||||
// create a 10x10 px canvas for the pattern's base shape
|
||||
let shape = document.createElement('canvas')
|
||||
shape.width = 10
|
||||
shape.height = 10
|
||||
let c = shape.getContext('2d')
|
||||
|
||||
c.fillStyle = color1
|
||||
c.strokeStyle = color2
|
||||
c.fillRect(0, 0, shape.width, shape.height);
|
||||
|
||||
c.beginPath()
|
||||
c.moveTo(2, 0)
|
||||
c.lineTo(10, 8)
|
||||
c.stroke()
|
||||
|
||||
c.beginPath()
|
||||
c.moveTo(0, 8)
|
||||
c.lineTo(2, 10)
|
||||
c.stroke()
|
||||
|
||||
return c.createPattern(shape, 'repeat')
|
||||
}
|
||||
|
||||
const labels = funnel.steps.map((step) => step.label)
|
||||
const stepData = funnel.steps.map((step) => step.visitors)
|
||||
|
||||
const dropOffData = funnel.steps.map((step) => step.dropoff)
|
||||
const ctx = canvasRef.current.getContext("2d")
|
||||
|
||||
const calcBarThickness = (ctx) => {
|
||||
if (ctx.dataset.data.length <= 3) {
|
||||
return 160
|
||||
} else {
|
||||
return Math.floor(650 / ctx.dataset.data.length)
|
||||
}
|
||||
}
|
||||
|
||||
// passing those verbatim to make sure canvas rendering picks them up
|
||||
var fontFamily = 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
|
||||
|
||||
var gradient = ctx.createLinearGradient(900, 0, 900, 900);
|
||||
gradient.addColorStop(1, palette.dropoffBackground);
|
||||
gradient.addColorStop(0, palette.visitorsBackground);
|
||||
|
||||
const data = {
|
||||
labels: labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Visitors',
|
||||
data: stepData,
|
||||
backgroundColor: gradient,
|
||||
hoverBackgroundColor: gradient,
|
||||
borderRadius: 4,
|
||||
stack: 'Stack 0',
|
||||
},
|
||||
{
|
||||
label: 'Dropoff',
|
||||
data: dropOffData,
|
||||
backgroundColor: createDiagonalPattern(palette.dropoffBackground, palette.dropoffStripes),
|
||||
hoverBackgroundColor: palette.dropoffBackground,
|
||||
borderRadius: 4,
|
||||
stack: 'Stack 0',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const config = {
|
||||
plugins: [ChartDataLabels],
|
||||
type: 'bar',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
barThickness: calcBarThickness,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
tooltip: {
|
||||
enabled: false,
|
||||
mode: 'index',
|
||||
intersect: true,
|
||||
position: 'average',
|
||||
external: FunnelTooltip(palette, funnel)
|
||||
},
|
||||
datalabels: {
|
||||
formatter: formatDataLabel,
|
||||
anchor: 'end',
|
||||
align: 'end',
|
||||
offset: calcOffset,
|
||||
backgroundColor: palette.dataLabelBackground,
|
||||
color: palette.dataLabelTextColor,
|
||||
borderRadius: 4,
|
||||
clip: true,
|
||||
font: { size: 12, weight: 'normal', lineHeight: 1.6, family: fontFamily },
|
||||
textAlign: 'center',
|
||||
padding: { top: 8, bottom: 8, right: 8, left: 8 },
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
y: { display: false },
|
||||
x: {
|
||||
position: 'bottom',
|
||||
display: true,
|
||||
border: { display: false },
|
||||
grid: { drawBorder: false, display: false },
|
||||
ticks: {
|
||||
padding: 8,
|
||||
font: { weight: 'bold', family: fontFamily, size: 14 },
|
||||
color: palette.stepNameLegendColor
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
chartRef.current = new Chart(ctx, config)
|
||||
}
|
||||
|
||||
const header = () => {
|
||||
return (
|
||||
<div className="flex justify-between w-full">
|
||||
<h4 className="mt-2 text-sm dark:text-gray-100">{props.funnelName}</h4>
|
||||
{props.tabs}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderError = () => {
|
||||
if (error.name === 'AbortError') return
|
||||
if (error.payload && error.payload.level === 'normal') {
|
||||
return (
|
||||
<>
|
||||
{header()}
|
||||
<div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">{error.message}</div>
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<>
|
||||
{header()}
|
||||
<div className="text-center text-gray-900 dark:text-gray-100 mt-16">
|
||||
<RocketIcon />
|
||||
<div className="text-lg font-bold">Oops! Something went wrong</div>
|
||||
<div className="text-lg">{error.message ? error.message : 'Failed to render funnel'}</div>
|
||||
<div className="text-xs mt-8">Please try refreshing your browser or selecting the funnel again.</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const renderInner = () => {
|
||||
if (loading) {
|
||||
return <div className="mx-auto loading pt-44"><div></div></div>
|
||||
} else if (error) {
|
||||
return renderError()
|
||||
} else if (funnel) {
|
||||
const conversionRate = funnel.steps[funnel.steps.length - 1].conversion_rate
|
||||
|
||||
return (
|
||||
<div className="mb-8">
|
||||
{header()}
|
||||
<p className="mt-1 text-gray-500 text-sm">{funnel.steps.length}-step funnel • {conversionRate}% conversion rate</p>
|
||||
{isSmallScreen && <div className="mt-4">{renderBars(funnel)}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const renderBar = (step) => {
|
||||
const palette = getPalette()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between my-1 text-sm">
|
||||
<Bar
|
||||
count={step.visitors}
|
||||
all={funnel.steps}
|
||||
bg={palette.smallBarClass}
|
||||
maxWidthDeduction={"5rem"}
|
||||
plot={'visitors'}
|
||||
>
|
||||
|
||||
<span className="flex px-2 py-1.5 group dark:text-gray-100 relative z-9 break-all">
|
||||
{step.label}
|
||||
</span>
|
||||
</Bar>
|
||||
|
||||
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={step.visitors.toLocaleString()}>
|
||||
{numberFormatter(step.visitors)}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const renderBars = (funnel) => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
|
||||
<span> </span>
|
||||
<span className="text-right">
|
||||
<span className="inline-block w-20">Visitors</span>
|
||||
</span>
|
||||
</div>
|
||||
<FlipMove>
|
||||
{funnel.steps.map(renderBar)}
|
||||
</FlipMove>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ minHeight: '400px' }}>
|
||||
<LazyLoader onVisible={() => setVisible(true)}>
|
||||
{renderInner()}
|
||||
</LazyLoader>
|
||||
{!isSmallScreen && <canvas className="" id="funnel" ref={canvasRef}></canvas>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,9 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
export default function Money({ formatted }) {
|
||||
if (formatted) {
|
||||
return <span tooltip={formatted.long}>{formatted.short}</span>
|
||||
} else {
|
||||
return "-"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
import * as Sentry from "@sentry/react";
|
||||
import { Integrations } from "@sentry/tracing";
|
||||
|
||||
const container = document.getElementById('stats-react-container')
|
||||
|
||||
Sentry.init({
|
||||
dsn: container.dataset.sentryDsn,
|
||||
environment: container.dataset.environment,
|
||||
integrations: [new Integrations.BrowserTracing()],
|
||||
release: container.dataset.sentryRelease || "unknown",
|
||||
initialScope: {
|
||||
tags: {
|
||||
'app_version': container.dataset.sentryRelease,
|
||||
'origin': 'dashboard'
|
||||
},
|
||||
},
|
||||
tracesSampleRate: 0.5,
|
||||
});
|
||||
@ -1,41 +0,0 @@
|
||||
import React from 'react';
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { escapeFilterValue } from '../../util/filters'
|
||||
|
||||
import { CR_METRIC } from '../reports/metrics';
|
||||
import ListReport from '../reports/list';
|
||||
|
||||
export default function Conversions(props) {
|
||||
const { site, query } = props
|
||||
|
||||
function fetchConversions() {
|
||||
return api.get(url.apiPath(site, '/conversions'), query, { limit: 9 })
|
||||
}
|
||||
|
||||
function getFilterFor(listItem) {
|
||||
return { goal: escapeFilterValue(listItem.name) }
|
||||
}
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchConversions}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel="Goal"
|
||||
onClick={props.onGoalFilterClick}
|
||||
metrics={[
|
||||
{ name: 'visitors', label: "Uniques", plot: true },
|
||||
{ name: 'events', label: "Total", hiddenOnMobile: true },
|
||||
CR_METRIC,
|
||||
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
|
||||
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
|
||||
]}
|
||||
detailsLink={url.sitePath(site, '/conversions')}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
import React from "react"
|
||||
import Conversions from './conversions'
|
||||
import ListReport from "../reports/list"
|
||||
import { CR_METRIC } from "../reports/metrics"
|
||||
import * as url from "../../util/url"
|
||||
import * as api from "../../api"
|
||||
|
||||
export const SPECIAL_GOALS = {
|
||||
'404': {title: '404 Pages', prop: 'path'},
|
||||
'Outbound Link: Click': {title: 'Outbound Links', prop: 'url'},
|
||||
'Cloaked Link: Click': {title: 'Cloaked Links', prop: 'url'},
|
||||
'File Download': {title: 'File Downloads', prop: 'url'}
|
||||
}
|
||||
|
||||
export function specialTitleWhenGoalFilter(query, defaultTitle) {
|
||||
return SPECIAL_GOALS[query.filters.goal]?.title || defaultTitle
|
||||
}
|
||||
|
||||
function SpecialPropBreakdown(props) {
|
||||
const { site, query } = props
|
||||
const prop = SPECIAL_GOALS[query.filters.goal].prop
|
||||
|
||||
function fetchData() {
|
||||
return api.get(url.apiPath(site, `/custom-prop-values/${prop}`), query)
|
||||
}
|
||||
|
||||
function externalLinkDest() {
|
||||
if (prop === 'path') {
|
||||
return (listItem) => url.externalLinkForPage(site.domain, listItem.name)
|
||||
} else {
|
||||
return (listItem) => listItem.name
|
||||
}
|
||||
}
|
||||
|
||||
const getFilterFor = (listItem) => { return {'props': JSON.stringify({[prop]: listItem['name']})} }
|
||||
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchData}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel={prop}
|
||||
metrics={[
|
||||
{name: 'visitors', label: 'Visitors', plot: true},
|
||||
{name: 'events', label: 'Events', hiddenOnMobile: true},
|
||||
CR_METRIC
|
||||
]}
|
||||
detailsLink={url.sitePath(site, `/custom-prop-values/${prop}`)}
|
||||
externalLinkDest={externalLinkDest()}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default function GoalConversions(props) {
|
||||
const {site, query} = props
|
||||
|
||||
if (SPECIAL_GOALS[query.filters.goal]) {
|
||||
return <SpecialPropBreakdown site={site} query={props.query} />
|
||||
} else {
|
||||
return <Conversions site={site} query={props.query} onGoalFilterClick={props.onGoalFilterClick}/>
|
||||
}
|
||||
}
|
||||
@ -1,344 +0,0 @@
|
||||
import React, { Fragment, useState, useEffect, useCallback } from 'react'
|
||||
import { Menu, Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import classNames from 'classnames'
|
||||
import * as storage from '../../util/storage'
|
||||
|
||||
import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions'
|
||||
import Properties from './props'
|
||||
import { FeatureSetupNotice } from '../../components/notice'
|
||||
import { SPECIAL_GOALS } from './goal-conversions'
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/funnel')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Funnel = maybeRequire().default
|
||||
|
||||
const ACTIVE_CLASS = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left'
|
||||
const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left'
|
||||
|
||||
export const CONVERSIONS = 'conversions'
|
||||
export const PROPS = 'props'
|
||||
export const FUNNELS = 'funnels'
|
||||
|
||||
export const sectionTitles = {
|
||||
[CONVERSIONS]: 'Goal Conversions',
|
||||
[PROPS]: 'Custom Properties',
|
||||
[FUNNELS]: 'Funnels'
|
||||
}
|
||||
|
||||
export default function Behaviours(props) {
|
||||
const { site, query, currentUserRole } = props
|
||||
const adminAccess = ['owner', 'admin', 'super_admin'].includes(currentUserRole)
|
||||
const tabKey = `behavioursTab__${site.domain}`
|
||||
const funnelKey = `behavioursTabFunnel__${site.domain}`
|
||||
const [enabledModes, setEnabledModes] = useState(getEnabledModes())
|
||||
const [mode, setMode] = useState(defaultMode())
|
||||
|
||||
const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name))
|
||||
const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel())
|
||||
|
||||
const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false)
|
||||
|
||||
const onGoalFilterClick = useCallback((e) => {
|
||||
const goalName = e.target.innerHTML
|
||||
const isSpecialGoal = Object.keys(SPECIAL_GOALS).includes(goalName)
|
||||
const isPageviewGoal = goalName.startsWith('Visit ')
|
||||
|
||||
if (!isSpecialGoal && !isPageviewGoal && enabledModes.includes(PROPS) && site.hasProps) {
|
||||
setShowingPropsForGoalFilter(true)
|
||||
setMode(PROPS)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const justRemovedGoalFilter = !query.filters.goal
|
||||
if (mode === PROPS && justRemovedGoalFilter && showingPropsForGoalFilter) {
|
||||
setShowingPropsForGoalFilter(false)
|
||||
setMode(CONVERSIONS)
|
||||
}
|
||||
}, [!!query.filters.goal])
|
||||
|
||||
useEffect(() => {
|
||||
setMode(defaultMode())
|
||||
}, [enabledModes])
|
||||
|
||||
function disableMode(mode) {
|
||||
setEnabledModes(enabledModes.filter((m) => { return m !== mode }))
|
||||
}
|
||||
|
||||
function setFunnel(selectedFunnel) {
|
||||
return () => {
|
||||
storage.setItem(tabKey, FUNNELS)
|
||||
storage.setItem(funnelKey, selectedFunnel)
|
||||
setMode(FUNNELS)
|
||||
setSelectedFunnel(selectedFunnel)
|
||||
}
|
||||
}
|
||||
|
||||
function defaultSelectedFunnel() {
|
||||
const stored = storage.getItem(funnelKey)
|
||||
const storedExists = stored && site.funnels.some((f) => f.name === stored)
|
||||
|
||||
if (storedExists) {
|
||||
return stored
|
||||
} else if (site.funnels.length > 0) {
|
||||
const firstAvailable = site.funnels[0].name
|
||||
|
||||
storage.setItem(funnelKey, firstAvailable)
|
||||
return firstAvailable
|
||||
}
|
||||
}
|
||||
|
||||
function hasFunnels() {
|
||||
return site.funnels.length > 0 && site.funnelsAvailable
|
||||
}
|
||||
|
||||
function tabFunnelPicker() {
|
||||
return <Menu as="div" className="relative inline-block text-left">
|
||||
<div>
|
||||
<Menu.Button className="inline-flex justify-between focus:outline-none">
|
||||
<span className={(mode == FUNNELS) ? ACTIVE_CLASS : DEFAULT_CLASS}>Funnels</span>
|
||||
<ChevronDownIcon className="-mr-1 ml-1 h-4 w-4" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items className="text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
|
||||
<div className="py-1">
|
||||
{funnelNames.map((funnelName) => {
|
||||
return (
|
||||
<Menu.Item key={funnelName}>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={setFunnel(funnelName)}
|
||||
className={classNames(
|
||||
active ? 'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer' : 'text-gray-700 dark:text-gray-200',
|
||||
'block px-4 py-2 text-sm',
|
||||
(mode === FUNNELS && selectedFunnel === funnelName) ? 'font-bold text-gray-500' : ''
|
||||
)}
|
||||
>
|
||||
{funnelName}
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
}
|
||||
|
||||
function tabSwitcher(toMode, displayName) {
|
||||
const className = classNames({ [ACTIVE_CLASS]: mode == toMode, [DEFAULT_CLASS]: mode !== toMode })
|
||||
const setTab = () => {
|
||||
storage.setItem(tabKey, toMode)
|
||||
setMode(toMode)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className} onClick={setTab}>
|
||||
{displayName}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function tabs() {
|
||||
return (
|
||||
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
|
||||
{isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')}
|
||||
{isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')}
|
||||
{isEnabled(FUNNELS) && Funnel && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderConversions() {
|
||||
if (site.hasGoals) {
|
||||
return <GoalConversions site={site} query={query} onGoalFilterClick={onGoalFilterClick} />
|
||||
}
|
||||
else if (adminAccess) {
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={CONVERSIONS}
|
||||
title={'Measure how often visitors complete specific actions'}
|
||||
info={'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'}
|
||||
callToAction={{
|
||||
action: "Set up goals",
|
||||
link: `/${encodeURIComponent(site.domain)}/settings/goals`
|
||||
}}
|
||||
onHideAction={onHideAction(CONVERSIONS)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
else { return noDataYet() }
|
||||
}
|
||||
|
||||
function renderFunnels() {
|
||||
if (Funnel === null) {
|
||||
return featureUnavailable()
|
||||
}
|
||||
else if (Funnel && selectedFunnel && site.funnelsAvailable) {
|
||||
return <Funnel site={site} query={query} funnelName={selectedFunnel} />
|
||||
}
|
||||
else if (Funnel && adminAccess) {
|
||||
let callToAction
|
||||
|
||||
if (site.funnelsAvailable) {
|
||||
callToAction = {action: 'Set up funnels', link: `/${encodeURIComponent(site.domain)}/settings/funnels`}
|
||||
} else {
|
||||
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
|
||||
}
|
||||
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={FUNNELS}
|
||||
title={'Follow the visitor journey from entry to conversion'}
|
||||
info={'Funnels allow you to analyze the user flow through your website, uncover possible issues, optimize your site and increase the conversion rate.'}
|
||||
callToAction={callToAction}
|
||||
onHideAction={onHideAction(FUNNELS)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
else { return noDataYet() }
|
||||
}
|
||||
|
||||
function renderProps() {
|
||||
if (site.hasProps && site.propsAvailable) {
|
||||
return <Properties site={site} query={query} />
|
||||
} else if (adminAccess) {
|
||||
let callToAction
|
||||
|
||||
if (site.propsAvailable) {
|
||||
callToAction = {action: 'Set up props', link: `/${encodeURIComponent(site.domain)}/settings/properties`}
|
||||
} else {
|
||||
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
|
||||
}
|
||||
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={PROPS}
|
||||
title={'Send custom data to create your own metrics'}
|
||||
info={'You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don\'t track automatically.'}
|
||||
callToAction={callToAction}
|
||||
onHideAction={onHideAction(PROPS)}
|
||||
/>
|
||||
)
|
||||
} else { return noDataYet() }
|
||||
}
|
||||
|
||||
function noDataYet() {
|
||||
return (
|
||||
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
|
||||
No data yet
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function featureUnavailable() {
|
||||
return (
|
||||
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
|
||||
This feature is unavailable
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function onHideAction(mode) {
|
||||
return () => { disableMode(mode) }
|
||||
}
|
||||
|
||||
function renderContent() {
|
||||
switch (mode) {
|
||||
case CONVERSIONS:
|
||||
return renderConversions()
|
||||
case PROPS:
|
||||
return renderProps()
|
||||
case FUNNELS:
|
||||
return renderFunnels()
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMode() {
|
||||
if (enabledModes.length === 0) { return null }
|
||||
|
||||
const storedMode = storage.getItem(tabKey)
|
||||
if (storedMode && enabledModes.includes(storedMode)) { return storedMode }
|
||||
|
||||
if (enabledModes.includes(CONVERSIONS)) { return CONVERSIONS }
|
||||
if (enabledModes.includes(PROPS)) { return PROPS }
|
||||
return FUNNELS
|
||||
}
|
||||
|
||||
function getEnabledModes() {
|
||||
let enabledModes = []
|
||||
|
||||
for (const feature of Object.keys(sectionTitles)) {
|
||||
const isOptedOut = site[feature + 'OptedOut']
|
||||
const isAvailable = site[feature + 'Available'] !== false
|
||||
|
||||
// If the feature is not supported by the site owner's subscription,
|
||||
// it only makes sense to display the feature tab to the owner itself
|
||||
// as only they can upgrade to make the feature available.
|
||||
const callToActionIsMissing = !isAvailable && currentUserRole !== 'owner'
|
||||
|
||||
if (!isOptedOut && !callToActionIsMissing) {
|
||||
enabledModes.push(feature)
|
||||
}
|
||||
}
|
||||
|
||||
return enabledModes
|
||||
}
|
||||
|
||||
function isEnabled(mode) {
|
||||
return enabledModes.includes(mode)
|
||||
}
|
||||
|
||||
function isRealtime() {
|
||||
return query.period === 'realtime'
|
||||
}
|
||||
|
||||
function sectionTitle() {
|
||||
if (mode === CONVERSIONS) {
|
||||
return specialTitleWhenGoalFilter(query, sectionTitles[mode])
|
||||
} else {
|
||||
return sectionTitles[mode]
|
||||
}
|
||||
}
|
||||
|
||||
if (mode) {
|
||||
return (
|
||||
<div className="items-start justify-between block w-full mt-6 md:flex">
|
||||
<div className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825">
|
||||
<div className="flex justify-between w-full">
|
||||
<h3 className="font-bold dark:text-gray-100">
|
||||
{sectionTitle() + (isRealtime() ? ' (last 30min)' : '')}
|
||||
</h3>
|
||||
{tabs()}
|
||||
</div>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,105 +0,0 @@
|
||||
import React, { useCallback, useState } from "react"
|
||||
import ListReport from "../reports/list";
|
||||
import Combobox from '../../components/combobox'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { CR_METRIC, PERCENTAGE_METRIC } from "../reports/metrics";
|
||||
import * as storage from "../../util/storage";
|
||||
import { parsePrefix, escapeFilterValue } from "../../util/filters"
|
||||
|
||||
|
||||
export default function Properties(props) {
|
||||
const { site, query } = props
|
||||
const propKeyStorageName = `prop_key__${site.domain}`
|
||||
const propKeyStorageNameForGoal = `${query.filters.goal}__prop_key__${site.domain}`
|
||||
|
||||
const [propKey, setPropKey] = useState(choosePropKey())
|
||||
|
||||
function singleGoalFilterApplied() {
|
||||
const goalFilter = query.filters.goal
|
||||
if (goalFilter) {
|
||||
const { type, values } = parsePrefix(goalFilter)
|
||||
return type === 'is' && values.length === 1
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function choosePropKey() {
|
||||
if (query.filters.props) {
|
||||
return Object.keys(query.filters.props)[0]
|
||||
} else {
|
||||
return getPropKeyFromStorage()
|
||||
}
|
||||
}
|
||||
|
||||
function getPropKeyFromStorage() {
|
||||
if (singleGoalFilterApplied()) {
|
||||
const storedForGoal = storage.getItem(propKeyStorageNameForGoal)
|
||||
if (storedForGoal) { return storedForGoal }
|
||||
}
|
||||
|
||||
return storage.getItem(propKeyStorageName)
|
||||
}
|
||||
|
||||
function fetchProps() {
|
||||
return api.get(url.apiPath(site, `/custom-prop-values/${encodeURIComponent(propKey)}`), query)
|
||||
}
|
||||
|
||||
const fetchPropKeyOptions = useCallback(() => {
|
||||
return (input) => {
|
||||
return api.get(url.apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
|
||||
}
|
||||
}, [query])
|
||||
|
||||
function onPropKeySelect() {
|
||||
return (selectedOptions) => {
|
||||
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0].value
|
||||
|
||||
if (newPropKey) {
|
||||
const storageName = singleGoalFilterApplied() ? propKeyStorageNameForGoal : propKeyStorageName
|
||||
storage.setItem(storageName, newPropKey)
|
||||
}
|
||||
|
||||
setPropKey(newPropKey)
|
||||
}
|
||||
}
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
function renderBreakdown() {
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchProps}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel={propKey}
|
||||
metrics={[
|
||||
{ name: 'visitors', label: 'Visitors', plot: true },
|
||||
{ name: 'events', label: 'Events', hiddenOnMobile: true },
|
||||
query.filters.goal ? CR_METRIC : PERCENTAGE_METRIC,
|
||||
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
|
||||
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
|
||||
]}
|
||||
detailsLink={url.sitePath(site, `/custom-prop-values/${propKey}`)}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const getFilterFor = (listItem) => ({
|
||||
props: JSON.stringify({ ...query.filters.props, [propKey]: escapeFilterValue(listItem.name) })
|
||||
})
|
||||
const comboboxValues = propKey ? [{ value: propKey, label: propKey }] : []
|
||||
const boxClass = 'pl-2 pr-8 py-1 bg-transparent dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-500'
|
||||
|
||||
return (
|
||||
<div className="w-full mt-4">
|
||||
<div>
|
||||
<Combobox boxClass={boxClass} fetchOptions={fetchPropKeyOptions()} singleOption={true} values={comboboxValues} onSelect={onPropKeySelect()} placeholder={'Select a property'} />
|
||||
</div>
|
||||
{propKey && renderBreakdown()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,126 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
import FlipMove from 'react-flip-move'
|
||||
|
||||
|
||||
import Bar from '../bar'
|
||||
import PropBreakdown from './prop-breakdown'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import LazyLoader from '../../components/lazy-loader'
|
||||
|
||||
const MOBILE_UPPER_WIDTH = 767
|
||||
const DEFAULT_WIDTH = 1080
|
||||
|
||||
export default class Conversions extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.htmlNode = React.createRef()
|
||||
this.state = {
|
||||
loading: true,
|
||||
viewport: DEFAULT_WIDTH,
|
||||
}
|
||||
this.onVisible = this.onVisible.bind(this)
|
||||
this.fetchConversions = this.fetchConversions.bind(this)
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('resize', this.handleResize, false);
|
||||
this.handleResize();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize, false);
|
||||
document.removeEventListener('tick', this.fetchConversions)
|
||||
}
|
||||
|
||||
handleResize() {
|
||||
this.setState({ viewport: window.innerWidth });
|
||||
}
|
||||
|
||||
onVisible() {
|
||||
this.fetchConversions()
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchConversions)
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.props.query !== prevProps.query) {
|
||||
const height = this.htmlNode.current.element.offsetHeight
|
||||
this.setState({loading: true, goals: null, prevHeight: height})
|
||||
this.fetchConversions()
|
||||
}
|
||||
}
|
||||
|
||||
getBarMaxWidth() {
|
||||
const { viewport } = this.state;
|
||||
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
|
||||
}
|
||||
|
||||
fetchConversions() {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/conversions`, this.props.query)
|
||||
.then((res) => this.setState({loading: false, goals: res, prevHeight: null}))
|
||||
}
|
||||
|
||||
renderGoal(goal) {
|
||||
const { viewport } = this.state;
|
||||
const renderProps = this.props.query.filters['goal'] == goal.name && goal.prop_names
|
||||
|
||||
return (
|
||||
<div className="my-2 text-sm" key={goal.name}>
|
||||
<div className="flex items-center justify-between my-2">
|
||||
<Bar
|
||||
count={goal.unique_conversions}
|
||||
all={this.state.goals}
|
||||
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={this.getBarMaxWidth()}
|
||||
plot="unique_conversions"
|
||||
>
|
||||
<Link to={url.setQuery('goal', goal.name)} className="block px-2 py-1.5 hover:underline relative z-9 break-all lg:truncate dark:text-gray-200">{goal.name}</Link>
|
||||
</Bar>
|
||||
<div className="dark:text-gray-200">
|
||||
<span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.unique_conversions)}</span>
|
||||
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.total_conversions)}</span>}
|
||||
<span className="inline-block w-20 font-medium text-right">{goal.conversion_rate}%</span>
|
||||
</div>
|
||||
</div>
|
||||
{ renderProps && <PropBreakdown site={this.props.site} query={this.props.query} goal={goal} /> }
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
renderInner() {
|
||||
const { viewport } = this.state;
|
||||
if (this.state.loading) {
|
||||
return <div className="mx-auto my-2 loading"><div></div></div>
|
||||
} else if (this.state.goals) {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h3 className="font-bold dark:text-gray-100">{this.props.title || "Goal Conversions"}</h3>
|
||||
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
|
||||
<span>Goal</span>
|
||||
<div className="text-right">
|
||||
<span className="inline-block w-20">Uniques</span>
|
||||
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20">Total</span>}
|
||||
<span className="inline-block w-20">CR</span>
|
||||
</div>
|
||||
</div>
|
||||
<FlipMove>
|
||||
{ this.state.goals.map(this.renderGoal.bind(this)) }
|
||||
</FlipMove>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<LazyLoader className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825" style={{minHeight: '132px', height: this.state.prevHeight ?? 'auto'}} onVisible={this.onVisible} ref={this.htmlNode}>
|
||||
{ this.renderInner() }
|
||||
</LazyLoader>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,212 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import * as storage from '../../util/storage'
|
||||
import Bar from '../bar'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
|
||||
const MOBILE_UPPER_WIDTH = 767
|
||||
const DEFAULT_WIDTH = 1080
|
||||
const BREAKDOWN_LIMIT = 100
|
||||
|
||||
// https://stackoverflow.com/a/43467144
|
||||
function isValidHttpUrl(string) {
|
||||
let url;
|
||||
|
||||
try {
|
||||
url = new URL(string);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return url.protocol === "http:" || url.protocol === "https:";
|
||||
}
|
||||
|
||||
export default class PropertyBreakdown extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
let propKey = props.goal.prop_names[0]
|
||||
this.storageKey = 'goalPropTab__' + props.site.domain + props.goal.name
|
||||
const storedKey = storage.getItem(this.storageKey)
|
||||
if (props.goal.prop_names.includes(storedKey)) {
|
||||
propKey = storedKey
|
||||
}
|
||||
if (props.query.filters['props']) {
|
||||
propKey = Object.keys(props.query.filters['props'])[0]
|
||||
}
|
||||
|
||||
this.state = {
|
||||
loading: true,
|
||||
propKey: propKey,
|
||||
viewport: DEFAULT_WIDTH,
|
||||
breakdown: [],
|
||||
page: 1,
|
||||
moreResultsAvailable: false
|
||||
}
|
||||
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
this.fetch = this.fetch.bind(this)
|
||||
this.fetchAndReplace = this.fetchAndReplace.bind(this)
|
||||
this.fetchAndConcat = this.fetchAndConcat.bind(this)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('resize', this.handleResize, false);
|
||||
|
||||
this.handleResize();
|
||||
this.fetchAndReplace()
|
||||
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize, false);
|
||||
document.removeEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
|
||||
handleResize() {
|
||||
this.setState({ viewport: window.innerWidth });
|
||||
}
|
||||
|
||||
getBarMaxWidth() {
|
||||
const { viewport } = this.state;
|
||||
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
|
||||
}
|
||||
|
||||
fetch({concat}) {
|
||||
if (!this.props.query.filters['goal']) return
|
||||
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/property/${encodeURIComponent(this.state.propKey)}`, this.props.query, {limit: BREAKDOWN_LIMIT, page: this.state.page})
|
||||
.then((res) => {
|
||||
let breakdown = concat ? this.state.breakdown.concat(res) : res
|
||||
|
||||
this.setState(() => ({
|
||||
loading: false,
|
||||
breakdown: breakdown,
|
||||
moreResultsAvailable: res.length >= BREAKDOWN_LIMIT
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fetchAndReplace() {
|
||||
this.fetch({concat: false})
|
||||
}
|
||||
|
||||
fetchAndConcat() {
|
||||
this.fetch({concat: true})
|
||||
}
|
||||
|
||||
loadMore() {
|
||||
this.setState({loading: true, page: this.state.page + 1}, this.fetchAndConcat.bind(this))
|
||||
}
|
||||
|
||||
renderUrl(value) {
|
||||
if (isValidHttpUrl(value.name)) {
|
||||
return (
|
||||
<a target="_blank" href={value.name} rel="noreferrer" className="hidden group-hover:block">
|
||||
<svg className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
renderPropContent(value, query) {
|
||||
return (
|
||||
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all">
|
||||
<Link
|
||||
to={{pathname: window.location.pathname, search: query.toString()}}
|
||||
className="md:truncate hover:underline block"
|
||||
>
|
||||
{ value.name }
|
||||
</Link>
|
||||
{ this.renderUrl(value) }
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
renderPropValue(value) {
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
query.set('props', JSON.stringify({[this.state.propKey]: value.name}))
|
||||
const { viewport } = this.state;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between my-2" key={value.name}>
|
||||
<Bar
|
||||
count={value.unique_conversions}
|
||||
plot="unique_conversions"
|
||||
all={this.state.breakdown}
|
||||
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={this.getBarMaxWidth()}
|
||||
>
|
||||
{this.renderPropContent(value, query)}
|
||||
</Bar>
|
||||
<div className="dark:text-gray-200">
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.unique_conversions)}</span>
|
||||
{
|
||||
viewport > MOBILE_UPPER_WIDTH ?
|
||||
(
|
||||
<span
|
||||
className="font-medium inline-block w-20 text-right"
|
||||
>{numberFormatter(value.total_conversions)}
|
||||
</span>
|
||||
)
|
||||
: null
|
||||
}
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.conversion_rate)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
changePropKey(newKey) {
|
||||
storage.setItem(this.storageKey, newKey)
|
||||
this.setState({propKey: newKey, loading: true, breakdown: [], page: 1, moreResultsAvailable: false}, this.fetchAndReplace)
|
||||
}
|
||||
|
||||
renderLoading() {
|
||||
if (this.state.loading) {
|
||||
return <div className="px-4 py-2"><div className="loading sm mx-auto"><div></div></div></div>
|
||||
} else if (this.state.moreResultsAvailable && this.props.query.period !== 'realtime') {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={this.loadMore.bind(this)} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
return this.state.breakdown.map((propValue) => this.renderPropValue(propValue))
|
||||
}
|
||||
|
||||
renderPill(key) {
|
||||
const isActive = this.state.propKey === key
|
||||
|
||||
if (isActive) {
|
||||
return <li key={key} className="inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold mr-2 active-prop-heading">{key}</li>
|
||||
} else {
|
||||
return <li key={key} className="hover:text-indigo-600 cursor-pointer mr-2" onClick={this.changePropKey.bind(this, key)}>{key}</li>
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="w-full pl-3 sm:pl-6 mt-4">
|
||||
<div className="flex-col sm:flex-row flex items-center pb-1">
|
||||
<span className="text-xs font-bold text-gray-600 dark:text-gray-300 self-start sm:self-auto mb-1 sm:mb-0">Breakdown by:</span>
|
||||
<ul className="flex flex-wrap font-medium text-xs text-gray-500 dark:text-gray-400 leading-5 pl-1 sm:pl-2">
|
||||
{ this.props.goal.prop_names.map(this.renderPill.bind(this)) }
|
||||
</ul>
|
||||
</div>
|
||||
{ this.renderBody() }
|
||||
{ this.renderLoading()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,122 +0,0 @@
|
||||
import { METRIC_FORMATTER, METRIC_LABELS } from './graph-util.js'
|
||||
import dateFormatter from './date-formatter.js'
|
||||
|
||||
const renderBucketLabel = function(query, graphData, label, comparison = false) {
|
||||
let isPeriodFull = graphData.full_intervals?.[label]
|
||||
if (comparison) isPeriodFull = true
|
||||
|
||||
const formattedLabel = dateFormatter({
|
||||
interval: graphData.interval, longForm: true, period: query.period, isPeriodFull,
|
||||
})(label)
|
||||
|
||||
if (query.period === 'realtime') {
|
||||
return dateFormatter({
|
||||
interval: graphData.interval, longForm: true, period: query.period,
|
||||
})(label)
|
||||
}
|
||||
|
||||
if (graphData.interval === 'hour' || graphData.interval == 'minute') {
|
||||
const date = dateFormatter({ interval: "date", longForm: true, period: query.period })(label)
|
||||
return `${date}, ${formattedLabel}`
|
||||
}
|
||||
|
||||
return formattedLabel
|
||||
}
|
||||
|
||||
const calculatePercentageDifference = function(oldValue, newValue) {
|
||||
if (oldValue == 0 && newValue > 0) {
|
||||
return 100
|
||||
} else if (oldValue == 0 && newValue == 0) {
|
||||
return 0
|
||||
} else {
|
||||
return Math.round((newValue - oldValue) / oldValue * 100)
|
||||
}
|
||||
}
|
||||
|
||||
const buildTooltipData = function(query, graphData, metric, tooltipModel) {
|
||||
const data = tooltipModel.dataPoints.find((dataPoint) => dataPoint.dataset.yAxisID == "y")
|
||||
const comparisonData = tooltipModel.dataPoints.find((dataPoint) => dataPoint.dataset.yAxisID == "yComparison")
|
||||
|
||||
const label = data && renderBucketLabel(query, graphData, graphData.labels[data.dataIndex])
|
||||
const comparisonLabel = comparisonData && renderBucketLabel(query, graphData, graphData.comparison_labels[comparisonData.dataIndex], true)
|
||||
|
||||
const value = data?.raw || 0
|
||||
const comparisonValue = comparisonData?.raw || 0
|
||||
const comparisonDifference = label && comparisonLabel && calculatePercentageDifference(comparisonValue, value)
|
||||
|
||||
const metricFormatter = METRIC_FORMATTER[metric]
|
||||
const formattedValue = metricFormatter(value)
|
||||
const formattedComparisonValue = comparisonData && metricFormatter(comparisonValue)
|
||||
|
||||
return { label, formattedValue, comparisonLabel, formattedComparisonValue, comparisonDifference }
|
||||
}
|
||||
|
||||
export default function GraphTooltip(graphData, metric, query) {
|
||||
return (context) => {
|
||||
const tooltipModel = context.tooltip
|
||||
const offset = document.getElementById("main-graph-canvas").getBoundingClientRect()
|
||||
let tooltipEl = document.getElementById('chartjs-tooltip')
|
||||
|
||||
if (!tooltipEl) {
|
||||
tooltipEl = document.createElement('div')
|
||||
tooltipEl.id = 'chartjs-tooltip'
|
||||
tooltipEl.style.display = 'none'
|
||||
tooltipEl.style.opacity = 0
|
||||
document.body.appendChild(tooltipEl)
|
||||
}
|
||||
|
||||
if (tooltipEl && offset && window.innerWidth < 768) {
|
||||
tooltipEl.style.top = offset.y + offset.height + window.scrollY + 15 + 'px'
|
||||
tooltipEl.style.left = offset.x + 'px'
|
||||
tooltipEl.style.right = null
|
||||
tooltipEl.style.opacity = 1
|
||||
}
|
||||
|
||||
if (tooltipModel.opacity === 0) {
|
||||
tooltipEl.style.display = 'none'
|
||||
return
|
||||
}
|
||||
|
||||
if (tooltipModel.body) {
|
||||
const tooltipData = buildTooltipData(query, graphData, metric, tooltipModel)
|
||||
|
||||
tooltipEl.innerHTML = `
|
||||
<aside class="text-gray-100 flex flex-col">
|
||||
<div class="flex justify-between items-center">
|
||||
<span class="font-semibold mr-4 text-lg">${METRIC_LABELS[metric]}</span>
|
||||
${tooltipData.comparisonDifference ?
|
||||
`<div class="inline-flex items-center space-x-1">
|
||||
${tooltipData.comparisonDifference > 0 ? `<span class="font-semibold text-sm text-green-500">↑</span><span>${tooltipData.comparisonDifference}%</span>` : ""}
|
||||
${tooltipData.comparisonDifference < 0 ? `<span class="font-semibold text-sm text-red-400">↓</span><span>${tooltipData.comparisonDifference * -1}%</span>` : ""}
|
||||
${tooltipData.comparisonDifference == 0 ? `<span class="font-semibold text-sm">〰 0%</span>` : ""}
|
||||
</div>` : ''}
|
||||
</div>
|
||||
|
||||
${tooltipData.label ?
|
||||
`<div class="flex flex-col">
|
||||
<div class="flex flex-row justify-between items-center">
|
||||
<span class="flex items-center mr-4">
|
||||
<div class="w-3 h-3 mr-1 rounded-full" style="background-color: rgba(101,116,205)"></div>
|
||||
<span>${tooltipData.label}</span>
|
||||
</span>
|
||||
<span class="text-base font-bold">${tooltipData.formattedValue}</span>
|
||||
</div>` : ''}
|
||||
|
||||
${tooltipData.comparisonLabel ?
|
||||
`<div class="flex flex-row justify-between items-center">
|
||||
<span class="flex items-center mr-4">
|
||||
<div class="w-3 h-3 mr-1 rounded-full bg-gray-500"></div>
|
||||
<span>${tooltipData.comparisonLabel}</span>
|
||||
</span>
|
||||
<span class="text-base font-bold">${tooltipData.formattedComparisonValue}</span>
|
||||
</div>` : ""}
|
||||
</div>
|
||||
|
||||
${graphData.interval === "month" ? `<span class="font-semibold italic">Click to view month</span>` : ""}
|
||||
${graphData.interval === "date" ? `<span class="font-semibold italic">Click to view day</span>` : ""}
|
||||
</aside>
|
||||
`
|
||||
}
|
||||
tooltipEl.style.display = null
|
||||
}
|
||||
}
|
||||
@ -1,247 +0,0 @@
|
||||
import React from 'react';
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import Chart from 'chart.js/auto';
|
||||
import { navigateToQuery } from '../../query'
|
||||
import GraphTooltip from './graph-tooltip'
|
||||
import { buildDataSet, METRIC_LABELS, METRIC_FORMATTER } from './graph-util'
|
||||
import dateFormatter from './date-formatter';
|
||||
import FadeIn from '../../fade-in';
|
||||
import classNames from 'classnames';
|
||||
|
||||
const calculateMaximumY = function(dataset) {
|
||||
const yAxisValues = dataset
|
||||
.flatMap((item) => item.data)
|
||||
.map((item) => item || 0)
|
||||
|
||||
if (yAxisValues) {
|
||||
return Math.max(...yAxisValues)
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
class LineGraph extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.regenerateChart = this.regenerateChart.bind(this);
|
||||
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
|
||||
}
|
||||
|
||||
getGraphMetric() {
|
||||
let metric = this.props.graphData.metric
|
||||
|
||||
if (metric == 'visitors' && this.props.query.filters.goal) {
|
||||
return 'conversions'
|
||||
} else {
|
||||
return metric
|
||||
}
|
||||
}
|
||||
|
||||
regenerateChart() {
|
||||
const { graphData, query } = this.props
|
||||
const metric = this.getGraphMetric()
|
||||
const graphEl = document.getElementById("main-graph-canvas")
|
||||
this.ctx = graphEl.getContext('2d');
|
||||
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
|
||||
|
||||
return new Chart(this.ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: graphData.labels,
|
||||
datasets: dataSet
|
||||
},
|
||||
options: {
|
||||
animation: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
enabled: false,
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
position: 'average',
|
||||
external: GraphTooltip(graphData, metric, query)
|
||||
},
|
||||
},
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
onResize: this.updateWindowDimensions,
|
||||
elements: { line: { tension: 0 }, point: { radius: 0 } },
|
||||
onClick: this.maybeHopToHoveredPeriod.bind(this),
|
||||
scale: {
|
||||
ticks: { precision: 0, maxTicksLimit: 8 }
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
min: 0,
|
||||
suggestedMax: calculateMaximumY(dataSet),
|
||||
ticks: {
|
||||
callback: METRIC_FORMATTER[metric],
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
},
|
||||
grid: {
|
||||
zeroLineColor: 'transparent',
|
||||
drawBorder: false,
|
||||
}
|
||||
},
|
||||
yComparison: {
|
||||
min: 0,
|
||||
suggestedMax: calculateMaximumY(dataSet),
|
||||
display: false,
|
||||
grid: { display: false },
|
||||
},
|
||||
x: {
|
||||
grid: { display: false },
|
||||
ticks: {
|
||||
callback: function(val, _index, _ticks) {
|
||||
if (this.getLabelForValue(val) == "__blank__") return ""
|
||||
|
||||
const hasMultipleYears =
|
||||
graphData.labels
|
||||
.filter((date) => typeof date === 'string')
|
||||
.map(date => date.split('-')[0])
|
||||
.filter((value, index, list) => list.indexOf(value) === index)
|
||||
.length > 1
|
||||
|
||||
if (graphData.interval === 'hour' && query.period !== 'day') {
|
||||
const date = dateFormatter({
|
||||
interval: "date",
|
||||
longForm: false,
|
||||
period: query.period,
|
||||
shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
|
||||
const hour = dateFormatter({
|
||||
interval: graphData.interval,
|
||||
longForm: false,
|
||||
period: query.period,
|
||||
shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
|
||||
// Returns a combination of date and hour. This is because
|
||||
// small intervals like hour may return multiple days
|
||||
// depending on the query period.
|
||||
return `${date}, ${hour}`
|
||||
}
|
||||
|
||||
if (graphData.interval === 'minute' && query.period !== 'realtime') {
|
||||
return dateFormatter({
|
||||
interval: "hour", longForm: false, period: query.period,
|
||||
})(this.getLabelForValue(val))
|
||||
}
|
||||
|
||||
return dateFormatter({
|
||||
interval: graphData.interval, longForm: false, period: query.period, shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
},
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
repositionTooltip(e) {
|
||||
const tooltipEl = document.getElementById('chartjs-tooltip');
|
||||
if (tooltipEl && window.innerWidth >= 768) {
|
||||
if (e.clientX > 0.66 * window.innerWidth) {
|
||||
tooltipEl.style.right = (window.innerWidth - e.clientX) + window.pageXOffset + 'px'
|
||||
tooltipEl.style.left = null;
|
||||
} else {
|
||||
tooltipEl.style.right = null;
|
||||
tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
|
||||
}
|
||||
tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
|
||||
tooltipEl.style.opacity = 1;
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.graphData) {
|
||||
this.chart = this.regenerateChart();
|
||||
}
|
||||
window.addEventListener('mousemove', this.repositionTooltip);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
const { graphData, darkTheme } = this.props;
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
|
||||
if (
|
||||
graphData !== prevProps.graphData ||
|
||||
darkTheme !== prevProps.darkTheme
|
||||
) {
|
||||
|
||||
if (graphData) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
this.chart = this.regenerateChart();
|
||||
this.chart.update();
|
||||
}
|
||||
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
if (!graphData) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
// Ensure that the tooltip doesn't hang around when we are loading more data
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
if (tooltip) {
|
||||
tooltip.style.opacity = 0;
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
window.removeEventListener('mousemove', this.repositionTooltip)
|
||||
}
|
||||
|
||||
/**
|
||||
* The current ticks' limits are set to treat iPad (regular/Mini/Pro) as a regular screen.
|
||||
* @param {*} chart - The chart instance.
|
||||
* @param {*} dimensions - An object containing the new dimensions *of the chart.*
|
||||
*/
|
||||
updateWindowDimensions(chart, dimensions) {
|
||||
chart.options.scales.x.ticks.maxTicksLimit = dimensions.width < 720 ? 5 : 8
|
||||
}
|
||||
|
||||
maybeHopToHoveredPeriod(e) {
|
||||
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
|
||||
const date = this.props.graphData.labels[element.index] || this.props.graphData.comparison_labels[element.index]
|
||||
|
||||
if (this.props.graphData.interval === 'month') {
|
||||
navigateToQuery(this.props.history, this.props.query, { period: 'month', date })
|
||||
} else if (this.props.graphData.interval === 'date') {
|
||||
navigateToQuery(this.props.history, this.props.query, { period: 'day', date })
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { graphData } = this.props
|
||||
const canvasClass = classNames('mt-4 select-none', { 'cursor-pointer': !['minute', 'hour'].includes(graphData?.interval) })
|
||||
|
||||
return (
|
||||
<FadeIn show={graphData}>
|
||||
<div className="relative h-96 print:h-auto print:pb-8 w-full z-0">
|
||||
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
|
||||
</div>
|
||||
</FadeIn>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(LineGraph)
|
||||
@ -1,17 +0,0 @@
|
||||
import React from "react"
|
||||
|
||||
export default function SamplingNotice({topStatData}) {
|
||||
const samplePercent = topStatData?.samplePercent
|
||||
|
||||
if (samplePercent && samplePercent < 100) {
|
||||
return (
|
||||
<div tooltip={`Stats based on a ${samplePercent}% sample of all visitors`} className="cursor-pointer w-4 h-4 mx-2">
|
||||
<svg className="absolute w-4 h-4 dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
import React, { useState } from "react"
|
||||
import * as api from '../../api'
|
||||
import { getCurrentInterval } from "./interval-picker"
|
||||
|
||||
export default function StatsExport({site, query}) {
|
||||
const [exporting, setExporting] = useState(false)
|
||||
|
||||
function startExport() {
|
||||
setExporting(true)
|
||||
document.cookie = "exporting="
|
||||
pollExportReady()
|
||||
}
|
||||
|
||||
function pollExportReady() {
|
||||
if (document.cookie.includes('exporting')) {
|
||||
setTimeout(pollExportReady, 1000)
|
||||
} else {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return (
|
||||
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function renderExportLink() {
|
||||
const interval = getCurrentInterval(site, query)
|
||||
const queryParams = api.serializeQuery(query, [{ interval }])
|
||||
const endpoint = `/${encodeURIComponent(site.domain)}/export${queryParams}`
|
||||
|
||||
return (
|
||||
<a href={endpoint} download onClick={startExport}>
|
||||
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
||||
<polyline points="7 10 12 15 17 10"></polyline>
|
||||
<line x1="12" y1="15" x2="12" y2="3"></line>
|
||||
</svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-4 h-4 mx-2">
|
||||
{exporting && renderLoading()}
|
||||
{!exporting && renderExportLink()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,161 +1,483 @@
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import React from 'react';
|
||||
import { withRouter, Link } from 'react-router-dom'
|
||||
import Chart from 'chart.js/auto';
|
||||
import { navigateToQuery } from '../../query'
|
||||
import * as api from '../../api'
|
||||
import * as storage from '../../util/storage'
|
||||
import { getGraphableMetrics } from './graph-util'
|
||||
import LazyLoader from '../../components/lazy-loader'
|
||||
import {GraphTooltip, buildDataSet, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER} from './graph-util';
|
||||
import dateFormatter from './date-formatter';
|
||||
import TopStats from './top-stats';
|
||||
import { IntervalPicker, getCurrentInterval } from './interval-picker'
|
||||
import StatsExport from './stats-export'
|
||||
import WithImportedSwitch from './with-imported-switch';
|
||||
import SamplingNotice from './sampling-notice';
|
||||
import { IntervalPicker, getStoredInterval, storeInterval } from './interval-picker';
|
||||
import FadeIn from '../../fade-in';
|
||||
import * as url from '../../util/url'
|
||||
import { isComparisonEnabled } from '../../comparison-input'
|
||||
import LineGraphWithRouter from './line-graph'
|
||||
import classNames from "classnames";
|
||||
|
||||
function fetchTopStats(site, query) {
|
||||
const q = { ...query }
|
||||
|
||||
if (!isComparisonEnabled(q.comparison)) {
|
||||
q.comparison = 'previous_period'
|
||||
const LOADING_STATE = {
|
||||
loading: 'loading',
|
||||
refreshing: 'refreshing',
|
||||
loaded: 'loaded'
|
||||
}
|
||||
|
||||
class LineGraph extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.boundary = React.createRef()
|
||||
this.regenerateChart = this.regenerateChart.bind(this);
|
||||
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
|
||||
this.state = {
|
||||
exported: false
|
||||
};
|
||||
}
|
||||
|
||||
return api.get(url.apiPath(site, '/top-stats'), q)
|
||||
}
|
||||
regenerateChart() {
|
||||
const { graphData, metric, query } = this.props
|
||||
const graphEl = document.getElementById("main-graph-canvas")
|
||||
this.ctx = graphEl.getContext('2d');
|
||||
const dataSet = buildDataSet(graphData.plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
|
||||
// const prev_dataSet = graphData.prev_plot && buildDataSet(graphData.prev_plot, false, this.ctx, METRIC_LABELS[metric], true)
|
||||
// const combinedDataSets = comparison.enabled && prev_dataSet ? [...dataSet, ...prev_dataSet] : dataSet;
|
||||
|
||||
function fetchMainGraph(site, query, metric, interval) {
|
||||
const params = {metric, interval}
|
||||
return api.get(url.apiPath(site, '/main-graph'), query, params)
|
||||
}
|
||||
return new Chart(this.ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: graphData.labels,
|
||||
datasets: dataSet
|
||||
},
|
||||
options: {
|
||||
animation: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
enabled: false,
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
position: 'average',
|
||||
external: GraphTooltip(graphData, metric, query)
|
||||
},
|
||||
},
|
||||
responsive: true,
|
||||
onResize: this.updateWindowDimensions,
|
||||
elements: { line: { tension: 0 }, point: { radius: 0 } },
|
||||
onClick: this.onClick.bind(this),
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
callback: METRIC_FORMATTER[metric],
|
||||
maxTicksLimit: 8,
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
},
|
||||
grid: {
|
||||
zeroLineColor: 'transparent',
|
||||
drawBorder: false,
|
||||
}
|
||||
},
|
||||
x: {
|
||||
grid: { display: false },
|
||||
ticks: {
|
||||
maxTicksLimit: 8,
|
||||
callback: function (val, _index, _ticks) {
|
||||
if (graphData.interval === 'hour' && query.period !== 'day') {
|
||||
const date = dateFormatter("date", false, query.period)(this.getLabelForValue(val))
|
||||
const hour = dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val))
|
||||
|
||||
export default function VisitorGraph(props) {
|
||||
const {site, query, lastLoadTimestamp} = props
|
||||
const isRealtime = query.period === 'realtime'
|
||||
const isDarkTheme = document.querySelector('html').classList.contains('dark') || false
|
||||
// Returns a combination of date and hour. This is because
|
||||
// small intervals like hour may return multiple days
|
||||
// depending on the query period.
|
||||
return `${date}, ${hour}`
|
||||
}
|
||||
|
||||
const topStatsBoundary = useRef(null)
|
||||
if (graphData.interval === 'minute' && query.period !== 'realtime') {
|
||||
return dateFormatter("hour", false, query.period)(this.getLabelForValue(val))
|
||||
}
|
||||
|
||||
const [topStatData, setTopStatData] = useState(null)
|
||||
const [topStatsLoading, setTopStatsLoading] = useState(true)
|
||||
const [graphData, setGraphData] = useState(null)
|
||||
const [graphLoading, setGraphLoading] = useState(true)
|
||||
return dateFormatter(graphData.interval, false, query.period)(this.getLabelForValue(val))
|
||||
},
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// This state is explicitly meant for the situation where either graph interval
|
||||
// or graph metric is changed. That results in behaviour where Top Stats stay
|
||||
// intact, but the graph container alone will display a loading spinner for as
|
||||
// long as new graph data is fetched.
|
||||
const [graphRefreshing, setGraphRefreshing] = useState(false)
|
||||
repositionTooltip(e) {
|
||||
const tooltipEl = document.getElementById('chartjs-tooltip');
|
||||
if (tooltipEl && window.innerWidth >= 768) {
|
||||
if (e.clientX > 0.66 * window.innerWidth) {
|
||||
tooltipEl.style.right = (window.innerWidth - e.clientX) + window.pageXOffset + 'px'
|
||||
tooltipEl.style.left = null;
|
||||
} else {
|
||||
tooltipEl.style.right = null;
|
||||
tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
|
||||
}
|
||||
tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
|
||||
tooltipEl.style.opacity = 1;
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.metric && this.props.graphData) {
|
||||
this.chart = this.regenerateChart();
|
||||
}
|
||||
window.addEventListener('mousemove', this.repositionTooltip);
|
||||
}
|
||||
|
||||
const onIntervalUpdate = useCallback((newInterval) => {
|
||||
setGraphData(null)
|
||||
setGraphRefreshing(true)
|
||||
fetchGraphData(getStoredMetric(), newInterval)
|
||||
}, [query])
|
||||
componentDidUpdate(prevProps) {
|
||||
const { graphData, metric, darkTheme } = this.props;
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
|
||||
const onMetricUpdate = useCallback((newMetric) => {
|
||||
setGraphData(null)
|
||||
setGraphRefreshing(true)
|
||||
fetchGraphData(newMetric, getCurrentInterval(site, query))
|
||||
}, [query])
|
||||
if (
|
||||
graphData !== prevProps.graphData ||
|
||||
darkTheme !== prevProps.darkTheme
|
||||
) {
|
||||
|
||||
useEffect(() => {
|
||||
setTopStatData(null)
|
||||
setTopStatsLoading(true)
|
||||
setGraphData(null)
|
||||
setGraphLoading(true)
|
||||
fetchTopStatsAndGraphData()
|
||||
if (metric && graphData) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
this.chart = this.regenerateChart();
|
||||
this.chart.update();
|
||||
}
|
||||
|
||||
if (isRealtime) {
|
||||
document.addEventListener('tick', fetchTopStatsAndGraphData)
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('tick', fetchTopStatsAndGraphData)
|
||||
}
|
||||
}, [query])
|
||||
if (!graphData || !metric) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (topStatData) { storeTopStatsContainerHeight() }
|
||||
}, [topStatData])
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function fetchTopStatsAndGraphData() {
|
||||
fetchTopStats(site, query)
|
||||
.then((res) => {
|
||||
setTopStatData(res)
|
||||
setTopStatsLoading(false)
|
||||
})
|
||||
|
||||
let metric = getStoredMetric()
|
||||
const availableMetrics = getGraphableMetrics(query, site)
|
||||
|
||||
if (!availableMetrics.includes(metric)) {
|
||||
metric = availableMetrics[0]
|
||||
storage.setItem(`metric__${site.domain}`, metric)
|
||||
componentWillUnmount() {
|
||||
// Ensure that the tooltip doesn't hang around when we are loading more data
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
if (tooltip) {
|
||||
tooltip.style.opacity = 0;
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
window.removeEventListener('mousemove', this.repositionTooltip)
|
||||
}
|
||||
|
||||
/**
|
||||
* The current ticks' limits are set to treat iPad (regular/Mini/Pro) as a regular screen.
|
||||
* @param {*} chart - The chart instance.
|
||||
* @param {*} dimensions - An object containing the new dimensions *of the chart.*
|
||||
*/
|
||||
updateWindowDimensions(chart, dimensions) {
|
||||
chart.options.scales.x.ticks.maxTicksLimit = dimensions.width < 720 ? 5 : 8
|
||||
chart.options.scales.y.ticks.maxTicksLimit = dimensions.height < 233 ? 3 : 8
|
||||
}
|
||||
|
||||
onClick(e) {
|
||||
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
|
||||
const date = this.chart.data.labels[element.index]
|
||||
|
||||
const interval = getCurrentInterval(site, query)
|
||||
if (this.props.graphData.interval === 'month') {
|
||||
navigateToQuery(
|
||||
this.props.history,
|
||||
this.props.query,
|
||||
{
|
||||
period: 'month',
|
||||
date,
|
||||
}
|
||||
)
|
||||
} else if (this.props.graphData.interval === 'date') {
|
||||
navigateToQuery(
|
||||
this.props.history,
|
||||
this.props.query,
|
||||
{
|
||||
period: 'day',
|
||||
date,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fetchGraphData(metric, interval)
|
||||
pollExportReady() {
|
||||
if (document.cookie.includes('exporting')) {
|
||||
setTimeout(this.pollExportReady.bind(this), 1000);
|
||||
} else {
|
||||
this.setState({exported: false})
|
||||
}
|
||||
}
|
||||
|
||||
function fetchGraphData(metric, interval) {
|
||||
fetchMainGraph(site, query, metric, interval)
|
||||
.then((res) => {
|
||||
setGraphData(res)
|
||||
setGraphLoading(false)
|
||||
setGraphRefreshing(false)
|
||||
})
|
||||
downloadSpinner() {
|
||||
this.setState({exported: true});
|
||||
document.cookie = "exporting=";
|
||||
setTimeout(this.pollExportReady.bind(this), 1000);
|
||||
}
|
||||
|
||||
function getStoredMetric() {
|
||||
return storage.getItem(`metric__${site.domain}`)
|
||||
downloadLink() {
|
||||
if (this.props.query.period !== 'realtime') {
|
||||
|
||||
if (this.state.exported) {
|
||||
return (
|
||||
<div className="w-4 h-4 mx-2">
|
||||
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
const interval = this.props.graphData?.interval
|
||||
const queryParams = api.serializeQuery(this.props.query, [{ interval }])
|
||||
const endpoint = `/${encodeURIComponent(this.props.site.domain)}/export${queryParams}`
|
||||
|
||||
return (
|
||||
<a className="w-4 h-4 mx-2" href={endpoint} download onClick={this.downloadSpinner.bind(this)}>
|
||||
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function storeTopStatsContainerHeight() {
|
||||
storage.setItem(`topStatsHeight__${site.domain}`, document.getElementById('top-stats-container').clientHeight)
|
||||
samplingNotice() {
|
||||
const samplePercent = this.props.topStatData && this.props.topStatData.sample_percent
|
||||
|
||||
if (samplePercent < 100) {
|
||||
return (
|
||||
<div tooltip={`Stats based on a ${samplePercent}% sample of all visitors`} className="cursor-pointer w-4 h-4 mx-2">
|
||||
<svg className="absolute w-4 h-4 dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// This function is used for maintaining the main-graph/top-stats container height in the
|
||||
// loading process. The container height depends on how many top stat metrics are returned
|
||||
// from the API, but in the loading state, we don't know that yet. We can use localStorage
|
||||
// to keep track of the Top Stats container height.
|
||||
function getTopStatsHeight() {
|
||||
if (topStatData) {
|
||||
return 'auto'
|
||||
} else {
|
||||
return `${storage.getItem(`topStatsHeight__${site.domain}`) || 89}px`
|
||||
importedNotice() {
|
||||
const source = this.props.topStatData && this.props.topStatData.imported_source;
|
||||
|
||||
if (source) {
|
||||
const withImported = this.props.topStatData.with_imported;
|
||||
const strike = withImported ? "" : " line-through"
|
||||
const target = url.setQuery('with_imported', !withImported)
|
||||
const tip = withImported ? "" : "do not ";
|
||||
|
||||
return (
|
||||
<Link to={target} className="w-4 h-4 mx-2">
|
||||
<div tooltip={`Stats ${tip}include data imported from ${source}.`} className="cursor-pointer w-4 h-4">
|
||||
<svg className="absolute dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<text x="4" y="18" fontSize="24" fill="currentColor" className={"text-gray-700 dark:text-gray-300" + strike}>{ source[0].toUpperCase() }</text>
|
||||
</svg>
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { updateMetric, metric, topStatData, query, site, graphData } = this.props
|
||||
const extraClass = this.props.graphData && this.props.graphData.interval === 'hour' ? '' : 'cursor-pointer'
|
||||
|
||||
return (
|
||||
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}>
|
||||
{(topStatsLoading || graphLoading) && renderLoader()}
|
||||
<FadeIn show={!(topStatsLoading || graphLoading)}>
|
||||
<div id="top-stats-container" className="flex flex-wrap" ref={topStatsBoundary} style={{ height: getTopStatsHeight() }}>
|
||||
<TopStats site={site} query={query} data={topStatData} onMetricUpdate={onMetricUpdate} tooltipBoundary={topStatsBoundary.current} lastLoadTimestamp={lastLoadTimestamp} />
|
||||
return (
|
||||
<div className="graph-inner">
|
||||
<div className="flex flex-wrap" ref={this.boundary}>
|
||||
<TopStats query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={this.props.lastLoadTimestamp} />
|
||||
</div>
|
||||
<div className="relative px-2">
|
||||
{graphRefreshing && renderLoader()}
|
||||
<div className="absolute right-4 -top-8 py-1 flex items-center">
|
||||
{!isRealtime && <StatsExport site={site} query={query} />}
|
||||
<SamplingNotice samplePercent={topStatData}/>
|
||||
<WithImportedSwitch site={site} topStatData={topStatData} />
|
||||
<IntervalPicker site={site} query={query} onIntervalUpdate={onIntervalUpdate} />
|
||||
<div className="absolute right-4 -top-10 py-2 md:py-0 flex items-center">
|
||||
{ this.downloadLink() }
|
||||
{ this.samplingNotice() }
|
||||
{ this.importedNotice() }
|
||||
<IntervalPicker site={site} query={query} graphData={graphData} metric={metric} updateInterval={this.props.updateInterval}/>
|
||||
</div>
|
||||
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} />
|
||||
<FadeIn show={graphData}>
|
||||
<canvas id="main-graph-canvas" className={'mt-4 select-none ' + extraClass} width="1054" height="342"></canvas>
|
||||
</FadeIn>
|
||||
</div>
|
||||
</FadeIn>
|
||||
</div>
|
||||
)
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function renderLoader() {
|
||||
return (
|
||||
<div className="absolute h-full w-full flex items-center justify-center">
|
||||
<div className="loading">
|
||||
<div></div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
const LineGraphWithRouter = withRouter(LineGraph)
|
||||
|
||||
export default class VisitorGraph extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.state = {
|
||||
topStatsLoadingState: LOADING_STATE.loading,
|
||||
mainGraphLoadingState: LOADING_STATE.loading,
|
||||
metric: storage.getItem(`metric__${this.props.site.domain}`) || 'visitors'
|
||||
}
|
||||
this.onVisible = this.onVisible.bind(this)
|
||||
this.updateMetric = this.updateMetric.bind(this)
|
||||
this.fetchTopStatData = this.fetchTopStatData.bind(this)
|
||||
this.fetchGraphData = this.fetchGraphData.bind(this)
|
||||
this.updateInterval = this.updateInterval.bind(this)
|
||||
}
|
||||
|
||||
isIntervalValid(interval) {
|
||||
const { query, site } = this.props
|
||||
const validIntervals = site.validIntervalsByPeriod[query.period] || []
|
||||
|
||||
return validIntervals.includes(interval)
|
||||
}
|
||||
|
||||
getIntervalFromStorage() {
|
||||
const { query, site } = this.props
|
||||
const storedInterval = getStoredInterval(query.period, site.domain)
|
||||
|
||||
if (this.isIntervalValid(storedInterval)) {
|
||||
return storedInterval
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
updateInterval(interval) {
|
||||
if (this.isIntervalValid(interval)) {
|
||||
storeInterval(this.props.query.period, this.props.site.domain, interval)
|
||||
this.setState({ mainGraphLoadingState: LOADING_STATE.refreshing }, this.fetchGraphData)
|
||||
}
|
||||
}
|
||||
|
||||
onVisible() {
|
||||
this.setState({mainGraphLoadingState: LOADING_STATE.loading}, this.fetchGraphData)
|
||||
this.fetchTopStatData()
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchGraphData)
|
||||
document.addEventListener('tick', this.fetchTopStatData)
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps, prevState) {
|
||||
const { metric, topStatData } = this.state;
|
||||
const { query, site } = this.props
|
||||
|
||||
if (query !== prevProps.query) {
|
||||
if (this.isGraphCollapsed()) {
|
||||
this.setState({ topStatsLoadingState: LOADING_STATE.loading, topStatData: null })
|
||||
} else {
|
||||
this.setState({ mainGraphLoadingState: LOADING_STATE.loading, topStatsLoadingState: LOADING_STATE.loading, graphData: null, topStatData: null }, this.fetchGraphData)
|
||||
}
|
||||
this.fetchTopStatData()
|
||||
}
|
||||
|
||||
if (metric !== prevState.metric) {
|
||||
this.setState({mainGraphLoadingState: LOADING_STATE.refreshing}, this.fetchGraphData)
|
||||
}
|
||||
|
||||
const savedMetric = storage.getItem(`metric__${site.domain}`)
|
||||
const topStatLabels = topStatData && topStatData.top_stats.map(({ name }) => METRIC_MAPPING[name]).filter(name => name)
|
||||
const prevTopStatLabels = prevState.topStatData && prevState.topStatData.top_stats.map(({ name }) => METRIC_MAPPING[name]).filter(name => name)
|
||||
if (topStatLabels && `${topStatLabels}` !== `${prevTopStatLabels}`) {
|
||||
if (query.filters.goal && metric !== 'conversions') {
|
||||
this.setState({ metric: 'conversions' })
|
||||
} else if (topStatLabels.includes(savedMetric) && savedMetric !== "") {
|
||||
this.setState({ metric: savedMetric })
|
||||
} else {
|
||||
this.setState({ metric: topStatLabels[0] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isGraphCollapsed() {
|
||||
return this.state.metric === ""
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener('tick', this.fetchGraphData)
|
||||
document.removeEventListener('tick', this.fetchTopStatData)
|
||||
}
|
||||
|
||||
updateMetric(clickedMetric) {
|
||||
const newMetric = clickedMetric === this.state.metric ? "" : clickedMetric
|
||||
|
||||
storage.setItem(`metric__${this.props.site.domain}`, newMetric)
|
||||
this.setState({ metric: newMetric })
|
||||
}
|
||||
|
||||
fetchGraphData() {
|
||||
if (this.isGraphCollapsed()) {
|
||||
this.setState({ mainGraphLoadingState: LOADING_STATE.loaded, graphData: null })
|
||||
return
|
||||
}
|
||||
|
||||
const url = `/api/stats/${encodeURIComponent(this.props.site.domain)}/main-graph`
|
||||
let params = { metric: this.state.metric }
|
||||
const interval = this.getIntervalFromStorage()
|
||||
if (interval) { params.interval = interval }
|
||||
|
||||
api.get(url, this.props.query, params)
|
||||
.then((res) => {
|
||||
this.setState({ mainGraphLoadingState: LOADING_STATE.loaded, graphData: res })
|
||||
return res
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err)
|
||||
this.setState({ mainGraphLoadingState: LOADING_STATE.loaded, graphData: false })
|
||||
})
|
||||
}
|
||||
|
||||
fetchTopStatData() {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, this.props.query)
|
||||
.then((res) => {
|
||||
this.setState({ topStatsLoadingState: LOADING_STATE.loaded, topStatData: res })
|
||||
return res
|
||||
})
|
||||
}
|
||||
|
||||
renderInner() {
|
||||
const { query, site } = this.props;
|
||||
const { graphData, metric, topStatData, topStatsLoadingState, mainGraphLoadingState } = this.state;
|
||||
|
||||
const theme = document.querySelector('html').classList.contains('dark') || false
|
||||
|
||||
const topStatsLoadedOrRefreshing = (topStatsLoadingState === LOADING_STATE.loaded || topStatsLoadingState === LOADING_STATE.refreshing)
|
||||
const mainGraphLoadedOrRefreshing = (mainGraphLoadingState === LOADING_STATE.loaded || mainGraphLoadingState === LOADING_STATE.refreshing)
|
||||
const noMetricOrRefreshing = (!metric || mainGraphLoadingState === LOADING_STATE.refreshing)
|
||||
const topStatAndGraphLoaded = !!(topStatData && graphData)
|
||||
|
||||
const showGraph =
|
||||
topStatsLoadedOrRefreshing &&
|
||||
mainGraphLoadedOrRefreshing &&
|
||||
(topStatData && noMetricOrRefreshing || topStatAndGraphLoaded)
|
||||
|
||||
return (
|
||||
<FadeIn show={showGraph}>
|
||||
<LineGraphWithRouter graphData={graphData} topStatData={topStatData} site={site} query={query} darkTheme={theme} metric={metric} updateMetric={this.updateMetric} updateInterval={this.updateInterval} lastLoadTimestamp={this.props.lastLoadTimestamp} />
|
||||
</FadeIn>
|
||||
)
|
||||
}
|
||||
|
||||
render() {
|
||||
const {metric, mainGraphLoadingState, topStatsLoadingState} = this.state
|
||||
const loaderClassName = classNames('mx-auto loading', {
|
||||
'pt-52 sm:pt-56 md:pt-60': mainGraphLoadingState == LOADING_STATE.refreshing,
|
||||
'pt-32 sm:pt-36 md:pt-48': mainGraphLoadingState !== LOADING_STATE.refreshing && metric,
|
||||
'pt-16 sm:pt-14 md:pt-18 lg:pt-5': mainGraphLoadingState !== LOADING_STATE.refreshing && !metric
|
||||
})
|
||||
|
||||
const loadingOrRefreshing =
|
||||
mainGraphLoadingState == LOADING_STATE.refreshing ||
|
||||
mainGraphLoadingState == LOADING_STATE.loading ||
|
||||
topStatsLoadingState == LOADING_STATE.refreshing ||
|
||||
topStatsLoadingState == LOADING_STATE.loading
|
||||
|
||||
return (
|
||||
<LazyLoader onVisible={this.onVisible}>
|
||||
<div className={`relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825 transition-padding ease-in-out duration-150 ${metric ? 'main-graph' : 'top-stats-only'}`}>
|
||||
{loadingOrRefreshing && <div className="graph-inner"><div className={loaderClassName}><div></div></div></div>}
|
||||
{this.renderInner()}
|
||||
</div>
|
||||
</LazyLoader>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
import React from "react"
|
||||
import { parseNaiveDate, isBefore } from '../../util/date'
|
||||
import { Link } from 'react-router-dom'
|
||||
import * as url from '../../util/url'
|
||||
import { BarsArrowUpIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
export default function WithImportedSwitch({site, topStatData}) {
|
||||
if (!topStatData?.imports_exist) {
|
||||
return null
|
||||
}
|
||||
|
||||
function isBeforeNativeStats(date) {
|
||||
if (!date) return false
|
||||
|
||||
const nativeStatsBegin = parseNaiveDate(site.nativeStatsBegin)
|
||||
const parsedDate = parseNaiveDate(date)
|
||||
|
||||
return isBefore(parsedDate, nativeStatsBegin, "day")
|
||||
}
|
||||
|
||||
const isQueryingImportedPeriod = isBeforeNativeStats(topStatData.from)
|
||||
const isComparingImportedPeriod = isBeforeNativeStats(topStatData.comparing_from)
|
||||
|
||||
if (isQueryingImportedPeriod || isComparingImportedPeriod) {
|
||||
const withImported = topStatData.with_imported;
|
||||
const toggleColor = withImported ? " dark:text-gray-300 text-gray-700" : " dark:text-gray-500 text-gray-400"
|
||||
const target = url.setQuery('with_imported', !withImported)
|
||||
const tip = withImported ? "" : "do not ";
|
||||
|
||||
return (
|
||||
<Link to={target} className="w-4 h-4 mx-2">
|
||||
<div tooltip={`Stats ${tip}include imported data.`} className="cursor-pointer w-4 h-4">
|
||||
<BarsArrowUpIcon className={"absolute " + toggleColor} />
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,129 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Link } from 'react-router-dom'
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import Modal from './modal'
|
||||
import * as api from '../../api'
|
||||
import * as url from "../../util/url";
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import { parseQuery } from '../../query'
|
||||
import { escapeFilterValue } from '../../util/filters'
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
function ConversionsModal(props) {
|
||||
const site = props.site
|
||||
const query = parseQuery(props.location.search, site)
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
|
||||
const [page, setPage] = useState(1)
|
||||
const [list, setList] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
function fetchData() {
|
||||
api.get(url.apiPath(site, `/conversions`), query, { limit: 100, page })
|
||||
.then((res) => {
|
||||
setLoading(false)
|
||||
setList(list.concat(res))
|
||||
setPage(page + 1)
|
||||
setMoreResultsAvailable(res.length >= 100)
|
||||
})
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
setLoading(true)
|
||||
fetchData()
|
||||
}
|
||||
|
||||
function renderLoadMore() {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={loadMore} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function filterSearchLink(listItem) {
|
||||
const searchParams = new URLSearchParams(window.location.search)
|
||||
searchParams.set('goal', escapeFilterValue(listItem.name))
|
||||
return searchParams.toString()
|
||||
}
|
||||
|
||||
function renderListItem(listItem, hasRevenue) {
|
||||
return (
|
||||
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
|
||||
<td className="p-2">
|
||||
<Link
|
||||
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
|
||||
className="hover:underline block truncate">
|
||||
{listItem.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return <div className="loading my-16 mx-auto"><div></div></div>
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const hasRevenue = BUILD_EXTRA && list.some((goal) => goal.total_revenue)
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Goal Conversions</h1>
|
||||
|
||||
<div className="my-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">Goal</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Uniques</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Total</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">CR</th>
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((item) => renderListItem(item, hasRevenue))}
|
||||
</tbody>
|
||||
</table>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={site}>
|
||||
{renderBody()}
|
||||
{loading && renderLoading()}
|
||||
{!loading && moreResultsAvailable && renderLoadMore()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(ConversionsModal)
|
||||
@ -1,24 +0,0 @@
|
||||
import React from "react"
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import Modal from './modal'
|
||||
import RegularFilterModal from './regular-filter-modal'
|
||||
import PropFilterModal from "./prop-filter-modal"
|
||||
|
||||
function FilterModal(props) {
|
||||
function renderBody() {
|
||||
const filterGroup = props.match.params.field || 'page'
|
||||
if (filterGroup === 'props') {
|
||||
return <PropFilterModal site={props.site} />
|
||||
} else {
|
||||
return <RegularFilterModal site={props.site} filterGroup={filterGroup} />
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={props.site} maxWidth="460px">
|
||||
{renderBody()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(FilterModal)
|
||||
@ -0,0 +1,402 @@
|
||||
import React, { Fragment } from "react";
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import classNames from 'classnames'
|
||||
import { Menu, Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
import SearchSelect from '../../components/search-select'
|
||||
import Modal from './modal'
|
||||
import { parseQuery, formattedFilters } from '../../query'
|
||||
import * as api from '../../api'
|
||||
import {apiPath, siteBasePath} from '../../util/url'
|
||||
|
||||
export const FILTER_GROUPS = {
|
||||
'page': ['page', 'entry_page', 'exit_page'],
|
||||
'source': ['source', 'referrer'],
|
||||
'location': ['country', 'region', 'city'],
|
||||
'screen': ['screen'],
|
||||
'browser': ['browser', 'browser_version'],
|
||||
'os': ['os', 'os_version'],
|
||||
'utm': ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'],
|
||||
'goal': ['goal'],
|
||||
'props': ['prop_key', 'prop_value']
|
||||
}
|
||||
|
||||
function getFormState(filterGroup, query) {
|
||||
if (filterGroup === 'props') {
|
||||
const propsObject = query.filters['props']
|
||||
const entries = propsObject && Object.entries(propsObject)
|
||||
|
||||
if (entries && entries.length == 1) {
|
||||
const propKey = entries[0][0]
|
||||
const propValue = valueWithoutPrefix(entries[0][1])
|
||||
|
||||
return {
|
||||
'prop_key': {name: propKey, value: propKey, type: FILTER_TYPES.is},
|
||||
'prop_value': {name: propValue, value: propValue, type: toFilterType(entries[0][1])}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return FILTER_GROUPS[filterGroup].reduce((result, filter) => {
|
||||
const rawFilterValue = query.filters[filter] || ''
|
||||
const type = toFilterType(rawFilterValue)
|
||||
const filterValue = valueWithoutPrefix(rawFilterValue)
|
||||
|
||||
let filterName = filterValue
|
||||
|
||||
if (filter === 'country' && filterValue !== '') {
|
||||
filterName = (new URLSearchParams(window.location.search)).get('country_name')
|
||||
}
|
||||
if (filter === 'region' && filterValue !== '') {
|
||||
filterName = (new URLSearchParams(window.location.search)).get('region_name')
|
||||
}
|
||||
if (filter === 'city' && filterValue !== '') {
|
||||
filterName = (new URLSearchParams(window.location.search)).get('city_name')
|
||||
}
|
||||
return Object.assign(result, {[filter]: {name: filterName, value: filterValue, type}})
|
||||
}, {})
|
||||
}
|
||||
|
||||
const FILTER_TYPES = {
|
||||
isNot: 'is not',
|
||||
contains: 'contains',
|
||||
is: 'is'
|
||||
};
|
||||
|
||||
const FILTER_PREFIXES = {
|
||||
[FILTER_TYPES.isNot]: '!',
|
||||
[FILTER_TYPES.contains]: '~',
|
||||
[FILTER_TYPES.is]: ''
|
||||
};
|
||||
|
||||
export function toFilterType(value) {
|
||||
return Object.keys(FILTER_PREFIXES)
|
||||
.find(type => FILTER_PREFIXES[type] === value[0]) || FILTER_TYPES.is;
|
||||
}
|
||||
|
||||
export function valueWithoutPrefix(value) {
|
||||
return [FILTER_TYPES.isNot, FILTER_TYPES.contains].includes(toFilterType(value))
|
||||
? value.substring(1)
|
||||
: value;
|
||||
}
|
||||
|
||||
function toFilterQuery(value, type) {
|
||||
const prefix = FILTER_PREFIXES[type];
|
||||
return prefix + value.trim();
|
||||
}
|
||||
|
||||
function supportsContains(filterName) {
|
||||
return ['page', 'entry_page', 'exit_page'].includes(filterName)
|
||||
}
|
||||
|
||||
function supportsIsNot(filterName) {
|
||||
return !['goal', 'prop_key'].includes(filterName)
|
||||
}
|
||||
|
||||
function withIndefiniteArticle(word) {
|
||||
if (word.startsWith('UTM')) {
|
||||
return `a ${ word}`
|
||||
} if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) {
|
||||
return `an ${ word}`
|
||||
}
|
||||
return `a ${ word}`
|
||||
|
||||
}
|
||||
|
||||
export function formatFilterGroup(filterGroup) {
|
||||
if (filterGroup === 'utm') {
|
||||
return 'UTM tags'
|
||||
} else if (filterGroup === 'location') {
|
||||
return 'Location'
|
||||
} else if (filterGroup === 'props') {
|
||||
return 'Property'
|
||||
} else {
|
||||
return formattedFilters[filterGroup]
|
||||
}
|
||||
}
|
||||
|
||||
export function filterGroupForFilter(filter) {
|
||||
const map = Object.entries(FILTER_GROUPS).reduce((filterToGroupMap, [group, filtersInGroup]) => {
|
||||
const filtersToAdd = {}
|
||||
filtersInGroup.forEach((filterInGroup) => {
|
||||
filtersToAdd[filterInGroup] = group
|
||||
})
|
||||
|
||||
return { ...filterToGroupMap, ...filtersToAdd}
|
||||
}, {})
|
||||
|
||||
|
||||
return map[filter] || filter
|
||||
}
|
||||
|
||||
class FilterModal extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const selectedFilterGroup = this.props.match.params.field || 'page'
|
||||
const formState = getFormState(selectedFilterGroup, query)
|
||||
|
||||
this.state = {selectedFilterGroup, query, formState}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
document.addEventListener("keydown", this.handleKeydown)
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener("keydown", this.handleKeydown);
|
||||
}
|
||||
|
||||
handleKeydown(e) {
|
||||
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.isComposing || e.keyCode === 229) {
|
||||
return
|
||||
}
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
this.handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
const { formState } = this.state;
|
||||
|
||||
const filters = Object.entries(formState).reduce((res, [filterKey, {type, value, name}]) => {
|
||||
if (filterKey === 'country') { res.push({filter: 'country_name', value: name}) }
|
||||
if (filterKey === 'region') { res.push({filter: 'region_name', value: name}) }
|
||||
if (filterKey === 'city') { res.push({filter: 'city_name', value: name}) }
|
||||
if (filterKey === 'prop_value') {return res}
|
||||
if (filterKey === 'prop_key') {
|
||||
let propValue = formState['prop_value']
|
||||
let filterValue = JSON.stringify({ [value]: toFilterQuery(propValue.value, propValue.type) })
|
||||
res.push({filter: 'props', value: filterValue})
|
||||
return res
|
||||
}
|
||||
|
||||
res.push({filter: filterKey, value: toFilterQuery(value, type)})
|
||||
return res
|
||||
}, [])
|
||||
|
||||
this.selectFiltersAndCloseModal(filters)
|
||||
}
|
||||
|
||||
onSelect(filterName) {
|
||||
if (this.state.selectedFilterGroup !== 'location') {
|
||||
return () => {}
|
||||
}
|
||||
|
||||
return (value) => {
|
||||
this.setState(prevState => ({formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], {value: value.code, name: value.name})
|
||||
})}))
|
||||
}
|
||||
}
|
||||
|
||||
onInput(filterName) {
|
||||
if (this.state.selectedFilterGroup === 'location') {
|
||||
return () => {}
|
||||
}
|
||||
|
||||
return (value) => {
|
||||
this.setState(prevState => ({formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], {value})
|
||||
})}))
|
||||
}
|
||||
}
|
||||
|
||||
setFilterType(filterName, newType) {
|
||||
this.setState(prevState => ({formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], {type: newType})
|
||||
})}))
|
||||
}
|
||||
|
||||
fetchOptions(filter) {
|
||||
return (input) => {
|
||||
const {query, formState} = this.state
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState).map(([k, v]) => [k, v.code || v.value])
|
||||
)
|
||||
const updatedQuery = this.queryForSuggestions(query, formFilters, filter)
|
||||
return api.get(apiPath(this.props.site, `/suggestions/${filter}`), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
queryForSuggestions(query, formFilters, filter) {
|
||||
if (filter === 'prop_key') {
|
||||
const propsFilter = formFilters.prop_value ? {'': formFilters.prop_value} : null
|
||||
return {...query, filters: { ...query.filters, props: propsFilter}}
|
||||
} else if (filter === 'prop_value') {
|
||||
const propsFilter = formFilters.prop_key ? {[formFilters.prop_key]: '!(none)'} : null
|
||||
return {...query, filters: { ...query.filters, props: propsFilter}}
|
||||
} else {
|
||||
return {...query, filters: { ...query.filters, ...formFilters, [filter]: null }}
|
||||
}
|
||||
}
|
||||
|
||||
selectedFilterType(filter) {
|
||||
return this.state.formState[filter].type
|
||||
}
|
||||
|
||||
isDisabled() {
|
||||
return Object.entries(this.state.formState).every(([_key, {value: val}]) => !val)
|
||||
}
|
||||
|
||||
selectFiltersAndCloseModal(filters) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
filters.forEach((entry) => {
|
||||
if (entry.value) {
|
||||
queryString.set(entry.filter, entry.value)
|
||||
} else {
|
||||
queryString.delete(entry.filter)
|
||||
}
|
||||
})
|
||||
|
||||
this.props.history.replace({pathname: siteBasePath(this.props.site), search: queryString.toString()})
|
||||
}
|
||||
|
||||
renderFilterInputs() {
|
||||
const groups = FILTER_GROUPS[this.state.selectedFilterGroup]
|
||||
|
||||
return groups.map((filter) => {
|
||||
return (
|
||||
<div className="mt-4" key={filter}>
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">{ formattedFilters[filter] }</div>
|
||||
<div className="flex items-start mt-1">
|
||||
{ this.renderFilterTypeSelector(filter) }
|
||||
<SearchSelect
|
||||
key={filter}
|
||||
fetchOptions={this.fetchOptions(filter)}
|
||||
initialSelectedItem={this.state.formState[filter]}
|
||||
onInput={this.onInput(filter)}
|
||||
onSelect={this.onSelect(filter)}
|
||||
placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
renderFilterTypeSelector(filterName) {
|
||||
return (
|
||||
<Menu as="div" className="relative inline-block text-left">
|
||||
{({ open }) => (
|
||||
<>
|
||||
<div className="w-24">
|
||||
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
|
||||
{ this.selectedFilterType(filterName) }
|
||||
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
show={open}
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
static
|
||||
className="z-10 origin-top-left absolute left-0 mt-2 w-24 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
>
|
||||
<div className="py-1">
|
||||
{ this.renderTypeItem(filterName, FILTER_TYPES.is, true) }
|
||||
{ this.renderTypeItem(filterName, FILTER_TYPES.isNot, supportsIsNot(filterName)) }
|
||||
{ this.renderTypeItem(filterName, FILTER_TYPES.contains, supportsContains(filterName)) }
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
renderTypeItem(filterName, type, shouldDisplay) {
|
||||
return (
|
||||
shouldDisplay && (
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={() => this.setFilterType(filterName, type)}
|
||||
className={classNames(
|
||||
active ? "bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100" : "text-gray-700 dark:text-gray-200",
|
||||
"cursor-pointer block px-4 py-2 text-sm"
|
||||
)}
|
||||
>
|
||||
{ type }
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
const { selectedFilterGroup, query } = this.state;
|
||||
const showClear = FILTER_GROUPS[selectedFilterGroup].some((filterName) => query.filters[filterName])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by {formatFilterGroup(selectedFilterGroup)}</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" id="filter-form" onSubmit={this.handleSubmit.bind(this)}>
|
||||
{this.renderFilterInputs()}
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={this.isDisabled()}
|
||||
>
|
||||
Save Filter
|
||||
</button>
|
||||
|
||||
{showClear && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => {
|
||||
const updatedFilters = FILTER_GROUPS[selectedFilterGroup].map((filterName) => ({filter: filterName, value: null}))
|
||||
this.selectFiltersAndCloseModal(updatedFilters)
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter{FILTER_GROUPS[selectedFilterGroup].length > 1 ? 's' : ''}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
{this.renderHints()}
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
renderHints() {
|
||||
if (['page', 'entry_page', 'exit_page'].includes(this.state.selectedFilterGroup)) {
|
||||
return (
|
||||
<p className="mt-6 text-xs text-gray-500">Hint: You can use double asterisks to match any character e.g. /blog** to group all of your blog posts. Or use double asterisks in front and back (e.g. **keyword**) to group all URLs containing a specific keyword.</p>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Modal site={this.props.site} maxWidth="460px">
|
||||
{ this.renderBody()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(FilterModal)
|
||||
@ -1,205 +0,0 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react'
|
||||
import { withRouter } from "react-router-dom";
|
||||
|
||||
import { FILTER_OPERATIONS } from "../../util/filters";
|
||||
import { parseQuery } from '../../query'
|
||||
import { siteBasePath } from '../../util/url'
|
||||
import { toFilterQuery, parseQueryPropsFilter } from '../../util/filters';
|
||||
import { shouldIgnoreKeypress } from '../../keybinding';
|
||||
import PropFilterRow from './prop-filter-row';
|
||||
|
||||
function getFormState(query) {
|
||||
if (query.filters['props']) {
|
||||
const values = Object.fromEntries(parseQueryPropsFilter(query, 'props').map((value, index) => [index, value]))
|
||||
|
||||
return {
|
||||
entries: Object.keys(values).sort(),
|
||||
values
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
entries: [0],
|
||||
values: {
|
||||
0: {
|
||||
propKey: null,
|
||||
type: FILTER_OPERATIONS.is,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function PropFilterModal(props) {
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const [formState, setFormState] = useState(getFormState(query))
|
||||
|
||||
const selectedPropKeys = useMemo(() => Object.values(formState.values).map((value) => value.propKey), [formState])
|
||||
|
||||
function onPropKeySelect(id, selectedOptions) {
|
||||
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0]
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
propKey: newPropKey,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onPropValueSelect(id, selection) {
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
clauses: selection
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onFilterTypeSelect(id, newType) {
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
type: newType
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onPropAdd() {
|
||||
setFormState(prevState => {
|
||||
const id = prevState.entries[prevState.entries.length - 1] + 1
|
||||
return {
|
||||
entries: prevState.entries.concat([id]),
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
propKey: null,
|
||||
type: FILTER_OPERATIONS.is,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function onPropDelete(id) {
|
||||
setFormState(prevState => {
|
||||
const entries = prevState.entries.filter((entry) => entry != id)
|
||||
const values = {...prevState.values}
|
||||
delete values[id]
|
||||
|
||||
return { entries, values }
|
||||
})
|
||||
}
|
||||
|
||||
function isDisabled() {
|
||||
return formState.entries.some((id) => !formState.values[id].propKey || formState.values[id].clauses.length == 0)
|
||||
}
|
||||
|
||||
function shouldShowClear() {
|
||||
return !!query.filters['props']
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState.values)
|
||||
.map(([_, {propKey, type, clauses}]) => [propKey.value, toFilterQuery(type, clauses)])
|
||||
)
|
||||
selectFiltersAndCloseModal(JSON.stringify(formFilters))
|
||||
}
|
||||
|
||||
function selectFiltersAndCloseModal(filterString) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
if (filterString) {
|
||||
queryString.set('props', filterString)
|
||||
} else {
|
||||
queryString.delete('props')
|
||||
}
|
||||
|
||||
props.history.replace({ pathname: siteBasePath(props.site), search: queryString.toString() })
|
||||
}
|
||||
|
||||
const handleKeydown = (e) => {
|
||||
if (shouldIgnoreKeypress(e)) return
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('keydown', handleKeydown)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeydown)
|
||||
}
|
||||
}, [handleSubmit])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by Property</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" onSubmit={handleSubmit}>
|
||||
{formState.entries.map((id) => (
|
||||
<PropFilterRow
|
||||
key={id}
|
||||
id={id}
|
||||
site={props.site}
|
||||
query={query}
|
||||
{...formState.values[id]}
|
||||
showDelete={formState.entries.length > 1}
|
||||
selectedPropKeys={selectedPropKeys}
|
||||
onPropKeySelect={onPropKeySelect}
|
||||
onPropValueSelect={onPropValueSelect}
|
||||
onFilterTypeSelect={onFilterTypeSelect}
|
||||
onPropDelete={onPropDelete}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className="mt-6">
|
||||
<a className="underline text-indigo-500 text-sm cursor-pointer" onClick={onPropAdd}>
|
||||
+ Add another
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={isDisabled()}
|
||||
>
|
||||
Apply Filter
|
||||
</button>
|
||||
|
||||
{shouldShowClear() && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => { selectFiltersAndCloseModal(null) }}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(PropFilterModal)
|
||||
@ -1,86 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import Combobox from '../../components/combobox'
|
||||
import FilterTypeSelector from "../../components/filter-type-selector";
|
||||
import { FILTER_OPERATIONS } from "../../util/filters";
|
||||
import * as api from '../../api'
|
||||
import { apiPath } from '../../util/url'
|
||||
import { TrashIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
function PropFilterRow({
|
||||
id,
|
||||
query,
|
||||
site,
|
||||
propKey,
|
||||
type,
|
||||
clauses,
|
||||
showDelete,
|
||||
selectedPropKeys,
|
||||
onPropKeySelect,
|
||||
onPropValueSelect,
|
||||
onFilterTypeSelect,
|
||||
onPropDelete
|
||||
}) {
|
||||
function fetchPropKeyOptions() {
|
||||
return (input) => {
|
||||
return api.get(apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
function fetchPropValueOptions() {
|
||||
return (input) => {
|
||||
if (type === FILTER_OPERATIONS.contains) {
|
||||
return Promise.resolve([])
|
||||
}
|
||||
|
||||
|
||||
const key = propKey?.value
|
||||
const updatedQuery = { ...query, filters: { ...query.filters, props: { [key]: '!(none)' } } }
|
||||
return api.get(apiPath(site, "/suggestions/prop_value"), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-12 mt-6">
|
||||
<div className="col-span-4">
|
||||
<Combobox
|
||||
className="mr-2"
|
||||
fetchOptions={fetchPropKeyOptions()}
|
||||
singleOption
|
||||
autoFocus
|
||||
values={propKey ? [propKey] : []}
|
||||
onSelect={(value) => onPropKeySelect(id, value)}
|
||||
placeholder={'Property'}
|
||||
disabledOptions={selectedPropKeys}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-3 mx-2">
|
||||
<FilterTypeSelector
|
||||
isDisabled={!propKey}
|
||||
forFilter={'prop_value'}
|
||||
onSelect={(value) => onFilterTypeSelect(id, value)}
|
||||
selectedType={type}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-4">
|
||||
<Combobox
|
||||
isDisabled={!propKey}
|
||||
fetchOptions={fetchPropValueOptions()}
|
||||
values={clauses}
|
||||
onSelect={(value) => onPropValueSelect(id, value)}
|
||||
placeholder={'Value'}
|
||||
freeChoice={type == FILTER_OPERATIONS.contains}
|
||||
/>
|
||||
</div>
|
||||
{showDelete && (
|
||||
<div className="col-span-1 flex flex-col justify-center">
|
||||
<a className="ml-2 text-red-600 h-5 w-5 cursor-pointer" onClick={() => onPropDelete(id)}>
|
||||
<TrashIcon />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PropFilterRow
|
||||
@ -1,132 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Link } from 'react-router-dom'
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import Modal from './modal'
|
||||
import * as api from '../../api'
|
||||
import * as url from "../../util/url";
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import { parseQuery } from '../../query'
|
||||
import { specialTitleWhenGoalFilter } from "../behaviours/goal-conversions";
|
||||
import { escapeFilterValue } from "../../util/filters"
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
function PropsModal(props) {
|
||||
const site = props.site
|
||||
const query = parseQuery(props.location.search, site)
|
||||
const propKey = props.location.pathname.split('/').pop()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
|
||||
const [page, setPage] = useState(1)
|
||||
const [list, setList] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
function fetchData() {
|
||||
api.get(url.apiPath(site, `/custom-prop-values/${propKey}`), query, { limit: 100, page })
|
||||
.then((res) => {
|
||||
setLoading(false)
|
||||
setList(list.concat(res))
|
||||
setPage(page + 1)
|
||||
setMoreResultsAvailable(res.length >= 100)
|
||||
})
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
setLoading(true)
|
||||
fetchData()
|
||||
}
|
||||
|
||||
function renderLoadMore() {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={loadMore} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function filterSearchLink(listItem) {
|
||||
const searchParams = new URLSearchParams(window.location.search)
|
||||
searchParams.set('props', JSON.stringify({ [propKey]: escapeFilterValue(listItem.name) }))
|
||||
return searchParams.toString()
|
||||
}
|
||||
|
||||
function renderListItem(listItem, hasRevenue) {
|
||||
return (
|
||||
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
|
||||
<td className="p-2">
|
||||
<Link
|
||||
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
|
||||
className="hover:underline block truncate">
|
||||
{url.trimURL(listItem.name, 30)}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
|
||||
{query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>}
|
||||
{!query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.percentage}</td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return <div className="loading my-16 mx-auto"><div></div></div>
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const hasRevenue = BUILD_EXTRA && list.some((prop) => prop.total_revenue)
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">{specialTitleWhenGoalFilter(query, 'Custom Property Breakdown')}</h1>
|
||||
|
||||
<div className="my-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">{propKey}</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Visitors</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Events</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{query.filters.goal ? 'CR' : '%'}</th>
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((item) => renderListItem(item, hasRevenue))}
|
||||
</tbody>
|
||||
</table>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={site}>
|
||||
{renderBody()}
|
||||
{loading && renderLoading()}
|
||||
{!loading && moreResultsAvailable && renderLoadMore()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(PropsModal)
|
||||
@ -1,209 +0,0 @@
|
||||
import React from "react";
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import FilterTypeSelector from "../../components/filter-type-selector";
|
||||
import Combobox from '../../components/combobox'
|
||||
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_OPERATIONS } from '../../util/filters'
|
||||
import { parseQuery } from '../../query'
|
||||
import * as api from '../../api'
|
||||
import { apiPath, siteBasePath } from '../../util/url'
|
||||
import { shouldIgnoreKeypress } from '../../keybinding'
|
||||
import { isFreeChoiceFilter } from "../../util/filters";
|
||||
|
||||
function getFormState(filterGroup, query) {
|
||||
return FILTER_GROUPS[filterGroup].reduce((result, filter) => {
|
||||
const {type, clauses} = parseQueryFilter(query, filter)
|
||||
|
||||
return Object.assign(result, { [filter]: { type, clauses } })
|
||||
}, {})
|
||||
}
|
||||
|
||||
function withIndefiniteArticle(word) {
|
||||
if (word.startsWith('UTM')) {
|
||||
return `a ${word}`
|
||||
} if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) {
|
||||
return `an ${word}`
|
||||
}
|
||||
return `a ${word}`
|
||||
}
|
||||
|
||||
class RegularFilterModal extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const formState = getFormState(props.filterGroup, query)
|
||||
|
||||
this.handleKeydown = this.handleKeydown.bind(this)
|
||||
this.state = { query, formState }
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
document.addEventListener("keydown", this.handleKeydown)
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener("keydown", this.handleKeydown);
|
||||
}
|
||||
|
||||
handleKeydown(e) {
|
||||
if (shouldIgnoreKeypress(e)) return
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
this.handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
const { formState } = this.state;
|
||||
|
||||
const filters = Object.entries(formState).reduce((res, [filterKey, { type, clauses }]) => {
|
||||
if (clauses.length === 0) { return res }
|
||||
if (filterKey === 'country') { res.push({ filter: 'country_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'region') { res.push({ filter: 'region_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'city') { res.push({ filter: 'city_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
|
||||
res.push({ filter: filterKey, value: toFilterQuery(type, clauses) })
|
||||
return res
|
||||
}, [])
|
||||
|
||||
this.selectFiltersAndCloseModal(filters)
|
||||
}
|
||||
|
||||
onComboboxSelect(filterName) {
|
||||
return (selection) => {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { clauses: selection })
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
onFilterTypeSelect(filterName) {
|
||||
return (newType) => {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { type: newType })
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fetchOptions(filter) {
|
||||
return (input) => {
|
||||
const { query, formState } = this.state
|
||||
if (formState[filter].type === FILTER_OPERATIONS.contains) {return Promise.resolve([])}
|
||||
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState)
|
||||
.filter(([_filter, {_type, clauses}]) => clauses.length > 0)
|
||||
.map(([filter, {type, clauses}]) => [filter, toFilterQuery(type, clauses)])
|
||||
)
|
||||
const updatedQuery = this.queryForSuggestions(query, formFilters, filter)
|
||||
return api.get(apiPath(this.props.site, `/suggestions/${filter}`), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
queryForSuggestions(query, formFilters, filter) {
|
||||
return { ...query, filters: { ...query.filters, ...formFilters, [filter]: this.negate(formFilters[filter]) } }
|
||||
}
|
||||
|
||||
negate(filterVal) {
|
||||
if (!filterVal) {
|
||||
return filterVal
|
||||
} else if (filterVal.startsWith('!')) {
|
||||
return filterVal
|
||||
} else if (filterVal.startsWith('~')) {
|
||||
return null
|
||||
} else {
|
||||
return '!' + filterVal
|
||||
}
|
||||
}
|
||||
|
||||
selectedFilterType(filter) {
|
||||
return this.state.formState[filter].type
|
||||
}
|
||||
|
||||
isDisabled() {
|
||||
return Object.entries(this.state.formState).every(([_key, { clauses }]) => clauses.length === 0)
|
||||
}
|
||||
|
||||
selectFiltersAndCloseModal(filters) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
filters.forEach((entry) => {
|
||||
if (entry.value) {
|
||||
queryString.set(entry.filter, entry.value)
|
||||
} else {
|
||||
queryString.delete(entry.filter)
|
||||
}
|
||||
})
|
||||
|
||||
this.props.history.replace({ pathname: siteBasePath(this.props.site), search: queryString.toString() })
|
||||
}
|
||||
|
||||
renderFilterInputs() {
|
||||
const filtersInGroup = FILTER_GROUPS[this.props.filterGroup]
|
||||
|
||||
return filtersInGroup.map((filter) => {
|
||||
return (
|
||||
<div className="mt-4" key={filter}>
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">{formattedFilters[filter]}</div>
|
||||
<div className="grid grid-cols-11 mt-1">
|
||||
<div className="col-span-3 mr-2">
|
||||
<FilterTypeSelector forFilter={filter} onSelect={this.onFilterTypeSelect(filter)} selectedType={this.selectedFilterType(filter)}/>
|
||||
</div>
|
||||
<div className="col-span-8">
|
||||
<Combobox fetchOptions={this.fetchOptions(filter)} freeChoice={isFreeChoiceFilter(filter)} values={this.state.formState[filter].clauses} onSelect={this.onComboboxSelect(filter)} placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`}/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
const { filterGroup } = this.props
|
||||
const { query } = this.state
|
||||
const showClear = FILTER_GROUPS[filterGroup].some((filterName) => query.filters[filterName])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by {formatFilterGroup(filterGroup)}</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" onSubmit={this.handleSubmit.bind(this)}>
|
||||
{this.renderFilterInputs()}
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={this.isDisabled()}
|
||||
>
|
||||
Apply Filter
|
||||
</button>
|
||||
|
||||
{showClear && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => {
|
||||
const updatedFilters = FILTER_GROUPS[filterGroup].map((filterName) => ({ filter: filterName, value: null }))
|
||||
this.selectFiltersAndCloseModal(updatedFilters)
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter{FILTER_GROUPS[filterGroup].length > 1 ? 's' : ''}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(RegularFilterModal)
|
||||
@ -1,54 +0,0 @@
|
||||
import numberFormatter from "../../util/number-formatter"
|
||||
import React from "react"
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
export const VISITORS_METRIC = {
|
||||
name: 'visitors',
|
||||
label: 'Visitors',
|
||||
realtimeLabel: 'Current visitors',
|
||||
goalFilterLabel: 'Conversions',
|
||||
plot: true
|
||||
}
|
||||
export const PERCENTAGE_METRIC = { name: 'percentage', label: '%' }
|
||||
export const CR_METRIC = { name: 'conversion_rate', label: 'CR' }
|
||||
|
||||
export function maybeWithCR(metrics, query) {
|
||||
if (metrics.includes(PERCENTAGE_METRIC) && query.filters.goal) {
|
||||
return metrics.filter((m) => { return m !== PERCENTAGE_METRIC }).concat([CR_METRIC])
|
||||
}
|
||||
else if (query.filters.goal) {
|
||||
return metrics.concat(CR_METRIC)
|
||||
}
|
||||
else {
|
||||
return metrics
|
||||
}
|
||||
}
|
||||
|
||||
export function displayMetricValue(value, metric) {
|
||||
if (['total_revenue', 'average_revenue'].includes(metric.name)) {
|
||||
return <Money formatted={value} />
|
||||
} else if (metric === PERCENTAGE_METRIC) {
|
||||
return value
|
||||
} else if (metric === CR_METRIC) {
|
||||
return `${value}%`
|
||||
} else {
|
||||
return <span tooltip={value}>{numberFormatter(value)}</span>
|
||||
}
|
||||
}
|
||||
|
||||
export function metricLabelFor(metric, query) {
|
||||
if (metric.realtimeLabel && query.period === 'realtime') { return metric.realtimeLabel }
|
||||
if (metric.goalFilterLabel && query.filters.goal) { return metric.goalFilterLabel }
|
||||
return metric.label
|
||||
}
|
||||
@ -1,48 +1,179 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
import FlipMove from 'react-flip-move';
|
||||
|
||||
import FadeIn from '../../fade-in'
|
||||
import Bar from '../bar'
|
||||
import MoreLink from '../more-link'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics'
|
||||
import ListReport from '../reports/list'
|
||||
import LazyLoader from '../../components/lazy-loader'
|
||||
|
||||
function LinkOption(props) {
|
||||
if (props.disabled) {
|
||||
return <span {...props}>{props.children}</span>
|
||||
} else {
|
||||
props = Object.assign({}, props, { className: props.className + ' hover:underline' })
|
||||
return <Link {...props}>{props.children}</Link>
|
||||
}
|
||||
}
|
||||
|
||||
export default class Referrers extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.state = { loading: true }
|
||||
this.onVisible = this.onVisible.bind(this)
|
||||
this.fetchReferrers = this.fetchReferrers.bind(this)
|
||||
}
|
||||
|
||||
onVisible() {
|
||||
this.fetchReferrers()
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchReferrers)
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.props.query !== prevProps.query) {
|
||||
this.setState({ loading: true, referrers: null })
|
||||
this.fetchReferrers()
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener('tick', this.fetchReferrers)
|
||||
}
|
||||
|
||||
showConversionRate() {
|
||||
return !!this.props.query.filters.goal
|
||||
}
|
||||
|
||||
export default function Referrers({site, query}) {
|
||||
function fetchReferrers() {
|
||||
return api.get(url.apiPath(site, `/referrers/${encodeURIComponent(query.filters.source)}`), query, {limit: 9})
|
||||
fetchReferrers() {
|
||||
if (this.props.query.filters.source) {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers/${encodeURIComponent(this.props.query.filters.source)}`, this.props.query)
|
||||
.then((res) => res.search_terms || res.referrers)
|
||||
.then((referrers) => this.setState({ loading: false, referrers: referrers }))
|
||||
} else if (this.props.query.filters.goal) {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/goal/referrers`, this.props.query)
|
||||
.then((res) => this.setState({ loading: false, referrers: res }))
|
||||
} else {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers`, this.props.query)
|
||||
.then((res) => this.setState({ loading: false, referrers: res }))
|
||||
}
|
||||
}
|
||||
|
||||
function externalLinkDest(referrer) {
|
||||
if (referrer.name === 'Direct / None') { return null }
|
||||
return `https://${referrer.name}`
|
||||
renderExternalLink(referrer) {
|
||||
if (this.props.query.filters.source && this.props.query.filters.source !== 'Google' && referrer.name !== 'Direct / None') {
|
||||
return (
|
||||
<a target="_blank" href={'//' + referrer.name} rel="noreferrer" className="hidden group-hover:block">
|
||||
<svg className="inline w-4 h-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function getFilterFor(referrer) {
|
||||
if (referrer.name === 'Direct / None') { return null }
|
||||
return { referrer: referrer.name }
|
||||
renderReferrer(referrer) {
|
||||
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
query.set('referrer', referrer.name)
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between my-1 text-sm" key={referrer.name}>
|
||||
<Bar
|
||||
count={referrer.visitors}
|
||||
all={this.state.referrers}
|
||||
bg="bg-blue-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={maxWidthDeduction}
|
||||
>
|
||||
<span className="flex px-2 py-1.5 z-9 relative break-all group">
|
||||
<LinkOption
|
||||
className="block md:truncate dark:text-gray-300"
|
||||
to={{ search: query.toString() }}
|
||||
disabled={referrer.name === 'Direct / None'}
|
||||
>
|
||||
<img
|
||||
src={`/favicon/sources/${encodeURIComponent(referrer.name)}`}
|
||||
referrerPolicy="no-referrer"
|
||||
className="inline w-4 h-4 mr-2 -mt-px align-middle"
|
||||
/>
|
||||
{referrer.name}
|
||||
</LinkOption>
|
||||
{this.renderExternalLink(referrer)}
|
||||
</span>
|
||||
</Bar>
|
||||
<span className="font-medium dark:text-gray-200">{numberFormatter(referrer.visitors)}</span>
|
||||
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
label() {
|
||||
if (this.props.query.period === 'realtime') {
|
||||
return 'Current visitors'
|
||||
}
|
||||
|
||||
if (this.showConversionRate()) {
|
||||
return 'Conversions'
|
||||
}
|
||||
|
||||
return 'Visitors'
|
||||
}
|
||||
|
||||
function renderIcon(listItem) {
|
||||
renderList() {
|
||||
if (this.state.referrers.length > 0) {
|
||||
return (
|
||||
<div className="flex flex-col flex-grow">
|
||||
<div
|
||||
className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500"
|
||||
>
|
||||
<span>Referrer</span>
|
||||
|
||||
<div className="text-right">
|
||||
<span className="inline-block w-20">{this.label()}</span>
|
||||
{this.showConversionRate() && <span className="inline-block w-20">CR</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FlipMove className="flex-grow">
|
||||
{this.state.referrers.map(this.renderReferrer.bind(this))}
|
||||
</FlipMove>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<img
|
||||
src={`/favicon/sources/${encodeURIComponent(listItem.name)}`}
|
||||
referrerPolicy="no-referrer"
|
||||
className="inline w-4 h-4 mr-2 -mt-px align-middle"
|
||||
/>
|
||||
<div
|
||||
className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400"
|
||||
>
|
||||
No data yet
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-grow">
|
||||
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
|
||||
<ListReport
|
||||
fetchData={fetchReferrers}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel="Referrer"
|
||||
metrics={maybeWithCR([VISITORS_METRIC], query)}
|
||||
detailsLink={url.sitePath(site, `/referrers/${encodeURIComponent(query.filters.source)}`)}
|
||||
query={query}
|
||||
externalLinkDest={externalLinkDest}
|
||||
renderIcon={renderIcon}
|
||||
color="bg-blue-50"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
renderContent() {
|
||||
if (this.state.referrers) {
|
||||
return (
|
||||
<React.Fragment>
|
||||
{this.renderList()}
|
||||
<MoreLink site={this.props.site} list={this.state.referrers} endpoint={`referrers/${this.props.query.filters.source}`} />
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col dark:bg-gray-825 mt-6 w-full"
|
||||
>
|
||||
<LazyLoader onVisible={this.onVisible} className="flex flex-col flex-grow">
|
||||
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
|
||||
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
|
||||
<FadeIn show={!this.state.loading}>
|
||||
{this.renderContent()}
|
||||
</FadeIn>
|
||||
</LazyLoader>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,162 +0,0 @@
|
||||
const flags = JSON.parse(document.getElementById('stats-react-container').dataset.flags)
|
||||
|
||||
export const FILTER_GROUPS = {
|
||||
'page': ['page', 'entry_page', 'exit_page'],
|
||||
'source': ['source', 'referrer'],
|
||||
'location': ['country', 'region', 'city'],
|
||||
'screen': ['screen'],
|
||||
'browser': ['browser', 'browser_version'],
|
||||
'os': ['os', 'os_version'],
|
||||
'utm': ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'],
|
||||
'goal': ['goal'],
|
||||
'props': ['prop_key', 'prop_value'],
|
||||
...(flags.hostname_filter ? { 'hostname': ['hostname'] } : {})
|
||||
|
||||
}
|
||||
|
||||
export const NO_CONTAINS_OPERATOR = new Set(['goal', 'screen'].concat(FILTER_GROUPS['location']))
|
||||
|
||||
export const FILTER_OPERATIONS = {
|
||||
isNot: 'is not',
|
||||
contains: 'contains',
|
||||
is: 'is'
|
||||
};
|
||||
|
||||
export const OPERATION_PREFIX = {
|
||||
[FILTER_OPERATIONS.isNot]: '!',
|
||||
[FILTER_OPERATIONS.contains]: '~',
|
||||
[FILTER_OPERATIONS.is]: ''
|
||||
};
|
||||
|
||||
export function supportsIsNot(filterName) {
|
||||
return !['goal', 'prop_key'].includes(filterName)
|
||||
}
|
||||
|
||||
export function isFreeChoiceFilter(filterName) {
|
||||
return !NO_CONTAINS_OPERATOR.has(filterName)
|
||||
}
|
||||
|
||||
// As of March 2023, Safari does not support negative lookbehind regexes. In case it throws an error, falls back to plain | matching. This means
|
||||
// escaping pipe characters in filters does not currently work in Safari
|
||||
let NON_ESCAPED_PIPE_REGEX;
|
||||
try {
|
||||
NON_ESCAPED_PIPE_REGEX = new RegExp("(?<!\\\\)\\|", "g")
|
||||
} catch (_e) {
|
||||
NON_ESCAPED_PIPE_REGEX = '|'
|
||||
}
|
||||
|
||||
const ESCAPED_PIPE = '\\|'
|
||||
|
||||
export function escapeFilterValue(value) {
|
||||
return value.replaceAll(NON_ESCAPED_PIPE_REGEX, ESCAPED_PIPE)
|
||||
}
|
||||
|
||||
export function toFilterQuery(type, clauses) {
|
||||
const prefix = OPERATION_PREFIX[type];
|
||||
const result = clauses.map(clause => escapeFilterValue(clause.value.trim())).join('|')
|
||||
return prefix + result;
|
||||
}
|
||||
|
||||
export function parsePrefix(rawValue) {
|
||||
const type = Object.keys(OPERATION_PREFIX)
|
||||
.find(type => OPERATION_PREFIX[type] === rawValue[0]) || FILTER_OPERATIONS.is;
|
||||
|
||||
const value = type === FILTER_OPERATIONS.is ? rawValue : rawValue.substring(1)
|
||||
|
||||
const values = value
|
||||
.split(NON_ESCAPED_PIPE_REGEX)
|
||||
.filter((clause) => !!clause)
|
||||
.map((val) => val.replaceAll(ESCAPED_PIPE, '|'))
|
||||
|
||||
return { type, values }
|
||||
}
|
||||
|
||||
export function parseQueryPropsFilter(query) {
|
||||
return Object.entries(query.filters['props']).map(([key, propVal]) => {
|
||||
const { type, values } = parsePrefix(propVal)
|
||||
const clauses = values.map(val => { return { value: val, label: val } })
|
||||
return { propKey: { label: key, value: key }, type, clauses }
|
||||
})
|
||||
}
|
||||
|
||||
export function parseQueryFilter(query, filter) {
|
||||
const { type, values } = parsePrefix(query.filters[filter] || '')
|
||||
|
||||
let labels = values
|
||||
|
||||
if (filter === 'country' && values.length > 0) {
|
||||
const rawLabel = (new URLSearchParams(window.location.search)).get('country_labels') || ''
|
||||
labels = rawLabel.split('|').filter(label => !!label)
|
||||
}
|
||||
|
||||
if (filter === 'region' && values.length > 0) {
|
||||
const rawLabel = (new URLSearchParams(window.location.search)).get('region_labels') || ''
|
||||
labels = rawLabel.split('|').filter(label => !!label)
|
||||
}
|
||||
|
||||
if (filter === 'city' && values.length > 0) {
|
||||
const rawLabel = (new URLSearchParams(window.location.search)).get('city_labels') || ''
|
||||
labels = rawLabel.split('|').filter(label => !!label)
|
||||
}
|
||||
|
||||
const clauses = values.map((value, index) => { return { value, label: labels[index] } })
|
||||
|
||||
return { type, clauses }
|
||||
}
|
||||
|
||||
export function isFilteringOnFixedValue(query, filter) {
|
||||
const { type, clauses } = parseQueryFilter(query, filter)
|
||||
return type == FILTER_OPERATIONS.is && clauses.length == 1
|
||||
}
|
||||
|
||||
export function formatFilterGroup(filterGroup) {
|
||||
if (filterGroup === 'utm') {
|
||||
return 'UTM tags'
|
||||
} else if (filterGroup === 'location') {
|
||||
return 'Location'
|
||||
} else if (filterGroup === 'props') {
|
||||
return 'Property'
|
||||
} else {
|
||||
return formattedFilters[filterGroup]
|
||||
}
|
||||
}
|
||||
|
||||
export function filterGroupForFilter(filter) {
|
||||
const map = Object.entries(FILTER_GROUPS).reduce((filterToGroupMap, [group, filtersInGroup]) => {
|
||||
const filtersToAdd = {}
|
||||
filtersInGroup.forEach((filterInGroup) => {
|
||||
filtersToAdd[filterInGroup] = group
|
||||
})
|
||||
|
||||
return { ...filterToGroupMap, ...filtersToAdd }
|
||||
}, {})
|
||||
|
||||
|
||||
return map[filter] || filter
|
||||
}
|
||||
|
||||
export const formattedFilters = {
|
||||
'goal': 'Goal',
|
||||
'props': 'Property',
|
||||
'prop_key': 'Property',
|
||||
'prop_value': 'Value',
|
||||
'source': 'Source',
|
||||
'utm_medium': 'UTM Medium',
|
||||
'utm_source': 'UTM Source',
|
||||
'utm_campaign': 'UTM Campaign',
|
||||
'utm_content': 'UTM Content',
|
||||
'utm_term': 'UTM Term',
|
||||
'referrer': 'Referrer URL',
|
||||
'screen': 'Screen size',
|
||||
'browser': 'Browser',
|
||||
'browser_version': 'Browser Version',
|
||||
'os': 'Operating System',
|
||||
'os_version': 'Operating System Version',
|
||||
'country': 'Country',
|
||||
'region': 'Region',
|
||||
'city': 'City',
|
||||
'page': 'Page',
|
||||
'hostname': 'Hostname',
|
||||
'entry_page': 'Entry Page',
|
||||
'exit_page': 'Exit Page',
|
||||
}
|
||||
@ -1,83 +0,0 @@
|
||||
// Courtesy of Benjamin von Polheim:
|
||||
// https://blog.devgenius.io/build-a-performat-autocomplete-using-phoenix-liveview-and-alpine-js-8bcbbed17ba7
|
||||
|
||||
export default (id) => ({
|
||||
isOpen: false,
|
||||
id: id,
|
||||
focus: null,
|
||||
selectionInProgress: false,
|
||||
setFocus(f) {
|
||||
this.focus = f;
|
||||
},
|
||||
initFocus() {
|
||||
if (this.focus === null) {
|
||||
this.setFocus(this.leastFocusableIndex())
|
||||
}
|
||||
},
|
||||
trackSubmitValueChange() {
|
||||
this.selectionInProgress = false;
|
||||
},
|
||||
open() {
|
||||
if (!this.isOpen) {
|
||||
this.initFocus()
|
||||
this.isOpen = true
|
||||
}
|
||||
},
|
||||
suggestionsCount() {
|
||||
return this.$refs.suggestions?.querySelectorAll('li').length
|
||||
},
|
||||
hasCreatableOption() {
|
||||
return this.$refs.suggestions?.querySelector('li').classList.contains("creatable")
|
||||
},
|
||||
leastFocusableIndex() {
|
||||
if (this.suggestionsCount() === 0) {
|
||||
return 0
|
||||
}
|
||||
return this.hasCreatableOption() ? 0 : 1
|
||||
},
|
||||
maxFocusableIndex() {
|
||||
return this.hasCreatableOption() ? this.suggestionsCount() - 1 : this.suggestionsCount()
|
||||
},
|
||||
nextFocusableIndex() {
|
||||
const currentFocus = this.focus
|
||||
return currentFocus + 1 > this.maxFocusableIndex() ? this.leastFocusableIndex() : currentFocus + 1
|
||||
},
|
||||
prevFocusableIndex() {
|
||||
const currentFocus = this.focus
|
||||
return currentFocus - 1 >= this.leastFocusableIndex() ? currentFocus - 1 : this.maxFocusableIndex()
|
||||
},
|
||||
close(e) {
|
||||
// Pressing Escape should not propagate to window,
|
||||
// so we'll only close the suggestions pop-up
|
||||
if (this.isOpen && e.key === "Escape") {
|
||||
e.stopPropagation()
|
||||
}
|
||||
this.isOpen = false
|
||||
},
|
||||
select() {
|
||||
this.$refs[`dropdown-${this.id}-option-${this.focus}`]?.click()
|
||||
this.close()
|
||||
document.getElementById(this.id).blur()
|
||||
},
|
||||
scrollTo(idx) {
|
||||
this.$refs[`dropdown-${this.id}-option-${idx}`]?.scrollIntoView(
|
||||
{ block: 'nearest', behavior: 'smooth', inline: 'start' }
|
||||
)
|
||||
},
|
||||
focusNext() {
|
||||
const nextIndex = this.nextFocusableIndex()
|
||||
|
||||
this.open()
|
||||
|
||||
this.setFocus(nextIndex)
|
||||
this.scrollTo(nextIndex)
|
||||
},
|
||||
focusPrev() {
|
||||
const prevIndex = this.prevFocusableIndex()
|
||||
|
||||
this.open()
|
||||
|
||||
this.setFocus(prevIndex)
|
||||
this.scrollTo(prevIndex)
|
||||
}
|
||||
})
|
||||
@ -1,20 +0,0 @@
|
||||
// From https://alpinejs.dev/component/dropdown
|
||||
|
||||
export default () => ({
|
||||
open: false,
|
||||
toggle() {
|
||||
if (this.open) {
|
||||
return this.close()
|
||||
}
|
||||
|
||||
this.$refs.button.focus()
|
||||
this.open = true
|
||||
},
|
||||
|
||||
close(focusAfter) {
|
||||
if (! this.open) return
|
||||
|
||||
this.open = false
|
||||
focusAfter && focusAfter.focus()
|
||||
},
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue