Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

live view events from master branch #4

Merged
merged 5 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config/.env.dev
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ S3_ENDPOINT=http://localhost:10000
S3_EXPORTS_BUCKET=dev-exports
S3_IMPORTS_BUCKET=dev-imports

VERIFICATION_ENABLED=true
VERIFICATION_ENABLED=false
3 changes: 2 additions & 1 deletion lib/plausible_web/plugs/tracker.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ defmodule PlausibleWeb.Tracker do
"file-downloads",
"pageview-props",
"tagged-events",
"revenue"
"revenue",
"live-view"
]

# Generates Power Set of all variants
Expand Down
2 changes: 1 addition & 1 deletion lib/plausible_web/templates/site/snippet.html.heex
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
id: "snippet_code",
class:
"transition overflow-hidden bg-gray-100 dark:bg-gray-900 appearance-none border border-transparent rounded w-full p-2 pr-6 text-gray-700 dark:text-gray-300 leading-normal appearance-none focus:outline-none focus:bg-white dark:focus:bg-gray-800 focus:border-gray-400 dark:focus:border-gray-500 text-xs mt-4 resize-none",
value: render_snippet(@site),
value: render_snippet(@site, ["live-view"]),
rows: 3,
readonly: "readonly"
) %>
Expand Down
7 changes: 4 additions & 3 deletions lib/plausible_web/views/site_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ defmodule PlausibleWeb.SiteView do
Plausible.Sites.shared_link_url(site, link)
end

def render_snippet(site) do
tracker = "#{plausible_url()}/js/script.js"
def render_snippet(site, addons \\ []) do
filename = Enum.join(["script"] ++ addons ++ ["js"], ".")
src = "#{plausible_url()}/js/#{filename}"

"""
<script defer data-domain="#{site.domain}" src="#{tracker}"></script>
<script defer data-domain="#{site.domain}" src="#{src}"></script>
"""
end

Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ defmodule Plausible.MixProject do
docs: docs(),
app: :plausible,
version: System.get_env("APP_VERSION", "0.0.1"),
elixir: "~> 1.15",
elixir: "~> 1.17",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() in [:prod, :ce],
aliases: aliases(),
Expand Down
2 changes: 1 addition & 1 deletion tracker/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function compilefile(input, output, templateVars = {}) {
}
}

const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue"]
const base_variants = ["hash", "outbound-links", "exclusions", "compat", "local", "manual", "file-downloads", "pageview-props", "tagged-events", "revenue", "live-view"]
const variants = [...g.clone.powerSet(base_variants)].filter(a => a.length > 0).map(a => a.sort());

compilefile(relPath('src/plausible.js'), relPath('../priv/tracker/js/plausible.js'))
Expand Down
23 changes: 23 additions & 0 deletions tracker/src/plausible.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,27 @@
{{#if (any outbound_links file_downloads tagged_events)}}
{{> customEvents}}
{{/if}}

{{#if live_view}}
{{#unless manual}}
window.addEventListener('phx:navigate', info => trigger('pageview', {u: info.detail.href}));
{{/unless}}

['phx-click', 'phx-change', 'phx-submit', 'phx-viewport-top', 'phx-viewport-bottom', 'phx-mounted', 'phx-connected', 'phx-disconnected'].map((name) => {
window.addEventListener(name, info => trigger('phx-event', {props: {event: name, detail: new URLSearchParams(info.detail || {}).toString()}}));
});

// form submit event
window.addEventListener("submit", e => trigger("js-submit", {props: {dom_id: e.target.id, ...Object.fromEntries(new FormData(e.target).entries())}}));

//track socket activity
if (window.liveSocket)
window.liveSocket.socket.logger = (kind, msg, data) => {
if ((kind === 'push') && !msg.includes("phoenix heartbeat")){
trigger('phx-push', {props: {msg, ...data}});
}
}
else
console && console.error("No liveSocket initialized")
{{/if}}
})();
20 changes: 20 additions & 0 deletions tracker/test/fixtures/live-view.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Plausible Playwright LiveView tests</title>
<script>window.liveSocket = {socket: {}}</script>
<script>window.liveSocket = {socket: {}}</script>
<script defer src="/tracker/js/plausible.live-view.local.manual.js"></script>
</head>
<body>
LiveView-related tests
<form id="main-form" onsubmit="event.preventDefault();">
<input type="text" name="user[name]" value="name" />
<input type="email" name="user[email]" value="[email protected]" />
<input type="submit" id="main-form-btn" />
</form>
</body>
</html>
28 changes: 28 additions & 0 deletions tracker/test/live-view.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const { mockRequest, expectCustomEvent } = require('./support/test-utils');
const { expect, test } = require('@playwright/test');

test.describe('script.live-view.js', () => {
let plausibleRequestMock;

test.beforeEach(async ({ page }) => {
plausibleRequestMock = mockRequest(page, '/api/event')
await page.goto('/live-view.html');
});

test('Sends pageview', async ({ page }) => {
await page.evaluate(() => window.dispatchEvent(new CustomEvent("phx:navigate", { detail: { href: "/navigate" } })))
const request = await plausibleRequestMock;
expect(request.postDataJSON().u).toEqual("/navigate")
expectCustomEvent(request, 'pageview', {})
});

test('Sends phx-event', async ({ page }) => {
await page.evaluate(() => window.liveSocket.socket.logger('push', '_message', { a: 1 }))
expectCustomEvent(await plausibleRequestMock, 'phx-event', { a: 1 })
});

test('Sends submit event', async ({ page }) => {
await (await page.locator("#main-form-btn")).click()
expectCustomEvent(await plausibleRequestMock, 'js-submit', { 'user[name]': "name", dom_id: "main-form" })
});
});
Loading