Compare commits

..

1 Commits

Author SHA1 Message Date
Uku Taht d72b569c8f Upgrade Chart.js dependency 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"]
]

@ -10,7 +10,7 @@ body:
[Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact our customer support](https://plausible.io/contact).
Have a feature request? Please check our [feedback board](https://feedback.plausible.io).
Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new).
Have an issue with your self-hosted install? Self-hosted is community supported and you can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support).

@ -4,8 +4,8 @@ contact_links:
url: https://github.com/plausible/analytics/discussions/categories/self-hosted-support
about: Please use the self-hosted community forum for any self-hosted issues and questions
- name: 💡 Feature requests and ideas
url: https://feedback.plausible.io
about: Please vote for and post new feature ideas on our feedback board
url: https://github.com/plausible/analytics/discussions/categories/feature-requests
about: Please vote for and post new feature ideas in the community forum
- name: 📖 Documentation
url: https://plausible.io/docs
about: A great place to find instructions and answers on how to get the most out of your Plausible experience

@ -20,7 +20,3 @@ updates:
schedule:
interval: "daily"
open-pull-requests-limit: 1
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"

@ -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>"}'

@ -5,21 +5,18 @@ on:
branches: [master, stable]
tags: ['r*']
pull_request:
branches: [master]
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
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v5.0.0
uses: docker/metadata-action@v4
with:
images: plausible/analytics-private
tags: |
@ -28,17 +25,17 @@ jobs:
type=ref,event=tag
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v3
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v5
uses: docker/build-push-action@v2
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
@ -46,7 +43,6 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=prod
BUILD_METADATA=${{ steps.meta.outputs.json }}
- name: Image digest

@ -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>"}'

@ -4,40 +4,36 @@ on:
push:
tags: ['v*']
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
runs-on: buildjet-16vcpu-ubuntu-2204
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v4
with:
images: plausible/community-edition
images: plausible/analytics
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
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v3
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v5
uses: docker/build-push-action@v2
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
@ -46,9 +42,7 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
MIX_ENV=small
BUILD_METADATA=${{ steps.meta.outputs.json }}
ERL_FLAGS=+JMsingle true
- name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }}

@ -1,42 +1,23 @@
name: Elixir CI
on:
pull_request:
push:
branches: [master, stable]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
CACHE_VERSION: v7
PERSISTENT_CACHE_DIR: cached
pull_request:
branches: [master, stable]
jobs:
build:
name: "Build and test (${{ matrix.mix_env }}, ${{ matrix.postgres_image }}${{ matrix.test_experimental_reduced_joins == '1' && ', experimental_reduced_joins' || '' }})"
runs-on: ubuntu-latest
name: Build and test
runs-on: buildjet-4vcpu-ubuntu-2004
strategy:
matrix:
mix_env: ['test', 'small_test']
postgres_image: ['postgres:16']
test_experimental_reduced_joins: ['0']
postgres_version: [12, 13, 14]
include:
- mix_env: 'test'
postgres_image: 'postgres:15'
test_experimental_reduced_joins: '0'
- mix_env: 'test'
postgres_image: 'postgres:16'
test_experimental_reduced_joins: '1'
env:
MIX_ENV: ${{ matrix.mix_env }}
TEST_EXPERIMENTAL_REDUCED_JOINS: ${{ matrix.test_experimental_reduced_joins }}
services:
postgres:
image: ${{ matrix.postgres_image }}
image: postgres:${{ matrix.postgres_version }}
ports:
- 5432:5432
env:
@ -46,8 +27,9 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
clickhouse:
image: clickhouse/clickhouse-server:23.3.7.5-alpine
image: clickhouse/clickhouse-server:22.8.13.20-alpine
ports:
- 8123:8123
env:
@ -56,91 +38,41 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: marocchino/tool-versions-action@v1
id: versions
- uses: erlef/setup-beam@v1
with:
elixir-version: ${{ steps.versions.outputs.elixir }}
otp-version: ${{ steps.versions.outputs.erlang }}
- uses: actions/cache@v4
with:
path: |
deps
_build
tracker/node_modules
priv/tracker/js
${{ env.PERSISTENT_CACHE_DIR }}
key: ${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-${{ hashFiles('**/mix.lock') }}
restore-keys: |
${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-
${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-refs/heads/master-
- name: Check for changes in tracker/**
uses: dorny/paths-filter@v3
id: changes
with:
filters: |
tracker:
- 'tracker/**'
- name: Check if priv/tracker/js/plausible.js exists
run: |
if [ -f priv/tracker/js/plausible.js ]; then
echo "HAS_BUILT_TRACKER=true" >> $GITHUB_ENV
else
echo "HAS_BUILT_TRACKER=false" >> $GITHUB_ENV
fi
- run: npm install --prefix ./tracker
if: steps.changes.outputs.tracker == 'true' || env.HAS_BUILT_TRACKER == 'false'
- run: npm run deploy --prefix ./tracker
if: steps.changes.outputs.tracker == 'true' || env.HAS_BUILT_TRACKER == 'false'
- run: mix deps.get --only $MIX_ENV
- run: mix compile --warnings-as-errors --all-warnings
- run: mix do ecto.create, ecto.migrate
- run: mix run -e "Tzdata.ReleaseUpdater.poll_for_update"
- run: mix test --include slow --include minio --max-failures 1 --warnings-as-errors
if: env.MIX_ENV == 'test'
- run: mix test --include slow --max-failures 1 --warnings-as-errors
if: env.MIX_ENV == 'small_test'
static:
name: Static checks (format, credo, dialyzer)
env:
MIX_ENV: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: marocchino/tool-versions-action@v1
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
id: versions
- uses: erlef/setup-beam@v1
- name: Set up Elixir
uses: erlef/setup-beam@v1
with:
elixir-version: ${{ steps.versions.outputs.elixir }}
otp-version: ${{ steps.versions.outputs.erlang }}
- uses: actions/cache@v4
elixir-version: ${{steps.versions.outputs.elixir}}
otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore dependencies cache
uses: actions/cache@v2
with:
path: |
deps
_build
priv/plts
key: static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-${{ hashFiles('**/mix.lock') }}
restore-keys: |
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-refs/heads/master-
- run: mix deps.get
- run: mix compile --warnings-as-errors --all-warnings
- run: mix format --check-formatted
- run: mix deps.unlock --check-unused
- run: mix credo diff --from-git-merge-base origin/master
- run: mix dialyzer
key: ${{ runner.os }}-mix-v2-${{ hashFiles('**/mix.lock') }}
restore-keys: ${{ runner.os }}-mix-v2-
- name: Install dependencies
run: mix deps.get && npm install --prefix ./tracker
- name: Check Formatting
run: mix format --check-formatted
- name: Check Compile Warnings
run: mix compile --warnings-as-errors --all-warnings
- name: Generate tracker files
run: npm run deploy --prefix ./tracker
- name: Check Credo Warnings
run: mix credo diff --from-git-merge-base origin/master
- name: Run tests
run: mix test --include slow --max-failures 1 --warnings-as-errors
- name: Check Dialyzer
run: mix dialyzer
env:
MIX_ENV: test

@ -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

@ -4,10 +4,7 @@ on:
push:
branches: [master, stable]
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
branches: [master, stable]
jobs:
build:
@ -15,16 +12,22 @@ jobs:
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
id: versions
- name: Set up Node
uses: actions/setup-node@v4
uses: actions/setup-node@v2
with:
node-version: ${{steps.versions.outputs.nodejs}}
- run: npm install --prefix ./assets
- run: npm install --prefix ./tracker
- run: npm run lint --prefix ./assets
- run: npm run check-format --prefix ./assets
- run: npm run deploy --prefix ./assets
- run: npm run deploy --prefix ./tracker
- name: Run BundleMon
run: npm run bundlemon --prefix ./assets
env:
BUNDLEMON_PROJECT_ID: "619e0b6ad4a54a00089861ac"
CI_COMMIT_SHA: ${{github.event.pull_request.head.sha || github.sha}} # important!

@ -22,7 +22,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
@ -35,7 +35,7 @@ jobs:
otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore Elixir dependencies cache
uses: actions/cache@v4
uses: actions/cache@v2
with:
path: |
deps

@ -4,16 +4,14 @@ on:
push:
branches:
- master
paths:
- 'test/e2e/**.tf'
paths:
- 'test/e2e/**.tf'
pull_request:
branches:
- master
paths:
- 'test/e2e/**.tf'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
jobs:
terraform:
concurrency: terraform_checkly
@ -27,10 +25,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
uses: hashicorp/setup-terraform@v2
with:
cli_config_credentials_token: ${{ secrets.TF_CLOUD_CHECKLY_API_TOKEN }}
@ -41,7 +39,7 @@ jobs:
- name: Terraform Init
id: init
run: terraform init
- name: Terraform Validate
id: validate
run: terraform validate -no-color
@ -52,7 +50,7 @@ jobs:
run: terraform plan -no-color
continue-on-error: true
- uses: actions/github-script@v7
- uses: actions/github-script@v6
if: github.event_name == 'pull_request'
env:
PLAN: "terraform\n${{ steps.plan.outputs.stdout }}"

@ -6,23 +6,28 @@ on:
paths:
- 'tracker/**'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
timeout-minutes: 15
build:
name: Build and test
runs-on: buildjet-4vcpu-ubuntu-2004
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v2
- name: Read .tool-versions
uses: marocchino/tool-versions-action@v1
id: versions
- name: Set up Node
uses: actions/setup-node@v2
with:
node-version: ${{steps.versions.outputs.nodejs}}
- name: 'BrowserStack Env Setup'
uses: 'browserstack/github-actions/setup-env@master'
with:
node-version: 16
- name: Install dependencies
run: npm --prefix ./tracker ci
- name: Install Playwright Browsers
username: ${{ secrets.BROWSERSTACK_USERNAME }}
access-key: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
build-name: 'BUILD_INFO'
- run: npm install --prefix ./tracker
- run: npm run deploy --prefix ./tracker
- name: "Install Playwright dependencies"
working-directory: ./tracker
run: npx playwright install --with-deps
- name: Run Playwright tests
run: npm --prefix ./tracker test
run: npx playwright install-deps
- run: npm --prefix ./tracker test

11
.gitignore vendored

@ -19,9 +19,6 @@ erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Temporary files, for example, from tests.
/tmp/
# Ignore package tarball (built via "mix hex.build").
plausible-*.tar
@ -38,8 +35,7 @@ npm-debug.log
# Since we are building assets from assets/,
# we ignore priv/static. You may want to comment
# this depending on your deployment strategy.
/priv/static/css
/priv/static/js
/priv/static/
/priv/version.json
# Files matching config/*.secret.exs pattern contain sensitive
@ -58,7 +54,6 @@ plausible-report.xml
*.iml
*.log
*.code-workspace
.vscode
# Dializer
/priv/plts/*.plt
@ -72,7 +67,3 @@ plausible-report.xml
# Auto-generated tracker files
/priv/tracker/js/*.js
# Docker volumes
.clickhouse_db_vol*
plausible_db*

@ -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

@ -1,106 +1,13 @@
# Changelog
All notable changes to this project will be documented in this file.
### Added
- Pages Block List in Site Settings
- Add `conversion_rate` to Stats API Timeseries and on the main graph
- Add `total_conversions` and `conversion_rate` to `visitors.csv` in a goal-filtered CSV export
- Ability to display total conversions (with a goal filter) on the main graph
- Add `conversion_rate` to Stats API Timeseries and on the main graph
- Add `time_on_page` metric into the Stats API
- County Block List in Site Settings
- Query the `views_per_visit` metric based on imported data as well if possible
- Group `operating_system_versions` by `operating_system` in Stats API breakdown
- Add `operating_system_versions.csv` into the CSV export
- Display `Total visitors`, `Conversions`, and `CR` in the "Details" views of Countries, Regions and Cities (when filtering by a goal)
- Add `conversion_rate` to Regions and Cities reports (when filtering by a goal)
- Add the `conversion_rate` metric to Stats API Breakdown and Aggregate endpoints
- IP Block List in Site Settings
- Allow filtering with `contains`/`matches` operator for Sources, Browsers and Operating Systems.
- Allow filtering by multiple custom properties
- Wildcard and member filtering on the Stats API `event:goal` property
- Allow filtering with `contains`/`matches` operator for custom properties
- Add `referrers.csv` to CSV export
- Add a new Properties section in the dashboard to break down by custom properties
- Add `custom_props.csv` to CSV export (almost the same as the old `prop_breakdown.csv`, but has different column headers, and includes props for pageviews too, not only custom events)
- Add `referrers.csv` to CSV export
- Improve password validation in registration and password reset forms
- Adds Gravatar profile image to navbar
- Enforce email reverification on update
- Add Plugins API Tokens provisioning UI
- Add searching sites by domain in /sites view
- Add last 24h plots to /sites view
- Add site pinning to /sites view
- Add support for JSON logger, via LOG_FORMAT=json environment variable
- Add support for 2FA authentication
- Add 'browser_versions.csv' to CSV export
- Add `CLICKHOUSE_MAX_BUFFER_SIZE_BYTES` env var which defaults to `100000` (100KB)
- Add alternative SMTP adapter plausible/analytics#3654
- Add `EXTRA_CONFIG_PATH` env var to specify extra Elixir config plausible/analytics#3906
- Add restrictive `robots.txt` for self-hosted plausible/analytics#3905
### Removed
- Removed the nested custom event property breakdown UI when filtering by a goal in Goal Conversions
- Removed the `prop_names` returned in the Stats API `event:goal` breakdown response
- Removed the `prop-breakdown.csv` file from CSV export
- Deprecated `CLICKHOUSE_MAX_BUFFER_SIZE`
- Removed `/app/init-admin.sh` that was deprecated in v2.0.0 plausible/analytics#3903
- Remove `DISABLE_AUTH` deprecation warning plausible/analytics#3904
### Changed
- A visits `entry_page` and `exit_page` is only set and updated for pageviews, not custom events
- Limit the number of Goal Conversions shown on the dashboard and render a "Details" link when there are more entries to show
- Show Outbound Links / File Downloads / 404 Pages / Cloaked Links instead of Goal Conversions when filtering by the corresponding goal
- Require custom properties to be explicitly added from Site Settings > Custom Properties in order for them to show up on the dashboard
- GA/SC sections moved to new settings: Integrations
- Replace `CLICKHOUSE_MAX_BUFFER_SIZE` with `CLICKHOUSE_MAX_BUFFER_SIZE_BYTES`
- Validate metric isn't queried multiple times
### Fixed
- Creating many sites no longer leads to cookie overflow
- Ignore sessions without pageviews for `entry_page` and `exit_page` breakdowns
- Using `VersionedCollapsingMergeTree` to store visit data to avoid rare race conditions that led to wrong visit data being shown
- Fix `conversion_rate` metric in a `browser_versions` breakdown
- Calculate `conversion_rate` percentage change in the same way like `bounce_rate` (subtraction instead of division)
- Calculate `bounce_rate` percentage change in the Stats API in the same way as it's done in the dashboard
- Stop returning custom events in goal breakdown with a pageview goal filter and vice versa
- Only return `(none)` values in custom property breakdown for the first page (pagination) of results
- Fixed weekly/monthly e-mail report [rendering issues](https://github.com/plausible/analytics/issues/284)
- Fix [broken interval selection](https://github.com/plausible/analytics/issues/2982) in the all time view plausible/analytics#3110
- Fixed [IPv6 problems](https://github.com/plausible/analytics/issues/3173) in data migration plausible/analytics#3179
- Fixed [long URLs display](https://github.com/plausible/analytics/issues/3158) in Outbound Link breakdown view
- Fixed [Sentry reports](https://github.com/plausible/analytics/discussions/3166) for ingestion requests plausible/analytics#3182
- Fix breakdown pagination bug in the dashboard details view when filtering by goals
- Update bot detection (matomo 6.1.4, ua_inspector 3.4.0)
- Improved the Goal Settings page (search, autcompletion etc.)
- Log mailer errors plausible/analytics#3336
- Allow custom event timeseries in stats API plausible/analytics#3505
- Fixes for sites with UTF characters in domain plausible/analytics#3560
- Fix crash when using special characters in filter plausible/analytics#3634
- Fix automatic scrolling to the bottom on the dashboard if previously selected properties tab plausible/analytics#3872
- Allow running the container with arbitrary UID plausible/analytics#2986
- Fix `width=manual` in embedded dashboards plausible/analytics#3910
- Fix URL escaping when pipes are used in UTM tags plausible/analytics#3930
## v2.0.0 - 2023-07-12
## Unreleased
### Added
- Call to action for tracking Goal Conversions and an option to hide the section from the dashboard
- Add support for `with_imported=true` in Stats API aggregate endpoint
- Ability to use '--' instead of '=' sign in the `tagged-events` classnames
- 'Last updated X seconds ago' info to 'current visitors' tooltips
- Add support for more Bamboo adapters, i.e. `Bamboo.MailgunAdapter`, `Bamboo.MandrillAdapter`, `Bamboo.SendGridAdapter` plausible/analytics#2649
- Ability to change domain for existing site (requires numeric IDs data migration, instructions will be provided separately) UI + API (`PUT /api/v1/sites`)
- Add `LOG_FAILED_LOGIN_ATTEMPTS` environment variable to enable failed login attempts logs plausible/analytics#2936
- Add `MAILER_NAME` environment variable support plausible/analytics#2937
- Add `MAILGUN_BASE_URI` support for `Bamboo.MailgunAdapter` plausible/analytics#2935
- Add a landing page for self-hosters plausible/analytics#2989
- Allow optional IPv6 for clickhouse repo plausible/analytics#2970
### Fixed
- Fix tracker bug - call callback function even when event is ignored
- Make goal-filtered CSV export return only unique_conversions timeseries in the 'visitors.csv' file
- Stop treating page filter as an entry page filter
- City report showing N/A instead of city names with imported data plausible/analytics#2675
- Empty values for Screen Size, OS and Browser are uniformly replaced with "(not set)"
- Fix [more pageviews with session prop filter than with no filters](https://github.com/plausible/analytics/issues/1666)
@ -112,25 +19,14 @@ All notable changes to this project will be documented in this file.
- Add error message in case a transfer to an invited (but not joined) user is requested plausible/analytics#2651
- Fix bug with [showing property breakdown with a prop filter](https://github.com/plausible/analytics/issues/1789)
- Fix bug when combining goal and prop filters plausible/analytics#2654
- Fix broken favicons when domain includes a slash
- Fix bug when using multiple [wildcard goal filters](https://github.com/plausible/analytics/pull/3015)
- Fix a bug where realtime would fail with imported data
- Fix a bug where the country name was not shown when [filtering through the map](https://github.com/plausible/analytics/issues/3086)
### Changed
- Treat page filter as entry page filter for `bounce_rate`
- Reject events with long URIs and data URIs plausible/analytics#2536
- Always show direct traffic in sources reports plausible/analytics#2531
- Stop recording XX and T1 country codes plausible/analytics#2556
- Device type is now determined from the User-Agent instead of window.innerWidth plausible/analytics#2711
- Add padding by default to embedded dashboards so that shadows are not cut off plausible/analytics#2744
- Update the User Agents database (https://github.com/matomo-org/device-detector/releases/tag/6.1.1)
- Disable registration in self-hosted setups by default plausible/analytics#3014
### Removed
- Remove Firewall plug and `IP_BLOCKLIST` environment variable
- Remove the ability to collapse the main graph plausible/analytics#2627
- Remove `custom_dimension_filter` feature flag plausible/analytics#2996
## v1.5.1 - 2022-12-06

@ -18,9 +18,8 @@ Make sure Docker, Elixir, Erlang and Node.js are all installed on your developme
4. Run `mix run priv/repo/seeds.exs` to seed the database. Check the [Seeds](#Seeds) section for more.
5. Run `npm ci --prefix assets` to install the required client-side dependencies.
6. Run `npm ci --prefix tracker` to install the required tracker dependencies.
7. Run `mix assets.setup` to install Tailwind and Esbuild
8. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js`
9. Run `mix download_country_database` to fetch geolocation database
7. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js`
8. Run `mix download_country_database` to fetch geolocation database
3. Run `make server` or `mix phx.server` to start the Phoenix server.
4. The system is now available on `localhost:8000`.

@ -2,26 +2,19 @@
# platform specific, it makes sense to build it in the docker
#### Builder
FROM hexpm/elixir:1.16.0-erlang-26.2.1-alpine-3.18.4 as buildcontainer
ARG MIX_ENV=small
FROM hexpm/elixir:1.13.4-erlang-24.3.3-alpine-3.15.3 as buildcontainer
# preparation
ENV MIX_ENV=$MIX_ENV
ENV MIX_ENV=prod
ENV NODE_ENV=production
ENV NODE_OPTIONS=--openssl-legacy-provider
# custom ERL_FLAGS are passed for (public) multi-platform builds
# to fix qemu segfault, more info: https://github.com/erlang/otp/pull/6340
ARG ERL_FLAGS
ENV ERL_FLAGS=$ERL_FLAGS
RUN mkdir /app
WORKDIR /app
# install build dependencies
RUN apk add --no-cache git nodejs yarn python3 npm ca-certificates wget gnupg make gcc libc-dev && \
npm install npm@latest -g
RUN apk add --no-cache git nodejs yarn python3 npm ca-certificates wget gnupg make erlang gcc libc-dev && \
npm install npm@latest -g && \
npm install -g webpack
COPY mix.exs ./
COPY mix.lock ./
@ -41,37 +34,38 @@ COPY assets ./assets
COPY tracker ./tracker
COPY priv ./priv
COPY lib ./lib
COPY extra ./extra
RUN npm run deploy --prefix ./tracker && \
mix assets.deploy && \
RUN npm run deploy --prefix ./assets && \
npm run deploy --prefix ./tracker && \
mix phx.digest priv/static && \
mix download_country_database && \
mix sentry.package_source_code
# https://hexdocs.pm/sentry/Sentry.Sources.html#module-source-code-storage
mix sentry_recompile
WORKDIR /app
COPY rel rel
RUN mix release plausible
# Main Docker Image
FROM alpine:3.18.4
LABEL maintainer="plausible.io <hello@plausible.io>"
FROM alpine:3.15.3
LABEL maintainer="tckb <tckb@tgrthi.me>"
ARG BUILD_METADATA={}
ENV BUILD_METADATA=$BUILD_METADATA
ENV LANG=C.UTF-8
ARG MIX_ENV=small
ENV MIX_ENV=$MIX_ENV
RUN adduser -S -H -u 999 -G nogroup plausible -g 'Plausible Analytics'
RUN apk upgrade --no-cache
RUN apk add --no-cache openssl ncurses libstdc++ libgcc ca-certificates
COPY --from=buildcontainer --chmod=a+rX /app/_build/${MIX_ENV}/rel/plausible /app
COPY --chmod=755 ./rel/docker-entrypoint.sh /entrypoint.sh
COPY ./rel/docker-entrypoint.sh /entrypoint.sh
RUN chmod a+x /entrypoint.sh && \
adduser -h /app -u 1000 -s /bin/sh -D plausibleuser
USER 999
COPY --from=buildcontainer /app/_build/prod/rel/plausible /app
RUN chown -R plausibleuser:plausibleuser /app
USER plausibleuser
WORKDIR /app
ENV LISTEN_IP=0.0.0.0
ENTRYPOINT ["/entrypoint.sh"]

@ -15,13 +15,13 @@ install: ## Run the initial setup
server: ## Start the web server
mix phx.server
CH_FLAGS ?= --detach -p 8123:8123 -p 9000:9000 --ulimit nofile=262144:262144 --name plausible_clickhouse
CH_FLAGS ?= --detach -p 8123:8123 --ulimit nofile=262144:262144 --name plausible_clickhouse
clickhouse: ## Start a container with a recent version of clickhouse
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol:/var/lib/clickhouse clickhouse/clickhouse-server:latest-alpine
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol:/var/lib/clickhouse clickhouse/clickhouse-server:22.9-alpine
clickhouse-prod: ## Start a container with the same version of clickhouse as the one in prod
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol_prod:/var/lib/clickhouse clickhouse/clickhouse-server:23.3.7.5-alpine
docker run $(CH_FLAGS) --volume=$$PWD/.clickhouse_db_vol_prod:/var/lib/clickhouse clickhouse/clickhouse-server:22.8.13.20-alpine
clickhouse-stop: ## Stop and remove the clickhouse container
docker stop plausible_clickhouse && docker rm plausible_clickhouse
@ -29,19 +29,10 @@ clickhouse-stop: ## Stop and remove the clickhouse container
PG_FLAGS ?= --detach -e POSTGRES_PASSWORD="postgres" -p 5432:5432 --name plausible_db
postgres: ## Start a container with a recent version of postgres
docker run $(PG_FLAGS) --volume=plausible_db:/var/lib/postgresql/data postgres:latest
docker run $(PG_FLAGS) --volume=plausible_db:/var/lib/postgresql/data postgres:14-alpine
postgres-prod: ## Start a container with the same version of postgres as the one in prod
docker run $(PG_FLAGS) --volume=plausible_db_prod:/var/lib/postgresql/data postgres:15
docker run $(PG_FLAGS) --volume=plausible_db_prod:/var/lib/postgresql/data postgres:12
postgres-stop: ## Stop and remove the postgres container
docker stop plausible_db && docker rm plausible_db
minio: ## Start a transient container with a recent version of minio (s3)
docker run -d --rm -p 10000:10000 -p 10001:10001 --name plausible_minio minio/minio server /data --address ":10000" --console-address ":10001"
while ! docker exec plausible_minio mc alias set local http://localhost:10000 minioadmin minioadmin; do sleep 1; done
docker exec plausible_minio mc mb local/dev-exports
docker exec plausible_minio mc mb local/dev-imports
minio-stop: ## Stop and remove the minio container
docker stop plausible_minio

@ -15,7 +15,7 @@
<br /><br />
</p>
[Plausible Analytics](https://plausible.io/) is an easy to use, lightweight (< 1 KB), open source and privacy-friendly alternative to Google Analytics. It doesn’t use cookies and is fully compliant with GDPR, CCPA and PECR. You can self-host Plausible Community Edition or have us manage Plausible Analytics for you in the cloud. Here's [the live demo of our own website stats](https://plausible.io/plausible.io). Made and hosted in the EU 🇪🇺
[Plausible Analytics](https://plausible.io/) is a simple, lightweight (< 1 KB), open source and privacy-friendly alternative to Google Analytics. It doesn’t use cookies and is fully compliant with GDPR, CCPA and PECR. You can self-host or have us run Plausible for you in the cloud. Here's [the live demo of our own website stats](https://plausible.io/plausible.io). Made and hosted in the EU 🇪🇺
We are dedicated to making web analytics more privacy-friendly. Our mission is to reduce corporate surveillance by providing an alternative web analytics tool which doesn’t come from the AdTech world. We are completely independent and solely funded by our subscribers.
@ -23,17 +23,16 @@ We are dedicated to making web analytics more privacy-friendly. Our mission is t
## Why Plausible?
Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 12,000+ paying subscribers to deliver their website and business insights:
Here's what makes Plausible a great Google Analytics alternative and why we're trusted by thousands of paying subscribers to deliver their website and business insights:
- **Clutter Free**: Plausible Analytics provides [simple web analytics](https://plausible.io/simple-web-analytics) and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary.
- **GDPR/CCPA/PECR compliant**: Measure traffic, not individuals. No personal data or IP addresses are ever stored in our database. We don't use cookies or any other persistent identifiers. [Read more about our data policy](https://plausible.io/data-policy)
- **Lightweight**: Plausible Analytics works by loading a script on your website, like Google Analytics. Our script is [45x smaller](https://plausible.io/lightweight-web-analytics), making your website quicker to load. You can also send events directly to our [events API](https://plausible.io/docs/events-api).
- **Lightweight**: Plausible Analytics works by loading a script on your website, like Google Analytics. Our script is [45x smaller](https://plausible.io/lightweight-web-analytics), making your website quicker to load.
- **Email or Slack reports**: Keep an eye on your traffic with weekly and/or monthly email or Slack reports. You can also get traffic spike notifications.
- **Invite team members and share stats**: You have the option to be transparent and open your web analytics to everyone. Your website stats are private by default but you can choose to make them public so anyone with your custom link can view them. You can [invite team members](https://plausible.io/docs/users-roles) and assign user roles too.
- **Define key goals and track conversions**: Create custom events with custom dimensions to track conversions and attribution to understand and identify the trends that matter. Includes easy ways to track outbound link clicks, file downloads and 404 error pages.
- **Open website stats**: You have the option to be transparent and open your web analytics to everyone. Your website stats are private by default but you can choose to make them public so anyone with your custom link can view them.
- **Define key goals and track conversions**: Set custom events or page URLs as your goals and see how they convert over time to understand and identify the trends that matter. Includes easy ways to track outbound link clicks and 404 error pages.
- **Search keywords**: Integrate your dashboard with Google Search Console to get the most accurate reporting on your search keywords.
- **SPA support**: Plausible is built with modern web frameworks in mind and it works automatically with any pushState based router on the frontend. We also support frameworks that use the URL hash for routing. See [our documentation](https://plausible.io/docs/hash-based-routing).
- **Smooth transition from Google Analytics**: There's a realtime dashboard, entry pages report and integration with Search Console. You can track your paid campaigns and conversions. You can invite team members. You can even [import your historical Google Analytics stats](https://plausible.io/docs/google-analytics-import). Learn how to [get the most out of your Plausible experience](https://plausible.io/docs/your-plausible-experience) and join thousands who have already migrated from Google Analytics.
Interested to learn more? [Read more on our website](https://plausible.io), learn more about the team and the goals of the project on [our about page](https://plausible.io/about) or explore [the documentation](https://plausible.io/docs).
@ -49,32 +48,34 @@ We choose the subscription business model rather than the business model of surv
## Getting started with Plausible
The easiest way to get started with Plausible Analytics is with [our official managed service in the cloud](https://plausible.io/#pricing). It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us.
The easiest way to get started with Plausible is with [our official managed service in the cloud](https://plausible.io/#pricing). It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us.
In order to be compliant with the GDPR and the Schrems II ruling, all visitor data for our managed service in the cloud is exclusively processed on servers and cloud infrastructure owned and operated by European providers. Your website data never leaves the EU.
Our managed hosting can save a substantial amount of developer time and resources. For most sites this ends up being the best value option and the revenue goes to funding the maintenance and further development of Plausible. So you’ll be supporting open source software and getting a great service!
### Can Plausible be self-hosted?
### Can Plausible Analytics be self-hosted?
Plausible is [open source web analytics](https://plausible.io/open-source-website-analytics) and we have a free as in beer and self-hosted solution called [Plausible Community Edition (CE)](https://plausible.io/self-hosted-web-analytics). Here are the differences between Plausible Analytics managed hosting in the cloud and the Plausible CE:
Plausible is fully [open source web analytics](https://plausible.io/open-source-website-analytics) and we have a free as in beer [Plausible Analytics Self-Hosted](https://plausible.io/self-hosted-web-analytics) solution. It’s exactly the same product as our cloud solution with a less frequent release schedule (think of it as a long term support release).
| | Plausible Analytics Cloud | Plausible Community Edition |
Bug fixes and new features are released to the cloud version several times per week. Features are battle-tested in the cloud which allows us to fix any bugs before the general self-hosted release. Every six months or so we combine all the changes into a new self-hosted release.
The main difference between the two is that the self-hosted version you have to install, host and manage yourself on your own infrastructure while the cloud version we manage everything for your ease and convenience. Here's the overview of all the differences:
| | Plausible Cloud | Self-Hosting |
| ------------- | ------------- | ------------- |
| **Infrastructure management** | Easy and convenient. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us. We manage everything so you don’t have to worry about anything and can focus on your stats. | You do it all yourself. You need to get a server and you need to manage your infrastructure. You are responsible for installation, maintenance, upgrades, server capacity, uptime, backup, security, stability, consistency, loading time and so on.|
| **Release schedule** | Continuously developed and improved with new features and updates multiple times per week. | [It's a long term release](https://plausible.io/blog/building-open-source) published twice per year so latest features and improvements won't be immediately available.|
| **Premium features** | All features available as listed in [our pricing plans](https://plausible.io/#pricing). | Selected premium features such as funnels and ecommerce revenue goals are not available as we aim to ensure a [protective barrier around our cloud offering](https://plausible.io/blog/community-edition).|
| **Bot filtering** | Advanced bot filtering for more accurate stats. Our algorithm detects and excludes non-human traffic patterns. We also exclude known bots by the User-Agent header and filter out traffic from data centers and referrer spam domains. | Basic bot filtering that targets the most common non-human traffic based on the User-Agent header and referrer spam domains.|
| **Server location** | All visitor data is exclusively processed on EU-owned cloud infrastructure. We keep your site data on a secure, encrypted and green energy powered server in Germany. This ensures that your site data is protected by the strict European Union data privacy laws and ensures compliance with GDPR. Your website data never leaves the EU. | You have full control and can host your instance on any server in any country that you wish. Host it on a server in your basement or host it with any cloud provider wherever you want, even those that are not GDPR compliant.|
| **Data portability** | You see all your site stats and metrics on our modern-looking, simple to use and fast loading dashboard. You can only see the stats aggregated in the dashboard. You can download the stats using the [CSV export](https://plausible.io/docs/export-stats), [stats API](https://plausible.io/docs/stats-api) or tools such as the [Data Studio Connector](https://plausible.io/docs/integration-guides#google-data-studio). | Do you want access to the raw data? Self-hosting gives you that option. You can take the data directly from the ClickHouse database. |
| **Premium support** | Real support delivered by real human beings who build and maintain Plausible. | Premium support is not included. CE is community supported only.|
| **Costs** | There's a cost associated with providing an analytics service so we charge a subscription fee. We choose the subscription business model rather than the business model of surveillance capitalism. Your money funds further development of Plausible. | You need to pay for your server, CDN, backups and whatever other cost there is associated with running the infrastructure. You never have to pay any fees to us. Your money goes to 3rd party companies with no connection to us.|
| Hosting | Easy and convenient. It takes 2 minutes to start counting your stats with a worldwide CDN, high availability, backups, security and maintenance all done for you by us. We manage everything so you don’t have to worry about anything and can focus on your stats. | You do it all yourself. You need to get a server and you need to manage your infrastructure. You are responsible for installation, maintenance, upgrades, server capacity, uptime, backup, security, stability, consistency, loading time and so on. |
| Storage | All visitor data is exclusively processed on EU-owned cloud infrastructure. We keep your site data on a secure, encrypted and green energy powered server in Germany. This ensures that your site data is protected by the strict European Union data privacy laws and ensures compliance with GDPR. Your website data never leaves the EU. | You have full control and can host your instance on any server in any country that you wish. Host it on a server in your basement or host it with any cloud provider wherever you want, even those that are not GDPR compliant. |
| Releases | Continuously developed and improved with new features and updates multiple times per week. | [It's a long term release](https://plausible.io/blog/building-open-source) published approximately twice per year so latest features won't be immediately available. You can see all the [currently unreleased features in the changelog](https://github.com/plausible/analytics/blob/master/CHANGELOG.md).|
| Raw data | You see all your site stats and metrics on our modern-looking, simple to use and fast loading dashboard. You can only see the stats aggregated in the dashboard. You can download the stats using the [CSV export](https://plausible.io/docs/export-stats), [stats API](https://plausible.io/docs/stats-api) or tools such as the [Data Studio Connector](https://plausible.io/docs/integration-guides#google-data-studio). | Do you want access to the raw data? Self-hosting gives you that option. You can take the data directly from the ClickHouse database. |
| Premium Support | Real support delivered by real human beings who build and maintain Plausible. | Premium support is not included. Self-hosting is community supported only. |
| Costs | There's a cost associated with providing an analytics service so we charge a subscription fee. We choose the subscription business model rather than the business model of surveillance capitalism. Your money funds further development of Plausible. | You need to pay for your server, CDN, backups and whatever other cost there is associated with running the infrastructure. You never have to pay any fees to us. Your money goes to 3rd party companies with no connection to us.|
Interested in self-hosting Plausible CE on your server? Take a look at our [Plausible CE installation instructions](https://github.com/plausible/community-edition/).
Interested in self-hosting Plausible on your server? Take a look at our [self-hosting installation instructions](https://plausible.io/docs/self-hosting).
Plausible CE is a community supported project and there are no guarantees that you will get support from the creators of Plausible to troubleshoot your self-hosting issues. There is a [community supported forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support) where you can ask for help.
Plausible Self-Hosted is a community supported project and there are no guarantees that you will get support from the creators of Plausible to troubleshoot your self-hosting issues. There is a [community supported forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support) where you can ask for help.
Our only source of funding is our premium, managed service for running Plausible in the cloud.
Our only source of funding is our premium, managed service for running Plausible in the cloud. If you're looking for an alternative way to support the project, we've put together some sponsorship packages. If you choose to self-host Plausible you can [become a sponsor](https://github.com/sponsors/plausible) which is a great way to give back to the community and to contribute to the long-term sustainability of the project.
## Technology
@ -89,14 +90,13 @@ For anyone wishing to contribute to Plausible, we recommend taking a look at [ou
## Feedback & Roadmap
We welcome feedback from our community. We have a public roadmap driven by the features suggested by the community members. Take a look at our [feedback board](https://plausible.io/feedback). Please let us know if you have any requests and vote on open issues so we can better prioritize.
To stay up to date with all the latest news and product updates, make sure to follow us on [X (formerly Twitter)](https://twitter.com/plausiblehq), [LinkedIn](https://www.linkedin.com/company/plausible-analytics/) or [Mastodon](https://fosstodon.org/@plausible).
We welcome feedback from our community. We have a public roadmap driven by the features suggested by the community members. Take a look at our [feedback board](https://plausible.io/feedback) directly here on GitHub. Please let us know if you have any requests and vote on open issues so we can better prioritize.
## License & Trademarks
To stay up to date with all the latest news and product updates, make sure to follow us on [Twitter](https://twitter.com/plausiblehq), [LinkedIn](https://www.linkedin.com/company/plausible-analytics/) or [Mastodon](https://fosstodon.org/@plausible).
Plausible CE is open source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can [find it here](https://github.com/plausible/analytics/blob/master/LICENSE.md).
## License
To avoid issues with AGPL virality, we've released the JavaScript tracker which gets included on your website under the MIT license. You can [find it here](https://github.com/plausible/analytics/blob/master/tracker/LICENSE.md).
Plausible is open-source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can [find it here](https://github.com/plausible/analytics/blob/master/LICENSE.md).
Copyright (c) 2018-present Plausible Insights OÜ. Plausible Analytics name and logo are trademarks of Plausible Insights OÜ. Please see our [trademark guidelines](https://plausible.io/trademark) for info on acceptable usage.
The only exception is our JavaScript tracker which gets included on your website. To avoid issues with AGPL virality, we've
released the tracker under the MIT license. You can [find it here](https://github.com/plausible/analytics/blob/master/tracker/LICENSE.md).

@ -7,8 +7,6 @@ want be up to date on security patches, make sure your Plausible image is up to
## Reporting a Vulnerability
Our software is updated several times per week and we also have a way for you to [report any security vulnerabilities](https://plausible.io/vulnerability-disclosure-program). A more detailed overview about our security practices can be found on [plausible.io/security](https://plausible.io/security).
If you've found a security vulnerability with the Plausible codebase, you can disclose it responsibly by sending a summary to security@plausible.io.
We will review the potential threat and fix it as fast as we can.

@ -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,7 +1,6 @@
{
"env": {
"browser": true,
"es6": true
"browser": true
},
"extends": ["eslint:recommended",
"plugin:react/recommended",
@ -25,8 +24,7 @@
"react/jsx-props-no-spreading": [0],
"jsx-a11y/click-events-have-key-events": [0],
"jsx-a11y/no-static-element-interactions": [0],
"react/no-did-update-set-state": [0],
"react/no-unknown-property": [2, {"ignore": ["tooltip"]}]
"react/no-did-update-set-state": [0]
},
"settings": {
"react": {

@ -1,20 +1,14 @@
@import "tailwindcss/base";
@import "flatpickr/dist/flatpickr.min.css";
@import "./modal.css";
@import "./loader.css";
@import "./tooltip.css";
@import "./flatpickr.css";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
/* purgecss start ignore */
@tailwind base;
@tailwind components;
[x-cloak] { display: none; }
/* purgecss end ignore */
@import "modal.css";
@import "loader.css";
@import "tooltip.css";
@import "flatpickr.css";
@media print {
canvas {
width: 100% !important;
height: auto !important;
}
}
[x-cloak] { display: none; }
.button {
@apply inline-flex justify-center px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md leading-5 transition hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500;
@ -28,10 +22,6 @@
@apply text-indigo-600 bg-transparent border border-indigo-600;
}
.button-outline:hover {
@apply text-white;
}
.button-sm {
@apply px-4 py-2 text-sm;
}
@ -47,10 +37,13 @@ html {
body {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width:100vw; /* Prevents content from jumping when scrollbar is added/removed due to vertical overflow */
overflow-x: hidden;
}
button:disabled {
cursor: default;
}
blockquote {
@apply px-4 py-2 my-4 border-l-4 border-gray-500;
}
@ -71,6 +64,8 @@ blockquote {
}
}
@tailwind utilities;
.light-text {
color: #F0F4F8;

@ -1,24 +1,9 @@
import "../css/app.css"
import "flatpickr/dist/flatpickr.min.css"
import "./polyfills/closest"
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
import Alpine from 'alpinejs'
import "./liveview/live_socket"
import comboBox from "./liveview/combo-box"
import dropdown from "./liveview/dropdown"
import "./liveview/phx_events"
Alpine.data('dropdown', dropdown)
Alpine.data('comboBox', comboBox)
Alpine.start()
if (document.querySelectorAll('[data-modal]').length > 0) {
window.addEventListener(`phx:close-modal`, (e) => {
document
.getElementById(e.detail.id)
.dispatchEvent(
new CustomEvent('close-modal', { bubbles: true, detail: e.detail.id })
)
})
}
import "phoenix_html"
import 'alpinejs'
const triggers = document.querySelectorAll('[data-dropdown-trigger]')
@ -49,17 +34,36 @@ if (triggers.length > 0) {
})
}
const registerForm = document.getElementById('register-form')
if (registerForm) {
registerForm.addEventListener('submit', function(e) {
e.preventDefault();
setTimeout(submitForm, 1000);
var formSubmitted = false;
function submitForm() {
if (!formSubmitted) {
formSubmitted = true;
registerForm.submit();
}
}
/* eslint-disable-next-line no-undef */
plausible('Signup', {callback: submitForm});
})
}
const changelogNotification = document.getElementById('changelog-notification')
if (changelogNotification) {
showChangelogNotification(changelogNotification)
fetch('https://plausible.io/changes.txt', { headers: { 'Content-Type': 'text/plain' } })
fetch('https://plausible.io/changes.txt', {headers: {'Content-Type': 'text/plain'}})
.then((res) => res.text())
.then((res) => {
localStorage.lastChangelogUpdate = new Date(res).getTime()
showChangelogNotification(changelogNotification)
})
})
}
function showChangelogNotification(el) {
@ -67,7 +71,7 @@ function showChangelogNotification(el) {
const lastChecked = Number(localStorage.lastChangelogClick)
const hasNewUpdateSinceLastClicked = lastUpdated > lastChecked
const notOlderThanThreeDays = Date.now() - lastUpdated < 1000 * 60 * 60 * 72
const notOlderThanThreeDays = Date.now() - lastUpdated < 1000 * 60 * 60 * 72
if ((!lastChecked || hasNewUpdateSinceLastClicked) && notOlderThanThreeDays) {
el.innerHTML = `
<a href="https://plausible.io/changelog" target="_blank">

@ -1,4 +1,4 @@
import { formatISO } from './util/date'
import {formatISO} from './util/date'
let abortController = new AbortController()
let SHARED_LINK_AUTH = null
@ -36,34 +36,26 @@ function serializeFilters(filters) {
return JSON.stringify(cleaned)
}
export function serializeQuery(query, extraQuery = []) {
export function serializeQuery(query, extraQuery=[]) {
const queryObj = {}
if (query.period) { queryObj.period = query.period }
if (query.date) { queryObj.date = formatISO(query.date) }
if (query.from) { queryObj.from = formatISO(query.from) }
if (query.to) { queryObj.to = formatISO(query.to) }
if (query.filters) { queryObj.filters = serializeFilters(query.filters) }
if (query.experimental_session_count) { queryObj.experimental_session_count = query.experimental_session_count }
if (query.with_imported) { queryObj.with_imported = query.with_imported }
if (query.period) { queryObj.period = query.period }
if (query.date) { queryObj.date = formatISO(query.date) }
if (query.from) { queryObj.from = formatISO(query.from) }
if (query.to) { queryObj.to = formatISO(query.to) }
if (query.filters) { queryObj.filters = serializeFilters(query.filters) }
if (query.with_imported) { queryObj.with_imported = query.with_imported }
if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH }
if (query.comparison) {
queryObj.comparison = query.comparison
queryObj.compare_from = query.compare_from ? formatISO(query.compare_from) : undefined
queryObj.compare_to = query.compare_to ? formatISO(query.compare_to) : undefined
queryObj.match_day_of_week = query.match_day_of_week
}
if (query.comparison) { queryObj.comparison = true }
Object.assign(queryObj, ...extraQuery)
return '?' + serialize(queryObj)
}
export function get(url, query = {}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? { 'X-Shared-Link-Auth': SHARED_LINK_AUTH } : {}
export function get(url, query={}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? {'X-Shared-Link-Auth': SHARED_LINK_AUTH} : {}
url = url + serializeQuery(query, extraQuery)
return fetch(url, { signal: abortController.signal, headers: headers })
.then(response => {
return fetch(url, {signal: abortController.signal, headers: headers})
.then( response => {
if (!response.ok) {
return response.json().then((msg) => {
throw new ApiError(msg.error, msg)
@ -72,11 +64,3 @@ export function get(url, query = {}, ...extraQuery) {
return response.json()
})
}
export function put(url, body) {
return fetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
}

@ -1,195 +1,22 @@
import React, { Fragment } from 'react'
import { withRouter } from 'react-router-dom'
import React 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 (!site.flags.comparisons) return null
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))
}
}
function update(event) {
navigateToQuery(history, query, { comparison: event.target.checked })
}
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>
</>
<div className="flex-none mx-3">
<input id="comparison-input" type="checkbox" onChange={update} checked={query.comparison} className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500" />
<label htmlFor="comparison-input" className="ml-1.5 font-medium text-xs md:text-sm text-gray-700 dark:text-white">Compare</label>
</div>
)
}

@ -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">&times;</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>
)
}

@ -7,6 +7,7 @@ import {
shiftDays,
shiftMonths,
formatDay,
formatDayShort,
formatMonthYYYY,
formatYear,
formatISO,
@ -17,15 +18,11 @@ import {
isThisMonth,
isThisYear,
parseUTCDate,
parseNaiveDate,
isBefore,
isAfter,
formatDateRange
} from "./util/date";
import { navigateToQuery, QueryLink, QueryButton } from "./query";
import { shouldIgnoreKeypress } from "./keybinding.js"
import { COMPARISON_DISABLED_PERIODS, toggleComparisons, isComparisonEnabled } from "../dashboard/comparison-input.js"
import classNames from "classnames"
function renderArrow(query, site, period, prevDate, nextDate) {
const insertionDate = parseUTCDate(site.statsBegin);
@ -40,29 +37,19 @@ function renderArrow(query, site, period, prevDate, nextDate) {
period
);
const isComparing = isComparisonEnabled(query.comparison)
const leftClass = classNames("flex items-center px-1 sm:px-2 border-r border-gray-300 rounded-l dark:border-gray-500 dark:text-gray-100", {
"bg-gray-300 dark:bg-gray-950": disabledLeft,
"hover:bg-gray-100 dark:hover:bg-gray-900": !disabledLeft,
})
const rightClass = classNames("flex items-center px-1 sm:px-2 rounded-r dark:text-gray-100", {
"bg-gray-300 dark:bg-gray-950": disabledRight,
"hover:bg-gray-100 dark:hover:bg-gray-900": !disabledRight,
})
const containerClass = classNames("rounded shadow bg-white mr-2 sm:mr-4 cursor-pointer dark:bg-gray-800", {
"hidden md:flex": isComparing,
"flex": !isComparing,
})
const leftClasses = `flex items-center px-1 sm:px-2 border-r border-gray-300 rounded-l
dark:border-gray-500 dark:text-gray-100 ${
disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900"
}`;
const rightClasses = `flex items-center px-1 sm:px-2 rounded-r dark:text-gray-100 ${
disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900"
}`;
return (
<div className={containerClass}>
<div className="flex rounded shadow bg-white mr-2 sm:mr-4 cursor-pointer dark:bg-gray-800">
<QueryButton
to={{ date: prevDate }}
query={query}
className={leftClass}
className={leftClasses}
disabled={disabledLeft}
>
<svg
@ -81,7 +68,7 @@ function renderArrow(query, site, period, prevDate, nextDate) {
<QueryButton
to={{ date: nextDate }}
query={query}
className={rightClass}
className={rightClasses}
disabled={disabledRight}
>
<svg
@ -101,7 +88,7 @@ function renderArrow(query, site, period, prevDate, nextDate) {
);
}
function DatePickerArrows({ site, query }) {
function DatePickerArrows({site, query}) {
if (query.period === "year") {
const prevDate = formatISO(shiftMonths(query.date, -12));
const nextDate = formatISO(shiftMonths(query.date, 12));
@ -122,7 +109,7 @@ function DatePickerArrows({ site, query }) {
return null
}
function DisplayPeriod({ query, site }) {
function DisplayPeriod({query, site}) {
if (query.period === "day") {
if (isToday(site, query.date)) {
return "Today";
@ -149,12 +136,12 @@ function DisplayPeriod({ query, site }) {
} if (query.period === 'all') {
return 'All time'
} if (query.period === 'custom') {
return formatDateRange(site, query.from, query.to)
return `${formatDayShort(query.from)} - ${formatDayShort(query.to)}`
}
return 'Realtime'
}
function DatePicker({ query, site, history }) {
function DatePicker({query, site, history}) {
const [open, setOpen] = useState(false)
const [mode, setMode] = useState('menu')
const dropDownNode = useRef(null)
@ -207,24 +194,11 @@ function DatePicker({ query, site, history }) {
setOpen(false);
const keybindings = {
d: { date: false, period: 'day' },
e: { date: formatISO(shiftDays(nowForSite(site), -1)), period: 'day' },
r: { period: 'realtime' },
w: { date: false, period: '7d' },
m: { date: false, period: 'month' },
y: { date: false, period: 'year' },
t: { date: false, period: '30d' },
s: { date: false, period: '6mo' },
l: { date: false, period: '12mo' },
a: { date: false, period: 'all' },
}
const keys = ['d', 'e', 'r', 'w', 'm', 'y', 't', 's', 'l', 'a'];
const redirects = [{date: false, period: 'day'}, {date: formatISO(shiftDays(nowForSite(site), -1)), period: 'day'}, {period: 'realtime'}, {date: false, period: '7d'}, {date: false, period: 'month'}, {date: false, period: 'year'}, {date: false, period: '30d'}, {date: false, period: '6mo'}, {date: false, period: '12mo'}, {date: false, period: 'all'}];
const redirect = keybindings[e.key.toLowerCase()]
if (redirect) {
navigateToQuery(history, query, { ...newSearch, ...redirect })
} else if (e.key.toLowerCase() === 'x') {
toggleComparisons(history, query, site)
if (keys.includes(e.key.toLowerCase())) {
navigateToQuery(history, query, {...newSearch, ...(redirects[keys.indexOf(e.key.toLowerCase())])});
} else if (e.key.toLowerCase() === 'c') {
setOpen(true)
setMode('calendar')
@ -240,7 +214,7 @@ function DatePicker({ query, site, history }) {
})
useEffect(() => {
if (mode === 'calendar' && open) {
if (mode === 'calendar' && open) {
openCalendar()
}
}, [mode])
@ -255,18 +229,34 @@ function DatePicker({ query, site, history }) {
return () => { document.removeEventListener("mousedown", handleClick, false); }
}, [])
function setCustomDate([from, to], _dateStr, _instance) {
if (from && to) {
[from, to] = [parseNaiveDate(from), parseNaiveDate(to)]
if (from.isSame(to)) {
navigateToQuery(history, query, { period: 'day', date: formatISO(from), from: false, to: false })
function setCustomDate(dates) {
if (dates.length === 2) {
const [from, to] = dates
if (formatISO(from) === formatISO(to)) {
navigateToQuery(
history,
query,
{
period: 'day',
date: formatISO(from),
from: false,
to: false
}
)
} else {
navigateToQuery(history, query, { period: 'custom', date: false, from: formatISO(from), to: formatISO(to) })
navigateToQuery(
history,
query,
{
period: 'custom',
date: false,
from: formatISO(from),
to: formatISO(to),
}
)
}
setOpen(false)
}
setOpen(false)
}
function toggle() {
@ -292,17 +282,27 @@ function DatePicker({ query, site, history }) {
opts.date = opts.date ? formatISO(opts.date) : false;
const keybinds = {
'Today': 'D',
'Realtime': 'R',
'Last 7 days': 'W',
'Month to Date': 'M',
'Year to Date': 'Y',
'Last 12 months': 'L',
'Last 30 days': 'T',
'All time': 'A',
};
return (
<QueryLink
to={{ from: false, to: false, period, ...opts }}
to={{from: false, to: false, period, ...opts}}
onClick={() => setOpen(false)}
query={query}
className={`${boldClass} px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900
className={`${boldClass } px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900
dark:hover:bg-gray-900 dark:hover:text-gray-100 flex items-center justify-between`}
>
{text}
{opts.keybindHint ? (<span className='font-normal'>{opts.keybindHint}</span>) : null}
<span className='font-normal'>{keybinds[text]}</span>
</QueryLink>
);
}
@ -319,23 +319,23 @@ function DatePicker({ query, site, history }) {
font-medium text-gray-800 dark:text-gray-200 date-options"
>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("day", "Today", { keybindHint: 'D' })}
{renderLink("realtime", "Realtime", { keybindHint: 'R' })}
{renderLink("day", "Today")}
{renderLink("realtime", "Realtime")}
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("7d", "Last 7 Days", { keybindHint: 'W' })}
{renderLink("30d", "Last 30 Days", { keybindHint: 'T' })}
{renderLink("7d", "Last 7 days")}
{renderLink("30d", "Last 30 days")}
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink('month', 'Month to Date', { keybindHint: 'M' })}
{renderLink('month', 'Last Month', { date: lastMonth(site) })}
{ renderLink('month', 'Month to Date') }
{ renderLink('month', 'Last month', {date: lastMonth(site)}) }
</div>
<div className="py-1 border-b border-gray-200 dark:border-gray-500 date-option-group">
{renderLink("year", "Year to Date", { keybindHint: 'Y' })}
{renderLink("12mo", "Last 12 months", { keybindHint: 'L' })}
{renderLink("year", "Year to Date")}
{renderLink("12mo", "Last 12 months")}
</div>
<div className="py-1 date-option-group">
{renderLink("all", "All time", { keybindHint: 'A' })}
{renderLink("all", "All time")}
<span
onClick={() => setMode('calendar')}
onKeyPress={() => setMode('calendar')}
@ -348,26 +348,16 @@ function DatePicker({ query, site, history }) {
aria-expanded="false"
aria-controls="calendar"
>
Custom Range
Custom range
<span className='font-normal'>C</span>
</span>
</div>
{!COMPARISON_DISABLED_PERIODS.includes(query.period) &&
<div className="py-1 date-option-group border-t border-gray-200 dark:border-gray-500">
<span
onClick={() => {
toggleComparisons(history, query, site)
setOpen(false)
}}
className="px-4 py-2 text-sm leading-tight hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer flex items-center justify-between">
{isComparisonEnabled(query.comparison) ? 'Disable comparison' : 'Compare'}
<span className='font-normal'>X</span>
</span>
</div>}
</div>
</div>
);
} if (mode === "calendar") {
const insertionDate = new Date(site.statsBegin);
const dayBeforeCreation = insertionDate - 86400000;
return (
<div className="h-0">
<Flatpickr
@ -375,14 +365,13 @@ function DatePicker({ query, site, history }) {
options={{
mode: 'range',
maxDate: 'today',
minDate: site.statsBegin,
minDate: dayBeforeCreation,
showMonths: 1,
static: true,
animate: true
}}
animate: true}}
ref={calendar}
className="invisible"
onClose={setCustomDate}
onChange={setCustomDate}
/>
</div>
)
@ -392,7 +381,7 @@ function DatePicker({ query, site, history }) {
function renderPicker() {
return (
<div
className="min-w-32 md:w-48 md:relative"
className="w-20 sm:w-36 md:w-48 md:relative"
ref={dropDownNode}
>
<div
@ -416,11 +405,11 @@ function DatePicker({ query, site, history }) {
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
{renderDropDownContent()}
</Transition>

@ -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>&nbsp;</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 "-"
}
}

@ -4,33 +4,22 @@ import { AdjustmentsVerticalIcon, MagnifyingGlassIcon, XMarkIcon, PencilSquareIc
import classNames from 'classnames'
import { Menu, Transition } from '@headlessui/react'
import { appliedFilters, navigateToQuery } from './query'
import { appliedFilters, navigateToQuery, formattedFilters } from './query'
import {
FILTER_GROUPS,
formatFilterGroup,
filterGroupForFilter,
parseQueryFilter,
parseQueryPropsFilter,
formattedFilters
} from "./util/filters";
function removeFilter(filterType, key, history, query) {
const newOpts = {}
if (filterType === 'props') {
if (Object.keys(query.filters.props).length == 1) {
newOpts.props = false
} else {
newOpts.props = JSON.stringify({
...query.filters.props,
[key]: undefined,
})
}
} else {
newOpts[key] = false
toFilterType,
valueWithoutPrefix
} from "./stats/modals/filter";
function removeFilter(key, history, query) {
const newOpts = {
[key]: false
}
if (key === 'country') { newOpts.country_labels = false }
if (key === 'region') { newOpts.region_labels = false }
if (key === 'city') { newOpts.city_labels = false }
if (key === 'country') { newOpts.country_name = false }
if (key === 'region') { newOpts.region_name = false }
if (key === 'city') { newOpts.city_name = false }
navigateToQuery(
history,
@ -48,38 +37,70 @@ function clearAllFilters(history, query) {
);
}
function filterText(filterType, key, query) {
function filterText(key, rawValue, query) {
let type = toFilterType(rawValue)
const value = valueWithoutPrefix(rawValue)
if (key === "goal") {
return <>Completed goal <b>{value}</b></>
}
if (key === "props") {
const [metaKey, metaValue] = Object.entries(value)[0]
const eventName = query.filters.goal ? query.filters.goal : 'event'
return <>{eventName}.{metaKey} {toFilterType(metaValue)} <b>{valueWithoutPrefix(metaValue)}</b></>
}
if (key === "browser_version") {
const isNotSet = query.filters.browser === '(not set)' || (!query.filters.browser)
const browserName = isNotSet ? 'Browser' : query.filters.browser
return <>{browserName}.Version {type} <b>{value}</b></>
}
if (key === "os_version") {
const isNotSet = query.filters.os === '(not set)' || (!query.filters.os)
const osName = isNotSet ? 'Operating System' : query.filters.os
console.info('osname', osName)
return <>{osName}.Version {type} <b>{value}</b></>
}
if (key === "country") {
const q = new URLSearchParams(window.location.search)
const countryName = q.get('country_name')
return <>Country {type} <b>{countryName}</b></>
}
if (key === "region") {
const q = new URLSearchParams(window.location.search)
const regionName = q.get('region_name')
return <>Region {type} <b>{regionName}</b></>
}
if (key === "city") {
const q = new URLSearchParams(window.location.search)
const cityName = q.get('city_name')
return <>City {type} <b>{cityName}</b></>
}
const formattedFilter = formattedFilters[key]
if (filterType === "props") {
const { propKey, clauses, type } = parseQueryPropsFilter(query).find((filter) => filter.propKey.value === key)
return <>Property <b>{propKey.label}</b> {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
} else if (formattedFilter) {
const {type, clauses} = parseQueryFilter(query, key)
return <>{formattedFilter} {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
if (formattedFilter) {
return <>{formattedFilter} {type} <b>{value}</b></>
}
throw new Error(`Unknown filter: ${key}`)
}
function renderDropdownFilter(site, history, { key, value, filterType }, query) {
function renderDropdownFilter(site, history, [key, value], query) {
return (
<Menu.Item key={`${filterType}::${key}`}>
<Menu.Item key={key}>
<div className="px-3 md:px-4 sm:py-2 py-3 text-sm leading-tight flex items-center justify-between" key={key + value}>
<Link
title={`Edit filter: ${formattedFilters[filterType]}`}
to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(filterType)}`, search: window.location.search }}
title={`Edit filter: ${formattedFilters[key]}`}
to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(key)}`, search: window.location.search }}
className="group flex w-full justify-between items-center"
style={{ width: 'calc(100% - 1.5rem)' }}
>
<span className="inline-block w-full truncate">{filterText(filterType, key, query)}</span>
<span className="inline-block w-full truncate">{filterText(key, value, query)}</span>
<PencilSquareIcon className="w-4 h-4 ml-1 cursor-pointer group-hover:text-indigo-700 dark:group-hover:text-indigo-500" />
</Link>
<b
title={`Remove filter: ${formattedFilters[filterType]}`}
className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500"
onClick={() => removeFilter(filterType, key, history, query)}
>
<b title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => removeFilter(key, history, query)}>
<XMarkIcon className="w-4 h-4" />
</b>
</div>
@ -109,10 +130,9 @@ function DropdownContent({ history, site, query, wrapped }) {
const [addingFilter, setAddingFilter] = useState(false);
if (wrapped === 0 || addingFilter) {
let filterGroups = {...FILTER_GROUPS}
if (!site.propsAvailable) delete filterGroups.props
return Object.keys(filterGroups).map((option) => filterDropdownOption(site, option))
return Object.keys(FILTER_GROUPS)
.filter((option) => option === 'props' ? site.flags.custom_dimension_filter : true)
.map((option) => filterDropdownOption(site, option))
}
return (
@ -217,21 +237,13 @@ class Filters extends React.Component {
});
};
renderListFilter(history, { key, value, filterType }, query) {
renderListFilter(history, [key, value], query) {
return (
<span key={`${filterType}::${key}`} title={value} className="flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded mr-2 items-center">
<Link
title={`Edit filter: ${formattedFilters[filterType]}`}
className="flex w-full h-full items-center py-2 pl-3"
to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${filterGroupForFilter(filterType)}`, search: window.location.search }}
>
<span className="inline-block max-w-2xs md:max-w-xs truncate">{filterText(filterType, key, query)}</span>
<span key={key} title={value} className="flex bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 shadow text-sm rounded mr-2 items-center">
<Link title={`Edit filter: ${formattedFilters[key]}`} className="flex w-full h-full items-center py-2 pl-3" to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}/filter/${filterGroupForFilter(key)}`, search: window.location.search }}>
<span className="inline-block max-w-2xs md:max-w-xs truncate">{filterText(key, value, query)}</span>
</Link>
<span
title={`Remove filter: ${formattedFilters[filterType]}`}
className="flex h-full w-full px-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 items-center"
onClick={() => removeFilter(filterType, key, history, query)}
>
<span title={`Remove filter: ${formattedFilters[key]}`} className="flex h-full w-full px-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500 items-center" onClick={() => removeFilter(key, history, query)}>
<XMarkIcon className="w-4 h-4" />
</span>
</span>
@ -258,10 +270,6 @@ class Filters extends React.Component {
)
}
trackFilterMenu() {
window.plausible && window.plausible('Filter Menu: Open', {u: `${window.location.protocol}//${window.location.hostname}/:dashboard`})
}
renderDropDown() {
const { history, query, site } = this.props;
@ -270,7 +278,7 @@ class Filters extends React.Component {
{({ open }) => (
<>
<div>
<Menu.Button onClick={this.trackFilterMenu} className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">
<Menu.Button className="flex items-center text-xs md:text-sm font-medium leading-tight px-3 py-2 cursor-pointer ml-auto text-gray-500 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-900 rounded">
{this.renderDropdownButton()}
</Menu.Button>
</div>
@ -279,11 +287,11 @@ class Filters extends React.Component {
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items
static

@ -9,14 +9,25 @@ import Sources from './stats/sources'
import Pages from './stats/pages'
import Locations from './stats/locations';
import Devices from './stats/devices'
import Behaviours from './stats/behaviours'
import Conversions from './stats/conversions'
import ComparisonInput from './comparison-input'
import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index';
function Historical(props) {
const tooltipBoundary = React.useRef(null)
function renderConversions() {
if (props.site.hasGoals) {
return (
<div className="items-start justify-between block w-full mt-6 md:flex">
<Conversions site={props.site} query={props.query} />
</div>
)
}
return null
}
return (
<div className="mb-12">
<div id="stats-container-top"></div>
@ -32,26 +43,15 @@ function Historical(props) {
</div>
</div>
<VisitorGraph site={props.site} query={props.query} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Sources site={props.site} query={props.query} />
</div>
<div className={ statsBoxClass }>
<Pages site={props.site} query={props.query} />
</div>
<div className="items-start justify-between block w-full md:flex">
<Sources site={props.site} query={props.query} />
<Pages site={props.site} query={props.query} />
</div>
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Locations site={props.site} query={props.query} />
</div>
<div className={ statsBoxClass }>
<Devices site={props.site} query={props.query} />
</div>
<div className="items-start justify-between block w-full md:flex">
<Locations site={props.site} query={props.query} />
<Devices site={props.site} query={props.query} />
</div>
<Behaviours site={props.site} query={props.query} currentUserRole={props.currentUserRole} />
{ renderConversions() }
</div>
)
}

@ -7,8 +7,6 @@ import {parseQuery} from './query'
import * as api from './api'
import { withComparisonProvider } from './comparison-provider-hoc';
export const statsBoxClass = "stats-item relative w-full mt-6 p-4 flex flex-col bg-white dark:bg-gray-825 shadow-xl rounded"
class Dashboard extends React.Component {
constructor(props) {
super(props)

@ -20,6 +20,7 @@ export function shouldIgnoreKeypress(event) {
return modifierPressed || isTyping
}
/**
* Returns whether the given keybinding has been pressed and should be
* processed. Events can be ignored based on `shouldIgnoreKeypress(event)`.
@ -29,6 +30,6 @@ export function shouldIgnoreKeypress(event) {
*
*/
export function isKeyPressed(event, keybinding) {
const keyPressed = event.key.toLowerCase() == keybinding.toLowerCase()
const keyPressed = event.key.toLowerCase() == keybinding.toLowerCase()
return keyPressed && !shouldIgnoreKeypress(event)
}

@ -2,10 +2,10 @@ import React from 'react';
import ReactDOM from 'react-dom';
import 'url-search-params-polyfill';
import Router from './dashboard/router'
import ErrorBoundary from './dashboard/error-boundary'
import * as api from './dashboard/api'
import * as timer from './dashboard/util/realtime-update-timer'
import Router from './router'
import ErrorBoundary from './error-boundary'
import * as api from './api'
import * as timer from './util/realtime-update-timer'
timer.start()
@ -16,16 +16,7 @@ if (container) {
domain: container.dataset.domain,
offset: container.dataset.offset,
hasGoals: container.dataset.hasGoals === 'true',
hasProps: container.dataset.hasProps === 'true',
funnelsAvailable: container.dataset.funnelsAvailable === 'true',
propsAvailable: container.dataset.propsAvailable === 'true',
conversionsOptedOut: container.dataset.conversionsOptedOut === 'true',
funnelsOptedOut: container.dataset.funnelsOptedOut === 'true',
propsOptedOut: container.dataset.propsOptedOut === 'true',
revenueGoals: JSON.parse(container.dataset.revenueGoals),
funnels: JSON.parse(container.dataset.funnels),
statsBegin: container.dataset.statsBegin,
nativeStatsBegin: container.dataset.nativeStatsBegin,
embedded: container.dataset.embedded,
background: container.dataset.background,
isDbip: container.dataset.isDbip === 'true',

@ -1,13 +1,8 @@
import React from 'react'
import { Link, withRouter } from 'react-router-dom'
import { nowForSite } from './util/date'
import {formatDay, formatMonthYYYY, nowForSite, parseUTCDate} from './util/date'
import * as storage from './util/storage'
import { COMPARISON_DISABLED_PERIODS, getStoredComparisonMode, isComparisonEnabled, getStoredMatchDayOfWeek } from './comparison-input'
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc)
import { COMPARISON_DISABLED_PERIODS } from './comparison-input'
const PERIODS = ['realtime', 'day', 'month', '7d', '30d', '6mo', '12mo', 'year', 'all', 'custom']
@ -24,22 +19,16 @@ export function parseQuery(querystring, site) {
period = '30d'
}
let comparison = q.get('comparison') || getStoredComparisonMode(site.domain)
if (COMPARISON_DISABLED_PERIODS.includes(period) || !isComparisonEnabled(comparison)) comparison = null
let matchDayOfWeek = q.get('match_day_of_week') || getStoredMatchDayOfWeek(site.domain)
let comparison = !!q.get('comparison')
if (COMPARISON_DISABLED_PERIODS.includes(period)) comparison = null
return {
period,
comparison,
compare_from: q.get('compare_from') ? dayjs.utc(q.get('compare_from')) : undefined,
compare_to: q.get('compare_to') ? dayjs.utc(q.get('compare_to')) : undefined,
date: q.get('date') ? dayjs.utc(q.get('date')) : nowForSite(site),
from: q.get('from') ? dayjs.utc(q.get('from')) : undefined,
to: q.get('to') ? dayjs.utc(q.get('to')) : undefined,
match_day_of_week: matchDayOfWeek == 'true',
date: q.get('date') ? parseUTCDate(q.get('date')) : nowForSite(site),
from: q.get('from') ? parseUTCDate(q.get('from')) : undefined,
to: q.get('to') ? parseUTCDate(q.get('to')) : undefined,
with_imported: q.get('with_imported') ? q.get('with_imported') === 'true' : true,
experimental_session_count: q.get('experimental_session_count'),
comparison: comparison,
filters: {
'goal': q.get('goal'),
'props': JSON.parse(q.get('props')),
@ -59,7 +48,6 @@ export function parseQuery(querystring, site) {
'region': q.get('region'),
'city': q.get('city'),
'page': q.get('page'),
'hostname': q.get('hostname'),
'entry_page': q.get('entry_page'),
'exit_page': q.get('exit_page')
}
@ -67,13 +55,9 @@ export function parseQuery(querystring, site) {
}
export function appliedFilters(query) {
const propKeys = Object.entries(query.filters.props || {})
.map(([key, value]) => ({ key, value, filterType: 'props' }))
return Object.entries(query.filters)
.map(([key, value]) => ({ key, value, filterType: key }))
.filter(({ key, value }) => key !== 'props' && !!value)
.concat(propKeys)
return Object.keys(query.filters)
.map((key) => [key, query.filters[key]])
.filter(([_key, value]) => !!value);
}
function generateQueryString(data) {
@ -128,7 +112,7 @@ class QueryLink extends React.Component {
const QueryLinkWithRouter = withRouter(QueryLink)
export { QueryLinkWithRouter as QueryLink };
function QueryButton({ history, query, to, disabled, className, children, onClick }) {
function QueryButton({history, query, to, disabled, className, children, onClick}) {
return (
<button
className={className}
@ -149,6 +133,23 @@ function QueryButton({ history, query, to, disabled, className, children, onClic
const QueryButtonWithRouter = withRouter(QueryButton)
export { QueryButtonWithRouter as QueryButton };
export function toHuman(query) {
if (query.period === 'day') {
return `on ${formatDay(query.date)}`
} if (query.period === 'month') {
return `in ${formatMonthYYYY(query.date)}`
} if (query.period === '7d') {
return 'in the last 7 days'
} if (query.period === '30d') {
return 'in the last 30 days'
} if (query.period === '6mo') {
return 'in the last 6 months'
} if (query.period === '12mo') {
return 'in the last 12 months'
}
return ''
}
export function eventName(query) {
if (query.filters.goal) {
if (query.filters.goal.startsWith('Visit ')) {
@ -158,3 +159,28 @@ export function eventName(query) {
}
return 'pageviews'
}
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',
'entry_page': 'Entry Page',
'exit_page': 'Exit Page'
}

@ -8,11 +8,22 @@ import Sources from './stats/sources'
import Pages from './stats/pages'
import Locations from './stats/locations'
import Devices from './stats/devices'
import Behaviours from './stats/behaviours'
import Conversions from './stats/conversions'
import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index';
class Realtime extends React.Component {
renderConversions() {
if (this.props.site.hasGoals) {
return (
<div className="items-start justify-between block w-full mt-6 md:flex">
<Conversions site={this.props.site} query={this.props.query} title="Goal Conversions (last 30 min)" />
</div>
)
}
return null
}
render() {
const navClass = this.props.site.embedded ? 'relative' : 'sticky'
@ -29,23 +40,16 @@ class Realtime extends React.Component {
</div>
</div>
<VisitorGraph site={this.props.site} query={this.props.query} lastLoadTimestamp={this.props.lastLoadTimestamp} />
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Sources site={this.props.site} query={this.props.query} />
</div>
<div className={ statsBoxClass }>
<Pages site={this.props.site} query={this.props.query} />
</div>
<div className="items-start justify-between block w-full md:flex">
<Sources site={this.props.site} query={this.props.query} />
<Pages site={this.props.site} query={this.props.query} />
</div>
<div className="w-full md:flex">
<div className={ statsBoxClass }>
<Locations site={this.props.site} query={this.props.query} />
</div>
<div className={ statsBoxClass }>
<Devices site={this.props.site} query={this.props.query} />
</div>
<div className="items-start justify-between block w-full md:flex">
<Locations site={this.props.site} query={this.props.query} />
<Devices site={this.props.site} query={this.props.query} />
</div>
<Behaviours site={this.props.site} query={this.props.query} currentUserRole={this.props.currentUserRole} />
{ this.renderConversions() }
</div>
)
}

@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { BrowserRouter, Switch, Route, useLocation } from "react-router-dom";
import {BrowserRouter, Switch, Route, useLocation} from "react-router-dom";
import Dash from './index'
import SourcesModal from './stats/modals/sources'
@ -9,10 +9,7 @@ import PagesModal from './stats/modals/pages'
import EntryPagesModal from './stats/modals/entry-pages'
import ExitPagesModal from './stats/modals/exit-pages'
import ModalTable from './stats/modals/table'
import PropsModal from './stats/modals/props'
import ConversionsModal from './stats/modals/conversions'
import FilterModal from './stats/modals/filter-modal'
import * as url from './util/url';
import FilterModal from './stats/modals/filter'
function ScrollToTop() {
const location = useLocation();
@ -26,14 +23,14 @@ function ScrollToTop() {
return null;
}
export default function Router({ site, loggedIn, currentUserRole }) {
export default function Router({site, loggedIn, currentUserRole}) {
return (
<BrowserRouter>
<Route path="/:domain">
<ScrollToTop />
<Dash site={site} loggedIn={loggedIn} currentUserRole={currentUserRole} />
<Switch>
<Route exact path={["/:domain/sources", "/:domain/utm_mediums", "/:domain/utm_sources", "/:domain/utm_campaigns", "/:domain/utm_contents", "/:domain/utm_terms"]}>
<Route exact path={["/:domain/sources", "/:domain/utm_mediums", "/:domain/utm_sources", "/:domain/utm_campaigns", "/:domain/utm_contents", "/:domain/utm_terms" ]}>
<SourcesModal site={site} />
</Route>
<Route exact path="/:domain/referrers/Google">
@ -52,19 +49,13 @@ export default function Router({ site, loggedIn, currentUserRole }) {
<ExitPagesModal site={site} />
</Route>
<Route path="/:domain/countries">
<ModalTable title="Top countries" site={site} endpoint={url.apiPath(site, '/countries')} filter={{ country: 'code', country_labels: 'name' }} keyLabel="Country" renderIcon={renderCountryIcon} showPercentage={true}/>
<ModalTable title="Top countries" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/countries`} filter={{country: 'code', country_name: 'name'}} keyLabel="Country" renderIcon={renderCountryIcon} />
</Route>
<Route path="/:domain/regions">
<ModalTable title="Top regions" site={site} endpoint={url.apiPath(site, '/regions')} filter={{ region: 'code', region_labels: 'name' }} keyLabel="Region" renderIcon={renderRegionIcon} />
<ModalTable title="Top regions" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/regions`} filter={{region: 'code', region_name: 'name'}} keyLabel="Region" renderIcon={renderRegionIcon} />
</Route>
<Route path="/:domain/cities">
<ModalTable title="Top cities" site={site} endpoint={url.apiPath(site, '/cities')} filter={{ city: 'code', city_labels: 'name' }} keyLabel="City" renderIcon={renderCityIcon} />
</Route>
<Route path="/:domain/custom-prop-values/:prop_key">
<PropsModal site={site} />
</Route>
<Route path="/:domain/conversions">
<ConversionsModal site={site} />
<ModalTable title="Top cities" site={site} endpoint={`/api/stats/${encodeURIComponent(site.domain)}/cities`} filter={{city: 'code', city_name: 'name'}} keyLabel="City" renderIcon={renderCityIcon} />
</Route>
<Route path={["/:domain/filter/:field"]}>
<FilterModal site={site} />

@ -131,7 +131,7 @@ export default class SiteSwitcher extends React.Component {
domain === this.props.site.domain
? 'font-medium text-gray-900 dark:text-gray-100 cursor-default font-bold'
: 'hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100'
const showHotkey = this.props.loggedIn && this.state.sites.length > 1
const showHotkey = !this.props.loggedIn
return (
<a
href={
@ -151,7 +151,7 @@ export default class SiteSwitcher extends React.Component {
{domain}
</span>
</span>
{showHotkey && index < 9 ? <span>{index + 1}</span> : null}
{showHotkey ? index < 9 && <span>{index + 1}</span> : null}
</a>
)
}
@ -164,14 +164,12 @@ export default class SiteSwitcher extends React.Component {
<React.Fragment>
<div className="py-1">
<a
href={`/${encodeURIComponent(
this.props.site.domain
)}/settings/general`}
href={`/${encodeURIComponent(this.props.site.domain)}/settings`}
className="group flex items-center px-4 py-2 md:text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100"
role="menuitem"
>
<Cog8ToothIcon className="mr-2 h-4 w-4 text-gray-500 dark:text-gray-200 group-hover:text-gray-600 dark:group-hover:text-gray-400 group-focus:text-gray-500 dark:group-focus:text-gray-200" />
Site Settings
Site settings
</a>
</div>
<div className="border-t border-gray-200 dark:border-gray-500"></div>
@ -219,7 +217,7 @@ export default class SiteSwitcher extends React.Component {
className="flex px-4 py-2 md:text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-900 dark:focus:text-gray-100"
role="menuitem"
>
View All
View all
</a>
</React.Fragment>
)
@ -251,10 +249,10 @@ export default class SiteSwitcher extends React.Component {
<Transition
show={this.state.open}
enter="transition ease-out duration-100"
enter="transition ease-out duration-100 transform"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leave="transition ease-in duration-75 transform"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>

@ -12,12 +12,11 @@ function barWidth(count, all, plot) {
export default function Bar({count, all, bg, maxWidthDeduction, children, plot = "visitors"}) {
const width = barWidth(count, all, plot)
const style = maxWidthDeduction ? {maxWidth: `calc(100% - ${maxWidthDeduction})`} : {}
return (
<div
className="w-full h-full relative"
style={style}
className="w-full relative"
style={{maxWidth: `calc(100% - ${maxWidthDeduction})`}}
>
<div
className={`absolute top-0 left-0 h-full ${bg || ''}`}

@ -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,27 +1,20 @@
import React from 'react';
import * as storage from '../../util/storage'
import { isFilteringOnFixedValue } from '../../util/filters'
import ListReport from '../reports/list'
import * as api from '../../api'
import * as url from '../../util/url'
import { VISITORS_METRIC, PERCENTAGE_METRIC, maybeWithCR } from '../reports/metrics';
function Browsers({ query, site }) {
function fetchData() {
return api.get(url.apiPath(site, '/browsers'), query)
}
function getFilterFor(listItem) {
return { browser: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{ browser: 'name' }}
keyLabel="Browser"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -32,19 +25,15 @@ function BrowserVersions({ query, site }) {
return api.get(url.apiPath(site, '/browser-versions'), query)
}
function getFilterFor(listItem) {
if (query.filters.browser === '(not set)') {
return {}
}
return { browser_version: listItem['name'] }
}
const isNotSet = query.filters.browser === '(not set)'
const browserName = isNotSet ? 'Browser' : query.filters.browser
const filter = isNotSet ? {} : { browser_version: 'name' }
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel="Browser version"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
filter={filter}
keyLabel={browserName + ' version'}
query={query}
/>
)
@ -56,16 +45,11 @@ function OperatingSystems({ query, site }) {
return api.get(url.apiPath(site, '/operating-systems'), query)
}
function getFilterFor(listItem) {
return { os: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{ os: 'name' }}
keyLabel="Operating system"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
/>
)
@ -76,19 +60,15 @@ function OperatingSystemVersions({ query, site }) {
return api.get(url.apiPath(site, '/operating-system-versions'), query)
}
function getFilterFor(listItem) {
if (query.filters.os === '(not set)') {
return {}
}
return { os_version: listItem['name'] }
}
const isNotSet = query.filters.os === '(not set)'
const osName = isNotSet ? 'Operating System' : query.filters.os
const filter = isNotSet ? {} : { os_version: 'name' }
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel="Operating System Version"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
filter={filter}
keyLabel={osName + ' version'}
query={query}
/>
)
@ -104,22 +84,29 @@ function ScreenSizes({ query, site }) {
return iconFor(screenSize.name)
}
function getFilterFor(listItem) {
return { screen: listItem['name'] }
function renderTooltipText(screenSize) {
return EXPLANATION[screenSize.name]
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{ screen: 'name' }}
keyLabel="Screen size"
metrics={maybeWithCR([VISITORS_METRIC, PERCENTAGE_METRIC], query)}
query={query}
renderIcon={renderIcon}
tooltipText={renderTooltipText}
/>
)
}
const EXPLANATION = {
'Mobile': 'up to 576px',
'Tablet': '576px to 992px',
'Laptop': '992px to 1440px',
'Desktop': 'above 1440px',
}
function iconFor(screenSize) {
if (screenSize === 'Mobile') {
return (
@ -148,7 +135,7 @@ export default class Devices extends React.Component {
this.tabKey = `deviceTab__${props.site.domain}`
const storedTab = storage.getItem(this.tabKey)
this.state = {
mode: storedTab || 'browser'
mode: storedTab || 'size'
}
}
@ -162,12 +149,12 @@ export default class Devices extends React.Component {
renderContent() {
switch (this.state.mode) {
case 'browser':
if (isFilteringOnFixedValue(this.props.query, 'browser')) {
if (this.props.query.filters.browser) {
return <BrowserVersions site={this.props.site} query={this.props.query} />
}
return <Browsers site={this.props.site} query={this.props.query} />
case 'os':
if (isFilteringOnFixedValue(this.props.query, 'os')) {
if (this.props.query.filters.os) {
return <OperatingSystemVersions site={this.props.site} query={this.props.query} />
}
return <OperatingSystems site={this.props.site} query={this.props.query} />
@ -204,16 +191,22 @@ export default class Devices extends React.Component {
render() {
return (
<div>
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Devices</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Browser', 'browser')}
{this.renderPill('OS', 'os')}
{this.renderPill('Size', 'size')}
<div
className="stats-item flex flex-col mt-6 stats-item--has-header w-full"
>
<div
className="stats-item-header flex flex-col flex-grow relative 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">Devices</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Size', 'size')}
{this.renderPill('Browser', 'browser')}
{this.renderPill('OS', 'os')}
</div>
</div>
{this.renderContent()}
</div>
{this.renderContent()}
</div>
)
}

@ -1,4 +1,4 @@
import {parseUTCDate, formatMonthYYYY, formatDayShort} from '../../util/date'
import { parseUTCDate, formatMonthYYYY, formatDay, formatDayShort } from '../../util/date'
const browserDateFormat = Intl.DateTimeFormat(navigator.language, { hour: 'numeric' })
@ -6,13 +6,32 @@ const is12HourClock = function () {
return browserDateFormat.resolvedOptions().hour12
}
const parseISODate = function (isoDate) {
const date = parseUTCDate(isoDate)
const minutes = date.getMinutes();
const year = date.getFullYear()
return { date, minutes, year }
}
const getYearString = (options, year) => options.shouldShowYear ? ` ${year}` : ''
const formatHours = function (isoDate) {
const monthIndex = 1
const dateParts = isoDate.split(/[^0-9]/);
dateParts[monthIndex] = dateParts[monthIndex] - 1
const localDate = new Date(...dateParts)
return browserDateFormat.format(localDate)
}
const monthIntervalFormatter = {
long(isoDate, options) {
const formatted = this.short(isoDate, options)
return options.isBucketPartial ? `Partial of ${formatted}` : formatted
},
short(isoDate, _options) {
return formatMonthYYYY(parseUTCDate(isoDate))
const { date } = parseISODate(isoDate)
return formatMonthYYYY(date)
}
}
@ -22,16 +41,19 @@ const weekIntervalFormatter = {
return options.isBucketPartial ? `Partial week of ${formatted}` : `Week of ${formatted}`
},
short(isoDate, options) {
return formatDayShort(parseUTCDate(isoDate), options.shouldShowYear)
const { date, year } = parseISODate(isoDate)
return `${formatDayShort(date)}${getYearString(options, year)}`
}
}
const dateIntervalFormatter = {
long(isoDate, _options) {
return parseUTCDate(isoDate).format('ddd, D MMM')
const { date } = parseISODate(isoDate)
return formatDay(date)
},
short(isoDate, options) {
return formatDayShort(parseUTCDate(isoDate), options.shouldShowYear)
const { date, year } = parseISODate(isoDate)
return `${formatDayShort(date)}${getYearString(options, year)}`
}
}
@ -40,10 +62,12 @@ const hourIntervalFormatter = {
return this.short(isoDate, options)
},
short(isoDate, _options) {
const formatted = formatHours(isoDate)
if (is12HourClock()) {
return parseUTCDate(isoDate).format('ha')
return formatted.replace(' ', '').toLowerCase()
} else {
return parseUTCDate(isoDate).format('HH:mm')
return formatted.replace(/[^0-9]/g, '').concat(":00")
}
}
}
@ -60,10 +84,12 @@ const minuteIntervalFormatter = {
short(isoDate, options) {
if (options.period === 'realtime') return isoDate + 'm'
const { minutes } = parseISODate(isoDate)
const formatted = formatHours(isoDate)
if (is12HourClock()) {
return parseUTCDate(isoDate).format('h:mma')
return formatted.replace(' ', ':' + (minutes < 10 ? `0${minutes}` : minutes)).toLowerCase()
} else {
return parseUTCDate(isoDate).format('HH:mm')
return formatted.replace(/[^0-9]/g, '').concat(":" + (minutes < 10 ? `0${minutes}` : minutes))
}
}
}

@ -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">&uarr;</span><span>${tooltipData.comparisonDifference}%</span>` : ""}
${tooltipData.comparisonDifference < 0 ? `<span class="font-semibold text-sm text-red-400">&darr;</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,108 +1,159 @@
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import { parsePrefix } from '../../util/filters'
export function getGraphableMetrics(query, site) {
const isRealtime = query.period === 'realtime'
const goalFilter = query.filters.goal
const pageFilter = query.filters.page
if (isRealtime && goalFilter) {
return ["visitors"]
} else if (isRealtime) {
return ["visitors", "pageviews"]
} else if (goalFilter && canGraphRevenueMetrics(goalFilter, site)) {
return ["visitors", "events", "average_revenue", "total_revenue", "conversion_rate"]
} else if (goalFilter) {
return ["visitors", "events", "conversion_rate"]
} else if (pageFilter) {
return ["visitors", "visits", "pageviews", "bounce_rate", "time_on_page"]
} else {
return ["visitors", "visits", "pageviews", "views_per_visit", "bounce_rate", "visit_duration"]
}
}
// Revenue metrics can only be graphed if:
// * The query is filtered by at least one revenue goal
// * All revenue goals in filter have the same currency
function canGraphRevenueMetrics(goalFilter, site) {
const goalsInFilter = parsePrefix(goalFilter).values
const revenueGoalsInFilter = site.revenueGoals.filter((rg) => {
return goalsInFilter.includes(rg.event_name)
})
const singleCurrency = revenueGoalsInFilter.every((rg) => {
return rg.currency === revenueGoalsInFilter[0].currency
})
return revenueGoalsInFilter.length > 0 && singleCurrency
import dateFormatter from './date-formatter.js'
export const METRIC_MAPPING = {
'Unique visitors (last 30 min)': 'visitors',
'Pageviews (last 30 min)': 'pageviews',
'Unique visitors': 'visitors',
'Visit duration': 'visit_duration',
'Total pageviews': 'pageviews',
'Bounce rate': 'bounce_rate',
'Unique conversions': 'conversions',
}
export const METRIC_LABELS = {
'visitors': 'Visitors',
'pageviews': 'Pageviews',
'events': 'Total Conversions',
'views_per_visit': 'Views per Visit',
'visits': 'Visits',
'bounce_rate': 'Bounce Rate',
'visit_duration': 'Visit Duration',
'conversions': 'Converted Visitors',
'conversion_rate': 'Conversion Rate',
'average_revenue': 'Average Revenue',
'total_revenue': 'Total Revenue',
}
export const METRIC_FORMATTER = {
'visitors': numberFormatter,
'pageviews': numberFormatter,
'events': numberFormatter,
'visits': numberFormatter,
'views_per_visit': (number) => (number),
'bounce_rate': (number) => (`${number}%`),
'visit_duration': durationFormatter,
'conversions': numberFormatter,
'conversion_rate': (number) => (`${number}%`),
'total_revenue': numberFormatter,
'average_revenue': numberFormatter,
}
const buildComparisonDataset = function(comparisonPlot) {
if (!comparisonPlot) return []
export const LoadingState = {
loading: 'loading',
refreshing: 'refreshing',
loaded: 'loaded',
isLoadingOrRefreshing: function (state) { return [this.loading, this.refreshing].includes(state) },
isLoadedOrRefreshing: function (state) { return [this.loaded, this.refreshing].includes(state) }
}
const renderBucketLabel = function(query, graphData, label, comparison = false) {
let isPeriodFull = graphData.full_intervals?.[label]
if (comparison) isPeriodFull = true
return [{
data: comparisonPlot,
borderColor: 'rgba(60,70,110,0.2)',
pointBackgroundColor: 'rgba(60,70,110,0.2)',
pointHoverBackgroundColor: 'rgba(60, 70, 110)',
yAxisID: 'yComparison',
}]
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 buildDashedDataset = function(plot, presentIndex) {
if (!presentIndex) return []
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 dashedPart = plot.slice(presentIndex - 1, presentIndex + 1);
const dashedPlot = (new Array(presentIndex - 1)).concat(dashedPart)
const label = renderBucketLabel(query, graphData, graphData.labels[data.dataIndex])
const comparisonLabel = comparisonData && renderBucketLabel(query, graphData, graphData.comparison_labels[data.dataIndex], true)
return [{
data: dashedPlot,
borderDash: [3, 3],
borderColor: 'rgba(101,116,205)',
pointHoverBackgroundColor: 'rgba(71, 87, 193)',
yAxisID: 'y',
}]
const value = data?.raw || 0
const comparisonValue = comparisonData?.raw || 0
const comparisonDifference = comparisonData && calculatePercentageDifference(comparisonValue, value)
const metricFormatter = METRIC_FORMATTER[metric]
const formattedValue = metricFormatter(value)
const formattedComparisonValue = comparisonData && metricFormatter(comparisonValue)
return { label, formattedValue, comparisonLabel, formattedComparisonValue, comparisonDifference }
}
const buildMainPlotDataset = function(plot, presentIndex) {
const data = presentIndex ? plot.slice(0, presentIndex) : plot
export const GraphTooltip = (graphData, metric, query) => {
return (context) => {
const tooltipModel = context.tooltip;
const offset = document.getElementById("main-graph-canvas").getBoundingClientRect()
// Tooltip Element
let tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
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;
}
// Stop if no tooltip showing
if (tooltipModel.opacity === 0) {
tooltipEl.style.display = 'none';
return;
}
// Set Tooltip Body
if (tooltipModel.body) {
const tooltipData = buildTooltipData(query, graphData, metric, tooltipModel)
let innerHtml = `
<div 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 ? `<span class='font-semibold text-sm'>${tooltipData.comparisonDifference}%</span>` : ''}
</div>
<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>
<span class='font-semibold italic'>${graphData.interval === 'month' ? 'Click to view month' : graphData.interval === 'date' ? 'Click to view day' : ''}</span>
</div>` : ''}
`;
tooltipEl.innerHTML = innerHtml;
}
tooltipEl.style.display = null;
}
}
return [{
data: data,
borderColor: 'rgba(101,116,205)',
pointBackgroundColor: 'rgba(101,116,205)',
pointHoverBackgroundColor: 'rgba(71, 87, 193)',
yAxisID: 'y',
}]
const truncateToPresentIndex = function(array, presentIndex) {
return array.slice(0, presentIndex)
}
export const buildDataSet = (plot, comparisonPlot, present_index, ctx, label) => {
@ -113,13 +164,72 @@ export const buildDataSet = (plot, comparisonPlot, present_index, ctx, label) =>
prev_gradient.addColorStop(0, 'rgba(101,116,205, 0.075)');
prev_gradient.addColorStop(1, 'rgba(101,116,205, 0)');
const defaultOptions = { label, borderWidth: 3, pointBorderColor: "transparent", pointHoverRadius: 4, backgroundColor: gradient, fill: true }
const dataset = [
...buildMainPlotDataset(plot, present_index),
...buildDashedDataset(plot, present_index),
...buildComparisonDataset(comparisonPlot)
]
let comparisonDataSet = []
if (comparisonPlot) {
comparisonDataSet = [
{
label,
data: truncateToPresentIndex(comparisonPlot, present_index),
borderWidth: 3,
borderColor: 'rgba(60,70,110,0.2)',
pointBackgroundColor: 'rgba(60,70,110,0.2)',
pointHoverBackgroundColor: 'rgba(60, 70, 110)',
pointBorderColor: 'transparent',
pointHoverRadius: 4,
backgroundColor: gradient,
fill: true,
yAxisID: 'yComparison',
}
]
}
return dataset.map((item) => Object.assign(item, defaultOptions))
if (present_index) {
var dashedPart = plot.slice(present_index - 1, present_index + 1);
var dashedPlot = (new Array(present_index - 1)).concat(dashedPart)
const _plot = truncateToPresentIndex([...plot], present_index)
return [
{
label,
data: _plot,
borderWidth: 3,
borderColor: 'rgba(101,116,205)',
pointBackgroundColor: 'rgba(101,116,205)',
pointHoverBackgroundColor: 'rgba(71, 87, 193)',
pointBorderColor: 'transparent',
pointHoverRadius: 4,
backgroundColor: gradient,
fill: true,
yAxisID: 'y',
},
{
label,
data: dashedPlot,
borderWidth: 3,
borderDash: [3, 3],
borderColor: 'rgba(101,116,205)',
pointHoverBackgroundColor: 'rgba(71, 87, 193)',
pointBorderColor: 'transparent',
pointHoverRadius: 4,
backgroundColor: gradient,
fill: true,
yAxisID: 'y',
}
].concat(comparisonDataSet)
} else {
return [
{
label,
data: plot,
borderWidth: 3,
borderColor: 'rgba(101,116,205)',
pointHoverBackgroundColor: 'rgba(71, 87, 193)',
pointBorderColor: 'transparent',
pointHoverRadius: 4,
backgroundColor: gradient,
fill: true,
yAxisID: 'y',
}
].concat(comparisonDataSet)
}
}

@ -4,9 +4,8 @@ import React, { Fragment, useCallback, useEffect } from 'react';
import classNames from 'classnames'
import * as storage from '../../util/storage'
import { isKeyPressed } from '../../keybinding.js'
import { monthsBetweenDates } from '../../util/date.js'
const INTERVAL_LABELS = {
export const INTERVAL_LABELS = {
'minute': 'Minutes',
'hour': 'Hours',
'date': 'Days',
@ -14,19 +13,11 @@ const INTERVAL_LABELS = {
'month': 'Months'
}
function validIntervals(site, query) {
if (query.period === "custom" && monthsBetweenDates(query.from, query.to) > 12) {
return ["week", "month"]
} else {
return site.validIntervalsByPeriod[query.period]
}
}
function getStoredInterval(period, domain) {
export const getStoredInterval = function(period, domain) {
return storage.getItem(`interval__${period}__${domain}`)
}
function storeInterval(period, domain, interval) {
export const storeInterval = function(period, domain, interval) {
storage.setItem(`interval__${period}__${domain}`, interval)
}
@ -41,69 +32,50 @@ function subscribeKeybinding(element) {
}, [handleKeyPress])
}
export const getCurrentInterval = function(site, query) {
const options = validIntervals(site, query)
const storedInterval = getStoredInterval(query.period, site.domain)
const defaultInterval = [...options].pop()
if (storedInterval && options.includes(storedInterval)) {
return storedInterval
} else {
return defaultInterval
}
function DropdownItem({ option, currentInterval, updateInterval }) {
return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => (
<span className={classNames({
'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer': active,
'text-gray-700 dark:text-gray-200': !active,
'font-bold cursor-none select-none': option == currentInterval,
}, 'block px-4 py-2 text-sm')}>
{ INTERVAL_LABELS[option] }
</span>
)}
</Menu.Item>
)
}
export function IntervalPicker({ query, site, onIntervalUpdate }) {
export function IntervalPicker({ graphData, query, site, updateInterval }) {
if (query.period == 'realtime') return null
const menuElement = React.useRef(null)
const options = validIntervals(site, query)
const currentInterval = getCurrentInterval(site, query)
const menuElement = React.useRef(null)
subscribeKeybinding(menuElement)
function updateInterval(interval) {
storeInterval(query.period, site.domain, interval)
onIntervalUpdate(interval)
}
function renderDropdownItem(option) {
return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => (
<span className={classNames({
'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer': active,
'text-gray-700 dark:text-gray-200': !active,
'font-bold cursor-none select-none': option == currentInterval,
}, 'block px-4 py-2 text-sm')}>
{INTERVAL_LABELS[option]}
</span>
)}
</Menu.Item>
)
}
const currentInterval = graphData?.interval
const options = site.validIntervalsByPeriod[query.period]
return (
<Menu as="div" className="relative inline-block pl-2">
{({ open }) => (
<>
<Menu.Button ref={menuElement} className="text-sm inline-flex focus:outline-none text-gray-700 dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600 items-center">
{INTERVAL_LABELS[currentInterval]}
{ INTERVAL_LABELS[currentInterval] }
<ChevronDownIcon className="ml-1 h-4 w-4" aria-hidden="true" />
</Menu.Button>
<Transition
as={Fragment}
show={open}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95">
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform 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>
{options.map(renderDropdownItem)}
{ options.map((option) => DropdownItem({ option, currentInterval, updateInterval })) }
</Menu.Items>
</Transition>
</>

@ -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>
)
}

@ -3,115 +3,77 @@ import { Tooltip } from '../../util/tooltip'
import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'
import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import * as storage from '../../util/storage'
import { formatDateRange } from '../../util/date.js'
import { getGraphableMetrics } from "./graph-util.js";
function Maybe({condition, children}) {
if (condition) {
return children
} else {
return null
}
}
function renderPercentageComparison(name, comparison, forceDarkBg = false) {
const formattedComparison = numberFormatter(Math.abs(comparison))
const defaultClassName = classNames({
"pl-2 text-xs dark:text-gray-100": !forceDarkBg,
"pl-2 text-xs text-gray-100": forceDarkBg
})
const noChangeClassName = classNames({
"pl-2 text-xs text-gray-700 dark:text-gray-300": !forceDarkBg,
"pl-2 text-xs text-gray-300": forceDarkBg
})
if (comparison > 0) {
const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
} else if (comparison < 0) {
const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400'
return <span className={defaultClassName}><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
} else if (comparison === 0) {
return <span className={noChangeClassName}>&#12336; 0%</span>
} else {
return null
import { METRIC_MAPPING } from './graph-util'
export default class TopStats extends React.Component {
renderComparison(name, comparison) {
const formattedComparison = numberFormatter(Math.abs(comparison))
if (comparison > 0) {
const color = name === 'Bounce rate' ? 'text-red-400' : 'text-green-500'
return <span className="text-xs dark:text-gray-100"><span className={color + ' font-bold'}>&uarr;</span> {formattedComparison}%</span>
} else if (comparison < 0) {
const color = name === 'Bounce rate' ? 'text-green-500' : 'text-red-400'
return <span className="text-xs dark:text-gray-100"><span className={color + ' font-bold'}>&darr;</span> {formattedComparison}%</span>
} else if (comparison === 0) {
return <span className="text-xs text-gray-700 dark:text-gray-300">&#12336; 0%</span>
}
}
}
function topStatNumberShort(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else if (['average revenue', 'total revenue'].includes(name.toLowerCase())) {
return value?.short
} else {
return numberFormatter(value)
topStatNumberShort(stat) {
if (['visit duration', 'time on page'].includes(stat.name.toLowerCase())) {
return durationFormatter(stat.value)
} else if (['bounce rate', 'conversion rate'].includes(stat.name.toLowerCase())) {
return stat.value + '%'
} else {
return numberFormatter(stat.value)
}
}
}
function topStatNumberLong(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
return value + '%'
} else if (['average revenue', 'total revenue'].includes(name.toLowerCase())) {
return value?.long
} else {
return (value || 0).toLocaleString()
topStatNumberLong(stat) {
if (['visit duration', 'time on page'].includes(stat.name.toLowerCase())) {
return durationFormatter(stat.value)
} else if (['bounce rate', 'conversion rate'].includes(stat.name.toLowerCase())) {
return stat.value + '%'
} else {
return stat.value.toLocaleString()
}
}
}
export default function TopStats(props) {
const {site, query, data, onMetricUpdate, tooltipBoundary, lastLoadTimestamp} = props
function tooltip(stat) {
topStatTooltip(stat) {
let statName = stat.name.toLowerCase()
statName = stat.value === 1 ? statName.slice(0, -1) : statName
return (
<div>
{query.comparison && <div className="whitespace-nowrap">
{topStatNumberLong(stat.name, stat.value)} vs. {topStatNumberLong(stat.name, stat.comparison_value)} {statName}
<span className="ml-2">{renderPercentageComparison(stat.name, stat.change, true)}</span>
</div>}
{!query.comparison && <div className="whitespace-nowrap">
{topStatNumberLong(stat.name, stat.value)} {statName}
</div>}
{stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp}/>s ago</p>}
<div className="whitespace-nowrap">{this.topStatNumberLong(stat)} {statName}</div>
{stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={this.props.lastLoadTimestamp}/>s ago</p>}
</div>
)
}
function canMetricBeGraphed(stat) {
const graphableMetrics = getGraphableMetrics(query, site)
return stat.graph_metric && graphableMetrics.includes(stat.graph_metric)
canMetricBeGraphed(stat) {
const isTotalUniqueVisitors = this.props.query.filters.goal && stat.name === 'Unique visitors'
const isKnownMetric = Object.keys(METRIC_MAPPING).includes(stat.name)
return isKnownMetric && !isTotalUniqueVisitors
}
function maybeUpdateMetric(stat) {
if (canMetricBeGraphed(stat)) {
storage.setItem(`metric__${site.domain}`, stat.graph_metric)
onMetricUpdate(stat.graph_metric)
maybeUpdateMetric(stat) {
if (this.canMetricBeGraphed(stat)) {
this.props.updateMetric(METRIC_MAPPING[stat.name])
}
}
function blinkingDot() {
blinkingDot() {
return (
<div key="dot" className="block pulsating-circle" style={{ left: '125px', top: '52px' }}></div>
)
}
function getStoredMetric() {
return storage.getItem(`metric__${site.domain}`)
}
function renderStatName(stat) {
const isSelected = stat.graph_metric === getStoredMetric()
renderStatName(stat) {
const { metric } = this.props
const isSelected = metric === METRIC_MAPPING[stat.name]
const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)
@ -128,45 +90,32 @@ export default function TopStats(props) {
)
}
function renderStat(stat, index) {
const className = classNames('px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none', {
'cursor-pointer': canMetricBeGraphed(stat),
'lg:border-l border-gray-300': index > 0,
'border-r lg:border-r-0': index % 2 === 0
})
render() {
const { topStatData, query } = this.props
return (
<Tooltip key={stat.name} info={tooltip(stat, query)} className={className} onClick={() => { maybeUpdateMetric(stat) }} boundary={tooltipBoundary}>
{renderStatName(stat)}
<div className="my-1 space-y-2">
<div>
<span className="flex items-center justify-between whitespace-nowrap">
<p className="font-bold text-xl dark:text-gray-100" id={stat.graph_metric}>{topStatNumberShort(stat.name, stat.value)}</p>
<Maybe condition={!query.comparison}>
{ renderPercentageComparison(stat.name, stat.change) }
</Maybe>
</span>
<Maybe condition={query.comparison}>
<p className="text-xs dark:text-gray-100">{ formatDateRange(site, data.from, data.to) }</p>
</Maybe>
</div>
<Maybe condition={query.comparison}>
<div>
<p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ topStatNumberShort(stat.name, stat.comparison_value) }</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{ formatDateRange(site, data.comparing_from, data.comparing_to) }</p>
const stats = topStatData && topStatData.top_stats.map((stat, index) => {
const className = classNames('px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none', {
'cursor-pointer': this.canMetricBeGraphed(stat),
'lg:border-l border-gray-300': index > 0,
'border-r lg:border-r-0': index % 2 === 0
})
return (
<Tooltip key={stat.name} info={this.topStatTooltip(stat)} className={className} onClick={() => { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}>
{this.renderStatName(stat)}
<div className="flex items-center justify-between my-1 whitespace-nowrap">
<b className="mr-4 text-xl md:text-2xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat)}</b>
{this.renderComparison(stat.name, stat.change)}
</div>
</Maybe>
</div>
</Tooltip>
)
}
</Tooltip>
)
})
const stats = data && data.top_stats.map(renderStat)
if (stats && query && query.period === 'realtime') {
stats.push(this.blinkingDot())
}
if (stats && query.period === 'realtime') {
stats.push(blinkingDot())
return stats || null;
}
return stats || null;
}

@ -1,153 +1,526 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import React from 'react';
import { withRouter, Link } from 'react-router-dom'
import {Chart, LineController, LineElement, PointElement, CategoryScale, LinearScale, Tooltip} from 'chart.js';
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, LoadingState} 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 calculateMaximumY = function(dataset) {
const yAxisValues = dataset
.flatMap((item) => item.data)
.map((item) => item || 0)
return api.get(url.apiPath(site, '/top-stats'), q)
if (yAxisValues) {
return Math.max(...yAxisValues)
} else {
return 1
}
}
function fetchMainGraph(site, query, metric, interval) {
const params = {metric, interval}
return api.get(url.apiPath(site, '/main-graph'), query, params)
}
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
};
}
export default function VisitorGraph(props) {
const {site, query, lastLoadTimestamp} = props
const isRealtime = query.period === 'realtime'
const isDarkTheme = document.querySelector('html').classList.contains('dark') || false
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.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
Chart.register([LineController, LineElement, PointElement, CategoryScale, LinearScale, Tooltip])
const topStatsBoundary = useRef(null)
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.onClick.bind(this),
scales: {
y: {
min: 0,
suggestedMax: calculateMaximumY(dataSet),
ticks: {
callback: METRIC_FORMATTER[metric],
maxTicksLimit: 8,
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: {
maxTicksLimit: 8,
callback: function (val, _index, _ticks) {
// realtime graph labels are not date strings
const hasMultipleYears = typeof graphData.labels[0] !== 'string' ? false :
graphData.labels
// date format: 'yyyy-mm-dd'; maps to -> 'yyyy'
.map(date => date.split('-')[0])
// reject any year that appears at a previous index, unique years only
.filter((value, index, list) => list.indexOf(value) === index)
.length > 1
const [topStatData, setTopStatData] = useState(null)
const [topStatsLoading, setTopStatsLoading] = useState(true)
const [graphData, setGraphData] = useState(null)
const [graphLoading, setGraphLoading] = useState(true)
if (graphData.interval === 'hour' && query.period !== 'day') {
const date = dateFormatter({
interval: "date",
longForm: false,
period: query.period,
shouldShowYear: hasMultipleYears,
})(this.getLabelForValue(val))
// 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)
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}`
}
const onIntervalUpdate = useCallback((newInterval) => {
setGraphData(null)
setGraphRefreshing(true)
fetchGraphData(getStoredMetric(), newInterval)
}, [query])
if (graphData.interval === 'minute' && query.period !== 'realtime') {
return dateFormatter({
interval: "hour", longForm: false, period: query.period,
})(this.getLabelForValue(val))
}
const onMetricUpdate = useCallback((newMetric) => {
setGraphData(null)
setGraphRefreshing(true)
fetchGraphData(newMetric, getCurrentInterval(site, query))
}, [query])
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,
}
}
});
}
useEffect(() => {
setTopStatData(null)
setTopStatsLoading(true)
setGraphData(null)
setGraphLoading(true)
fetchTopStatsAndGraphData()
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;
}
}
if (isRealtime) {
document.addEventListener('tick', fetchTopStatsAndGraphData)
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
) {
return () => {
document.removeEventListener('tick', fetchTopStatsAndGraphData)
if (graphData) {
if (this.chart) {
this.chart.destroy();
}
this.chart = this.regenerateChart();
this.chart.update();
}
if (tooltip) {
tooltip.style.display = 'none';
}
}
}, [query])
useEffect(() => {
if (topStatData) { storeTopStatsContainerHeight() }
}, [topStatData])
if (!graphData) {
if (this.chart) {
this.chart.destroy();
}
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)
if (tooltip) {
tooltip.style.display = 'none';
}
}
}
const interval = getCurrentInterval(site, query)
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)
}
fetchGraphData(metric, interval)
/**
* 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
}
function fetchGraphData(metric, interval) {
fetchMainGraph(site, query, metric, interval)
.then((res) => {
setGraphData(res)
setGraphLoading(false)
setGraphRefreshing(false)
})
onClick(e) {
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
const date = this.chart.data.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,
}
)
}
}
pollExportReady() {
if (document.cookie.includes('exporting')) {
setTimeout(this.pollExportReady.bind(this), 1000);
} else {
this.setState({exported: 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>
)
}
}
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>
)
}
}
// 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) {
getTopStatsHeight() {
if (this.props.topStatData) {
return 'auto'
} else {
return `${storage.getItem(`topStatsHeight__${site.domain}`) || 89}px`
return `${storage.getItem(`topStatsHeight__${this.props.site.domain}`) || 89}px`
}
}
render() {
const { mainGraphRefreshing, updateMetric, updateInterval, metric, topStatData, query, site, graphData, lastLoadTimestamp } = this.props
const canvasClass = classNames('mt-4 select-none', {'cursor-pointer': !['minute', 'hour'].includes(graphData?.interval)})
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>
<div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{height: this.getTopStatsHeight()}}>
<TopStats query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={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} />
{mainGraphRefreshing && renderLoader()}
<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={updateInterval}/>
</div>
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} />
<FadeIn show={graphData}>
<div className="relative h-96 w-full">
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
</div>
</FadeIn>
</div>
</div>
)
}
}
const LineGraphWithRouter = withRouter(LineGraph)
export default class VisitorGraph extends React.Component {
constructor(props) {
super(props)
this.state = {
topStatsLoadingState: LoadingState.loading,
mainGraphLoadingState: LoadingState.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: LoadingState.refreshing, graphData: null }, this.fetchGraphData)
}
}
onVisible() {
this.setState({mainGraphLoadingState: LoadingState.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 } = this.state;
const { query } = this.props
if (query !== prevProps.query) {
this.setState({ mainGraphLoadingState: LoadingState.loading, topStatsLoadingState: LoadingState.loading, graphData: null, topStatData: null }, this.fetchGraphData)
this.fetchTopStatData()
}
if (metric !== prevState.metric) {
this.setState({mainGraphLoadingState: LoadingState.refreshing}, this.fetchGraphData)
}
}
resetMetric() {
const { topStatData } = this.state
const { query, site } = this.props
const savedMetric = storage.getItem(`metric__${site.domain}`)
const selectableMetrics = topStatData && topStatData.top_stats.map(({ name }) => METRIC_MAPPING[name]).filter(name => name)
const canSelectSavedMetric = selectableMetrics && selectableMetrics.includes(savedMetric)
if (query.filters.goal) {
this.setState({ metric: 'conversions' })
} else if (canSelectSavedMetric) {
this.setState({ metric: savedMetric })
} else {
this.setState({ metric: 'visitors' })
}
}
componentWillUnmount() {
document.removeEventListener('tick', this.fetchGraphData)
document.removeEventListener('tick', this.fetchTopStatData)
}
storeTopStatsContainerHeight() {
storage.setItem(`topStatsHeight__${this.props.site.domain}`, document.getElementById('top-stats-container').clientHeight)
}
updateMetric(clickedMetric) {
if (this.state.metric == clickedMetric) return
storage.setItem(`metric__${this.props.site.domain}`, clickedMetric)
this.setState({ metric: clickedMetric, graphData: null })
}
fetchGraphData() {
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: LoadingState.loaded, graphData: res })
return res
})
.catch((err) => {
console.log(err)
this.setState({ mainGraphLoadingState: LoadingState.loaded, graphData: false })
})
}
fetchTopStatData() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, this.props.query)
.then((res) => {
this.setState({ topStatsLoadingState: LoadingState.loaded, topStatData: res }, () => {
this.storeTopStatsContainerHeight()
this.resetMetric()
})
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 mainGraphRefreshing = (mainGraphLoadingState === LoadingState.refreshing)
const topStatAndGraphLoaded = !!(topStatData && graphData)
const shouldShow =
topStatsLoadingState === LoadingState.loaded &&
LoadingState.isLoadedOrRefreshing(mainGraphLoadingState) &&
(topStatData && mainGraphRefreshing || topStatAndGraphLoaded)
return (
<FadeIn show={shouldShow}>
<LineGraphWithRouter mainGraphRefreshing={mainGraphRefreshing} graphData={graphData} topStatData={topStatData} site={site} query={query} darkTheme={theme} metric={metric} updateMetric={this.updateMetric} updateInterval={this.updateInterval} lastLoadTimestamp={this.props.lastLoadTimestamp} />
</FadeIn>
</div>
)
)
}
render() {
const {mainGraphLoadingState, topStatsLoadingState} = this.state
const showLoader =
[mainGraphLoadingState, topStatsLoadingState].includes(LoadingState.loading) &&
mainGraphLoadingState !== LoadingState.refreshing
return (
<LazyLoader onVisible={this.onVisible}>
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}>
{showLoader && renderLoader()}
{this.renderInner()}
</div>
</LazyLoader>
)
}
}
function renderLoader() {

@ -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
}
}

@ -6,7 +6,6 @@ import CountriesMap from './map'
import * as api from '../../api'
import {apiPath, sitePath} from '../../util/url'
import ListReport from '../reports/list'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics';
function Countries({query, site, onClick}) {
function fetchData() {
@ -19,17 +18,12 @@ function Countries({query, site, onClick}) {
return <span className="mr-1">{country.flag}</span>
}
function getFilterFor(listItem) {
return { country: listItem['code'], country_labels: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{country: 'code', country_name: 'name'}}
onClick={onClick}
keyLabel="Country"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/countries')}
query={query}
renderIcon={renderIcon}
@ -47,17 +41,12 @@ function Regions({query, site, onClick}) {
return <span className="mr-1">{region.country_flag}</span>
}
function getFilterFor(listItem) {
return {region: listItem['code'], region_labels: listItem['name']}
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{region: 'code', region_name: 'name'}}
onClick={onClick}
keyLabel="Region"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/regions')}
query={query}
renderIcon={renderIcon}
@ -75,16 +64,11 @@ function Cities({query, site}) {
return <span className="mr-1">{city.country_flag}</span>
}
function getFilterFor(listItem) {
return {city: listItem['code'], city_labels: listItem['name']}
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{city: 'code', city_name: 'name'}}
keyLabel="City"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={sitePath(site, '/cities')}
query={query}
renderIcon={renderIcon}
@ -183,19 +167,25 @@ export default class Locations extends React.Component {
render() {
return (
<div>
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Locations'}
</h3>
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Map', 'map') }
{ this.renderPill('Countries', 'countries') }
{ this.renderPill('Regions', 'regions') }
{ this.renderPill('Cities', 'cities') }
<div
className="stats-item flex flex-col w-full mt-6 stats-item--has-header"
>
<div
className="stats-item-header flex flex-col flex-grow bg-white dark:bg-gray-825 shadow-xl rounded p-4 relative"
>
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Locations'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Map', 'map') }
{ this.renderPill('Countries', 'countries') }
{ this.renderPill('Regions', 'regions') }
{ this.renderPill('Cities', 'cities') }
</div>
</div>
{ this.renderContent() }
</div>
{this.renderContent()}
</div>
)
}

@ -121,7 +121,7 @@ class Countries extends React.Component {
this.props.query,
{
country: country.code,
country_labels: country.name
country_name: country.name
}
)
}

@ -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,12 +1,11 @@
import React from "react";
import { Link, withRouter } from 'react-router-dom'
import { Link , withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
import {parseQuery} from '../../query'
class EntryPagesModal extends React.Component {
constructor(props) {
@ -25,12 +24,12 @@ class EntryPagesModal extends React.Component {
}
loadPages() {
const { query, page } = this.state;
const {query, page} = this.state;
api.get(
`/api/stats/${encodeURIComponent(this.props.site.domain)}/entry-pages`,
query,
{ limit: 100, page }
{limit: 100, page}
)
.then(
(res) => this.setState((state) => ({
@ -43,11 +42,11 @@ class EntryPagesModal extends React.Component {
loadMore() {
const { page } = this.state;
this.setState({ loading: true, page: page + 1 }, this.loadPages.bind(this))
this.setState({loading: true, page: page + 1}, this.loadPages.bind(this))
}
formatBounceRate(page) {
if (typeof (page.bounce_rate) === 'number') {
if (typeof(page.bounce_rate) === 'number') {
return `${page.bounce_rate}%`;
}
return '-';
@ -79,7 +78,7 @@ class EntryPagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2 truncate">
<td className="p-2">
<Link
to={{
pathname: `/${encodeURIComponent(this.props.site.domain)}`,
@ -87,12 +86,12 @@ class EntryPagesModal extends React.Component {
}}
className="hover:underline"
>
{trimURL(page.name, 40)}
{page.name}
</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visits)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.unique_entrances)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_entrances)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{durationFormatter(page.visit_duration)}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.conversion_rate)}%</td>}
</tr>
@ -131,13 +130,13 @@ class EntryPagesModal extends React.Component {
</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Visitors </th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >{this.label()} </th>
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Entrances </th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Visit Duration </th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Entrances </th> }
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Visit Duration </th> }
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >CR </th>}
</tr>
</thead>
<tbody>
{this.state.pages.map(this.renderPage.bind(this))}
{ this.state.pages.map(this.renderPage.bind(this)) }
</tbody>
</table>
</main>
@ -149,8 +148,8 @@ class EntryPagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{this.renderBody()}
{this.renderLoading()}
{ this.renderBody() }
{ this.renderLoading() }
</Modal>
)
}

@ -5,8 +5,8 @@ import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
import {parseQuery} from '../../query'
class ExitPagesModal extends React.Component {
constructor(props) {
super(props)
@ -24,18 +24,18 @@ class ExitPagesModal extends React.Component {
}
loadPages() {
const { query, page } = this.state;
const {query, page} = this.state;
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/exit-pages`, query, { limit: 100, page })
.then((res) => this.setState((state) => ({ loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100 })))
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/exit-pages`, query, {limit: 100, page})
.then((res) => this.setState((state) => ({loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100})))
}
loadMore() {
this.setState({ loading: true, page: this.state.page + 1 }, this.loadPages.bind(this))
this.setState({loading: true, page: this.state.page + 1}, this.loadPages.bind(this))
}
formatPercentage(number) {
if (typeof (number) === 'number') {
if (typeof(number) === 'number') {
return number + '%'
} else {
return '-'
@ -68,12 +68,12 @@ class ExitPagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2 truncate">
<Link to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString() }} className="hover:underline">{trimURL(page.name, 40)}</Link>
<td className="p-2">
<Link to={{pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString()}} className="hover:underline">{page.name}</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visits)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.unique_exits)}</td>
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.total_exits)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatPercentage(page.exit_rate)}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.conversion_rate)}%</td>}
</tr>
@ -114,7 +114,7 @@ class ExitPagesModal extends React.Component {
</tr>
</thead>
<tbody>
{this.state.pages.map(this.renderPage.bind(this))}
{ this.state.pages.map(this.renderPage.bind(this)) }
</tbody>
</table>
</main>
@ -126,8 +126,8 @@ class ExitPagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{this.renderBody()}
{this.renderLoading()}
{ this.renderBody() }
{ this.renderLoading() }
</Modal>
)
}

@ -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)

@ -4,7 +4,7 @@ import { Link, withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter from '../../util/number-formatter'
import {parseQuery} from '../../query'
import {parseQuery, toHuman} from '../../query'
import RocketIcon from './rocket-icon'
class GoogleKeywordsModal extends React.Component {
@ -66,7 +66,7 @@ class GoogleKeywordsModal extends React.Component {
<RocketIcon />
<div className="text-lg">The site is not connected to Google Search Keywords</div>
<div className="text-lg">Configure the integration to view search terms</div>
<a href={`/${encodeURIComponent(this.props.site.domain)}/settings/integrations`} className="button mt-4">Connect with Google</a>
<a href={`/${encodeURIComponent(this.props.site.domain)}/settings/search-console`} className="button mt-4">Connect with Google</a>
</div>
)
} else {
@ -124,6 +124,7 @@ class GoogleKeywordsModal extends React.Component {
<main className="modal__content">
<h1 className="text-xl font-semibold mb-0 leading-none dark:text-gray-200">
{this.state.totalVisitors} visitors from Google<br />
{toHuman(this.state.query)}
</h1>
{this.renderGoalText()}
{ this.renderKeywords() }

@ -1,7 +1,6 @@
import React from "react";
import { createPortal } from "react-dom";
import { withRouter } from 'react-router-dom';
import { shouldIgnoreKeypress } from '../../keybinding'
// This corresponds to the 'md' breakpoint on TailwindCSS.
const MD_WIDTH = 768;
@ -47,7 +46,7 @@ class Modal extends React.Component {
}
handleKeyup(e) {
if (!shouldIgnoreKeypress(e) && e.code === 'Escape') {
if (e.code === 'Escape') {
this.close()
}
}

@ -4,9 +4,8 @@ import { withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import { parseQuery } from '../../query'
import { trimURL } from '../../util/url'
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import {parseQuery} from '../../query'
class PagesModal extends React.Component {
constructor(props) {
@ -26,14 +25,14 @@ class PagesModal extends React.Component {
loadPages() {
const detailed = this.showExtra()
const { query, page } = this.state;
const {query, page} = this.state;
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/pages`, query, { limit: 100, page, detailed })
.then((res) => this.setState((state) => ({ loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100 })))
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/pages`, query, {limit: 100, page, detailed})
.then((res) => this.setState((state) => ({loading: false, pages: state.pages.concat(res), moreResultsAvailable: res.length === 100})))
}
loadMore() {
this.setState({ loading: true, page: this.state.page + 1 }, this.loadPages.bind(this))
this.setState({loading: true, page: this.state.page + 1}, this.loadPages.bind(this))
}
showExtra() {
@ -49,7 +48,7 @@ class PagesModal extends React.Component {
}
formatBounceRate(page) {
if (typeof (page.bounce_rate) === 'number') {
if (typeof(page.bounce_rate) === 'number') {
return page.bounce_rate + '%'
} else {
return '-'
@ -64,14 +63,14 @@ class PagesModal extends React.Component {
return (
<tr className="text-sm dark:text-gray-200" key={page.name}>
<td className="p-2">
<Link to={{ pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString() }} className="hover:underline block truncate">{trimURL(page.name, 50)}</Link>
<Link to={{pathname: `/${encodeURIComponent(this.props.site.domain)}`, search: query.toString()}} className="hover:underline block truncate">{page.name}</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.total_visitors}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.total_visitors}</td> }
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.visitors)}</td>
{this.showPageviews() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.pageviews)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatBounceRate(page)}</td>}
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{timeOnPage}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.conversion_rate}%</td>}
{this.showPageviews() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(page.pageviews)}</td> }
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{this.formatBounceRate(page)}</td> }
{this.showExtra() && <td className="p-2 w-32 font-medium" align="right">{timeOnPage}</td> }
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{page.conversion_rate}%</td> }
</tr>
)
}
@ -115,7 +114,7 @@ class PagesModal extends React.Component {
<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" align="left">Page url</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Total visitors</th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{this.label()}</th>
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{ this.label() }</th>
{this.showPageviews() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Pageviews</th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Bounce rate</th>}
{this.showExtra() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Time on Page</th>}
@ -123,7 +122,7 @@ class PagesModal extends React.Component {
</tr>
</thead>
<tbody>
{this.state.pages.map(this.renderPage.bind(this))}
{ this.state.pages.map(this.renderPage.bind(this)) }
</tbody>
</table>
</main>
@ -135,8 +134,8 @@ class PagesModal extends React.Component {
render() {
return (
<Modal site={this.props.site}>
{this.renderBody()}
{this.renderLoading()}
{ this.renderBody() }
{ this.renderLoading() }
</Modal>
)
}

@ -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)

@ -4,7 +4,7 @@ import { Link, withRouter } from 'react-router-dom'
import Modal from './modal'
import * as api from '../../api'
import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import {parseQuery} from '../../query'
import {parseQuery, toHuman} from '../../query'
class ReferrerDrilldownModal extends React.Component {
constructor(props) {
@ -19,7 +19,7 @@ class ReferrerDrilldownModal extends React.Component {
const detailed = this.showExtra()
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers/${this.props.match.params.referrer}`, this.state.query, {limit: 100, detailed})
.then((referrers) => this.setState({loading: false, referrers: referrers}))
.then((res) => this.setState({loading: false, referrers: res.referrers, totalVisitors: res.total_visitors}))
}
showExtra() {
@ -74,7 +74,7 @@ class ReferrerDrilldownModal extends React.Component {
return (
<span className="flex group items-center">
<img src={`/favicon/sources/${referrer.name}`} referrerPolicy="no-referrer" className="h-4 w-4 mr-2 inline" />
<img src={`https://icons.duckduckgo.com/ip3/${referrer.url}.ico`} referrerPolicy="no-referrer" className="h-4 w-4 mr-2 inline" />
<Link className="block truncate hover:underline dark:text-gray-200" to={{search: query.toString(), pathname: '/' + this.props.site.domain}} title={referrer.name}>
{referrer.name}
</Link>
@ -98,6 +98,14 @@ class ReferrerDrilldownModal extends React.Component {
)
}
renderGoalText() {
if (this.state.query.filters.goal) {
return (
<h1 className="text-xl font-semibold text-gray-500 dark:text-gray-300 leading-none">completed {this.state.query.filters.goal}</h1>
)
}
}
renderBody() {
if (this.state.loading) {
return (
@ -110,6 +118,9 @@ class ReferrerDrilldownModal extends React.Component {
<div className="my-4 border-b border-gray-300 dark:border-gray-500"></div>
<main className="modal__content mt-0">
<h1 className="text-xl font-semibold mb-0 leading-none dark:text-gray-200">{this.state.totalVisitors} visitors from {decodeURIComponent(this.props.match.params.referrer)}<br /> {toHuman(this.state.query)}</h1>
{this.renderGoalText()}
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed mt-4">
<thead>
<tr>

@ -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)

@ -20,24 +20,8 @@ class ModalTable extends React.Component {
.then((res) => this.setState({loading: false, list: res}))
}
showConversionRate() {
return !!this.state.query.filters.goal
}
showPercentage() {
return this.props.showPercentage && !this.showConversionRate()
}
label() {
if (this.state.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
return this.state.query.period === 'realtime' ? 'Current visitors' : 'Visitors'
}
renderTableItem(tableItem) {
@ -56,10 +40,11 @@ class ModalTable extends React.Component {
{tableItem.name}
</Link>
</td>
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.total_visitors)}</td>}
<td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.visitors)}</td>
{this.showPercentage() && <td className="p-2 w-32 font-medium" align="right">{tableItem.percentage}</td>}
{this.showConversionRate() && <td className="p-2 w-32 font-medium" align="right">{numberFormatter(tableItem.conversion_rate)}%</td>}
<td className="p-2 w-32 font-medium" align="right">
{numberFormatter(tableItem.visitors)}
{tableItem.percentage >= 0 &&
<span className="inline-block text-xs w-8 pl-1 text-right">({tableItem.percentage}%)</span> }
</td>
</tr>
)
}
@ -81,11 +66,19 @@ class ModalTable extends React.Component {
<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" align="left">{this.props.keyLabel}</th>
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right" >Total Visitors</th>}
<th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{this.label()}</th>
{this.showPercentage() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">%</th>}
{this.showConversionRate() && <th className="p-2 w-32 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">CR</th>}
<th
className="p-2 w-48 lg:w-1/2 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"
align="left"
>
{this.props.keyLabel}
</th>
<th
// eslint-disable-next-line max-len
className="p-2 w-32 lg:w-1/2 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400"
align="right"
>
{this.label()}
</th>
</tr>
</thead>
<tbody>

@ -1,36 +1,29 @@
import React from 'react';
import { Link } from 'react-router-dom'
function detailsIcon() {
return (
<svg
className="feather mr-1"
style={{marginTop: '-2px'}}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
{/* eslint-disable-next-line max-len */}
<path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />
</svg>
)
}
export default function MoreLink({url, site, list, endpoint, className, onClick}) {
export default function MoreLink({url, site, list, endpoint}) {
if (list.length > 0) {
return (
<div className={`w-full text-center ${className ? className : ''}`}>
<div className="text-center w-full py-3 md:pb-3 md:pt-0 md:absolute md:bottom-0 md:left-0">
<Link
to={url || `/${encodeURIComponent(site.domain)}/${endpoint}${window.location.search}`}
// eslint-disable-next-line max-len
className="leading-snug font-bold text-sm text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400 transition tracking-wide"
onClick={onClick}
>
{ detailsIcon() }
<svg
className="feather mr-1"
style={{marginTop: '-2px'}}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
{/* eslint-disable-next-line max-len */}
<path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3" />
</svg>
DETAILS
</Link>
</div>

@ -4,27 +4,23 @@ import * as storage from '../../util/storage'
import * as url from '../../util/url'
import * as api from '../../api'
import ListReport from './../reports/list'
import { VISITORS_METRIC, maybeWithCR } from './../reports/metrics';
function EntryPages({ query, site }) {
function EntryPages({query, site}) {
function fetchData() {
return api.get(url.apiPath(site, '/entry-pages'), query, { limit: 9 })
return api.get(url.apiPath(site, '/entry-pages'), query, {limit: 9})
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { entry_page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{entry_page: 'name'}}
keyLabel="Entry page"
metrics={maybeWithCR([{ ...VISITORS_METRIC, label: 'Unique Entrances' }], query)}
valueLabel="Unique Entrances"
valueKey="unique_entrances"
detailsLink={url.sitePath(site, '/entry-pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -33,25 +29,22 @@ function EntryPages({ query, site }) {
)
}
function ExitPages({ query, site }) {
function ExitPages({query, site}) {
function fetchData() {
return api.get(url.apiPath(site, '/exit-pages'), query, { limit: 9 })
return api.get(url.apiPath(site, '/exit-pages'), query, {limit: 9})
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { exit_page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{exit_page: 'name'}}
keyLabel="Exit page"
metrics={maybeWithCR([{ ...VISITORS_METRIC, label: "Unique Exits" }], query)}
valueLabel="Unique Exits"
valueKey="unique_exits"
detailsLink={url.sitePath(site, '/exit-pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -60,25 +53,20 @@ function ExitPages({ query, site }) {
)
}
function TopPages({ query, site }) {
function TopPages({query, site}) {
function fetchData() {
return api.get(url.apiPath(site, '/pages'), query, { limit: 9 })
return api.get(url.apiPath(site, '/pages'), query, {limit: 9})
}
function externalLinkDest(page) {
return url.externalLinkForPage(site.domain, page.name)
}
function getFilterFor(listItem) {
return { page: listItem['name'] }
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
filter={{page: 'name'}}
keyLabel="Page"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, '/pages')}
query={query}
externalLinkDest={externalLinkDest}
@ -88,15 +76,15 @@ function TopPages({ query, site }) {
}
const labelFor = {
'pages': 'Top Pages',
'entry-pages': 'Entry Pages',
'exit-pages': 'Exit Pages',
'pages': 'Top Pages',
'entry-pages': 'Entry Pages',
'exit-pages': 'Exit Pages',
}
export default class Pages extends React.Component {
constructor(props) {
super(props)
this.tabKey = `pageTab__${props.site.domain}`
this.tabKey = `pageTab__${ props.site.domain}`
const storedTab = storage.getItem(this.tabKey)
this.state = {
mode: storedTab || 'pages'
@ -106,19 +94,19 @@ export default class Pages extends React.Component {
setMode(mode) {
return () => {
storage.setItem(this.tabKey, mode)
this.setState({ mode })
this.setState({mode})
}
}
renderContent() {
switch (this.state.mode) {
case "entry-pages":
return <EntryPages site={this.props.site} query={this.props.query} />
case "exit-pages":
return <ExitPages site={this.props.site} query={this.props.query} />
case "pages":
default:
return <TopPages site={this.props.site} query={this.props.query} />
switch(this.state.mode) {
case "entry-pages":
return <EntryPages site={this.props.site} query={this.props.query} />
case "exit-pages":
return <ExitPages site={this.props.site} query={this.props.query} />
case "pages":
default:
return <TopPages site={this.props.site} query={this.props.query} />
}
}
@ -148,20 +136,26 @@ export default class Pages extends React.Component {
render() {
return (
<div>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Page Visits'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{this.renderPill('Top Pages', 'pages')}
{this.renderPill('Entry Pages', 'entry-pages')}
{this.renderPill('Exit Pages', 'exit-pages')}
<div
className="stats-item flex flex-col w-full mt-6 stats-item--has-header"
>
<div
className="stats-item-header flex flex-col flex-grow bg-white dark:bg-gray-825 shadow-xl rounded p-4 relative"
>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
{labelFor[this.state.mode] || 'Page Visits'}
</h3>
<div className="flex font-medium text-xs text-gray-500 dark:text-gray-400 space-x-2">
{ this.renderPill('Top Pages', 'pages') }
{ this.renderPill('Entry Pages', 'entry-pages') }
{ this.renderPill('Exit Pages', 'exit-pages') }
</div>
</div>
{/* Main Contents */}
{ this.renderContent() }
</div>
{/* Main Contents */}
{this.renderContent()}
</div>
)
}

@ -2,51 +2,25 @@ import React, { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move';
import { displayMetricValue, metricLabelFor } from './metrics';
import FadeIn from '../../fade-in'
import MoreLink from '../more-link'
import numberFormatter from '../../util/number-formatter'
import Bar from '../bar'
import LazyLoader from '../../components/lazy-loader'
import classNames from 'classnames'
import { trimURL } from '../../util/url'
const MAX_ITEMS = 9
const MIN_HEIGHT = 380
const ROW_HEIGHT = 32
const ROW_GAP_HEIGHT = 4
const DATA_CONTAINER_HEIGHT = (ROW_HEIGHT + ROW_GAP_HEIGHT) * (MAX_ITEMS - 1) + ROW_HEIGHT
const COL_MIN_WIDTH = 70
function FilterLink({ filterQuery, onClick, children }) {
const className = classNames('max-w-max w-full flex md:overflow-hidden', {
'hover:underline': !!filterQuery
})
function ExternalLink({item, externalLinkDest}) {
if (externalLinkDest) {
const dest = externalLinkDest(item)
if (filterQuery) {
return (
<Link
to={{ search: filterQuery.toString() }}
onClick={onClick}
className={className}
>
{children}
</Link>
)
} else {
return <span className={className}>{children}</span>
}
}
function ExternalLink({ item, externalLinkDest }) {
const dest = externalLinkDest && externalLinkDest(item)
if (dest) {
return (
<a
target="_blank"
rel="noreferrer"
href={dest}
className="w-4 h-4 hidden group-hover:block"
className="hidden group-hover:block"
>
<svg className="inline w-full h-full 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>
<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>
)
}
@ -54,270 +28,117 @@ function ExternalLink({ item, externalLinkDest }) {
return null
}
// The main function component for rendering list reports and making them react to what
// is happening on the dashboard.
// A `fetchData` function must be passed through props. This function defines the format
// of the data, which is expected to be a list of objects. Think of these objects as rows
// with keys being columns. The number of columns is dynamic and should be configured
// via the `metrics` input list. For example:
// | keyLabel | METRIC_1.label | METRIC_2.label | ...
// |--------------------|---------------------------|---------------------------|-----
// | LISTITEM_1.name | LISTITEM_1[METRIC_1.name] | LISTITEM_1[METRIC_2.name] | ...
// | LISTITEM_2.name | LISTITEM_2[METRIC_1.name] | LISTITEM_2[METRIC_2.name] | ...
// Further configuration of the report is possible through optional props.
// REQUIRED PROPS:
// * `keyLabel` - What each entry in the list represents (for UI only).
// * `query` - The query object representing the current state of the dashboard.
// * `fetchData` - a function that returns an `api.get` promise that will resolve to the
// list of data.
// * `metrics` - a list of `metric` objects. Each `metric` object is required to have at
// least the `name` and the `label` keys. If the metric should have a different label
// in realtime or goal-filtered views, we'll use `realtimeLabel` and `GoalFilterLabel`.
// * `getFilterFor` - a function that takes a list item and returns the query link (with
// the filter) to navigate to when this list item is clicked. If a list item is not
// supposed to be clickable, this function should return `null` for that list item.
// OPTIONAL PROPS:
// * `onClick` - function with additional action to be taken when a list entry is clicked.
// * `detailsLink` - the pathname to the detailed view of this report. E.g.:
// `/dummy.site/pages`. If this is given as input to the ListReport, the Details button
// will always be rendered.
// * `maybeHideDetails` - set this to `true` if the details button should be hidden on
// the condition that there are less than MAX_ITEMS entries in the list. (i.e . nothing
// more to show)
// * `externalLinkDest` - a function that takes a list item and returns an external url
// to navigate to. If this prop is given, an additional icon is rendered upon hovering
// the entry.
// * `renderIcon` - a function that takes a list item and returns the
// HTML of an icon (such as a flag, favicon, or a screen size icon) for a listItem.
// * `color` - color of the comparison bars in light-mode
export default function ListReport(props) {
const [state, setState] = useState({ loading: true, list: null })
const [state, setState] = useState({loading: true, list: null})
const [visible, setVisible] = useState(false)
const metrics = props.metrics
const colMinWidth = props.colMinWidth || COL_MIN_WIDTH
const isRealtime = props.query.period === 'realtime'
const goalFilterApplied = !!props.query.filters.goal
const valueKey = props.valueKey || 'visitors'
const showConversionRate = !!props.query.filters.goal
const fetchData = useCallback(() => {
if (!isRealtime) {
setState({ loading: true, list: null })
if (props.query.period !== 'realtime') {
setState({loading: true, list: null})
}
props.fetchData()
.then((res) => setState({loading: false, list: res}))
}, [props.query])
function onVisible() {
setVisible(true)
if (props.query.period == 'realtime') {
document.addEventListener('tick', fetchData)
}
props.fetchData()
.then((res) => setState({ loading: false, list: res }))
}, [props.keyLabel, props.query])
const onVisible = () => { setVisible(true) }
}
useEffect(() => {
if (isRealtime) {
// When a goal filter is applied or removed, we always want the component to go into a
// loading state, even in realtime mode, because the metrics list will change. We can
// only read the new metrics once the new list is loaded.
setState({ loading: true, list: null })
}
}, [goalFilterApplied]);
if (visible) { fetchData() }
}, [props.query, visible]);
useEffect(() => {
if (visible) {
if (isRealtime) { document.addEventListener('tick', fetchData) }
fetchData()
}
return () => { document.removeEventListener('tick', fetchData) }
}, [props.keyLabel, props.query, visible]);
}, []);
// returns a filtered `metrics` list. Since currently, the backend can return different
// metrics based on filters and existing data, this function validates that the metrics
// we want to display are actually there in the API response.
function getAvailableMetrics() {
return metrics.filter((metric) => {
return state.list.some((listItem) => listItem[metric.name] != null)
})
}
function hiddenOnMobileClass(metric) {
if (metric.hiddenOnMobile) {
return 'hidden md:block'
} else {
return ''
function label() {
if (props.query.period === 'realtime') {
return 'Current visitors'
}
}
function renderReport() {
if (state.list && state.list.length > 0) {
return (
<div className="h-full flex flex-col">
<div style={{ height: ROW_HEIGHT }}>
{renderReportHeader()}
</div>
<div style={{ minHeight: DATA_CONTAINER_HEIGHT }}>
{renderReportBody()}
</div>
{maybeRenderDetailsLink()}
</div>
)
if (showConversionRate) {
return 'Conversions'
}
return renderNoDataYet()
}
function renderReportHeader() {
const metricLabels = getAvailableMetrics().map((metric) => {
return (
<div
key={metric.name}
className={`text-right ${hiddenOnMobileClass(metric)}`}
style={{ minWidth: colMinWidth }}
>
{metricLabelFor(metric, props.query)}
</div>
)
})
return (
<div className="pt-3 w-full text-xs font-bold tracking-wide text-gray-500 flex items-center dark:text-gray-400">
<span className="flex-grow truncate">{props.keyLabel}</span>
{metricLabels}
</div>
)
}
function renderReportBody() {
return (
<FlipMove className="flex-grow">
{state.list.slice(0, MAX_ITEMS).map(renderRow)}
</FlipMove>
)
}
function renderRow(listItem) {
return (
<div key={listItem.name} style={{ minHeight: ROW_HEIGHT }}>
<div className="flex w-full" style={{ marginTop: ROW_GAP_HEIGHT }}>
{renderBarFor(listItem)}
{renderMetricValuesFor(listItem)}
</div>
</div>
)
return props.valueLabel || 'Visitors'
}
function getFilterQuery(listItem) {
const filter = props.getFilterFor(listItem)
if (!filter) { return null }
function renderListItem(listItem) {
const query = new URLSearchParams(window.location.search)
Object.entries(filter).forEach((([key, value]) => {
query.set(key, value)
}))
return query
}
Object.entries(props.filter).forEach((([key, valueKey]) => {
query.set(key, listItem[valueKey])
}))
function renderBarFor(listItem) {
const maxWidthDeduction = showConversionRate ? "10rem" : "5rem"
const lightBackground = props.color || 'bg-green-50'
const noop = () => { }
const metricToPlot = metrics.find(m => m.plot).name
const noop = () => {}
return (
<div className="flex-grow w-full overflow-hidden">
<div className="flex items-center justify-between my-1 text-sm" key={listItem.name}>
<Bar
count={listItem[metricToPlot]}
count={listItem[valueKey]}
all={state.list}
bg={`${lightBackground} dark:bg-gray-500 dark:bg-opacity-15`}
plot={metricToPlot}
maxWidthDeduction={maxWidthDeduction}
plot={valueKey}
>
<div className="flex justify-start px-2 py-1.5 group text-sm dark:text-gray-300 relative z-9 break-all w-full">
<FilterLink filterQuery={getFilterQuery(listItem)} onClick={props.onClick || noop}>
{maybeRenderIconFor(listItem)}
<span className="w-full md:truncate">
{trimURL(listItem.name, colMinWidth)}
</span>
</FilterLink>
<ExternalLink item={listItem} externalLinkDest={props.externalLinkDest} />
</div>
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all" tooltip={props.tooltipText && props.tooltipText(listItem)}>
<Link onClick={props.onClick || noop} className="md:truncate block hover:underline" to={{search: query.toString()}}>
{props.renderIcon && props.renderIcon(listItem)}
{props.renderIcon && ' '}
{listItem.name}
</Link>
<ExternalLink item={listItem} externalLinkDest={props.externalLinkDest} />
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={listItem[valueKey]}>
{numberFormatter(listItem[valueKey])}
{
listItem.percentage >= 0
? <span className="inline-block w-8 pl-1 text-xs text-right">({listItem.percentage}%)</span>
: null
}
</span>
{showConversionRate && <span className="font-medium dark:text-gray-200 w-20 text-right">{listItem.conversion_rate}%</span>}
</div>
)
}
function maybeRenderIconFor(listItem) {
if (props.renderIcon) {
function renderList() {
if (state.list && state.list.length > 0) {
return (
<span className="pr-1">
{props.renderIcon(listItem)}
</span>
<>
<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>{ props.keyLabel }</span>
<span className="text-right">
<span className="inline-block w-30">{label()}</span>
{showConversionRate && <span className="inline-block w-20">CR</span>}
</span>
</div>
<FlipMove>
{ state.list.map(renderListItem) }
</FlipMove>
</>
)
}
}
function renderMetricValuesFor(listItem) {
return getAvailableMetrics().map((metric) => {
return (
<div
key={`${listItem.name}__${metric.name}`}
className={`text-right ${hiddenOnMobileClass(metric)}`}
style={{ width: colMinWidth, minWidth: colMinWidth }}
>
<span className="font-medium text-sm dark:text-gray-200 text-right">
{displayMetricValue(listItem[metric.name], metric)}
</span>
</div>
)
})
}
function renderLoading() {
return (
<div className="w-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT}px` }}>
<div className="mx-auto loading"><div></div></div>
</div>
)
}
function renderNoDataYet() {
return (
<div className="w-full h-full flex flex-col justify-center" style={{ minHeight: `${MIN_HEIGHT}px` }}>
<div className="mx-auto font-medium text-gray-500 dark:text-gray-400">No data yet</div>
</div>
)
}
function maybeRenderDetailsLink() {
const moreResultsAvailable = state.list.length >= MAX_ITEMS
const hideDetails = props.maybeHideDetails && !moreResultsAvailable
const showDetails = props.detailsLink && !state.loading && !hideDetails
return showDetails && <MoreLink className={'mt-2'} url={props.detailsLink} list={state.list} />
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
}
return (
<LazyLoader onVisible={onVisible} >
<div className="w-full" style={{ minHeight: `${MIN_HEIGHT}px` }}>
{state.loading && renderLoading()}
{!state.loading && <FadeIn show={!state.loading} className="h-full">
{renderReport()}
</FadeIn>}
</div>
<LazyLoader onVisible={onVisible} className="flex flex-col flex-grow">
{ state.loading && <div className="mx-auto loading mt-44"><div></div></div> }
<FadeIn show={!state.loading} className="flex-grow">
{ renderList() }
</FadeIn>
{props.detailsLink && !state.loading && <MoreLink url={props.detailsLink} list={state.list} />}
</LazyLoader>
)
}

@ -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
}

@ -2,13 +2,11 @@ import React from 'react';
import SearchTerms from './search-terms'
import SourceList from './source-list'
import ReferrerList from './referrer-list'
import { isFilteringOnFixedValue } from '../../util/filters'
export default function Sources(props) {
if (props.query.filters.source === 'Google') {
return <SearchTerms {...props} />
} else if (isFilteringOnFixedValue(props.query, 'source')) {
} else if (props.query.filters.source) {
return <ReferrerList {...props} />
} else {
return <SourceList {...props} />

@ -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>
)
}
}

@ -85,7 +85,7 @@ export default class SearchTerms extends React.Component {
This site is not connected to Search Console so we cannot show the search phrases.
{this.state.isAdmin && this.state.error && <><br/><br/><p>Please click below to connect your Search Console account.</p></>}
</div>
{this.state.isAdmin && <a href={`/${encodeURIComponent(this.props.site.domain)}/settings/integrations`} className="button mt-4">Connect with Google</a> }
{this.state.isAdmin && <a href={`/${encodeURIComponent(this.props.site.domain)}/settings/search-console`} className="button mt-4">Connect with Google</a> }
</div>
)
} else if (this.state.searchTerms.length > 0) {
@ -119,7 +119,7 @@ export default class SearchTerms extends React.Component {
<React.Fragment>
<h3 className="font-bold dark:text-gray-100">Search Terms</h3>
{ this.renderList() }
<MoreLink site={this.props.site} list={this.state.searchTerms} endpoint="referrers/Google" className="w-full pb-4 absolute bottom-0 left-0"/>
<MoreLink site={this.props.site} list={this.state.searchTerms} endpoint="referrers/Google" />
</React.Fragment>
)
}
@ -127,7 +127,9 @@ export default class SearchTerms extends React.Component {
render() {
return (
<div>
<div
className="stats-item flex flex-col relative bg-white dark:bg-gray-825 shadow-xl rounded p-4 mt-6 w-full"
>
{ this.state.loading && <div className="loading mt-44 mx-auto"><div></div></div> }
<FadeIn show={!this.state.loading} className="flex-grow">
<LazyLoader onVisible={this.onVisible}>

@ -1,109 +1,320 @@
import React, { Fragment, useState } from 'react';
import React from 'react';
import { Link } from 'react-router-dom'
import FlipMove from 'react-flip-move';
import * as storage from '../../util/storage'
import * as url from '../../util/url'
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 ListReport from '../reports/list'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics';
import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { escapeFilterValue } from '../../util/filters'
import classNames from 'classnames'
import * as url from '../../util/url'
import LazyLoader from '../../components/lazy-loader'
class AllSources extends React.Component {
constructor(props) {
super(props)
this.onVisible = this.onVisible.bind(this)
this.fetchReferrers = this.fetchReferrers.bind(this)
this.state = { loading: true }
}
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
}
fetchReferrers() {
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/sources`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
}
renderReferrer(referrer) {
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
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 dark:text-gray-300 relative z-9 break-all">
<Link
className="md:truncate block hover:underline"
to={url.setQuery('source', referrer.name)}
>
<img
src={`/favicon/sources/${encodeURIComponent(referrer.name)}`}
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
{referrer.name}
</Link>
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={referrer.visitors}>{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'
}
renderList() {
if (this.state.referrers && this.state.referrers.length > 0) {
return (
<React.Fragment>
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500">
<span>Source</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>
<MoreLink site={this.props.site} list={this.state.referrers} endpoint="sources" />
</React.Fragment>
)
} else {
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
}
}
renderContent() {
return (
<LazyLoader className="flex flex-col flex-grow" onVisible={this.onVisible}>
<div id="sources" className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Top Sources</h3>
{this.props.renderTabs()}
</div>
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
<FadeIn show={!this.state.loading} className="flex flex-col flex-grow">
{this.renderList()}
</FadeIn>
</LazyLoader>
)
}
render() {
return (
<div
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col mt-6 w-full dark:bg-gray-825"
>
{this.renderContent()}
</div>
)
}
}
const UTM_TAGS = {
utm_medium: { label: 'UTM Medium', shortLabel: 'UTM Medium', endpoint: '/utm_mediums' },
utm_source: { label: 'UTM Source', shortLabel: 'UTM Source', endpoint: '/utm_sources' },
utm_campaign: { label: 'UTM Campaign', shortLabel: 'UTM Campai', endpoint: '/utm_campaigns' },
utm_content: { label: 'UTM Content', shortLabel: 'UTM Conten', endpoint: '/utm_contents' },
utm_term: { label: 'UTM Term', shortLabel: 'UTM Term', endpoint: '/utm_terms' },
utm_medium: { label: 'UTM Medium', shortLabel: 'UTM Medium', endpoint: 'utm_mediums' },
utm_source: { label: 'UTM Source', shortLabel: 'UTM Source', endpoint: 'utm_sources' },
utm_campaign: { label: 'UTM Campaign', shortLabel: 'UTM Campai', endpoint: 'utm_campaigns' },
utm_content: { label: 'UTM Content', shortLabel: 'UTM Conten', endpoint: 'utm_contents' },
utm_term: { label: 'UTM Term', shortLabel: 'UTM Term', endpoint: 'utm_terms' },
}
function AllSources(props) {
const { site, query } = props
class UTMSources extends React.Component {
constructor(props) {
super(props)
this.onVisible = this.onVisible.bind(this)
this.fetchReferrers = this.fetchReferrers.bind(this)
this.state = { loading: true }
}
onVisible() {
this.fetchReferrers()
if (this.props.query.period === 'realtime') {
document.addEventListener('tick', this.fetchReferrers)
}
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query || this.props.tab !== prevProps.tab) {
this.setState({ loading: true, referrers: null })
this.fetchReferrers()
}
}
function fetchData() {
return api.get(url.apiPath(site, '/sources'), query, { limit: 9 })
componentWillUnmount() {
document.removeEventListener('tick', this.fetchReferrers)
}
function getFilterFor(listItem) {
return { source: escapeFilterValue(listItem['name']) }
showNoRef() {
return this.props.query.period === 'realtime'
}
function renderIcon(listItem) {
showConversionRate() {
return !!this.props.query.filters.goal
}
fetchReferrers() {
const endpoint = UTM_TAGS[this.props.tab].endpoint
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/${endpoint}`, this.props.query)
.then((res) => this.setState({ loading: false, referrers: res }))
}
renderReferrer(referrer) {
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
return (
<img
src={`/favicon/sources/${encodeURIComponent(listItem.name)}`}
className="inline w-4 h-4 mr-2 -mt-px align-middle"
/>
<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 dark:text-gray-300 relative z-9 break-all">
<Link
className="md:truncate block hover:underline"
to={url.setQuery(this.props.tab, referrer.name)}
>
{referrer.name}
</Link>
</span>
</Bar>
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={referrer.visitors}>{numberFormatter(referrer.visitors)}</span>
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
</div>
)
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel="Source"
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, '/sources')}
renderIcon={renderIcon}
query={query}
color="bg-blue-50"
/>
)
}
label() {
if (this.props.query.period === 'realtime') {
return 'Current visitors'
}
if (this.showConversionRate()) {
return 'Conversions'
}
return 'Visitors'
}
function UTMSources(props) {
const { site, query } = props
const utmTag = UTM_TAGS[props.tab]
renderList() {
if (this.state.referrers && 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 dark:text-gray-400">
<span>{UTM_TAGS[this.props.tab].label}</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>
function fetchData() {
return api.get(url.apiPath(site, utmTag.endpoint), query, { limit: 9 })
<FlipMove className="flex-grow">
{this.state.referrers.map(this.renderReferrer.bind(this))}
</FlipMove>
<MoreLink site={this.props.site} list={this.state.referrers} endpoint={UTM_TAGS[this.props.tab].endpoint} />
</div>
)
} else {
return <div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">No data yet</div>
}
}
function getFilterFor(listItem) {
return { [props.tab]: escapeFilterValue(listItem['name']) }
renderContent() {
return (
<LazyLoader onVisible={this.onVisible}>
<div className="flex justify-between w-full">
<h3 className="font-bold dark:text-gray-100">Top Sources</h3>
{this.props.renderTabs()}
</div>
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
<FadeIn show={!this.state.loading} className="flex flex-col flex-grow">
{this.renderList()}
</FadeIn>
</LazyLoader>
)
}
return (
<ListReport
fetchData={fetchData}
getFilterFor={getFilterFor}
keyLabel={utmTag.label}
metrics={maybeWithCR([VISITORS_METRIC], query)}
detailsLink={url.sitePath(site, utmTag.endpoint)}
query={query}
color="bg-blue-50"
/>
)
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"
>
{this.renderContent()}
</div>
)
}
}
export default function SourceList(props) {
const { site, query } = props
const tabKey = 'sourceTab__' + props.site.domain
const storedTab = storage.getItem(tabKey)
const [currentTab, setCurrentTab] = useState(storedTab || 'all')
import { Fragment } from 'react'
import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import classNames from 'classnames'
export default class SourceList extends React.Component {
constructor(props) {
super(props)
this.tabKey = 'sourceTab__' + props.site.domain
const storedTab = storage.getItem(this.tabKey)
this.state = {
tab: storedTab || 'all'
}
}
function setTab(tab) {
setTab(tab) {
return () => {
storage.setItem(tabKey, tab)
setCurrentTab(tab)
storage.setItem(this.tabKey, tab)
this.setState({ tab })
}
}
function renderTabs() {
renderTabs() {
const activeClass = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left'
const defaultClass = 'hover:text-indigo-600 cursor-pointer truncate text-left'
const dropdownOptions = Object.keys(UTM_TAGS)
let buttonText = UTM_TAGS[currentTab] ? UTM_TAGS[currentTab].label : 'Campaigns'
let buttonText = UTM_TAGS[this.state.tab] ? UTM_TAGS[this.state.tab].label : 'Campaigns'
return (
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
<div className={currentTab === 'all' ? activeClass : defaultClass} onClick={setTab('all')}>All</div>
<div className={this.state.tab === 'all' ? activeClass : defaultClass} onClick={this.setTab('all')}>All</div>
<Menu as="div" className="relative inline-block text-left">
<div>
<Menu.Button className="inline-flex justify-between focus:outline-none">
<span className={currentTab.startsWith('utm_') ? activeClass : defaultClass}>{buttonText}</span>
<span className={this.state.tab.startsWith('utm_') ? activeClass : defaultClass}>{buttonText}</span>
<ChevronDownIcon className="-mr-1 ml-1 h-4 w-4" aria-hidden="true" />
</Menu.Button>
</div>
@ -111,11 +322,11 @@ export default function SourceList(props) {
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform 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">
@ -124,11 +335,11 @@ export default function SourceList(props) {
<Menu.Item key={option}>
{({ active }) => (
<span
onClick={setTab(option)}
onClick={this.setTab(option)}
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',
currentTab === option ? 'font-bold' : ''
this.state.tab === option ? 'font-bold' : ''
)}
>
{UTM_TAGS[option].label}
@ -145,25 +356,11 @@ export default function SourceList(props) {
)
}
function renderContent() {
if (currentTab === 'all') {
return <AllSources site={site} query={query} />
} else {
return <UTMSources tab={currentTab} site={site} query={query} />
render() {
if (this.state.tab === 'all') {
return <AllSources tab={this.state.tab} setTab={this.setTab.bind(this)} renderTabs={this.renderTabs.bind(this)} {...this.props} />
} else if (Object.keys(UTM_TAGS).includes(this.state.tab)) {
return <UTMSources tab={this.state.tab} setTab={this.setTab.bind(this)} renderTabs={this.renderTabs.bind(this)} {...this.props} />
}
}
return (
<div>
{/* Header Container */}
<div className="w-full flex justify-between">
<h3 className="font-bold dark:text-gray-100">
Top Sources
</h3>
{renderTabs()}
</div>
{/* Main Contents */}
{renderContent()}
</div>
)
}

@ -1,74 +1,76 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc)
// https://stackoverflow.com/a/50130338
export function formatISO(date) {
return date.format('YYYY-MM-DD')
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
.toISOString()
.split("T")[0];
}
export function shiftMonths(date, months) {
return date.add(months, 'months')
const newDate = new Date(date.getTime())
const d = newDate.getDate();
newDate.setMonth(newDate.getMonth() + +months);
if (newDate.getDate() != d) {
newDate.setDate(0);
}
return newDate;
}
export function shiftDays(date, days) {
return date.add(days, 'days')
const newDate = new Date(date.getTime())
newDate.setDate(newDate.getDate() + days)
return newDate
}
const MONTHS = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
]
const DAYS_ABBREV = [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
]
export function formatMonthYYYY(date) {
return date.format('MMMM YYYY')
return `${MONTHS[date.getMonth()]} ${date.getFullYear()}`;
}
export function formatYear(date) {
return `Year of ${date.year()}`;
}
export function formatYearShort(date) {
return date.getUTCFullYear().toString().substring(2)
return `Year of ${date.getFullYear()}`;
}
export function formatDay(date) {
if (date.year() !== dayjs().year()) {
return date.format('ddd, DD MMM YYYY')
var weekday = DAYS_ABBREV[date.getDay()];
if (date.getFullYear() !== (new Date()).getFullYear()) {
return `${weekday}, ${date.getDate()} ${formatMonthShort(date)} ${date.getFullYear()}`;
} else {
return date.format('ddd, DD MMM')
return `${weekday}, ${date.getDate()} ${formatMonthShort(date)}`;
}
}
export function formatDayShort(date, includeYear = false) {
if (includeYear) {
return date.format('D MMM YY')
} else {
return date.format('D MMM')
}
export function formatDayShort(date) {
return `${date.getDate()} ${formatMonthShort(date)}`;
}
export function formatDateRange(site, from, to) {
if (!from || !to) return
if (typeof from === 'string') from = parseUTCDate(from)
if (typeof to === 'string') to = parseUTCDate(to)
if (from.isSame(to)) {
return formatDay(from)
} else if (from.isSame(to, 'year')) {
const includeYear = !isThisYear(site, from)
return `${formatDayShort(from, false)} - ${formatDayShort(to, includeYear)}`
export function parseUTCDate(dateString) {
var date;
// Safari Compatibility
if (typeof dateString === "string" && dateString.includes(' ')) {
const parts = dateString.split(/[^0-9]/);
parts[1] -= 1;
date = new Date(...parts);
} else {
return `${formatDayShort(from, true)} - ${formatDayShort(to, true)}`
date = new Date(dateString);
}
}
export function parseUTCDate(dateString) {
return dayjs.utc(dateString)
}
export function parseNaiveDate(dateString) {
return dayjs(dateString)
return new Date(date.getTime() + date.getTimezoneOffset() * 60000);
}
// https://stackoverflow.com/a/11124448
export function nowForSite(site) {
return dayjs.utc().utcOffset(site.offset / 60)
const browserOffset = (new Date()).getTimezoneOffset() * 60
return new Date(new Date().getTime() + (site.offset * 1000) + (browserOffset * 1000))
}
export function lastMonth(site) {
@ -88,44 +90,43 @@ export function isThisMonth(site, date) {
}
export function isThisYear(site, date) {
return date.year() === nowForSite(site).year()
return date.getFullYear() === nowForSite(site).getFullYear()
}
export function isBefore(date1, date2, period) {
/* assumes 'day' and 'month' are the only valid periods */
if (date1.year() !== date2.year()) {
return date1.year() < date2.year();
if (date1.getFullYear() !== date2.getFullYear()) {
return date1.getFullYear() < date2.getFullYear();
}
if (period === "year") {
return false;
}
if (date1.month() !== date2.month()) {
return date1.month() < date2.month();
if (date1.getMonth() !== date2.getMonth()) {
return date1.getMonth() < date2.getMonth();
}
if (period === "month") {
return false;
}
return date1.date() < date2.date()
return date1.getDate() < date2.getDate()
}
export function isAfter(date1, date2, period) {
/* assumes 'day' and 'month' are the only valid periods */
if (date1.year() !== date2.year()) {
return date1.year() > date2.year();
if (date1.getFullYear() !== date2.getFullYear()) {
return date1.getFullYear() > date2.getFullYear();
}
if (period === "year") {
return false;
}
if (date1.month() !== date2.month()) {
return date1.month() > date2.month();
if (date1.getMonth() !== date2.getMonth()) {
return date1.getMonth() > date2.getMonth();
}
if (period === "month") {
return false;
}
return date1.date() > date2.date()
return date1.getDate() > date2.getDate()
}
export function monthsBetweenDates(date1, date2) {
var diffMonths = (date2.year() - date1.year()) * 12 + date2.month() - date1.month();
return Math.abs(diffMonths);
function formatMonthShort(date) {
return `${MONTHS[date.getMonth()].substring(0, 3)}`;
}

@ -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',
}

@ -20,59 +20,3 @@ export function externalLinkForPage(domain, page) {
const domainURL = new URL(`https://${domain}`)
return `https://${domainURL.host}${page}`
}
export function isValidHttpUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
export function trimURL(url, maxLength) {
if (url.length <= maxLength) {
return url;
}
const ellipsis = "...";
if (isValidHttpUrl(url)) {
const [protocol, restURL] = url.split('://');
const parts = restURL.split('/');
const host = parts.shift();
if (host.length > maxLength - 5) {
return `${protocol}://${host.substr(0, maxLength - 5)}${ellipsis}${restURL.slice(-maxLength + 5)}`;
}
let remainingLength = maxLength - host.length - 5;
let trimmedURL = `${protocol}://${host}`;
for (const part of parts) {
if (part.length <= remainingLength) {
trimmedURL += '/' + part;
remainingLength -= part.length + 1;
} else {
const startTrim = Math.floor((remainingLength - 3) / 2);
const endTrim = Math.ceil((remainingLength - 3) / 2);
trimmedURL += `/${part.substr(0, startTrim)}...${part.slice(-endTrim)}`;
break;
}
}
return trimmedURL;
} else {
const leftSideLength = Math.floor(maxLength / 2);
const rightSideLength = maxLength - leftSideLength;
const leftSide = url.slice(0, leftSideLength);
const rightSide = url.slice(-rightSideLength);
return leftSide + ellipsis + rightSide;
}
}

@ -2,8 +2,7 @@ import iframeResize from 'iframe-resizer/js/iframeResizer'
var iframes = iframeResize({
heightCalculationMethod: 'taggedElement',
onInit: onInit,
checkOrigin: false
onInit: onInit
}, '[plausible-embed]')
function onInit() {

@ -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()
},
})

@ -1,57 +0,0 @@
import "phoenix_html"
import Alpine from 'alpinejs'
import { Socket } from "phoenix"
import { LiveSocket } from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']")
let websocketUrl = document.querySelector("meta[name='websocket-url']")
if (csrfToken && websocketUrl) {
let Hooks = {}
Hooks.Metrics = {
mounted() {
this.handleEvent("send-metrics", ({ event_name, params }) => {
const afterMetrics = () => {
this.pushEvent("send-metrics-after", {event_name, params})
}
setTimeout(afterMetrics, 5000)
params.callback = afterMetrics
window.plausible(event_name, params)
})
}
}
let Uploaders = {}
Uploaders.S3 = function (entries, onViewError) {
entries.forEach(entry => {
let xhr = new XMLHttpRequest()
onViewError(() => xhr.abort())
xhr.onload = () => xhr.status === 200 ? entry.progress(100) : entry.error()
xhr.onerror = () => entry.error()
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable) {
let percent = Math.round((event.loaded / event.total) * 100)
if (percent < 100) { entry.progress(percent) }
}
})
let url = entry.meta.url
xhr.open("PUT", url, true)
xhr.send(entry.file)
})
}
let token = csrfToken.getAttribute("content")
let url = websocketUrl.getAttribute("content")
let liveUrl = (url === "") ? "/live" : new URL("/live", url).href;
let liveSocket = new LiveSocket(liveUrl, Socket, {
heartbeatIntervalMs: 10000,
params: { _csrf_token: token }, hooks: Hooks, uploaders: Uploaders, dom: {
// for alpinejs integration
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
Alpine.clone(from, to);
}
},
}
})
liveSocket.connect()
window.liveSocket = liveSocket
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save