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
Improvements to LV dashboard scaffolding (#5937)
Adrian Gruntkowskiee906f4033a4
diff --git a/assets/js/dashboard/index.tsx b/assets/js/dashboard/index.tsxindex 81b46a180e..d0c6fc0a36 100644--- a/assets/js/dashboard/index.tsx+++ b/assets/js/dashboard/index.tsx@@ -48,7 +48,7 @@ function DashboardStats({onLiveNavigate as EventListener)}- }, [navigate])+ }, [onLiveNavigate])const statsBoxClass ='relative min-h-[436px] w-full mt-5 p-4 flex flex-col bg-white dark:bg-gray-900 shadow-sm rounded-md md:min-h-initial md:h-27.25rem md:w-[calc(50%-10px)] md:ml-[10px] md:mr-[10px] first:ml-0 last:mr-0'diff --git a/assets/js/liveview/dashboard_root.js b/assets/js/liveview/dashboard_root.jsnew file mode 100644index 0000000000..42af690f10--- /dev/null+++ b/assets/js/liveview/dashboard_root.js@@ -0,0 +1,57 @@+/**+ * Hook widget delegating navigation events to and from React.+ * Necessary to emulate navigation events in LiveView with pushState+ * manipulation disabled.+ */++import { buildHook } from './hook_builder'++export default buildHook({+ initialize() {+ this.url = window.location.href++ this.addListener('click', document.body, (e) => {+ const type = e.target.dataset.type || null++ if (type === 'dashboard-link') {+ this.url = e.target.href+ const uri = new URL(this.url)+ // Domain is dropped from URL prefix, because that's what react-dom-router+ // expects.+ const path = '/' + uri.pathname.split('/').slice(2).join('/')+ this.el.dispatchEvent(+ new CustomEvent('dashboard:live-navigate', {+ bubbles: true,+ detail: { path: path, search: uri.search }+ })+ )++ this.pushEvent('handle_dashboard_params', { url: this.url })++ e.preventDefault()+ }+ })++ // Browser back and forward navigation triggers that event.+ this.addListener('popstate', window, () => {+ if (this.url !== window.location.href) {+ this.pushEvent('handle_dashboard_params', {+ url: window.location.href+ })+ }+ })++ // Navigation events triggered from liveview are propagated via this+ // handler.+ this.addListener('dashboard:live-navigate-back', window, (e) => {+ if (+ typeof e.detail.search === 'string' &&+ this.url !== window.location.href+ ) {+ this.pushEvent('handle_dashboard_params', {+ url: window.location.href+ })+ }+ })+ }+})diff --git a/assets/js/liveview/dashboard_tabs.js b/assets/js/liveview/dashboard_tabs.jsnew file mode 100644index 0000000000..0f645a7f01--- /dev/null+++ b/assets/js/liveview/dashboard_tabs.js@@ -0,0 +1,44 @@+/**+ * Hook widget for optimistic loading of tabs and+ * client-side persistence of selection using localStorage.+ */++import { buildHook } from './hook_builder'++function getDomain(url) {+ const uri = typeof url === 'object' ? url : new URL(url)+ return uri.pathname.split('/')[1]+}++export default buildHook({+ initialize() {+ const domain = getDomain(window.location.href)++ this.addListener('click', this.el, (e) => {+ const button = e.target.closest('button')+ const tab = button && button.dataset.tab++ if (tab) {+ const label = button.dataset.label+ const storageKey = button.dataset.storageKey+ const activeClasses = button.dataset.activeClasses+ const inactiveClasses = button.dataset.inactiveClasses+ const title = this.el+ .closest('[data-tile]')+ .querySelector('[data-title]')++ title.innerText = label++ this.el.querySelectorAll(`button[data-tab] span`).forEach((s) => {+ s.className = inactiveClasses+ })++ button.querySelector('span').className = activeClasses++ if (storageKey) {+ localStorage.setItem(`${storageKey}__${domain}`, tab)+ }+ }+ })+ }+})diff --git a/assets/js/liveview/hook_builder.js b/assets/js/liveview/hook_builder.jsnew file mode 100644index 0000000000..48c998d7bf--- /dev/null+++ b/assets/js/liveview/hook_builder.js@@ -0,0 +1,53 @@+export function buildHook({ initialize, cleanup }) {+ cleanup = cleanup || function () {}++ return {+ mounted() {+ this.initialize()+ },++ updated() {+ this.initialize()+ },++ reconnected() {+ this.initialize()+ },++ destroyed() {+ this.cleanup()+ },++ initialize() {+ this.cleanup()+ initialize.bind(this)()+ },++ cleanup() {+ this.removeListeners()+ cleanup.bind(this)()+ },++ addListener(eventName, listener, callback) {+ this.listeners = this.listeners || []++ listener.addEventListener(eventName, callback)++ this.listeners.push({+ element: listener,+ event: eventName,+ callback: callback+ })+ },++ removeListeners() {+ if (this.listeners) {+ this.listeners.forEach((l) => {+ l.element.removeEventListener(l.event, l.callback)+ })++ this.listeners = null+ }+ }+ }+}diff --git a/assets/js/liveview/live_dashboard.js b/assets/js/liveview/live_dashboard.jsdeleted file mode 100644index 222ab1c0ed..0000000000--- a/assets/js/liveview/live_dashboard.js+++ /dev/null@@ -1,156 +0,0 @@-/**- * Hook used by LiveView dashboard.- *- * Defines various widgets to use by various dashboard specific components.- */--const WIDGETS = {- // Hook widget delegating navigation events to and from React.- // Necessary to emulate navigation events in LiveView with pushState- // manipulation disabled.- 'dashboard-root': {- initialize: function () {- this.url = window.location.href-- addListener.bind(this)('click', document.body, (e) => {- const type = e.target.dataset.type || null-- if (type === 'dashboard-link') {- this.url = e.target.href- const uri = new URL(this.url)- // Domain is dropped from URL prefix, because that's what react-dom-router- // expects.- const path = '/' + uri.pathname.split('/').slice(2).join('/')- this.el.dispatchEvent(- new CustomEvent('dashboard:live-navigate', {- bubbles: true,- detail: { path: path, search: uri.search }- })- )-- this.pushEvent('handle_dashboard_params', { url: this.url })-- e.preventDefault()- }- })-- // Browser back and forward navigation triggers that event.- addListener.bind(this)('popstate', window, () => {- if (this.url !== window.location.href) {- this.pushEvent('handle_dashboard_params', {- url: window.location.href- })- }- })-- // Navigation events triggered from liveview are propagated via this- // handler.- addListener.bind(this)('dashboard:live-navigate-back', window, (e) => {- if (- typeof e.detail.search === 'string' &&- this.url !== window.location.href- ) {- this.pushEvent('handle_dashboard_params', {- url: window.location.href- })- }- })- },- cleanup: function () {- removeListeners.bind(this)()- }- },- // Hook widget for optimistic loading of tabs and- // client-side persistence of selection using localStorage.- tabs: {- initialize: function () {- const domain = getDomain(window.location.href)-- addListener.bind(this)('click', this.el, (e) => {- const button = e.target.closest('button')- const tab = button && button.dataset.tab-- if (tab) {- const label = button.dataset.label- const storageKey = button.dataset.storageKey- const activeClasses = button.dataset.activeClasses- const inactiveClasses = button.dataset.inactiveClasses- const title = this.el- .closest('[data-tile]')- .querySelector('[data-title]')-- title.innerText = label-- this.el.querySelectorAll(`button[data-tab] span`).forEach((s) => {- s.className = inactiveClasses- })-- button.querySelector('span').className = activeClasses-- if (storageKey) {- localStorage.setItem(`${storageKey}__${domain}`, tab)- }- }- })- },- cleanup: function () {- removeListeners.bind(this)()- }- }-}--function getDomain(url) {- const uri = typeof url === 'object' ? url : new URL(url)- return uri.pathname.split('/')[1]-}--function addListener(eventName, listener, callback) {- this.listeners = this.listeners || []-- listener.addEventListener(eventName, callback)-- this.listeners.push({- element: listener,- event: eventName,- callback: callback- })-}--function removeListeners() {- if (this.listeners) {- this.listeners.forEach((l) => {- l.element.removeEventListener(l.event, l.callback)- })-- this.listeners = null- }-}--export default {- mounted() {- this.widget = this.el.getAttribute('data-widget')-- this.initialize()- },-- updated() {- this.initialize()- },-- reconnected() {- this.initialize()- },-- destroyed() {- this.cleanup()- },-- initialize() {- this.cleanup()- WIDGETS[this.widget].initialize.bind(this)()- },-- cleanup() {- WIDGETS[this.widget].cleanup.bind(this)()- }-}diff --git a/assets/js/liveview/live_socket.js b/assets/js/liveview/live_socket.jsindex 3ac14c51fc..627eaff7a4 100644--- a/assets/js/liveview/live_socket.js+++ b/assets/js/liveview/live_socket.js@@ -8,7 +8,8 @@ import 'phoenix_html'import { Socket } from 'phoenix'import { LiveSocket } from 'phoenix_live_view'import { Modal, Dropdown } from 'prima'-import LiveDashboard from './live_dashboard'+import DashboardRoot from './dashboard_root'+import DashboardTabs from './dashboard_tabs.js'import topbar from 'topbar'/* eslint-enable import/no-unresolved */@@ -21,7 +22,7 @@ let disablePushStateFlag = document.querySelector()let domain = document.querySelector("meta[name='dashboard-domain']")if (csrfToken && websocketUrl) {- let Hooks = { Modal, Dropdown, LiveDashboard }+ let Hooks = { Modal, Dropdown, DashboardRoot, DashboardTabs }Hooks.Metrics = {mounted() {this.handleEvent('send-metrics', ({ event_name }) => {diff --git a/lib/plausible_web/live/components/dashboard/base.ex b/lib/plausible_web/live/components/dashboard/base.exindex 8db5e45c7b..041cac215d 100644--- a/lib/plausible_web/live/components/dashboard/base.ex+++ b/lib/plausible_web/live/components/dashboard/base.ex@@ -19,7 +19,7 @@ defmodule PlausibleWeb.Components.Dashboard.Base do~H"""<.linkdata-type="dashboard-link"- href={@url}+ patch={@url}{@rest}>{render_slot(@inner_block)}diff --git a/lib/plausible_web/live/components/dashboard/tile.ex b/lib/plausible_web/live/components/dashboard/tile.exindex 426f9223da..b09ef681d7 100644--- a/lib/plausible_web/live/components/dashboard/tile.ex+++ b/lib/plausible_web/live/components/dashboard/tile.ex@@ -16,21 +16,18 @@ defmodule PlausibleWeb.Components.Dashboard.Tile doslot :inner_block, required: truedef tile(assigns) do- assigns = assign(assigns, :update_mode, if(assigns.connected?, do: "ignore", else: "replace"))-~H"""<div data-tile id={@id}>- <div data-tile class="w-full flex justify-between h-full">- <div id={@id <> "-title"} class="flex gap-x-1" phx-update={@update_mode}>+ <div class="w-full flex justify-between h-full">+ <div id={@id <> "-title"} class="flex gap-x-1" phx-update="ignore"><h3 data-title class="font-bold dark:text-gray-100">{@title}</h3></div><div:if={@tabs != []}id={@id <> "-tabs"}- phx-update={@update_mode}- phx-hook="LiveDashboard"- data-widget="tabs"+ phx-update="ignore"+ phx-hook="DashboardTabs"class="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2 items-baseline">{render_slot(@tabs)}@@ -42,22 +39,6 @@ defmodule PlausibleWeb.Components.Dashboard.Tile do"""end- attr :id, :string, required: true- slot :inner_block, required: true-- def tabs(assigns) do- ~H"""- <div- id={@id}- phx-hook="LiveDashboard"- data-widget="tabs"- class="flex text-xs font-medium text-gray-500 dark:text-gray-400 space-x-2 items-baseline"- >- {render_slot(@inner_block)}- </div>- """- end-attr :label, :string, required: trueattr :value, :string, required: trueattr :active, :string, required: truediff --git a/lib/plausible_web/live/dashboard.ex b/lib/plausible_web/live/dashboard.exindex 58685e9524..a1729f7355 100644--- a/lib/plausible_web/live/dashboard.ex+++ b/lib/plausible_web/live/dashboard.ex@@ -47,7 +47,7 @@ defmodule PlausibleWeb.Live.Dashboard dodef render(assigns) do~H"""- <div id="live-dashboard-container" phx-hook="LiveDashboard" data-widget="dashboard-root">+ <div id="live-dashboard-container" phx-hook="DashboardRoot"><.portal_wrapper id="pages-breakdown-live-container" target="#pages-breakdown-live"><.live_componentmodule={PlausibleWeb.Live.Dashboard.Pages}