Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Team management UI improvements (#6699)
RobertJoonas736048e35ec3
diff --git a/assets/css/app.css b/assets/css/app.cssindex 905a6be945..22b1ad7d34 100644--- a/assets/css/app.css+++ b/assets/css/app.css@@ -303,6 +303,11 @@@custom-variant phx-submit-loading (.phx-submit-loading&, .phx-submit-loading &);@custom-variant phx-change-loading (.phx-change-loading&, .phx-change-loading &);+/* Prima components usually mark their disabled state with `data-disabled` rather than+ the native attribute, so `disabled:` covers both. */++@custom-variant disabled (&:disabled, &[data-disabled="true"], [data-disabled="true"] &);+[x-cloak] {display: none;}diff --git a/assets/js/liveview/confirm.js b/assets/js/liveview/confirm.jsnew file mode 100644index 0000000000..14d6d18438--- /dev/null+++ b/assets/js/liveview/confirm.js@@ -0,0 +1,27 @@+// An alternative for phoenix_html's `data-confirm`. Currently delegates to+// `window.confirm` just as `data-confirm` does, but can be extended with custom+// styling in the future.++// Unlike `data-confirm` (which uses a window-level click listener), this hook+// intercepts the click on the element itself, so it also works when a listener+// closer to the element acts on the click first - e.g. a Prima listbox selecting+// the clicked option.++export default {+ mounted() {+ this.handleClick = (e) => {+ const message = this.el.dataset.confirmMessage++ if (message && !window.confirm(message)) {+ e.preventDefault()+ e.stopImmediatePropagation()+ }+ }++ this.el.addEventListener('click', this.handleClick, true)+ },++ destroyed() {+ this.el.removeEventListener('click', this.handleClick, true)+ }+}diff --git a/assets/js/liveview/live_socket.js b/assets/js/liveview/live_socket.jsindex e1c9513fb2..ba097a872c 100644--- a/assets/js/liveview/live_socket.js+++ b/assets/js/liveview/live_socket.js@@ -7,19 +7,20 @@import 'phoenix_html'import { Socket } from 'phoenix'import { LiveSocket } from 'phoenix_live_view'-import { Modal, Dropdown } from 'prima'+import { Modal, Dropdown, Listbox } from 'prima'import topbar from 'topbar'/* eslint-enable import/no-unresolved */import Alpine from 'alpinejs'+import Confirm from './confirm'import CopySnippet from './copy-snippet'import MemberRows from './member-rows'let csrfToken = document.querySelector("meta[name='csrf-token']")let websocketUrl = document.querySelector("meta[name='websocket-url']")if (csrfToken && websocketUrl) {- let Hooks = { Modal, Dropdown, CopySnippet, MemberRows }+ let Hooks = { Modal, Dropdown, Listbox, Confirm, CopySnippet, MemberRows }Hooks.VerificationLifecycle = {mounted() {diff --git a/e2e/tests/dashboard/team-management.spec.ts b/e2e/tests/dashboard/team-management.spec.tsnew file mode 100644index 0000000000..16d44d42e8--- /dev/null+++ b/e2e/tests/dashboard/team-management.spec.ts@@ -0,0 +1,179 @@+import { test, expect, Page } from '@playwright/test'+import { setupSite } from '../fixtures'+import {+ closeFlashMessage,+ expectLiveViewConnected,+ hasFlashMessage,+ hasNoFlashMessage,+ randomID+} from '../test-utils'++async function createTeam(page: Page) {+ await page.goto('/team/setup', { waitUntil: 'commit' })+ await expectLiveViewConnected(page)+ await page.getByRole('button', { name: 'Create team' }).click()+ await expect(page).toHaveURL(/\/settings\/team\/general/)+ await expectLiveViewConnected(page)+ // so that tests start without a flash+ await closeFlashMessage(page)+}++async function submitInviteForm(+ page: Page,+ { email, roleOptionName }: { email: string; roleOptionName: string | RegExp }+) {+ await page.getByPlaceholder('Enter e-mail').fill(email)+ await page.locator('#input-role-picker-trigger').click()+ await page+ .locator('#input-role-picker')+ .getByRole('option', { name: roleOptionName })+ .click()+ await page.getByRole('button', { name: 'Invite' }).click()+}++test('lowering your own role asks for confirmation', async ({+ page,+ request+}) => {+ const { user } = await setupSite({ page, request })+ await createTeam(page)++ // The only owner can't change their own role, so a second (invited) owner+ // is needed for the self-demotion options to become selectable.+ const ownerEmail = `owner-${randomID()}@example.com`+ await submitInviteForm(page, { email: ownerEmail, roleOptionName: /^Owner/ })+ await expect(+ page.getByRole('button', { name: `Role for ${ownerEmail}:` })+ ).toContainText('Owner')++ const trigger = page.getByRole('button', { name: `Role for ${user.email}:` })+ const options = page.getByRole('listbox', {+ name: `Role for ${user.email}:`+ })++ const dialogs: string[] = []+ const answerNextDialog = (accept: boolean) =>+ page.once('dialog', async (dialog) => {+ dialogs.push(dialog.message())+ await (accept ? dialog.accept() : dialog.dismiss())+ })++ await expect(trigger).toBeEnabled()+ await expect(trigger).toContainText('Owner')++ await test.step('lower your own role, but cancel the confirmation dialog (mouse)', async () => {+ answerNextDialog(false)++ await trigger.click()+ await options.getByRole('option', { name: /^Viewer/ }).click()++ expect(dialogs).toHaveLength(1)+ expect(dialogs[0]).toContain("You're about to lower your own role")+ await expect(trigger).toContainText('Owner')+ await hasNoFlashMessage(page)++ // Close the listbox that remained open because the option selection click didn't+ // go through -- our confirmation dialog prevented it from bubbling up to Prima.+ await page.keyboard.press('Escape')+ })++ await test.step('lower your own role, but cancel the confirmation dialog (keyboard)', async () => {+ answerNextDialog(false)++ await trigger.focus()+ await page.keyboard.press('ArrowUp')+ await expect(+ options.getByRole('option', { name: /^Viewer/ })+ ).toHaveAttribute('data-focus')+ await page.keyboard.press('Enter')++ expect(dialogs).toHaveLength(2)+ await expect(trigger).toContainText('Owner')+ await hasNoFlashMessage(page)++ // Close the listbox that remained open because the option selection click didn't+ // go through -- our confirmation dialog prevented it from bubbling up to Prima.+ await page.keyboard.press('Escape')+ })++ await test.step('lower your own role and confirm (mouse)', async () => {+ answerNextDialog(true)++ await trigger.click()+ await options.getByRole('option', { name: /^Viewer/ }).click()++ // The change reaches the server, which rejects it: the other owner has only+ // been invited so far.+ await hasFlashMessage(page, 'The team has to have at least one owner')++ // asked once: phoenix_html must not ask again as the confirmed click bubbles up+ expect(dialogs).toHaveLength(3)++ // Known bug, to be fixed soon: the trigger keeps showing the rejected role+ // until the page is reloaded. Once fixed, the reload won't be necessary.+ await page.reload()+ await expectLiveViewConnected(page)++ await expect(trigger).toContainText('Owner')+ })++ await test.step('lower your own role and confirm (keyboard)', async () => {+ answerNextDialog(true)++ await trigger.focus()+ await page.keyboard.press('ArrowUp')+ await expect(+ options.getByRole('option', { name: /^Viewer/ })+ ).toHaveAttribute('data-focus')+ await page.keyboard.press('Enter')++ // The change reaches the server, which rejects it: the other owner has only+ // been invited so far.+ await hasFlashMessage(page, 'The team has to have at least one owner')++ // asked once: phoenix_html must not ask again as the confirmed click bubbles up+ expect(dialogs).toHaveLength(4)++ // Known bug, to be fixed soon: the trigger keeps showing the rejected role+ // until the page is reloaded. Once fixed, the reload won't be necessary.+ await page.reload()+ await expectLiveViewConnected(page)++ await expect(trigger).toContainText('Owner')+ })+})++test('choosing the current role again just closes the listbox', async ({+ page,+ request+}) => {+ await setupSite({ page, request })+ await createTeam(page)++ const viewerEmail = `viewer-${randomID()}@example.com`+ await submitInviteForm(page, {+ email: viewerEmail,+ roleOptionName: /^Viewer/+ })++ const trigger = page.getByRole('button', { name: `Role for ${viewerEmail}:` })+ const options = page.getByRole('listbox', {+ name: `Role for ${viewerEmail}:`+ })++ await expect(trigger).toContainText('Viewer')++ const dialogs: string[] = []+ page.on('dialog', async (dialog) => {+ dialogs.push(dialog.message())+ await dialog.dismiss()+ })++ await trigger.click()+ await options.getByRole('option', { name: /^Viewer/ }).click()++ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ await expect(trigger).toContainText('Viewer')+ expect(dialogs).toHaveLength(0)+ await hasNoFlashMessage(page)+})diff --git a/e2e/tests/test-utils.ts b/e2e/tests/test-utils.tsindex ade7b67446..0001172740 100644--- a/e2e/tests/test-utils.ts+++ b/e2e/tests/test-utils.ts@@ -21,6 +21,25 @@ export async function expectLiveViewConnected(page: Page) {.toBeGreaterThan(0)}+const visibleFlash = (page: Page) =>+ page.getByTestId('live-flash').filter({ visible: true })++export async function hasFlashMessage(page: Page, message?: string) {+ const flash = visibleFlash(page)+ await expect(+ message ? flash.filter({ hasText: message }) : flash+ ).toBeVisible()+}++export async function hasNoFlashMessage(page: Page) {+ await expect(visibleFlash(page)).toHaveCount(0)+}++export async function closeFlashMessage(page: Page) {+ await visibleFlash(page).getByRole('button').click()+ await hasNoFlashMessage(page)+}+export function randomID() {return Math.random().toString(16).slice(2)}diff --git a/lib/plausible_web/components/prima_dropdown.ex b/lib/plausible_web/components/prima_dropdown.exindex 2e30da8393..1ea3051b28 100644--- a/lib/plausible_web/components/prima_dropdown.ex+++ b/lib/plausible_web/components/prima_dropdown.ex@@ -64,8 +64,7 @@ defmodule PlausibleWeb.Components.PrimaDropdown do<Dropdown.dropdown_menuid={@id}placement="bottom-end"- match_trigger_width={true}- class="bg-white rounded-md shadow-lg ring-1 ring-black/5 focus:outline-none p-1.5 dark:bg-gray-800 relative z-10"+ class="min-w-[var(--reference-width)] bg-white rounded-md shadow-lg ring-1 ring-black/5 focus:outline-none p-1.5 dark:bg-gray-800 relative z-10">{render_slot(@inner_block)}</Dropdown.dropdown_menu>diff --git a/lib/plausible_web/components/prima_listbox.ex b/lib/plausible_web/components/prima_listbox.exnew file mode 100644index 0000000000..fe7a22d156--- /dev/null+++ b/lib/plausible_web/components/prima_listbox.ex@@ -0,0 +1,134 @@+defmodule PlausibleWeb.Components.PrimaListbox do+ @moduledoc false+ alias Prima.Listbox+ use Phoenix.Component++ # Themes/sizes/base are defined as component classes in+ # assets/css/app.css, shared with the Phoenix `button` component+ # (lib/plausible_web/components/generic.ex). Update there only.+ @trigger_base_class "btn-base justify-between focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"++ @trigger_themes %{+ "secondary" => "btn-theme-secondary",+ "ghost" => "btn-theme-ghost",+ "link" => "btn-theme-link"+ }++ @trigger_sizes %{+ "xs" => "btn-xs",+ "sm" => "btn-sm",+ "md" => "btn-md"+ }++ @options_base_class "relative z-50 p-1.5 w-max rounded-md shadow-lg overflow-hidden bg-white dark:bg-gray-800 ring-1 ring-black/5 focus:outline-none"+ @option_class "group block rounded-md text-sm/6 text-gray-900 dark:text-gray-100 px-3 py-1.5 cursor-pointer data-focus:bg-gray-100 dark:data-focus:bg-gray-700/80"++ defdelegate listbox_value(assigns), to: Listbox++ attr(:id, :string, required: true)+ attr(:name, :string, required: true)+ attr(:value, :any, default: nil)+ attr(:disabled, :boolean, default: false)+ attr(:rest, :global)+ slot(:inner_block, required: true)++ def listbox(assigns) do+ ~H"""+ <Listbox.listbox id={@id} name={@name} value={@value} disabled={@disabled} {@rest}>+ {render_slot(@inner_block)}+ </Listbox.listbox>+ """+ end++ attr(:id, :string, required: true)+ attr(:theme, :string, default: "secondary")+ attr(:size, :string, default: "md")+ attr(:class, :string, default: "")+ attr(:rest, :global)+ slot(:inner_block, required: true)++ def listbox_trigger(assigns) do+ assigns =+ assign(assigns,+ computed_class: [+ @trigger_base_class,+ @trigger_sizes[assigns.size],+ @trigger_themes[assigns.theme],+ assigns.class+ ]+ )++ ~H"""+ <Listbox.listbox_trigger id={@id} class={@computed_class} {@rest}>+ {render_slot(@inner_block)}+ </Listbox.listbox_trigger>+ """+ end++ attr(:id, :string, required: true)+ attr(:class, :string, default: "")+ slot(:inner_block, required: true)++ def listbox_options(assigns) do+ assigns = assign(assigns, computed_class: [@options_base_class, assigns.class])++ ~H"""+ <Listbox.listbox_options+ id={@id}+ placement="bottom-end"+ offset={8}+ transition_enter={+ {"transition ease-out duration-100", "opacity-0 scale-95", "opacity-100 scale-100"}+ }+ transition_leave={+ {"transition ease-in duration-75", "opacity-100 scale-100", "opacity-0 scale-95"}+ }+ class={@computed_class}+ >+ {render_slot(@inner_block)}+ </Listbox.listbox_options>+ """+ end++ attr(:id, :string, required: true)+ attr(:value, :any, required: true)+ attr(:display, :string, default: nil)+ attr(:rest, :global)+ slot(:inner_block, required: true)++ def listbox_option(assigns) do+ assigns = assign(assigns, :option_class, @option_class)++ ~H"""+ <Listbox.listbox_option+ id={@id}+ value={@value}+ display={@display}+ class={@option_class}+ {@rest}+ >+ {render_slot(@inner_block)}+ </Listbox.listbox_option>+ """+ end++ def selected_option_check_icon(assigns) do+ ~H"""+ <Heroicons.check+ mini+ class="size-4 text-indigo-600 dark:text-indigo-400 hidden group-data-selected:inline"+ />+ """+ end++ attr(:class, :string, default: "")+ slot(:inner_block, required: true)++ def option_description(assigns) do+ ~H"""+ <div class={["text-xs/5 text-gray-500 dark:text-gray-400", @class]}>+ {render_slot(@inner_block)}+ </div>+ """+ end+enddiff --git a/lib/plausible_web/live/components/team.ex b/lib/plausible_web/live/components/team.exindex 459dd76a86..90a3868be2 100644--- a/lib/plausible_web/live/components/team.ex+++ b/lib/plausible_web/live/components/team.ex@@ -7,6 +7,7 @@ defmodule PlausibleWeb.Live.Components.Team doimport PlausibleWeb.Components.Genericalias Plausible.Auth.User+ alias PlausibleWeb.Components.PrimaListbox@role_descriptions [owner: "Manage the team without restrictions",@@ -22,11 +23,16 @@ defmodule PlausibleWeb.Live.Components.Team dodef role_to_atom(role), do: Map.fetch!(@roles_cast_map, role)+ defp role_to_capitalized_string(role) when is_atom(role) do+ role |> Atom.to_string() |> String.capitalize()+ end+attr(:user, User, required: true)attr(:label, :string, default: nil)attr(:role, :atom, default: nil)attr(:my_role, :atom, required: true)attr(:me?, :boolean, default: false)+ attr(:pending?, :boolean, default: false)attr(:disabled, :boolean, default: false)attr(:remove_disabled, :boolean, default: false)@@ -43,73 +49,53 @@ defmodule PlausibleWeb.Live.Components.Team do)}>- <div class="flex items-center gap-x-5">- <img src={User.profile_img_url(@user)} class="w-8 rounded-full bg-gray-300" />- <div class="flex flex-col">- <span class="text-sm font-medium">- {@user.name}+ <div class="flex items-center gap-x-3 sm:gap-x-5">+ <img+ :if={not @pending?}+ src={User.profile_img_url(@user)}+ class="size-8 shrink-0 rounded-full bg-gray-300"+ />+ <div+ :if={@pending?}+ class="size-8 shrink-0 flex items-center justify-center rounded-full bg-indigo-500"+ >+ <Heroicons.envelope class="size-4 text-white" />+ </div>+ <div class="flex flex-col min-w-0">+ <div class="flex items-center gap-x-1 text-sm font-medium">+ <span :if={@pending?} class="truncate">Pending invitation</span>+ <span :if={not @pending?} class="truncate">{@user.name}</span><span- :if={@label}- class="ml-1 dark:bg-indigo-600 dark:text-gray-200 bg-gray-150 text-gray-500 text-xs px-1 py-0.5 rounded-md"+ :if={@label && @me?}+ class="shrink-0 dark:bg-indigo-600 dark:text-gray-200 bg-gray-150 text-gray-500 text-xs px-1 py-0.5 rounded-md">{@label}</span>- </span>- <span class="text-gray-500 text-xs">+ <.pill :if={@label && not @me?} color={:gray} class="shrink-0">{@label}</.pill>+ </div>+ <span class="text-gray-500 text-xs truncate">{@user.email}</span></div>- <div class="flex-1 text-right">- <.dropdown id={"role-dropdown-#{@user.email}"}>- <:button theme="ghost" size="sm" class="role">- <span :if={@disabled} class="text-gray-400">- {@role |> to_string() |> String.capitalize()}- </span>- <span :if={not @disabled}>- {@role |> to_string() |> String.capitalize()}- </span>- <Heroicons.chevron_down :if={@disabled} mini class="text-gray-400 size-4" />- <Heroicons.chevron_down :if={not @disabled} mini class="size-4" />- </:button>- <:menu class="dropdown-items max-w-60">- <.role_item- :for={{role, description} <- role_descriptions()}- user={@user}- id={"option-#{:erlang.phash2(@user.email)}-#{role}"}- phx-value-email={@user.email}- phx-value-name={@user.name}- role={role}- disabled={@disabled or @role == role}- dispatch_animation?={@role == :guest}- data-confirm={- if @me? and role in [:editor, :billing, :viewer], do: lower_role_warning()- }- >- {description}- </.role_item>- <.dropdown_divider />-- <.dropdown_item- id={"#{:erlang.phash2(@user.email)}-remove"}- href="#"- disabled={@disabled or @remove_disabled}- phx-click="remove-member"- phx-value-email={@user.email}- phx-value-name={@user.name}- data-confirm="Are you sure you want to remove this member from the team?"- >- <div class={- not @remove_disabled &&- "text-red-600 hover:text-red-600 dark:text-red-500 hover:dark:text-red-400"- }>- Remove member- </div>- <div class="text-gray-500 dark:text-gray-400 text-xs/5">- Remove member from your team- </div>- </.dropdown_item>- </:menu>- </.dropdown>+ <div class="flex-1 shrink-0 flex items-center justify-end gap-x-2">+ <.role_switcher+ id={"role-dropdown-#{@user.email}"}+ user={@user}+ role={@role}+ my_role={@my_role}+ me?={@me?}+ disabled={@disabled}+ />++ <.delete_button+ id={"#{:erlang.phash2(@user.email)}-remove"}+ disabled={@disabled or @remove_disabled}+ class="disabled:!text-gray-500 dark:disabled:!text-gray-600"+ aria-label={"Remove member #{@user.email}"}+ phx-click="remove-member"+ phx-value-email={@user.email}+ data-confirm="Are you sure you want to remove this member from the team?"+ /></div></div></div>@@ -117,77 +103,110 @@ defmodule PlausibleWeb.Live.Components.Team doendattr(:id, :string, required: true)+ attr(:user, User, required: true)attr(:role, :atom, required: true)attr(:my_role, :atom, required: true)- attr(:rest, :global)+ attr(:me?, :boolean, default: false)+ attr(:disabled, :boolean, default: false)++ def role_switcher(assigns) do+ assigns = assign(assigns, :change, role_change(assigns.user, assigns.role))- def role_picker(assigns) do~H"""- <.dropdown id={@id}>- <:button theme="secondary" size="md" class="role w-[100px] justify-between">- {@role |> Atom.to_string() |> String.capitalize()}- <Heroicons.chevron_down mini class="size-4" />- </:button>- <:menu class="dropdown-items max-w-60">- <.role_item- :for={{role, description} <- role_descriptions()}- role={role}- disabled={role_change_disabled?(@my_role, role)}- {@rest}+ <form id={"role-form-#{:erlang.phash2(@user.email)}"} phx-change={@change}>+ <input type="hidden" name="email" value={@user.email} />++ <PrimaListbox.listbox id={@id} name="role" value={@role} disabled={@disabled}>+ <PrimaListbox.listbox_trigger+ id={"#{@id}-trigger"}+ theme="ghost"+ size="sm">- {description}- </.role_item>- </:menu>- </.dropdown>+ <span class="sr-only">Role for {@user.email}:</span>+ <PrimaListbox.listbox_value data-test-id="role">+ {role_to_capitalized_string(@role)}+ </PrimaListbox.listbox_value>+ <Heroicons.chevron_down mini class="size-4" />+ </PrimaListbox.listbox_trigger>++ <PrimaListbox.listbox_options id={"#{@id}-options"} class="max-w-60">+ <PrimaListbox.listbox_option+ :for={{role, description} <- selectable_role_descriptions(@my_role)}+ id={"option-#{:erlang.phash2(@user.email)}-#{role}"}+ value={role}+ display={role_to_capitalized_string(role)}+ phx-hook="Confirm"+ data-confirm-message={+ if @me? and role in [:editor, :billing, :viewer], do: lower_role_warning()+ }+ >+ <div class="flex items-center justify-between gap-x-2">+ <span>{role_to_capitalized_string(role)}</span>+ <PrimaListbox.selected_option_check_icon />+ </div>+ <PrimaListbox.option_description>+ {description}+ </PrimaListbox.option_description>+ </PrimaListbox.listbox_option>+ </PrimaListbox.listbox_options>+ </PrimaListbox.listbox>+ </form>"""end- attr(:role, :atom, required: true)- attr(:disabled, :boolean, default: false)- attr(:dispatch_animation?, :boolean, default: false)- attr(:rest, :global)- attr(:user, :map, default: %{email: nil})- attr(:id, :string, default: nil)-- slot(:inner_block, required: true)-- def role_item(assigns) do- click =- cond do- phx_click = assigns.rest[:"phx-click"] ->- phx_click-- assigns.dispatch_animation? ->- JS.hide(- transition: {"duration-500", "opacity-100", "opacity-0"},- to: "#member-row-#{:erlang.phash2(assigns.user.email)}",- time: 500- )- |> JS.push("update-role")+ defp role_change(user, :guest) do+ JS.hide(+ transition: {"duration-500", "opacity-100", "opacity-0"},+ to: "#member-row-#{:erlang.phash2(user.email)}",+ time: 500+ )+ |> JS.push("update-role")+ end- true ->- "update-role"- end+ defp role_change(_user, _role), do: "update-role"- assigns = assign(assigns, :click, click)+ attr(:id, :string, required: true)+ attr(:name, :string, required: true)+ attr(:role, :atom, required: true)+ attr(:my_role, :atom, required: true)+ def role_select_input(assigns) do~H"""- <.dropdown_item- id={@id}- href="#"- phx-click={@click}- phx-value-role={@role}- disabled={@disabled}- {@rest}- >- <div>{@role |> Atom.to_string() |> String.capitalize()}</div>- <div class="text-gray-500 dark:text-gray-400 text-xs/5">- {render_slot(@inner_block)}- </div>- </.dropdown_item>+ <PrimaListbox.listbox id={@id} name={@name} value={@role}>+ <PrimaListbox.listbox_trigger id={"#{@id}-trigger"} class="w-[100px]">+ <span class="sr-only">Role:</span>+ <PrimaListbox.listbox_value>+ {role_to_capitalized_string(@role)}+ </PrimaListbox.listbox_value>+ <Heroicons.chevron_down mini class="size-4" />+ </PrimaListbox.listbox_trigger>++ <PrimaListbox.listbox_options id={"#{@id}-options"} class="max-w-64">+ <PrimaListbox.listbox_option+ :for={{role, description} <- selectable_role_descriptions(@my_role)}+ id={"#{@id}-option-#{role}"}+ value={role}+ display={role_to_capitalized_string(role)}+ >+ <div class="flex items-center justify-between gap-x-2">+ <span>{role_to_capitalized_string(role)}</span>+ <PrimaListbox.selected_option_check_icon />+ </div>+ <PrimaListbox.option_description class="whitespace-nowrap">+ {description}+ </PrimaListbox.option_description>+ </PrimaListbox.listbox_option>+ </PrimaListbox.listbox_options>+ </PrimaListbox.listbox>"""end+ defp selectable_role_descriptions(my_role) do+ Enum.reject(@role_descriptions, fn {role, _description} ->+ role_change_disabled?(my_role, role)+ end)+ end+defp role_change_disabled?(my_role, :owner), do: my_role != :ownerdefp role_change_disabled?(my_role, _role), do: my_role not in [:owner, :admin]diff --git a/lib/plausible_web/live/flash.ex b/lib/plausible_web/live/flash.exindex 5258913af1..9bc8f3d01b 100644--- a/lib/plausible_web/live/flash.ex+++ b/lib/plausible_web/live/flash.ex@@ -110,6 +110,7 @@ defmodule PlausibleWeb.Live.Flash do@class,"mb-4 max-w-sm w-full bg-white dark:bg-gray-800 shadow-lg rounded-lg pointer-events-auto"]}+ data-testid="live-flash"{@rest}><div class="rounded-lg ring-1/5 ring-black overflow-hidden">diff --git a/lib/plausible_web/live/team_management.ex b/lib/plausible_web/live/team_management.exindex 94ed2bdbe9..2c52448b35 100644--- a/lib/plausible_web/live/team_management.ex+++ b/lib/plausible_web/live/team_management.ex@@ -25,7 +25,6 @@ defmodule PlausibleWeb.Live.TeamManagement dolayout: layout,my_role: my_role,team_layout_changed?: false,- input_role: :viewer,input_email: "")end@@ -56,11 +55,11 @@ defmodule PlausibleWeb.Live.TeamManagement do/></div>- <.role_picker+ <.role_select_inputid="input-role-picker"- role={@input_role}+ name="input-role"+ role={:viewer}my_role={@my_role}- phx-click="switch-role"/><.button@@ -81,6 +80,7 @@ defmodule PlausibleWeb.Live.TeamManagement dorole={entry.role}label={entry_label(entry, @current_user)}me?={entry.id == @current_user.id}+ pending?={entry.type in [:invitation_pending, :invitation_sent]}my_role={@my_role}remove_disabled={not Layout.removable?(@layout, email)}disabled={@@ -105,6 +105,7 @@ defmodule PlausibleWeb.Live.TeamManagement douser={%User{email: entry.email, name: entry.name}}role={entry.role}label={entry_label(entry, @current_user)}+ pending?={entry.type in [:invitation_pending, :invitation_sent]}my_role={@my_role}remove_disabled={not Layout.removable?(@layout, email)}disabled={@my_role not in [:owner, :admin]}@@ -118,17 +119,13 @@ defmodule PlausibleWeb.Live.TeamManagement do{:noreply, assign(socket, input_email: params["input-email"])}end- def handle_event("switch-role", %{"role" => role}, socket) do- socket = assign(socket, input_role: role_to_atom(role))- {:noreply, socket}- end-def handle_event("input-invitation",- %{"input-email" => email},- %{assigns: %{layout: layout, input_role: role}} = socket+ %{"input-email" => email, "input-role" => role},+ %{assigns: %{layout: layout}} = socket) doemail = String.trim(email)+ role = role_to_atom(role)existing_entry = Map.get(layout, email)diff --git a/mix.exs b/mix.exsindex 09b8cc2559..4ba9fc5372 100644--- a/mix.exs+++ b/mix.exs@@ -134,7 +134,7 @@ defmodule Plausible.MixProject do{:phoenix_live_view, "~> 1.1.17"},{:php_serializer, "~> 2.0"},{:plug, "~> 1.13", override: true},- {:prima, "~> 0.2.6"},+ {:prima, "~> 0.3.0"},{:plug_cowboy, "~> 2.3"},{:polymorphic_embed, "~> 5.0"},{:postgrex, "~> 0.22.2"},diff --git a/mix.lock b/mix.lockindex 0fb519ba4a..3580bdf473 100644--- a/mix.lock+++ b/mix.lock@@ -134,7 +134,7 @@"plug_crypto": {:hex, :plug_crypto, "1.2.5", "918772575e48e81e455818229bf719d4ab4181fcbf7f85b68a35620f78d89ced", [:mix], [], "hexpm", "26549a1d6345e2172eb1c233866756ae44a9609bd33ee6f99147ab3fd87fd842"},"polymorphic_embed": {:hex, :polymorphic_embed, "5.0.3", "37444e0af941026a2c29b0539b6471bdd6737a6492a19264bf2bb0118e3ac242", [:mix], [{:attrs, "~> 0.6", [hex: :attrs, repo: "hexpm", optional: false]}, {:ecto, "~> 3.12", [hex: :ecto, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:phoenix_html_helpers, "~> 1.0", [hex: :phoenix_html_helpers, repo: "hexpm", optional: true]}, {:phoenix_live_view, "~> 0.20 or ~> 1.0", [hex: :phoenix_live_view, repo: "hexpm", optional: true]}], "hexpm", "2fed44f57abf0a0fc7642e0eb0807a55b65de1562712cc0620772cbbb80e49c1"},"postgrex": {:hex, :postgrex, "0.22.4", "d271f595dfd25230b6398354e19d17bb5e2d20130fd2d9bdca7e15f125d43552", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "4aae45a2d60e35b04eea2602440be152fae332901f1fc7a60fc7cb7f0f9a9c5a"},- "prima": {:hex, :prima, "0.2.6", "a40993d108760a711c2da183cff20234497e977f6155aad1ee5e17a3b00a46b6", [:mix], [{:esbuild, "~> 0.7", [hex: :esbuild, repo: "hexpm", optional: false]}, {:phoenix, ">= 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 4.2", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 1.1", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}], "hexpm", "00ec378bd7b0c58d58043e59581f9aa5ba35a0d5031e011e36c449d3a0b7418c"},+ "prima": {:hex, :prima, "0.3.0", "0f2d4068e47951c681a398dfab41f13eac376729732aaffdcd1fdcfe08102720", [:mix], [{:esbuild, "~> 0.7", [hex: :esbuild, repo: "hexpm", optional: false]}, {:phoenix, ">= 1.7.0", [hex: :phoenix, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 4.2", [hex: :phoenix_html, repo: "hexpm", optional: false]}, {:phoenix_live_view, "~> 1.1", [hex: :phoenix_live_view, repo: "hexpm", optional: false]}], "hexpm", "c57849bc9bc084949e25dcb7418b7a76ecd46a25f306e29a18804ef14db2d7e3"},"prom_ex": {:hex, :prom_ex, "1.12.0", "a82cbd5b49964e4d4295ab72a18e007aadd5f4a91630b7c49fad42cc7e49c880", [:mix], [{:absinthe, ">= 1.8.0", [hex: :absinthe, repo: "hexpm", optional: true]}, {:broadway, ">= 1.1.0", [hex: :broadway, repo: "hexpm", optional: true]}, {:ecto, ">= 3.14.0", [hex: :ecto, repo: "hexpm", optional: true]}, {:finch, "~> 0.18", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.4", [hex: :jason, repo: "hexpm", optional: false]}, {:oban, ">= 2.10.0", [hex: :oban, repo: "hexpm", optional: true]}, {:octo_fetch, "~> 0.4", [hex: :octo_fetch, repo: "hexpm", optional: false]}, {:peep, "~> 3.0 or ~> 4.0", [hex: :peep, repo: "hexpm", optional: false]}, {:phoenix, ">= 1.7.0", [hex: :phoenix, repo: "hexpm", optional: true]}, {:phoenix_live_view, ">= 0.20.0", [hex: :phoenix_live_view, repo: "hexpm", optional: true]}, {:plug, ">= 1.16.0", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 2.6.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:telemetry, ">= 1.0.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 1.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}, {:telemetry_metrics_prometheus_core, "~> 1.2", [hex: :telemetry_metrics_prometheus_core, repo: "hexpm", optional: false]}, {:telemetry_poller, "~> 1.1", [hex: :telemetry_poller, repo: "hexpm", optional: false]}], "hexpm", "6357484941489ba2fee64bb1e9f2a1e86309545304f9e90144e3c10e553c958b"},"public_suffix": {:git, "https://github.com/axelson/publicsuffix-elixir", "fa40c243d4b5d8598b90cff268bc4e33f3bb63f1", []},"ranch": {:hex, :ranch, "1.8.1", "208169e65292ac5d333d6cdbad49388c1ae198136e4697ae2f474697140f201c", [:make, :rebar3], [], "hexpm", "aed58910f4e21deea992a67bf51632b6d60114895eb03bb392bb733064594dd0"},diff --git a/test/plausible_web/live/team_management_test.exs b/test/plausible_web/live/team_management_test.exsindex 4f1dd12f73..7819eda9b2 100644--- a/test/plausible_web/live/team_management_test.exs+++ b/test/plausible_web/live/team_management_test.exs@@ -89,10 +89,10 @@ defmodule PlausibleWeb.Live.TeamMangementTest doself_row = "#member-row-#{:erlang.phash2(user.email)}"member_row = "#member-row-#{:erlang.phash2(member.email)}"- assert text_of_element(html, "#{self_row} button") == "Owner"+ assert text_of_element(html, "#{self_row} #{role_el()}") == "Owner"assert text_of_element(html, self_row) =~ "You (SSO)"- assert text_of_element(html, "#{member_row} button") == "Viewer"+ assert text_of_element(html, "#{member_row} #{role_el()}") == "Viewer"assert text_of_element(html, member_row) =~ "SSO"change_role(lv, member.email, "owner")@@ -119,8 +119,7 @@ defmodule PlausibleWeb.Live.TeamMangementTest domember_row1 = find(html, "#{member_el()}:nth-of-type(1)") |> text()assert member_row1 =~ "[email protected]"- assert member_row1 =~ "Invited User"- assert member_row1 =~ "Invitation sent"+ assert member_row1 =~ "Pending invitation"member_row2 = find(html, "#{member_el()}:nth-of-type(2)") |> text()assert member_row2 =~ "#{user.name}"@@ -141,13 +140,13 @@ defmodule PlausibleWeb.Live.TeamMangementTest doself_row = "#member-row-#{:erlang.phash2(user.email)}"member2_row = "#member-row-#{:erlang.phash2(member2.email)}"- assert text_of_element(html, "#{self_row} button") == "Owner"- assert text_of_element(html, "#{member2_row} button") == "Admin"+ assert text_of_element(html, "#{self_row} #{role_el()}") == "Owner"+ assert text_of_element(html, "#{member2_row} #{role_el()}") == "Admin"change_role(lv, member2.email, "viewer")html = render(lv)- assert text_of_element(html, "#{member2_row} button") == "Viewer"+ assert text_of_element(html, "#{member2_row} #{role_el()}") == "Viewer"assert_no_emails_delivered()@@ -164,7 +163,8 @@ defmodule PlausibleWeb.Live.TeamMangementTest doassert elem_count(html, member_el()) == 1- assert text_of_element(html, "#{guest_el()}:first-of-type button") == "Guest"+ assert text_of_element(html, "#{guest_el()}:first-of-type #{role_el()}") ==+ "Guest"change_role(lv, "[email protected]", "viewer")html = render(lv)@@ -235,8 +235,8 @@ defmodule PlausibleWeb.Live.TeamMangementTest doguest_member = find(html, "#{guest_el()}:first-of-type") |> text()- assert pending =~ "Invitation pending"- assert sent =~ "Invitation sent"+ assert pending =~ "Pending invitation"+ assert sent =~ "Pending invitation"assert owner =~ "Owner"assert admin != ""assert guest_member =~ "Guest"@@ -250,8 +250,7 @@ defmodule PlausibleWeb.Live.TeamMangementTest dohtml = render(lv) |> text()- refute html =~ "Invitation pending"- refute html =~ "Invitation sent"+ refute html =~ "Pending invitation"refute html =~ "Guest"html = render(lv)@@ -304,7 +303,7 @@ defmodule PlausibleWeb.Live.TeamMangementTest doguest_member = find(html, "#{guest_el()}:first-of-type") |> text()- assert sent =~ "Invitation sent"+ assert sent =~ "Pending invitation"assert owner =~ "Owner"assert admin != ""assert guest_member =~ "Guest"@@ -317,7 +316,7 @@ defmodule PlausibleWeb.Live.TeamMangementTest dohtml = render(lv) |> text()- refute html =~ "Invitation sent"+ refute html =~ "Pending invitation"refute html =~ "Guest"html = render(lv)@@ -401,7 +400,7 @@ defmodule PlausibleWeb.Live.TeamMangementTest doassert attr_defined?(html, "##{:erlang.phash2(member2.email)}-remove", "data-confirm")end- test "self-demotion role items carry data-confirm, others do not", %{+ test "self-demotion role items carry data-confirm-message, others do not", %{conn: conn,team: team,user: user@@ -416,16 +415,16 @@ defmodule PlausibleWeb.Live.TeamMangementTest doother_hash = :erlang.phash2(member2.email)for role <- ~w(editor billing viewer) do- assert attr_defined?(html, "#option-#{my_hash}-#{role}", "data-confirm"),- "expected data-confirm on self #{role} item"+ assert attr_defined?(html, "#option-#{my_hash}-#{role}", "data-confirm-message"),+ "expected data-confirm-message on self #{role} item"- refute attr_defined?(html, "#option-#{other_hash}-#{role}", "data-confirm"),- "expected no data-confirm on other member #{role} item"+ refute attr_defined?(html, "#option-#{other_hash}-#{role}", "data-confirm-message"),+ "expected no data-confirm-message on other member #{role} item"endfor role <- ~w(owner admin) do- refute attr_defined?(html, "#option-#{my_hash}-#{role}", "data-confirm"),- "expected no data-confirm on self #{role} item"+ refute attr_defined?(html, "#option-#{my_hash}-#{role}", "data-confirm-message"),+ "expected no data-confirm-message on self #{role} item"endend@@ -497,8 +496,8 @@ defmodule PlausibleWeb.Live.TeamMangementTest dodefp change_role(lv, email, role) dolv- |> element(~s|#option-#{:erlang.phash2(email)}-#{role}|)- |> render_click()+ |> element(~s|#role-form-#{:erlang.phash2(email)}|)+ |> render_change(%{"role" => role})enddefp remove_member(lv, email) do@@ -508,14 +507,11 @@ defmodule PlausibleWeb.Live.TeamMangementTest doenddefp add_invite(lv, email, role) do- lv- |> element(~s|#input-role-picker a[phx-value-role="#{role}"]|)- |> render_click()-lv|> element("#team-layout-form")|> render_submit(%{- "input-email" => email+ "input-email" => email,+ "input-role" => role})end@@ -537,4 +533,8 @@ defmodule PlausibleWeb.Live.TeamMangementTest dodefp guest_el() do~s|#guest-list div[data-test-kind="guest"]|end++ defp role_el() do+ ~s|[data-test-id="role"]|+ endend