Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Latency-friendly LV modal implementation and Goals form refactor (#3649)

Adrian Gruntkowskieaa702023090
diff --git a/assets/js/app.js b/assets/js/app.js
index 3e344c2aa9..eaad0400bf 100644
--- a/assets/js/app.js
+++ b/assets/js/app.js
@@ -10,6 +10,16 @@ Alpine.data('dropdown', dropdown)
Alpine.data('comboBox', comboBox)
Alpine.start()
+if (document.querySelectorAll('[data-modal]').length > 0) {
+ window.addEventListener(`phx:close-modal`, (e) => {
+ document
+ .getElementById(e.detail.id)
+ .dispatchEvent(
+ new CustomEvent('close-modal', { bubbles: true, detail: e.detail.id })
+ )
+ })
+}
+
const triggers = document.querySelectorAll('[data-dropdown-trigger]')
for (const trigger of triggers) {
diff --git a/assets/js/liveview/combo-box.js b/assets/js/liveview/combo-box.js
index 59006b7676..7849e6db6d 100644
--- a/assets/js/liveview/combo-box.js
+++ b/assets/js/liveview/combo-box.js
@@ -5,6 +5,7 @@ export default (id) => ({
isOpen: false,
id: id,
focus: null,
+ selectionInProgress: false,
setFocus(f) {
this.focus = f;
},
@@ -13,6 +14,9 @@ export default (id) => ({
this.setFocus(this.leastFocusableIndex())
}
},
+ trackSubmitValueChange() {
+ this.selectionInProgress = false;
+ },
open() {
this.initFocus()
this.isOpen = true
diff --git a/extra/lib/plausible_web/live/funnel_settings/form.ex b/extra/lib/plausible_web/live/funnel_settings/form.ex
index d2b53ebf5b..e3f5248a5e 100644
--- a/extra/lib/plausible_web/live/funnel_settings/form.ex
+++ b/extra/lib/plausible_web/live/funnel_settings/form.ex
@@ -84,6 +84,11 @@ defmodule PlausibleWeb.Live.FunnelSettings.Form do
submit_name={"funnel[steps][#{step_idx}][goal_id]"}
module={PlausibleWeb.Live.Components.ComboBox}
suggest_fun={&PlausibleWeb.Live.Components.ComboBox.StaticSearch.suggest/2}
+ on_selection_made={
+ fn value, by_id ->
+ send(self(), {:selection_made, %{submit_value: value, by: by_id}})
+ end
+ }
id={"step-#{step_idx}"}
options={reject_already_selected("step-#{step_idx}", @goals, @selections_made)}
/>
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index 4a207c1c43..8a72d0f28e 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -250,6 +250,7 @@ defmodule PlausibleWeb.Components.Generic do
end
attr :class, :any, default: ""
+ attr :rest, :global
def spinner(assigns) do
~H"""
@@ -258,6 +259,7 @@ defmodule PlausibleWeb.Components.Generic do
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
+ {@rest}
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4">
</circle>
diff --git a/lib/plausible_web/live/components/combo_box.ex b/lib/plausible_web/live/components/combo_box.ex
index e1e238baca..4af94347fb 100644
--- a/lib/plausible_web/live/components/combo_box.ex
+++ b/lib/plausible_web/live/components/combo_box.ex
@@ -36,7 +36,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
ComboBox own test suite, so there is no need for additional
verification.
"""
- use Phoenix.LiveComponent
+ use Phoenix.LiveComponent, global_prefixes: ~w(x-)
alias Phoenix.LiveView.JS
@default_suggestions_limit 15
@@ -69,6 +69,7 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
attr(:creatable, :boolean, default: false)
attr(:errors, :list, default: [])
attr(:async, :boolean, default: Mix.env() != :test)
+ attr(:on_selection_made, :any)
def render(assigns) do
assigns =
@@ -103,15 +104,22 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
phx-target={@myself}
phx-debounce={200}
value={@display_value}
- class="border-none py-1 px-1 p-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm"
+ class="[&.phx-change-loading+svg.spinner]:block border-none py-1 px-1 p-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm"
style="background-color: inherit;"
required={@required}
/>
+ <PlausibleWeb.Components.Generic.spinner class="spinner hidden absolute inset-y-3 right-8" />
+ <PlausibleWeb.Components.Generic.spinner
+ x-show="selectionInProgress"
+ class="spinner absolute inset-y-3 right-8"
+ />
+
<.dropdown_anchor id={@id} />
<input
type="hidden"
+ x-init={"trackSubmitValueChange('#{@submit_value}')"}
name={@submit_name}
value={@submit_value}
phx-target={@myself}
@@ -235,7 +243,9 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
>
<a
x-ref={"dropdown-#{@ref}-option-#{@idx}"}
+ x-on:click="selectionInProgress = true"
phx-click={select_option(@ref, @submit_value, @display_value)}
+ phx-value-submit-value={@submit_value}
phx-value-display-value={@display_value}
phx-target={@target}
class="block truncate py-2 px-3"
@@ -306,14 +316,9 @@ defmodule PlausibleWeb.Live.Components.ComboBox do
|> assign(:display_value, display_value)
|> assign(:submit_value, submit_value)
- send(
- self(),
- {:selection_made,
- %{
- by: id,
- submit_value: submit_value
- }}
- )
+ if socket.assigns[:on_selection_made] do
+ socket.assigns.on_selection_made.(submit_value, id)
+ end
socket
end
diff --git a/lib/plausible_web/live/components/modal.ex b/lib/plausible_web/live/components/modal.ex
new file mode 100644
index 0000000000..72e194f0bc
--- /dev/null
+++ b/lib/plausible_web/live/components/modal.ex
@@ -0,0 +1,227 @@
+defmodule PlausibleWeb.Live.Components.Modal do
+ @moduledoc """
+ LiveView implementation of modal component.
+
+ This component is a general purpose modal implementation for LiveView
+ with emphasis on keeping nested components largely agnostic of the fact
+ that they are placed in a modal and maintaining good user experience
+ on connections with high latency.
+
+ ## Usage
+
+ An example use case for a modal is embedding a form inside
+ existing live view which allows adding new entries of some kind:
+
+ ```
+ <.live_component module={Modal} id="some-form-modal">
+ <.live_component
+ module={SomeForm}
+ id="some-form"
+ on_save_form={
+ fn entry, socket ->
+ send(self(), {:entry_added, entry})
+ Modal.close(socket, "some-form-modal")
+ end
+ }
+ />
+ </.live_component>
+ ```
+
+ Then somewhere in the same live view the modal is rendered in:
+
+ ```
+ <.button x-data x-on:click={Modal.JS.open("goals-form-modal")}>
+ + Add Entry
+ </.button>
+ ```
+
+ ## Explanation
+
+ The component embedded inside the modal is always rendered when
+ the live view is mounted but is kept hidden until `Modal.JS.open`
+ is called on it. On subsequent openings within the same session
+ the contents of the modal are completely remounted. This assures
+ that any stateful components inside the modal are reset to their
+ initial state.
+
+ `Modal` exposes two functions for managing window state:
+
+ * `Modal.JS.open/1` - to open the modal from the frontend. It's
+ important to make sure the element triggering that call is
+ wrapped in an Alpine UI component - or is an Alpine component
+ itself - adding `x-data` attribute without any value is enough
+ to ensure that.
+ * `Modal.close/2` - to close the modal from the backend; usually
+ done inside wrapped component's `handle_event/2`. The example
+ qouted above shows one way to implement this, under that assumption
+ that the component exposes a callback, like this:
+
+ ```
+ defmodule SomeForm do
+ use Phoenix.LiveComponent
+
+ def update(assigns, socket) do
+ # ...
+
+ {:ok, assign(socket, :on_save_form, assigns.on_save_form)}
+ end
+
+ #...
+
+ def handle_event("save-form", %{"form" => form}, socket) do
+ case save_entry(form) do
+ {:ok, entry} ->
+ {:noreply, socket.assigns.on_save_form(entry, socket)}
+
+ # error case handling ...
+ end
+ end
+ end
+ ```
+
+ Using callback approach has an added benefit of making the
+ component more flexible.
+
+ """
+
+ use Phoenix.LiveComponent, global_prefixes: ~w(x-)
+
+ alias Phoenix.LiveView
+ alias Phoenix.LiveView.JS, as: LiveViewJS
+
+ defmodule JS do
+ @moduledoc false
+
+ @spec open(String.t()) :: String.t()
+ def open(id) do
+ "$dispatch('open-modal', '#{id}')"
+ end
+ end
+
+ @spec close(Phoenix.LiveView.Socket.t(), String.t()) :: Phoenix.LiveView.Socket.t()
+ def close(socket, id) do
+ Phoenix.LiveView.push_event(socket, "close-modal", %{id: id})
+ end
+
+ @impl true
+ def update(assigns, socket) do
+ socket =
+ assign(socket,
+ id: assigns.id,
+ inner_block: assigns.inner_block,
+ load_content?: true
+ )
+
+ {:ok, socket}
+ end
+
+ attr :id, :any, required: true
+ attr :class, :string, default: ""
+ slot :inner_block, required: true
+
+ def render(assigns) do
+ class = [
+ "md:w-1/2 w-full max-w-md mx-auto bg-white dark:bg-gray-800 shadow-xl rounded-lg px-8 pt-6 pb-8 top-24",
+ assigns.class
+ ]
+
+ assigns =
+ assign(assigns,
+ class: ["modal-dialog relative opacity-0 translate-y-4 sm:translate-y-0" | class],
+ dialog_id: assigns.id <> "-dialog"
+ )
+
+ ~H"""
+ <div
+ id={@id}
+ class="relative z-50 [&[data-phx-ref]_div.modal-dialog]:hidden [&[data-phx-ref]_div.modal-loading]:block"
+ data-modal
+ x-cloak
+ x-data="{
+ firstLoadDone: false,
+ modalOpen: false,
+ openModal() {
+ document.body.style['overflow-y'] = 'hidden';
+
+ if (this.firstLoadDone) {
+ liveSocket.execJS($el, $el.dataset.onclose);
+ liveSocket.execJS($el, $el.dataset.onopen);
+ } else {
+ this.firstLoadDone = true;
+ }
+
+ this.modalOpen = true;
+ },
+ closeModal() {
+ this.modalOpen = false;
+
+ setTimeout(function() {
+ document.body.style['overflow-y'] = 'auto';
+ }, 200);
+ }
+ }"
+ x-on:open-modal.window={"if ($event.detail === '#{@id}') openModal()"}
+ x-on:close-modal.window={"if ($event.detail === '#{@id}') closeModal()"}
+ data-onopen={LiveView.JS.push("open", target: @myself)}
+ data-onclose={LiveView.JS.push("close", target: @myself)}
+ x-on:keydown.escape.window="closeModal()"
+ role="dialog"
+ aria-modal="true"
+ >
+ <div
+ x-show="modalOpen"
+ x-transition:enter="transition ease-out duration-300"
+ x-transition:enter-start="bg-opacity-0"
+ x-transition:enter-end="bg-opacity-75"
+ x-transition:leave="transition ease-in duration-200"
+ x-transition:leave-start="bg-opacity-75"
+ x-transition:leave-end="bg-opacity-0"
+ class="fixed inset-0 bg-gray-500 bg-opacity-75 z-50"
+ >
+ </div>
+ <div
+ x-show="modalOpen"
+ class="fixed flex inset-0 items-start z-50 overflow-y-auto overflow-x-hidden"
+ >
+ <Phoenix.Component.focus_wrap
+ :if={@load_content?}
+ phx-mounted={
+ LiveViewJS.show(
+ time: 300,
+ transition:
+ {"ease-out duration-300", "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95",
+ "opacity-100 translate-y-0 sm:scale-100"}
+ )
+ }
+ id={@dialog_id}
+ class={@class}
+ x-show="modalOpen"
+ x-transition:enter="transition ease-out duration-300"
+ x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
+ x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
+ x-transition:leave="transition ease-in duration-200"
+ x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
+ x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
+ x-on:click.outside="closeModal()"
+ >
+ <%= render_slot(@inner_block) %>
+ </Phoenix.Component.focus_wrap>
+ <div class="modal-loading hidden w-full self-center">
+ <div class="text-center">
+ <PlausibleWeb.Components.Generic.spinner class="inline-block h-8 w-8" />
+ </div>
+ </div>
+ </div>
+ </div>
+ """
+ end
+
+ @impl true
+ def handle_event("open", _, socket) do
+ {:noreply, assign(socket, load_content?: true)}
+ end
+
+ def handle_event("close", _, socket) do
+ {:noreply, assign(socket, load_content?: false)}
+ end
+end
diff --git a/lib/plausible_web/live/goal_settings.ex b/lib/plausible_web/live/goal_settings.ex
index 081066f30e..2b154a83f6 100644
--- a/lib/plausible_web/live/goal_settings.ex
+++ b/lib/plausible_web/live/goal_settings.ex
@@ -6,6 +6,7 @@ defmodule PlausibleWeb.Live.GoalSettings do
use Phoenix.HTML
alias Plausible.{Sites, Goals}
+ alias PlausibleWeb.Live.Components.Modal
def mount(
_params,
@@ -20,14 +21,15 @@ defmodule PlausibleWeb.Live.GoalSettings do
|> assign_new(:all_goals, fn %{site: site} ->
Goals.for_site(site, preload_funnels?: true)
end)
+ |> assign_new(:current_user, fn ->
+ Plausible.Repo.get(Plausible.Auth.User, user_id)
+ end)
{:ok,
assign(socket,
site_id: site_id,
domain: domain,
displayed_goals: socket.assigns.all_goals,
- add_goal?: false,
- current_user_id: user_id,
filter_text: ""
)}
end
@@ -38,19 +40,21 @@ defmodule PlausibleWeb.Live.GoalSettings do
~H"""
<div id="goal-settings-main">
<.flash_messages flash={@flash} />
- <%= if @add_goal? do %>
- <%= live_render(
- @socket,
- PlausibleWeb.Live.GoalSettings.Form,
- id: "goals-form",
- session: %{
- "current_user_id" => @current_user_id,
- "domain" => @domain,
- "site_id" => @site_id,
- "rendered_by" => self()
+ <.live_component module={Modal} id="goals-form-modal">
+ <.live_component
+ module={PlausibleWeb.Live.GoalSettings.Form}
+ id="goals-form"
+ domain={@domain}
+ site={@site}
+ current_user={@current_user}
+ on_save_goal={
+ fn goal, socket ->
+ send(self(), {:goal_added, goal})
+ Modal.close(socket, "goals-form-modal")
+ end
}
- ) %>
- <% end %>
+ />
+ </.live_component>
<.live_component
module={PlausibleWeb.Live.GoalSettings.List}
id="goals-list"
@@ -76,10 +80,6 @@ defmodule PlausibleWeb.Live.GoalSettings do
{:noreply, assign(socket, displayed_goals: new_list, filter_text: filter_text)}
end
- def handle_event("add-goal", _value, socket) do
- {:noreply, assign(socket, add_goal?: true)}
- end
-
def handle_event("delete-goal", %{"goal-id" => goal_id}, socket) do
goal_id = String.to_integer(goal_id)
@@ -100,15 +100,10 @@ defmodule PlausibleWeb.Live.GoalSettings do
end
end
- def handle_info(:cancel_add_goal, socket) do
- {:noreply, assign(socket, add_goal?: false)}
- end
-
def handle_info({:goal_added, goal}, socket) do
socket =
socket
|> assign(
- add_goal?: false,
filter_text: "",
all_goals: [goal | socket.assigns.all_goals],
displayed_goals: [goal | socket.assigns.all_goals]
diff --git a/lib/plausible_web/live/goal_settings/form.ex b/lib/plausible_web/live/goal_settings/form.ex
index 0f53babbd7..d9d39c420b 100644
--- a/lib/plausible_web/live/goal_settings/form.ex
+++ b/lib/plausible_web/live/goal_settings/form.ex
@@ -2,84 +2,85 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
@moduledoc """
Live view for the goal creation form
"""
- use PlausibleWeb, :live_view
+ use Phoenix.LiveComponent, global_prefixes: ~w(x-)
+ use Plausible
+
import PlausibleWeb.Live.Components.Form
- alias PlausibleWeb.Live.Components.ComboBox
+ alias PlausibleWeb.Live.Components.ComboBox
alias Plausible.Repo
- def mount(
- _params,
- %{
- "site_id" => _site_id,
- "current_user_id" => user_id,
- "domain" => domain,
- "rendered_by" => pid
- },
- socket
- ) do
- form = to_form(Plausible.Goal.changeset(%Plausible.Goal{}))
-
- site =
- user_id
- |> Plausible.Sites.get_for_user!(domain, [:owner, :admin, :super_admin])
- |> Repo.preload([:owner])
-
+ def update(assigns, socket) do
+ site = Repo.preload(assigns.site, [:owner])
owner = Plausible.Users.with_subscription(site.owner)
- site = Map.put(site, :owner, owner)
+ site = %{site | owner: owner}
has_access_to_revenue_goals? =
Plausible.Billing.Feature.RevenueGoals.check_availability(owner) == :ok
- {:ok,
- assign(socket,
- current_user: Repo.get(Plausible.Auth.User, user_id),
- form: form,
- domain: domain,
- rendered_by: pid,
- tabs: %{custom_events: true, pageviews: false},
- site: site,
- has_access_to_revenue_goals?: has_access_to_revenue_goals?
- )}
+ form =
+ %Plausible.Goal{}
+ |> Plausible.Goal.changeset()
+ |> to_form()
+
+ socket =
+ socket
+ |> assign(
+ id: assigns.id,
+ form: form,
+ current_user: assigns.current_user,
+ domain: assigns.domain,
+ selected_tab: "custom_events",
+ site: site,
+ has_access_to_revenue_goals?: has_access_to_revenue_goals?,
+ on_save_goal: assigns.on_save_goal
+ )
+
+ {:ok, socket}
end
def render(assigns) do
~H"""
- <div
- class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity z-50"
- phx-window-keydown="cancel-add-goal"
- phx-key="Escape"
- >
- </div>
- <div class="fixed inset-0 flex items-center justify-center mt-16 z-50 overflow-y-auto overflow-x-hidden">
- <div class="w-1/2 h-full">
- <.form
- :let={f}
- for={@form}
- class="max-w-md w-full mx-auto bg-white dark:bg-gray-800 shadow-md rounded px-8 pt-6 pb-8 mb-4 mt-8"
- phx-submit="save-goal"
- phx-click-away="cancel-add-goal"
- >
- <h2 class="text-xl font-black dark:text-gray-100">Add Goal for <%= @domain %></h2>
+ <div id={@id}>
+ <.form
+ :let={f}
+ x-data="{ tabSelectionInProgress: false }"
+ for={@form}
+ phx-submit="save-goal"
+ phx-target={@myself}
+ >
+ <PlausibleWeb.Components.Generic.spinner
+ class="spinner block absolute right-9 top-8"
+ x-show="tabSelectionInProgress"
+ />
- <.tabs tabs={@tabs} />
+ <h2 class="text-xl font-black dark:text-gray-100">Add Goal for <%= @domain %></h2>
- <.custom_event_fields
- :if={@tabs.custom_events}
- f={f}
- current_user={@current_user}
- site={@site}
- has_access_to_revenue_goals?={@has_access_to_revenue_goals?}
- />
- <.pageview_fields :if={@tabs.pageviews} f={f} site={@site} />
+ <.tabs selected_tab={@selected_tab} myself={@myself} />
- <div class="py-4">
- <PlausibleWeb.Components.Generic.button type="submit" class="w-full">
- Add Goal →
- </PlausibleWeb.Components.Generic.button>
- </div>
- </.form>
- </div>
+ <.custom_event_fields
+ :if={@selected_tab == "custom_events"}
+ x-show="!tabSelectionInProgress"
+ f={f}
+ current_user={@current_user}
+ site={@site}
+ has_access_to_revenue_goals?={@has_access_to_revenue_goals?}
+ x-init="tabSelectionInProgress = false"
+ />
+ <.pageview_fields
+ :if={@selected_tab == "pageviews"}
+ x-show="!tabSelectionInProgress"
+ f={f}
+ site={@site}
+ x-init="tabSelectionInProgress = false"
+ />
+
+ <div class="py-4" x-show="!tabSelectionInProgress">
+ <PlausibleWeb.Components.Generic.button type="submit" class="w-full">
+ Add Goal →
+ </PlausibleWeb.Components.Generic.button>
+ </div>
+ </.form>
</div>
"""
end
@@ -87,9 +88,11 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
attr(:f, Phoenix.HTML.Form)
attr(:site, Plausible.Site)
+ attr(:rest, :global)
+
def pageview_fields(assigns) do
~H"""
- <div class="py-2">
+ <div id="pageviews-form" class="py-2" {@rest}>
<.label for="page_path_input">
Page Path
</.label>
@@ -119,9 +122,11 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
attr(:current_user, Plausible.Auth.User)
attr(:has_access_to_revenue_goals?, :boolean)
+ attr(:rest, :global)
+
def custom_event_fields(assigns) do
~H"""
- <div class="my-6">
+ <div id="custom-events-form" class="my-6" {@rest}>
<div id="event-fields">
<div class="pb-6 text-xs text-gray-700 dark:text-gray-200 text-justify rounded-md">
Custom Events are not tracked by default - you have to configure them on your site to be sent to Plausible. See examples and learn more in <a
@@ -229,8 +234,8 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
~H"""
<div class="mt-6 font-medium dark:text-gray-100">Goal Trigger</div>
<div class="my-3 w-full flex rounded border border-gray-300 dark:border-gray-500">
- <.custom_events_tab tabs={@tabs} />
- <.pageviews_tab tabs={@tabs} />
+ <.custom_events_tab selected?={@selected_tab == "custom_events"} myself={@myself} />
+ <.pageviews_tab selected?={@selected_tab == "pageviews"} myself={@myself} />
</div>
"""
end
@@ -241,11 +246,14 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
class={[
"w-1/2 text-center py-2 border-r dark:border-gray-500",
"cursor-pointer",
- @tabs.custom_events && "shadow-inner font-bold bg-indigo-600 text-white",
- [email protected]_events && "dark:text-gray-100 text-gray-800"
+ @selected? && "shadow-inner font-bold bg-indigo-600 text-white",
+ !@selected? && "dark:text-gray-100 text-gray-800"
]}
id="event-tab"
+ x-on:click="tabSelectionInProgress = true"
phx-click="switch-tab"
+ phx-value-tab="custom_events"
+ phx-target={@myself}
>
Custom Event
</a>
@@ -257,35 +265,32 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
<a
class={[
"w-1/2 text-center py-2 cursor-pointer",
- @tabs.pageviews && "shadow-inner font-bold bg-indigo-600 text-white",
- [email protected] && "dark:text-gray-100 text-gray-800"
+ @selected? && "shadow-inner font-bold bg-indigo-600 text-white",
+ !@selected? && "dark:text-gray-100 text-gray-800"
]}
id="pageview-tab"
+ x-on:click="tabSelectionInProgress = true"
phx-click="switch-tab"
+ phx-value-tab="pageviews"
+ phx-target={@myself}
>
Pageview
</a>
"""
end
- def handle_info({:selection_made, %{submit_value: _prop}}, socket) do
- {:noreply, socket}
- end
-
- def handle_event("switch-tab", _params, socket) do
- {:noreply,
- assign(socket,
- tabs: %{
- custom_events: !socket.assigns.tabs.custom_events,
- pageviews: !socket.assigns.tabs.pageviews
- }
- )}
+ def handle_event("switch-tab", %{"tab" => tab}, socket) do
+ {:noreply, assign(socket, selected_tab: tab)}
end
def handle_event("save-goal", %{"goal" => goal}, socket) do
case Plausible.Goals.create(socket.assigns.site, goal) do
{:ok, goal} ->
- send(socket.assigns.rendered_by, {:goal_added, Map.put(goal, :funnels, [])})
+ socket =
+ goal
+ |> Map.put(:funnels, [])
+ |> socket.assigns.on_save_goal.(socket)
+
{:noreply, socket}
{:error, %Ecto.Changeset{} = changeset} ->
@@ -293,11 +298,6 @@ defmodule PlausibleWeb.Live.GoalSettings.Form do
end
end
- def handle_event("cancel-add-goal", _value, socket) do
- send(socket.assigns.rendered_by, :cancel_add_goal)
- {:noreply, socket}
- end
-
def suggest_page_paths(input, _options, site) do
query = Plausible.Stats.Query.from(site, %{})
diff --git a/lib/plausible_web/live/goal_settings/list.ex b/lib/plausible_web/live/goal_settings/list.ex
index f57fe91839..6dd47a0fb0 100644
--- a/lib/plausible_web/live/goal_settings/list.ex
+++ b/lib/plausible_web/live/goal_settings/list.ex
@@ -2,9 +2,11 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
@moduledoc """
Phoenix LiveComponent module that renders a list of goals
"""
- use Phoenix.LiveComponent
+ use Phoenix.LiveComponent, global_prefixes: ~w(x-)
use Phoenix.HTML
+ alias PlausibleWeb.Live.Components.Modal
+
attr(:goals, :list, required: true)
attr(:domain, :string, required: true)
attr(:filter_text, :string)
@@ -38,7 +40,11 @@ defmodule PlausibleWeb.Live.GoalSettings.List do
</div>
</form>
<div class="mt-4 flex sm:ml-4 sm:mt-0">
- <PlausibleWeb.Components.Generic.button phx-click="add-goal">
+ <PlausibleWeb.Components.Generic.button
+ id="add-goal-button"
+ x-data
+ x-on:click={Modal.JS.open("goals-form-modal")}
+ >
+ Add Goal
</PlausibleWeb.Components.Generic.button>
</div>
diff --git a/lib/plausible_web/live/props_settings/form.ex b/lib/plausible_web/live/props_settings/form.ex
index a1cc47d6a8..b0f750b8b4 100644
--- a/lib/plausible_web/live/props_settings/form.ex
+++ b/lib/plausible_web/live/props_settings/form.ex
@@ -113,10 +113,6 @@ defmodule PlausibleWeb.Live.PropsSettings.Form do
{:noreply, assign(socket, prop_key_options_count: count)}
end
- def handle_info({:selection_made, %{submit_value: _prop}}, socket) do
- {:noreply, socket}
- end
-
def handle_event("allow-prop", %{"prop" => prop}, socket) do
case Plausible.Props.allow(socket.assigns.site, prop) do
{:ok, site} ->
diff --git a/test/plausible_web/live/goal_settings/form_test.exs b/test/plausible_web/live/goal_settings/form_test.exs
index 287df73875..8621d82476 100644
--- a/test/plausible_web/live/goal_settings/form_test.exs
+++ b/test/plausible_web/live/goal_settings/form_test.exs
@@ -21,15 +21,6 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
event_tab = lv |> element(~s/a#event-tab/) |> render_click()
assert event_tab =~ "Event Name"
end
-
- test "escape closes the form", %{conn: conn, site: site} do
- {parent, lv} = get_liveview(conn, site, with_parent?: true)
- html = render(parent)
- assert html =~ "Goal Trigger"
- render_keydown(lv, "cancel-add-goal")
- html = render(parent)
- refute html =~ "Goal Trigger"
- end
end
describe "Goal submission" do
@@ -40,15 +31,17 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
lv = get_liveview(conn, site)
html = render(lv)
- [event_name, currency_display, currency_submit] = find(html, "input")
+ [event_name, currency_display, currency_submit] = find(html, "#goals-form input")
assert name_of(event_name) == "goal[event_name]"
assert name_of(currency_display) == "display-currency_input"
assert name_of(currency_submit) == "goal[currency]"
- html = lv |> element(~s/a#pageview-tab/) |> render_click()
+ lv |> element(~s/a#pageview-tab/) |> render_click()
+
+ html = render(lv)
- [page_path_display, page_path] = find(html, "input")
+ [page_path_display, page_path] = find(html, "#goals-form input")
assert name_of(page_path_display) == "display-page_path_input"
assert name_of(page_path) == "goal[page_path]"
end
@@ -58,20 +51,23 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
lv = get_liveview(conn, site)
html = render(lv)
- [event_name] = find(html, "input")
+ [event_name] = find(html, "#goals-form input")
assert name_of(event_name) == "goal[event_name]"
- html = lv |> element(~s/a#pageview-tab/) |> render_click()
+ lv |> element(~s/a#pageview-tab/) |> render_click()
+
+ html = render(lv)
- [page_path_display, page_path] = find(html, "input")
+ [page_path_display, page_path] = find(html, "#goals-form input")
assert name_of(page_path_display) == "display-page_path_input"
assert name_of(page_path) == "goal[page_path]"
end
test "renders error on empty submission", %{conn: conn, site: site} do
lv = get_liveview(conn, site)
- html = lv |> element("form") |> render_submit()
+ lv |> element("#goals-form form") |> render_submit()
+ html = render(lv)
assert html =~ "this field is required and cannot be blank"
pageview_tab = lv |> element(~s/a#pageview-tab/) |> render_click()
@@ -79,35 +75,40 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
end
test "creates a custom event", %{conn: conn, site: site} do
- {parent, lv} = get_liveview(conn, site, with_parent?: true)
- refute render(parent) =~ "SampleCustomEvent"
- lv |> element("form") |> render_submit(%{goal: %{event_name: "SampleCustomEvent"}})
- parent_html = render(parent)
- assert parent_html =~ "SampleCustomEvent"
- assert parent_html =~ "Custom Event"
+ lv = get_liveview(conn, site)
+ refute render(lv) =~ "SampleCustomEvent"
+
+ lv
+ |> element("#goals-form form")
+ |> render_submit(%{goal: %{event_name: "SampleCustomEvent"}})
+
+ html = render(lv)
+ assert html =~ "SampleCustomEvent"
+ assert html =~ "Custom Event"
end
@tag :full_build_only
test "creates a revenue goal", %{conn: conn, site: site} do
- {parent, lv} = get_liveview(conn, site, with_parent?: true)
- refute render(parent) =~ "SampleRevenueGoal"
+ lv = get_liveview(conn, site)
+ refute render(lv) =~ "SampleRevenueGoal"
lv
- |> element("form")
+ |> element("#goals-form form")
|> render_submit(%{goal: %{event_name: "SampleRevenueGoal", currency: "EUR"}})
- parent_html = render(parent)
- assert parent_html =~ "SampleRevenueGoal (EUR)"
- assert parent_html =~ "Revenue Goal"
+ html = render(lv)
+
+ assert html =~ "SampleRevenueGoal (EUR)"
+ assert html =~ "Revenue Goal"
end
test "creates a pageview goal", %{conn: conn, site: site} do
- {parent, lv} = get_liveview(conn, site, with_parent?: true)
- refute render(parent) =~ "Visit /page/**"
- lv |> element("form") |> render_submit(%{goal: %{page_path: "/page/**"}})
- parent_html = render(parent)
- assert parent_html =~ "Visit /page/**"
- assert parent_html =~ "Pageview"
+ lv = get_liveview(conn, site)
+ refute render(lv) =~ "Visit /page/**"
+ lv |> element("#goals-form form") |> render_submit(%{goal: %{page_path: "/page/**"}})
+ html = render(lv)
+ assert html =~ "Visit /page/**"
+ assert html =~ "Pageview"
end
end
@@ -129,13 +130,6 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
refute element_exists?(html, ~s/a[phx-value-display-value="PLN - Polish Zloty"]/)
assert element_exists?(html, ~s/a[phx-value-display-value="EUR - Euro"]/)
-
- lv
- |> element("#dropdown-currency_input-option-1 a")
- |> render_click()
-
- # make sure combo's {:selection_made, ...} message is received
- render(lv)
end
test "pageview combo works", %{conn: conn, site: site} do
@@ -186,16 +180,10 @@ defmodule PlausibleWeb.Live.GoalSettings.FormTest do
{:ok, [g1, g2, g3]}
end
- defp get_liveview(conn, site, opts \\ []) do
+ defp get_liveview(conn, site) do
conn = assign(conn, :live_module, PlausibleWeb.Live.GoalSettings)
{:ok, lv, _html} = live(conn, "/#{site.domain}/settings/goals")
- lv |> element(~s/button[phx-click="add-goal"]/) |> render_click()
- assert form_view = find_live_child(lv, "goals-form")
- if opts[:with_parent?] do
- {lv, form_view}
- else
- form_view
- end
+ lv
end
end
diff --git a/test/plausible_web/live/goal_settings_test.exs b/test/plausible_web/live/goal_settings_test.exs
index 448ffec6a5..99e51b1ed0 100644
--- a/test/plausible_web/live/goal_settings_test.exs
+++ b/test/plausible_web/live/goal_settings_test.exs
@@ -57,7 +57,10 @@ defmodule PlausibleWeb.Live.GoalSettingsTest do
test "add goal button is rendered", %{conn: conn, site: site} do
conn = get(conn, "/#{site.domain}/settings/goals")
resp = html_response(conn, 200)
- assert element_exists?(resp, ~s/button[phx-click="add-goal"]/)
+ assert element_exists?(resp, ~s/button#add-goal-button[x-data]/)
+ attr = text_of_attr(resp, ~s/button#add-goal-button/, "x-on:click")
+ assert attr =~ "open-modal"
+ assert attr =~ "goals-form-modal"
end
test "search goals input is rendered", %{conn: conn, site: site} do
@@ -135,23 +138,22 @@ defmodule PlausibleWeb.Live.GoalSettingsTest do
refute html =~ "No goals found for this site. Please refine or"
end
- test "clicking Add Goal button renders the form view", %{conn: conn, site: site} do
+ test "Add Goal form view is rendered immediately, though hidden", %{conn: conn, site: site} do
{:ok, _goals} = setup_goals(site)
- lv = get_liveview(conn, site)
- html = lv |> element(~s/button[phx-click="add-goal"]/) |> render_click()
+ {_, html} = get_liveview(conn, site, with_html?: true)
assert html =~ "Add Goal for #{site.domain}"
assert element_exists?(
html,
- ~s/div#goals-form form[phx-submit="save-goal"][phx-click-away="cancel-add-goal"]/
+ ~s/div#goals-form form[phx-submit="save-goal"]/
)
end
end
defp setup_goals(site) do
{:ok, g1} = Plausible.Goals.create(site, %{"page_path" => "/go/to/blog/**"})
- {:ok, g2} = Plausible.Goals.create(site, %{"event_name" => "Signup"})
+ {:ok, g2} = Plausible.Goals.create(site, %{"event_name" => "Register"})
{:ok, g3} = Plausible.Goals.create(site, %{"event_name" => "Purchase", "currency" => "EUR"})
{:ok, [g1, g2, g3]}
end