Compare commits
33 Commits
master
...
support-mu
| Author | SHA1 | Date |
|---|---|---|
|
|
45fe06082d | 4 years ago |
|
|
2f9108b77e | 4 years ago |
|
|
0e9b1b14ae | 4 years ago |
|
|
819a76dc35 | 4 years ago |
|
|
ff511787e6 | 4 years ago |
|
|
fde4ce8ce8 | 4 years ago |
|
|
93ac9d4a3f | 4 years ago |
|
|
3beca900a6 | 4 years ago |
|
|
f4d8ef9081 | 4 years ago |
|
|
fda03e3822 | 4 years ago |
|
|
c50793b4bd | 4 years ago |
|
|
2bad1ea32b | 4 years ago |
|
|
b688e29211 | 4 years ago |
|
|
6642a4c14e | 4 years ago |
|
|
a725be0371 | 4 years ago |
|
|
9095a468c0 | 4 years ago |
|
|
6d5fc3998c | 4 years ago |
|
|
4ed62cb0e3 | 4 years ago |
|
|
2e0852cd03 | 4 years ago |
|
|
669a3559f8 | 4 years ago |
|
|
4cac26f634 | 4 years ago |
|
|
338fcdece1 | 4 years ago |
|
|
12e7ac869e | 4 years ago |
|
|
fdd1ab65d3 | 4 years ago |
|
|
219f662fe2 | 4 years ago |
|
|
df95b61eca | 4 years ago |
|
|
181de8225e | 4 years ago |
|
|
89c3e38197 | 4 years ago |
|
|
4fc211f993 | 4 years ago |
|
|
9701904523 | 4 years ago |
|
|
4b93cba06d | 4 years ago |
|
|
0559d96c05 | 4 years ago |
|
|
255d20bee7 | 4 years ago |
@ -1,205 +0,0 @@
|
||||
# This file contains the configuration for Credo and you are probably reading
|
||||
# this after creating it with `mix credo.gen.config`.
|
||||
#
|
||||
# If you find anything wrong or unclear in this file, please report an
|
||||
# issue on GitHub: https://github.com/rrrene/credo/issues
|
||||
#
|
||||
%{
|
||||
#
|
||||
# You can have as many configs as you like in the `configs:` field.
|
||||
configs: [
|
||||
%{
|
||||
#
|
||||
# Run any config using `mix credo -C <name>`. If no config name is given
|
||||
# "default" is used.
|
||||
#
|
||||
name: "default",
|
||||
#
|
||||
# These are the files included in the analysis:
|
||||
files: %{
|
||||
#
|
||||
# You can give explicit globs or simply directories.
|
||||
# In the latter case `**/*.{ex,exs}` will be used.
|
||||
#
|
||||
included: [
|
||||
"lib/",
|
||||
"test/",
|
||||
"extra/"
|
||||
],
|
||||
excluded: [~r"/_build/", ~r"/deps/", ~r"/node_modules/"]
|
||||
},
|
||||
#
|
||||
# Load and configure plugins here:
|
||||
#
|
||||
plugins: [],
|
||||
#
|
||||
# If you create your own checks, you must specify the source files for
|
||||
# them here, so they can be loaded by Credo before running the analysis.
|
||||
#
|
||||
requires: [],
|
||||
#
|
||||
# If you want to enforce a style guide and need a more traditional linting
|
||||
# experience, you can change `strict` to `true` below:
|
||||
#
|
||||
strict: false,
|
||||
#
|
||||
# To modify the timeout for parsing files, change this value:
|
||||
#
|
||||
parse_timeout: 5000,
|
||||
#
|
||||
# If you want to use uncolored output by default, you can change `color`
|
||||
# to `false` below:
|
||||
#
|
||||
color: true,
|
||||
#
|
||||
# You can customize the parameters of any check by adding a second element
|
||||
# to the tuple.
|
||||
#
|
||||
# To disable a check put `false` as second element:
|
||||
#
|
||||
# {Credo.Check.Design.DuplicatedCode, false}
|
||||
#
|
||||
checks: %{
|
||||
enabled: [
|
||||
#
|
||||
## Consistency Checks
|
||||
#
|
||||
{Credo.Check.Consistency.ExceptionNames, []},
|
||||
{Credo.Check.Consistency.LineEndings, []},
|
||||
{Credo.Check.Consistency.ParameterPatternMatching, []},
|
||||
{Credo.Check.Consistency.SpaceAroundOperators, []},
|
||||
{Credo.Check.Consistency.SpaceInParentheses, []},
|
||||
{Credo.Check.Consistency.TabsOrSpaces, []},
|
||||
|
||||
#
|
||||
## Design Checks
|
||||
#
|
||||
# You can customize the priority of any check
|
||||
# Priority values are: `low, normal, high, higher`
|
||||
#
|
||||
{Credo.Check.Design.AliasUsage,
|
||||
[priority: :low, if_nested_deeper_than: 2, if_called_more_often_than: 0]},
|
||||
# You can also customize the exit_status of each check.
|
||||
# If you don't want TODO comments to cause `mix credo` to fail, just
|
||||
# set this value to 0 (zero).
|
||||
#
|
||||
{Credo.Check.Design.TagTODO, [exit_status: 2]},
|
||||
{Credo.Check.Design.TagFIXME, []},
|
||||
|
||||
#
|
||||
## Readability Checks
|
||||
#
|
||||
{Credo.Check.Readability.AliasOrder, []},
|
||||
{Credo.Check.Readability.FunctionNames, []},
|
||||
{Credo.Check.Readability.LargeNumbers, []},
|
||||
{Credo.Check.Readability.MaxLineLength, [priority: :low, max_length: 120]},
|
||||
{Credo.Check.Readability.ModuleAttributeNames, []},
|
||||
{Credo.Check.Readability.ModuleDoc, []},
|
||||
{Credo.Check.Readability.ModuleNames, []},
|
||||
{Credo.Check.Readability.ParenthesesInCondition, []},
|
||||
{Credo.Check.Readability.ParenthesesOnZeroArityDefs, []},
|
||||
{Credo.Check.Readability.PipeIntoAnonymousFunctions, []},
|
||||
{Credo.Check.Readability.PredicateFunctionNames, []},
|
||||
{Credo.Check.Readability.PreferImplicitTry, []},
|
||||
{Credo.Check.Readability.RedundantBlankLines, []},
|
||||
{Credo.Check.Readability.Semicolons, []},
|
||||
{Credo.Check.Readability.SpaceAfterCommas, []},
|
||||
{Credo.Check.Readability.StringSigils, []},
|
||||
{Credo.Check.Readability.TrailingBlankLine, []},
|
||||
{Credo.Check.Readability.TrailingWhiteSpace, []},
|
||||
{Credo.Check.Readability.UnnecessaryAliasExpansion, []},
|
||||
{Credo.Check.Readability.VariableNames, []},
|
||||
{Credo.Check.Readability.WithSingleClause, []},
|
||||
|
||||
#
|
||||
## Refactoring Opportunities
|
||||
#
|
||||
{Credo.Check.Refactor.Apply, []},
|
||||
{Credo.Check.Refactor.CondStatements, []},
|
||||
{Credo.Check.Refactor.CyclomaticComplexity, false},
|
||||
{Credo.Check.Refactor.FunctionArity, []},
|
||||
{Credo.Check.Refactor.LongQuoteBlocks, []},
|
||||
{Credo.Check.Refactor.MatchInCondition, []},
|
||||
{Credo.Check.Refactor.MapJoin, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsInUnless, []},
|
||||
{Credo.Check.Refactor.NegatedConditionsWithElse, false},
|
||||
{Credo.Check.Refactor.Nesting, []},
|
||||
{Credo.Check.Refactor.UnlessWithElse, []},
|
||||
{Credo.Check.Refactor.WithClauses, []},
|
||||
{Credo.Check.Refactor.FilterFilter, []},
|
||||
{Credo.Check.Refactor.RejectReject, []},
|
||||
{Credo.Check.Refactor.RedundantWithClauseResult, []},
|
||||
|
||||
#
|
||||
## Warnings
|
||||
#
|
||||
{Credo.Check.Warning.ApplicationConfigInModuleAttribute, []},
|
||||
{Credo.Check.Warning.BoolOperationOnSameValues, []},
|
||||
{Credo.Check.Warning.ExpensiveEmptyEnumCheck, []},
|
||||
{Credo.Check.Warning.IExPry, []},
|
||||
{Credo.Check.Warning.IoInspect, []},
|
||||
{Credo.Check.Warning.OperationOnSameValues, []},
|
||||
{Credo.Check.Warning.OperationWithConstantResult, []},
|
||||
{Credo.Check.Warning.RaiseInsideRescue, []},
|
||||
{Credo.Check.Warning.SpecWithStruct, []},
|
||||
{Credo.Check.Warning.WrongTestFileExtension, []},
|
||||
{Credo.Check.Warning.UnusedEnumOperation, []},
|
||||
{Credo.Check.Warning.UnusedFileOperation, []},
|
||||
{Credo.Check.Warning.UnusedKeywordOperation, []},
|
||||
{Credo.Check.Warning.UnusedListOperation, []},
|
||||
{Credo.Check.Warning.UnusedPathOperation, []},
|
||||
{Credo.Check.Warning.UnusedRegexOperation, []},
|
||||
{Credo.Check.Warning.UnusedStringOperation, []},
|
||||
{Credo.Check.Warning.UnusedTupleOperation, []},
|
||||
{Credo.Check.Warning.UnsafeExec, []}
|
||||
],
|
||||
disabled: [
|
||||
#
|
||||
# Checks scheduled for next check update (opt-in for now, just replace `false` with `[]`)
|
||||
|
||||
#
|
||||
# Controversial and experimental checks (opt-in, just move the check to `:enabled`
|
||||
# and be sure to use `mix credo --strict` to see low priority checks)
|
||||
#
|
||||
{Credo.Check.Consistency.MultiAliasImportRequireUse, []},
|
||||
{Credo.Check.Consistency.UnusedVariableNames, []},
|
||||
{Credo.Check.Design.DuplicatedCode, []},
|
||||
{Credo.Check.Design.SkipTestWithoutComment, []},
|
||||
{Credo.Check.Readability.AliasAs, []},
|
||||
{Credo.Check.Readability.BlockPipe, []},
|
||||
{Credo.Check.Readability.ImplTrue, []},
|
||||
{Credo.Check.Readability.MultiAlias, []},
|
||||
{Credo.Check.Readability.NestedFunctionCalls, []},
|
||||
{Credo.Check.Readability.SeparateAliasRequire, []},
|
||||
{Credo.Check.Readability.SingleFunctionToBlockPipe, []},
|
||||
{Credo.Check.Readability.SinglePipe, []},
|
||||
{Credo.Check.Readability.Specs, []},
|
||||
{Credo.Check.Readability.StrictModuleLayout, []},
|
||||
{Credo.Check.Readability.WithCustomTaggedTuple, []},
|
||||
{Credo.Check.Refactor.ABCSize, []},
|
||||
{Credo.Check.Refactor.AppendSingleItem, []},
|
||||
{Credo.Check.Refactor.DoubleBooleanNegation, []},
|
||||
{Credo.Check.Refactor.FilterReject, []},
|
||||
{Credo.Check.Refactor.IoPuts, []},
|
||||
{Credo.Check.Refactor.MapMap, []},
|
||||
{Credo.Check.Refactor.ModuleDependencies, []},
|
||||
{Credo.Check.Refactor.NegatedIsNil, []},
|
||||
{Credo.Check.Refactor.PipeChainStart, []},
|
||||
{Credo.Check.Refactor.RejectFilter, []},
|
||||
{Credo.Check.Refactor.VariableRebinding, []},
|
||||
{Credo.Check.Warning.LazyLogging, []},
|
||||
{Credo.Check.Warning.LeakyEnvironment, []},
|
||||
{Credo.Check.Warning.MapGetUnsafePass, []},
|
||||
{Credo.Check.Warning.MixEnv, []},
|
||||
{Credo.Check.Warning.UnsafeToAtom, []}
|
||||
|
||||
# {Credo.Check.Refactor.MapInto, []},
|
||||
|
||||
#
|
||||
# Custom checks can be created using `mix credo.gen.check`.
|
||||
#
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
# This file excludes paths from the Docker build context.
|
||||
#
|
||||
# By default, Docker's build context includes all files (and folders) in the
|
||||
# current directory. Even if a file isn't copied into the container it is still sent to
|
||||
# the Docker daemon.
|
||||
#
|
||||
# There are multiple reasons to exclude files from the build context:
|
||||
#
|
||||
# 1. Prevent nested folders from being copied into the container (ex: exclude
|
||||
# /assets/node_modules when copying /assets)
|
||||
# 2. Reduce the size of the build context and improve build time (ex. /build, /deps, /doc)
|
||||
# 3. Avoid sending files containing sensitive information
|
||||
#
|
||||
# More information on using .dockerignore is available here:
|
||||
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
|
||||
|
||||
.dockerignore
|
||||
|
||||
# Ignore git, but keep git HEAD and refs to access current commit hash if needed:
|
||||
#
|
||||
# $ cat .git/HEAD | awk '{print ".git/"$2}' | xargs cat
|
||||
# d0b8727759e1e0e7aa3d41707d12376e373d5ecc
|
||||
.git
|
||||
!.git/HEAD
|
||||
!.git/refs
|
||||
|
||||
# Common development/test artifacts
|
||||
/cover/
|
||||
/doc/
|
||||
/test/
|
||||
/tmp/
|
||||
.elixir_ls
|
||||
plausible-report.xml
|
||||
.env
|
||||
.idea
|
||||
*.iml
|
||||
*.log
|
||||
*.code-workspace
|
||||
.vscode
|
||||
|
||||
# Mix artifacts
|
||||
/_build/
|
||||
/deps/
|
||||
*.ez
|
||||
|
||||
# Generated on crash by the VM
|
||||
erl_crash.dump
|
||||
|
||||
# If NPM crashes, it generates a log, let's ignore it too.
|
||||
npm-debug.log
|
||||
|
||||
# Static artifacts - These should be fetched and built inside the Docker image
|
||||
/assets/node_modules/
|
||||
/tracker/node_modules/
|
||||
/priv/static/cache_manifest.json
|
||||
/priv/static/css
|
||||
/priv/static/js
|
||||
/priv/version.json
|
||||
|
||||
# Auto-generated tracker files
|
||||
/priv/tracker/js/*.js
|
||||
|
||||
# Dializer
|
||||
/priv/plts/*.plt
|
||||
/priv/plts/*.plt.hash
|
||||
|
||||
# Geolocation databases
|
||||
/priv/geodb/*.mmdb
|
||||
/priv/geodb/*.mmdb.gz
|
||||
|
||||
# Docker volumes
|
||||
.clickhouse_db_vol*
|
||||
plausible_db*
|
||||
@ -1,6 +1,5 @@
|
||||
[
|
||||
plugins: [Phoenix.LiveView.HTMLFormatter],
|
||||
import_deps: [:ecto, :ecto_sql, :phoenix],
|
||||
subdirectories: ["priv/*/migrations"],
|
||||
inputs: ["*.{heex,ex,exs}", "{config,lib,test,extra}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"]
|
||||
import_deps: [:ecto, :phoenix],
|
||||
inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"],
|
||||
subdirectories: ["priv/*/migrations"]
|
||||
]
|
||||
|
||||
@ -1,67 +0,0 @@
|
||||
name: Build Private Images GHCR
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master, stable]
|
||||
tags: ['r*']
|
||||
pull_request:
|
||||
types: [synchronize, labeled]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
if: ${{ github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'deploy-to-staging') }}
|
||||
runs-on: buildjet-16vcpu-ubuntu-2204
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5.0.0
|
||||
with:
|
||||
images: ghcr.io/plausible/analytics/ee
|
||||
tags: |
|
||||
type=ref,event=pr
|
||||
type=ref,event=branch
|
||||
type=ref,event=tag
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
MIX_ENV=prod
|
||||
BUILD_METADATA=${{ steps.meta.outputs.json }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
- name: Notify team on failure
|
||||
if: ${{ failure() }}
|
||||
uses: fjogeleit/http-request-action@v1
|
||||
with:
|
||||
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
|
||||
method: 'POST'
|
||||
customHeaders: '{"Content-Type": "application/json"}'
|
||||
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-private-images.yml\">Build failed</a>"}'
|
||||
@ -1,68 +0,0 @@
|
||||
name: Build Public Images GHCR
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: buildjet-16vcpu-ubuntu-2204
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/plausible/community-edition
|
||||
tags: |
|
||||
type=semver,pattern={{version}},prefix=v
|
||||
type=semver,pattern={{major}}.{{minor}},prefix=v
|
||||
type=semver,pattern={{major}},prefix=v
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64, linux/arm64
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
MIX_ENV=small
|
||||
BUILD_METADATA=${{ steps.meta.outputs.json }}
|
||||
ERL_FLAGS=+JPperf true
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
|
||||
- name: Notify team on failure
|
||||
if: ${{ failure() }}
|
||||
uses: fjogeleit/http-request-action@v1
|
||||
with:
|
||||
url: ${{ secrets.BUILD_NOTIFICATION_URL }}
|
||||
method: 'POST'
|
||||
customHeaders: '{"Content-Type": "application/json"}'
|
||||
data: '{"content": "<a href=\"https://github.com/plausible/analytics/actions/workflows/build-public-images.yml\">Build failed</a>"}'
|
||||
@ -1,28 +0,0 @@
|
||||
name: Validate migrations
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'priv/repo/migrations/**'
|
||||
- 'priv/ingest_repo/migrations/**'
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: App code does not change at the same time
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: changes
|
||||
with:
|
||||
list-files: json
|
||||
filters: |
|
||||
lib:
|
||||
- 'lib/**'
|
||||
- 'extra/**'
|
||||
- 'config/**'
|
||||
|
||||
- if: steps.changes.outputs.lib == 'true'
|
||||
run: |
|
||||
echo "::error file=${{ fromJSON(steps.changes.outputs.lib_files)[0] }}::Code and migrations shouldn't be changed at the same time"
|
||||
exit 1
|
||||
@ -1,19 +0,0 @@
|
||||
alias Plausible.{Repo, ClickhouseRepo, IngestRepo}
|
||||
alias Plausible.{Site, Sites, Goal, Goals, Stats}
|
||||
|
||||
import_if_available(Ecto.Query)
|
||||
import_if_available(Plausible.Factory)
|
||||
|
||||
Logger.configure(level: :warning)
|
||||
|
||||
IO.puts(
|
||||
IO.ANSI.cyan() <>
|
||||
~S[
|
||||
.*$$$$$$s.
|
||||
*$$$$$$$$$$$,
|
||||
:$$SSS#######S *$$$$/. $$ ** $$ l$:
|
||||
,$$SSS#######. $$ ,$:$$ $$$$$ .S* $: $$@$* $% $$$$@s :$: s$@$s
|
||||
.**$$$#####` $@$$$$' $l s-' $:.@* $| '$@s. $% $$ \$ :$:,$$ *$:
|
||||
,***/` #$ `$$ %$$%$$ *$$$#`.*sss$ $% $#$$$' %$ *$sss,
|
||||
,$$'] <> IO.ANSI.reset() <> "\n\n"
|
||||
)
|
||||
@ -1,3 +1,4 @@
|
||||
erlang 26.2.1
|
||||
elixir 1.16.0-otp-26
|
||||
nodejs 21.0.0
|
||||
erlang 25.2.3
|
||||
elixir 1.14.3-otp-25
|
||||
nodejs 16.3.0
|
||||
python 3.9.12
|
||||
|
||||
@ -0,0 +1,6 @@
|
||||
{
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
"@babel/preset-react"
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
{
|
||||
"baseDir": "../priv/",
|
||||
"reportOutput": ["github"],
|
||||
"files": [
|
||||
{
|
||||
"path": "static/js/*.js"
|
||||
},
|
||||
{
|
||||
"path": "static/css/app.css"
|
||||
},
|
||||
{
|
||||
"path": "tracker/js/plausible.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
import React, { Fragment } from "react";
|
||||
|
||||
import { FILTER_OPERATIONS } from "../util/filters";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import { isFreeChoiceFilter, supportsIsNot } from "../util/filters";
|
||||
import classNames from "classnames";
|
||||
|
||||
export default function FilterTypeSelector(props) {
|
||||
const filterName = props.forFilter
|
||||
|
||||
function renderTypeItem(type, shouldDisplay) {
|
||||
return (
|
||||
shouldDisplay && (
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={() => props.onSelect(type)}
|
||||
className={classNames("cursor-pointer block px-4 py-2 text-sm", {
|
||||
"bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100": active,
|
||||
"text-gray-700 dark:text-gray-200": !active
|
||||
}
|
||||
)}
|
||||
>
|
||||
{type}
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const containerClass = classNames("w-full", {
|
||||
'opacity-20 cursor-default pointer-events-none': props.isDisabled
|
||||
})
|
||||
|
||||
return (
|
||||
<div className={containerClass}>
|
||||
<Menu as="div" className="relative inline-block text-left w-full">
|
||||
{({ open }) => (
|
||||
<>
|
||||
<div className="w-full">
|
||||
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
|
||||
{props.selectedType}
|
||||
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
show={open}
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
static
|
||||
className="z-10 origin-top-left absolute left-0 mt-2 w-full rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
>
|
||||
<div className="py-1">
|
||||
{renderTypeItem(FILTER_OPERATIONS.is, true)}
|
||||
{renderTypeItem(FILTER_OPERATIONS.isNot, supportsIsNot(filterName))}
|
||||
{renderTypeItem(FILTER_OPERATIONS.contains, isFreeChoiceFilter(filterName))}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,22 +1,40 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import React from 'react';
|
||||
|
||||
export default function LazyLoader(props) {
|
||||
const [hasBecomeVisibleYet, setHasBecomeVisibleYet] = useState(false)
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && !hasBecomeVisibleYet) {
|
||||
setHasBecomeVisibleYet(true)
|
||||
props.onVisible && props.onVisible()
|
||||
export default class extends React.Component {
|
||||
componentDidMount() {
|
||||
if ('IntersectionObserver' in window) {
|
||||
this.attachObserver()
|
||||
} else {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
}
|
||||
}, [inView])
|
||||
}
|
||||
|
||||
attachObserver() {
|
||||
this.observer = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting) {
|
||||
this.props.onVisible && this.props.onVisible()
|
||||
this.observer.unobserve(this.element);
|
||||
}
|
||||
}, {
|
||||
threshold: 0
|
||||
});
|
||||
|
||||
this.observer.observe(this.element);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.observer && this.observer.unobserve(this.element);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={ref}>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
ref={(el) => { this.element = el }}
|
||||
className={this.props.className}
|
||||
style={this.props.style}
|
||||
>
|
||||
{this.props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,56 +0,0 @@
|
||||
import React from "react"
|
||||
import { sectionTitles } from "../stats/behaviours"
|
||||
import * as api from '../api'
|
||||
|
||||
export function FeatureSetupNotice({ site, feature, title, info, callToAction, onHideAction }) {
|
||||
const sectionTitle = sectionTitles[feature]
|
||||
|
||||
const requestHideSection = () => {
|
||||
if (window.confirm(`Are you sure you want to hide ${sectionTitle}? You can make it visible again in your site settings later.`)) {
|
||||
api.put(`/api/${encodeURIComponent(site.domain)}/disable-feature`, { feature: feature })
|
||||
.then(response => {
|
||||
if (response.ok) { onHideAction() }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function renderCallToAction() {
|
||||
return (
|
||||
<a href={callToAction.link} className="ml-2 sm:ml-4 button px-2 sm:px-4">
|
||||
<p className="flex flex-col justify-center text-xs sm:text-sm">{callToAction.action}</p>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="ml-2 w-5 h-5">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12h15m0 0l-6.75-6.75M19.5 12l-6.75 6.75" />
|
||||
</svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
function renderHideButton() {
|
||||
return (
|
||||
<button
|
||||
onClick={requestHideSection}
|
||||
className="inline-block px-2 sm:px-4 py-2 border border-gray-300 dark:border-gray-500 leading-5 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition ease-in-out duration-150">
|
||||
Hide this report
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="sm:mx-32 mt-6 mb-3" >
|
||||
<div className="py-3">
|
||||
<div className="text-center mt-2 text-gray-800 dark:text-gray-200">
|
||||
{title}
|
||||
</div>
|
||||
|
||||
<div className="text-justify mt-4 font-small text-sm text-gray-500 dark:text-gray-200">
|
||||
{info}
|
||||
</div>
|
||||
|
||||
<div className="text-xs sm:text-sm flex my-6 justify-center">
|
||||
{renderHideButton()}
|
||||
{renderCallToAction()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,5 +0,0 @@
|
||||
Plausible copyright notice
|
||||
|
||||
This software is Copyright 2024 Plausible Insights OÜ
|
||||
|
||||
This repository is provided for informational purposes only, and no rights to use, distribute or otherwise exploit this software are granted to you. Our other repositories include software that is offered under the Affero GPL, but this repository is not. If you wish to discuss a license, or our hosted service that uses the software, please contact us at hello@plausible.io
|
||||
@ -1,85 +0,0 @@
|
||||
export default function FunnelTooltip(palette, funnel) {
|
||||
return (context) => {
|
||||
const tooltipModel = context.tooltip
|
||||
const dataIndex = tooltipModel.dataPoints[0].dataIndex
|
||||
const offset = document.getElementById("funnel").getBoundingClientRect()
|
||||
let tooltipEl = document.getElementById('chartjs-tooltip')
|
||||
|
||||
if (!tooltipEl) {
|
||||
tooltipEl = document.createElement('div')
|
||||
tooltipEl.id = 'chartjs-tooltip'
|
||||
tooltipEl.style.display = 'none'
|
||||
tooltipEl.style.opacity = 0
|
||||
document.body.appendChild(tooltipEl)
|
||||
}
|
||||
|
||||
if (tooltipEl && offset && window.innerWidth < 768) {
|
||||
tooltipEl.style.top = offset.y + offset.height + window.scrollY + 15 + 'px'
|
||||
tooltipEl.style.left = offset.x + 'px'
|
||||
tooltipEl.style.right = null
|
||||
tooltipEl.style.opacity = 1
|
||||
}
|
||||
|
||||
if (tooltipModel.opacity === 0) {
|
||||
tooltipEl.style.display = 'none'
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
if (tooltipModel.body) {
|
||||
const currentStep = funnel.steps[dataIndex]
|
||||
const previousStep = (dataIndex > 0) ? funnel.steps[dataIndex - 1] : null
|
||||
|
||||
tooltipEl.innerHTML = `
|
||||
<aside class="text-gray-100 flex flex-col">
|
||||
<div class="flex justify-between items-center border-b-2 border-gray-700 pb-2">
|
||||
<span class="font-semibold mr-4 text-lg">${previousStep ? `<span class="mr-2">${previousStep.label}</span>` : ""}
|
||||
<span class="text-gray-500 mr-2">→</span>
|
||||
${tooltipModel.title}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<table class="min-w-full mt-2">
|
||||
<tr>
|
||||
<th>
|
||||
<span class="flex items-center mr-4">
|
||||
<div class="w-3 h-3 mr-1 rounded-full ${palette.visitorsLegendClass}"></div>
|
||||
<span>
|
||||
${dataIndex == 0 ? "Entered the funnel" : "Visitors"}
|
||||
</span>
|
||||
</span>
|
||||
</th>
|
||||
<td class="text-right font-bold px-4">
|
||||
<span>
|
||||
${dataIndex == 0 ? funnel.entering_visitors.toLocaleString() : currentStep.visitors.toLocaleString()}
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-right text-sm">
|
||||
<span>
|
||||
${dataIndex == 0 ? funnel.entering_visitors_percentage : currentStep.conversion_rate_step}%
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>
|
||||
<span class="flex items-center">
|
||||
<div class="w-3 h-3 mr-1 rounded-full ${palette.dropoffLegendClass}"></div>
|
||||
<span>
|
||||
${dataIndex == 0 ? "Never entered the funnel" : "Dropoff"}
|
||||
</span>
|
||||
</span>
|
||||
</th>
|
||||
<td class="text-right font-bold px-4">
|
||||
<span>${dataIndex == 0 ? funnel.never_entering_visitors.toLocaleString() : currentStep.dropoff.toLocaleString()}</span>
|
||||
</td >
|
||||
<td class="text-right text-sm">
|
||||
<span>${dataIndex == 0 ? funnel.never_entering_visitors_percentage : currentStep.dropoff_percentage}%</span>
|
||||
</td>
|
||||
</tr >
|
||||
</table >
|
||||
</aside >
|
||||
`
|
||||
}
|
||||
tooltipEl.style.display = null
|
||||
}
|
||||
}
|
||||
@ -1,358 +0,0 @@
|
||||
import React, { useEffect, useState, useRef } from 'react'
|
||||
import FlipMove from 'react-flip-move';
|
||||
import Chart from 'chart.js/auto'
|
||||
import FunnelTooltip from './funnel-tooltip.js'
|
||||
import ChartDataLabels from 'chartjs-plugin-datalabels'
|
||||
import numberFormatter from '../util/number-formatter'
|
||||
import Bar from '../stats/bar'
|
||||
|
||||
import RocketIcon from '../stats/modals/rocket-icon'
|
||||
|
||||
import * as api from '../api'
|
||||
import LazyLoader from '../components/lazy-loader'
|
||||
|
||||
|
||||
export default function Funnel(props) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [visible, setVisible] = useState(false)
|
||||
const [error, setError] = useState(undefined)
|
||||
const [funnel, setFunnel] = useState(null)
|
||||
const [isSmallScreen, setSmallScreen] = useState(false)
|
||||
const chartRef = useRef(null)
|
||||
const canvasRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
setLoading(true)
|
||||
fetchFunnel()
|
||||
.then((res) => {
|
||||
setFunnel(res)
|
||||
setError(undefined)
|
||||
})
|
||||
.catch((error) => {
|
||||
setError(error)
|
||||
})
|
||||
.finally(() => {
|
||||
setLoading(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
if (chartRef.current) {
|
||||
chartRef.current.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [props.query, props.funnelName, visible, isSmallScreen])
|
||||
|
||||
useEffect(() => {
|
||||
if (canvasRef.current && funnel && visible && !isSmallScreen) {
|
||||
initialiseChart()
|
||||
}
|
||||
}, [funnel, visible])
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQuery = window.matchMedia('(max-width: 768px)')
|
||||
setSmallScreen(mediaQuery.matches)
|
||||
const handleScreenChange = (e) => {
|
||||
setSmallScreen(e.matches);
|
||||
}
|
||||
mediaQuery.addEventListener("change", handleScreenChange);
|
||||
return () => {
|
||||
mediaQuery.removeEventListener("change", handleScreenChange)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const isDarkMode = () => {
|
||||
return document.querySelector('html').classList.contains('dark') || false
|
||||
}
|
||||
|
||||
const getPalette = () => {
|
||||
if (isDarkMode()) {
|
||||
return {
|
||||
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
|
||||
dataLabelTextColor: 'rgb(243, 244, 246)',
|
||||
visitorsBackground: 'rgb(99, 102, 241)',
|
||||
dropoffBackground: '#2F3949',
|
||||
dropoffStripes: 'rgb(25, 30, 56)',
|
||||
stepNameLegendColor: 'rgb(228, 228, 231)',
|
||||
visitorsLegendClass: 'bg-indigo-500',
|
||||
dropoffLegendClass: 'bg-gray-600',
|
||||
smallBarClass: 'bg-indigo-500'
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
dataLabelBackground: 'rgba(25, 30, 56, 0.97)',
|
||||
dataLabelTextColor: 'rgb(243, 244, 246)',
|
||||
visitorsBackground: 'rgb(99, 102, 241)',
|
||||
dropoffBackground: 'rgb(224, 231, 255)',
|
||||
dropoffStripes: 'rgb(255, 255, 255)',
|
||||
stepNameLegendColor: 'rgb(12, 24, 39)',
|
||||
visitorsLegendClass: 'bg-indigo-500',
|
||||
dropoffLegendClass: 'bg-indigo-100',
|
||||
smallBarClass: 'bg-indigo-300'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const formatDataLabel = (visitors, ctx) => {
|
||||
if (ctx.dataset.label === 'Visitors') {
|
||||
const conversionRate = funnel.steps[ctx.dataIndex].conversion_rate
|
||||
return `${conversionRate}% \n(${numberFormatter(visitors)} Visitors)`
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const calcOffset = (ctx) => {
|
||||
const conversionRate = parseFloat(funnel.steps[ctx.dataIndex].conversion_rate)
|
||||
if (conversionRate > 90) {
|
||||
return -64
|
||||
} else if (conversionRate > 20) {
|
||||
return -28
|
||||
} else {
|
||||
return 8
|
||||
}
|
||||
}
|
||||
|
||||
const getFunnel = () => {
|
||||
return props.site.funnels.find((funnel) => funnel.name === props.funnelName)
|
||||
}
|
||||
|
||||
const fetchFunnel = async () => {
|
||||
const funnelMeta = getFunnel()
|
||||
if (typeof funnelMeta === 'undefined') {
|
||||
throw new Error('Could not fetch the funnel. Perhaps it was deleted?')
|
||||
} else {
|
||||
return api.get(`/api/stats/${encodeURIComponent(props.site.domain)}/funnels/${funnelMeta.id}`, props.query)
|
||||
}
|
||||
}
|
||||
|
||||
const initialiseChart = () => {
|
||||
if (chartRef.current) {
|
||||
chartRef.current.destroy()
|
||||
}
|
||||
|
||||
const palette = getPalette()
|
||||
|
||||
const createDiagonalPattern = (color1, color2) => {
|
||||
// create a 10x10 px canvas for the pattern's base shape
|
||||
let shape = document.createElement('canvas')
|
||||
shape.width = 10
|
||||
shape.height = 10
|
||||
let c = shape.getContext('2d')
|
||||
|
||||
c.fillStyle = color1
|
||||
c.strokeStyle = color2
|
||||
c.fillRect(0, 0, shape.width, shape.height);
|
||||
|
||||
c.beginPath()
|
||||
c.moveTo(2, 0)
|
||||
c.lineTo(10, 8)
|
||||
c.stroke()
|
||||
|
||||
c.beginPath()
|
||||
c.moveTo(0, 8)
|
||||
c.lineTo(2, 10)
|
||||
c.stroke()
|
||||
|
||||
return c.createPattern(shape, 'repeat')
|
||||
}
|
||||
|
||||
const labels = funnel.steps.map((step) => step.label)
|
||||
const stepData = funnel.steps.map((step) => step.visitors)
|
||||
|
||||
const dropOffData = funnel.steps.map((step) => step.dropoff)
|
||||
const ctx = canvasRef.current.getContext("2d")
|
||||
|
||||
const calcBarThickness = (ctx) => {
|
||||
if (ctx.dataset.data.length <= 3) {
|
||||
return 160
|
||||
} else {
|
||||
return Math.floor(650 / ctx.dataset.data.length)
|
||||
}
|
||||
}
|
||||
|
||||
// passing those verbatim to make sure canvas rendering picks them up
|
||||
var fontFamily = 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'
|
||||
|
||||
var gradient = ctx.createLinearGradient(900, 0, 900, 900);
|
||||
gradient.addColorStop(1, palette.dropoffBackground);
|
||||
gradient.addColorStop(0, palette.visitorsBackground);
|
||||
|
||||
const data = {
|
||||
labels: labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Visitors',
|
||||
data: stepData,
|
||||
backgroundColor: gradient,
|
||||
hoverBackgroundColor: gradient,
|
||||
borderRadius: 4,
|
||||
stack: 'Stack 0',
|
||||
},
|
||||
{
|
||||
label: 'Dropoff',
|
||||
data: dropOffData,
|
||||
backgroundColor: createDiagonalPattern(palette.dropoffBackground, palette.dropoffStripes),
|
||||
hoverBackgroundColor: palette.dropoffBackground,
|
||||
borderRadius: 4,
|
||||
stack: 'Stack 0',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const config = {
|
||||
plugins: [ChartDataLabels],
|
||||
type: 'bar',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
barThickness: calcBarThickness,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
tooltip: {
|
||||
enabled: false,
|
||||
mode: 'index',
|
||||
intersect: true,
|
||||
position: 'average',
|
||||
external: FunnelTooltip(palette, funnel)
|
||||
},
|
||||
datalabels: {
|
||||
formatter: formatDataLabel,
|
||||
anchor: 'end',
|
||||
align: 'end',
|
||||
offset: calcOffset,
|
||||
backgroundColor: palette.dataLabelBackground,
|
||||
color: palette.dataLabelTextColor,
|
||||
borderRadius: 4,
|
||||
clip: true,
|
||||
font: { size: 12, weight: 'normal', lineHeight: 1.6, family: fontFamily },
|
||||
textAlign: 'center',
|
||||
padding: { top: 8, bottom: 8, right: 8, left: 8 },
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
y: { display: false },
|
||||
x: {
|
||||
position: 'bottom',
|
||||
display: true,
|
||||
border: { display: false },
|
||||
grid: { drawBorder: false, display: false },
|
||||
ticks: {
|
||||
padding: 8,
|
||||
font: { weight: 'bold', family: fontFamily, size: 14 },
|
||||
color: palette.stepNameLegendColor
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
chartRef.current = new Chart(ctx, config)
|
||||
}
|
||||
|
||||
const header = () => {
|
||||
return (
|
||||
<div className="flex justify-between w-full">
|
||||
<h4 className="mt-2 text-sm dark:text-gray-100">{props.funnelName}</h4>
|
||||
{props.tabs}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderError = () => {
|
||||
if (error.name === 'AbortError') return
|
||||
if (error.payload && error.payload.level === 'normal') {
|
||||
return (
|
||||
<>
|
||||
{header()}
|
||||
<div className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400">{error.message}</div>
|
||||
</>
|
||||
)
|
||||
} else {
|
||||
return (
|
||||
<>
|
||||
{header()}
|
||||
<div className="text-center text-gray-900 dark:text-gray-100 mt-16">
|
||||
<RocketIcon />
|
||||
<div className="text-lg font-bold">Oops! Something went wrong</div>
|
||||
<div className="text-lg">{error.message ? error.message : 'Failed to render funnel'}</div>
|
||||
<div className="text-xs mt-8">Please try refreshing your browser or selecting the funnel again.</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const renderInner = () => {
|
||||
if (loading) {
|
||||
return <div className="mx-auto loading pt-44"><div></div></div>
|
||||
} else if (error) {
|
||||
return renderError()
|
||||
} else if (funnel) {
|
||||
const conversionRate = funnel.steps[funnel.steps.length - 1].conversion_rate
|
||||
|
||||
return (
|
||||
<div className="mb-8">
|
||||
{header()}
|
||||
<p className="mt-1 text-gray-500 text-sm">{funnel.steps.length}-step funnel • {conversionRate}% conversion rate</p>
|
||||
{isSmallScreen && <div className="mt-4">{renderBars(funnel)}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const renderBar = (step) => {
|
||||
const palette = getPalette()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between my-1 text-sm">
|
||||
<Bar
|
||||
count={step.visitors}
|
||||
all={funnel.steps}
|
||||
bg={palette.smallBarClass}
|
||||
maxWidthDeduction={"5rem"}
|
||||
plot={'visitors'}
|
||||
>
|
||||
|
||||
<span className="flex px-2 py-1.5 group dark:text-gray-100 relative z-9 break-all">
|
||||
{step.label}
|
||||
</span>
|
||||
</Bar>
|
||||
|
||||
<span className="font-medium dark:text-gray-200 w-20 text-right" tooltip={step.visitors.toLocaleString()}>
|
||||
{numberFormatter(step.visitors)}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const renderBars = (funnel) => {
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
|
||||
<span> </span>
|
||||
<span className="text-right">
|
||||
<span className="inline-block w-20">Visitors</span>
|
||||
</span>
|
||||
</div>
|
||||
<FlipMove>
|
||||
{funnel.steps.map(renderBar)}
|
||||
</FlipMove>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ minHeight: '400px' }}>
|
||||
<LazyLoader onVisible={() => setVisible(true)}>
|
||||
{renderInner()}
|
||||
</LazyLoader>
|
||||
{!isSmallScreen && <canvas className="" id="funnel" ref={canvasRef}></canvas>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,9 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
export default function Money({ formatted }) {
|
||||
if (formatted) {
|
||||
return <span tooltip={formatted.long}>{formatted.short}</span>
|
||||
} else {
|
||||
return "-"
|
||||
}
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
import React from 'react';
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { escapeFilterValue } from '../../util/filters'
|
||||
|
||||
import { CR_METRIC } from '../reports/metrics';
|
||||
import ListReport from '../reports/list';
|
||||
|
||||
export default function Conversions(props) {
|
||||
const { site, query } = props
|
||||
|
||||
function fetchConversions() {
|
||||
return api.get(url.apiPath(site, '/conversions'), query, { limit: 9 })
|
||||
}
|
||||
|
||||
function getFilterFor(listItem) {
|
||||
return { goal: escapeFilterValue(listItem.name) }
|
||||
}
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchConversions}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel="Goal"
|
||||
onClick={props.onGoalFilterClick}
|
||||
metrics={[
|
||||
{ name: 'visitors', label: "Uniques", plot: true },
|
||||
{ name: 'events', label: "Total", hiddenOnMobile: true },
|
||||
CR_METRIC,
|
||||
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
|
||||
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
|
||||
]}
|
||||
detailsLink={url.sitePath(site, '/conversions')}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@ -1,65 +0,0 @@
|
||||
import React from "react"
|
||||
import Conversions from './conversions'
|
||||
import ListReport from "../reports/list"
|
||||
import { CR_METRIC } from "../reports/metrics"
|
||||
import * as url from "../../util/url"
|
||||
import * as api from "../../api"
|
||||
|
||||
export const SPECIAL_GOALS = {
|
||||
'404': {title: '404 Pages', prop: 'path'},
|
||||
'Outbound Link: Click': {title: 'Outbound Links', prop: 'url'},
|
||||
'Cloaked Link: Click': {title: 'Cloaked Links', prop: 'url'},
|
||||
'File Download': {title: 'File Downloads', prop: 'url'}
|
||||
}
|
||||
|
||||
export function specialTitleWhenGoalFilter(query, defaultTitle) {
|
||||
return SPECIAL_GOALS[query.filters.goal]?.title || defaultTitle
|
||||
}
|
||||
|
||||
function SpecialPropBreakdown(props) {
|
||||
const { site, query } = props
|
||||
const prop = SPECIAL_GOALS[query.filters.goal].prop
|
||||
|
||||
function fetchData() {
|
||||
return api.get(url.apiPath(site, `/custom-prop-values/${prop}`), query)
|
||||
}
|
||||
|
||||
function externalLinkDest() {
|
||||
if (prop === 'path') {
|
||||
return (listItem) => url.externalLinkForPage(site.domain, listItem.name)
|
||||
} else {
|
||||
return (listItem) => listItem.name
|
||||
}
|
||||
}
|
||||
|
||||
const getFilterFor = (listItem) => { return {'props': JSON.stringify({[prop]: listItem['name']})} }
|
||||
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchData}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel={prop}
|
||||
metrics={[
|
||||
{name: 'visitors', label: 'Visitors', plot: true},
|
||||
{name: 'events', label: 'Events', hiddenOnMobile: true},
|
||||
CR_METRIC
|
||||
]}
|
||||
detailsLink={url.sitePath(site, `/custom-prop-values/${prop}`)}
|
||||
externalLinkDest={externalLinkDest()}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default function GoalConversions(props) {
|
||||
const {site, query} = props
|
||||
|
||||
if (SPECIAL_GOALS[query.filters.goal]) {
|
||||
return <SpecialPropBreakdown site={site} query={props.query} />
|
||||
} else {
|
||||
return <Conversions site={site} query={props.query} onGoalFilterClick={props.onGoalFilterClick}/>
|
||||
}
|
||||
}
|
||||
@ -1,344 +0,0 @@
|
||||
import React, { Fragment, useState, useEffect, useCallback } from 'react'
|
||||
import { Menu, Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import classNames from 'classnames'
|
||||
import * as storage from '../../util/storage'
|
||||
|
||||
import GoalConversions, { specialTitleWhenGoalFilter } from './goal-conversions'
|
||||
import Properties from './props'
|
||||
import { FeatureSetupNotice } from '../../components/notice'
|
||||
import { SPECIAL_GOALS } from './goal-conversions'
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/funnel')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Funnel = maybeRequire().default
|
||||
|
||||
const ACTIVE_CLASS = 'inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold active-prop-heading truncate text-left'
|
||||
const DEFAULT_CLASS = 'hover:text-indigo-600 cursor-pointer truncate text-left'
|
||||
|
||||
export const CONVERSIONS = 'conversions'
|
||||
export const PROPS = 'props'
|
||||
export const FUNNELS = 'funnels'
|
||||
|
||||
export const sectionTitles = {
|
||||
[CONVERSIONS]: 'Goal Conversions',
|
||||
[PROPS]: 'Custom Properties',
|
||||
[FUNNELS]: 'Funnels'
|
||||
}
|
||||
|
||||
export default function Behaviours(props) {
|
||||
const { site, query, currentUserRole } = props
|
||||
const adminAccess = ['owner', 'admin', 'super_admin'].includes(currentUserRole)
|
||||
const tabKey = `behavioursTab__${site.domain}`
|
||||
const funnelKey = `behavioursTabFunnel__${site.domain}`
|
||||
const [enabledModes, setEnabledModes] = useState(getEnabledModes())
|
||||
const [mode, setMode] = useState(defaultMode())
|
||||
|
||||
const [funnelNames, _setFunnelNames] = useState(site.funnels.map(({ name }) => name))
|
||||
const [selectedFunnel, setSelectedFunnel] = useState(defaultSelectedFunnel())
|
||||
|
||||
const [showingPropsForGoalFilter, setShowingPropsForGoalFilter] = useState(false)
|
||||
|
||||
const onGoalFilterClick = useCallback((e) => {
|
||||
const goalName = e.target.innerHTML
|
||||
const isSpecialGoal = Object.keys(SPECIAL_GOALS).includes(goalName)
|
||||
const isPageviewGoal = goalName.startsWith('Visit ')
|
||||
|
||||
if (!isSpecialGoal && !isPageviewGoal && enabledModes.includes(PROPS) && site.hasProps) {
|
||||
setShowingPropsForGoalFilter(true)
|
||||
setMode(PROPS)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const justRemovedGoalFilter = !query.filters.goal
|
||||
if (mode === PROPS && justRemovedGoalFilter && showingPropsForGoalFilter) {
|
||||
setShowingPropsForGoalFilter(false)
|
||||
setMode(CONVERSIONS)
|
||||
}
|
||||
}, [!!query.filters.goal])
|
||||
|
||||
useEffect(() => {
|
||||
setMode(defaultMode())
|
||||
}, [enabledModes])
|
||||
|
||||
function disableMode(mode) {
|
||||
setEnabledModes(enabledModes.filter((m) => { return m !== mode }))
|
||||
}
|
||||
|
||||
function setFunnel(selectedFunnel) {
|
||||
return () => {
|
||||
storage.setItem(tabKey, FUNNELS)
|
||||
storage.setItem(funnelKey, selectedFunnel)
|
||||
setMode(FUNNELS)
|
||||
setSelectedFunnel(selectedFunnel)
|
||||
}
|
||||
}
|
||||
|
||||
function defaultSelectedFunnel() {
|
||||
const stored = storage.getItem(funnelKey)
|
||||
const storedExists = stored && site.funnels.some((f) => f.name === stored)
|
||||
|
||||
if (storedExists) {
|
||||
return stored
|
||||
} else if (site.funnels.length > 0) {
|
||||
const firstAvailable = site.funnels[0].name
|
||||
|
||||
storage.setItem(funnelKey, firstAvailable)
|
||||
return firstAvailable
|
||||
}
|
||||
}
|
||||
|
||||
function hasFunnels() {
|
||||
return site.funnels.length > 0 && site.funnelsAvailable
|
||||
}
|
||||
|
||||
function tabFunnelPicker() {
|
||||
return <Menu as="div" className="relative inline-block text-left">
|
||||
<div>
|
||||
<Menu.Button className="inline-flex justify-between focus:outline-none">
|
||||
<span className={(mode == FUNNELS) ? ACTIVE_CLASS : DEFAULT_CLASS}>Funnels</span>
|
||||
<ChevronDownIcon className="-mr-1 ml-1 h-4 w-4" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items className="text-left origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none z-10">
|
||||
<div className="py-1">
|
||||
{funnelNames.map((funnelName) => {
|
||||
return (
|
||||
<Menu.Item key={funnelName}>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={setFunnel(funnelName)}
|
||||
className={classNames(
|
||||
active ? 'bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-200 cursor-pointer' : 'text-gray-700 dark:text-gray-200',
|
||||
'block px-4 py-2 text-sm',
|
||||
(mode === FUNNELS && selectedFunnel === funnelName) ? 'font-bold text-gray-500' : ''
|
||||
)}
|
||||
>
|
||||
{funnelName}
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
}
|
||||
|
||||
function tabSwitcher(toMode, displayName) {
|
||||
const className = classNames({ [ACTIVE_CLASS]: mode == toMode, [DEFAULT_CLASS]: mode !== toMode })
|
||||
const setTab = () => {
|
||||
storage.setItem(tabKey, toMode)
|
||||
setMode(toMode)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className} onClick={setTab}>
|
||||
{displayName}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function tabs() {
|
||||
return (
|
||||
<div className="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2">
|
||||
{isEnabled(CONVERSIONS) && tabSwitcher(CONVERSIONS, 'Goals')}
|
||||
{isEnabled(PROPS) && tabSwitcher(PROPS, 'Properties')}
|
||||
{isEnabled(FUNNELS) && Funnel && (hasFunnels() ? tabFunnelPicker() : tabSwitcher(FUNNELS, 'Funnels'))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderConversions() {
|
||||
if (site.hasGoals) {
|
||||
return <GoalConversions site={site} query={query} onGoalFilterClick={onGoalFilterClick} />
|
||||
}
|
||||
else if (adminAccess) {
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={CONVERSIONS}
|
||||
title={'Measure how often visitors complete specific actions'}
|
||||
info={'Goals allow you to track registrations, button clicks, form completions, external link clicks, file downloads, 404 error pages and more.'}
|
||||
callToAction={{
|
||||
action: "Set up goals",
|
||||
link: `/${encodeURIComponent(site.domain)}/settings/goals`
|
||||
}}
|
||||
onHideAction={onHideAction(CONVERSIONS)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
else { return noDataYet() }
|
||||
}
|
||||
|
||||
function renderFunnels() {
|
||||
if (Funnel === null) {
|
||||
return featureUnavailable()
|
||||
}
|
||||
else if (Funnel && selectedFunnel && site.funnelsAvailable) {
|
||||
return <Funnel site={site} query={query} funnelName={selectedFunnel} />
|
||||
}
|
||||
else if (Funnel && adminAccess) {
|
||||
let callToAction
|
||||
|
||||
if (site.funnelsAvailable) {
|
||||
callToAction = {action: 'Set up funnels', link: `/${encodeURIComponent(site.domain)}/settings/funnels`}
|
||||
} else {
|
||||
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
|
||||
}
|
||||
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={FUNNELS}
|
||||
title={'Follow the visitor journey from entry to conversion'}
|
||||
info={'Funnels allow you to analyze the user flow through your website, uncover possible issues, optimize your site and increase the conversion rate.'}
|
||||
callToAction={callToAction}
|
||||
onHideAction={onHideAction(FUNNELS)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
else { return noDataYet() }
|
||||
}
|
||||
|
||||
function renderProps() {
|
||||
if (site.hasProps && site.propsAvailable) {
|
||||
return <Properties site={site} query={query} />
|
||||
} else if (adminAccess) {
|
||||
let callToAction
|
||||
|
||||
if (site.propsAvailable) {
|
||||
callToAction = {action: 'Set up props', link: `/${encodeURIComponent(site.domain)}/settings/properties`}
|
||||
} else {
|
||||
callToAction = {action: 'Upgrade', link: '/billing/choose-plan'}
|
||||
}
|
||||
|
||||
return (
|
||||
<FeatureSetupNotice
|
||||
site={site}
|
||||
feature={PROPS}
|
||||
title={'Send custom data to create your own metrics'}
|
||||
info={'You can attach custom properties when sending a pageview or event. This allows you to create custom metrics and analyze stats we don\'t track automatically.'}
|
||||
callToAction={callToAction}
|
||||
onHideAction={onHideAction(PROPS)}
|
||||
/>
|
||||
)
|
||||
} else { return noDataYet() }
|
||||
}
|
||||
|
||||
function noDataYet() {
|
||||
return (
|
||||
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
|
||||
No data yet
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function featureUnavailable() {
|
||||
return (
|
||||
<div className="font-medium text-gray-500 dark:text-gray-400 py-12 text-center">
|
||||
This feature is unavailable
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function onHideAction(mode) {
|
||||
return () => { disableMode(mode) }
|
||||
}
|
||||
|
||||
function renderContent() {
|
||||
switch (mode) {
|
||||
case CONVERSIONS:
|
||||
return renderConversions()
|
||||
case PROPS:
|
||||
return renderProps()
|
||||
case FUNNELS:
|
||||
return renderFunnels()
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMode() {
|
||||
if (enabledModes.length === 0) { return null }
|
||||
|
||||
const storedMode = storage.getItem(tabKey)
|
||||
if (storedMode && enabledModes.includes(storedMode)) { return storedMode }
|
||||
|
||||
if (enabledModes.includes(CONVERSIONS)) { return CONVERSIONS }
|
||||
if (enabledModes.includes(PROPS)) { return PROPS }
|
||||
return FUNNELS
|
||||
}
|
||||
|
||||
function getEnabledModes() {
|
||||
let enabledModes = []
|
||||
|
||||
for (const feature of Object.keys(sectionTitles)) {
|
||||
const isOptedOut = site[feature + 'OptedOut']
|
||||
const isAvailable = site[feature + 'Available'] !== false
|
||||
|
||||
// If the feature is not supported by the site owner's subscription,
|
||||
// it only makes sense to display the feature tab to the owner itself
|
||||
// as only they can upgrade to make the feature available.
|
||||
const callToActionIsMissing = !isAvailable && currentUserRole !== 'owner'
|
||||
|
||||
if (!isOptedOut && !callToActionIsMissing) {
|
||||
enabledModes.push(feature)
|
||||
}
|
||||
}
|
||||
|
||||
return enabledModes
|
||||
}
|
||||
|
||||
function isEnabled(mode) {
|
||||
return enabledModes.includes(mode)
|
||||
}
|
||||
|
||||
function isRealtime() {
|
||||
return query.period === 'realtime'
|
||||
}
|
||||
|
||||
function sectionTitle() {
|
||||
if (mode === CONVERSIONS) {
|
||||
return specialTitleWhenGoalFilter(query, sectionTitles[mode])
|
||||
} else {
|
||||
return sectionTitles[mode]
|
||||
}
|
||||
}
|
||||
|
||||
if (mode) {
|
||||
return (
|
||||
<div className="items-start justify-between block w-full mt-6 md:flex">
|
||||
<div className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825">
|
||||
<div className="flex justify-between w-full">
|
||||
<h3 className="font-bold dark:text-gray-100">
|
||||
{sectionTitle() + (isRealtime() ? ' (last 30min)' : '')}
|
||||
</h3>
|
||||
{tabs()}
|
||||
</div>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,105 +0,0 @@
|
||||
import React, { useCallback, useState } from "react"
|
||||
import ListReport from "../reports/list";
|
||||
import Combobox from '../../components/combobox'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { CR_METRIC, PERCENTAGE_METRIC } from "../reports/metrics";
|
||||
import * as storage from "../../util/storage";
|
||||
import { parsePrefix, escapeFilterValue } from "../../util/filters"
|
||||
|
||||
|
||||
export default function Properties(props) {
|
||||
const { site, query } = props
|
||||
const propKeyStorageName = `prop_key__${site.domain}`
|
||||
const propKeyStorageNameForGoal = `${query.filters.goal}__prop_key__${site.domain}`
|
||||
|
||||
const [propKey, setPropKey] = useState(choosePropKey())
|
||||
|
||||
function singleGoalFilterApplied() {
|
||||
const goalFilter = query.filters.goal
|
||||
if (goalFilter) {
|
||||
const { type, values } = parsePrefix(goalFilter)
|
||||
return type === 'is' && values.length === 1
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function choosePropKey() {
|
||||
if (query.filters.props) {
|
||||
return Object.keys(query.filters.props)[0]
|
||||
} else {
|
||||
return getPropKeyFromStorage()
|
||||
}
|
||||
}
|
||||
|
||||
function getPropKeyFromStorage() {
|
||||
if (singleGoalFilterApplied()) {
|
||||
const storedForGoal = storage.getItem(propKeyStorageNameForGoal)
|
||||
if (storedForGoal) { return storedForGoal }
|
||||
}
|
||||
|
||||
return storage.getItem(propKeyStorageName)
|
||||
}
|
||||
|
||||
function fetchProps() {
|
||||
return api.get(url.apiPath(site, `/custom-prop-values/${encodeURIComponent(propKey)}`), query)
|
||||
}
|
||||
|
||||
const fetchPropKeyOptions = useCallback(() => {
|
||||
return (input) => {
|
||||
return api.get(url.apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
|
||||
}
|
||||
}, [query])
|
||||
|
||||
function onPropKeySelect() {
|
||||
return (selectedOptions) => {
|
||||
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0].value
|
||||
|
||||
if (newPropKey) {
|
||||
const storageName = singleGoalFilterApplied() ? propKeyStorageNameForGoal : propKeyStorageName
|
||||
storage.setItem(storageName, newPropKey)
|
||||
}
|
||||
|
||||
setPropKey(newPropKey)
|
||||
}
|
||||
}
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
function renderBreakdown() {
|
||||
return (
|
||||
<ListReport
|
||||
fetchData={fetchProps}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel={propKey}
|
||||
metrics={[
|
||||
{ name: 'visitors', label: 'Visitors', plot: true },
|
||||
{ name: 'events', label: 'Events', hiddenOnMobile: true },
|
||||
query.filters.goal ? CR_METRIC : PERCENTAGE_METRIC,
|
||||
BUILD_EXTRA && { name: 'total_revenue', label: 'Revenue', hiddenOnMobile: true },
|
||||
BUILD_EXTRA && { name: 'average_revenue', label: 'Average', hiddenOnMobile: true }
|
||||
]}
|
||||
detailsLink={url.sitePath(site, `/custom-prop-values/${propKey}`)}
|
||||
maybeHideDetails={true}
|
||||
query={query}
|
||||
color="bg-red-50"
|
||||
colMinWidth={90}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const getFilterFor = (listItem) => ({
|
||||
props: JSON.stringify({ ...query.filters.props, [propKey]: escapeFilterValue(listItem.name) })
|
||||
})
|
||||
const comboboxValues = propKey ? [{ value: propKey, label: propKey }] : []
|
||||
const boxClass = 'pl-2 pr-8 py-1 bg-transparent dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-500'
|
||||
|
||||
return (
|
||||
<div className="w-full mt-4">
|
||||
<div>
|
||||
<Combobox boxClass={boxClass} fetchOptions={fetchPropKeyOptions()} singleOption={true} values={comboboxValues} onSelect={onPropKeySelect()} placeholder={'Select a property'} />
|
||||
</div>
|
||||
{propKey && renderBreakdown()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,126 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
import FlipMove from 'react-flip-move'
|
||||
|
||||
|
||||
import Bar from '../bar'
|
||||
import PropBreakdown from './prop-breakdown'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import LazyLoader from '../../components/lazy-loader'
|
||||
|
||||
const MOBILE_UPPER_WIDTH = 767
|
||||
const DEFAULT_WIDTH = 1080
|
||||
|
||||
export default class Conversions extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.htmlNode = React.createRef()
|
||||
this.state = {
|
||||
loading: true,
|
||||
viewport: DEFAULT_WIDTH,
|
||||
}
|
||||
this.onVisible = this.onVisible.bind(this)
|
||||
this.fetchConversions = this.fetchConversions.bind(this)
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('resize', this.handleResize, false);
|
||||
this.handleResize();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize, false);
|
||||
document.removeEventListener('tick', this.fetchConversions)
|
||||
}
|
||||
|
||||
handleResize() {
|
||||
this.setState({ viewport: window.innerWidth });
|
||||
}
|
||||
|
||||
onVisible() {
|
||||
this.fetchConversions()
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchConversions)
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.props.query !== prevProps.query) {
|
||||
const height = this.htmlNode.current.element.offsetHeight
|
||||
this.setState({loading: true, goals: null, prevHeight: height})
|
||||
this.fetchConversions()
|
||||
}
|
||||
}
|
||||
|
||||
getBarMaxWidth() {
|
||||
const { viewport } = this.state;
|
||||
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
|
||||
}
|
||||
|
||||
fetchConversions() {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/conversions`, this.props.query)
|
||||
.then((res) => this.setState({loading: false, goals: res, prevHeight: null}))
|
||||
}
|
||||
|
||||
renderGoal(goal) {
|
||||
const { viewport } = this.state;
|
||||
const renderProps = this.props.query.filters['goal'] == goal.name && goal.prop_names
|
||||
|
||||
return (
|
||||
<div className="my-2 text-sm" key={goal.name}>
|
||||
<div className="flex items-center justify-between my-2">
|
||||
<Bar
|
||||
count={goal.unique_conversions}
|
||||
all={this.state.goals}
|
||||
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={this.getBarMaxWidth()}
|
||||
plot="unique_conversions"
|
||||
>
|
||||
<Link to={url.setQuery('goal', goal.name)} className="block px-2 py-1.5 hover:underline relative z-9 break-all lg:truncate dark:text-gray-200">{goal.name}</Link>
|
||||
</Bar>
|
||||
<div className="dark:text-gray-200">
|
||||
<span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.unique_conversions)}</span>
|
||||
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20 font-medium text-right">{numberFormatter(goal.total_conversions)}</span>}
|
||||
<span className="inline-block w-20 font-medium text-right">{goal.conversion_rate}%</span>
|
||||
</div>
|
||||
</div>
|
||||
{ renderProps && <PropBreakdown site={this.props.site} query={this.props.query} goal={goal} /> }
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
renderInner() {
|
||||
const { viewport } = this.state;
|
||||
if (this.state.loading) {
|
||||
return <div className="mx-auto my-2 loading"><div></div></div>
|
||||
} else if (this.state.goals) {
|
||||
return (
|
||||
<React.Fragment>
|
||||
<h3 className="font-bold dark:text-gray-100">{this.props.title || "Goal Conversions"}</h3>
|
||||
<div className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500 dark:text-gray-400">
|
||||
<span>Goal</span>
|
||||
<div className="text-right">
|
||||
<span className="inline-block w-20">Uniques</span>
|
||||
{viewport > MOBILE_UPPER_WIDTH && <span className="inline-block w-20">Total</span>}
|
||||
<span className="inline-block w-20">CR</span>
|
||||
</div>
|
||||
</div>
|
||||
<FlipMove>
|
||||
{ this.state.goals.map(this.renderGoal.bind(this)) }
|
||||
</FlipMove>
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<LazyLoader className="w-full p-4 bg-white rounded shadow-xl dark:bg-gray-825" style={{minHeight: '132px', height: this.state.prevHeight ?? 'auto'}} onVisible={this.onVisible} ref={this.htmlNode}>
|
||||
{ this.renderInner() }
|
||||
</LazyLoader>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,212 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
|
||||
import * as storage from '../../util/storage'
|
||||
import Bar from '../bar'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
|
||||
const MOBILE_UPPER_WIDTH = 767
|
||||
const DEFAULT_WIDTH = 1080
|
||||
const BREAKDOWN_LIMIT = 100
|
||||
|
||||
// https://stackoverflow.com/a/43467144
|
||||
function isValidHttpUrl(string) {
|
||||
let url;
|
||||
|
||||
try {
|
||||
url = new URL(string);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return url.protocol === "http:" || url.protocol === "https:";
|
||||
}
|
||||
|
||||
export default class PropertyBreakdown extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
let propKey = props.goal.prop_names[0]
|
||||
this.storageKey = 'goalPropTab__' + props.site.domain + props.goal.name
|
||||
const storedKey = storage.getItem(this.storageKey)
|
||||
if (props.goal.prop_names.includes(storedKey)) {
|
||||
propKey = storedKey
|
||||
}
|
||||
if (props.query.filters['props']) {
|
||||
propKey = Object.keys(props.query.filters['props'])[0]
|
||||
}
|
||||
|
||||
this.state = {
|
||||
loading: true,
|
||||
propKey: propKey,
|
||||
viewport: DEFAULT_WIDTH,
|
||||
breakdown: [],
|
||||
page: 1,
|
||||
moreResultsAvailable: false
|
||||
}
|
||||
|
||||
this.handleResize = this.handleResize.bind(this);
|
||||
this.fetch = this.fetch.bind(this)
|
||||
this.fetchAndReplace = this.fetchAndReplace.bind(this)
|
||||
this.fetchAndConcat = this.fetchAndConcat.bind(this)
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
window.addEventListener('resize', this.handleResize, false);
|
||||
|
||||
this.handleResize();
|
||||
this.fetchAndReplace()
|
||||
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
window.removeEventListener('resize', this.handleResize, false);
|
||||
document.removeEventListener('tick', this.fetchAndReplace)
|
||||
}
|
||||
|
||||
handleResize() {
|
||||
this.setState({ viewport: window.innerWidth });
|
||||
}
|
||||
|
||||
getBarMaxWidth() {
|
||||
const { viewport } = this.state;
|
||||
return viewport > MOBILE_UPPER_WIDTH ? "16rem" : "10rem";
|
||||
}
|
||||
|
||||
fetch({concat}) {
|
||||
if (!this.props.query.filters['goal']) return
|
||||
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/property/${encodeURIComponent(this.state.propKey)}`, this.props.query, {limit: BREAKDOWN_LIMIT, page: this.state.page})
|
||||
.then((res) => {
|
||||
let breakdown = concat ? this.state.breakdown.concat(res) : res
|
||||
|
||||
this.setState(() => ({
|
||||
loading: false,
|
||||
breakdown: breakdown,
|
||||
moreResultsAvailable: res.length >= BREAKDOWN_LIMIT
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
fetchAndReplace() {
|
||||
this.fetch({concat: false})
|
||||
}
|
||||
|
||||
fetchAndConcat() {
|
||||
this.fetch({concat: true})
|
||||
}
|
||||
|
||||
loadMore() {
|
||||
this.setState({loading: true, page: this.state.page + 1}, this.fetchAndConcat.bind(this))
|
||||
}
|
||||
|
||||
renderUrl(value) {
|
||||
if (isValidHttpUrl(value.name)) {
|
||||
return (
|
||||
<a target="_blank" href={value.name} rel="noreferrer" className="hidden group-hover:block">
|
||||
<svg className="inline h-4 w-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
renderPropContent(value, query) {
|
||||
return (
|
||||
<span className="flex px-2 py-1.5 group dark:text-gray-300 relative z-9 break-all">
|
||||
<Link
|
||||
to={{pathname: window.location.pathname, search: query.toString()}}
|
||||
className="md:truncate hover:underline block"
|
||||
>
|
||||
{ value.name }
|
||||
</Link>
|
||||
{ this.renderUrl(value) }
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
renderPropValue(value) {
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
query.set('props', JSON.stringify({[this.state.propKey]: value.name}))
|
||||
const { viewport } = this.state;
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between my-2" key={value.name}>
|
||||
<Bar
|
||||
count={value.unique_conversions}
|
||||
plot="unique_conversions"
|
||||
all={this.state.breakdown}
|
||||
bg="bg-red-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={this.getBarMaxWidth()}
|
||||
>
|
||||
{this.renderPropContent(value, query)}
|
||||
</Bar>
|
||||
<div className="dark:text-gray-200">
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.unique_conversions)}</span>
|
||||
{
|
||||
viewport > MOBILE_UPPER_WIDTH ?
|
||||
(
|
||||
<span
|
||||
className="font-medium inline-block w-20 text-right"
|
||||
>{numberFormatter(value.total_conversions)}
|
||||
</span>
|
||||
)
|
||||
: null
|
||||
}
|
||||
<span className="font-medium inline-block w-20 text-right">{numberFormatter(value.conversion_rate)}%</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
changePropKey(newKey) {
|
||||
storage.setItem(this.storageKey, newKey)
|
||||
this.setState({propKey: newKey, loading: true, breakdown: [], page: 1, moreResultsAvailable: false}, this.fetchAndReplace)
|
||||
}
|
||||
|
||||
renderLoading() {
|
||||
if (this.state.loading) {
|
||||
return <div className="px-4 py-2"><div className="loading sm mx-auto"><div></div></div></div>
|
||||
} else if (this.state.moreResultsAvailable && this.props.query.period !== 'realtime') {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={this.loadMore.bind(this)} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
return this.state.breakdown.map((propValue) => this.renderPropValue(propValue))
|
||||
}
|
||||
|
||||
renderPill(key) {
|
||||
const isActive = this.state.propKey === key
|
||||
|
||||
if (isActive) {
|
||||
return <li key={key} className="inline-block h-5 text-indigo-700 dark:text-indigo-500 font-bold mr-2 active-prop-heading">{key}</li>
|
||||
} else {
|
||||
return <li key={key} className="hover:text-indigo-600 cursor-pointer mr-2" onClick={this.changePropKey.bind(this, key)}>{key}</li>
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="w-full pl-3 sm:pl-6 mt-4">
|
||||
<div className="flex-col sm:flex-row flex items-center pb-1">
|
||||
<span className="text-xs font-bold text-gray-600 dark:text-gray-300 self-start sm:self-auto mb-1 sm:mb-0">Breakdown by:</span>
|
||||
<ul className="flex flex-wrap font-medium text-xs text-gray-500 dark:text-gray-400 leading-5 pl-1 sm:pl-2">
|
||||
{ this.props.goal.prop_names.map(this.renderPill.bind(this)) }
|
||||
</ul>
|
||||
</div>
|
||||
{ this.renderBody() }
|
||||
{ this.renderLoading()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,247 +0,0 @@
|
||||
import React from 'react';
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import Chart from 'chart.js/auto';
|
||||
import { navigateToQuery } from '../../query'
|
||||
import GraphTooltip from './graph-tooltip'
|
||||
import { buildDataSet, METRIC_LABELS, METRIC_FORMATTER } from './graph-util'
|
||||
import dateFormatter from './date-formatter';
|
||||
import FadeIn from '../../fade-in';
|
||||
import classNames from 'classnames';
|
||||
|
||||
const calculateMaximumY = function(dataset) {
|
||||
const yAxisValues = dataset
|
||||
.flatMap((item) => item.data)
|
||||
.map((item) => item || 0)
|
||||
|
||||
if (yAxisValues) {
|
||||
return Math.max(...yAxisValues)
|
||||
} else {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
class LineGraph extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.regenerateChart = this.regenerateChart.bind(this);
|
||||
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
|
||||
}
|
||||
|
||||
getGraphMetric() {
|
||||
let metric = this.props.graphData.metric
|
||||
|
||||
if (metric == 'visitors' && this.props.query.filters.goal) {
|
||||
return 'conversions'
|
||||
} else {
|
||||
return metric
|
||||
}
|
||||
}
|
||||
|
||||
regenerateChart() {
|
||||
const { graphData, query } = this.props
|
||||
const metric = this.getGraphMetric()
|
||||
const graphEl = document.getElementById("main-graph-canvas")
|
||||
this.ctx = graphEl.getContext('2d');
|
||||
const dataSet = buildDataSet(graphData.plot, graphData.comparison_plot, graphData.present_index, this.ctx, METRIC_LABELS[metric])
|
||||
|
||||
return new Chart(this.ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: graphData.labels,
|
||||
datasets: dataSet
|
||||
},
|
||||
options: {
|
||||
animation: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
enabled: false,
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
position: 'average',
|
||||
external: GraphTooltip(graphData, metric, query)
|
||||
},
|
||||
},
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
onResize: this.updateWindowDimensions,
|
||||
elements: { line: { tension: 0 }, point: { radius: 0 } },
|
||||
onClick: this.maybeHopToHoveredPeriod.bind(this),
|
||||
scale: {
|
||||
ticks: { precision: 0, maxTicksLimit: 8 }
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
min: 0,
|
||||
suggestedMax: calculateMaximumY(dataSet),
|
||||
ticks: {
|
||||
callback: METRIC_FORMATTER[metric],
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
},
|
||||
grid: {
|
||||
zeroLineColor: 'transparent',
|
||||
drawBorder: false,
|
||||
}
|
||||
},
|
||||
yComparison: {
|
||||
min: 0,
|
||||
suggestedMax: calculateMaximumY(dataSet),
|
||||
display: false,
|
||||
grid: { display: false },
|
||||
},
|
||||
x: {
|
||||
grid: { display: false },
|
||||
ticks: {
|
||||
callback: function(val, _index, _ticks) {
|
||||
if (this.getLabelForValue(val) == "__blank__") return ""
|
||||
|
||||
const hasMultipleYears =
|
||||
graphData.labels
|
||||
.filter((date) => typeof date === 'string')
|
||||
.map(date => date.split('-')[0])
|
||||
.filter((value, index, list) => list.indexOf(value) === index)
|
||||
.length > 1
|
||||
|
||||
if (graphData.interval === 'hour' && query.period !== 'day') {
|
||||
const date = dateFormatter({
|
||||
interval: "date",
|
||||
longForm: false,
|
||||
period: query.period,
|
||||
shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
|
||||
const hour = dateFormatter({
|
||||
interval: graphData.interval,
|
||||
longForm: false,
|
||||
period: query.period,
|
||||
shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
|
||||
// Returns a combination of date and hour. This is because
|
||||
// small intervals like hour may return multiple days
|
||||
// depending on the query period.
|
||||
return `${date}, ${hour}`
|
||||
}
|
||||
|
||||
if (graphData.interval === 'minute' && query.period !== 'realtime') {
|
||||
return dateFormatter({
|
||||
interval: "hour", longForm: false, period: query.period,
|
||||
})(this.getLabelForValue(val))
|
||||
}
|
||||
|
||||
return dateFormatter({
|
||||
interval: graphData.interval, longForm: false, period: query.period, shouldShowYear: hasMultipleYears,
|
||||
})(this.getLabelForValue(val))
|
||||
},
|
||||
color: this.props.darkTheme ? 'rgb(243, 244, 246)' : undefined
|
||||
}
|
||||
}
|
||||
},
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
repositionTooltip(e) {
|
||||
const tooltipEl = document.getElementById('chartjs-tooltip');
|
||||
if (tooltipEl && window.innerWidth >= 768) {
|
||||
if (e.clientX > 0.66 * window.innerWidth) {
|
||||
tooltipEl.style.right = (window.innerWidth - e.clientX) + window.pageXOffset + 'px'
|
||||
tooltipEl.style.left = null;
|
||||
} else {
|
||||
tooltipEl.style.right = null;
|
||||
tooltipEl.style.left = e.clientX + window.pageXOffset + 'px'
|
||||
}
|
||||
tooltipEl.style.top = e.clientY + window.pageYOffset + 'px'
|
||||
tooltipEl.style.opacity = 1;
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.graphData) {
|
||||
this.chart = this.regenerateChart();
|
||||
}
|
||||
window.addEventListener('mousemove', this.repositionTooltip);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
const { graphData, darkTheme } = this.props;
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
|
||||
if (
|
||||
graphData !== prevProps.graphData ||
|
||||
darkTheme !== prevProps.darkTheme
|
||||
) {
|
||||
|
||||
if (graphData) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
this.chart = this.regenerateChart();
|
||||
this.chart.update();
|
||||
}
|
||||
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
if (!graphData) {
|
||||
if (this.chart) {
|
||||
this.chart.destroy();
|
||||
}
|
||||
|
||||
if (tooltip) {
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
// Ensure that the tooltip doesn't hang around when we are loading more data
|
||||
const tooltip = document.getElementById('chartjs-tooltip');
|
||||
if (tooltip) {
|
||||
tooltip.style.opacity = 0;
|
||||
tooltip.style.display = 'none';
|
||||
}
|
||||
window.removeEventListener('mousemove', this.repositionTooltip)
|
||||
}
|
||||
|
||||
/**
|
||||
* The current ticks' limits are set to treat iPad (regular/Mini/Pro) as a regular screen.
|
||||
* @param {*} chart - The chart instance.
|
||||
* @param {*} dimensions - An object containing the new dimensions *of the chart.*
|
||||
*/
|
||||
updateWindowDimensions(chart, dimensions) {
|
||||
chart.options.scales.x.ticks.maxTicksLimit = dimensions.width < 720 ? 5 : 8
|
||||
}
|
||||
|
||||
maybeHopToHoveredPeriod(e) {
|
||||
const element = this.chart.getElementsAtEventForMode(e, 'index', { intersect: false })[0]
|
||||
const date = this.props.graphData.labels[element.index] || this.props.graphData.comparison_labels[element.index]
|
||||
|
||||
if (this.props.graphData.interval === 'month') {
|
||||
navigateToQuery(this.props.history, this.props.query, { period: 'month', date })
|
||||
} else if (this.props.graphData.interval === 'date') {
|
||||
navigateToQuery(this.props.history, this.props.query, { period: 'day', date })
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { graphData } = this.props
|
||||
const canvasClass = classNames('mt-4 select-none', { 'cursor-pointer': !['minute', 'hour'].includes(graphData?.interval) })
|
||||
|
||||
return (
|
||||
<FadeIn show={graphData}>
|
||||
<div className="relative h-96 print:h-auto print:pb-8 w-full z-0">
|
||||
<canvas id="main-graph-canvas" className={canvasClass}></canvas>
|
||||
</div>
|
||||
</FadeIn>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(LineGraph)
|
||||
@ -1,17 +0,0 @@
|
||||
import React from "react"
|
||||
|
||||
export default function SamplingNotice({topStatData}) {
|
||||
const samplePercent = topStatData?.samplePercent
|
||||
|
||||
if (samplePercent && samplePercent < 100) {
|
||||
return (
|
||||
<div tooltip={`Stats based on a ${samplePercent}% sample of all visitors`} className="cursor-pointer w-4 h-4 mx-2">
|
||||
<svg className="absolute w-4 h-4 dark:text-gray-300 text-gray-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
import React, { useState } from "react"
|
||||
import * as api from '../../api'
|
||||
import { getCurrentInterval } from "./interval-picker"
|
||||
|
||||
export default function StatsExport({site, query}) {
|
||||
const [exporting, setExporting] = useState(false)
|
||||
|
||||
function startExport() {
|
||||
setExporting(true)
|
||||
document.cookie = "exporting="
|
||||
pollExportReady()
|
||||
}
|
||||
|
||||
function pollExportReady() {
|
||||
if (document.cookie.includes('exporting')) {
|
||||
setTimeout(pollExportReady, 1000)
|
||||
} else {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return (
|
||||
<svg className="animate-spin h-4 w-4 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function renderExportLink() {
|
||||
const interval = getCurrentInterval(site, query)
|
||||
const queryParams = api.serializeQuery(query, [{ interval }])
|
||||
const endpoint = `/${encodeURIComponent(site.domain)}/export${queryParams}`
|
||||
|
||||
return (
|
||||
<a href={endpoint} download onClick={startExport}>
|
||||
<svg className="absolute text-gray-700 feather dark:text-gray-300 hover:text-indigo-600 dark:hover:text-indigo-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
|
||||
<polyline points="7 10 12 15 17 10"></polyline>
|
||||
<line x1="12" y1="15" x2="12" y2="3"></line>
|
||||
</svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-4 h-4 mx-2">
|
||||
{exporting && renderLoading()}
|
||||
{!exporting && renderExportLink()}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,40 +0,0 @@
|
||||
import React from "react"
|
||||
import { parseNaiveDate, isBefore } from '../../util/date'
|
||||
import { Link } from 'react-router-dom'
|
||||
import * as url from '../../util/url'
|
||||
import { BarsArrowUpIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
export default function WithImportedSwitch({site, topStatData}) {
|
||||
if (!topStatData?.imports_exist) {
|
||||
return null
|
||||
}
|
||||
|
||||
function isBeforeNativeStats(date) {
|
||||
if (!date) return false
|
||||
|
||||
const nativeStatsBegin = parseNaiveDate(site.nativeStatsBegin)
|
||||
const parsedDate = parseNaiveDate(date)
|
||||
|
||||
return isBefore(parsedDate, nativeStatsBegin, "day")
|
||||
}
|
||||
|
||||
const isQueryingImportedPeriod = isBeforeNativeStats(topStatData.from)
|
||||
const isComparingImportedPeriod = isBeforeNativeStats(topStatData.comparing_from)
|
||||
|
||||
if (isQueryingImportedPeriod || isComparingImportedPeriod) {
|
||||
const withImported = topStatData.with_imported;
|
||||
const toggleColor = withImported ? " dark:text-gray-300 text-gray-700" : " dark:text-gray-500 text-gray-400"
|
||||
const target = url.setQuery('with_imported', !withImported)
|
||||
const tip = withImported ? "" : "do not ";
|
||||
|
||||
return (
|
||||
<Link to={target} className="w-4 h-4 mx-2">
|
||||
<div tooltip={`Stats ${tip}include imported data.`} className="cursor-pointer w-4 h-4">
|
||||
<BarsArrowUpIcon className={"absolute " + toggleColor} />
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,129 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Link } from 'react-router-dom'
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import Modal from './modal'
|
||||
import * as api from '../../api'
|
||||
import * as url from "../../util/url";
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import { parseQuery } from '../../query'
|
||||
import { escapeFilterValue } from '../../util/filters'
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
function ConversionsModal(props) {
|
||||
const site = props.site
|
||||
const query = parseQuery(props.location.search, site)
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
|
||||
const [page, setPage] = useState(1)
|
||||
const [list, setList] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
function fetchData() {
|
||||
api.get(url.apiPath(site, `/conversions`), query, { limit: 100, page })
|
||||
.then((res) => {
|
||||
setLoading(false)
|
||||
setList(list.concat(res))
|
||||
setPage(page + 1)
|
||||
setMoreResultsAvailable(res.length >= 100)
|
||||
})
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
setLoading(true)
|
||||
fetchData()
|
||||
}
|
||||
|
||||
function renderLoadMore() {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={loadMore} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function filterSearchLink(listItem) {
|
||||
const searchParams = new URLSearchParams(window.location.search)
|
||||
searchParams.set('goal', escapeFilterValue(listItem.name))
|
||||
return searchParams.toString()
|
||||
}
|
||||
|
||||
function renderListItem(listItem, hasRevenue) {
|
||||
return (
|
||||
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
|
||||
<td className="p-2">
|
||||
<Link
|
||||
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
|
||||
className="hover:underline block truncate">
|
||||
{listItem.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return <div className="loading my-16 mx-auto"><div></div></div>
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const hasRevenue = BUILD_EXTRA && list.some((goal) => goal.total_revenue)
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Goal Conversions</h1>
|
||||
|
||||
<div className="my-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">Goal</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Uniques</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Total</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">CR</th>
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((item) => renderListItem(item, hasRevenue))}
|
||||
</tbody>
|
||||
</table>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={site}>
|
||||
{renderBody()}
|
||||
{loading && renderLoading()}
|
||||
{!loading && moreResultsAvailable && renderLoadMore()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(ConversionsModal)
|
||||
@ -1,24 +0,0 @@
|
||||
import React from "react"
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import Modal from './modal'
|
||||
import RegularFilterModal from './regular-filter-modal'
|
||||
import PropFilterModal from "./prop-filter-modal"
|
||||
|
||||
function FilterModal(props) {
|
||||
function renderBody() {
|
||||
const filterGroup = props.match.params.field || 'page'
|
||||
if (filterGroup === 'props') {
|
||||
return <PropFilterModal site={props.site} />
|
||||
} else {
|
||||
return <RegularFilterModal site={props.site} filterGroup={filterGroup} />
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={props.site} maxWidth="460px">
|
||||
{renderBody()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(FilterModal)
|
||||
@ -0,0 +1,312 @@
|
||||
import React, { Fragment } from "react";
|
||||
import { withRouter } from 'react-router-dom'
|
||||
import classNames from 'classnames'
|
||||
import { Menu, Transition } from '@headlessui/react'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
import Combobox from '../../components/combobox'
|
||||
import Modal from './modal'
|
||||
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_TYPES } from '../../util/filters'
|
||||
import { parseQuery } from '../../query'
|
||||
import * as api from '../../api'
|
||||
import { apiPath, siteBasePath } from '../../util/url'
|
||||
import { shouldIgnoreKeypress } from '../../keybinding'
|
||||
|
||||
function getFormState(filterGroup, query) {
|
||||
if (filterGroup === 'props') {
|
||||
const propsObject = query.filters['props']
|
||||
const entries = propsObject && Object.entries(propsObject)
|
||||
|
||||
if (entries && entries.length == 1) {
|
||||
const [[propKey, _propVal]] = entries
|
||||
const {type, clauses} = parseQueryFilter(query, 'props')
|
||||
|
||||
return {
|
||||
'prop_key': { type: FILTER_TYPES.is, clauses: [{label: propKey, value: propKey}] },
|
||||
'prop_value': { type, clauses }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return FILTER_GROUPS[filterGroup].reduce((result, filter) => {
|
||||
const {type, clauses} = parseQueryFilter(query, filter)
|
||||
|
||||
return Object.assign(result, { [filter]: { type, clauses } })
|
||||
}, {})
|
||||
}
|
||||
|
||||
function supportsContains(filterName) {
|
||||
return ['page', 'entry_page', 'exit_page'].includes(filterName)
|
||||
}
|
||||
|
||||
function supportsIsNot(filterName) {
|
||||
return !['goal', 'prop_key'].includes(filterName)
|
||||
}
|
||||
|
||||
function withIndefiniteArticle(word) {
|
||||
if (word.startsWith('UTM')) {
|
||||
return `a ${word}`
|
||||
} if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) {
|
||||
return `an ${word}`
|
||||
}
|
||||
return `a ${word}`
|
||||
|
||||
}
|
||||
|
||||
class FilterModal extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const selectedFilterGroup = this.props.match.params.field || 'page'
|
||||
const formState = getFormState(selectedFilterGroup, query)
|
||||
|
||||
this.state = { selectedFilterGroup, query, formState }
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
document.addEventListener("keydown", this.handleKeydown)
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener("keydown", this.handleKeydown);
|
||||
}
|
||||
|
||||
handleKeydown(e) {
|
||||
if (shouldIgnoreKeypress(e)) return
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
this.handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
const { formState } = this.state;
|
||||
|
||||
const filters = Object.entries(formState).reduce((res, [filterKey, { type, clauses }]) => {
|
||||
if (clauses.length === 0) { return res }
|
||||
if (filterKey === 'country') { res.push({ filter: 'country_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'region') { res.push({ filter: 'region_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'city') { res.push({ filter: 'city_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'prop_value') { return res }
|
||||
if (filterKey === 'prop_key') {
|
||||
const [{value: propKey}] = clauses
|
||||
res.push({ filter: 'props', value: JSON.stringify({ [propKey]: toFilterQuery(formState.prop_value.type, formState.prop_value.clauses) }) })
|
||||
return res
|
||||
}
|
||||
|
||||
res.push({ filter: filterKey, value: toFilterQuery(type, clauses) })
|
||||
return res
|
||||
}, [])
|
||||
|
||||
this.selectFiltersAndCloseModal(filters)
|
||||
}
|
||||
|
||||
onChange(filterName) {
|
||||
return (selection) => {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { clauses: selection })
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
setFilterType(filterName, newType) {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { type: newType })
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
fetchOptions(filter) {
|
||||
return (input) => {
|
||||
const { query, formState } = this.state
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState).map(([filter, {type, clauses}]) => [filter, toFilterQuery(type, clauses)])
|
||||
)
|
||||
const updatedQuery = this.queryForSuggestions(query, formFilters, filter)
|
||||
return api.get(apiPath(this.props.site, `/suggestions/${filter}`), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
queryForSuggestions(query, formFilters, filter) {
|
||||
if (filter === 'prop_key') {
|
||||
const propsFilter = formFilters.prop_value ? { '': formFilters.prop_value } : null
|
||||
return { ...query, filters: { ...query.filters, props: propsFilter } }
|
||||
} else if (filter === 'prop_value') {
|
||||
const propsFilter = formFilters.prop_key ? { [formFilters.prop_key]: '!(none)' } : null
|
||||
return { ...query, filters: { ...query.filters, props: propsFilter } }
|
||||
} else {
|
||||
return { ...query, filters: { ...query.filters, ...formFilters, [filter]: this.negate(formFilters[filter]) } }
|
||||
}
|
||||
}
|
||||
|
||||
negate(filterVal) {
|
||||
if (!filterVal) {
|
||||
return filterVal
|
||||
} else if (filterVal.startsWith('!')) {
|
||||
return filterVal
|
||||
} else {
|
||||
return '!' + filterVal
|
||||
}
|
||||
}
|
||||
|
||||
selectedFilterType(filter) {
|
||||
return this.state.formState[filter].type
|
||||
}
|
||||
|
||||
isDisabled() {
|
||||
if (this.state.selectedFilterGroup === 'props') {
|
||||
return Object.entries(this.state.formState).some(([_key, { clauses }]) => clauses.length === 0)
|
||||
} else {
|
||||
return Object.entries(this.state.formState).every(([_key, { clauses }]) => clauses.length === 0)
|
||||
}
|
||||
}
|
||||
|
||||
selectFiltersAndCloseModal(filters) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
filters.forEach((entry) => {
|
||||
if (entry.value) {
|
||||
queryString.set(entry.filter, entry.value)
|
||||
} else {
|
||||
queryString.delete(entry.filter)
|
||||
}
|
||||
})
|
||||
|
||||
this.props.history.replace({ pathname: siteBasePath(this.props.site), search: queryString.toString() })
|
||||
}
|
||||
|
||||
renderSearchBox(filter) {
|
||||
const freeChoice = this.state.selectedFilterGroup === 'page'
|
||||
return <Combobox fetchOptions={this.fetchOptions(filter)} freeChoice={freeChoice} values={this.state.formState[filter].clauses} onChange={this.onChange(filter)} placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`} />
|
||||
}
|
||||
|
||||
renderFilterInputs() {
|
||||
const groups = FILTER_GROUPS[this.state.selectedFilterGroup]
|
||||
|
||||
return groups.map((filter) => {
|
||||
return (
|
||||
<div className="mt-4" key={filter}>
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">{formattedFilters[filter]}</div>
|
||||
<div className="flex items-start mt-1">
|
||||
{this.renderFilterTypeSelector(filter)}
|
||||
{this.renderSearchBox(filter)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
renderFilterTypeSelector(filterName) {
|
||||
return (
|
||||
<Menu as="div" className="relative inline-block text-left">
|
||||
{({ open }) => (
|
||||
<>
|
||||
<div className="w-24">
|
||||
<Menu.Button className="inline-flex justify-between items-center w-full rounded-md border border-gray-300 dark:border-gray-500 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-850 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 dark:focus:ring-offset-gray-900 focus:ring-indigo-500">
|
||||
{this.selectedFilterType(filterName)}
|
||||
<ChevronDownIcon className="-mr-2 ml-2 h-4 w-4 text-gray-500 dark:text-gray-400" aria-hidden="true" />
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
show={open}
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
static
|
||||
className="z-10 origin-top-left absolute left-0 mt-2 w-24 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5 focus:outline-none"
|
||||
>
|
||||
<div className="py-1">
|
||||
{this.renderTypeItem(filterName, FILTER_TYPES.is, true)}
|
||||
{this.renderTypeItem(filterName, FILTER_TYPES.isNot, supportsIsNot(filterName))}
|
||||
{this.renderTypeItem(filterName, FILTER_TYPES.contains, supportsContains(filterName))}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
)
|
||||
}
|
||||
|
||||
renderTypeItem(filterName, type, shouldDisplay) {
|
||||
return (
|
||||
shouldDisplay && (
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<span
|
||||
onClick={() => this.setFilterType(filterName, type)}
|
||||
className={classNames(
|
||||
active ? "bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100" : "text-gray-700 dark:text-gray-200",
|
||||
"cursor-pointer block px-4 py-2 text-sm"
|
||||
)}
|
||||
>
|
||||
{type}
|
||||
</span>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
renderBody() {
|
||||
const { selectedFilterGroup, query } = this.state;
|
||||
const showClear = FILTER_GROUPS[selectedFilterGroup].some((filterName) => query.filters[filterName])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by {formatFilterGroup(selectedFilterGroup)}</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" onSubmit={this.handleSubmit.bind(this)}>
|
||||
{this.renderFilterInputs()}
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={this.isDisabled()}
|
||||
>
|
||||
Apply Filter
|
||||
</button>
|
||||
|
||||
{showClear && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => {
|
||||
const updatedFilters = FILTER_GROUPS[selectedFilterGroup].map((filterName) => ({ filter: filterName, value: null }))
|
||||
this.selectFiltersAndCloseModal(updatedFilters)
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter{FILTER_GROUPS[selectedFilterGroup].length > 1 ? 's' : ''}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Modal site={this.props.site} maxWidth="460px">
|
||||
{this.renderBody()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(FilterModal)
|
||||
@ -1,205 +0,0 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react'
|
||||
import { withRouter } from "react-router-dom";
|
||||
|
||||
import { FILTER_OPERATIONS } from "../../util/filters";
|
||||
import { parseQuery } from '../../query'
|
||||
import { siteBasePath } from '../../util/url'
|
||||
import { toFilterQuery, parseQueryPropsFilter } from '../../util/filters';
|
||||
import { shouldIgnoreKeypress } from '../../keybinding';
|
||||
import PropFilterRow from './prop-filter-row';
|
||||
|
||||
function getFormState(query) {
|
||||
if (query.filters['props']) {
|
||||
const values = Object.fromEntries(parseQueryPropsFilter(query, 'props').map((value, index) => [index, value]))
|
||||
|
||||
return {
|
||||
entries: Object.keys(values).sort(),
|
||||
values
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
entries: [0],
|
||||
values: {
|
||||
0: {
|
||||
propKey: null,
|
||||
type: FILTER_OPERATIONS.is,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function PropFilterModal(props) {
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const [formState, setFormState] = useState(getFormState(query))
|
||||
|
||||
const selectedPropKeys = useMemo(() => Object.values(formState.values).map((value) => value.propKey), [formState])
|
||||
|
||||
function onPropKeySelect(id, selectedOptions) {
|
||||
const newPropKey = selectedOptions.length === 0 ? null : selectedOptions[0]
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
propKey: newPropKey,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onPropValueSelect(id, selection) {
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
clauses: selection
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onFilterTypeSelect(id, newType) {
|
||||
setFormState(prevState => ({
|
||||
...prevState,
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
...prevState.values[id],
|
||||
type: newType
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
function onPropAdd() {
|
||||
setFormState(prevState => {
|
||||
const id = prevState.entries[prevState.entries.length - 1] + 1
|
||||
return {
|
||||
entries: prevState.entries.concat([id]),
|
||||
values: {
|
||||
...prevState.values,
|
||||
[id]: {
|
||||
propKey: null,
|
||||
type: FILTER_OPERATIONS.is,
|
||||
clauses: []
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function onPropDelete(id) {
|
||||
setFormState(prevState => {
|
||||
const entries = prevState.entries.filter((entry) => entry != id)
|
||||
const values = {...prevState.values}
|
||||
delete values[id]
|
||||
|
||||
return { entries, values }
|
||||
})
|
||||
}
|
||||
|
||||
function isDisabled() {
|
||||
return formState.entries.some((id) => !formState.values[id].propKey || formState.values[id].clauses.length == 0)
|
||||
}
|
||||
|
||||
function shouldShowClear() {
|
||||
return !!query.filters['props']
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState.values)
|
||||
.map(([_, {propKey, type, clauses}]) => [propKey.value, toFilterQuery(type, clauses)])
|
||||
)
|
||||
selectFiltersAndCloseModal(JSON.stringify(formFilters))
|
||||
}
|
||||
|
||||
function selectFiltersAndCloseModal(filterString) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
if (filterString) {
|
||||
queryString.set('props', filterString)
|
||||
} else {
|
||||
queryString.delete('props')
|
||||
}
|
||||
|
||||
props.history.replace({ pathname: siteBasePath(props.site), search: queryString.toString() })
|
||||
}
|
||||
|
||||
const handleKeydown = (e) => {
|
||||
if (shouldIgnoreKeypress(e)) return
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('keydown', handleKeydown)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeydown)
|
||||
}
|
||||
}, [handleSubmit])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by Property</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" onSubmit={handleSubmit}>
|
||||
{formState.entries.map((id) => (
|
||||
<PropFilterRow
|
||||
key={id}
|
||||
id={id}
|
||||
site={props.site}
|
||||
query={query}
|
||||
{...formState.values[id]}
|
||||
showDelete={formState.entries.length > 1}
|
||||
selectedPropKeys={selectedPropKeys}
|
||||
onPropKeySelect={onPropKeySelect}
|
||||
onPropValueSelect={onPropValueSelect}
|
||||
onFilterTypeSelect={onFilterTypeSelect}
|
||||
onPropDelete={onPropDelete}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className="mt-6">
|
||||
<a className="underline text-indigo-500 text-sm cursor-pointer" onClick={onPropAdd}>
|
||||
+ Add another
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={isDisabled()}
|
||||
>
|
||||
Apply Filter
|
||||
</button>
|
||||
|
||||
{shouldShowClear() && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => { selectFiltersAndCloseModal(null) }}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(PropFilterModal)
|
||||
@ -1,86 +0,0 @@
|
||||
import React from 'react'
|
||||
|
||||
import Combobox from '../../components/combobox'
|
||||
import FilterTypeSelector from "../../components/filter-type-selector";
|
||||
import { FILTER_OPERATIONS } from "../../util/filters";
|
||||
import * as api from '../../api'
|
||||
import { apiPath } from '../../util/url'
|
||||
import { TrashIcon } from '@heroicons/react/20/solid'
|
||||
|
||||
function PropFilterRow({
|
||||
id,
|
||||
query,
|
||||
site,
|
||||
propKey,
|
||||
type,
|
||||
clauses,
|
||||
showDelete,
|
||||
selectedPropKeys,
|
||||
onPropKeySelect,
|
||||
onPropValueSelect,
|
||||
onFilterTypeSelect,
|
||||
onPropDelete
|
||||
}) {
|
||||
function fetchPropKeyOptions() {
|
||||
return (input) => {
|
||||
return api.get(apiPath(site, "/suggestions/prop_key"), query, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
function fetchPropValueOptions() {
|
||||
return (input) => {
|
||||
if (type === FILTER_OPERATIONS.contains) {
|
||||
return Promise.resolve([])
|
||||
}
|
||||
|
||||
|
||||
const key = propKey?.value
|
||||
const updatedQuery = { ...query, filters: { ...query.filters, props: { [key]: '!(none)' } } }
|
||||
return api.get(apiPath(site, "/suggestions/prop_value"), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-12 mt-6">
|
||||
<div className="col-span-4">
|
||||
<Combobox
|
||||
className="mr-2"
|
||||
fetchOptions={fetchPropKeyOptions()}
|
||||
singleOption
|
||||
autoFocus
|
||||
values={propKey ? [propKey] : []}
|
||||
onSelect={(value) => onPropKeySelect(id, value)}
|
||||
placeholder={'Property'}
|
||||
disabledOptions={selectedPropKeys}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-3 mx-2">
|
||||
<FilterTypeSelector
|
||||
isDisabled={!propKey}
|
||||
forFilter={'prop_value'}
|
||||
onSelect={(value) => onFilterTypeSelect(id, value)}
|
||||
selectedType={type}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-4">
|
||||
<Combobox
|
||||
isDisabled={!propKey}
|
||||
fetchOptions={fetchPropValueOptions()}
|
||||
values={clauses}
|
||||
onSelect={(value) => onPropValueSelect(id, value)}
|
||||
placeholder={'Value'}
|
||||
freeChoice={type == FILTER_OPERATIONS.contains}
|
||||
/>
|
||||
</div>
|
||||
{showDelete && (
|
||||
<div className="col-span-1 flex flex-col justify-center">
|
||||
<a className="ml-2 text-red-600 h-5 w-5 cursor-pointer" onClick={() => onPropDelete(id)}>
|
||||
<TrashIcon />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default PropFilterRow
|
||||
@ -1,132 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Link } from 'react-router-dom'
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import Modal from './modal'
|
||||
import * as api from '../../api'
|
||||
import * as url from "../../util/url";
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import { parseQuery } from '../../query'
|
||||
import { specialTitleWhenGoalFilter } from "../behaviours/goal-conversions";
|
||||
import { escapeFilterValue } from "../../util/filters"
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
function PropsModal(props) {
|
||||
const site = props.site
|
||||
const query = parseQuery(props.location.search, site)
|
||||
const propKey = props.location.pathname.split('/').pop()
|
||||
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
|
||||
const [page, setPage] = useState(1)
|
||||
const [list, setList] = useState([])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
function fetchData() {
|
||||
api.get(url.apiPath(site, `/custom-prop-values/${propKey}`), query, { limit: 100, page })
|
||||
.then((res) => {
|
||||
setLoading(false)
|
||||
setList(list.concat(res))
|
||||
setPage(page + 1)
|
||||
setMoreResultsAvailable(res.length >= 100)
|
||||
})
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
setLoading(true)
|
||||
fetchData()
|
||||
}
|
||||
|
||||
function renderLoadMore() {
|
||||
return (
|
||||
<div className="w-full text-center my-4">
|
||||
<button onClick={loadMore} type="button" className="button">
|
||||
Load more
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function filterSearchLink(listItem) {
|
||||
const searchParams = new URLSearchParams(window.location.search)
|
||||
searchParams.set('props', JSON.stringify({ [propKey]: escapeFilterValue(listItem.name) }))
|
||||
return searchParams.toString()
|
||||
}
|
||||
|
||||
function renderListItem(listItem, hasRevenue) {
|
||||
return (
|
||||
<tr className="text-sm dark:text-gray-200" key={listItem.name}>
|
||||
<td className="p-2">
|
||||
<Link
|
||||
to={{ pathname: url.siteBasePath(site), search: filterSearchLink(listItem) }}
|
||||
className="hover:underline block truncate">
|
||||
{url.trimURL(listItem.name, 30)}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.visitors)}</td>
|
||||
<td className="p-2 w-24 font-medium" align="right">{numberFormatter(listItem.events)}</td>
|
||||
{query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.conversion_rate}%</td>}
|
||||
{!query.filters.goal && <td className="p-2 w-24 font-medium" align="right">{listItem.percentage}</td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.total_revenue} /></td>}
|
||||
{hasRevenue && <td className="p-2 w-24 font-medium" align="right"><Money formatted={listItem.average_revenue} /></td>}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return <div className="loading my-16 mx-auto"><div></div></div>
|
||||
}
|
||||
|
||||
function renderBody() {
|
||||
const hasRevenue = BUILD_EXTRA && list.some((prop) => prop.total_revenue)
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">{specialTitleWhenGoalFilter(query, 'Custom Property Breakdown')}</h1>
|
||||
|
||||
<div className="my-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<table className="w-max overflow-x-auto md:w-full table-striped table-fixed">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 w-48 md:w-56 lg:w-1/3 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400 truncate" align="left">{propKey}</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Visitors</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Events</th>
|
||||
<th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">{query.filters.goal ? 'CR' : '%'}</th>
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Revenue</th>}
|
||||
{hasRevenue && <th className="p-2 w-24 text-xs tracking-wide font-bold text-gray-500 dark:text-gray-400" align="right">Average</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.map((item) => renderListItem(item, hasRevenue))}
|
||||
</tbody>
|
||||
</table>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal site={site}>
|
||||
{renderBody()}
|
||||
{loading && renderLoading()}
|
||||
{!loading && moreResultsAvailable && renderLoadMore()}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withRouter(PropsModal)
|
||||
@ -1,209 +0,0 @@
|
||||
import React from "react";
|
||||
import { withRouter } from 'react-router-dom'
|
||||
|
||||
import FilterTypeSelector from "../../components/filter-type-selector";
|
||||
import Combobox from '../../components/combobox'
|
||||
import { FILTER_GROUPS, parseQueryFilter, formatFilterGroup, formattedFilters, toFilterQuery, FILTER_OPERATIONS } from '../../util/filters'
|
||||
import { parseQuery } from '../../query'
|
||||
import * as api from '../../api'
|
||||
import { apiPath, siteBasePath } from '../../util/url'
|
||||
import { shouldIgnoreKeypress } from '../../keybinding'
|
||||
import { isFreeChoiceFilter } from "../../util/filters";
|
||||
|
||||
function getFormState(filterGroup, query) {
|
||||
return FILTER_GROUPS[filterGroup].reduce((result, filter) => {
|
||||
const {type, clauses} = parseQueryFilter(query, filter)
|
||||
|
||||
return Object.assign(result, { [filter]: { type, clauses } })
|
||||
}, {})
|
||||
}
|
||||
|
||||
function withIndefiniteArticle(word) {
|
||||
if (word.startsWith('UTM')) {
|
||||
return `a ${word}`
|
||||
} if (['a', 'e', 'i', 'o', 'u'].some((vowel) => word.toLowerCase().startsWith(vowel))) {
|
||||
return `an ${word}`
|
||||
}
|
||||
return `a ${word}`
|
||||
}
|
||||
|
||||
class RegularFilterModal extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
const query = parseQuery(props.location.search, props.site)
|
||||
const formState = getFormState(props.filterGroup, query)
|
||||
|
||||
this.handleKeydown = this.handleKeydown.bind(this)
|
||||
this.state = { query, formState }
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
document.addEventListener("keydown", this.handleKeydown)
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener("keydown", this.handleKeydown);
|
||||
}
|
||||
|
||||
handleKeydown(e) {
|
||||
if (shouldIgnoreKeypress(e)) return
|
||||
|
||||
if (e.target.tagName === 'BODY' && e.key === 'Enter') {
|
||||
this.handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
const { formState } = this.state;
|
||||
|
||||
const filters = Object.entries(formState).reduce((res, [filterKey, { type, clauses }]) => {
|
||||
if (clauses.length === 0) { return res }
|
||||
if (filterKey === 'country') { res.push({ filter: 'country_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'region') { res.push({ filter: 'region_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
if (filterKey === 'city') { res.push({ filter: 'city_labels', value: clauses.map(clause => clause.label).join('|') }) }
|
||||
|
||||
res.push({ filter: filterKey, value: toFilterQuery(type, clauses) })
|
||||
return res
|
||||
}, [])
|
||||
|
||||
this.selectFiltersAndCloseModal(filters)
|
||||
}
|
||||
|
||||
onComboboxSelect(filterName) {
|
||||
return (selection) => {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { clauses: selection })
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
onFilterTypeSelect(filterName) {
|
||||
return (newType) => {
|
||||
this.setState(prevState => ({
|
||||
formState: Object.assign(prevState.formState, {
|
||||
[filterName]: Object.assign(prevState.formState[filterName], { type: newType })
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fetchOptions(filter) {
|
||||
return (input) => {
|
||||
const { query, formState } = this.state
|
||||
if (formState[filter].type === FILTER_OPERATIONS.contains) {return Promise.resolve([])}
|
||||
|
||||
const formFilters = Object.fromEntries(
|
||||
Object.entries(formState)
|
||||
.filter(([_filter, {_type, clauses}]) => clauses.length > 0)
|
||||
.map(([filter, {type, clauses}]) => [filter, toFilterQuery(type, clauses)])
|
||||
)
|
||||
const updatedQuery = this.queryForSuggestions(query, formFilters, filter)
|
||||
return api.get(apiPath(this.props.site, `/suggestions/${filter}`), updatedQuery, { q: input.trim() })
|
||||
}
|
||||
}
|
||||
|
||||
queryForSuggestions(query, formFilters, filter) {
|
||||
return { ...query, filters: { ...query.filters, ...formFilters, [filter]: this.negate(formFilters[filter]) } }
|
||||
}
|
||||
|
||||
negate(filterVal) {
|
||||
if (!filterVal) {
|
||||
return filterVal
|
||||
} else if (filterVal.startsWith('!')) {
|
||||
return filterVal
|
||||
} else if (filterVal.startsWith('~')) {
|
||||
return null
|
||||
} else {
|
||||
return '!' + filterVal
|
||||
}
|
||||
}
|
||||
|
||||
selectedFilterType(filter) {
|
||||
return this.state.formState[filter].type
|
||||
}
|
||||
|
||||
isDisabled() {
|
||||
return Object.entries(this.state.formState).every(([_key, { clauses }]) => clauses.length === 0)
|
||||
}
|
||||
|
||||
selectFiltersAndCloseModal(filters) {
|
||||
const queryString = new URLSearchParams(window.location.search)
|
||||
|
||||
filters.forEach((entry) => {
|
||||
if (entry.value) {
|
||||
queryString.set(entry.filter, entry.value)
|
||||
} else {
|
||||
queryString.delete(entry.filter)
|
||||
}
|
||||
})
|
||||
|
||||
this.props.history.replace({ pathname: siteBasePath(this.props.site), search: queryString.toString() })
|
||||
}
|
||||
|
||||
renderFilterInputs() {
|
||||
const filtersInGroup = FILTER_GROUPS[this.props.filterGroup]
|
||||
|
||||
return filtersInGroup.map((filter) => {
|
||||
return (
|
||||
<div className="mt-4" key={filter}>
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">{formattedFilters[filter]}</div>
|
||||
<div className="grid grid-cols-11 mt-1">
|
||||
<div className="col-span-3 mr-2">
|
||||
<FilterTypeSelector forFilter={filter} onSelect={this.onFilterTypeSelect(filter)} selectedType={this.selectedFilterType(filter)}/>
|
||||
</div>
|
||||
<div className="col-span-8">
|
||||
<Combobox fetchOptions={this.fetchOptions(filter)} freeChoice={isFreeChoiceFilter(filter)} values={this.state.formState[filter].clauses} onSelect={this.onComboboxSelect(filter)} placeholder={`Select ${withIndefiniteArticle(formattedFilters[filter])}`}/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
const { filterGroup } = this.props
|
||||
const { query } = this.state
|
||||
const showClear = FILTER_GROUPS[filterGroup].some((filterName) => query.filters[filterName])
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-xl font-bold dark:text-gray-100">Filter by {formatFilterGroup(filterGroup)}</h1>
|
||||
|
||||
<div className="mt-4 border-b border-gray-300"></div>
|
||||
<main className="modal__content">
|
||||
<form className="flex flex-col" onSubmit={this.handleSubmit.bind(this)}>
|
||||
{this.renderFilterInputs()}
|
||||
|
||||
<div className="mt-6 flex items-center justify-start">
|
||||
<button
|
||||
type="submit"
|
||||
className="button"
|
||||
disabled={this.isDisabled()}
|
||||
>
|
||||
Apply Filter
|
||||
</button>
|
||||
|
||||
{showClear && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-2 button px-4 flex bg-red-500 dark:bg-red-500 hover:bg-red-600 dark:hover:bg-red-700 items-center"
|
||||
onClick={() => {
|
||||
const updatedFilters = FILTER_GROUPS[filterGroup].map((filterName) => ({ filter: filterName, value: null }))
|
||||
this.selectFiltersAndCloseModal(updatedFilters)
|
||||
}}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
|
||||
Remove filter{FILTER_GROUPS[filterGroup].length > 1 ? 's' : ''}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(RegularFilterModal)
|
||||
@ -1,54 +0,0 @@
|
||||
import numberFormatter from "../../util/number-formatter"
|
||||
import React from "react"
|
||||
|
||||
/*global BUILD_EXTRA*/
|
||||
/*global require*/
|
||||
function maybeRequire() {
|
||||
if (BUILD_EXTRA) {
|
||||
return require('../../extra/money')
|
||||
} else {
|
||||
return { default: null }
|
||||
}
|
||||
}
|
||||
|
||||
const Money = maybeRequire().default
|
||||
|
||||
export const VISITORS_METRIC = {
|
||||
name: 'visitors',
|
||||
label: 'Visitors',
|
||||
realtimeLabel: 'Current visitors',
|
||||
goalFilterLabel: 'Conversions',
|
||||
plot: true
|
||||
}
|
||||
export const PERCENTAGE_METRIC = { name: 'percentage', label: '%' }
|
||||
export const CR_METRIC = { name: 'conversion_rate', label: 'CR' }
|
||||
|
||||
export function maybeWithCR(metrics, query) {
|
||||
if (metrics.includes(PERCENTAGE_METRIC) && query.filters.goal) {
|
||||
return metrics.filter((m) => { return m !== PERCENTAGE_METRIC }).concat([CR_METRIC])
|
||||
}
|
||||
else if (query.filters.goal) {
|
||||
return metrics.concat(CR_METRIC)
|
||||
}
|
||||
else {
|
||||
return metrics
|
||||
}
|
||||
}
|
||||
|
||||
export function displayMetricValue(value, metric) {
|
||||
if (['total_revenue', 'average_revenue'].includes(metric.name)) {
|
||||
return <Money formatted={value} />
|
||||
} else if (metric === PERCENTAGE_METRIC) {
|
||||
return value
|
||||
} else if (metric === CR_METRIC) {
|
||||
return `${value}%`
|
||||
} else {
|
||||
return <span tooltip={value}>{numberFormatter(value)}</span>
|
||||
}
|
||||
}
|
||||
|
||||
export function metricLabelFor(metric, query) {
|
||||
if (metric.realtimeLabel && query.period === 'realtime') { return metric.realtimeLabel }
|
||||
if (metric.goalFilterLabel && query.filters.goal) { return metric.goalFilterLabel }
|
||||
return metric.label
|
||||
}
|
||||
@ -1,48 +1,179 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom'
|
||||
import FlipMove from 'react-flip-move';
|
||||
|
||||
import FadeIn from '../../fade-in'
|
||||
import Bar from '../bar'
|
||||
import MoreLink from '../more-link'
|
||||
import numberFormatter from '../../util/number-formatter'
|
||||
import * as api from '../../api'
|
||||
import * as url from '../../util/url'
|
||||
import { VISITORS_METRIC, maybeWithCR } from '../reports/metrics'
|
||||
import ListReport from '../reports/list'
|
||||
import LazyLoader from '../../components/lazy-loader'
|
||||
|
||||
function LinkOption(props) {
|
||||
if (props.disabled) {
|
||||
return <span {...props}>{props.children}</span>
|
||||
} else {
|
||||
props = Object.assign({}, props, { className: props.className + ' hover:underline' })
|
||||
return <Link {...props}>{props.children}</Link>
|
||||
}
|
||||
}
|
||||
|
||||
export default class Referrers extends React.Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
this.state = { loading: true }
|
||||
this.onVisible = this.onVisible.bind(this)
|
||||
this.fetchReferrers = this.fetchReferrers.bind(this)
|
||||
}
|
||||
|
||||
onVisible() {
|
||||
this.fetchReferrers()
|
||||
if (this.props.query.period === 'realtime') {
|
||||
document.addEventListener('tick', this.fetchReferrers)
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.props.query !== prevProps.query) {
|
||||
this.setState({ loading: true, referrers: null })
|
||||
this.fetchReferrers()
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener('tick', this.fetchReferrers)
|
||||
}
|
||||
|
||||
showConversionRate() {
|
||||
return !!this.props.query.filters.goal
|
||||
}
|
||||
|
||||
export default function Referrers({site, query}) {
|
||||
function fetchReferrers() {
|
||||
return api.get(url.apiPath(site, `/referrers/${encodeURIComponent(query.filters.source)}`), query, {limit: 9})
|
||||
fetchReferrers() {
|
||||
if (this.props.query.filters.source) {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers/${encodeURIComponent(this.props.query.filters.source)}`, this.props.query)
|
||||
.then((res) => res.search_terms || res.referrers)
|
||||
.then((referrers) => this.setState({ loading: false, referrers: referrers }))
|
||||
} else if (this.props.query.filters.goal) {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/goal/referrers`, this.props.query)
|
||||
.then((res) => this.setState({ loading: false, referrers: res }))
|
||||
} else {
|
||||
api.get(`/api/stats/${encodeURIComponent(this.props.site.domain)}/referrers`, this.props.query)
|
||||
.then((res) => this.setState({ loading: false, referrers: res }))
|
||||
}
|
||||
}
|
||||
|
||||
function externalLinkDest(referrer) {
|
||||
if (referrer.name === 'Direct / None') { return null }
|
||||
return `https://${referrer.name}`
|
||||
renderExternalLink(referrer) {
|
||||
if (this.props.query.filters.source && this.props.query.filters.source !== 'Google' && referrer.name !== 'Direct / None') {
|
||||
return (
|
||||
<a target="_blank" href={'//' + referrer.name} rel="noreferrer" className="hidden group-hover:block">
|
||||
<svg className="inline w-4 h-4 ml-1 -mt-1 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"></path><path d="M5 5a2 2 0 00-2 2v8a2 2 0 002 2h8a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"></path></svg>
|
||||
</a>
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function getFilterFor(referrer) {
|
||||
if (referrer.name === 'Direct / None') { return null }
|
||||
return { referrer: referrer.name }
|
||||
renderReferrer(referrer) {
|
||||
const maxWidthDeduction = this.showConversionRate() ? "10rem" : "5rem"
|
||||
const query = new URLSearchParams(window.location.search)
|
||||
query.set('referrer', referrer.name)
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between my-1 text-sm" key={referrer.name}>
|
||||
<Bar
|
||||
count={referrer.visitors}
|
||||
all={this.state.referrers}
|
||||
bg="bg-blue-50 dark:bg-gray-500 dark:bg-opacity-15"
|
||||
maxWidthDeduction={maxWidthDeduction}
|
||||
>
|
||||
<span className="flex px-2 py-1.5 z-9 relative break-all group">
|
||||
<LinkOption
|
||||
className="block md:truncate dark:text-gray-300"
|
||||
to={{ search: query.toString() }}
|
||||
disabled={referrer.name === 'Direct / None'}
|
||||
>
|
||||
<img
|
||||
src={`/favicon/sources/${encodeURIComponent(referrer.name)}`}
|
||||
referrerPolicy="no-referrer"
|
||||
className="inline w-4 h-4 mr-2 -mt-px align-middle"
|
||||
/>
|
||||
{referrer.name}
|
||||
</LinkOption>
|
||||
{this.renderExternalLink(referrer)}
|
||||
</span>
|
||||
</Bar>
|
||||
<span className="font-medium dark:text-gray-200">{numberFormatter(referrer.visitors)}</span>
|
||||
{this.showConversionRate() && <span className="font-medium dark:text-gray-200 w-20 text-right">{referrer.conversion_rate}%</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
label() {
|
||||
if (this.props.query.period === 'realtime') {
|
||||
return 'Current visitors'
|
||||
}
|
||||
|
||||
if (this.showConversionRate()) {
|
||||
return 'Conversions'
|
||||
}
|
||||
|
||||
return 'Visitors'
|
||||
}
|
||||
|
||||
function renderIcon(listItem) {
|
||||
renderList() {
|
||||
if (this.state.referrers.length > 0) {
|
||||
return (
|
||||
<div className="flex flex-col flex-grow">
|
||||
<div
|
||||
className="flex items-center justify-between mt-3 mb-2 text-xs font-bold tracking-wide text-gray-500"
|
||||
>
|
||||
<span>Referrer</span>
|
||||
|
||||
<div className="text-right">
|
||||
<span className="inline-block w-20">{this.label()}</span>
|
||||
{this.showConversionRate() && <span className="inline-block w-20">CR</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FlipMove className="flex-grow">
|
||||
{this.state.referrers.map(this.renderReferrer.bind(this))}
|
||||
</FlipMove>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<img
|
||||
src={`/favicon/sources/${encodeURIComponent(listItem.name)}`}
|
||||
referrerPolicy="no-referrer"
|
||||
className="inline w-4 h-4 mr-2 -mt-px align-middle"
|
||||
/>
|
||||
<div
|
||||
className="font-medium text-center text-gray-500 mt-44 dark:text-gray-400"
|
||||
>
|
||||
No data yet
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-grow">
|
||||
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
|
||||
<ListReport
|
||||
fetchData={fetchReferrers}
|
||||
getFilterFor={getFilterFor}
|
||||
keyLabel="Referrer"
|
||||
metrics={maybeWithCR([VISITORS_METRIC], query)}
|
||||
detailsLink={url.sitePath(site, `/referrers/${encodeURIComponent(query.filters.source)}`)}
|
||||
query={query}
|
||||
externalLinkDest={externalLinkDest}
|
||||
renderIcon={renderIcon}
|
||||
color="bg-blue-50"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
renderContent() {
|
||||
if (this.state.referrers) {
|
||||
return (
|
||||
<React.Fragment>
|
||||
{this.renderList()}
|
||||
<MoreLink site={this.props.site} list={this.state.referrers} endpoint={`referrers/${this.props.query.filters.source}`} />
|
||||
</React.Fragment>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
className="relative p-4 bg-white rounded shadow-xl stats-item flex flex-col dark:bg-gray-825 mt-6 w-full"
|
||||
>
|
||||
<LazyLoader onVisible={this.onVisible} className="flex flex-col flex-grow">
|
||||
<h3 className="font-bold dark:text-gray-100">Top Referrers</h3>
|
||||
{this.state.loading && <div className="mx-auto loading mt-44"><div></div></div>}
|
||||
<FadeIn show={!this.state.loading}>
|
||||
{this.renderContent()}
|
||||
</FadeIn>
|
||||
</LazyLoader>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,83 +0,0 @@
|
||||
// Courtesy of Benjamin von Polheim:
|
||||
// https://blog.devgenius.io/build-a-performat-autocomplete-using-phoenix-liveview-and-alpine-js-8bcbbed17ba7
|
||||
|
||||
export default (id) => ({
|
||||
isOpen: false,
|
||||
id: id,
|
||||
focus: null,
|
||||
selectionInProgress: false,
|
||||
setFocus(f) {
|
||||
this.focus = f;
|
||||
},
|
||||
initFocus() {
|
||||
if (this.focus === null) {
|
||||
this.setFocus(this.leastFocusableIndex())
|
||||
}
|
||||
},
|
||||
trackSubmitValueChange() {
|
||||
this.selectionInProgress = false;
|
||||
},
|
||||
open() {
|
||||
if (!this.isOpen) {
|
||||
this.initFocus()
|
||||
this.isOpen = true
|
||||
}
|
||||
},
|
||||
suggestionsCount() {
|
||||
return this.$refs.suggestions?.querySelectorAll('li').length
|
||||
},
|
||||
hasCreatableOption() {
|
||||
return this.$refs.suggestions?.querySelector('li').classList.contains("creatable")
|
||||
},
|
||||
leastFocusableIndex() {
|
||||
if (this.suggestionsCount() === 0) {
|
||||
return 0
|
||||
}
|
||||
return this.hasCreatableOption() ? 0 : 1
|
||||
},
|
||||
maxFocusableIndex() {
|
||||
return this.hasCreatableOption() ? this.suggestionsCount() - 1 : this.suggestionsCount()
|
||||
},
|
||||
nextFocusableIndex() {
|
||||
const currentFocus = this.focus
|
||||
return currentFocus + 1 > this.maxFocusableIndex() ? this.leastFocusableIndex() : currentFocus + 1
|
||||
},
|
||||
prevFocusableIndex() {
|
||||
const currentFocus = this.focus
|
||||
return currentFocus - 1 >= this.leastFocusableIndex() ? currentFocus - 1 : this.maxFocusableIndex()
|
||||
},
|
||||
close(e) {
|
||||
// Pressing Escape should not propagate to window,
|
||||
// so we'll only close the suggestions pop-up
|
||||
if (this.isOpen && e.key === "Escape") {
|
||||
e.stopPropagation()
|
||||
}
|
||||
this.isOpen = false
|
||||
},
|
||||
select() {
|
||||
this.$refs[`dropdown-${this.id}-option-${this.focus}`]?.click()
|
||||
this.close()
|
||||
document.getElementById(this.id).blur()
|
||||
},
|
||||
scrollTo(idx) {
|
||||
this.$refs[`dropdown-${this.id}-option-${idx}`]?.scrollIntoView(
|
||||
{ block: 'nearest', behavior: 'smooth', inline: 'start' }
|
||||
)
|
||||
},
|
||||
focusNext() {
|
||||
const nextIndex = this.nextFocusableIndex()
|
||||
|
||||
this.open()
|
||||
|
||||
this.setFocus(nextIndex)
|
||||
this.scrollTo(nextIndex)
|
||||
},
|
||||
focusPrev() {
|
||||
const prevIndex = this.prevFocusableIndex()
|
||||
|
||||
this.open()
|
||||
|
||||
this.setFocus(prevIndex)
|
||||
this.scrollTo(prevIndex)
|
||||
}
|
||||
})
|
||||
@ -1,20 +0,0 @@
|
||||
// From https://alpinejs.dev/component/dropdown
|
||||
|
||||
export default () => ({
|
||||
open: false,
|
||||
toggle() {
|
||||
if (this.open) {
|
||||
return this.close()
|
||||
}
|
||||
|
||||
this.$refs.button.focus()
|
||||
this.open = true
|
||||
},
|
||||
|
||||
close(focusAfter) {
|
||||
if (! this.open) return
|
||||
|
||||
this.open = false
|
||||
focusAfter && focusAfter.focus()
|
||||
},
|
||||
})
|
||||
@ -1,57 +0,0 @@
|
||||
import "phoenix_html"
|
||||
import Alpine from 'alpinejs'
|
||||
import { Socket } from "phoenix"
|
||||
import { LiveSocket } from "phoenix_live_view"
|
||||
|
||||
let csrfToken = document.querySelector("meta[name='csrf-token']")
|
||||
let websocketUrl = document.querySelector("meta[name='websocket-url']")
|
||||
if (csrfToken && websocketUrl) {
|
||||
let Hooks = {}
|
||||
Hooks.Metrics = {
|
||||
mounted() {
|
||||
this.handleEvent("send-metrics", ({ event_name, params }) => {
|
||||
const afterMetrics = () => {
|
||||
this.pushEvent("send-metrics-after", {event_name, params})
|
||||
}
|
||||
setTimeout(afterMetrics, 5000)
|
||||
params.callback = afterMetrics
|
||||
window.plausible(event_name, params)
|
||||
})
|
||||
}
|
||||
}
|
||||
let Uploaders = {}
|
||||
Uploaders.S3 = function (entries, onViewError) {
|
||||
entries.forEach(entry => {
|
||||
let xhr = new XMLHttpRequest()
|
||||
onViewError(() => xhr.abort())
|
||||
xhr.onload = () => xhr.status === 200 ? entry.progress(100) : entry.error()
|
||||
xhr.onerror = () => entry.error()
|
||||
xhr.upload.addEventListener("progress", (event) => {
|
||||
if (event.lengthComputable) {
|
||||
let percent = Math.round((event.loaded / event.total) * 100)
|
||||
if (percent < 100) { entry.progress(percent) }
|
||||
}
|
||||
})
|
||||
let url = entry.meta.url
|
||||
xhr.open("PUT", url, true)
|
||||
xhr.send(entry.file)
|
||||
})
|
||||
}
|
||||
let token = csrfToken.getAttribute("content")
|
||||
let url = websocketUrl.getAttribute("content")
|
||||
let liveUrl = (url === "") ? "/live" : new URL("/live", url).href;
|
||||
let liveSocket = new LiveSocket(liveUrl, Socket, {
|
||||
heartbeatIntervalMs: 10000,
|
||||
params: { _csrf_token: token }, hooks: Hooks, uploaders: Uploaders, dom: {
|
||||
// for alpinejs integration
|
||||
onBeforeElUpdated(from, to) {
|
||||
if (from._x_dataStack) {
|
||||
Alpine.clone(from, to);
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
liveSocket.connect()
|
||||
window.liveSocket = liveSocket
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
window.addEventListener(`phx:update-value`, (e) => {
|
||||
let el = document.getElementById(e.detail.id)
|
||||
el.value = e.detail.value
|
||||
if (e.detail.fire) {
|
||||
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))
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue