Skip to content

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

3.0 KB
Raw Blame
/**
  The modules below this comment block are resolved from '../deps' folder,
  which does not exist when running the lint command in GitHub CI
*/

/* eslint-disable import/no-unresolved */
import 'phoenix_html'
import { Socket } from 'phoenix'
import { LiveSocket } from 'phoenix_live_view'
import { Modal, Dropdown, Listbox, Combobox } 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,
    Listbox,
    Confirm,
    CopySnippet,
    MemberRows,
    Combobox
  }

  Hooks.VerificationLifecycle = {
    mounted() {
      // Lets a LiveView tell the client to tear down the websocket connection
      // once it's done with it (e.g. PlausibleWeb.Live.Verification, once its
      // banner has been dismissed) - the server-side process then terminates
      // gracefully.
      this.handleEvent('disconnect-liveview', () => liveSocket.disconnect())

      this.handleEvent('verification-succeeded', ({ queryParams }) => {
        window.dispatchEvent(
          new CustomEvent('verification-finished', { detail: { queryParams } })
        )
      })
    }
  }

  let Uploaders = {}
  Uploaders.S3 = function (entries, onViewError) {
    entries.forEach((entry) => {
      let xhr = new XMLHttpRequest()
      onViewError(() => xhr.abort())
      xhr.onload = () =>
        xhr.status === 200 ? entry.progress(100) : entry.error()
      xhr.onerror = () => entry.error()
      xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable) {
          let percent = Math.round((event.loaded / event.total) * 100)
          if (percent < 100) {
            entry.progress(percent)
          }
        }
      })
      let url = entry.meta.url
      xhr.open('PUT', url, true)
      xhr.send(entry.file)
    })
  }
  let token = csrfToken.getAttribute('content')
  let url = websocketUrl.getAttribute('content')
  let liveUrl = url === '' ? '/live' : new URL('/live', url).href
  let liveSocket = new LiveSocket(liveUrl, Socket, {
    heartbeatIntervalMs: 10000,
    params: { _csrf_token: token },
    hooks: Hooks,
    uploaders: Uploaders,
    dom: {
      // for alpinejs integration
      onBeforeElUpdated(from, to) {
        if (from._x_dataStack) {
          Alpine.clone(from, to)
        }
      }
    }
  })

  topbar.config({
    barColors: { 0: '#303f9f' },
    shadowColor: 'rgba(0, 0, 0, .3)',
    barThickness: 4
  })
  window.addEventListener('phx:page-loading-start', (_info) => topbar.show())
  window.addEventListener('phx:page-loading-stop', (_info) => topbar.hide())
  window.addEventListener('scroll-to-top', () => window.scrollTo(0, 0))

  liveSocket.connect()
  window.liveSocket = liveSocket
}