From 145a3599c1c5f7e7c9c1fccc34be311f88dd5e06 Mon Sep 17 00:00:00 2001 From: Thomas Hutterer <5372947+thutterer@users.noreply.github.com> Date: Tue, 13 Jul 2021 13:11:42 +0200 Subject: [PATCH 01/15] Turn off form autocompletion for new shared links (#1175) * Turn off form autocompletion for new shared links Many browser autofill input fields based on their name, but here it makes no sense to use the user's name (email) or even password for the shared link. * Update changelog --- CHANGELOG.md | 1 + lib/plausible_web/templates/site/new_shared_link.html.eex | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 297b56373..2eb5dd0f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ All notable changes to this project will be documented in this file. - UI fix for details button overlapping content on mobile plausible/analytics#1114 - UI fix for the main graph on mobile overlapping its tick items on both axis - UI fixes for text not showing properly in bars across multiple lines. This hides the totals on <768px and only shows the uniques and % to accommodate the goals text too. +- Turn off autocomplete for name and password inputs in the _New shared link_ form. ### Removed - Removes AppSignal monitoring package diff --git a/lib/plausible_web/templates/site/new_shared_link.html.eex b/lib/plausible_web/templates/site/new_shared_link.html.eex index 00ae88c94..533a183fa 100644 --- a/lib/plausible_web/templates/site/new_shared_link.html.eex +++ b/lib/plausible_web/templates/site/new_shared_link.html.eex @@ -5,14 +5,14 @@
<%= label f, :name, "Name", class: "block text-sm font-medium text-gray-700 dark:text-gray-100" %>
- <%= text_input f, :name, class: "shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md", required: "required" %> + <%= text_input f, :name, class: "shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md", required: "required", autocomplete: "off" %> <%= error_tag f, :name %>
<%= label f, :password, "Password (optional)", class: "block text-sm font-medium text-gray-700 dark:text-gray-100" %>
- <%= password_input f, :password, class: "shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md" %> + <%= password_input f, :password, class: "shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md", autocomplete: "off" %> <%= error_tag f, :password %>

Password protection is optional. Please make sure you save it in a secure place. Once the link is created, we cannot reveal the password. From 70c601053840b263b19195f1997c93f9853f168c Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Thu, 15 Jul 2021 10:28:09 +0300 Subject: [PATCH 02/15] Check lock status after subscription has been updated --- lib/plausible/billing/billing.ex | 2 +- test/plausible/billing/billing_test.exs | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/plausible/billing/billing.ex b/lib/plausible/billing/billing.ex index af6b927a8..d43832912 100644 --- a/lib/plausible/billing/billing.ex +++ b/lib/plausible/billing/billing.ex @@ -25,7 +25,7 @@ defmodule Plausible.Billing do subscription = Repo.get_by!(Subscription, paddle_subscription_id: params["subscription_id"]) changeset = Subscription.changeset(subscription, format_subscription(params)) - Repo.update(changeset) + Repo.update(changeset) |> check_lock_status end def subscription_cancelled(params) do diff --git a/test/plausible/billing/billing_test.exs b/test/plausible/billing/billing_test.exs index c0e082b3b..86d9e084b 100644 --- a/test/plausible/billing/billing_test.exs +++ b/test/plausible/billing/billing_test.exs @@ -310,6 +310,28 @@ defmodule Plausible.BillingTest do assert subscription.paddle_plan_id == "new-plan-id" assert subscription.next_bill_amount == "12.00" end + + test "unlocks sites if subscription is changed from past_due to active" do + user = insert(:user) + subscription = insert(:subscription, user: user, status: "past_due") + site = insert(:site, locked: true, members: [user]) + + Billing.subscription_updated(%{ + "alert_name" => "subscription_updated", + "subscription_id" => subscription.paddle_subscription_id, + "subscription_plan_id" => "new-plan-id", + "update_url" => "update_url.com", + "cancel_url" => "cancel_url.com", + "passthrough" => user.id, + "old_status" => "past_due", + "status" => "active", + "next_bill_date" => "2019-06-01", + "new_unit_price" => "12.00", + "currency" => "EUR" + }) + + refute Repo.reload!(site).locked + end end describe "subscription_cancelled" do From 0089add5944177bd2352510236a09157dc9d16bf Mon Sep 17 00:00:00 2001 From: Vignesh Joglekar Date: Fri, 16 Jul 2021 02:15:16 -0500 Subject: [PATCH 03/15] Transforms Bug Report Issue Template to new Github Issue Forms (#1193) * Swaps issue template to new issue form syntax * Indentation update * Indentation update? * More indentation * Intendation is hard * Finalized indentation? * Github indentation * Missing fields * Formatting changes * Checkbox changes --- .github/ISSUE_TEMPLATE/bug_report.md | 36 -------------- .github/ISSUE_TEMPLATE/bug_report.yaml | 67 ++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 36 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yaml diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 63be6723d..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve Plausible Analytics -title: '' -labels: '' -assignees: '' - ---- - -### Precheck - -Please note that this tracker is only for bugs. Do not use the issue tracker for help, support or feature requests. - -[Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact us](https://plausible.io/contact). - -Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new). - -Have an issue with your self-hosted install? You can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support). Thanks! - -## Prerequisites -- [ ] I have searched open and closed issues to make sure that the bug has not yet been reported. - -## Bug report -**Describe the bug** -A clear and concise description of what the bug is. - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots (If applicable)** -If applicable, add screenshots to help explain your problem. - -**Environment (If applicable):** - - OS: [e.g. macos] - - Browser [e.g. safari, firefox] - - Version [e.g. 78] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml new file mode 100644 index 000000000..20aa25101 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yaml @@ -0,0 +1,67 @@ +name: "πŸ› Bug Report" +description: Create a report to help us improve Plausible Analytics +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + + Please note that this tracker is only for bugs. Do not use the issue tracker for help, support or feature requests. + + [Our docs](https://plausible.io/docs) are a great place for most answers, but if you can’t find your answer there, you can [contact us](https://plausible.io/contact). + + Have a feature request? Please search the ideas [on our forum](https://github.com/plausible/analytics/discussions/categories/feature-requests) to make sure that the feature has not yet been requested. If you cannot find what you had in mind, please [submit your feature request here](https://github.com/plausible/analytics/discussions/new). + + Have an issue with your self-hosted install? You can ask in [our self-hosted forum](https://github.com/plausible/analytics/discussions/categories/self-hosted-support). + + **Thanks!** + - type: checkboxes + attributes: + label: Past Issues Searched + options: + - label: >- + I have searched open and closed issues to make sure that the bug has + not yet been reported + required: true + - type: checkboxes + attributes: + label: Issue is a Bug Report + options: + - label: >- + This is a bug report and not a feature request, nor asking for self-hosted support + required: true + - type: textarea + id: bug-description + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is + placeholder: Tell us what happened! + validations: + required: true + - type: textarea + id: bug-expectation + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen + placeholder: Tell us what you expected + validations: + required: true + - type: textarea + id: bug-screenshots + attributes: + label: Screenshots + description: 'If applicable, add screenshots to help explain your problem' + placeholder: Insert screenshots here + - type: textarea + attributes: + label: Environment + description: | + examples: + - **OS**: MacOS + - **Browser**: Firefox + - **Browser Version**: 88 + value: | + - OS: + - Browser: + - Browser Version: + render: markdown From 78e96a6d6754801b74b30a53b494e8b9898c913e Mon Sep 17 00:00:00 2001 From: Marko Saric <34340819+metmarkosaric@users.noreply.github.com> Date: Mon, 19 Jul 2021 11:15:57 +0200 Subject: [PATCH 04/15] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3063db09f..83bc423bf 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ We are dedicated to making web analytics more privacy-friendly. Our mission is t ### Why Plausible? -Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 3,000+ paying subscribers to deliver their website and business insights: +Here's what makes Plausible a great Google Analytics alternative and why we're trusted by 4,000+ paying subscribers to deliver their website and business insights: - **Clutter Free**: Plausible Analytics provides [simple web analytics](https://plausible.io/simple-web-analytics) and it cuts through the noise. No layers of menus, no need for custom reports. Get all the important insights on one single page. No training necessary. - **GDPR/CCPA/PECR compliant**: Measure traffic, not individuals. No personal data or IP addresses are ever stored in our database. We don't use cookies or any other persistent idenfitiers. [Read more about our data policy](https://plausible.io/data-policy) From fef5337a6465be076986d715504cb745dcec7ff2 Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Mon, 19 Jul 2021 15:03:15 +0300 Subject: [PATCH 05/15] Make sure only the current subcription is used in expiry notifications --- lib/workers/notify_annual_renewal.ex | 31 ++++++++++++++------- test/workers/notify_annual_renewal_test.exs | 20 +++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/lib/workers/notify_annual_renewal.ex b/lib/workers/notify_annual_renewal.ex index 7c89e23a1..d5a66fbe8 100644 --- a/lib/workers/notify_annual_renewal.ex +++ b/lib/workers/notify_annual_renewal.ex @@ -9,19 +9,30 @@ defmodule Plausible.Workers.NotifyAnnualRenewal do Sends a notification at most 7 days and at least 1 day before the renewal of an annual subscription """ def perform(_job) do + current_subscriptions = from( + s in Plausible.Billing.Subscription, + group_by: s.user_id, + select: %{ + user_id: s.user_id, + inserted_at: max(s.inserted_at) + } + ) + users = Repo.all( from u in Plausible.Auth.User, - join: s in Plausible.Billing.Subscription, - on: s.user_id == u.id, - left_join: sent in "sent_renewal_notifications", - on: s.user_id == sent.user_id, - where: s.paddle_plan_id in @yearly_plans, - where: - s.next_bill_date > fragment("now()::date") and - s.next_bill_date <= fragment("now()::date + INTERVAL '7 days'"), - where: is_nil(sent.id) or sent.timestamp < fragment("now() - INTERVAL '1 month'"), - preload: [subscription: s] + join: cs in subquery(current_subscriptions), + on: cs.user_id == u.id, + join: s in Plausible.Billing.Subscription, + on: s.inserted_at == cs.inserted_at, + left_join: sent in "sent_renewal_notifications", + on: s.user_id == sent.user_id, + where: s.paddle_plan_id in @yearly_plans, + where: + s.next_bill_date > fragment("now()::date") and + s.next_bill_date <= fragment("now()::date + INTERVAL '7 days'"), + where: is_nil(sent.id) or sent.timestamp < fragment("now() - INTERVAL '1 month'"), + preload: [subscription: s] ) for user <- users do diff --git a/test/workers/notify_annual_renewal_test.exs b/test/workers/notify_annual_renewal_test.exs index 3c0b0fedc..847ffec54 100644 --- a/test/workers/notify_annual_renewal_test.exs +++ b/test/workers/notify_annual_renewal_test.exs @@ -39,6 +39,26 @@ defmodule Plausible.Workers.NotifyAnnualRenewalTest do assert_no_emails_delivered() end + test "ignores user with old yearly subscription that's been superseded by a newer one", %{user: user} do + insert(:subscription, + inserted_at: Timex.shift(Timex.now(), days: -1), + user: user, + paddle_plan_id: @yearly_plan, + next_bill_date: Timex.shift(Timex.today(), days: 5) + ) + + insert(:subscription, + inserted_at: Timex.now(), + user: user, + paddle_plan_id: @yearly_plan, + next_bill_date: Timex.shift(Timex.today(), days: 30) + ) + + NotifyAnnualRenewal.perform(nil) + + assert_no_emails_delivered() + end + test "sends renewal notification to user whose subscription is due for renewal in 7 days", %{ user: user } do From 2d413129a72d433061a1076c0cfa14eda5041e03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niklas=20Hamb=C3=BCchen?= Date: Tue, 20 Jul 2021 08:43:27 +0200 Subject: [PATCH 06/15] Fix shell scripts. (#1179) There were various mistakes in the shell scripts, such as lack of quoting; they would break them immediately e.g. if `BIN_DIR` contained a space. Pointed out by `shellcheck`. --- .gitlab/build-scripts/docker-entrypoint.sh | 4 ++-- .gitlab/build-scripts/docker.gitlab.sh | 8 ++++---- rel/overlays/createdb.sh | 4 ++-- rel/overlays/init-admin.sh | 4 ++-- rel/overlays/migrate.sh | 4 ++-- rel/overlays/rollback.sh | 4 ++-- rel/overlays/seed.sh | 4 ++-- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.gitlab/build-scripts/docker-entrypoint.sh b/.gitlab/build-scripts/docker-entrypoint.sh index 0ab3e8ff2..b693040f9 100755 --- a/.gitlab/build-scripts/docker-entrypoint.sh +++ b/.gitlab/build-scripts/docker-entrypoint.sh @@ -1,10 +1,10 @@ #!/bin/sh set -e -if [[ "$1" = 'run' ]]; then +if [ "$1" = 'run' ]; then exec /app/bin/plausible start -elif [[ "$1" = 'db' ]]; then +elif [ "$1" = 'db' ]; then exec /app/"$2".sh else exec "$@" diff --git a/.gitlab/build-scripts/docker.gitlab.sh b/.gitlab/build-scripts/docker.gitlab.sh index 4cc663ca0..51395c8b1 100644 --- a/.gitlab/build-scripts/docker.gitlab.sh +++ b/.gitlab/build-scripts/docker.gitlab.sh @@ -23,10 +23,10 @@ function docker_build_image() { /kaniko/executor \ --cache=true \ - --context ${CI_PROJECT_DIR} \ - --dockerfile ${CI_PROJECT_DIR}/Dockerfile \ - --destination ${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-${CI_COMMIT_SHORT_SHA} \ - --destination ${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-latest \ + --context "${CI_PROJECT_DIR}" \ + --dockerfile "${CI_PROJECT_DIR}"/Dockerfile \ + --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-${CI_COMMIT_SHORT_SHA}" \ + --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_SLUG}-latest" \ \ "$@" diff --git a/rel/overlays/createdb.sh b/rel/overlays/createdb.sh index 21a221f0d..172c9bb71 100755 --- a/rel/overlays/createdb.sh +++ b/rel/overlays/createdb.sh @@ -2,6 +2,6 @@ # Creates the database if needed -BIN_DIR=`dirname "$0"` +BIN_DIR=$(dirname "$0") -${BIN_DIR}/bin/plausible eval Plausible.Release.createdb \ No newline at end of file +"${BIN_DIR}"/bin/plausible eval Plausible.Release.createdb diff --git a/rel/overlays/init-admin.sh b/rel/overlays/init-admin.sh index 5d64ec6d4..474fc3f03 100755 --- a/rel/overlays/init-admin.sh +++ b/rel/overlays/init-admin.sh @@ -1,6 +1,6 @@ #!/bin/sh # Create an admin user -BIN_DIR=`dirname "$0"` +BIN_DIR=$(dirname "$0") -${BIN_DIR}/bin/plausible eval Plausible.Release.init_admin +"${BIN_DIR}"/bin/plausible eval Plausible.Release.init_admin diff --git a/rel/overlays/migrate.sh b/rel/overlays/migrate.sh index d77c1ece0..15a0e0d40 100755 --- a/rel/overlays/migrate.sh +++ b/rel/overlays/migrate.sh @@ -1,6 +1,6 @@ #!/bin/sh # starts the db migration -BIN_DIR=`dirname "$0"` +BIN_DIR=$(dirname "$0") -${BIN_DIR}/bin/plausible eval Plausible.Release.migrate \ No newline at end of file +"${BIN_DIR}"/bin/plausible eval Plausible.Release.migrate diff --git a/rel/overlays/rollback.sh b/rel/overlays/rollback.sh index db69eba64..fc39fed5b 100755 --- a/rel/overlays/rollback.sh +++ b/rel/overlays/rollback.sh @@ -1,5 +1,5 @@ #!/bin/sh -BIN_DIR=`dirname "$0"` +BIN_DIR=$(dirname "$0") -${BIN_DIR}/bin/plausible eval Plausible.Release.rollback \ No newline at end of file +"${BIN_DIR}"/bin/plausible eval Plausible.Release.rollback diff --git a/rel/overlays/seed.sh b/rel/overlays/seed.sh index 1791f86d7..919c09e62 100755 --- a/rel/overlays/seed.sh +++ b/rel/overlays/seed.sh @@ -1,5 +1,5 @@ #!/bin/sh -BIN_DIR=`dirname "$0"` +BIN_DIR=$(dirname "$0") -${BIN_DIR}/bin/plausible eval Plausible.Release.seed \ No newline at end of file +"${BIN_DIR}"/bin/plausible eval Plausible.Release.seed From 0de89bad82ab04ef1daa506c20bc7e7c41ca01d9 Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Wed, 21 Jul 2021 16:50:26 +0300 Subject: [PATCH 07/15] Add filter groups (#1167) * Add filter groups * New flow for filters * Visual consistency * Mobile improvements to dropdown * Do not let filters wrap on a new line * Fix country filter * Add mix format to pre-commit configuration * Make eslint happy * Fix formatting * Use transition from headlessUI --- .pre-commit-config.yaml | 5 + assets/.eslintrc.json | 7 +- assets/css/app.css | 13 + .../js/dashboard/components/search-select.js | 14 +- assets/js/dashboard/datepicker-arrows.js | 91 ++++ assets/js/dashboard/datepicker.js | 217 +++------ assets/js/dashboard/filters.js | 445 ++++++++++-------- assets/js/dashboard/historical.js | 24 +- assets/js/dashboard/query.js | 11 +- assets/js/dashboard/realtime.js | 20 +- assets/js/dashboard/router.js | 2 +- assets/js/dashboard/site-switcher.js | 10 +- assets/js/dashboard/stats/current-visitors.js | 8 +- assets/js/dashboard/stats/modals/filter.js | 353 ++++++++------ assets/js/dashboard/stats/modals/sources.js | 1 - assets/js/dashboard/stats/visitor-graph.js | 2 +- assets/js/dashboard/url.js | 7 + assets/js/transition.js | 107 ----- assets/package-lock.json | 54 +++ assets/package.json | 3 + .../templates/layout/_header.html.eex | 2 +- lib/workers/notify_annual_renewal.ex | 41 +- test/workers/notify_annual_renewal_test.exs | 4 +- 23 files changed, 751 insertions(+), 690 deletions(-) create mode 100644 assets/js/dashboard/datepicker-arrows.js create mode 100644 assets/js/dashboard/url.js delete mode 100644 assets/js/transition.js diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 47a5baffc..d894db377 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,3 +26,8 @@ repos: - eslint-plugin-jsx-a11y@6.4.1 - eslint-plugin-react@7.21.5 - eslint-plugin-react-hooks@4.2.0 + + - repo: https://gitlab.com/jvenom/elixir-pre-commit-hooks + rev: v1.0.0 + hooks: + - id: mix-format diff --git a/assets/.eslintrc.json b/assets/.eslintrc.json index 7ee18d54e..e25d18b46 100644 --- a/assets/.eslintrc.json +++ b/assets/.eslintrc.json @@ -5,7 +5,7 @@ "extends": ["airbnb", "prettier"], "plugins": ["prettier"], "rules": { - "max-len": [2, {"code": 100}], + "max-len": [0, {"code": 120}], "prettier/prettier": [2], "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "react/destructuring-assignment": [0], @@ -13,6 +13,9 @@ "max-classes-per-file": [0], "react/jsx-one-expression-per-line": [0], "react/self-closing-comp": [0], - "no-unused-expressions": [1, { "allowShortCircuit": true }] + "no-unused-expressions": [1, { "allowShortCircuit": true }], + "no-unused-vars": [2, { "varsIgnorePattern": "^_", "argsIgnorePattern": "^_" }], + "jsx-a11y/click-events-have-key-events": [0], + "jsx-a11y/no-static-element-interactions": [0] } } diff --git a/assets/css/app.css b/assets/css/app.css index e3e0d7660..e1af8c8d8 100644 --- a/assets/css/app.css +++ b/assets/css/app.css @@ -315,3 +315,16 @@ iframe[hidden] { .pagination-link[disabled] { @apply cursor-default bg-gray-100 dark:bg-gray-300 pointer-events-none; } + +.flatpickr-calendar.static.open { + top: 12px; +} + +@media (max-width: 768px) { + .flatpickr-wrapper { + position: absolute!important; + right: 0!important; + left: 0!important; + } +} + diff --git a/assets/js/dashboard/components/search-select.js b/assets/js/dashboard/components/search-select.js index 24ec5e2b3..766140af8 100644 --- a/assets/js/dashboard/components/search-select.js +++ b/assets/js/dashboard/components/search-select.js @@ -2,6 +2,7 @@ import React, {useState, useCallback} from 'react' import {useCombobox} from 'downshift' import classNames from 'classnames' import debounce from 'debounce-promise' +import { ChevronDownIcon } from '@heroicons/react/solid' function selectInputText(e) { e.target.select() @@ -27,7 +28,6 @@ function Spinner() { export default function SearchSelect(props) { const [items, setItems] = useState([]) const [loading, setLoading] = useState(false) - const [initialLoadComplete, setInitialLoadComplete] = useState(false) function fetchOptions({inputValue, isOpen}) { setLoading(isOpen) @@ -60,11 +60,9 @@ export default function SearchSelect(props) { props.onInput(changes.inputValue) }, initialSelectedItem: props.initialSelectedItem, - onIsOpenChange: ({inputValue}) => { - if (!initialLoadComplete) { - fetchOptions({inputValue: inputValue, isOpen: true}).then(() => { - setInitialLoadComplete(true) - }) + onIsOpenChange: ({isOpen, inputValue}) => { + if (isOpen) { + fetchOptions({inputValue, isOpen}) } } }) @@ -79,11 +77,11 @@ export default function SearchSelect(props) { } return ( -

+
- { !loading && } + { !loading && } { loading && }
diff --git a/assets/js/dashboard/datepicker-arrows.js b/assets/js/dashboard/datepicker-arrows.js new file mode 100644 index 000000000..8d6ec9e98 --- /dev/null +++ b/assets/js/dashboard/datepicker-arrows.js @@ -0,0 +1,91 @@ +import React from "react"; +import { + shiftDays, + shiftMonths, + formatISO, + nowForSite, + parseUTCDate, + isBefore, + isAfter, +} from "./date"; +import { QueryButton } from "./query"; + +function renderArrow(query, site, period, prevDate, nextDate) { + const insertionDate = parseUTCDate(site.insertedAt); + const disabledLeft = isBefore( + parseUTCDate(prevDate), + insertionDate, + period + ); + const disabledRight = isAfter( + parseUTCDate(nextDate), + nowForSite(site), + period + ); + + const leftClasses = `flex items-center px-2 border-r border-gray-300 rounded-l + dark:border-gray-500 dark:text-gray-100 ${ + disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900" + }`; + const rightClasses = `flex items-center px-2 rounded-r dark:text-gray-100 ${ + disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-100 dark:hover:bg-gray-900" + }`; + return ( +
+ + + + + + + + + + +
+ ); +} + +export default function DatePickerArrows({site, query}) { + if (query.period === "month") { + const prevDate = formatISO(shiftMonths(query.date, -1)); + const nextDate = formatISO(shiftMonths(query.date, 1)); + + return renderArrow(query, site, "month", prevDate, nextDate); + } if (query.period === "day") { + const prevDate = formatISO(shiftDays(query.date, -1)); + const nextDate = formatISO(shiftDays(query.date, 1)); + + return renderArrow(query, site, "day", prevDate, nextDate); + } + + return null +} diff --git a/assets/js/dashboard/datepicker.js b/assets/js/dashboard/datepicker.js index c5b4a897f..f047d225a 100644 --- a/assets/js/dashboard/datepicker.js +++ b/assets/js/dashboard/datepicker.js @@ -1,6 +1,8 @@ -import React from "react"; +import React, { Fragment } from "react"; import { withRouter } from "react-router-dom"; import Flatpickr from "react-flatpickr"; +import classNames from 'classnames' +import { ChevronDownIcon } from '@heroicons/react/solid' import { shiftDays, shiftMonths, @@ -17,7 +19,7 @@ import { isBefore, isAfter, } from "./date"; -import Transition from "../transition"; +import { Transition } from '@headlessui/react' import { navigateToQuery, QueryLink, QueryButton } from "./query"; class DatePicker extends React.Component { @@ -26,7 +28,7 @@ class DatePicker extends React.Component { this.handleKeydown = this.handleKeydown.bind(this); this.handleClick = this.handleClick.bind(this); this.openCalendar = this.openCalendar.bind(this); - this.open = this.open.bind(this); + this.toggle = this.toggle.bind(this); this.state = { mode: "menu", open: false }; } @@ -148,137 +150,9 @@ class DatePicker extends React.Component { return 'Realtime' } - renderArrow(period, prevDate, nextDate) { - const insertionDate = parseUTCDate(this.props.site.insertedAt); - const disabledLeft = isBefore( - parseUTCDate(prevDate), - insertionDate, - period - ); - const disabledRight = isAfter( - parseUTCDate(nextDate), - nowForSite(this.props.site), - period - ); - - const leftClasses = `flex items-center px-2 border-r border-gray-300 rounded-l - dark:border-gray-500 dark:text-gray-100 ${ - disabledLeft ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-200 dark:hover:bg-gray-900" - }`; - const rightClasses = `flex items-center px-2 rounded-r dark:text-gray-100 ${ - disabledRight ? "bg-gray-300 dark:bg-gray-950" : "hover:bg-gray-200 dark:hover:bg-gray-900" - }`; - return ( -
- - - - - - - - - - -
- ); - } - - renderArrows() { - const { query } = this.props; - - if (query.period === "month") { - const prevDate = formatISO(shiftMonths(query.date, -1)); - const nextDate = formatISO(shiftMonths(query.date, 1)); - - return this.renderArrow("month", prevDate, nextDate); - } if (query.period === "day") { - const prevDate = formatISO(shiftDays(query.date, -1)); - const nextDate = formatISO(shiftDays(query.date, 1)); - - return this.renderArrow("day", prevDate, nextDate); - } - } - - open() { - this.setState({ mode: "menu", open: true }); - } - - renderDropDown() { - return ( -
(this.dropDownNode = node)} - > - - - - {this.renderDropDownContent()} - -
- ); + toggle() { + const newMode = this.state.mode === 'calendar' && !this.state.open ? 'menu' : this.state.mode + this.setState({ mode: newMode, open: !this.state.open }); } close() { @@ -314,7 +188,7 @@ class DatePicker extends React.Component { to={{from: false, to: false, period, ...opts}} onClick={this.close.bind(this)} query={this.props.query} - className={`${boldClass } px-4 py-2 md:text-sm leading-tight hover:bg-gray-200 + className={`${boldClass } px-4 py-2 text-sm leading-tight hover:bg-gray-100 hover:text-gray-900 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 flex items-center justify-between`} > {text} @@ -328,11 +202,10 @@ class DatePicker extends React.Component { return (
@@ -359,7 +232,7 @@ class DatePicker extends React.Component { this.setState({mode: 'calendar'}, this.openCalendar)} onKeyPress={() => this.setState({mode: 'calendar'}, this.openCalendar)} - className="px-4 py-2 md:text-sm leading-tight hover:bg-gray-100 + className="px-4 py-2 text-sm leading-tight hover:bg-gray-100 dark:hover:bg-gray-900 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer flex items-center justify-between" tabIndex="0" @@ -379,19 +252,21 @@ class DatePicker extends React.Component { const insertionDate = new Date(this.props.site.insertedAt); const dayBeforeCreation = insertionDate - 86400000; return ( - this.calendar = calendar} - className="invisible" - onChange={this.setCustomDate.bind(this)} - /> +
+ this.calendar = calendar} + className="invisible" + onChange={this.setCustomDate.bind(this)} + /> +
) } } @@ -432,9 +307,41 @@ class DatePicker extends React.Component { render() { return ( -
- { this.renderArrows() } - { this.renderDropDown() } +
(this.dropDownNode = node)} + > + + + + {this.renderDropDownContent()} +
); } diff --git a/assets/js/dashboard/filters.js b/assets/js/dashboard/filters.js index 6189f7dd2..769040435 100644 --- a/assets/js/dashboard/filters.js +++ b/assets/js/dashboard/filters.js @@ -1,29 +1,173 @@ -import React from 'react'; -import { withRouter, Link } from 'react-router-dom' -import { countFilters, formattedFilters, navigateToQuery } from './query' +import React, { Fragment, useState } from 'react'; +import { Link, withRouter } from 'react-router-dom' +import { AdjustmentsIcon, PlusIcon, XIcon, PencilIcon } from '@heroicons/react/solid' +import classNames from 'classnames' import Datamap from 'datamaps' -import Transition from "../transition.js"; +import { Menu, Transition } from '@headlessui/react' + +import { appliedFilters, navigateToQuery, formattedFilters } from './query' +import { FILTER_GROUPS, formatFilterGroup, filterGroupForFilter } from './stats/modals/filter' + +function removeFilter(key, history, query) { + const newOpts = { + [key]: false + } + if (key === 'goal') { newOpts.props = false } + navigateToQuery( + history, + query, + newOpts + ) +} + +function clearAllFilters(history, query) { + const newOpts = Object.keys(query.filters).reduce((acc, red) => ({ ...acc, [red]: false }), {}); + navigateToQuery( + history, + query, + newOpts + ); +} + +function filterText(key, value, query) { + if (key === "goal") { + return Completed goal {value} + } + if (key === "props") { + const [metaKey, metaValue] = Object.entries(value)[0] + const eventName = query.filters.goal ? query.filters.goal : 'event' + return {eventName}.{metaKey} is {metaValue} + } + if (key === "source") { + return Source: {value} + } + if (key === "utm_medium") { + return UTM medium: {value} + } + if (key === "utm_source") { + return UTM source: {value} + } + if (key === "utm_campaign") { + return UTM campaign: {value} + } + if (key === "referrer") { + return Referrer: {value} + } + if (key === "screen") { + return Screen size: {value} + } + if (key === "browser") { + return Browser: {value} + } + if (key === "browser_version") { + const browserName = query.filters.browser ? query.filters.browser : 'Browser' + return {browserName}.Version: {value} + } + if (key === "os") { + return Operating System: {value} + } + if (key === "os_version") { + const osName = query.filters.os ? query.filters.os : 'OS' + return {osName}.Version: {value} + } + if (key === "country") { + const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; + const selectedCountry = allCountries.find((c) => c.id === value) || {properties: {name: value}}; + return Country: {selectedCountry.properties.name} + } + if (key === "page") { + return Page: {value} + } + if (key === "entry_page") { + return Entry Page: {value} + } + if (key === "exit_page") { + return Exit Page: {value} + } + + throw new Error(`Unknown filter: ${key}`) +} + +function renderDropdownFilter(site, history, [key, value], query) { + if (key === 'props') { + return ( + +
+ {filterText(key, value, query)} + removeFilter(key, history, query)}>βœ• +
+
+ ) + } + + return ( + +
+ + {filterText(key, value, query)} + + + removeFilter(key, history, query)}> + + +
+
+ ) +} + +function filterDropdownOption(site, option) { + return ( + + {({ active }) => ( + + {formatFilterGroup(option)} + + )} + + ) +} + +function DropdownContent({history, site, query, wrapped}) { + const [addingFilter, setAddingFilter] = useState(false); + + if (wrapped === 0 || addingFilter) { + return Object.keys(FILTER_GROUPS).map((option) => filterDropdownOption(site, option)) + } + + return ( + <> +
setAddingFilter(true)}> + + Add filter +
+ {appliedFilters(query).map((filter) => renderDropdownFilter(site, history, filter, query))} +
clearAllFilters(history, query)}> + Clear All Filters +
+ + ) +} class Filters extends React.Component { constructor(props) { super(props); this.state = { - dropdownOpen: false, wrapped: 1, // 0=unwrapped, 1=waiting to check, 2=wrapped - viewport: 1080 + viewport: 1080, }; - this.appliedFilters = Object.keys(props.query.filters) - .map((key) => [key, props.query.filters[key]]) - .filter(([key, value]) => !!value); - this.renderDropDown = this.renderDropDown.bind(this); - this.renderDropDownContent = this.renderDropDownContent.bind(this); - this.handleClick = this.handleClick.bind(this); this.handleResize = this.handleResize.bind(this); - this.rewrapFilters = this.rewrapFilters.bind(this); - this.renderFilterList = this.renderFilterList.bind(this); this.handleKeyup = this.handleKeyup.bind(this) } @@ -32,19 +176,16 @@ class Filters extends React.Component { window.addEventListener('resize', this.handleResize, false); document.addEventListener('keyup', this.handleKeyup); - this.rewrapFilters(); this.handleResize(); + this.rewrapFilters(); } componentDidUpdate(prevProps, prevState) { const { query } = this.props; const { viewport, wrapped } = this.state; - this.appliedFilters = Object.keys(query.filters) - .map((key) => [key, query.filters[key]]) - .filter(([key, value]) => !!value) - if (JSON.stringify(query) !== JSON.stringify(prevProps.query) || viewport !== prevState.viewport) { + // eslint-disable-next-line react/no-did-update-set-state this.setState({ wrapped: 1 }); } @@ -60,40 +201,42 @@ class Filters extends React.Component { } handleKeyup(e) { - const { query, history } = this.props + const {query, history} = this.props if (e.ctrlKey || e.metaKey || e.altKey) return if (e.key === 'Escape') { - this.clearAllFilters(history, query) + clearAllFilters(history, query) } } handleResize() { - this.setState({ viewport: window.innerWidth || 639 }); + this.setState({ viewport: window.innerWidth || 639}); } - handleClick(e) { - if (this.dropDownNode && this.dropDownNode.contains(e.target)) return; - - this.setState({ dropdownOpen: false }); - }; - // Checks if the filter container is wrapping items rewrapFilters() { - let currItem, prevItem, items = document.getElementById('filters'); - const { wrapped } = this.state; + const items = document.getElementById('filters'); + const { wrapped, viewport } = this.state; + + // Always wrap on mobile + if (appliedFilters(this.props.query).length > 0 && viewport <= 768) { + this.setState({ wrapped: 2 }) + return; + } this.setState({ wrapped: 0 }); // Don't rewrap if we're already properly wrapped, there are no DOM children, or there is only filter - if (wrapped !== 1 || !items || this.appliedFilters.length === 1) { + if (wrapped !== 1 || !items || appliedFilters(this.props.query).length === 1) { return; }; + let prevItem = null; + // For every filter DOM Node, check if its y value is higher than the previous (this indicates a wrap) [...(items.childNodes)].forEach(item => { - currItem = item.getBoundingClientRect(); + const currItem = item.getBoundingClientRect(); if (prevItem && prevItem.top < currItem.top) { this.setState({ wrapped: 2 }); } @@ -101,206 +244,106 @@ class Filters extends React.Component { }); }; - filterText(key, value, query) { - const negated = value[0] == '!' && ['page', 'entry_page', 'exit_page'].includes(key) - value = negated ? value.slice(1) : value - - if (key === "goal") { - return Completed goal {value} - } - if (key === "props") { - const [metaKey, metaValue] = Object.entries(value)[0] - const eventName = query.filters["goal"] ? query.filters["goal"] : 'event' - return {eventName}.{metaKey} is {metaValue} - } - if (key === "source") { - return Source is {value} - } - if (key === "utm_medium") { - return UTM medium is {value} - } - if (key === "utm_source") { - return UTM source is {value} - } - if (key === "utm_campaign") { - return UTM campaign is {value} - } - if (key === "referrer") { - return Referrer URL is {value} - } - if (key === "screen") { - return Screen size is {value} - } - if (key === "browser") { - return Browser is {value} - } - if (key === "browser_version") { - const browserName = query.filters["browser"] ? query.filters["browser"] : 'Browser' - return {browserName} Version is {value} - } - if (key === "os") { - return Operating System is {value} - } - if (key === "os_version") { - const osName = query.filters["os"] ? query.filters["os"] : 'OS' - return {osName} Version is {value} - } - if (key === "country") { - const allCountries = Datamap.prototype.worldTopo.objects.world.geometries; - const selectedCountry = allCountries.find((c) => c.id === value) || { properties: { name: value } }; - return Country is {selectedCountry.properties.name} - } - if (key === "page") { - return Page is{negated ? ' not' : ''} {value} - } - if (key === "entry_page") { - return Entry Page is{negated ? ' not' : ''} {value} - } - if (key === "exit_page") { - return Exit Page is{negated ? ' not' : ''} {value} - } - } - - removeFilter(key, history, query) { - const newOpts = { - [key]: false - } - if (key === 'goal') { newOpts.props = false } - navigateToQuery( - history, - query, - newOpts - ) - } - - renderDropdownFilter(history, [key, value], query) { - if ('props' == key) { - return ( -
- {this.filterText(key, value, query)} - this.removeFilter(key, history, query)}>βœ• -
- ) - } - - return ( -
- - {this.filterText(key, value, query)} - - - this.removeFilter(key, history, query)}>βœ• -
- ) - } - renderListFilter(history, [key, value], query) { return ( - {'props' == key ? ( + {key === 'props' ? ( - {this.filterText(key, value, query)} + {filterText(key, value, query)} ) : ( <> - - {this.filterText(key, value, query)} + + {filterText(key, value, query)} - - - )} - this.removeFilter(key, history, query)}> - + removeFilter(key, history, query)}> + ) } - clearAllFilters(history, query) { - const newOpts = Object.keys(query.filters).reduce((acc, red) => ({ ...acc, [red]: false }), {}); - navigateToQuery( - history, - query, - newOpts - ); - } - - renderDropDownContent() { - const { viewport } = this.state; - const { history, query, site } = this.props; + renderDropdownButton() { + if (this.state.wrapped === 2) { + return ( + <> +