Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineComponent, html, type RefOrValue, type SRef, sref } from 'regor'
import type { DashboardScope } from '../lib/dashboard/scope'
import type { DashboardStatus } from '../lib/dashboard/state'
import type { DashboardModel } from '../lib/dashboard-model'
import { filterExpression } from '../lib/format'
import { filterExpression, formatFilterLabel } from '../lib/format'

export interface DashboardFilters {
filterOpen: SRef<boolean>
Expand Down Expand Up @@ -147,10 +147,10 @@ const reportControls = html`<div>
r-for="(filter,index) in dashboard.filters"
class="filter-chip"
variant="none"
:ariaLabel="'Remove filter ' + filter"
:ariaLabel="'Remove filter ' + formatFilterLabel(filter)"
@click="dashboard.removeFilter(index)"
>
{{ filter }} ×
{{ formatFilterLabel(filter) }} ×
</Btn>
</div>
<dialog
Expand Down Expand Up @@ -205,6 +205,7 @@ const reportControls = html`<div>

export interface ReportControls {
dashboard: RefOrValue<DashboardModel>
formatFilterLabel: typeof formatFilterLabel
rangeOptions: FormSelectOption[]
compareOptions: FormSelectOption[]
dimensionOptions: FormSelectOption[]
Expand All @@ -215,6 +216,7 @@ export function defineReportControlsComponent() {
props: ['dashboard'],
context: (head) => ({
...head.props,
formatFilterLabel,
rangeOptions: [
{ value: 'today', label: 'Today' },
{ value: 'yesterday', label: 'Yesterday' },
Expand Down
41 changes: 41 additions & 0 deletions apps/ZoneTree.Analytics.Dashboard/ui/content/lib/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,47 @@ export const change = (
current == null || previous == null || previous === 0
? null
: (current - previous) / previous

const utf8Escapes =
/%[cd][0-9a-f]%[89ab][0-9a-f]|%e[0-9a-f](?:%[89ab][0-9a-f]){2}|%f[0-4](?:%[89ab][0-9a-f]){3}/gi
const unsafeLabelCharacters = /[\p{Cc}\p{Bidi_Control}\u2028\u2029]/gu

function decodePathCharacter(encoded: string): string {
try {
const character = decodeURIComponent(encoded)
return character.search(unsafeLabelCharacters) < 0 ? character : encoded
} catch {
return encoded
}
}

// Match the .NET PagePath formatter. Use the original value for report actions.
export function formatPagePath(path: string): string {
const firstEscape = path.indexOf('%')
if (firstEscape >= 0) {
const suffix = path.search(/[?#]/)
if (suffix < 0) path = path.replace(utf8Escapes, decodePathCharacter)
else if (firstEscape < suffix)
path =
path.slice(0, suffix).replace(utf8Escapes, decodePathCharacter) +
path.slice(suffix)
}
return path.replace(unsafeLabelCharacters, encodeURIComponent)
}

export function formatDimensionValue(dimension: string, value: string): string {
return dimension === 'page' || dimension === 'entry_page'
? formatPagePath(value)
: value
}

export function formatFilterLabel(filter: string): string {
const prefix = /^(?:page|entry_page)(?:==|!=(?!~)|\^=|~=)/.exec(filter)?.[0]
return prefix && !filter.includes('|')
? prefix + formatPagePath(filter.slice(prefix.length))
: filter
}

export function csv(rows: unknown[][]): string {
return (
'\uFEFF' +
Expand Down
14 changes: 10 additions & 4 deletions apps/ZoneTree.Analytics.Dashboard/ui/content/lib/reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ import type {
QueryResult,
Summary,
} from './contracts'
import { change, duration, number, percent } from './format'
import {
change,
duration,
formatDimensionValue,
number,
percent,
} from './format'

export const reportInfo = {
overview: {
Expand Down Expand Up @@ -114,7 +120,7 @@ export function countryName(value: string | null) {
const drill = (
dimension: string,
value: string | null,
text = value,
text = value == null ? null : formatDimensionValue(dimension, value),
): Cell => ({
text: text || (value === '' ? '(empty)' : 'Unknown'),
...(value != null ? { dimension, value } : {}),
Expand Down Expand Up @@ -184,7 +190,7 @@ export function breakdownTable(
drill(
dimension,
row.value,
dimension === 'country' ? countryName(row.value) : row.value,
dimension === 'country' ? countryName(row.value) : undefined,
),
numeric(number(row.visitors)),
numeric(percent(row.visitorShare)),
Expand Down Expand Up @@ -277,7 +283,7 @@ export function queryTable(result: QueryResult): TableModel {
cells: [
...(bucket ? [{ text: row.bucket || '' }] : []),
...result.groupBy.map((key) => ({
text: row.dimensions?.[key] ?? 'Unknown',
text: formatDimensionValue(key, row.dimensions?.[key] ?? 'Unknown'),
})),
...result.metrics.map((key) => numeric(number(row.values[key]))),
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import {
unref,
} from 'regor'
import type { DashboardModel } from '../lib/dashboard-model'
import { formatPagePath } from '../lib/format'

export interface OverviewTopPages {
dashboard: DashboardModel | SRef<DashboardModel>
max: ComputedRef<number>
barWidth: (views: number) => string
filterPage: (page: string | null) => void
formatPagePath: typeof formatPagePath
}

const template = html`<Panel>
Expand All @@ -33,7 +35,10 @@ const template = html`<Panel>
:style="{'--bar-width': barWidth(row.pageViews)}"
@click="filterPage(row.page)"
>
<span class="row-name">{{ row.page || 'Unknown' }}</span>
<span
class="row-name"
r-text="row.page ? formatPagePath(row.page) : 'Unknown'"
></span>
<span class="row-count">{{ dashboard.number(row.pageViews) }}</span>
</button>
</div>
Expand All @@ -55,6 +60,7 @@ export function defineOverviewTopPages() {
return {
...head.props,
max,
formatPagePath,
barWidth: (views) =>
`${Math.min(100, Math.max(0, (views / max()) * 80))}%`,
filterPage: (page) => {
Expand Down
2 changes: 1 addition & 1 deletion apps/ZoneTree.Analytics.Dashboard/ui/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zonetree-analytics-dashboard",
"version": "1.0.4",
"version": "1.0.5",
"private": true,
"type": "module",
"scripts": {
Expand Down
78 changes: 78 additions & 0 deletions apps/ZoneTree.Analytics.Dashboard/ui/tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@ import {
csv,
duration,
filterExpression,
formatFilterLabel,
formatPagePath,
percent,
} from '../content/lib/format'
import { pagesTable, queryTable } from '../content/lib/reports'

const scope: Scope = {
site: 'store',
Expand Down Expand Up @@ -93,6 +96,81 @@ test('null and zero stay distinct; CSV protects tracked strings against spreadsh
assert.equal(filterExpression('page', '~=', '/blog'), 'page~=/blog')
assert.throws(() => filterExpression('page', '==', '/a,/b'))
})
test('page labels decode UTF-8 without changing delimiters, malformed escapes, or the query', () => {
for (const [value, label] of [
['', ''],
['/docs/already-应用', '/docs/already-应用'],
['/Blog/net-%E5%BA%94%E7%94%A8', '/Blog/net-应用'],
['/caf%c3%a9/%F0%9F%8C%8D', '/café/🌍'],
[
'/caf%C3%A9%2F%3F%23%25%5C%3C%0A%252F+%20',
'/café%2F%3F%23%25%5C%3C%0A%252F+%20',
],
['/caf%C3%A9?q=%E5%BA%94#%C3%A9', '/café?q=%E5%BA%94#%C3%A9'],
['/ascii?q=%C3%A9', '/ascii?q=%C3%A9'],
['/caf%C3%A9#%C3%A9', '/café#%C3%A9'],
[
'/%C0%AF/%E0%80%AF/%ED%A0%80/%F4%90%80%80/%E2%98/%ZZ/%/%C3%A9',
'/%C0%AF/%E0%80%AF/%ED%A0%80/%F4%90%80%80/%E2%98/%ZZ/%/é',
],
[
'/%c2%85/%e2%80%ae%E2%81%A6%E2%80%A8%C3%A9',
'/%c2%85/%e2%80%ae%E2%81%A6%E2%80%A8é',
],
['/a\u202Eb\u0000?x=\u0085#\u2029', '/a%E2%80%AEb%00?x=%C2%85#%E2%80%A9'],
]) {
assert.equal(formatPagePath(value), label)
assert.equal(formatPagePath(label), label)
}
})
test('page and query tables format labels while keeping original filter and export values', () => {
const page = '/blog/%E5%BA%94%E7%94%A8%2Ftips'
const label = '/blog/应用%2Ftips'
const pages = pagesTable([
{
page,
visitors: 5,
pageViews: 7,
entrances: 3,
exits: 1,
exitRate: 1 / 7,
botHits: null,
},
])
assert.deepEqual(pages.rows[0].cells[0], {
text: label,
dimension: 'page',
value: page,
})
assert.equal(pages.exportRows[1][0], page)
const filter = filterExpression('page', '==', page)
assert.equal(formatFilterLabel(filter), `page==${label}`)
assert.equal(formatFilterLabel(`source==${page}`), `source==${page}`)
assert.equal(formatFilterLabel(`${filter}|/`), `${filter}|/`)

const query = queryTable({
from: '2026-11-01',
to: '2026-11-02',
timeZone: 'UTC',
interval: 'none',
groupBy: ['page', 'entry_page', 'source'],
metrics: ['pageviews'],
totalRows: 1,
totals: { values: { pageviews: 7 } },
rows: [
{
dimensions: { page, entry_page: page, source: page },
values: { pageviews: 7 },
},
],
plan: { complete: true, warnings: [], steps: [], rollupSuggestions: [] },
})
assert.deepEqual(
query.rows[0].cells.map((cell) => cell.text),
[label, label, page, '7'],
)
assert.deepEqual(query.exportRows[1], [page, page, page, 7])
})
test('demo summary, pages, devices and time series share one dataset and honor filters', async () => {
const demo = new DemoClient()
const signal = new AbortController().signal
Expand Down
55 changes: 53 additions & 2 deletions apps/ZoneTree.Analytics.Dashboard/ui/tests/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import assert from 'node:assert/strict'
import { setTimeout as pause } from 'node:timers/promises'
import type { Browser } from 'playwright'
import { chromium, request } from 'playwright'
import { inject, test } from 'vitest'
import { inject, test, vi } from 'vitest'
import { validateConfig } from '../content/lib/config'
import type { SummaryReport } from '../content/lib/contracts'
import type { Page, Report, SummaryReport } from '../content/lib/contracts'
import {
dashboardConfigPath,
dashboardEventPath,
Expand Down Expand Up @@ -143,6 +143,57 @@ test('dashboard visits record accepted beacons in the live .NET engine', async (
after.pageViews >= before.pageViews + 2,
'Dashboard visits must increase real page views',
)

const pageKey = '/blog/%E5%BA%94%E7%94%A8%2Ftips'
const pageLabel = '/blog/应用%2Ftips'
const beaconStatus = await page.evaluate(
async ({ endpoint, path }) => {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: JSON.stringify({ n: 'pageview', u: location.origin + path }),
})
return response.status
},
{ endpoint: dashboardEventPath, path: pageKey },
)
assert.equal(beaconStatus, 202)
await vi.waitFor(
async () => {
const result = await http.get(`${config.apiBaseUrl}/pages`, {
params: {
site: 'dashboard-usage',
range: 'today',
tz: config.timeZone,
},
})
assert.ok(result.ok())
const pages = (await result.json()) as Report<Page>
assert.ok(pages.rows.some((row) => row.page === pageKey))
},
{ timeout: 10_000, interval: 200 },
)
await page.goto(new URL('?site=dashboard-usage&range=today', base).href)
await page
.locator('.row-name')
.getByText(pageLabel, { exact: true })
.waitFor()
await page.goto(
new URL('pages/?site=dashboard-usage&range=today', base).href,
)
const filtered = page.waitForRequest((request) => {
const url = new URL(request.url())
return (
url.pathname === `${reportPath}pages` &&
url.searchParams.getAll('filter').includes(`page==${pageKey}`)
)
})
await page.getByRole('button', { name: pageLabel, exact: true }).click()
await filtered
await page
.getByRole('button', { name: `Remove filter page==${pageLabel}` })
.waitFor()

console.log(
`Tracker checks passed: dashboard navigation sent accepted beacons; page views increased from ${before.pageViews} to ${after.pageViews}.`,
)
Expand Down
2 changes: 2 additions & 0 deletions docs-site/content/docs/guides/web-reports/web-reports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ Disabled fields remain null, not zero. Exit-page reports require page-flow metri

A summary exposes `Summary`; list and time-series reports expose `Rows`. Use `TotalRows` for pagination and choose a time interval appropriate to the chart.

The dashboard displays Unicode page paths as readable labels. For your own reports, use `PagePath.FormatForDisplay(row.Page)` and render the result as plain text. Use `row.Page` for filters and exports so the values still match the stored page keys. This works for historical rows too.

Keep the selected range and filters visible to readers. Check plan warnings when a range extends beyond available history, and distinguish unavailable metrics from zero activity.

## Related pages
Expand Down
2 changes: 1 addition & 1 deletion docs-site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"private": true,
"type": "module",
"name": "analytics.zonetree.dev",
"version": "1.0.4",
"version": "1.0.5",
"scripts": {
"check": "tsc --noEmit",
"build": "purestack build --content ./content --clean",
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
matching ZoneTree.Analytics. Pass VersionSuffix (for example preview.1) to pack a pre-release.
-->
<PropertyGroup>
<VersionPrefix>1.0.4</VersionPrefix>
<VersionPrefix>1.0.5</VersionPrefix>
<IsPackable>false</IsPackable>
<Authors>Ahmed Yasin Koculu</Authors>
<Company>ZoneTree</Company>
Expand Down
28 changes: 28 additions & 0 deletions src/ZoneTree.Analytics.UnitTests/PagePathTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using ZoneTree.Analytics.Web;

namespace ZoneTree.Analytics.UnitTests;

public sealed class PagePathTests
{
[TestCase(null, null)]
[TestCase("", "")]
[TestCase("/docs/already-应用", "/docs/already-应用")]
[TestCase("/Blog/net-%E5%BA%94%E7%94%A8", "/Blog/net-应用")]
[TestCase("/caf%c3%a9/%F0%9F%8C%8D", "/café/🌍")]
[TestCase("/caf%C3%A9%2F%3F%23%25%5C%3C%0A%252F+%20", "/café%2F%3F%23%25%5C%3C%0A%252F+%20")]
[TestCase("/caf%C3%A9?q=%E5%BA%94#%C3%A9", "/café?q=%E5%BA%94#%C3%A9")]
[TestCase("/ascii?q=%C3%A9", "/ascii?q=%C3%A9")]
[TestCase("/caf%C3%A9#%C3%A9", "/café#%C3%A9")]
[TestCase("/%C0%AF/%E0%80%AF/%ED%A0%80/%F4%90%80%80/%E2%98/%ZZ/%/%C3%A9", "/%C0%AF/%E0%80%AF/%ED%A0%80/%F4%90%80%80/%E2%98/%ZZ/%/é")]
[TestCase("/%c2%85/%e2%80%ae%E2%81%A6%E2%80%A8%C3%A9", "/%c2%85/%e2%80%ae%E2%81%A6%E2%80%A8é")]
[TestCase("/a\u202Eb\u0000?x=\u0085#\u2029", "/a%E2%80%AEb%00?x=%C2%85#%E2%80%A9")]
public void FormatsLabelsWithoutChangingPathStructure(string path, string label)
{
var formatted = PagePath.FormatForDisplay(path);
Assert.Multiple(() =>
{
Assert.That(formatted, Is.EqualTo(label));
Assert.That(PagePath.FormatForDisplay(formatted), Is.EqualTo(label));
});
}
}
Loading
Loading