Compare commits

..

No commits in common. 'master' and 'list' have entirely different histories.
master ... list

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

@ -2,5 +2,5 @@
plugins: [Phoenix.LiveView.HTMLFormatter], plugins: [Phoenix.LiveView.HTMLFormatter],
import_deps: [:ecto, :ecto_sql, :phoenix], import_deps: [:ecto, :ecto_sql, :phoenix],
subdirectories: ["priv/*/migrations"], subdirectories: ["priv/*/migrations"],
inputs: ["*.{heex,ex,exs}", "{config,lib,test,extra}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"] inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
] ]

@ -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,6 +5,7 @@ on:
branches: [master, stable] branches: [master, stable]
tags: ['r*'] tags: ['r*']
pull_request: pull_request:
branches: [master]
types: [synchronize, labeled] types: [synchronize, labeled]
concurrency: concurrency:
@ -19,7 +20,7 @@ jobs:
steps: steps:
- name: Docker meta - name: Docker meta
id: meta id: meta
uses: docker/metadata-action@v5.0.0 uses: docker/metadata-action@v5
with: with:
images: plausible/analytics-private images: plausible/analytics-private
tags: | tags: |
@ -46,7 +47,6 @@ jobs:
cache-from: type=gha cache-from: type=gha
cache-to: type=gha,mode=max cache-to: type=gha,mode=max
build-args: | build-args: |
MIX_ENV=prod
BUILD_METADATA=${{ steps.meta.outputs.json }} BUILD_METADATA=${{ steps.meta.outputs.json }}
- name: Image digest - 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>"}'

@ -17,7 +17,7 @@ jobs:
id: meta id: meta
uses: docker/metadata-action@v5 uses: docker/metadata-action@v5
with: with:
images: plausible/community-edition images: plausible/analytics
tags: | tags: |
type=semver,pattern={{version}},prefix=v type=semver,pattern={{version}},prefix=v
type=semver,pattern={{major}}.{{minor}},prefix=v type=semver,pattern={{major}}.{{minor}},prefix=v
@ -46,9 +46,8 @@ jobs:
cache-from: type=gha cache-from: type=gha
cache-to: type=gha,mode=max cache-to: type=gha,mode=max
build-args: | build-args: |
MIX_ENV=small
BUILD_METADATA=${{ steps.meta.outputs.json }} BUILD_METADATA=${{ steps.meta.outputs.json }}
ERL_FLAGS=+JMsingle true ERL_FLAGS=+JPperf true
- name: Image digest - name: Image digest
run: echo ${{ steps.docker_build.outputs.digest }} run: echo ${{ steps.docker_build.outputs.digest }}

@ -1,42 +1,27 @@
name: Elixir CI name: Elixir CI
on: on:
pull_request:
push: push:
branches: [master, stable] branches: [master, stable]
pull_request:
branches: [master, stable]
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.ref }} group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true cancel-in-progress: true
env:
CACHE_VERSION: v7
PERSISTENT_CACHE_DIR: cached
jobs: jobs:
build: build:
name: "Build and test (${{ matrix.mix_env }}, ${{ matrix.postgres_image }}${{ matrix.test_experimental_reduced_joins == '1' && ', experimental_reduced_joins' || '' }})" name: Build and test
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
mix_env: ['test', 'small_test'] postgres_version: [13, 14, 15]
postgres_image: ['postgres:16']
test_experimental_reduced_joins: ['0']
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: services:
postgres: postgres:
image: ${{ matrix.postgres_image }} image: postgres:${{ matrix.postgres_version }}
ports: ports:
- 5432:5432 - 5432:5432
env: env:
@ -46,6 +31,7 @@ jobs:
--health-interval 10s --health-interval 10s
--health-timeout 5s --health-timeout 5s
--health-retries 5 --health-retries 5
clickhouse: clickhouse:
image: clickhouse/clickhouse-server:23.3.7.5-alpine image: clickhouse/clickhouse-server:23.3.7.5-alpine
ports: ports:
@ -56,91 +42,41 @@ jobs:
--health-interval 10s --health-interval 10s
--health-timeout 5s --health-timeout 5s
--health-retries 5 --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: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Read .tool-versions
- uses: marocchino/tool-versions-action@v1 uses: marocchino/tool-versions-action@v1
id: versions id: versions
- uses: erlef/setup-beam@v1 - name: Set up Elixir
uses: erlef/setup-beam@v1
with: with:
elixir-version: ${{ steps.versions.outputs.elixir }} elixir-version: ${{steps.versions.outputs.elixir}}
otp-version: ${{ steps.versions.outputs.erlang }} otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore dependencies cache
- uses: actions/cache@v4 uses: buildjet/cache@v3
with: with:
path: | path: |
deps deps
_build _build
priv/plts priv/plts
key: static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}-${{ hashFiles('**/mix.lock') }} key: ${{ runner.os }}-mix-v5-${{ hashFiles('**/mix.lock') }}
restore-keys: | restore-keys: ${{ runner.os }}-mix-v5-
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-${{ github.head_ref || github.ref }}- - name: Install dependencies
static-${{ env.MIX_ENV }}-${{ env.CACHE_VERSION }}-refs/heads/master- run: mix deps.get && npm install --prefix ./tracker
- name: Check Formatting
- run: mix deps.get run: mix format --check-formatted
- run: mix compile --warnings-as-errors --all-warnings - name: Check Compile Warnings
- run: mix format --check-formatted run: mix compile --warnings-as-errors --all-warnings
- run: mix deps.unlock --check-unused - name: Generate tracker files
- run: mix credo diff --from-git-merge-base origin/master run: npm run deploy --prefix ./tracker
- run: mix dialyzer - 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,6 +4,7 @@ on:
push: push:
branches: [master, stable] branches: [master, stable]
pull_request: pull_request:
branches: [master, stable]
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.ref }} group: ${{ github.workflow }}-${{ github.ref }}
@ -20,11 +21,17 @@ jobs:
uses: marocchino/tool-versions-action@v1 uses: marocchino/tool-versions-action@v1
id: versions id: versions
- name: Set up Node - name: Set up Node
uses: actions/setup-node@v4 uses: actions/setup-node@v3
with: with:
node-version: ${{steps.versions.outputs.nodejs}} node-version: ${{steps.versions.outputs.nodejs}}
- run: npm install --prefix ./assets - run: npm install --prefix ./assets
- run: npm install --prefix ./tracker - run: npm install --prefix ./tracker
- run: npm run lint --prefix ./assets - run: npm run lint --prefix ./assets
- run: npm run check-format --prefix ./assets - run: npm run check-format --prefix ./assets
- run: npm run deploy --prefix ./assets
- run: npm run deploy --prefix ./tracker - 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!

@ -35,7 +35,7 @@ jobs:
otp-version: ${{ steps.versions.outputs.erlang}} otp-version: ${{ steps.versions.outputs.erlang}}
- name: Restore Elixir dependencies cache - name: Restore Elixir dependencies cache
uses: actions/cache@v4 uses: actions/cache@v3
with: with:
path: | path: |
deps deps

@ -7,6 +7,8 @@ on:
paths: paths:
- 'test/e2e/**.tf' - 'test/e2e/**.tf'
pull_request: pull_request:
branches:
- master
paths: paths:
- 'test/e2e/**.tf' - 'test/e2e/**.tf'
@ -30,7 +32,7 @@ jobs:
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Setup Terraform - name: Setup Terraform
uses: hashicorp/setup-terraform@v3 uses: hashicorp/setup-terraform@v2
with: with:
cli_config_credentials_token: ${{ secrets.TF_CLOUD_CHECKLY_API_TOKEN }} cli_config_credentials_token: ${{ secrets.TF_CLOUD_CHECKLY_API_TOKEN }}
@ -52,7 +54,7 @@ jobs:
run: terraform plan -no-color run: terraform plan -no-color
continue-on-error: true continue-on-error: true
- uses: actions/github-script@v7 - uses: actions/github-script@v6
if: github.event_name == 'pull_request' if: github.event_name == 'pull_request'
env: env:
PLAN: "terraform\n${{ steps.plan.outputs.stdout }}" PLAN: "terraform\n${{ steps.plan.outputs.stdout }}"

@ -16,7 +16,7 @@ jobs:
runs-on: buildjet-4vcpu-ubuntu-2004 runs-on: buildjet-4vcpu-ubuntu-2004
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v3
with: with:
node-version: 16 node-version: 16
- name: Install dependencies - name: Install dependencies

7
.gitignore vendored

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

@ -4,7 +4,7 @@ alias Plausible.{Site, Sites, Goal, Goals, Stats}
import_if_available(Ecto.Query) import_if_available(Ecto.Query)
import_if_available(Plausible.Factory) import_if_available(Plausible.Factory)
Logger.configure(level: :warning) Logger.configure(level: :warn)
IO.puts( IO.puts(
IO.ANSI.cyan() <> IO.ANSI.cyan() <>

@ -1,3 +1,4 @@
erlang 26.2.1 erlang 25.2.3
elixir 1.16.0-otp-26 elixir 1.14.3-otp-25
nodejs 21.0.0 nodejs 18.17.1
python 3.9.12

@ -1,25 +1,9 @@
# Changelog # Changelog
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## Unreleased
### Added ### 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 `referrers.csv` to CSV export
- Add a new Properties section in the dashboard to break down by custom properties - 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 `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)
@ -28,42 +12,18 @@ All notable changes to this project will be documented in this file.
- Adds Gravatar profile image to navbar - Adds Gravatar profile image to navbar
- Enforce email reverification on update - Enforce email reverification on update
- Add Plugins API Tokens provisioning UI - 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
- Removed the nested custom event property breakdown UI when filtering by a goal in Goal Conversions - 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 - 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 ### 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 - 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 - 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 - 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 - 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 ### 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 - 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) - 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 - Fix [broken interval selection](https://github.com/plausible/analytics/issues/2982) in the all time view plausible/analytics#3110
@ -74,13 +34,6 @@ All notable changes to this project will be documented in this file.
- Update bot detection (matomo 6.1.4, ua_inspector 3.4.0) - Update bot detection (matomo 6.1.4, ua_inspector 3.4.0)
- Improved the Goal Settings page (search, autcompletion etc.) - Improved the Goal Settings page (search, autcompletion etc.)
- Log mailer errors plausible/analytics#3336 - 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 ## v2.0.0 - 2023-07-12

@ -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. 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. 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. 6. Run `npm ci --prefix tracker` to install the required tracker dependencies.
7. Run `mix assets.setup` to install Tailwind and Esbuild 7. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js`
8. Run `npm run deploy --prefix tracker` to generate tracker files in `priv/tracker/js` 8. Run `mix download_country_database` to fetch geolocation database
9. Run `mix download_country_database` to fetch geolocation database
3. Run `make server` or `mix phx.server` to start the Phoenix server. 3. Run `make server` or `mix phx.server` to start the Phoenix server.
4. The system is now available on `localhost:8000`. 4. The system is now available on `localhost:8000`.

@ -2,12 +2,10 @@
# platform specific, it makes sense to build it in the docker # platform specific, it makes sense to build it in the docker
#### Builder #### Builder
FROM hexpm/elixir:1.16.0-erlang-26.2.1-alpine-3.18.4 as buildcontainer FROM hexpm/elixir:1.14.3-erlang-25.2.3-alpine-3.18.0 as buildcontainer
ARG MIX_ENV=small
# preparation # preparation
ENV MIX_ENV=$MIX_ENV ENV MIX_ENV=prod
ENV NODE_ENV=production ENV NODE_ENV=production
ENV NODE_OPTIONS=--openssl-legacy-provider ENV NODE_OPTIONS=--openssl-legacy-provider
@ -21,7 +19,8 @@ WORKDIR /app
# install build dependencies # install build dependencies
RUN apk add --no-cache git nodejs yarn python3 npm ca-certificates wget gnupg make gcc libc-dev && \ RUN apk add --no-cache git nodejs yarn python3 npm ca-certificates wget gnupg make gcc libc-dev && \
npm install npm@latest -g npm install npm@latest -g && \
npm install -g webpack
COPY mix.exs ./ COPY mix.exs ./
COPY mix.lock ./ COPY mix.lock ./
@ -41,37 +40,38 @@ COPY assets ./assets
COPY tracker ./tracker COPY tracker ./tracker
COPY priv ./priv COPY priv ./priv
COPY lib ./lib COPY lib ./lib
COPY extra ./extra
RUN npm run deploy --prefix ./tracker && \ RUN npm run deploy --prefix ./assets && \
mix assets.deploy && \ npm run deploy --prefix ./tracker && \
mix phx.digest priv/static && \ mix phx.digest priv/static && \
mix download_country_database && \ 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 WORKDIR /app
COPY rel rel COPY rel rel
RUN mix release plausible RUN mix release plausible
# Main Docker Image # Main Docker Image
FROM alpine:3.18.4 FROM alpine:3.18.0
LABEL maintainer="plausible.io <hello@plausible.io>" LABEL maintainer="plausible.io <hello@plausible.io>"
ARG BUILD_METADATA={} ARG BUILD_METADATA={}
ENV BUILD_METADATA=$BUILD_METADATA ENV BUILD_METADATA=$BUILD_METADATA
ENV LANG=C.UTF-8 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 upgrade --no-cache
RUN apk add --no-cache openssl ncurses libstdc++ libgcc ca-certificates 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 ./rel/docker-entrypoint.sh /entrypoint.sh
COPY --chmod=755 ./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 WORKDIR /app
ENV LISTEN_IP=0.0.0.0 ENV LISTEN_IP=0.0.0.0
ENTRYPOINT ["/entrypoint.sh"] ENTRYPOINT ["/entrypoint.sh"]

@ -18,7 +18,7 @@ server: ## Start the web server
CH_FLAGS ?= --detach -p 8123:8123 -p 9000:9000 --ulimit nofile=262144:262144 --name plausible_clickhouse CH_FLAGS ?= --detach -p 8123:8123 -p 9000:9000 --ulimit nofile=262144:262144 --name plausible_clickhouse
clickhouse: ## Start a container with a recent version of 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 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:23.3.7.5-alpine
@ -36,12 +36,3 @@ postgres-prod: ## Start a container with the same version of postgres as the one
postgres-stop: ## Stop and remove the postgres container postgres-stop: ## Stop and remove the postgres container
docker stop plausible_db && docker rm plausible_db 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 /> <br /><br />
</p> </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 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 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. 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,7 +23,7 @@ We are dedicated to making web analytics more privacy-friendly. Our mission is t
## Why Plausible? ## 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 11,000+ paying subscribers to deliver their website and business insights:
- **Clutter Free**: Plausible Analytics provides [simple web analytics](https://plausible.io/simple-web-analytics) and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary. - **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) - **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)
@ -49,32 +49,30 @@ We choose the subscription business model rather than the business model of surv
## Getting started with Plausible ## 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. 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! 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 [open source web analytics](https://plausible.io/open-source-website-analytics) and we have a free as in beer [self-hosted solution](https://plausible.io/self-hosted-web-analytics). Here are the differences between Plausible Analytics managed hosting in the cloud and the self-hosting:
| | Plausible Analytics Cloud | Plausible Community Edition | | | 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.| | 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. |
| **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.| | 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. |
| **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).| | Features | 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. Selected premium features are not available as we aim to ensure a protective barrier around our cloud offering. |
| **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.| | 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. |
| **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.| | 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. |
| **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. | | 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.|
| **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.|
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 ## Technology
@ -95,7 +93,7 @@ To stay up to date with all the latest news and product updates, make sure to fo
## License & Trademarks ## License & Trademarks
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). 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).
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). 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).

@ -7,8 +7,6 @@ want be up to date on security patches, make sure your Plausible image is up to
## Reporting a Vulnerability ## 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. 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. 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,20 +1,14 @@
@import "tailwindcss/base"; /* purgecss start ignore */
@import "flatpickr/dist/flatpickr.min.css"; @tailwind base;
@import "./modal.css"; @tailwind components;
@import "./loader.css";
@import "./tooltip.css";
@import "./flatpickr.css";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
[x-cloak] { display: none; } /* purgecss end ignore */
@import "modal.css";
@import "loader.css";
@import "tooltip.css";
@import "flatpickr.css";
@media print { [x-cloak] { display: none; }
canvas {
width: 100% !important;
height: auto !important;
}
}
.button { .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; @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;
@ -71,6 +65,8 @@ blockquote {
} }
} }
@tailwind utilities;
.light-text { .light-text {
color: #F0F4F8; color: #F0F4F8;

@ -1,3 +1,5 @@
import "../css/app.css"
import "flatpickr/dist/flatpickr.min.css"
import "./polyfills/closest" import "./polyfills/closest"
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch' import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
import Alpine from 'alpinejs' import Alpine from 'alpinejs'
@ -10,16 +12,6 @@ Alpine.data('dropdown', dropdown)
Alpine.data('comboBox', comboBox) Alpine.data('comboBox', comboBox)
Alpine.start() 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 })
)
})
}
const triggers = document.querySelectorAll('[data-dropdown-trigger]') const triggers = document.querySelectorAll('[data-dropdown-trigger]')
for (const trigger of triggers) { for (const trigger of triggers) {

@ -1,4 +1,4 @@
import { formatISO } from './util/date' import {formatISO} from './util/date'
let abortController = new AbortController() let abortController = new AbortController()
let SHARED_LINK_AUTH = null let SHARED_LINK_AUTH = null
@ -36,14 +36,13 @@ function serializeFilters(filters) {
return JSON.stringify(cleaned) return JSON.stringify(cleaned)
} }
export function serializeQuery(query, extraQuery = []) { export function serializeQuery(query, extraQuery=[]) {
const queryObj = {} const queryObj = {}
if (query.period) { queryObj.period = query.period } if (query.period) { queryObj.period = query.period }
if (query.date) { queryObj.date = formatISO(query.date) } if (query.date) { queryObj.date = formatISO(query.date) }
if (query.from) { queryObj.from = formatISO(query.from) } if (query.from) { queryObj.from = formatISO(query.from) }
if (query.to) { queryObj.to = formatISO(query.to) } if (query.to) { queryObj.to = formatISO(query.to) }
if (query.filters) { queryObj.filters = serializeFilters(query.filters) } 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.with_imported) { queryObj.with_imported = query.with_imported }
if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH } if (SHARED_LINK_AUTH) { queryObj.auth = SHARED_LINK_AUTH }
@ -59,11 +58,11 @@ export function serializeQuery(query, extraQuery = []) {
return '?' + serialize(queryObj) return '?' + serialize(queryObj)
} }
export function get(url, query = {}, ...extraQuery) { export function get(url, query={}, ...extraQuery) {
const headers = SHARED_LINK_AUTH ? { 'X-Shared-Link-Auth': SHARED_LINK_AUTH } : {} const headers = SHARED_LINK_AUTH ? {'X-Shared-Link-Auth': SHARED_LINK_AUTH} : {}
url = url + serializeQuery(query, extraQuery) url = url + serializeQuery(query, extraQuery)
return fetch(url, { signal: abortController.signal, headers: headers }) return fetch(url, {signal: abortController.signal, headers: headers})
.then(response => { .then( response => {
if (!response.ok) { if (!response.ok) {
return response.json().then((msg) => { return response.json().then((msg) => {
throw new ApiError(msg.error, msg) throw new ApiError(msg.error, msg)

@ -66,9 +66,8 @@ function ComparisonModeOption({ label, value, isCurrentlySelected, updateMode, s
} }
const render = ({ active }) => { const render = ({ active }) => {
const buttonClass = classNames("px-4 py-2 w-full text-left text-sm dark:text-white", { const buttonClass = classNames("px-4 py-2 w-full text-left font-medium text-sm dark:text-white cursor-pointer", {
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": active, "bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": active,
"font-medium": !isCurrentlySelected,
"font-bold": isCurrentlySelected, "font-bold": isCurrentlySelected,
}) })
@ -91,9 +90,8 @@ function MatchDayOfWeekInput({ history, query, site }) {
} }
const buttonClass = (hover, selected) => const buttonClass = (hover, selected) =>
classNames("px-4 py-2 w-full text-left text-sm dark:text-white cursor-pointer", { classNames("px-4 py-2 w-full text-left font-medium text-sm dark:text-white cursor-pointer", {
"bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": hover, "bg-gray-100 text-gray-900 dark:bg-gray-900 dark:text-gray-100": hover,
"font-medium": !selected,
"font-bold": selected, "font-bold": selected,
}) })
@ -183,7 +181,7 @@ const ComparisonInput = function({ site, query, history }) {
</Transition> </Transition>
{ uiMode == "datepicker" && { uiMode == "datepicker" &&
<div className="h-0 md:absolute"> <div className="h-0 absolute">
<Flatpickr ref={calendar} options={flatpickrOptions} className="invisible" /> <Flatpickr ref={calendar} options={flatpickrOptions} className="invisible" />
</div> } </div> }
</Menu> </Menu>

@ -91,10 +91,8 @@ export default function PlausibleCombobox(props) {
} }
} }
function isOptionDisabled(option) { function isDisabled(option) {
const optionAlreadySelected = props.values.some((val) => val.value === option.value) return props.values.some((val) => val.value === option.value)
const optionDisabled = (props.disabledOptions || []).some((val) => val?.value === option.value)
return optionAlreadySelected || optionDisabled
} }
function fetchOptions(query) { function fetchOptions(query) {
@ -159,10 +157,10 @@ export default function PlausibleCombobox(props) {
}, []) }, [])
useEffect(() => { useEffect(() => {
if (props.singleOption && props.values.length === 0 && props.autoFocus) { if (props.singleOption && props.values.length === 0) {
searchRef.current.focus() searchRef.current.focus()
} }
}, [props.values.length === 0, props.singleOption, props.autoFocus]) }, [props.values.length === 0])
const searchBoxClass = 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm' const searchBoxClass = 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm'
@ -219,7 +217,7 @@ export default function PlausibleCombobox(props) {
} }
function renderDropDownContent() { function renderDropDownContent() {
const matchesFound = visibleOptions.length > 0 && visibleOptions.some(option => !isOptionDisabled(option)) const matchesFound = visibleOptions.length > 0 && visibleOptions.some(option => !isDisabled(option))
if (loading) { if (loading) {
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Loading options...</div> return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Loading options...</div>
@ -227,7 +225,7 @@ export default function PlausibleCombobox(props) {
if (matchesFound) { if (matchesFound) {
return visibleOptions return visibleOptions
.filter(option => !isOptionDisabled(option)) .filter(option => !isDisabled(option))
.map((option, i) => { .map((option, i) => {
const text = option.freeChoice ? `Filter by '${option.label}'` : option.label const text = option.freeChoice ? `Filter by '${option.label}'` : option.label

@ -1,6 +1,6 @@
import React, { Fragment } from "react"; import React, { Fragment } from "react";
import { FILTER_OPERATIONS } from "../util/filters"; import { FILTER_TYPES } from "../util/filters";
import { Menu, Transition } from "@headlessui/react"; import { Menu, Transition } from "@headlessui/react";
import { ChevronDownIcon } from '@heroicons/react/20/solid' import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { isFreeChoiceFilter, supportsIsNot } from "../util/filters"; import { isFreeChoiceFilter, supportsIsNot } from "../util/filters";
@ -61,9 +61,9 @@ export default function FilterTypeSelector(props) {
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" 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"> <div className="py-1">
{renderTypeItem(FILTER_OPERATIONS.is, true)} {renderTypeItem(FILTER_TYPES.is, true)}
{renderTypeItem(FILTER_OPERATIONS.isNot, supportsIsNot(filterName))} {renderTypeItem(FILTER_TYPES.isNot, supportsIsNot(filterName))}
{renderTypeItem(FILTER_OPERATIONS.contains, isFreeChoiceFilter(filterName))} {renderTypeItem(FILTER_TYPES.contains, isFreeChoiceFilter(filterName))}
</div> </div>
</Menu.Items> </Menu.Items>
</Transition> </Transition>

@ -2,7 +2,7 @@ import React from "react"
import { sectionTitles } from "../stats/behaviours" import { sectionTitles } from "../stats/behaviours"
import * as api from '../api' import * as api from '../api'
export function FeatureSetupNotice({ site, feature, title, info, callToAction, onHideAction }) { export function FeatureSetupNotice({ site, feature, shortFeatureName, title, info, settingsLink, onHideAction }) {
const sectionTitle = sectionTitles[feature] const sectionTitle = sectionTitles[feature]
const requestHideSection = () => { const requestHideSection = () => {
@ -14,10 +14,10 @@ export function FeatureSetupNotice({ site, feature, title, info, callToAction, o
} }
} }
function renderCallToAction() { function setupButton() {
return ( return (
<a href={callToAction.link} className="ml-2 sm:ml-4 button px-2 sm:px-4"> <a href={settingsLink} 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> <p className="flex flex-col justify-center text-xs sm:text-sm">Set up {shortFeatureName}</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"> <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" /> <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75" />
</svg> </svg>
@ -25,7 +25,7 @@ export function FeatureSetupNotice({ site, feature, title, info, callToAction, o
) )
} }
function renderHideButton() { function hideButton() {
return ( return (
<button <button
onClick={requestHideSection} onClick={requestHideSection}
@ -47,8 +47,8 @@ export function FeatureSetupNotice({ site, feature, title, info, callToAction, o
</div> </div>
<div className="text-xs sm:text-sm flex my-6 justify-center"> <div className="text-xs sm:text-sm flex my-6 justify-center">
{renderHideButton()} {hideButton()}
{renderCallToAction()} {setupButton()}
</div> </div>
</div> </div>
</div> </div>

@ -1,5 +0,0 @@
Plausible copyright notice
This software is Copyright 2024 Plausible Insights OÜ
This repository is provided for informational purposes only, and no rights to use, distribute or otherwise exploit this software are granted to you. Our other repositories include software that is offered under the Affero GPL, but this repository is not. If you wish to discuss a license, or our hosted service that uses the software, please contact us at hello@plausible.io

@ -10,23 +10,12 @@ import {
formatFilterGroup, formatFilterGroup,
filterGroupForFilter, filterGroupForFilter,
parseQueryFilter, parseQueryFilter,
parseQueryPropsFilter,
formattedFilters formattedFilters
} from "./util/filters"; } from "./util/filters";
function removeFilter(filterType, key, history, query) { function removeFilter(key, history, query) {
const newOpts = {} const newOpts = {
if (filterType === 'props') { [key]: false
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
} }
if (key === 'country') { newOpts.country_labels = false } if (key === 'country') { newOpts.country_labels = false }
if (key === 'region') { newOpts.region_labels = false } if (key === 'region') { newOpts.region_labels = false }
@ -48,38 +37,34 @@ function clearAllFilters(history, query) {
); );
} }
function filterText(filterType, key, query) { function filterText(key, _rawValue, query) {
const {type, clauses} = parseQueryFilter(query, key)
const formattedFilter = formattedFilters[key] const formattedFilter = formattedFilters[key]
if (filterType === "props") { if (key === "props") {
const { propKey, clauses, type } = parseQueryPropsFilter(query).find((filter) => filter.propKey.value === key) const [[propKey, _propValue]] = Object.entries(query.filters['props'])
return <>Property <b>{propKey.label}</b> {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </> return <>Property <b>{propKey}</b> {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
} else if (formattedFilter) { } 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])} </> return <>{formattedFilter} {type} {clauses.map(({label}) => <b key={label}>{label}</b>).reduce((prev, curr) => [prev, ' or ', curr])} </>
} }
throw new Error(`Unknown filter: ${key}`) throw new Error(`Unknown filter: ${key}`)
} }
function renderDropdownFilter(site, history, { key, value, filterType }, query) { function renderDropdownFilter(site, history, [key, value], query) {
return ( 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}> <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 <Link
title={`Edit filter: ${formattedFilters[filterType]}`} title={`Edit filter: ${formattedFilters[key]}`}
to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(filterType)}`, search: window.location.search }} to={{ pathname: `/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(key)}`, search: window.location.search }}
className="group flex w-full justify-between items-center" className="group flex w-full justify-between items-center"
style={{ width: 'calc(100% - 1.5rem)' }} 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" /> <PencilSquareIcon className="w-4 h-4 ml-1 cursor-pointer group-hover:text-indigo-700 dark:group-hover:text-indigo-500" />
</Link> </Link>
<b <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)}>
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)}
>
<XMarkIcon className="w-4 h-4" /> <XMarkIcon className="w-4 h-4" />
</b> </b>
</div> </div>
@ -110,7 +95,7 @@ function DropdownContent({ history, site, query, wrapped }) {
if (wrapped === 0 || addingFilter) { if (wrapped === 0 || addingFilter) {
let filterGroups = {...FILTER_GROUPS} let filterGroups = {...FILTER_GROUPS}
if (!site.propsAvailable) delete filterGroups.props if (!site.propsEnabled) delete filterGroups.props
return Object.keys(filterGroups).map((option) => filterDropdownOption(site, option)) return Object.keys(filterGroups).map((option) => filterDropdownOption(site, option))
} }
@ -217,21 +202,13 @@ class Filters extends React.Component {
}); });
}; };
renderListFilter(history, { key, value, filterType }, query) { renderListFilter(history, [key, value], query) {
return ( 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"> <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 <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 }}>
title={`Edit filter: ${formattedFilters[filterType]}`} <span className="inline-block max-w-2xs md:max-w-xs truncate">{filterText(key, value, query)}</span>
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>
</Link> </Link>
<span <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)}>
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)}
>
<XMarkIcon className="w-4 h-4" /> <XMarkIcon className="w-4 h-4" />
</span> </span>
</span> </span>
@ -258,10 +235,6 @@ class Filters extends React.Component {
) )
} }
trackFilterMenu() {
window.plausible && window.plausible('Filter Menu: Open', {u: `${window.location.protocol}//${window.location.hostname}/:dashboard`})
}
renderDropDown() { renderDropDown() {
const { history, query, site } = this.props; const { history, query, site } = this.props;
@ -270,7 +243,7 @@ class Filters extends React.Component {
{({ open }) => ( {({ open }) => (
<> <>
<div> <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()} {this.renderDropdownButton()}
</Menu.Button> </Menu.Button>
</div> </div>

@ -12,7 +12,7 @@ import Devices from './stats/devices'
import Behaviours from './stats/behaviours' import Behaviours from './stats/behaviours'
import ComparisonInput from './comparison-input' import ComparisonInput from './comparison-input'
import { withPinnedHeader } from './pinned-header-hoc'; import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index'; import { statsBoxClass } from '.';
function Historical(props) { function Historical(props) {
const tooltipBoundary = React.useRef(null) const tooltipBoundary = React.useRef(null)

@ -2,10 +2,10 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import 'url-search-params-polyfill'; import 'url-search-params-polyfill';
import Router from './dashboard/router' import Router from './router'
import ErrorBoundary from './dashboard/error-boundary' import ErrorBoundary from './error-boundary'
import * as api from './dashboard/api' import * as api from './api'
import * as timer from './dashboard/util/realtime-update-timer' import * as timer from './util/realtime-update-timer'
timer.start() timer.start()
@ -16,13 +16,10 @@ if (container) {
domain: container.dataset.domain, domain: container.dataset.domain,
offset: container.dataset.offset, offset: container.dataset.offset,
hasGoals: container.dataset.hasGoals === 'true', hasGoals: container.dataset.hasGoals === 'true',
conversionsEnabled: container.dataset.conversionsEnabled === 'true',
funnelsEnabled: container.dataset.funnelsEnabled === 'true',
propsEnabled: container.dataset.propsEnabled === 'true',
hasProps: container.dataset.hasProps === '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), funnels: JSON.parse(container.dataset.funnels),
statsBegin: container.dataset.statsBegin, statsBegin: container.dataset.statsBegin,
nativeStatsBegin: container.dataset.nativeStatsBegin, nativeStatsBegin: container.dataset.nativeStatsBegin,

@ -1,8 +1,8 @@
import React from 'react' import React from 'react'
import { Link, withRouter } from 'react-router-dom' import { Link, withRouter } from 'react-router-dom'
import { nowForSite } from './util/date' import {nowForSite} from './util/date'
import * as storage from './util/storage' import * as storage from './util/storage'
import { COMPARISON_DISABLED_PERIODS, getStoredComparisonMode, isComparisonEnabled, getStoredMatchDayOfWeek } from './comparison-input' import { COMPARISON_DISABLED_PERIODS, getStoredComparisonMode, isComparisonEnabled,getStoredMatchDayOfWeek } from './comparison-input'
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc'; import utc from 'dayjs/plugin/utc';
@ -39,7 +39,6 @@ export function parseQuery(querystring, site) {
to: q.get('to') ? dayjs.utc(q.get('to')) : undefined, to: q.get('to') ? dayjs.utc(q.get('to')) : undefined,
match_day_of_week: matchDayOfWeek == 'true', match_day_of_week: matchDayOfWeek == 'true',
with_imported: q.get('with_imported') ? q.get('with_imported') === 'true' : true, with_imported: q.get('with_imported') ? q.get('with_imported') === 'true' : true,
experimental_session_count: q.get('experimental_session_count'),
filters: { filters: {
'goal': q.get('goal'), 'goal': q.get('goal'),
'props': JSON.parse(q.get('props')), 'props': JSON.parse(q.get('props')),
@ -59,7 +58,6 @@ export function parseQuery(querystring, site) {
'region': q.get('region'), 'region': q.get('region'),
'city': q.get('city'), 'city': q.get('city'),
'page': q.get('page'), 'page': q.get('page'),
'hostname': q.get('hostname'),
'entry_page': q.get('entry_page'), 'entry_page': q.get('entry_page'),
'exit_page': q.get('exit_page') 'exit_page': q.get('exit_page')
} }
@ -67,13 +65,9 @@ export function parseQuery(querystring, site) {
} }
export function appliedFilters(query) { export function appliedFilters(query) {
const propKeys = Object.entries(query.filters.props || {}) return Object.keys(query.filters)
.map(([key, value]) => ({ key, value, filterType: 'props' })) .map((key) => [key, query.filters[key]])
.filter(([_key, value]) => !!value);
return Object.entries(query.filters)
.map(([key, value]) => ({ key, value, filterType: key }))
.filter(({ key, value }) => key !== 'props' && !!value)
.concat(propKeys)
} }
function generateQueryString(data) { function generateQueryString(data) {
@ -128,7 +122,7 @@ class QueryLink extends React.Component {
const QueryLinkWithRouter = withRouter(QueryLink) const QueryLinkWithRouter = withRouter(QueryLink)
export { QueryLinkWithRouter as QueryLink }; export { QueryLinkWithRouter as QueryLink };
function QueryButton({ history, query, to, disabled, className, children, onClick }) { function QueryButton({history, query, to, disabled, className, children, onClick}) {
return ( return (
<button <button
className={className} className={className}

@ -10,7 +10,7 @@ import Locations from './stats/locations'
import Devices from './stats/devices' import Devices from './stats/devices'
import Behaviours from './stats/behaviours' import Behaviours from './stats/behaviours'
import { withPinnedHeader } from './pinned-header-hoc'; import { withPinnedHeader } from './pinned-header-hoc';
import { statsBoxClass } from './index'; import { statsBoxClass } from '.';
class Realtime extends React.Component { class Realtime extends React.Component {
render() { render() {

@ -52,7 +52,7 @@ export default function Router({ site, loggedIn, currentUserRole }) {
<ExitPagesModal site={site} /> <ExitPagesModal site={site} />
</Route> </Route>
<Route path="/:domain/countries"> <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={url.apiPath(site, '/countries')} filter={{ country: 'code', country_labels: 'name' }} keyLabel="Country" renderIcon={renderCountryIcon} />
</Route> </Route>
<Route path="/:domain/regions"> <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={url.apiPath(site, '/regions')} filter={{ region: 'code', region_labels: 'name' }} keyLabel="Region" renderIcon={renderRegionIcon} />

@ -131,7 +131,7 @@ export default class SiteSwitcher extends React.Component {
domain === this.props.site.domain domain === this.props.site.domain
? 'font-medium text-gray-900 dark:text-gray-100 cursor-default font-bold' ? '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' : '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 ( return (
<a <a
href={ href={
@ -151,7 +151,7 @@ export default class SiteSwitcher extends React.Component {
{domain} {domain}
</span> </span>
</span> </span>
{showHotkey && index < 9 ? <span>{index + 1}</span> : null} {showHotkey ? index < 9 && <span>{index + 1}</span> : null}
</a> </a>
) )
} }
@ -164,9 +164,7 @@ export default class SiteSwitcher extends React.Component {
<React.Fragment> <React.Fragment>
<div className="py-1"> <div className="py-1">
<a <a
href={`/${encodeURIComponent( href={`/${encodeURIComponent(this.props.site.domain)}/settings`}
this.props.site.domain
)}/settings/general`}
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" 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" role="menuitem"
> >

@ -7,17 +7,16 @@ import { CR_METRIC } from '../reports/metrics';
import ListReport from '../reports/list'; import ListReport from '../reports/list';
export default function Conversions(props) { export default function Conversions(props) {
const { site, query } = props const {site, query} = props
function fetchConversions() { function fetchConversions() {
return api.get(url.apiPath(site, '/conversions'), query, { limit: 9 }) return api.get(url.apiPath(site, '/conversions'), query, {limit: 9})
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { goal: escapeFilterValue(listItem.name) } return {goal: escapeFilterValue(listItem.name)}
} }
/*global BUILD_EXTRA*/
return ( return (
<ListReport <ListReport
fetchData={fetchConversions} fetchData={fetchConversions}
@ -25,11 +24,11 @@ export default function Conversions(props) {
keyLabel="Goal" keyLabel="Goal"
onClick={props.onGoalFilterClick} onClick={props.onGoalFilterClick}
metrics={[ metrics={[
{ name: 'visitors', label: "Uniques", plot: true }, {name: 'visitors', label: "Uniques", plot: true},
{ name: 'events', label: "Total", hiddenOnMobile: true }, {name: 'events', label: "Total", hiddenOnMobile: true},
CR_METRIC, CR_METRIC,
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true }, {name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true},
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true } {name: 'average_revenue', label: 'Average', hiddenOnMobile: true}
]} ]}
detailsLink={url.sitePath(site, '/conversions')} detailsLink={url.sitePath(site, '/conversions')}
maybeHideDetails={true} maybeHideDetails={true}

@ -3,13 +3,13 @@ import FlipMove from 'react-flip-move';
import Chart from 'chart.js/auto' import Chart from 'chart.js/auto'
import FunnelTooltip from './funnel-tooltip.js' import FunnelTooltip from './funnel-tooltip.js'
import ChartDataLabels from 'chartjs-plugin-datalabels' import ChartDataLabels from 'chartjs-plugin-datalabels'
import numberFormatter from '../util/number-formatter' import numberFormatter from '../../util/number-formatter'
import Bar from '../stats/bar' import Bar from '../bar'
import RocketIcon from '../stats/modals/rocket-icon' import RocketIcon from '../modals/rocket-icon'
import * as api from '../api' import * as api from '../../api'
import LazyLoader from '../components/lazy-loader' import LazyLoader from '../../components/lazy-loader'
export default function Funnel(props) { export default function Funnel(props) {

@ -6,21 +6,10 @@ import * as storage from '../../util/storage'
import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions' import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions'
import Properties from './props' import Properties from './props'
import Funnel from './funnel'
import { FeatureSetupNotice } from '../../components/notice' import { FeatureSetupNotice } from '../../components/notice'
import { SPECIAL_GOALS } from './goal-conversions' 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 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' const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left'
@ -43,7 +32,7 @@ export default function Behaviours(props) {
const [mode, setMode] = useState(defaultMode()) const [mode, setMode] = useState(defaultMode())
const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name)) const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name))
const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel()) const [selectedFunnel, setSelectedFunnel] = useState(storage.getItem(funnelKey))
const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false) const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false)
@ -83,22 +72,8 @@ export default function Behaviours(props) {
} }
} }
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() { function hasFunnels() {
return site.funnels.length > 0 && site.funnelsAvailable return site.funnels.length > 0
} }
function tabFunnelPicker() { function tabFunnelPicker() {
@ -164,7 +139,7 @@ export default function Behaviours(props) {
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2"> <div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
{isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')} {isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')}
{isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')} {isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')}
{isEnabled(FUNNELS) && Funnel && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))} {isEnabled(FUNNELS) && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))}
</div> </div>
) )
} }
@ -178,12 +153,10 @@ export default function Behaviours(props) {
<FeatureSetupNotice <FeatureSetupNotice
site={site} site={site}
feature={CONVERSIONS} feature={CONVERSIONS}
shortFeatureName={'goals'}
title={'Measure how often visitors complete specific actions'} 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.'} info={'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'}
callToAction={{ settingsLink={`/${encodeURIComponent(site.domain)}/settings/goals`}
action: "Set up goals",
link: `/${encodeURIComponent(site.domain)}/settings/goals`
}}
onHideAction={onHideAction(CONVERSIONS)} onHideAction={onHideAction(CONVERSIONS)}
/> />
) )
@ -192,28 +165,16 @@ export default function Behaviours(props) {
} }
function renderFunnels() { function renderFunnels() {
if (Funnel === null) { if (selectedFunnel) { return <Funnel site={site} query={query} funnelName={selectedFunnel} /> }
return featureUnavailable() else if (adminAccess) {
}
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 ( return (
<FeatureSetupNotice <FeatureSetupNotice
site={site} site={site}
feature={FUNNELS} feature={FUNNELS}
shortFeatureName={'funnels'}
title={'Follow the visitor journey from entry to conversion'} 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.'} 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} settingsLink={`/${encodeURIComponent(site.domain)}/settings/funnels`}
onHideAction={onHideAction(FUNNELS)} onHideAction={onHideAction(FUNNELS)}
/> />
) )
@ -222,24 +183,17 @@ export default function Behaviours(props) {
} }
function renderProps() { function renderProps() {
if (site.hasProps && site.propsAvailable) { if (site.hasProps) {
return <Properties site={site} query={query} /> return <Properties site={site} query={query} />
} else if (adminAccess) { } 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 ( return (
<FeatureSetupNotice <FeatureSetupNotice
site={site} site={site}
feature={PROPS} feature={PROPS}
title={'Send custom data to create your own metrics'} shortFeatureName={'props'}
title={'No custom properties found'}
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.'} 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} settingsLink={`/${encodeURIComponent(site.domain)}/settings/properties`}
onHideAction={onHideAction(PROPS)} onHideAction={onHideAction(PROPS)}
/> />
) )
@ -254,14 +208,6 @@ export default function Behaviours(props) {
) )
} }
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) { function onHideAction(mode) {
return () => { disableMode(mode) } return () => { disableMode(mode) }
} }
@ -291,20 +237,15 @@ export default function Behaviours(props) {
function getEnabledModes() { function getEnabledModes() {
let enabledModes = [] let enabledModes = []
for (const feature of Object.keys(sectionTitles)) { if (site.conversionsEnabled) {
const isOptedOut = site[feature + 'OptedOut'] enabledModes.push(CONVERSIONS)
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)
} }
if (site.propsEnabled) {
enabledModes.push(PROPS)
}
if (site.funnelsEnabled && !isRealtime()) {
enabledModes.push(FUNNELS)
} }
return enabledModes return enabledModes
} }

@ -7,3 +7,4 @@ export default function Money({ formatted }) {
return "-" return "-"
} }
} }

@ -0,0 +1,199 @@
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'
import Money from './money'
import { isValidHttpUrl, trimURL } from '../../util/url'
const MOBILE_UPPER_WIDTH = 767
const DEFAULT_WIDTH = 1080
const BREAKDOWN_LIMIT = 100
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 });
}
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"
>
{trimURL(value.name, 100)}
</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}>
<div className="flex-1 truncate">
<Bar
count={value.unique_conversions}
plot="unique_conversions"
all={this.state.breakdown}
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
>
{this.renderPropContent(value, query)}
</Bar>
</div>
<div className="flex 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>
{this.props.renderRevenueColumn && <span className="hidden md:inline-block md:w-20 font-medium text-right"><Money formatted={value.total_revenue} /></span>}
{this.props.renderRevenueColumn && <span className="hidden md:inline-block md:w-20 font-medium text-right"><Money formatted={value.average_revenue} /></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,4 +1,4 @@
import React, { useCallback, useState } from "react" import React, { useCallback, useState, useEffect } from "react";
import ListReport from "../reports/list"; import ListReport from "../reports/list";
import Combobox from '../../components/combobox' import Combobox from '../../components/combobox'
import * as api from '../../api' import * as api from '../../api'
@ -15,6 +15,10 @@ export default function Properties(props) {
const [propKey, setPropKey] = useState(choosePropKey()) const [propKey, setPropKey] = useState(choosePropKey())
useEffect(() => {
setPropKey(choosePropKey())
}, [query.filters.goal, query.filters.props])
function singleGoalFilterApplied() { function singleGoalFilterApplied() {
const goalFilter = query.filters.goal const goalFilter = query.filters.goal
if (goalFilter) { if (goalFilter) {
@ -65,7 +69,6 @@ export default function Properties(props) {
} }
} }
/*global BUILD_EXTRA*/
function renderBreakdown() { function renderBreakdown() {
return ( return (
<ListReport <ListReport
@ -73,11 +76,11 @@ export default function Properties(props) {
getFilterFor={getFilterFor} getFilterFor={getFilterFor}
keyLabel={propKey} keyLabel={propKey}
metrics={[ metrics={[
{ name: 'visitors', label: 'Visitors', plot: true }, {name: 'visitors', label: 'Visitors', plot: true},
{ name: 'events', label: 'Events', hiddenOnMobile: true }, {name: 'events', label: 'Events', hiddenOnMobile: true},
query.filters.goal ? CR_METRIC : PERCENTAGE_METRIC, query.filters.goal ? CR_METRIC : PERCENTAGE_METRIC,
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true }, {name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true},
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true } {name: 'average_revenue', label: 'Average', hiddenOnMobile: true}
]} ]}
detailsLink={url.sitePath(site, `/custom-prop-values/${propKey}`)} detailsLink={url.sitePath(site, `/custom-prop-values/${propKey}`)}
maybeHideDetails={true} maybeHideDetails={true}
@ -88,18 +91,16 @@ export default function Properties(props) {
) )
} }
const getFilterFor = (listItem) => ({ const getFilterFor = (listItem) => { return {'props': JSON.stringify({[propKey]: escapeFilterValue(listItem.name)})} }
props: JSON.stringify({ ...query.filters.props, [propKey]: escapeFilterValue(listItem.name) }) const comboboxValues = propKey ? [{value: propKey, label: propKey}] : []
})
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' 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 ( return (
<div className="w-full mt-4"> <div className="w-full mt-4">
<div> <div>
<Combobox boxClass={boxClass} fetchOptions={fetchPropKeyOptions()} singleOption={true} values={comboboxValues} onSelect={onPropKeySelect()} placeholder={'Select a property'} /> <Combobox isDisabled={!!query.filters.props} boxClass={boxClass} fetchOptions={fetchPropKeyOptions()} singleOption={true} values={comboboxValues} onSelect={onPropKeySelect()} placeholder={'Select a property'} />
</div> </div>
{propKey && renderBreakdown()} { propKey && renderBreakdown() }
</div> </div>
) )
} }

@ -1,7 +1,6 @@
import React from 'react'; import React from 'react';
import * as storage from '../../util/storage' import * as storage from '../../util/storage'
import { isFilteringOnFixedValue } from '../../util/filters'
import ListReport from '../reports/list' import ListReport from '../reports/list'
import * as api from '../../api' import * as api from '../../api'
import * as url from '../../util/url' import * as url from '../../util/url'
@ -13,7 +12,7 @@ function Browsers({ query, site }) {
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { browser: listItem['name'] } return { browser: listItem['name']}
} }
return ( return (
@ -36,7 +35,7 @@ function BrowserVersions({ query, site }) {
if (query.filters.browser === '(not set)') { if (query.filters.browser === '(not set)') {
return {} return {}
} }
return { browser_version: listItem['name'] } return { browser_version: listItem['name']}
} }
return ( return (
@ -57,7 +56,7 @@ function OperatingSystems({ query, site }) {
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { os: listItem['name'] } return { os: listItem['name']}
} }
return ( return (
@ -80,7 +79,7 @@ function OperatingSystemVersions({ query, site }) {
if (query.filters.os === '(not set)') { if (query.filters.os === '(not set)') {
return {} return {}
} }
return { os_version: listItem['name'] } return { os_version: listItem['name']}
} }
return ( return (
@ -105,7 +104,7 @@ function ScreenSizes({ query, site }) {
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { screen: listItem['name'] } return { screen: listItem['name']}
} }
return ( return (
@ -162,12 +161,12 @@ export default class Devices extends React.Component {
renderContent() { renderContent() {
switch (this.state.mode) { switch (this.state.mode) {
case 'browser': 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 <BrowserVersions site={this.props.site} query={this.props.query} />
} }
return <Browsers site={this.props.site} query={this.props.query} /> return <Browsers site={this.props.site} query={this.props.query} />
case 'os': 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 <OperatingSystemVersions site={this.props.site} query={this.props.query} />
} }
return <OperatingSystems site={this.props.site} query={this.props.query} /> return <OperatingSystems site={this.props.site} query={this.props.query} />

@ -1,53 +1,27 @@
import numberFormatter, {durationFormatter} from '../../util/number-formatter' import numberFormatter, {durationFormatter} from '../../util/number-formatter'
import { parsePrefix } from '../../util/filters'
export function getGraphableMetrics(query, site) { export const METRIC_MAPPING = {
const isRealtime = query.period === 'realtime' 'Unique visitors (last 30 min)': 'visitors',
const goalFilter = query.filters.goal 'Pageviews (last 30 min)': 'pageviews',
const pageFilter = query.filters.page 'Unique visitors': 'visitors',
'Visit duration': 'visit_duration',
if (isRealtime && goalFilter) { 'Total pageviews': 'pageviews',
return ["visitors"] 'Views per visit': 'views_per_visit',
} else if (isRealtime) { 'Total visits': 'visits',
return ["visitors", "pageviews"] 'Bounce rate': 'bounce_rate',
} else if (goalFilter && canGraphRevenueMetrics(goalFilter, site)) { 'Unique conversions': 'conversions',
return ["visitors", "events", "average_revenue", "total_revenue", "conversion_rate"] 'Average revenue': 'average_revenue',
} else if (goalFilter) { 'Total revenue': 'total_revenue',
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
} }
export const METRIC_LABELS = { export const METRIC_LABELS = {
'visitors': 'Visitors', 'visitors': 'Visitors',
'pageviews': 'Pageviews', 'pageviews': 'Pageviews',
'events': 'Total Conversions',
'views_per_visit': 'Views per Visit', 'views_per_visit': 'Views per Visit',
'visits': 'Visits', 'visits': 'Visits',
'bounce_rate': 'Bounce Rate', 'bounce_rate': 'Bounce Rate',
'visit_duration': 'Visit Duration', 'visit_duration': 'Visit Duration',
'conversions': 'Converted Visitors', 'conversions': 'Converted Visitors',
'conversion_rate': 'Conversion Rate',
'average_revenue': 'Average Revenue', 'average_revenue': 'Average Revenue',
'total_revenue': 'Total Revenue', 'total_revenue': 'Total Revenue',
} }
@ -55,17 +29,23 @@ export const METRIC_LABELS = {
export const METRIC_FORMATTER = { export const METRIC_FORMATTER = {
'visitors': numberFormatter, 'visitors': numberFormatter,
'pageviews': numberFormatter, 'pageviews': numberFormatter,
'events': numberFormatter,
'visits': numberFormatter, 'visits': numberFormatter,
'views_per_visit': (number) => (number), 'views_per_visit': (number) => (number),
'bounce_rate': (number) => (`${number}%`), 'bounce_rate': (number) => (`${number}%`),
'visit_duration': durationFormatter, 'visit_duration': durationFormatter,
'conversions': numberFormatter, 'conversions': numberFormatter,
'conversion_rate': (number) => (`${number}%`),
'total_revenue': numberFormatter, 'total_revenue': numberFormatter,
'average_revenue': numberFormatter, 'average_revenue': numberFormatter,
} }
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 buildComparisonDataset = function(comparisonPlot) { const buildComparisonDataset = function(comparisonPlot) {
if (!comparisonPlot) return [] if (!comparisonPlot) return []

@ -6,7 +6,7 @@ import * as storage from '../../util/storage'
import { isKeyPressed } from '../../keybinding.js' import { isKeyPressed } from '../../keybinding.js'
import { monthsBetweenDates } from '../../util/date.js' import { monthsBetweenDates } from '../../util/date.js'
const INTERVAL_LABELS = { export const INTERVAL_LABELS = {
'minute': 'Minutes', 'minute': 'Minutes',
'hour': 'Hours', 'hour': 'Hours',
'date': 'Days', 'date': 'Days',
@ -14,19 +14,11 @@ const INTERVAL_LABELS = {
'month': 'Months' 'month': 'Months'
} }
function validIntervals(site, query) { export const getStoredInterval = function(period, domain) {
if (query.period === "custom" && monthsBetweenDates(query.from, query.to) > 12) {
return ["week", "month"]
} else {
return site.validIntervalsByPeriod[query.period]
}
}
function getStoredInterval(period, domain) {
return storage.getItem(`interval__${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) storage.setItem(`interval__${period}__${domain}`, interval)
} }
@ -41,34 +33,7 @@ function subscribeKeybinding(element) {
}, [handleKeyPress]) }, [handleKeyPress])
} }
export const getCurrentInterval = function(site, query) { function DropdownItem({ option, currentInterval, updateInterval }) {
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
}
}
export function IntervalPicker({ query, site, onIntervalUpdate }) {
if (query.period == 'realtime') return null
const menuElement = React.useRef(null)
const options = validIntervals(site, query)
const currentInterval = getCurrentInterval(site, query)
subscribeKeybinding(menuElement)
function updateInterval(interval) {
storeInterval(query.period, site.domain, interval)
onIntervalUpdate(interval)
}
function renderDropdownItem(option) {
return ( return (
<Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}> <Menu.Item onClick={() => updateInterval(option)} key={option} disabled={option == currentInterval}>
{({ active }) => ( {({ active }) => (
@ -82,6 +47,23 @@ export function IntervalPicker({ query, site, onIntervalUpdate }) {
)} )}
</Menu.Item> </Menu.Item>
) )
}
export function IntervalPicker({ graphData, query, site, updateInterval }) {
if (query.period == 'realtime') return null
const menuElement = React.useRef(null)
subscribeKeybinding(menuElement)
let currentInterval = graphData?.interval
let options = site.validIntervalsByPeriod[query.period]
if (query.period === "custom" && monthsBetweenDates(query.from, query.to) > 12) {
options = ["week", "month"]
}
if (!options.includes(currentInterval)) {
currentInterval = [...options].pop()
} }
return ( return (
@ -103,7 +85,7 @@ export function IntervalPicker({ query, site, onIntervalUpdate }) {
leaveFrom="opacity-100 scale-100" leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"> 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> <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> </Menu.Items>
</Transition> </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,9 +3,8 @@ import { Tooltip } from '../../util/tooltip'
import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load' import { SecondsSinceLastLoad } from '../../util/seconds-since-last-load'
import classNames from "classnames"; import classNames from "classnames";
import numberFormatter, { durationFormatter } from '../../util/number-formatter' import numberFormatter, { durationFormatter } from '../../util/number-formatter'
import * as storage from '../../util/storage' import { METRIC_MAPPING } from './graph-util'
import { formatDateRange } from '../../util/date.js' import { formatDateRange } from '../../util/date.js'
import { getGraphableMetrics } from "./graph-util.js";
function Maybe({condition, children}) { function Maybe({condition, children}) {
if (condition) { if (condition) {
@ -15,7 +14,8 @@ function Maybe({condition, children}) {
} }
} }
function renderPercentageComparison(name, comparison, forceDarkBg = false) { export default class TopStats extends React.Component {
renderPercentageComparison(name, comparison, forceDarkBg = false) {
const formattedComparison = numberFormatter(Math.abs(comparison)) const formattedComparison = numberFormatter(Math.abs(comparison))
const defaultClassName = classNames({ const defaultClassName = classNames({
@ -39,9 +39,9 @@ function renderPercentageComparison(name, comparison, forceDarkBg = false) {
} else { } else {
return null return null
} }
} }
function topStatNumberShort(name, value) { topStatNumberShort(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) { if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value) return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) { } else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
@ -51,9 +51,9 @@ function topStatNumberShort(name, value) {
} else { } else {
return numberFormatter(value) return numberFormatter(value)
} }
} }
function topStatNumberLong(name, value) { topStatNumberLong(name, value) {
if (['visit duration', 'time on page'].includes(name.toLowerCase())) { if (['visit duration', 'time on page'].includes(name.toLowerCase())) {
return durationFormatter(value) return durationFormatter(value)
} else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) { } else if (['bounce rate', 'conversion rate'].includes(name.toLowerCase())) {
@ -63,55 +63,54 @@ function topStatNumberLong(name, value) {
} else { } else {
return (value || 0).toLocaleString() return (value || 0).toLocaleString()
} }
} }
export default function TopStats(props) {
const {site, query, data, onMetricUpdate, tooltipBoundary, lastLoadTimestamp} = props
function tooltip(stat) { topStatTooltip(stat, query) {
let statName = stat.name.toLowerCase() let statName = stat.name.toLowerCase()
statName = stat.value === 1 ? statName.slice(0, -1) : statName statName = stat.value === 1 ? statName.slice(0, -1) : statName
const { topStatData, lastLoadTimestamp } = this.props
const showingImported = topStatData?.imported_source && topStatData?.with_imported
return ( return (
<div> <div>
{query.comparison && <div className="whitespace-nowrap"> {query.comparison && <div className="whitespace-nowrap">
{topStatNumberLong(stat.name, stat.value)} vs. {topStatNumberLong(stat.name, stat.comparison_value)} {statName} {this.topStatNumberLong(stat.name, stat.value)} vs. {this.topStatNumberLong(stat.name, stat.comparison_value)} {statName}
<span className="ml-2">{renderPercentageComparison(stat.name, stat.change, true)}</span> <span className="ml-2">{this.renderPercentageComparison(stat.name, stat.change, true)}</span>
</div>} </div>}
{!query.comparison && <div className="whitespace-nowrap"> {!query.comparison && <div className="whitespace-nowrap">
{topStatNumberLong(stat.name, stat.value)} {statName} {this.topStatNumberLong(stat.name, stat.value)} {statName}
</div>} </div>}
{stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp}/>s ago</p>} {stat.name === 'Current visitors' && <p className="font-normal text-xs">Last updated <SecondsSinceLastLoad lastLoadTimestamp={lastLoadTimestamp}/>s ago</p>}
{stat.name === 'Views per visit' && showingImported && <p className="font-normal text-xs whitespace-nowrap">Based only on native data</p>}
</div> </div>
) )
} }
function canMetricBeGraphed(stat) { canMetricBeGraphed(stat) {
const graphableMetrics = getGraphableMetrics(query, site) const isTotalUniqueVisitors = this.props.query.filters.goal && stat.name === 'Unique visitors'
return stat.graph_metric && graphableMetrics.includes(stat.graph_metric) const isKnownMetric = Object.keys(METRIC_MAPPING).includes(stat.name)
return isKnownMetric && !isTotalUniqueVisitors
} }
function maybeUpdateMetric(stat) { maybeUpdateMetric(stat) {
if (canMetricBeGraphed(stat)) { if (this.canMetricBeGraphed(stat)) {
storage.setItem(`metric__${site.domain}`, stat.graph_metric) this.props.updateMetric(METRIC_MAPPING[stat.name])
onMetricUpdate(stat.graph_metric)
} }
} }
function blinkingDot() { blinkingDot() {
return ( return (
<div key="dot" className="block pulsating-circle" style={{ left: '125px', top: '52px' }}></div> <div key="dot" className="block pulsating-circle" style={{ left: '125px', top: '52px' }}></div>
) )
} }
function getStoredMetric() { renderStatName(stat) {
return storage.getItem(`metric__${site.domain}`) const { metric } = this.props
} const isSelected = metric === METRIC_MAPPING[stat.name]
function renderStatName(stat) {
const isSelected = stat.graph_metric === getStoredMetric()
const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g) const [statDisplayName, statExtraName] = stat.name.split(/(\(.+\))/g)
@ -128,45 +127,48 @@ export default function TopStats(props) {
) )
} }
function renderStat(stat, index) { render() {
const { topStatData, query, site } = this.props
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', { const className = classNames('px-4 md:px-6 w-1/2 my-4 lg:w-auto group select-none', {
'cursor-pointer': canMetricBeGraphed(stat), 'cursor-pointer': this.canMetricBeGraphed(stat),
'lg:border-l border-gray-300': index > 0, 'lg:border-l border-gray-300': index > 0,
'border-r lg:border-r-0': index % 2 === 0 'border-r lg:border-r-0': index % 2 === 0
}) })
return ( return (
<Tooltip key={stat.name} info={tooltip(stat, query)} className={className} onClick={() => { maybeUpdateMetric(stat) }} boundary={tooltipBoundary}> <Tooltip key={stat.name} info={this.topStatTooltip(stat, query)} className={className} onClick={() => { this.maybeUpdateMetric(stat) }} boundary={this.props.tooltipBoundary}>
{renderStatName(stat)} {this.renderStatName(stat)}
<div className="my-1 space-y-2"> <div className="my-1 space-y-2">
<div> <div>
<span className="flex items-center justify-between whitespace-nowrap"> <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> <p className="font-bold text-xl dark:text-gray-100" id={METRIC_MAPPING[stat.name]}>{this.topStatNumberShort(stat.name, stat.value)}</p>
<Maybe condition={!query.comparison}> <Maybe condition={!query.comparison}>
{ renderPercentageComparison(stat.name, stat.change) } { this.renderPercentageComparison(stat.name, stat.change) }
</Maybe> </Maybe>
</span> </span>
<Maybe condition={query.comparison}> <Maybe condition={query.comparison}>
<p className="text-xs dark:text-gray-100">{ formatDateRange(site, data.from, data.to) }</p> <p className="text-xs dark:text-gray-100">{ formatDateRange(site, topStatData.from, topStatData.to) }</p>
</Maybe> </Maybe>
</div> </div>
<Maybe condition={query.comparison}> <Maybe condition={query.comparison}>
<div> <div>
<p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ topStatNumberShort(stat.name, stat.comparison_value) }</p> <p className="font-bold text-xl text-gray-500 dark:text-gray-400">{ this.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> <p className="text-xs text-gray-500 dark:text-gray-400">{ formatDateRange(site, topStatData.comparing_from, topStatData.comparing_to) }</p>
</div> </div>
</Maybe> </Maybe>
</div> </div>
</Tooltip> </Tooltip>
) )
} })
const stats = data && data.top_stats.map(renderStat)
if (stats && query.period === 'realtime') { if (stats && query && query.period === 'realtime') {
stats.push(blinkingDot()) stats.push(this.blinkingDot())
} }
return stats || null; return stats || null;
}
} }

@ -1,153 +1,534 @@
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React from 'react';
import { withRouter, Link } from 'react-router-dom'
import Chart from 'chart.js/auto';
import { navigateToQuery } from '../../query'
import * as api from '../../api' import * as api from '../../api'
import * as storage from '../../util/storage' import * as storage from '../../util/storage'
import { getGraphableMetrics } from './graph-util' import LazyLoader from '../../components/lazy-loader'
import GraphTooltip from './graph-tooltip'
import { buildDataSet, METRIC_MAPPING, METRIC_LABELS, METRIC_FORMATTER, LoadingState } from './graph-util'
import dateFormatter from './date-formatter';
import TopStats from './top-stats'; import TopStats from './top-stats';
import { IntervalPicker, getCurrentInterval } from './interval-picker' import { IntervalPicker, getStoredInterval, storeInterval } from './interval-picker';
import StatsExport from './stats-export'
import WithImportedSwitch from './with-imported-switch';
import SamplingNotice from './sampling-notice';
import FadeIn from '../../fade-in'; import FadeIn from '../../fade-in';
import * as url from '../../util/url' import * as url from '../../util/url'
import classNames from 'classnames';
import { monthsBetweenDates, parseNaiveDate, isBefore } from '../../util/date'
import { isComparisonEnabled } from '../../comparison-input' import { isComparisonEnabled } from '../../comparison-input'
import LineGraphWithRouter from './line-graph'
function fetchTopStats(site, query) { const calculateMaximumY = function(dataset) {
const q = { ...query } const yAxisValues = dataset
.flatMap((item) => item.data)
.map((item) => item || 0)
if (!isComparisonEnabled(q.comparison)) { if (yAxisValues) {
q.comparison = 'previous_period' return Math.max(...yAxisValues)
} else {
return 1
} }
return api.get(url.apiPath(site, '/top-stats'), q)
} }
function fetchMainGraph(site, query, metric, interval) { class LineGraph extends React.Component {
const params = {metric, interval} constructor(props) {
return api.get(url.apiPath(site, '/main-graph'), query, params) 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) { regenerateChart() {
const {site, query, lastLoadTimestamp} = props const { graphData, metric, query } = this.props
const isRealtime = query.period === 'realtime' const graphEl = document.getElementById("main-graph-canvas")
const isDarkTheme = document.querySelector('html').classList.contains('dark') || false this.ctx = graphEl.getContext('2d');
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
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),
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 [topStatData, setTopStatData] = useState(null) const hasMultipleYears =
const [topStatsLoading, setTopStatsLoading] = useState(true) graphData.labels
const [graphData, setGraphData] = useState(null) .filter((date) => typeof date === 'string')
const [graphLoading, setGraphLoading] = useState(true) .map(date => date.split('-')[0])
.filter((value, index, list) => list.indexOf(value) === index)
.length > 1
// This state is explicitly meant for the situation where either graph interval if (graphData.interval === 'hour' && query.period !== 'day') {
// or graph metric is changed. That results in behaviour where Top Stats stay const date = dateFormatter({
// intact, but the graph container alone will display a loading spinner for as interval: "date",
// long as new graph data is fetched. longForm: false,
const [graphRefreshing, setGraphRefreshing] = useState(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))
const onIntervalUpdate = useCallback((newInterval) => { // Returns a combination of date and hour. This is because
setGraphData(null) // small intervals like hour may return multiple days
setGraphRefreshing(true) // depending on the query period.
fetchGraphData(getStoredMetric(), newInterval) return `${date}, ${hour}`
}, [query]) }
const onMetricUpdate = useCallback((newMetric) => { if (graphData.interval === 'minute' && query.period !== 'realtime') {
setGraphData(null) return dateFormatter({
setGraphRefreshing(true) interval: "hour", longForm: false, period: query.period,
fetchGraphData(newMetric, getCurrentInterval(site, query)) })(this.getLabelForValue(val))
}, [query]) }
useEffect(() => { return dateFormatter({
setTopStatData(null) interval: graphData.interval, longForm: false, period: query.period, shouldShowYear: hasMultipleYears,
setTopStatsLoading(true) })(this.getLabelForValue(val))
setGraphData(null) },
setGraphLoading(true) color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
fetchTopStatsAndGraphData() }
}
},
interaction: {
mode: 'index',
intersect: false,
}
}
});
}
if (isRealtime) { repositionTooltip(e) {
document.addEventListener('tick', fetchTopStatsAndGraphData) 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;
}
} }
return () => { componentDidMount() {
document.removeEventListener('tick', fetchTopStatsAndGraphData) if (this.props.graphData) {
this.chart = this.regenerateChart();
}
window.addEventListener('mousemove', this.repositionTooltip);
} }
}, [query])
useEffect(() => { componentDidUpdate(prevProps) {
if (topStatData) { storeTopStatsContainerHeight() } const { graphData, darkTheme } = this.props;
}, [topStatData]) const tooltip = document.getElementById('chartjs-tooltip');
function fetchTopStatsAndGraphData() { if (
fetchTopStats(site, query) graphData !== prevProps.graphData ||
.then((res) => { darkTheme !== prevProps.darkTheme
setTopStatData(res) ) {
setTopStatsLoading(false)
})
let metric = getStoredMetric() if (graphData) {
const availableMetrics = getGraphableMetrics(query, site) if (this.chart) {
this.chart.destroy();
}
this.chart = this.regenerateChart();
this.chart.update();
}
if (!availableMetrics.includes(metric)) { if (tooltip) {
metric = availableMetrics[0] tooltip.style.display = 'none';
storage.setItem(`metric__${site.domain}`, metric) }
} }
const interval = getCurrentInterval(site, query) if (!graphData) {
if (this.chart) {
this.chart.destroy();
}
fetchGraphData(metric, interval) if (tooltip) {
tooltip.style.display = 'none';
}
}
} }
function fetchGraphData(metric, interval) { componentWillUnmount() {
fetchMainGraph(site, query, metric, interval) // Ensure that the tooltip doesn't hang around when we are loading more data
.then((res) => { const tooltip = document.getElementById('chartjs-tooltip');
setGraphData(res) if (tooltip) {
setGraphLoading(false) tooltip.style.opacity = 0;
setGraphRefreshing(false) 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
}
onClick(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 })
}
}
pollExportReady() {
if (document.cookie.includes('exporting')) {
setTimeout(this.pollExportReady.bind(this), 1000);
} else {
this.setState({ exported: false })
}
} }
function getStoredMetric() { downloadSpinner() {
return storage.getItem(`metric__${site.domain}`) this.setState({ exported: true });
document.cookie = "exporting=";
setTimeout(this.pollExportReady.bind(this), 1000);
} }
function storeTopStatsContainerHeight() { downloadLink() {
storage.setItem(`topStatsHeight__${site.domain}`, document.getElementById('top-stats-container').clientHeight) 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>
)
}
}
}
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() {
if (!this.props.topStatData?.imported_source) return
const isBeforeNativeStats = (date) => {
if (!date) return false
const nativeStatsBegin = parseNaiveDate(this.props.site.nativeStatsBegin)
const parsedDate = parseNaiveDate(date)
return isBefore(parsedDate, nativeStatsBegin, "day")
}
const isQueryingImportedPeriod = isBeforeNativeStats(this.props.topStatData.from)
const isComparingImportedPeriod = isBeforeNativeStats(this.props.topStatData.comparing_from)
if (isQueryingImportedPeriod || isComparingImportedPeriod) {
const source = this.props.topStatData.imported_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 // 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 // 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 // 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. // to keep track of the Top Stats container height.
function getTopStatsHeight() { getTopStatsHeight() {
if (topStatData) { if (this.props.topStatData) {
return 'auto' return 'auto'
} else { } 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 ( return (
<div className={"relative w-full mt-2 bg-white rounded shadow-xl dark:bg-gray-825"}> <div>
{(topStatsLoading || graphLoading) && renderLoader()} <div id="top-stats-container" className="flex flex-wrap" ref={this.boundary} style={{ height: this.getTopStatsHeight() }}>
<FadeIn show={!(topStatsLoading || graphLoading)}> <TopStats site={site} query={query} metric={metric} updateMetric={updateMetric} topStatData={topStatData} tooltipBoundary={this.boundary.current} lastLoadTimestamp={lastLoadTimestamp} />
<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} />
</div> </div>
<div className="relative px-2"> <div className="relative px-2">
{graphRefreshing && renderLoader()} {mainGraphRefreshing && renderLoader()}
<div className="absolute right-4 -top-8 py-1 flex items-center"> <div className="absolute right-4 -top-8 py-1 flex items-center">
{!isRealtime && <StatsExport site={site} query={query} />} {this.downloadLink()}
<SamplingNotice samplePercent={topStatData}/> {this.samplingNotice()}
<WithImportedSwitch site={site} topStatData={topStatData} /> {this.importedNotice()}
<IntervalPicker site={site} query={query} onIntervalUpdate={onIntervalUpdate} /> <IntervalPicker site={site} query={query} graphData={graphData} metric={metric} updateInterval={updateInterval} />
</div> </div>
<LineGraphWithRouter graphData={graphData} darkTheme={isDarkTheme} query={query} /> <FadeIn show={graphData}>
<div className="relative h-96 w-full z-0">
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
</div> </div>
</FadeIn> </FadeIn>
</div> </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
let interval = getStoredInterval(query.period, site.domain)
if (interval !== "week" && interval !== "month" && query.period === "custom" && monthsBetweenDates(query.from, query.to) > 12) {
interval = "month"
}
if (this.isIntervalValid(interval)) {
return interval
} 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() {
const query = { ...this.props.query }
if (!isComparisonEnabled(query.comparison)) query.comparison = 'previous_period'
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/top-stats`, 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>
)
}
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() { 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
}
}

@ -57,7 +57,7 @@ function Regions({query, site, onClick}) {
getFilterFor={getFilterFor} getFilterFor={getFilterFor}
onClick={onClick} onClick={onClick}
keyLabel="Region" keyLabel="Region"
metrics={maybeWithCR([VISITORS_METRIC], query)} metrics={[VISITORS_METRIC]}
detailsLink={sitePath(site, '/regions')} detailsLink={sitePath(site, '/regions')}
query={query} query={query}
renderIcon={renderIcon} renderIcon={renderIcon}
@ -84,7 +84,7 @@ function Cities({query, site}) {
fetchData={fetchData} fetchData={fetchData}
getFilterFor={getFilterFor} getFilterFor={getFilterFor}
keyLabel="City" keyLabel="City"
metrics={maybeWithCR([VISITORS_METRIC], query)} metrics={[VISITORS_METRIC]}
detailsLink={sitePath(site, '/cities')} detailsLink={sitePath(site, '/cities')}
query={query} query={query}
renderIcon={renderIcon} renderIcon={renderIcon}

@ -1,26 +1,15 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom' import { withRouter } from 'react-router-dom'
import Money from "../behaviours/money";
import Modal from './modal' import Modal from './modal'
import * as api from '../../api' import * as api from '../../api'
import * as url from "../../util/url"; import * as url from "../../util/url";
import numberFormatter from '../../util/number-formatter' import numberFormatter from '../../util/number-formatter'
import { parseQuery } from '../../query' import {parseQuery} from '../../query'
import { escapeFilterValue } from '../../util/filters' 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) { function ConversionsModal(props) {
const site = props.site const site = props.site
const query = parseQuery(props.location.search, site) const query = parseQuery(props.location.search, site)
@ -35,7 +24,7 @@ function ConversionsModal(props) {
}, []) }, [])
function fetchData() { function fetchData() {
api.get(url.apiPath(site, `/conversions`), query, { limit: 100, page }) api.get(url.apiPath(site, `/conversions`), query, {limit: 100, page})
.then((res) => { .then((res) => {
setLoading(false) setLoading(false)
setList(list.concat(res)) setList(list.concat(res))
@ -70,7 +59,7 @@ function ConversionsModal(props) {
<tr className="text-sm dark:text-gray-200" key={listItem.name}> <tr className="text-sm dark:text-gray-200" key={listItem.name}>
<td className="p-2"> <td className="p-2">
<Link <Link
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }} to={{pathname: url.siteBasePath(site), search: filterSearchLink(listItem)}}
className="hover:underline block truncate"> className="hover:underline block truncate">
{listItem.name} {listItem.name}
</Link> </Link>
@ -78,8 +67,8 @@ function ConversionsModal(props) {
<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.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">{numberFormatter(listItem.events)}</td>
<td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</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.total_revenue}/></td> }
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>} { hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue}/></td> }
</tr> </tr>
) )
} }
@ -89,7 +78,7 @@ function ConversionsModal(props) {
} }
function renderBody() { function renderBody() {
const hasRevenue = BUILD_EXTRA && list.some((goal) => goal.total_revenue) const hasRevenue = list.some((goal) => goal.total_revenue)
return ( return (
<> <>
@ -109,7 +98,7 @@ function ConversionsModal(props) {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{list.map((item) => renderListItem(item, hasRevenue))} { list.map((item) => renderListItem(item, hasRevenue)) }
</tbody> </tbody>
</table> </table>
</main> </main>
@ -119,9 +108,9 @@ function ConversionsModal(props) {
return ( return (
<Modal site={site}> <Modal site={site}>
{renderBody()} { renderBody() }
{loading && renderLoading()} { loading && renderLoading() }
{!loading && moreResultsAvailable && renderLoadMore()} { !loading && moreResultsAvailable && renderLoadMore() }
</Modal> </Modal>
) )
} }

@ -66,7 +66,7 @@ class GoogleKeywordsModal extends React.Component {
<RocketIcon /> <RocketIcon />
<div className="text-lg">The site is not connected to Google Search Keywords</div> <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> <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> </div>
) )
} else { } else {

@ -1,32 +1,30 @@
import React, { useEffect, useState, useMemo } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { withRouter } from "react-router-dom"; import { withRouter } from "react-router-dom";
import { FILTER_OPERATIONS } from "../../util/filters"; import Combobox from '../../components/combobox'
import FilterTypeSelector from "../../components/filter-type-selector";
import { FILTER_TYPES } from "../../util/filters";
import { parseQuery } from '../../query' import { parseQuery } from '../../query'
import { siteBasePath } from '../../util/url' import * as api from '../../api'
import { toFilterQuery, parseQueryPropsFilter } from '../../util/filters'; import { apiPath, siteBasePath } from '../../util/url'
import { toFilterQuery, parseQueryFilter } from '../../util/filters';
import { shouldIgnoreKeypress } from '../../keybinding'; import { shouldIgnoreKeypress } from '../../keybinding';
import PropFilterRow from './prop-filter-row';
function getFormState(query) { function getFormState(query) {
if (query.filters['props']) { const rawValue = query.filters['props']
const values = Object.fromEntries(parseQueryPropsFilter(query, 'props').map((value, index) => [index, value])) if (rawValue) {
const [[propKey, _propValue]] = Object.entries(rawValue)
const {type, clauses} = parseQueryFilter(query, 'props')
return { return {
entries: Object.keys(values).sort(), prop_key: {value: propKey, label: propKey},
values prop_value: { type: type, clauses: clauses }
}
} else {
return {
entries: [0],
values: {
0: {
propKey: null,
type: FILTER_OPERATIONS.is,
clauses: []
}
} }
} }
return {
prop_key: null,
prop_value: { type: FILTER_TYPES.is, clauses: [] }
} }
} }
@ -34,78 +32,68 @@ function PropFilterModal(props) {
const query = parseQuery(props.location.search, props.site) const query = parseQuery(props.location.search, props.site)
const [formState, setFormState] = useState(getFormState(query)) const [formState, setFormState] = useState(getFormState(query))
const selectedPropKeys = useMemo(() => Object.values(formState.values).map((value) => value.propKey), [formState]) function fetchPropKeyOptions() {
return (input) => {
function onPropKeySelect(id, selectedOptions) { return api.get(apiPath(props.site, "/suggestions/prop_key"), query, { q: input.trim() })
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0]
setFormState(prevState => ({
...prevState,
values: {
...prevState.values,
[id]: {
...prevState.values[id],
propKey: newPropKey,
clauses: []
} }
} }
}))
const fetchPropValueOptions = useCallback(() => {
return (input) => {
const propKey = formState.prop_key?.value
const updatedQuery = { ...query, filters: { ...query.filters, props: {[propKey]: '!(none)'} } }
return api.get(apiPath(props.site, "/suggestions/prop_value"), updatedQuery, { q: input.trim() })
} }
}, [formState.prop_key])
function onPropValueSelect(id, selection) { function onPropKeySelect() {
return (selectedOptions) => {
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0]
setFormState(prevState => ({ setFormState(prevState => ({
...prevState, prop_key: newPropKey,
values: { prop_value: { type: prevState.prop_value.type, clauses: [] }
...prevState.values,
[id]: {
...prevState.values[id],
clauses: selection
}
}
})) }))
} }
}
function onFilterTypeSelect(id, newType) { function onPropValueSelect() {
return (selection) => {
setFormState(prevState => ({ setFormState(prevState => ({
...prevState, ...prevState, prop_value: { ...prevState.prop_value, clauses: selection }
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 onFilterTypeSelect() {
return (newType) => {
setFormState(prevState => ({
...prevState, prop_value: { ...prevState.prop_value, type: newType }
}))
} }
})
} }
function onPropDelete(id) { function selectedFilterType() {
setFormState(prevState => { return formState.prop_value.type
const entries = prevState.entries.filter((entry) => entry != id) }
const values = {...prevState.values}
delete values[id]
return { entries, values } function renderFilterInputs() {
}) return (
<div className="grid grid-cols-11 mt-6">
<div className="col-span-4">
<Combobox className="mr-2" fetchOptions={fetchPropKeyOptions()} singleOption={true} values={formState.prop_key ? [formState.prop_key] : []} onSelect={onPropKeySelect()} placeholder={'Property'} />
</div>
<div className="col-span-3 mx-2">
<FilterTypeSelector isDisabled={!formState.prop_key} forFilter={'prop_value'} onSelect={onFilterTypeSelect()} selectedType={selectedFilterType()} />
</div>
<div className="col-span-4">
<Combobox isDisabled={!formState.prop_key} fetchOptions={fetchPropValueOptions()} values={formState.prop_value.clauses} onSelect={onPropValueSelect()} placeholder={'Value'} />
</div>
</div>
)
} }
function isDisabled() { function isDisabled() {
return formState.entries.some((id) => !formState.values[id].propKey || formState.values[id].clauses.length == 0) return !(formState.prop_key && formState.prop_value.clauses.length > 0)
} }
function shouldShowClear() { function shouldShowClear() {
@ -113,11 +101,8 @@ function PropFilterModal(props) {
} }
function handleSubmit() { function handleSubmit() {
const formFilters = Object.fromEntries( const filterString = JSON.stringify({ [formState.prop_key.value]: toFilterQuery(formState.prop_value.type, formState.prop_value.clauses) })
Object.entries(formState.values) selectFiltersAndCloseModal(filterString)
.map(([_, {propKey, type, clauses}]) => [propKey.value, toFilterQuery(type, clauses)])
)
selectFiltersAndCloseModal(JSON.stringify(formFilters))
} }
function selectFiltersAndCloseModal(filterString) { function selectFiltersAndCloseModal(filterString) {
@ -154,27 +139,7 @@ function PropFilterModal(props) {
<div className="mt-4 border-b border-gray-300"></div> <div className="mt-4 border-b border-gray-300"></div>
<main className="modal__content"> <main className="modal__content">
<form className="flex flex-col" onSubmit={handleSubmit}> <form className="flex flex-col" onSubmit={handleSubmit}>
{formState.entries.map((id) => ( {renderFilterInputs()}
<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"> <div className="mt-6 flex items-center justify-start">
<button <button
@ -189,7 +154,7 @@ function PropFilterModal(props) {
<button <button
type="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" 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) }} 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> <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 Remove filter

@ -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,6 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom' import { withRouter } from 'react-router-dom'
import Money from "../behaviours/money";
import Modal from './modal' import Modal from './modal'
import * as api from '../../api' import * as api from '../../api'
@ -10,18 +11,6 @@ import { parseQuery } from '../../query'
import { specialTitleWhenGoalFilter } from "../behaviours/goal-conversions"; import { specialTitleWhenGoalFilter } from "../behaviours/goal-conversions";
import { escapeFilterValue } from "../../util/filters" 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) { function PropsModal(props) {
const site = props.site const site = props.site
const query = parseQuery(props.location.search, site) const query = parseQuery(props.location.search, site)
@ -92,11 +81,11 @@ function PropsModal(props) {
} }
function renderBody() { function renderBody() {
const hasRevenue = BUILD_EXTRA && list.some((prop) => prop.total_revenue) const hasRevenue = list.some((prop) => prop.total_revenue)
return ( return (
<> <>
<h1 className="text-xl font-bold dark:text-gray-100">{specialTitleWhenGoalFilter(query, 'Custom Property Breakdown')}</h1> <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> <div className="my-4 border-b border-gray-300"></div>
<main className="modal__content"> <main className="modal__content">

@ -3,7 +3,7 @@ import { withRouter } from 'react-router-dom'
import FilterTypeSelector from "../../components/filter-type-selector"; import FilterTypeSelector from "../../components/filter-type-selector";
import Combobox from '../../components/combobox' import Combobox from '../../components/combobox'
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_OPERATIONS } from '../../util/filters' import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_TYPES } from '../../util/filters'
import { parseQuery } from '../../query' import { parseQuery } from '../../query'
import * as api from '../../api' import * as api from '../../api'
import { apiPath, siteBasePath } from '../../util/url' import { apiPath, siteBasePath } from '../../util/url'
@ -92,7 +92,7 @@ class RegularFilterModal extends React.Component {
fetchOptions(filter) { fetchOptions(filter) {
return (input) => { return (input) => {
const { query, formState } = this.state const { query, formState } = this.state
if (formState[filter].type === FILTER_OPERATIONS.contains) {return Promise.resolve([])} if (formState[filter].type === FILTER_TYPES.contains) {return Promise.resolve([])}
const formFilters = Object.fromEntries( const formFilters = Object.fromEntries(
Object.entries(formState) Object.entries(formState)

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

@ -307,7 +307,7 @@ export default function ListReport(props) {
const hideDetails = props.maybeHideDetails && !moreResultsAvailable const hideDetails = props.maybeHideDetails && !moreResultsAvailable
const showDetails = props.detailsLink && !state.loading && !hideDetails const showDetails = props.detailsLink && !state.loading && !hideDetails
return showDetails && <MoreLink className={'mt-2'} url={props.detailsLink} list={state.list} /> return showDetails && <MoreLink className={'mt-2'} url={props.detailsLink} list={state.list} onClick={props.onClick}/>
} }
return ( return (

@ -1,17 +1,6 @@
import numberFormatter from "../../util/number-formatter" import numberFormatter from "../../util/number-formatter"
import React from "react" import React from "react"
import Money from "../behaviours/money"
/*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 = { export const VISITORS_METRIC = {
name: 'visitors', name: 'visitors',
@ -43,7 +32,7 @@ export function displayMetricValue(value, metric) {
} else if (metric === CR_METRIC) { } else if (metric === CR_METRIC) {
return `${value}%` return `${value}%`
} else { } else {
return <span tooltip={value}>{numberFormatter(value)}</span> return <span tooltip={value}>{ numberFormatter(value) }</span>
} }
} }

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

@ -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 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></>} {this.state.isAdmin && this.state.error && <><br/><br/><p>Please click below to connect your Search Console account.</p></>}
</div> </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> </div>
) )
} else if (this.state.searchTerms.length > 0) { } else if (this.state.searchTerms.length > 0) {

@ -7,7 +7,6 @@ import ListReport from '../reports/list'
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics'; import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics';
import { Menu, Transition } from '@headlessui/react' import { Menu, Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid' import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { escapeFilterValue } from '../../util/filters'
import classNames from 'classnames' import classNames from 'classnames'
const UTM_TAGS = { const UTM_TAGS = {
@ -26,7 +25,7 @@ function AllSources(props) {
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { source: escapeFilterValue(listItem['name']) } return { source: listItem['name'] }
} }
function renderIcon(listItem) { function renderIcon(listItem) {
@ -61,7 +60,7 @@ function UTMSources(props) {
} }
function getFilterFor(listItem) { function getFilterFor(listItem) {
return { [props.tab]: escapeFilterValue(listItem['name']) } return { [props.tab]: listItem['name'] }
} }
return ( return (

@ -1,5 +1,3 @@
const flags = JSON.parse(document.getElementById('stats-react-container').dataset.flags)
export const FILTER_GROUPS = { export const FILTER_GROUPS = {
'page': ['page', 'entry_page', 'exit_page'], 'page': ['page', 'entry_page', 'exit_page'],
'source': ['source', 'referrer'], 'source': ['source', 'referrer'],
@ -9,23 +7,19 @@ export const FILTER_GROUPS = {
'os': ['os', 'os_version'], 'os': ['os', 'os_version'],
'utm': ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'], 'utm': ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'],
'goal': ['goal'], 'goal': ['goal'],
'props': ['prop_key', 'prop_value'], '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_TYPES = {
export const FILTER_OPERATIONS = {
isNot: 'is not', isNot: 'is not',
contains: 'contains', contains: 'contains',
is: 'is' is: 'is'
}; };
export const OPERATION_PREFIX = { export const FILTER_PREFIXES = {
[FILTER_OPERATIONS.isNot]: '!', [FILTER_TYPES.isNot]: '!',
[FILTER_OPERATIONS.contains]: '~', [FILTER_TYPES.contains]: '~',
[FILTER_OPERATIONS.is]: '' [FILTER_TYPES.is]: ''
}; };
export function supportsIsNot(filterName) { export function supportsIsNot(filterName) {
@ -33,7 +27,7 @@ export function supportsIsNot(filterName) {
} }
export function isFreeChoiceFilter(filterName) { export function isFreeChoiceFilter(filterName) {
return !NO_CONTAINS_OPERATOR.has(filterName) return FILTER_GROUPS['page'].concat(FILTER_GROUPS['utm']).includes(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 // As of March 2023, Safari does not support negative lookbehind regexes. In case it throws an error, falls back to plain | matching. This means
@ -41,7 +35,7 @@ export function isFreeChoiceFilter(filterName) {
let NON_ESCAPED_PIPE_REGEX; let NON_ESCAPED_PIPE_REGEX;
try { try {
NON_ESCAPED_PIPE_REGEX = new RegExp("(?<!\\\\)\\|", "g") NON_ESCAPED_PIPE_REGEX = new RegExp("(?<!\\\\)\\|", "g")
} catch (_e) { } catch(_e) {
NON_ESCAPED_PIPE_REGEX = '|' NON_ESCAPED_PIPE_REGEX = '|'
} }
@ -52,35 +46,34 @@ export function escapeFilterValue(value) {
} }
export function toFilterQuery(type, clauses) { export function toFilterQuery(type, clauses) {
const prefix = OPERATION_PREFIX[type]; const prefix = FILTER_PREFIXES[type];
const result = clauses.map(clause => escapeFilterValue(clause.value.trim())).join('|') const result = clauses.map(clause => escapeFilterValue(clause.value.trim())).join('|')
return prefix + result; return prefix + result;
} }
export function parsePrefix(rawValue) { export function parsePrefix(rawValue) {
const type = Object.keys(OPERATION_PREFIX) const type = Object.keys(FILTER_PREFIXES)
.find(type => OPERATION_PREFIX[type] === rawValue[0]) || FILTER_OPERATIONS.is; .find(type => FILTER_PREFIXES[type] === rawValue[0]) || FILTER_TYPES.is;
const value = type === FILTER_OPERATIONS.is ? rawValue : rawValue.substring(1) const value = type === FILTER_TYPES.is ? rawValue : rawValue.substring(1)
const values = value const values = value
.split(NON_ESCAPED_PIPE_REGEX) .split(NON_ESCAPED_PIPE_REGEX)
.filter((clause) => !!clause) .filter((clause) => !!clause)
.map((val) => val.replaceAll(ESCAPED_PIPE, '|')) .map((val) => val.replaceAll(ESCAPED_PIPE, '|'))
return { type, values } 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) { export function parseQueryFilter(query, filter) {
const { type, values } = parsePrefix(query.filters[filter] || '') if (filter === 'props') {
const rawValue = query.filters['props']
const [[_propKey, propVal]] = Object.entries(rawValue)
const {type, values} = parsePrefix(propVal)
const clauses = values.map(val => { return {value: val, label: val}})
return {type, clauses}
} else {
const {type, values} = parsePrefix(query.filters[filter] || '')
let labels = values let labels = values
@ -99,14 +92,10 @@ export function parseQueryFilter(query, filter) {
labels = rawLabel.split('|').filter(label => !!label) labels = rawLabel.split('|').filter(label => !!label)
} }
const clauses = values.map((value, index) => { return { value, label: labels[index] } }) const clauses = values.map((value, index) => { return {value, label: labels[index]}})
return { type, clauses } 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) { export function formatFilterGroup(filterGroup) {
@ -156,7 +145,6 @@ export const formattedFilters = {
'region': 'Region', 'region': 'Region',
'city': 'City', 'city': 'City',
'page': 'Page', 'page': 'Page',
'hostname': 'Hostname',
'entry_page': 'Entry Page', 'entry_page': 'Entry Page',
'exit_page': 'Exit Page', 'exit_page': 'Exit Page'
} }

@ -5,7 +5,6 @@ export default (id) => ({
isOpen: false, isOpen: false,
id: id, id: id,
focus: null, focus: null,
selectionInProgress: false,
setFocus(f) { setFocus(f) {
this.focus = f; this.focus = f;
}, },
@ -14,14 +13,9 @@ export default (id) => ({
this.setFocus(this.leastFocusableIndex()) this.setFocus(this.leastFocusableIndex())
} }
}, },
trackSubmitValueChange() {
this.selectionInProgress = false;
},
open() { open() {
if (!this.isOpen) {
this.initFocus() this.initFocus()
this.isOpen = true this.isOpen = true
}
}, },
suggestionsCount() { suggestionsCount() {
return this.$refs.suggestions?.querySelectorAll('li').length return this.$refs.suggestions?.querySelectorAll('li').length
@ -67,7 +61,7 @@ export default (id) => ({
focusNext() { focusNext() {
const nextIndex = this.nextFocusableIndex() const nextIndex = this.nextFocusableIndex()
this.open() if (!this.isOpen) this.open()
this.setFocus(nextIndex) this.setFocus(nextIndex)
this.scrollTo(nextIndex) this.scrollTo(nextIndex)
@ -75,7 +69,7 @@ export default (id) => ({
focusPrev() { focusPrev() {
const prevIndex = this.prevFocusableIndex() const prevIndex = this.prevFocusableIndex()
this.open() if (!this.isOpen) this.open()
this.setFocus(prevIndex) this.setFocus(prevIndex)
this.scrollTo(prevIndex) this.scrollTo(prevIndex)

@ -17,4 +17,10 @@ export default () => ({
this.open = false this.open = false
focusAfter && focusAfter.focus() focusAfter && focusAfter.focus()
}, },
onPanelClick(e) {
if (e.target.tagName === 'A') {
this.close()
}
}
}) })

@ -19,30 +19,12 @@ if (csrfToken && websocketUrl) {
}) })
} }
} }
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 token = csrfToken.getAttribute("content")
let url = websocketUrl.getAttribute("content") let url = websocketUrl.getAttribute("content")
let liveUrl = (url === "") ? "/live" : new URL("/live", url).href; let liveUrl = (url === "") ? "/live" : new URL("/live", url).href;
let liveSocket = new LiveSocket(liveUrl, Socket, { let liveSocket = new LiveSocket(liveUrl, Socket, {
heartbeatIntervalMs: 10000, heartbeatIntervalMs: 10000,
params: { _csrf_token: token }, hooks: Hooks, uploaders: Uploaders, dom: { params: { _csrf_token: token }, hooks: Hooks, dom: {
// for alpinejs integration // for alpinejs integration
onBeforeElUpdated(from, to) { onBeforeElUpdated(from, to) {
if (from._x_dataStack) { if (from._x_dataStack) {

@ -5,9 +5,3 @@ window.addEventListener(`phx:update-value`, (e) => {
el.dispatchEvent(new Event("input", { bubbles: true })) el.dispatchEvent(new Event("input", { bubbles: true }))
} }
}) })
window.addEventListener(`phx:js-exec`, ({ detail }) => {
document.querySelectorAll(detail.to).forEach(el => {
window.liveSocket.execJS(el, el.getAttribute(detail.attr))
})
})

17493
assets/package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -3,12 +3,17 @@
"version": "1.4.0", "version": "1.4.0",
"license": "AGPL-3.0-or-later", "license": "AGPL-3.0-or-later",
"scripts": { "scripts": {
"deploy": "webpack --mode production",
"watch": "webpack --mode development --watch",
"format": "prettier --write {css,js}/**", "format": "prettier --write {css,js}/**",
"check-format": "prettier --check {css,js}/**", "check-format": "prettier --check {css,js}/**",
"lint": "eslint js/**", "lint": "eslint js/**",
"bundlemon": "bundlemon" "bundlemon": "bundlemon"
}, },
"dependencies": { "dependencies": {
"@babel/core": "^7.14.3",
"@babel/preset-env": "^7.14.4",
"@babel/preset-react": "^7.13.13",
"@headlessui/react": "^1.7.10", "@headlessui/react": "^1.7.10",
"@heroicons/react": "^2.0.11", "@heroicons/react": "^2.0.11",
"@juggle/resize-observer": "^3.3.1", "@juggle/resize-observer": "^3.3.1",
@ -19,16 +24,24 @@
"@tailwindcss/typography": "^0.4.1", "@tailwindcss/typography": "^0.4.1",
"abortcontroller-polyfill": "^1.7.3", "abortcontroller-polyfill": "^1.7.3",
"alpinejs": "^3.13.1", "alpinejs": "^3.13.1",
"autoprefixer": "^10.4.15",
"babel-loader": "^8.2.2",
"chart.js": "^3.3.2", "chart.js": "^3.3.2",
"chartjs-plugin-datalabels": "^2.2.0", "chartjs-plugin-datalabels": "^2.2.0",
"classnames": "^2.3.1", "classnames": "^2.3.1",
"copy-webpack-plugin": "^9.0.0",
"css-loader": "^5.2.6",
"css-minimizer-webpack-plugin": "^3.2.0",
"datamaps": "^0.5.9", "datamaps": "^0.5.9",
"dayjs": "^1.11.7", "dayjs": "^1.11.7",
"debounce-promise": "^3.1.2", "debounce-promise": "^3.1.2",
"iframe-resizer": "^4.3.2", "iframe-resizer": "^4.3.2",
"mini-css-extract-plugin": "^1.6.0",
"phoenix": "^1.7.2", "phoenix": "^1.7.2",
"phoenix_html": "^3.3.1", "phoenix_html": "^3.3.1",
"phoenix_live_view": "^0.18.18", "phoenix_live_view": "^0.18.18",
"postcss": "^8.4.29",
"postcss-loader": "^6.1.1",
"react": "^16.13.1", "react": "^16.13.1",
"react-dom": "^16.13.1", "react-dom": "^16.13.1",
"react-flatpickr": "3.10.5", "react-flatpickr": "3.10.5",
@ -37,10 +50,15 @@
"react-popper": "^2.3.0", "react-popper": "^2.3.0",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-transition-group": "^4.4.2", "react-transition-group": "^4.4.2",
"url-search-params-polyfill": "^8.1.1" "tailwindcss": "^3.3.3",
"terser-webpack-plugin": "^5.1.2",
"url-search-params-polyfill": "^8.1.1",
"webpack": "5.88.1",
"webpack-cli": "^4.7.0"
}, },
"devDependencies": { "devDependencies": {
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"bundlemon": "^1.4.0",
"eslint": "^7.2.0", "eslint": "^7.2.0",
"eslint-config-prettier": "^7.0.0", "eslint-config-prettier": "^7.0.0",
"eslint-plugin-import": "^2.26.0", "eslint-plugin-import": "^2.26.0",
@ -50,7 +68,8 @@
"eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-react-hooks": "^4.2.0",
"stylelint": "^14.1.0", "stylelint": "^14.1.0",
"stylelint-config-prettier": "^9.0.3", "stylelint-config-prettier": "^9.0.3",
"stylelint-config-standard": "^24.0.0" "stylelint-config-standard": "^24.0.0",
"webpack-bundle-analyzer": "^4.4.2"
}, },
"name": "assets" "name": "assets"
} }

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

@ -0,0 +1,37 @@
var pref = document.currentScript.dataset.pref;
function reapplyTheme() {
var userPref = pref || "system";
var mediaPref = window.matchMedia('(prefers-color-scheme: dark)').matches;
var htmlRef = document.querySelector('html');
var hcaptchaRefs = document.getElementsByClassName('h-captcha');
htmlRef.classList.remove('dark');
for (let i = 0; i < hcaptchaRefs.length; i++) {
hcaptchaRefs[i].dataset.theme = "light";
}
switch (userPref) {
case "dark":
htmlRef.classList.add('dark');
for (let i = 0; i < hcaptchaRefs.length; i++) {
hcaptchaRefs[i].dataset.theme = "dark";
}
break;
case "system":
if (mediaPref) {
htmlRef.classList.add('dark');
for (let i = 0; i < hcaptchaRefs.length; i++) {
hcaptchaRefs[i].dataset.theme = "dark";
}
}
break;
}
}
reapplyTheme();
window.matchMedia('(prefers-color-scheme: dark)').addListener(reapplyTheme);
window.onload = function() {
reapplyTheme();
};

@ -0,0 +1,5 @@
# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
#
# To ban all spiders from the entire site uncomment the next two lines:
# User-agent: *
# Disallow: /

@ -3,9 +3,11 @@ const plugin = require('tailwindcss/plugin')
module.exports = { module.exports = {
content: [ content: [
"./js/**/*.js", './js/**/*.js',
"../lib/*_web.ex", '../lib/plausible_web/templates/**/*.html.eex',
"../lib/*_web/**/*.*ex" '../lib/plausible_web/templates/**/*.html.heex',
'../lib/plausible_web/live/**/*.ex',
'../lib/plausible_web/components/**/*.ex',
], ],
safelist: [ safelist: [
// PlausibleWeb.StatsView.stats_container_class/1 uses this class // PlausibleWeb.StatsView.stats_container_class/1 uses this class

@ -0,0 +1,48 @@
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = (env, options) => ({
optimization: {
minimizer: [
new TerserPlugin(),
new CssMinimizerWebpackPlugin()
]
},
entry: {
'app': ['./js/app.js'],
'dashboard': ['./js/dashboard/mount.js'],
'embed.host': ['./js/embed.host.js'],
'embed.content': ['./js/embed.content.js']
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, '../priv/static/js')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
}
]
},
externals: { moment: 'moment' },
plugins: [
new MiniCssExtractPlugin({filename: '../css/[name].css'}),
new CopyWebpackPlugin({patterns: [{from: 'static/', to: '../' }]}),
new webpack.ProvidePlugin({
ResizeObserver: ['@juggle/resize-observer', 'ResizeObserver'] // https://caniuse.com/?search=ResizeObserver
})
]
});

@ -2,13 +2,11 @@ BASE_URL=http://localhost:8000
SECURE_COOKIE=false SECURE_COOKIE=false
DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/plausible_dev DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/plausible_dev
CLICKHOUSE_DATABASE_URL=http://127.0.0.1:8123/plausible_events_db CLICKHOUSE_DATABASE_URL=http://127.0.0.1:8123/plausible_events_db
CLICKHOUSE_MAX_BUFFER_SIZE_BYTES=1000000
SECRET_KEY_BASE=/njrhntbycvastyvtk1zycwfm981vpo/0xrvwjjvemdakc/vsvbrevlwsc6u8rcg SECRET_KEY_BASE=/njrhntbycvastyvtk1zycwfm981vpo/0xrvwjjvemdakc/vsvbrevlwsc6u8rcg
TOTP_VAULT_KEY=Q3BD4nddbkVJIPXgHuo5NthGKSIH0yesRfG05J88HIo=
ENVIRONMENT=dev ENVIRONMENT=dev
MAILER_ADAPTER=Bamboo.LocalAdapter MAILER_ADAPTER=Bamboo.LocalAdapter
LOG_LEVEL=debug LOG_LEVEL=debug
SELFHOST=true SELFHOST=false
DISABLE_CRON=true DISABLE_CRON=true
ADMIN_USER_IDS=1 ADMIN_USER_IDS=1
SHOW_CITIES=true SHOW_CITIES=true
@ -20,11 +18,3 @@ GOOGLE_CLIENT_SECRET=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
PROMEX_DISABLED=false PROMEX_DISABLED=false
SITE_DEFAULT_INGEST_THRESHOLD=1000000 SITE_DEFAULT_INGEST_THRESHOLD=1000000
S3_DISABLED=false
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
S3_REGION=us-east-1
S3_ENDPOINT=http://localhost:10000
S3_EXPORTS_BUCKET=dev-exports
S3_IMPORTS_BUCKET=dev-imports

@ -1,10 +1,9 @@
DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/plausible_test?pool_size=40 DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/plausible_test?pool_size=40
CLICKHOUSE_DATABASE_URL=http://127.0.0.1:8123/plausible_test CLICKHOUSE_DATABASE_URL=http://127.0.0.1:8123/plausible_test
SECRET_KEY_BASE=/njrhntbycvastyvtk1zycwfm981vpo/0xrvwjjvemdakc/vsvbrevlwsc6u8rcg SECRET_KEY_BASE=/njrhntbycvastyvtk1zycwfm981vpo/0xrvwjjvemdakc/vsvbrevlwsc6u8rcg
TOTP_VAULT_KEY=1Jah1HEOnCEnmBE+4/OgbJRraJIppPmYCNbZoFJboZs=
BASE_URL=http://localhost:8000 BASE_URL=http://localhost:8000
CRON_ENABLED=false CRON_ENABLED=false
LOG_LEVEL=warning LOG_LEVEL=warn
ENVIRONMENT=test ENVIRONMENT=test
MAILER_ADAPTER=Bamboo.TestAdapter MAILER_ADAPTER=Bamboo.TestAdapter
ENABLE_EMAIL_VERIFICATION=true ENABLE_EMAIL_VERIFICATION=true
@ -13,13 +12,3 @@ HCAPTCHA_SITEKEY=test
HCAPTCHA_SECRET=scottiger HCAPTCHA_SECRET=scottiger
IP_GEOLOCATION_DB=test/priv/GeoLite2-City-Test.mmdb IP_GEOLOCATION_DB=test/priv/GeoLite2-City-Test.mmdb
SITE_DEFAULT_INGEST_THRESHOLD=1000000 SITE_DEFAULT_INGEST_THRESHOLD=1000000
GOOGLE_CLIENT_ID=fake_client_id
GOOGLE_CLIENT_SECRET=fake_client_secret
S3_DISABLED=false
S3_ACCESS_KEY_ID=minioadmin
S3_SECRET_ACCESS_KEY=minioadmin
S3_REGION=us-east-1
S3_ENDPOINT=http://localhost:10000
S3_EXPORTS_BUCKET=test-exports
S3_IMPORTS_BUCKET=test-imports

@ -13,39 +13,24 @@ config :plausible, PlausibleWeb.Endpoint,
accepts: ~w(html json) accepts: ~w(html json)
] ]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix # Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason config :phoenix, :json_library, Jason
config :esbuild,
version: "0.17.11",
default: [
args:
~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=true),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
config :tailwind,
version: "3.3.3",
default: [
args: ~w(
--config=tailwind.config.js
--input=css/app.css
--output=../priv/static/css/app.css
),
cd: Path.expand("../assets", __DIR__)
]
config :ua_inspector, config :ua_inspector,
database_path: "priv/ua_inspector", database_path: "priv/ua_inspector",
remote_release: "6.3.0" remote_release: "66d80de32fbb265941f4d7941fadc19097375097"
config :ref_inspector, config :ref_inspector,
database_path: "priv/ref_inspector" database_path: "priv/ref_inspector"
config :plausible, config :plausible,
paddle_api: Plausible.Billing.PaddleApi, paddle_api: Plausible.Billing.PaddleApi,
google_api: Plausible.Google.API google_api: Plausible.Google.Api
config :plausible, config :plausible,
# 30 minutes # 30 minutes
@ -65,7 +50,10 @@ config :plausible, Plausible.Repo,
connect_timeout: 300_000, connect_timeout: 300_000,
handshake_timeout: 300_000 handshake_timeout: 300_000
config :plausible, Plausible.Cache, enabled: true config :plausible,
sites_by_domain_cache_enabled: true,
sites_by_domain_cache_refresh_interval_max_jitter: :timer.seconds(5),
sites_by_domain_cache_refresh_interval: :timer.minutes(15)
config :plausible, Plausible.Ingestion.Counters, enabled: true config :plausible, Plausible.Ingestion.Counters, enabled: true
@ -73,8 +61,4 @@ config :ex_cldr,
default_locale: "en", default_locale: "en",
default_backend: Plausible.Cldr default_backend: Plausible.Cldr
config :sentry,
enable_source_code_context: true,
root_source_code_path: [File.cwd!()]
import_config "#{config_env()}.exs" import_config "#{config_env()}.exs"

@ -6,8 +6,14 @@ config :plausible, PlausibleWeb.Endpoint,
code_reloader: true, code_reloader: true,
check_origin: false, check_origin: false,
watchers: [ watchers: [
esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]}, node: [
tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]}, "node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch",
"--watch-options-stdin",
cd: Path.expand("../assets", __DIR__)
],
npm: [ npm: [
"run", "run",
"deploy", "deploy",
@ -17,9 +23,15 @@ config :plausible, PlausibleWeb.Endpoint,
live_reload: [ live_reload: [
patterns: [ patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r"lib/plausible_web/(controllers|live|components|templates|views|plugs)/.*(ex|heex)$" ~r{lib/plausible_web/views/.*(ex)$},
~r{lib/plausible_web/templates/.*(eex)$},
~r{lib/plausible_web/templates/.*(heex)$},
~r{lib/plausible_web/controllers/.*(ex)$},
~r{lib/plausible_web/plugs/.*(ex)$},
~r{lib/plausible_web/live/.*(ex)$}
] ]
] ]
config :logger, :console, format: "[$level] $message\n"
config :phoenix, :stacktrace_depth, 20 config :phoenix, :stacktrace_depth, 20
config :phoenix, :plug_init_mode, :runtime config :phoenix, :plug_init_mode, :runtime

@ -6,46 +6,8 @@ if config_env() in [:dev, :test] do
Envy.load(["config/.env.#{config_env()}"]) Envy.load(["config/.env.#{config_env()}"])
end end
if config_env() == :small_dev do
Envy.load(["config/.env.dev"])
end
if config_env() == :small_test do
Envy.load(["config/.env.test"])
end
config_dir = System.get_env("CONFIG_DIR", "/run/secrets") config_dir = System.get_env("CONFIG_DIR", "/run/secrets")
log_format =
get_var_from_path_or_env(config_dir, "LOG_FORMAT", "standard")
log_level =
config_dir
|> get_var_from_path_or_env("LOG_LEVEL", "warning")
|> String.to_existing_atom()
config :logger,
level: log_level,
backends: [:console]
config :logger, Sentry.LoggerBackend,
capture_log_messages: true,
level: :error
case String.downcase(log_format) do
"standard" ->
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
"json" ->
config :logger, :console,
format: {ExJsonLogger, :format},
metadata: [
:request_id
]
end
# Listen IP supports IPv4 and IPv6 addresses. # Listen IP supports IPv4 and IPv6 addresses.
listen_ip = listen_ip =
( (
@ -140,31 +102,11 @@ ch_db_url =
|> get_var_from_path_or_env("CLICKHOUSE_FLUSH_INTERVAL_MS", "5000") |> get_var_from_path_or_env("CLICKHOUSE_FLUSH_INTERVAL_MS", "5000")
|> Integer.parse() |> Integer.parse()
if get_var_from_path_or_env(config_dir, "CLICKHOUSE_MAX_BUFFER_SIZE") do
Logger.warning(
"CLICKHOUSE_MAX_BUFFER_SIZE is deprecated, please use CLICKHOUSE_MAX_BUFFER_SIZE_BYTES instead"
)
end
{ch_max_buffer_size, ""} = {ch_max_buffer_size, ""} =
config_dir config_dir
|> get_var_from_path_or_env("CLICKHOUSE_MAX_BUFFER_SIZE_BYTES", "100000") |> get_var_from_path_or_env("CLICKHOUSE_MAX_BUFFER_SIZE", "10000")
|> Integer.parse() |> Integer.parse()
# Can be generated with `Base.encode64(:crypto.strong_rand_bytes(32))` from
# iex shell or `openssl rand -base64 32` from command line.
totp_vault_key = get_var_from_path_or_env(config_dir, "TOTP_VAULT_KEY", nil)
case totp_vault_key do
nil ->
raise "TOTP_VAULT_KEY configuration option is required. See https://plausible.io/docs/self-hosting-configuration#server"
key ->
if byte_size(Base.decode64!(key)) != 32 do
raise "TOTP_VAULT_KEY must exactly 32 bytes long. See https://plausible.io/docs/self-hosting-configuration#server"
end
end
### Mandatory params End ### Mandatory params End
build_metadata_raw = get_var_from_path_or_env(config_dir, "BUILD_METADATA", "{}") build_metadata_raw = get_var_from_path_or_env(config_dir, "BUILD_METADATA", "{}")
@ -177,13 +119,13 @@ build_metadata =
{:error, error} -> {:error, error} ->
error = Exception.format(:error, error) error = Exception.format(:error, error)
Logger.warning(""" Logger.warn("""
failed to parse $BUILD_METADATA: #{error} failed to parse $BUILD_METADATA: #{error}
$BUILD_METADATA is set to #{build_metadata_raw}\ $BUILD_METADATA is set to #{build_metadata_raw}\
""") """)
Logger.warning("falling back to empty build metadata, as if $BUILD_METADATA was set to {}") Logger.warn("falling back to empty build metadata, as if $BUILD_METADATA was set to {}")
_fallback = %{} _fallback = %{}
end end
@ -197,8 +139,6 @@ runtime_metadata = [
config :plausible, :runtime_metadata, runtime_metadata config :plausible, :runtime_metadata, runtime_metadata
config :plausible, Plausible.Auth.TOTP, vault_key: totp_vault_key
sentry_dsn = get_var_from_path_or_env(config_dir, "SENTRY_DSN") sentry_dsn = get_var_from_path_or_env(config_dir, "SENTRY_DSN")
honeycomb_api_key = get_var_from_path_or_env(config_dir, "HONEYCOMB_API_KEY") honeycomb_api_key = get_var_from_path_or_env(config_dir, "HONEYCOMB_API_KEY")
honeycomb_dataset = get_var_from_path_or_env(config_dir, "HONEYCOMB_DATASET") honeycomb_dataset = get_var_from_path_or_env(config_dir, "HONEYCOMB_DATASET")
@ -208,11 +148,6 @@ google_cid = get_var_from_path_or_env(config_dir, "GOOGLE_CLIENT_ID")
google_secret = get_var_from_path_or_env(config_dir, "GOOGLE_CLIENT_SECRET") google_secret = get_var_from_path_or_env(config_dir, "GOOGLE_CLIENT_SECRET")
postmark_api_key = get_var_from_path_or_env(config_dir, "POSTMARK_API_KEY") postmark_api_key = get_var_from_path_or_env(config_dir, "POSTMARK_API_KEY")
{otel_sampler_ratio, ""} =
config_dir
|> get_var_from_path_or_env("OTEL_SAMPLER_RATIO", "0.5")
|> Float.parse()
cron_enabled = cron_enabled =
config_dir config_dir
|> get_var_from_path_or_env("CRON_ENABLED", "false") |> get_var_from_path_or_env("CRON_ENABLED", "false")
@ -229,7 +164,11 @@ ip_geolocation_db = get_var_from_path_or_env(config_dir, "IP_GEOLOCATION_DB", ge
geonames_source_file = get_var_from_path_or_env(config_dir, "GEONAMES_SOURCE_FILE") geonames_source_file = get_var_from_path_or_env(config_dir, "GEONAMES_SOURCE_FILE")
maxmind_license_key = get_var_from_path_or_env(config_dir, "MAXMIND_LICENSE_KEY") maxmind_license_key = get_var_from_path_or_env(config_dir, "MAXMIND_LICENSE_KEY")
maxmind_edition = get_var_from_path_or_env(config_dir, "MAXMIND_EDITION", "GeoLite2-City") maxmind_edition = get_var_from_path_or_env(config_dir, "MAXMIND_EDITION", "GeoLite2-City")
persistent_cache_dir = get_var_from_path_or_env(config_dir, "PERSISTENT_CACHE_DIR")
if System.get_env("DISABLE_AUTH") do
require Logger
Logger.warn("DISABLE_AUTH env var is no longer supported")
end
enable_email_verification = enable_email_verification =
config_dir config_dir
@ -256,6 +195,11 @@ end
hcaptcha_sitekey = get_var_from_path_or_env(config_dir, "HCAPTCHA_SITEKEY") hcaptcha_sitekey = get_var_from_path_or_env(config_dir, "HCAPTCHA_SITEKEY")
hcaptcha_secret = get_var_from_path_or_env(config_dir, "HCAPTCHA_SECRET") hcaptcha_secret = get_var_from_path_or_env(config_dir, "HCAPTCHA_SECRET")
log_level =
config_dir
|> get_var_from_path_or_env("LOG_LEVEL", "warn")
|> String.to_existing_atom()
custom_script_name = custom_script_name =
config_dir config_dir
|> get_var_from_path_or_env("CUSTOM_SCRIPT_NAME", "script") |> get_var_from_path_or_env("CUSTOM_SCRIPT_NAME", "script")
@ -287,16 +231,13 @@ secure_cookie =
|> get_var_from_path_or_env("SECURE_COOKIE", if(is_selfhost, do: "false", else: "true")) |> get_var_from_path_or_env("SECURE_COOKIE", if(is_selfhost, do: "false", else: "true"))
|> String.to_existing_atom() |> String.to_existing_atom()
license_key = get_var_from_path_or_env(config_dir, "LICENSE_KEY", "")
config :plausible, config :plausible,
environment: env, environment: env,
mailer_email: mailer_email, mailer_email: mailer_email,
super_admin_user_ids: super_admin_user_ids, super_admin_user_ids: super_admin_user_ids,
is_selfhost: is_selfhost, is_selfhost: is_selfhost,
custom_script_name: custom_script_name, custom_script_name: custom_script_name,
log_failed_login_attempts: log_failed_login_attempts, log_failed_login_attempts: log_failed_login_attempts
license_key: license_key
config :plausible, :selfhost, config :plausible, :selfhost,
enable_email_verification: enable_email_verification, enable_email_verification: enable_email_verification,
@ -335,16 +276,25 @@ else
database: get_var_from_path_or_env(config_dir, "DATABASE_NAME", "plausible") database: get_var_from_path_or_env(config_dir, "DATABASE_NAME", "plausible")
end end
included_environments = if sentry_dsn, do: ["prod", "staging", "dev"], else: []
sentry_app_version = runtime_metadata[:version] || app_version sentry_app_version = runtime_metadata[:version] || app_version
config :sentry, config :sentry,
dsn: sentry_dsn, dsn: sentry_dsn,
environment_name: env, environment_name: env,
included_environments: included_environments,
release: sentry_app_version, release: sentry_app_version,
tags: %{app_version: sentry_app_version}, tags: %{app_version: sentry_app_version},
enable_source_code_context: true,
root_source_code_path: [File.cwd!()],
client: Plausible.Sentry.Client, client: Plausible.Sentry.Client,
send_max_attempts: 1, send_max_attempts: 1,
before_send: {Plausible.SentryFilter, :before_send} filter: Plausible.SentryFilter,
before_send_event: {Plausible.SentryFilter, :before_send}
config :logger, Sentry.LoggerBackend,
capture_log_messages: true,
level: :error
config :plausible, :paddle, config :plausible, :paddle,
vendor_auth_code: paddle_auth_code, vendor_auth_code: paddle_auth_code,
@ -354,10 +304,8 @@ config :plausible, :google,
client_id: google_cid, client_id: google_cid,
client_secret: google_secret, client_secret: google_secret,
api_url: "https://www.googleapis.com", api_url: "https://www.googleapis.com",
reporting_api_url: "https://analyticsreporting.googleapis.com" reporting_api_url: "https://analyticsreporting.googleapis.com",
max_buffer_size: get_int_from_path_or_env(config_dir, "GOOGLE_MAX_BUFFER_SIZE", 10_000)
config :plausible, :imported,
max_buffer_size: get_int_from_path_or_env(config_dir, "IMPORTED_MAX_BUFFER_SIZE", 10_000)
maybe_ch_ipv6 = maybe_ch_ipv6 =
get_var_from_path_or_env(config_dir, "ECTO_CH_IPV6", "false") get_var_from_path_or_env(config_dir, "ECTO_CH_IPV6", "false")
@ -379,28 +327,27 @@ ch_transport_opts =
end end
config :plausible, Plausible.ClickhouseRepo, config :plausible, Plausible.ClickhouseRepo,
loggers: [Ecto.LogEntry],
queue_target: 500, queue_target: 500,
queue_interval: 2000, queue_interval: 2000,
url: ch_db_url, url: ch_db_url,
transport_opts: ch_transport_opts, transport_opts: ch_transport_opts,
settings: [ settings: [
readonly: 1, readonly: 1
join_algorithm: "direct,parallel_hash"
] ]
config :plausible, Plausible.IngestRepo, config :plausible, Plausible.IngestRepo,
loggers: [Ecto.LogEntry],
queue_target: 500, queue_target: 500,
queue_interval: 2000, queue_interval: 2000,
url: ch_db_url, url: ch_db_url,
transport_opts: ch_transport_opts, transport_opts: ch_transport_opts,
flush_interval_ms: ch_flush_interval_ms, flush_interval_ms: ch_flush_interval_ms,
max_buffer_size: ch_max_buffer_size, max_buffer_size: ch_max_buffer_size,
pool_size: ingest_pool_size, pool_size: ingest_pool_size
settings: [
materialized_views_ignore_errors: 1
]
config :plausible, Plausible.AsyncInsertRepo, config :plausible, Plausible.AsyncInsertRepo,
loggers: [Ecto.LogEntry],
queue_target: 500, queue_target: 500,
queue_interval: 2000, queue_interval: 2000,
url: ch_db_url, url: ch_db_url,
@ -408,11 +355,11 @@ config :plausible, Plausible.AsyncInsertRepo,
pool_size: 1, pool_size: 1,
settings: [ settings: [
async_insert: 1, async_insert: 1,
wait_for_async_insert: 0, wait_for_async_insert: 0
materialized_views_ignore_errors: 1
] ]
config :plausible, Plausible.ImportDeletionRepo, config :plausible, Plausible.ImportDeletionRepo,
loggers: [Ecto.LogEntry],
queue_target: 500, queue_target: 500,
queue_interval: 2000, queue_interval: 2000,
url: ch_db_url, url: ch_db_url,
@ -467,20 +414,6 @@ case mailer_adapter do
retries: get_var_from_path_or_env(config_dir, "SMTP_RETRIES") || 2, retries: get_var_from_path_or_env(config_dir, "SMTP_RETRIES") || 2,
no_mx_lookups: get_var_from_path_or_env(config_dir, "SMTP_MX_LOOKUPS_ENABLED") || true no_mx_lookups: get_var_from_path_or_env(config_dir, "SMTP_MX_LOOKUPS_ENABLED") || true
"Bamboo.Mua" ->
config :plausible, Plausible.Mailer, adapter: Bamboo.Mua
if relay = get_var_from_path_or_env(config_dir, "SMTP_HOST_ADDR") do
port = get_int_from_path_or_env(config_dir, "SMTP_HOST_PORT", 25)
username = get_var_from_path_or_env(config_dir, "SMTP_USER_NAME")
password = get_var_from_path_or_env(config_dir, "SMTP_USER_PWD")
config :plausible, Plausible.Mailer,
auth: [username: username, password: password],
relay: relay,
port: port
end
"Bamboo.LocalAdapter" -> "Bamboo.LocalAdapter" ->
config :plausible, Plausible.Mailer, adapter: Bamboo.LocalAdapter config :plausible, Plausible.Mailer, adapter: Bamboo.LocalAdapter
@ -521,9 +454,7 @@ cloud_cron = [
# Daily at 15 # Daily at 15
{"0 15 * * *", Plausible.Workers.NotifyAnnualRenewal}, {"0 15 * * *", Plausible.Workers.NotifyAnnualRenewal},
# Every midnight # Every midnight
{"0 0 * * *", Plausible.Workers.LockSites}, {"0 0 * * *", Plausible.Workers.LockSites}
# Daily at 8
{"0 8 * * *", Plausible.Workers.AcceptTrafficUntil}
] ]
crontab = if(is_selfhost, do: base_cron, else: base_cron ++ cloud_cron) crontab = if(is_selfhost, do: base_cron, else: base_cron ++ cloud_cron)
@ -536,11 +467,8 @@ base_queues = [
check_stats_emails: 1, check_stats_emails: 1,
site_setup_emails: 1, site_setup_emails: 1,
clean_invitations: 1, clean_invitations: 1,
analytics_imports: 1, google_analytics_imports: 1,
domain_change_transition: 1, domain_change_transition: 1
check_accept_traffic_until: 1,
# NOTE: maybe move s3_csv_export to cloud_queues?
s3_csv_export: 1
] ]
cloud_queues = [ cloud_queues = [
@ -564,7 +492,8 @@ cond do
{Oban.Plugins.Pruner, max_age: thirty_days_in_seconds}, {Oban.Plugins.Pruner, max_age: thirty_days_in_seconds},
{Oban.Plugins.Cron, crontab: if(cron_enabled, do: crontab, else: [])}, {Oban.Plugins.Cron, crontab: if(cron_enabled, do: crontab, else: [])},
# Rescue orphaned jobs after 2 hours # Rescue orphaned jobs after 2 hours
{Oban.Plugins.Lifeline, rescue_after: :timer.minutes(120)} {Oban.Plugins.Lifeline, rescue_after: :timer.minutes(120)},
{Oban.Plugins.Stager, interval: :timer.seconds(5)}
], ],
queues: if(cron_enabled, do: queues, else: []), queues: if(cron_enabled, do: queues, else: []),
peer: if(cron_enabled, do: Oban.Peers.Postgres, else: false) peer: if(cron_enabled, do: Oban.Peers.Postgres, else: false)
@ -595,8 +524,10 @@ config :ref_inspector,
config :ua_inspector, config :ua_inspector,
init: {Plausible.Release, :configure_ua_inspector} init: {Plausible.Release, :configure_ua_inspector}
if config_env() in [:dev, :staging, :prod] do config :hammer,
config :kaffy, backend: {Hammer.Backend.ETS, [expiry_ms: 60_000 * 60 * 4, cleanup_interval_ms: 60_000 * 10]}
config :kaffy,
otp_app: :plausible, otp_app: :plausible,
ecto_repo: Plausible.Repo, ecto_repo: Plausible.Repo,
router: PlausibleWeb.Router, router: PlausibleWeb.Router,
@ -622,7 +553,6 @@ if config_env() in [:dev, :staging, :prod] do
] ]
] ]
] ]
end
geo_opts = geo_opts =
cond do cond do
@ -630,7 +560,6 @@ geo_opts =
[ [
license_key: maxmind_license_key, license_key: maxmind_license_key,
edition: maxmind_edition, edition: maxmind_edition,
cache_dir: persistent_cache_dir,
async: true async: true
] ]
@ -662,10 +591,14 @@ if geonames_source_file do
config :location, :geonames_source_file, geonames_source_file config :location, :geonames_source_file, geonames_source_file
end end
config :logger,
level: log_level,
backends: [:console]
if honeycomb_api_key && honeycomb_dataset do if honeycomb_api_key && honeycomb_dataset do
config :opentelemetry, config :opentelemetry,
resource: Plausible.OpenTelemetry.resource_attributes(runtime_metadata), resource: Plausible.OpenTelemetry.resource_attributes(runtime_metadata),
sampler: {Plausible.OpenTelemetry.Sampler, %{ratio: otel_sampler_ratio}}, sampler: {Plausible.OpenTelemetry.Sampler, nil},
span_processor: :batch, span_processor: :batch,
traces_exporter: :otlp traces_exporter: :otlp
@ -682,7 +615,9 @@ else
traces_exporter: :none traces_exporter: :none
end end
config :tzdata, :data_dir, Path.join(persistent_cache_dir || System.tmp_dir!(), "tzdata_data") config :tzdata,
:data_dir,
get_var_from_path_or_env(config_dir, "STORAGE_DIR", Application.app_dir(:tzdata, "priv"))
promex_disabled? = promex_disabled? =
config_dir config_dir
@ -709,73 +644,3 @@ if not is_selfhost do
config :plausible, Plausible.Site, default_ingest_threshold: site_default_ingest_threshold config :plausible, Plausible.Site, default_ingest_threshold: site_default_ingest_threshold
end end
s3_disabled? =
config_dir
|> get_var_from_path_or_env("S3_DISABLED", "true")
|> String.to_existing_atom()
unless s3_disabled? do
s3_env = [
%{
name: "S3_ACCESS_KEY_ID",
example: "AKIAIOSFODNN7EXAMPLE"
},
%{
name: "S3_SECRET_ACCESS_KEY",
example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
},
%{
name: "S3_REGION",
example: "us-east-1"
},
%{
name: "S3_ENDPOINT",
example: "https://<ACCOUNT_ID>.r2.cloudflarestorage.com"
},
%{
name: "S3_EXPORTS_BUCKET",
example: "my-csv-exports-bucket"
},
%{
name: "S3_IMPORTS_BUCKET",
example: "my-csv-imports-bucket"
}
]
s3_env =
Enum.map(s3_env, fn var ->
Map.put(var, :value, get_var_from_path_or_env(config_dir, var.name))
end)
s3_missing_env = Enum.filter(s3_env, &is_nil(&1.value))
unless s3_missing_env == [] do
raise ArgumentError, """
Missing S3 configuration. Please set #{s3_missing_env |> Enum.map(& &1.name) |> Enum.join(", ")} environment variable(s):
#{s3_missing_env |> Enum.map(fn %{name: name, example: example} -> "\t#{name}=#{example}" end) |> Enum.join("\n")}
"""
end
s3_env_value = fn name ->
s3_env |> Enum.find(&(&1.name == name)) |> Map.fetch!(:value)
end
config :ex_aws,
http_client: Plausible.S3.Client,
access_key_id: s3_env_value.("S3_ACCESS_KEY_ID"),
secret_access_key: s3_env_value.("S3_SECRET_ACCESS_KEY"),
region: s3_env_value.("S3_REGION")
%URI{scheme: s3_scheme, host: s3_host, port: s3_port} = URI.parse(s3_env_value.("S3_ENDPOINT"))
config :ex_aws, :s3,
scheme: s3_scheme <> "://",
host: s3_host,
port: s3_port
config :plausible, Plausible.S3,
exports_bucket: s3_env_value.("S3_EXPORTS_BUCKET"),
imports_bucket: s3_env_value.("S3_IMPORTS_BUCKET")
end

@ -1,11 +0,0 @@
import Config
import_config "prod.exs"
config :esbuild,
default: [
args:
~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=false),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]

@ -1,11 +0,0 @@
import Config
import_config "dev.exs"
config :esbuild,
default: [
args:
~w(js/app.js js/dashboard.js js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=false),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]

@ -1,3 +0,0 @@
import Config
import_config "test.exs"

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

Loading…
Cancel
Save