Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d0bc3f59d | ||
|
|
60d5155fd2 | ||
|
|
3518ac9ac7 | ||
|
|
5c2433b766 | ||
|
|
2959f971bc | ||
|
|
8ee22de060 | ||
|
|
9be1491f0e | ||
|
|
29c1dc64ed | ||
|
|
a27958117f | ||
|
|
56fd5f854d | ||
|
|
932aee4404 | ||
|
|
ca1c0d5a6f | ||
|
|
9cbc4ab59d | ||
|
|
7aa2abbf8f | ||
|
|
eddb3f22f3 | ||
|
|
1702281dbf | ||
|
|
38b894a789 | ||
|
|
06409cdaac | ||
|
|
7ba6094360 | ||
|
|
c59ab2f058 | ||
|
|
078e80591b | ||
|
|
6563eebdba | ||
|
|
cac74ebb6b | ||
|
|
8b1bb6f994 | ||
|
|
3173a113b6 | ||
|
|
a21f919601 | ||
|
|
158b5f1961 | ||
|
|
f9ce0a4f3b | ||
|
|
2d595f8c15 | ||
|
|
b1fc8e24d7 | ||
|
|
c5cf799f68 | ||
|
|
a5edc7b3b6 | ||
|
|
09ebc63690 | ||
|
|
2868843028 | ||
|
|
6fcebaea3f | ||
|
|
4a48d08a19 | ||
|
|
e3e29251ca | ||
|
|
8affc41289 | ||
|
|
2de4717230 | ||
|
|
563e8fcaf2 | ||
|
|
921a5484a2 | ||
|
|
0e2e52fa45 | ||
|
|
075848f782 | ||
|
|
7b8899af92 |
+109
-48
@@ -20,11 +20,15 @@ Struct dumped to disk — separate from the kanta content database, path from
|
|||||||
## What is collected
|
## What is collected
|
||||||
|
|
||||||
The client (`pagerite.js`) POSTs fire-and-forget pings to `/_a` with
|
The client (`pagerite.js`) POSTs fire-and-forget pings to `/_a` with
|
||||||
`{fr, to}` (`fr` = source path):
|
`fr`, `to`, `hide` and `read` as query parameters (`fr` = source path;
|
||||||
|
falsy values are omitted):
|
||||||
|
|
||||||
- **Initial page load**: `to` is the loaded path. This ping is what starts
|
- **Initial page load**: only `to` — the loaded path — is sent, never `fr`
|
||||||
|
(an `fr` equal to `to` would log a bogus self-transition when a session
|
||||||
|
already exists, e.g. a second tab). This ping is what starts
|
||||||
the visit and counts the entry page view — the document GET alone records
|
the visit and counts the entry page view — the document GET alone records
|
||||||
nothing, so bots and admin browsing never register. JS-running crawlers
|
nothing, so bots never register (admin browsing does register, but
|
||||||
|
flagged `hide`; see **Admins** below). JS-running crawlers
|
||||||
(Googlebot, GoogleOther, Applebot, ...) do ping, but their User-Agent
|
(Googlebot, GoogleOther, Applebot, ...) do ping, but their User-Agent
|
||||||
gives them away: pings whose UA matches `_is_bot_ua` (anything calling
|
gives them away: pings whose UA matches `_is_bot_ua` (anything calling
|
||||||
itself a "bot", plus known exceptions such as GoogleOther) are ignored
|
itself a "bot", plus known exceptions such as GoogleOther) are ignored
|
||||||
@@ -34,7 +38,8 @@ The client (`pagerite.js`) POSTs fire-and-forget pings to `/_a` with
|
|||||||
abuse rules regardless. Reloads are not
|
abuse rules regardless. Reloads are not
|
||||||
visits: the ping is skipped (PerformanceNavigationTiming `reload`), so a
|
visits: the ping is skipped (PerformanceNavigationTiming `reload`), so a
|
||||||
refresh neither counts a second view nor logs a self-transition. The GET
|
refresh neither counts a second view nor logs a self-transition. The GET
|
||||||
handler stashes a cross-origin https `Referer` (origin part only) and any
|
handler stashes a cross-origin https `Referer` (origin part only —
|
||||||
|
unavailable to JS once the page has loaded) and any
|
||||||
`utm_*` query parameters in in-memory IP tables, consumed by the ping that
|
`utm_*` query parameters in in-memory IP tables, consumed by the ping that
|
||||||
starts the visit; internal or absent referers never touch the referer table.
|
starts the visit; internal or absent referers never touch the referer table.
|
||||||
- **Internal fetch-navigations**: `to` is the target path, sent only after
|
- **Internal fetch-navigations**: `to` is the target path, sent only after
|
||||||
@@ -45,17 +50,26 @@ The client (`pagerite.js`) POSTs fire-and-forget pings to `/_a` with
|
|||||||
back), so the exit URL is not necessarily the last trail entry. Outbound
|
back), so the exit URL is not necessarily the last trail entry. Outbound
|
||||||
links are stored by full URL so several links to the same domain remain
|
links are stored by full URL so several links to the same domain remain
|
||||||
distinct.
|
distinct.
|
||||||
- **Excluded**: back/forward (popstate) navigations, navigation involving
|
- **Excluded**: back/forward (popstate) navigations, navigating *to* the
|
||||||
the analytics page itself (`/_a`), and everything while the user has the
|
analytics page (`/_a` — its GET is untracked, and the server rejects it
|
||||||
editor open (`body.editing`). Admin noise, not visits.
|
as a ping target anyway), and everything while the user has the editor
|
||||||
|
open (`body.editing`). Admin noise, not visits. Navigating *away* from
|
||||||
|
`/_a` does ping: the fetch-navigation already GET-ed the target page
|
||||||
|
without the preload header, and without the ping that GET would flush to
|
||||||
|
the crawler list.
|
||||||
- **Admins**: when SSO is in use and the session is known to be an admin,
|
- **Admins**: when SSO is in use and the session is known to be an admin,
|
||||||
the client still pings but adds `hide=1`. The server then records
|
the client still pings but adds `hide=1`. The activity is recorded as
|
||||||
nothing — and if the same client session already had a visit from before
|
usual (navigations and all), but the `hide` flag is set on the **client
|
||||||
logging in, that visit is removed from the JSON along with the counts
|
record** — so it covers everything that client ever did: visits and
|
||||||
recorded when it was created (site visit, entry view, entry transition).
|
crawler hits from before the login included. Hidden clients never appear
|
||||||
Views/transitions logged by later pings inside such a visit lack
|
in the viewer payload: `Store.display()` drops their visits, crawler
|
||||||
per-event timestamps and are left as-is. With no auth proxy (dev/test)
|
hits, abuse hits and metadata, and computes every aggregate (site visits,
|
||||||
"admin" is everyone's state, so `hide` stays 0 and everything is recorded.
|
page views, transitions) from the visible visits only, so nothing needs
|
||||||
|
to be reversed or redacted. Pending crawler hits from a hidden client
|
||||||
|
are discarded when they expire, so admin browsing never lands in the
|
||||||
|
crawler list either. With no auth proxy
|
||||||
|
(dev/test) "admin" is everyone's state, so `hide` stays 0 and everything
|
||||||
|
is recorded.
|
||||||
- The server validates `to`: internal paths must be valid slug paths
|
- The server validates `to`: internal paths must be valid slug paths
|
||||||
("/" or `[a-z0-9_-]` segments), external ones are re-derived to the
|
("/" or `[a-z0-9_-]` segments), external ones are re-derived to the
|
||||||
https origin and accepted only when the client sent exactly that.
|
https origin and accepted only when the client sent exactly that.
|
||||||
@@ -87,13 +101,14 @@ The client (`pagerite.js`) POSTs fire-and-forget pings to `/_a` with
|
|||||||
the header only hides a GET from the crawler stats, the path-based abuse
|
the header only hides a GET from the crawler stats, the path-based abuse
|
||||||
classification is unaffected). If a ping
|
classification is unaffected). If a ping
|
||||||
from the same client arrives within 10 seconds the hit is discarded;
|
from the same client arrives within 10 seconds the hit is discarded;
|
||||||
otherwise it is written to `crawlers`. Crawlers do not count as
|
otherwise it is written to `crawlers` — unless the client is hidden
|
||||||
|
(admin), in which case the hit is discarded on expiry too. Crawlers do not count as
|
||||||
visits or views. The `Accept-Language` header is stored on the shared
|
visits or views. The `Accept-Language` header is stored on the shared
|
||||||
`Client` immediately; reverse-DNS host names and DB-IP geoip
|
`Client` immediately; reverse-DNS host names and DB-IP geoip
|
||||||
country/city are filled in asynchronously, just like for real visits. In
|
country/city are filled in asynchronously, just like for real visits. In
|
||||||
the analytics viewer, crawler hits are grouped by client hash and shown as
|
the analytics viewer, crawler hits are grouped by client hash and shown as
|
||||||
a trail of internal pages that crawler visited; the crawler table lists
|
a trail of internal pages that crawler visited; the crawler table lists
|
||||||
the most active crawlers first rather than the most recent hits.
|
the most recent crawler first, with the most active as a tie-breaker.
|
||||||
- **Abuse (scanner) hits**: a 404 for a telltale path — any URL segment
|
- **Abuse (scanner) hits**: a 404 for a telltale path — any URL segment
|
||||||
starting with a dot (`/.env`, `/.git/config`) or ending in `.php` —
|
starting with a dot (`/.env`, `/.git/config`) or ending in `.php` —
|
||||||
classifies the source IP as abuse immediately, and ten plain 404s from one
|
classifies the source IP as abuse immediately, and ten plain 404s from one
|
||||||
@@ -134,7 +149,10 @@ Each `Client` record:
|
|||||||
- `city` — city name from the DB-IP MMDB lookup, when available,
|
- `city` — city name from the DB-IP MMDB lookup, when available,
|
||||||
- `ua` — raw `User-Agent` string,
|
- `ua` — raw `User-Agent` string,
|
||||||
- `ua_pretty` — compact display form of the UA (browser/OS/device) when
|
- `ua_pretty` — compact display form of the UA (browser/OS/device) when
|
||||||
parsable, otherwise the raw string.
|
parsable, otherwise the raw string,
|
||||||
|
- `hide` — true for admin clients (`hide=1` ping): all their visits,
|
||||||
|
crawler hits and abuse hits are recorded but excluded from every
|
||||||
|
statistic and from the viewer payload.
|
||||||
|
|
||||||
Each `Visit` record:
|
Each `Visit` record:
|
||||||
|
|
||||||
@@ -142,11 +160,16 @@ Each `Visit` record:
|
|||||||
- `entry` — first page (path) seen,
|
- `entry` — first page (path) seen,
|
||||||
- `referer` — external https origin of the initial load, `""` for direct,
|
- `referer` — external https origin of the initial load, `""` for direct,
|
||||||
- `client` — 6-byte blake3 hash referencing `Analytics.clients`,
|
- `client` — 6-byte blake3 hash referencing `Analytics.clients`,
|
||||||
- `trail` — everything seen afterwards in first-seen order: page paths and
|
- `trail` — the entry page and everything seen afterwards, keyed by the
|
||||||
external exit URLs. Re-visiting an already seen page (incl. the entry)
|
timestamp of first sight (insertion order = first-seen order). Each item
|
||||||
does not append.
|
holds `to` (page path or external exit URL), the accumulated active
|
||||||
|
reading time in seconds (`read`) and the most recent HTTP status seen
|
||||||
|
for the target (`status`). Re-visiting an already seen target updates
|
||||||
|
its item instead of appending.
|
||||||
|
- `navs` — every navigation ping (`fr`, `to`), keyed by its timestamp,
|
||||||
|
repeats included. The aggregates are computed from this log at display
|
||||||
|
time.
|
||||||
- `utm` — `utm_*` query parameters from the landing URL, as a dict.
|
- `utm` — `utm_*` query parameters from the landing URL, as a dict.
|
||||||
- `read` — active reading time per path (seconds), keyed by path.
|
|
||||||
|
|
||||||
Each `CrawlerHit` record:
|
Each `CrawlerHit` record:
|
||||||
|
|
||||||
@@ -154,7 +177,9 @@ Each `CrawlerHit` record:
|
|||||||
- `entry` — page path requested,
|
- `entry` — page path requested,
|
||||||
- `client` — 6-byte blake3 hash referencing `Analytics.clients`,
|
- `client` — 6-byte blake3 hash referencing `Analytics.clients`,
|
||||||
- `referer` — external https origin of the request, `""` for direct/none,
|
- `referer` — external https origin of the request, `""` for direct/none,
|
||||||
- `query` — raw query string of the request.
|
- `query` — raw query string of the request,
|
||||||
|
- `status` — HTTP status of the served response (200 for a real page, 404
|
||||||
|
for a category placeholder or missing page).
|
||||||
|
|
||||||
Each `AbuseHit` record:
|
Each `AbuseHit` record:
|
||||||
|
|
||||||
@@ -173,12 +198,22 @@ that triggered classification are lifted to the top, followed by other 404s
|
|||||||
and then document GETs from the abuser. Within each category paths are
|
and then document GETs from the abuser. Within each category paths are
|
||||||
sorted by count descending, then by their earliest hit.
|
sorted by count descending, then by their earliest hit.
|
||||||
|
|
||||||
|
In the visitor and crawler tables, internal paths that returned a 404 status
|
||||||
|
are shown in red and the link title includes the status code, so it is easy
|
||||||
|
to tell misses from real pages at a glance.
|
||||||
|
|
||||||
## Aggregates
|
## Aggregates
|
||||||
|
|
||||||
|
Aggregates are **not stored**; they are computed at display time by
|
||||||
|
`Store.display()` from the visit records (entry + `navs` log), skipping
|
||||||
|
hidden clients' visits. This is what allows a client to become hidden after
|
||||||
|
navigations were already logged: no counts need reversing. The computed
|
||||||
|
shapes, part of the WebSocket payload (`Display` struct alongside `visits`,
|
||||||
|
`crawlers`, `abuse` and `clients`):
|
||||||
|
|
||||||
- `transitions`: time series of page transitions, sparse nested dict
|
- `transitions`: time series of page transitions, sparse nested dict
|
||||||
`from -> to -> bucket -> count` with the same 5-minute bucketing as
|
`from -> to -> bucket -> count` with 5-minute bucketing. `from` is the
|
||||||
`views`. `from` is the referer origin or `"(direct)"` for initial loads,
|
referer origin or `"(direct)"` for initial loads, a page path for pings.
|
||||||
a page path for pings.
|
|
||||||
- `views`: time series of page loads, `path -> bucket -> count`, sparse: only
|
- `views`: time series of page loads, `path -> bucket -> count`, sparse: only
|
||||||
non-zero 5-minute buckets exist (bucket key is its floored ISO timestamp).
|
non-zero 5-minute buckets exist (bucket key is its floored ISO timestamp).
|
||||||
Every load counts, including repeats within a visit; external exit origins
|
Every load counts, including repeats within a visit; external exit origins
|
||||||
@@ -187,7 +222,7 @@ sorted by count descending, then by their earliest hit.
|
|||||||
5-minute bucketing.
|
5-minute bucketing.
|
||||||
|
|
||||||
Sparseness keeps quiet sites small; dropping old data is a matter of deleting
|
Sparseness keeps quiet sites small; dropping old data is a matter of deleting
|
||||||
list/dict entries (`visits` is a plain append-only list, buckets plain keys).
|
list entries (`visits` is a plain append-only list).
|
||||||
|
|
||||||
## Persistence
|
## Persistence
|
||||||
|
|
||||||
@@ -216,12 +251,11 @@ spans less than 24 hours, otherwise `week`.
|
|||||||
`AnalyticsView.vue` is no longer a full-screen overlay; the `body.analytics-open`
|
`AnalyticsView.vue` is no longer a full-screen overlay; the `body.analytics-open`
|
||||||
page-chrome hiding and `#/analytics/<range>` hash routing have been removed.
|
page-chrome hiding and `#/analytics/<range>` hash routing have been removed.
|
||||||
|
|
||||||
Charts are SVG curves (Catmull-Rom over an edge-aware adaptive Gaussian —
|
Charts are SVG curves (Catmull-Rom over an edge-aware Gaussian — a
|
||||||
a change-point detector splits the series at traffic-level shifts, then
|
change-point detector splits the series at traffic-level shifts, then each
|
||||||
each segment is smoothed with a bandwidth that ramps with a broad pilot
|
segment is smoothed independently with a fixed sigma chosen so N events in
|
||||||
estimate of the local rate: isolated events stay narrow (~0.4-unit sigma,
|
a single bucket peak at N events per unit. The raw series is drawn faint
|
||||||
peaking at ~1 event/unit), busy traffic widens to a 1-unit sigma. The raw
|
underneath). Values are
|
||||||
series is drawn faint underneath). Values are
|
|
||||||
**per-unit rates** — per hour on the week view (5-minute bucket counts × 12,
|
**per-unit rates** — per hour on the week view (5-minute bucket counts × 12,
|
||||||
plotted at native 5-minute resolution), per day on the month+ ranges — and
|
plotted at native 5-minute resolution), per day on the month+ ranges — and
|
||||||
the smoothing time scale follows the unit: the month+ sigmas are 24× the
|
the smoothing time scale follows the unit: the month+ sigmas are 24× the
|
||||||
@@ -232,31 +266,58 @@ labeled intervals, minor lines at fifths when integral; the minimum y-axis
|
|||||||
range is 10 so tiny values such as a single visit are not stretched to a
|
range is 10 so tiny values such as a single visit are not stretched to a
|
||||||
fractional scale).
|
fractional scale).
|
||||||
The week range is aligned to Monday 00:00 UTC and overlays up to 8 previous
|
The week range is aligned to Monday 00:00 UTC and overlays up to 8 previous
|
||||||
weeks in the same accent color at decreasing opacity (the current week is
|
weeks in the muted color at decreasing opacity (the current week keeps the
|
||||||
|
accent color and is
|
||||||
truncated at the current bucket, never drawing fake zeroes for the future);
|
truncated at the current bucket, never drawing fake zeroes for the future);
|
||||||
its x labels are weekday names centered at midday UTC, without vertical grid
|
a compact legend inside the top right of the visits chart marks the current
|
||||||
|
ISO week in accent and the overlaid past weeks as "Week M" or "Week M–N" on
|
||||||
|
a muted specimen. Its x labels are weekday names centered at midday UTC, without
|
||||||
|
vertical grid
|
||||||
lines (day boundaries would be misleading in the viewer's timezone). The
|
lines (day boundaries would be misleading in the viewer's timezone). The
|
||||||
month view labels days the same lineless way — day numbers at noon UTC,
|
month view labels days the same lineless way — day numbers at noon UTC,
|
||||||
with the month name substituted for the 1st. Year is a rolling 365-day window ending at now, re-bucketed to daily points,
|
with the month name substituted for the 1st. Month, year and all are
|
||||||
with boundary lines at months/years. All uses the full data reach, but keeps
|
rolling windows ending at now, aligned to UTC day boundaries at the start
|
||||||
at least the past 30 days so the chart never collapses to a tiny sliver when
|
so the labels span the whole range; the bucket size follows the window —
|
||||||
the site is young. Below the charts: a radial **transition map** (all pages from
|
6 hours up to 31 days, daily beyond — with boundary lines at months/years
|
||||||
`/_api/pages` — front page at the center, each slug level on its own ring,
|
on the longer ranges. All uses the full data reach, but keeps
|
||||||
siblings clockwise in navigation order from the top, radial gap equal to
|
at least the past 30 days (identical to the month view when the site is
|
||||||
the arc spacing — opposite transition directions joined into organic
|
younger than that, bucket size included) so the chart never collapses to a
|
||||||
tapered connections whose middle width grows logarithmically with the
|
tiny sliver when the site is young. Below the charts: a **transition map** (all pages from
|
||||||
count (a single count renders as a ~1 px line, uncapped), connections
|
`/_api/pages` — top-level menu items on a large-radius circular arc whose
|
||||||
|
bottom point is the last item (each earlier item a bit higher), connected
|
||||||
|
by a top lane labeled 🏠︎ beside the home pill (50% thicker than
|
||||||
|
the branch lanes, its label font and guide offset scaled along), each item's
|
||||||
|
subtree fanning out below it in menu order along a large-radius circular
|
||||||
|
arc that leaves heading
|
||||||
|
straight down and gradually bends right, index pages without views omitted
|
||||||
|
and their children promoted in their place. The submenu structure is drawn
|
||||||
|
as wide branch lanes: one per path prefix with at least two visible
|
||||||
|
nodes, running behind the branch's node pills as circle arcs concentric
|
||||||
|
with the fan (parent levels one radius step outward, so all lanes of a
|
||||||
|
group share exactly one form), each labeled with its branch slug
|
||||||
|
left-aligned just past the first pill and allowed to run along the lane to
|
||||||
|
its end, disappearing under later pills when long — so the lanes reflect
|
||||||
|
the path
|
||||||
|
structure even where index pages are omitted — opposite transition
|
||||||
|
directions joined into organic
|
||||||
|
tapered connections whose middle width grows logarithmically (base 2)
|
||||||
|
with the daily hit rate (uncapped), connections
|
||||||
carrying less than 1% of the total traffic
|
carrying less than 1% of the total traffic
|
||||||
pruned; beads are simulated one by one in JS (requestAnimationFrame) and
|
pruned, as are those whose thin middle would render below ~0.8 px —
|
||||||
flow along each edge, emitted at a rate linearly proportional
|
fainter strands are invisible and only their wide end flares would show; beads are simulated one by one in JS (requestAnimationFrame) and
|
||||||
|
flow along each edge, persisting across data reloads (emitters are keyed
|
||||||
|
per edge direction and beads tracked by progress, so an unrelated count
|
||||||
|
change never reshuffles them), emitted at a rate linearly proportional
|
||||||
to the directional count with no in-flight limit, opposing directions
|
to the directional count with no in-flight limit, opposing directions
|
||||||
offset onto parallel lanes. External sources show as a node row above the
|
offset onto parallel lanes. External sources and exits whose connectors are
|
||||||
|
all culled by the width threshold are dropped from their rows themselves
|
||||||
|
(the site's own page nodes always stay, connected or not). External sources show as a node row above the
|
||||||
map: each visit is attributed to `utm_campaign`, then `utm_source`, then the
|
map: each visit is attributed to `utm_campaign`, then `utm_source`, then the
|
||||||
referer origin, then any other `utm_*` tag, so UTM-tagged visits are grouped
|
referer origin, then any other `utm_*` tag, so UTM-tagged visits are grouped
|
||||||
under their campaign/source value rather than the referer domain. A UTM
|
under their campaign/source value rather than the referer domain. A UTM
|
||||||
source node only links to its referer when every visit carrying that tag
|
source node only links to its referer when every visit carrying that tag
|
||||||
came from the same origin. External exits are small nodes fanned outwards
|
came from the same origin. External exits are full-size nodes in a matching
|
||||||
from their source page), per-page view
|
row centered below the map, so the site itself stays in the middle), per-page view
|
||||||
counts, the top transitions and the 50 most recent visit trails. Data is
|
counts, the top transitions and the 50 most recent visit trails. Data is
|
||||||
streamed live over `WebSocket /_api/ws/analytics`, which pushes the latest
|
streamed live over `WebSocket /_api/ws/analytics`, which pushes the latest
|
||||||
JSON snapshot on connect and again whenever the analytics file is updated
|
JSON snapshot on connect and again whenever the analytics file is updated
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ Pagerite is a single-user CMS/blog. This document records the initial high-level
|
|||||||
|
|
||||||
- Content is written in **Markdown** with powerful extensions (tables, footnotes, code highlighting, etc.).
|
- Content is written in **Markdown** with powerful extensions (tables, footnotes, code highlighting, etc.).
|
||||||
- **Embedded HTML is passed through unfiltered**, including inline scripts and other dynamic content the author wants to post. This is safe by the single-trusted-author assumption above.
|
- **Embedded HTML is passed through unfiltered**, including inline scripts and other dynamic content the author wants to post. This is safe by the single-trusted-author assumption above.
|
||||||
- Renderer: **markdown-it-py** with mdit-py-plugins (footnotes, definition lists, task lists, brace-attributes; tables and strikethrough from the default preset), with `html=True` for raw passthrough, `typographer=True` for SmartyPants-style replacements in body text (curly quotes, `--` / `---` → en / em dashes, `...` → ellipsis, `(c)` → ©, etc.), and `breaks=True` so single line breaks inside paragraphs become `<br>`. Code spans/blocks and raw HTML are left untouched. Fenced code blocks are highlighted server-side with **Pygments** (`nowrap` spans styled by `/_assets/pygments-*.css`, which maps every token class onto the `--code-*` variables; the base stylesheet defines light and dark palette sets resolved via `light-dark()`, so each theme gets the set matching its `color-scheme` and may only retint `--code-bg` to keep the well in the page's color family); a JS copy button appears on hover. Should this prove limiting, we implement our own renderer on top of html5tagger, which we already use for all HTML generation.
|
- Renderer: **markdown-it-py** with mdit-py-plugins (footnotes, definition lists, task lists, brace-attributes, admonitions and `::: name` containers — generic `<div class="name">` wrappers (the name may be followed by brace attributes: `::: aside {.right}`), of which `::: aside` floats as a muted side box (leaning into the empty right gutter on wide single-column pages) and `::: nocols` opts its section out of column layout; tables and strikethrough from the default preset), GitHub-style alerts (`> [!NOTE]` / TIP / IMPORTANT / WARNING / CAUTION, rendered in the admonition callout styling), with `html=True` for raw passthrough, `typographer=True` for SmartyPants-style replacements in body text (curly quotes, `--` / `---` → en / em dashes, `...` → ellipsis, `(c)` → ©, etc.), and `breaks=True` so single line breaks inside paragraphs become `<br>` — including inside blockquotes, where every newline is kept and a blank `>` line starts a new paragraph. Code spans/blocks and raw HTML are left untouched. Fenced code blocks are highlighted server-side with **Pygments** (`nowrap` spans styled by `/_assets/pygments-*.css`, which maps every token class onto the `--code-*` variables; the base stylesheet defines light and dark palette sets resolved via `light-dark()`, so each theme gets the set matching its `color-scheme` and may only retint `--code-bg` to keep the well in the page's color family); a JS copy button appears on hover. Should this prove limiting, we implement our own renderer on top of html5tagger, which we already use for all HTML generation.
|
||||||
- **Files are content-addressed.** Uploads (`PUT /_api/files/{filename}`) are stored by content hash — blake3, first 6 bytes hex + original extension — and served immutable from `/_f/{hash}.ext`. Absolute URLs that survive page renames and dedupe identical content; pages no longer own files. An image standing alone in its paragraph becomes a block `<figure>` — with `<figcaption>` when it has a title; images inline with text and raw `<img>` HTML stay plain inline images. Positioning is by attribute classes: `{.right}` — `{.right}`, `{.left}` float at 30% of the text column (the caption wraps within it; an explicit `width=300` makes the figure shrink-wrap the image instead), `{.wide}` goes full bleed (viewport edge to edge, or up to the docked editor; the sidebar stacks on top of it); plain attributes like `width=300` work too. Headings (h1/h2) clear floats, so images never overflow into the next section.
|
- **Files are content-addressed.** Uploads (`PUT /_api/files/{filename}`) are stored by content hash — blake3, first 6 bytes hex + original extension — and served immutable from `/_f/{hash}.ext`. Absolute URLs that survive page renames and dedupe identical content; pages no longer own files. An image standing alone in its paragraph becomes a block `<figure>` — with `<figcaption>` when it has a title; images inline with text and raw `<img>` HTML stay plain inline images. Positioning is by attribute classes: `{.right}` — `{.right}`, `{.left}` float at 30% of the text column (the caption wraps within it; an explicit `width=300` makes the figure shrink-wrap the image instead), `{.wide}` goes full bleed (viewport edge to edge, or up to the docked editor; the sidebar stacks on top of it); plain attributes like `width=300` work too. The same brace syntax on a block's last line (no blank line between) applies to the whole block: a paragraph ending with `{.wide}` becomes a full-width element that breaks out of the column layout; written on the line after a block it applies to that preceding block — this is how headings, `::: containers` and code fences take classes (a wide code fence goes full bleed like a wide figure). Headings (h1/h2) clear floats, so images never overflow into the next section.
|
||||||
|
|
||||||
## Page structure and navigation
|
## Page structure and navigation
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ Pagerite is a single-user CMS/blog. This document records the initial high-level
|
|||||||
|
|
||||||
## Reading experience
|
## Reading experience
|
||||||
|
|
||||||
- The article column is sized by the **viewport, never by content**: a symmetric grid (`1fr minmax(0, 78rem) 1fr`) with flexible gutters keeps the layout stable across navigation. The sidebar occupies the left gutter, the right gutter balances it; wide screens get columns inside long articles without changing the article's width.
|
- The article column is sized by the **viewport, never by content**: a symmetric grid (`1fr minmax(0, 78rem) 1fr`) with flexible gutters keeps the layout stable across navigation. The sidebar occupies the left gutter, the right gutter balances it; wide screens get columns inside long articles without changing the article's width. Columns are decided client-side (pagerite.js): the body splits into segments at h1/h2 headings and `.wide` elements (full-width separators, never inside columns), and a segment gets columns only when it holds enough text — code blocks are excluded from that measure, and a `::: nocols` container opts its whole section out.
|
||||||
- A gentle **scroll-reveal** of headings, figures and block-level elements (IntersectionObserver). It is layout-level: articles need no support for it, and `prefers-reduced-motion` disables all motion.
|
- A gentle **scroll-reveal** of headings, figures and block-level elements (IntersectionObserver). It is layout-level: articles need no support for it, and `prefers-reduced-motion` disables all motion.
|
||||||
|
|
||||||
## Styling
|
## Styling
|
||||||
@@ -45,7 +45,7 @@ Pagerite is a single-user CMS/blog. This document records the initial high-level
|
|||||||
## Editing
|
## Editing
|
||||||
|
|
||||||
- Editing happens **in place**, in two modes opened by two pens:
|
- Editing happens **in place**, in two modes opened by two pens:
|
||||||
- **Page mode** — the 🖊️ next to a page's heading (including 404s, which is how new pages start) opens a CodeMirror Markdown editor docked to the left of the article: the host sits inside `#content` (below the banner, never over the footer), the content shifts right and the sidebar hides while editing. Preview renders server-side per keystroke (no debouncing) straight into the visible article's heading and body.
|
- **Page mode** — the 🖊️ next to a page's heading (including 404s, which is how new pages start) opens a CodeMirror Markdown editor docked to the left of the article: the panel is fixed to the viewport's left edge (its top tracks the banner's bottom until the banner scrolls away), the content shifts right and the sidebar hides while editing. Preview renders server-side per keystroke (no debouncing) straight into the visible article's heading and body.
|
||||||
- **Site mode** — the 🖊️ on the banner opens a panel with the site **brand** (applied to the header live), a **theme** selector (swapping the theme stylesheet in place), **font** picks (heading/body/brand — stored as plain `:root` rows inside the custom CSS, referencing the base stylesheet's per-family font variables), a **site-wide custom CSS** field (injected into `<style id="pagerite-user">` in the live page head and swapped during fetch-navigation), the page's **banner design** selector (inherit / none / any design found on disk, inherited by children), the page's **banner HTML** field (supplementing the design, previewed into the real banner region, so you see exactly which banner you're editing) and the **structure tree**. Everything saves immediately as you edit — no save button, no edit mode.
|
- **Site mode** — the 🖊️ on the banner opens a panel with the site **brand** (applied to the header live), a **theme** selector (swapping the theme stylesheet in place), **font** picks (heading/body/brand — stored as plain `:root` rows inside the custom CSS, referencing the base stylesheet's per-family font variables), a **site-wide custom CSS** field (injected into `<style id="pagerite-user">` in the live page head and swapped during fetch-navigation), the page's **banner design** selector (inherit / none / any design found on disk, inherited by children), the page's **banner HTML** field (supplementing the design, previewed into the real banner region, so you see exactly which banner you're editing) and the **structure tree**. Everything saves immediately as you edit — no save button, no edit mode.
|
||||||
- Clicking a pen again closes the editor (without saving; a dirty preview reloads the page). The pens are `<button>`s wired up by `pagerite.js` — editing is an action, not a navigation. The editor's WebSocket **reconnects automatically** with local text and pending saves preserved. (All users are trusted authors for now; access control later with SSO.)
|
- Clicking a pen again closes the editor (without saving; a dirty preview reloads the page). The pens are `<button>`s wired up by `pagerite.js` — editing is an action, not a navigation. The editor's WebSocket **reconnects automatically** with local text and pending saves preserved. (All users are trusted authors for now; access control later with SSO.)
|
||||||
- **CodeMirror 6** for Markdown editing (no WYSIWYG), title/published controls. Images can be pasted straight into the editor or chosen via a file input: they upload to the content store (`PUT /_api/files/...`) and insert `` at the cursor.
|
- **CodeMirror 6** for Markdown editing (no WYSIWYG), title/published controls. Images can be pasted straight into the editor or chosen via a file input: they upload to the content store (`PUT /_api/files/...`) and insert `` at the cursor.
|
||||||
|
|||||||
+3
-3
@@ -6,18 +6,18 @@ The Vue editor is a single tabbed `EditorShell.vue` mounted in a host div create
|
|||||||
|
|
||||||
The shell hosts four kept-alive tabs (ordered site-wide first — site, structure — then, after a visual break, the per-page tabs — article, banner):
|
The shell hosts four kept-alive tabs (ordered site-wide first — site, structure — then, after a visual break, the per-page tabs — article, banner):
|
||||||
|
|
||||||
- `PageEditor.vue` — CodeMirror + server-rendered preview over WebSocket `/_api/ws/editor`, previewing into the visible article; editor scroll drives the article scroll — while any editor is open the window scroll is locked (`body.editing`), the panel exactly fills the available window height, and only `#main` scrolls; a format bar offers Markdown helpers — bold/italic/code/link/table/image upload, with Ctrl/Cmd-B/I/S bindings — for the hard-to-remember syntax. Edits content and title only, never the path.
|
- `PageEditor.vue` — CodeMirror + server-rendered preview over WebSocket `/_api/ws/editor`, previewing into the visible article; editor and article scrolls are linked proportionally both ways, applied instantly (the window keeps scrolling normally while any editor is open — the panel is fixed to the viewport's left edge, its top tracking the banner's bottom edge until the banner scrolls away — and the panel scrolls internally); a format bar offers Markdown helpers — bold/italic/code/link/table/image upload, with Ctrl/Cmd-B/I/S bindings — for the hard-to-remember syntax. Edits content and title only, never the path.
|
||||||
- `BannerEditor.vue` — per-page banner HTML + banner design selector, previewed into `#page-banner`.
|
- `BannerEditor.vue` — per-page banner HTML + banner design selector, previewed into `#page-banner`.
|
||||||
- `SiteEditor.vue` — site brand + optional custom brand HTML with image/video upload + theme selector + font picker + favicon upload — clicking the preview tile picks a new one — + site-wide custom CSS, CSS injected into `<head id="pagerite-user">`.
|
- `SiteEditor.vue` — site brand + optional custom brand HTML with image/video upload + theme selector + font picker + favicon upload — clicking the preview tile picks a new one — + site-wide custom CSS, CSS injected into `<head id="pagerite-user">`.
|
||||||
- `StructureEditor.vue` — the vue-draggable structure tree with always-editable title/slug inputs per row.
|
- `StructureEditor.vue` — the vue-draggable structure tree with always-editable title/slug inputs per row.
|
||||||
|
|
||||||
Media uploads everywhere use the image icon buttons (pasting into the editor works too). The article, banner and site-settings pens are shorthands that open the shell on the matching tab; once open, clicking a pen switches tabs (and retargets the editors to the current page) instead of closing/remounting. The close button in the tab bar closes the shell (Escape too); tabs have no close buttons of their own. Closing only HIDES the shell — the Vue app stays mounted, so page-editor state (unsaved text included) survives until a real page reload; saving there is explicit (Ctrl+S) and refreshes the page regions in place. Admin panels never reload the page.
|
Media uploads everywhere use the image icon buttons (pasting into the editor works too). The article, banner and site-settings pens are shorthands that open the shell on the matching tab; once open, clicking a pen switches tabs (and retargets the editors to the current page) instead of closing/remounting. The close button in the tab bar closes the shell (Escape too); tabs have no close buttons of their own. Closing only HIDES the shell — the Vue app stays mounted, so page-editor state (unsaved text included) survives until a real page reload; saving there is explicit (Ctrl+S) and refreshes the page regions in place. Admin panels never reload the page.
|
||||||
|
|
||||||
In-place page re-rendering shared by the banner/site/structure tabs lives in `swapdoc.js` (`runScripts`/`loadPlain`: fetch a page, swap the dynamic regions, replaceState). Placeholder texts are reserved for showing the actual default in effect when a field is left empty (e.g. the pending row's slug derived from its title); labels and help are real elements or tooltips, never placeholders.
|
In-place page re-rendering shared by the banner/site/structure tabs lives in `swapdoc.js` (`runScripts`/`loadPlain`: fetch a page, swap the dynamic regions, replaceState). It also exports `dropPageCache`, which the editor tabs call after any save that can alter the rendered HTML of other pages (theme, headings, structure, banners, site brand/CSS, favicon). Dropping the cache while editing avoids re-fetching every page immediately; the public runtime re-preloads visible links once the editor panel closes.
|
||||||
|
|
||||||
## Saving behavior
|
## Saving behavior
|
||||||
|
|
||||||
Everything saves immediately as you edit (brand/title/CSS debounced, slug on commit since it renames the path), theme change swaps the stylesheet in place, tree rows navigate in place without transitions when focused, and the front page is a root-only row whose empty slug is editable like any other.
|
Everything saves immediately as you edit (brand/title/CSS debounced, slug on commit since it renames the path), theme change swaps the stylesheet in place, tree rows navigate in place without transitions when focused, and the front page is a root-only row whose empty slug is editable like any other. Saves that can affect other pages drop the prefetch cache; the cache is rebuilt when the editor panel closes so navigation stays instant.
|
||||||
|
|
||||||
Every non-empty list (and the root) ends with a non-draggable plus footer row (vuedraggable `#footer` slot): clicking it starts a new pending page at that level (its slug placeholder shows the slug derived live from the title being typed), and while dragging it is the list's "end of list" drop target. Committing a pending page PUTs it with empty markdown (creates an empty page that renders with its title — saving never deletes; deletion is the page editor's explicit choice: saving trimmed-empty text issues a REST DELETE), then switches to the page editor tab for the actual writing.
|
Every non-empty list (and the root) ends with a non-draggable plus footer row (vuedraggable `#footer` slot): clicking it starts a new pending page at that level (its slug placeholder shows the slug derived live from the title being typed), and while dragging it is the list's "end of list" drop target. Committing a pending page PUTs it with empty markdown (creates an empty page that renders with its title — saving never deletes; deletion is the page editor's explicit choice: saving trimmed-empty text issues a REST DELETE), then switches to the page editor tab for the actual writing.
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Vue editor app entry, mounts the tabbed `EditorShell`. See `docs/editing.md` for
|
|||||||
|
|
||||||
## `pagerite.js`
|
## `pagerite.js`
|
||||||
|
|
||||||
Public page entry; runs fetch-navigation (backed by an in-memory page cache: every visible internal link is fetched once at load and clicks are then served from JS with no fetch — the current page itself is not refetched, it enters the cache when navigated to — and the editors' `loadPlain` keeps the cache current via a `pagerite:page-fetched` event; articles are `cache-control: no-cache` on the wire), scroll-reveal, OverlayScrollbars on `document.body` (floating, auto-hiding scrollbars that never reserve layout space or shift the page when appearing; native scroll APIs like `window.scrollTo` keep working; themed via the `--os-*` variables in pagerite.css), brand shrink-to-fit (the themed size is the maximum; JS reduces the font-size so a long brand or narrow viewport still fits one line), nav condense-to-fit (the top nav stays on one row: link gaps shrink first, then the side padding, then the font size; `flex-wrap: wrap` remains the no-JS fallback), code copy buttons, and the auth check.
|
Public page entry; runs fetch-navigation (backed by an in-memory page cache: every visible internal link is fetched once at load and clicks are then served from JS with no fetch — the current page itself is not refetched, it enters the cache when navigated to — and the editors' `loadPlain` keeps the cache current via a `pagerite:page-fetched` event; articles are `cache-control: no-cache` on the wire). Editors can drop the entire cache with the `pagerite:drop-page-cache` event when site-wide or page changes (theme, headings, structure, banners, etc.) invalidate the cached HTML of other pages; `main.js` triggers a fresh `pagerite:preload-pages` pass when the editor panel closes so navigation is fast again. Navigation that starts while the editor is open bypasses the cache and fetches the target page on demand. Also runs scroll-reveal, OverlayScrollbars on `document.body` (floating, auto-hiding scrollbars that never reserve layout space or shift the page when appearing; native scroll APIs like `window.scrollTo` keep working; themed via the `--os-*` variables in pagerite.css), brand shrink-to-fit (the themed size is the maximum; JS reduces the font-size so a long brand or narrow viewport still fits one line), nav condense-to-fit (the top nav stays on one row: link gaps shrink first, then the side padding, then the font size; `flex-wrap: wrap` remains the no-JS fallback), code copy buttons, and the auth check.
|
||||||
|
|
||||||
It first probes `GET /auth/api/settings` to detect whether Paskia SSO is available, then `GET /_api/settings` to learn the current session's admin status. The same reverse proxy that gates `/_api` returns 401 for anonymous users, 403 for users without the admin permission, and 200 for admins. When Paskia is detected, a login link (anonymous) or profile link (logged in) is shown in the banner corner; both are plain `<a href="/auth/">` links (Paskia does not support being iframed, so we navigate normally), and a `pageshow` handler re-probes auth when history navigation restores a cached page. Admins also get the page/banner edit pens and a site-settings pen, plus a `modulepreload` warm-up of the editor bundle (the hashed asset is immutable, so it costs nothing). If no Paskia SSO is detected (dev/no proxy), editing is left open. Pages themselves render identically for everyone; the real gate is the auth proxy in front of all of `/_api`.
|
It first probes `GET /auth/api/settings` to detect whether Paskia SSO is available, then `GET /_api/settings` to learn the current session's admin status. The same reverse proxy that gates `/_api` returns 401 for anonymous users, 403 for users without the admin permission, and 200 for admins. When Paskia is detected, a login link (anonymous) or profile link (logged in) is shown in the banner corner; both are plain `<a href="/auth/">` links (Paskia does not support being iframed, so we navigate normally), and a `pageshow` handler re-probes auth when history navigation restores a cached page. Admins also get the page/banner edit pens and a site-settings pen, plus a `modulepreload` warm-up of the editor bundle (the hashed asset is immutable, so it costs nothing). If no Paskia SSO is detected (dev/no proxy), editing is left open. Pages themselves render identically for everyone; the real gate is the auth proxy in front of all of `/_api`.
|
||||||
|
|
||||||
|
|||||||
@@ -34,4 +34,4 @@ The banner artwork has scroll parallax: pagerite.js sets the `--pry` scroll para
|
|||||||
|
|
||||||
## Stylesheet order
|
## Stylesheet order
|
||||||
|
|
||||||
The backend emits the stylesheets in a fixed order — base (Vite build), theme, banner design, entry sheets, custom CSS last — each with a stable id so fetch-navigation and the site editor can sync them in place. In dev they are `<link>`s (the base is Vite-injected from JS instead); in production they are inlined as `<style>` elements. The base stylesheet's `--font-brand` defaults to `var(--font-heading)`.
|
The backend emits the stylesheets in a fixed order — base (Vite build), theme, banner design, entry sheets, custom CSS last — each with a stable id so fetch-navigation and the site editor can sync them in place. In dev they are `<link>`s (the base is Vite-injected from JS instead); in production they are inlined as `<style>` elements. The base stylesheet's `--font-brand` defaults to `var(--font-heading)`. Code text (Fira Code by default) is optically matched to the body font by x-height: `font-size-adjust: ex-height var(--code-x-height)` scales whatever code font is in use, so a theme that switches its body font sets `--code-x-height` to that font's x-height ratio (base: 0.478 for Source Sans 3; themes ship values for Inter, Montserrat, Literata and Cause).
|
||||||
|
|||||||
@@ -5,7 +5,13 @@
|
|||||||
// visit/crawler tables. Read-only.
|
// visit/crawler tables. Read-only.
|
||||||
// See docs/analytics.md for the data format.
|
// See docs/analytics.md for the data format.
|
||||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
import { RANGES } from './analytics/time.js'
|
import {
|
||||||
|
RANGES,
|
||||||
|
rangeWindow,
|
||||||
|
filterRecordsByRange,
|
||||||
|
filterTransitionsByRange,
|
||||||
|
filterViewsByRange,
|
||||||
|
} from './analytics/time.js'
|
||||||
import {
|
import {
|
||||||
calcReadStats,
|
calcReadStats,
|
||||||
calcTotalViews,
|
calcTotalViews,
|
||||||
@@ -20,6 +26,11 @@ import TrailLink from './TrailLink.vue'
|
|||||||
import VisitorCell from './VisitorCell.vue'
|
import VisitorCell from './VisitorCell.vue'
|
||||||
import TransitionGraph from './TransitionGraph.vue'
|
import TransitionGraph from './TransitionGraph.vue'
|
||||||
import VisitorCharts from './VisitorCharts.vue'
|
import VisitorCharts from './VisitorCharts.vue'
|
||||||
|
import { VIEW_W } from './analytics/chart.js'
|
||||||
|
|
||||||
|
// Same centering margin as the charts, so the totals row's left edge
|
||||||
|
// aligns with the chart svg above the natural width.
|
||||||
|
const CHART_MARGIN = `max(0px, calc(50% - ${VIEW_W / 2}px))`
|
||||||
|
|
||||||
const ABUSE_MAX_LINES = 5
|
const ABUSE_MAX_LINES = 5
|
||||||
|
|
||||||
@@ -90,8 +101,25 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const visits = computed(() => data.value?.visits || [])
|
const window = computed(() => rangeWindow(range.value))
|
||||||
const totalViews = computed(() => calcTotalViews(data.value?.views))
|
|
||||||
|
// All non-chart stats follow the selected range; the charts keep their own
|
||||||
|
// range-specific x windows (week overlays previous weeks aligned to Monday).
|
||||||
|
const rangeData = computed(() => {
|
||||||
|
if (!data.value) return null
|
||||||
|
const { t0, t1 } = window.value
|
||||||
|
return {
|
||||||
|
...data.value,
|
||||||
|
transitions: filterTransitionsByRange(data.value.transitions, t0, t1),
|
||||||
|
views: filterViewsByRange(data.value.views, t0, t1),
|
||||||
|
visits: filterRecordsByRange(data.value.visits, t0, t1),
|
||||||
|
crawlers: filterRecordsByRange(data.value.crawlers, t0, t1),
|
||||||
|
abuse: filterRecordsByRange(data.value.abuse, t0, t1),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const visits = computed(() => rangeData.value?.visits || [])
|
||||||
|
const totalViews = computed(() => calcTotalViews(rangeData.value?.views))
|
||||||
const readStats = computed(() => calcReadStats(visits.value))
|
const readStats = computed(() => calcReadStats(visits.value))
|
||||||
|
|
||||||
// Keep the URL shareable when the range changes.
|
// Keep the URL shareable when the range changes.
|
||||||
@@ -103,9 +131,9 @@ watch(range, (r) => {
|
|||||||
|
|
||||||
const clients = computed(() => data.value?.clients || {})
|
const clients = computed(() => data.value?.clients || {})
|
||||||
const visitRows = computed(() => formatVisitRows(visits.value, clients.value, pageTree.value, now.value))
|
const visitRows = computed(() => formatVisitRows(visits.value, clients.value, pageTree.value, now.value))
|
||||||
const crawlers = computed(() => data.value?.crawlers || [])
|
const crawlers = computed(() => rangeData.value?.crawlers || [])
|
||||||
const crawlerRows = computed(() => formatCrawlerRows(crawlers.value, clients.value, pageTree.value, now.value))
|
const crawlerRows = computed(() => formatCrawlerRows(crawlers.value, clients.value, pageTree.value, now.value))
|
||||||
const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], clients.value, now.value))
|
const abuseRows = computed(() => formatAbuseRows(rangeData.value?.abuse || [], clients.value, now.value))
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -125,15 +153,15 @@ const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], client
|
|||||||
<p v-if="error" class="error">⚠️ {{ error }}</p>
|
<p v-if="error" class="error">⚠️ {{ error }}</p>
|
||||||
<p v-else-if="!data" class="loading">loading…</p>
|
<p v-else-if="!data" class="loading">loading…</p>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<section class="totals">
|
<section class="totals" :style="{ marginLeft: CHART_MARGIN }">
|
||||||
<div><strong :title="String(visits.length)">{{ formatCount(visits.length) }}</strong> visits</div>
|
<div><strong :title="String(visits.length)">{{ formatCount(visits.length) }}</strong> visits</div>
|
||||||
<div><strong :title="String(totalViews)">{{ formatCount(totalViews) }}</strong> page views</div>
|
<div><strong :title="String(totalViews)">{{ formatCount(totalViews) }}</strong> page views</div>
|
||||||
<div><strong>{{ readStats.avgMinPerVisit }}</strong> min/visit</div>
|
<div><strong>{{ readStats.avgMinPerVisit }}</strong> min/visit</div>
|
||||||
<div><strong>{{ readStats.avgArticleMedianMin }}</strong> min article read</div>
|
<div><strong>{{ readStats.avgArticleMedianMin }}</strong> min/read</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<VisitorCharts :data="data" :range="range" />
|
<VisitorCharts :data="data" :range="range" />
|
||||||
<TransitionGraph :data="data" :range="range" :page-tree="pageTree" />
|
<TransitionGraph :data="rangeData" :window="window" :page-tree="pageTree" />
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
<h2>Recent visits</h2>
|
<h2>Recent visits</h2>
|
||||||
@@ -205,7 +233,6 @@ const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], client
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<p v-else class="empty">no crawler hits recorded yet</p>
|
|
||||||
|
|
||||||
<div v-if="abuseRows.length" class="visit-table-wrap">
|
<div v-if="abuseRows.length" class="visit-table-wrap">
|
||||||
<table class="visit-table">
|
<table class="visit-table">
|
||||||
@@ -265,6 +292,8 @@ const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], client
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
/* Same 1.25rem side spacing as main's article padding. */
|
/* Same 1.25rem side spacing as main's article padding. */
|
||||||
padding: 1.5rem 1.25rem 4rem;
|
padding: 1.5rem 1.25rem 4rem;
|
||||||
|
/* Container for cqw-based shrink-to-fit (see .totals). */
|
||||||
|
container-type: inline-size;
|
||||||
}
|
}
|
||||||
|
|
||||||
.analytics-panel header {
|
.analytics-panel header {
|
||||||
@@ -331,12 +360,15 @@ const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], client
|
|||||||
.analytics-view :deep(.muted) { color: var(--muted); }
|
.analytics-view :deep(.muted) { color: var(--muted); }
|
||||||
.analytics-view :deep(.small) { font-size: 0.75em; }
|
.analytics-view :deep(.small) { font-size: 0.75em; }
|
||||||
|
|
||||||
|
/* One line at any width: the gap shrinks first, then the font (the number
|
||||||
|
scales along in em), both following the panel's container width. */
|
||||||
.totals {
|
.totals {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 2rem;
|
gap: clamp(0.5rem, 3cqw, 2rem);
|
||||||
font-size: 1.1rem;
|
font-size: clamp(0.6rem, 2.2cqw, 1.1rem);
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
.totals strong { font-size: 1.5rem; }
|
.totals strong { font-size: 1.36em; }
|
||||||
|
|
||||||
.visit-table-wrap {
|
.visit-table-wrap {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
@@ -392,6 +424,11 @@ const abuseRows = computed(() => formatAbuseRows(data.value?.abuse || [], client
|
|||||||
margin-left: 0.5rem;
|
margin-left: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.analytics-view :deep(.trail-link.error),
|
||||||
|
.analytics-view :deep(.trail-link.error:hover) {
|
||||||
|
color: var(--error, #c00);
|
||||||
|
}
|
||||||
|
|
||||||
.visit-table .utm-tag {
|
.visit-table .utm-tag {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { EditorView, basicSetup } from 'codemirror'
|
|||||||
import { EditorState } from '@codemirror/state'
|
import { EditorState } from '@codemirror/state'
|
||||||
import { html } from '@codemirror/lang-html'
|
import { html } from '@codemirror/lang-html'
|
||||||
import { cmHighlight, cmTheme } from './cmtheme'
|
import { cmHighlight, cmTheme } from './cmtheme'
|
||||||
import { loadPlain, runScripts } from './swapdoc'
|
import { dropPageCache, loadPlain, runScripts } from './swapdoc'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
pagePath: { type: String, default: '' },
|
pagePath: { type: String, default: '' },
|
||||||
@@ -215,6 +215,8 @@ function onMessage(ev) {
|
|||||||
} else if (msg.type === 'saved') {
|
} else if (msg.type === 'saved') {
|
||||||
saveError.value = ''
|
saveError.value = ''
|
||||||
pendingSave = null
|
pendingSave = null
|
||||||
|
// Banner HTML/design changes affect the rendered page; invalidate prefetches.
|
||||||
|
dropPageCache()
|
||||||
refreshOnSave?.()
|
refreshOnSave?.()
|
||||||
refreshOnSave = null
|
refreshOnSave = null
|
||||||
} else if (msg.type === 'error') {
|
} else if (msg.type === 'error') {
|
||||||
|
|||||||
+45
-15
@@ -4,9 +4,9 @@
|
|||||||
// (/_api/ws/editor). Docked left of the article on the page itself.
|
// (/_api/ws/editor). Docked left of the article on the page itself.
|
||||||
// The socket connects when the editor is opened and reconnects with
|
// The socket connects when the editor is opened and reconnects with
|
||||||
// exponential backoff after a failure; unsaved text and pending saves
|
// exponential backoff after a failure; unsaved text and pending saves
|
||||||
// survive a disconnect. Editor scroll drives the article scroll (while
|
// survive a disconnect. Editor and article (window) scrolls are linked
|
||||||
// editing the window scroll is locked and only #main scrolls), keeping the
|
// proportionally both ways (syncWindowToEditor / syncEditorToWindow).
|
||||||
// rendered article at the cursor's position. Saving (💾 / Ctrl+S) is explicit
|
// Saving (💾 / Ctrl+S) is explicit
|
||||||
// and refreshes the page regions in place — never a reload — so the editor
|
// and refreshes the page regions in place — never a reload — so the editor
|
||||||
// state (unsaved text included) also survives closing the shell; it is lost
|
// state (unsaved text included) also survives closing the shell; it is lost
|
||||||
// only on a real page reload.
|
// only on a real page reload.
|
||||||
@@ -15,7 +15,7 @@ import { EditorView, basicSetup } from 'codemirror'
|
|||||||
import { EditorState } from '@codemirror/state'
|
import { EditorState } from '@codemirror/state'
|
||||||
import { markdown } from '@codemirror/lang-markdown'
|
import { markdown } from '@codemirror/lang-markdown'
|
||||||
import { cmHighlight, cmTheme } from './cmtheme'
|
import { cmHighlight, cmTheme } from './cmtheme'
|
||||||
import { loadPlain } from './swapdoc'
|
import { dropPageCache, loadPlain } from './swapdoc'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
pagePath: { type: String, default: '' },
|
pagePath: { type: String, default: '' },
|
||||||
@@ -113,7 +113,9 @@ async function saveAndRefresh() {
|
|||||||
await save()
|
await save()
|
||||||
dirty.value = false
|
dirty.value = false
|
||||||
// Refresh the page regions from the server so nav/sidebar changes apply
|
// Refresh the page regions from the server so nav/sidebar changes apply
|
||||||
// (never a reload: the editor keeps its state).
|
// (never a reload: the editor keeps its state). Drop the prefetch cache
|
||||||
|
// first: heading/title changes affect navigation on every page.
|
||||||
|
dropPageCache()
|
||||||
loadPlain(path.value)
|
loadPlain(path.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,20 +309,42 @@ function onEditorShown() {
|
|||||||
if (dirty.value) requestRender()
|
if (dirty.value) requestRender()
|
||||||
}
|
}
|
||||||
|
|
||||||
function syncScroll() {
|
// Bidirectional proportional scroll sync between the CodeMirror scroller
|
||||||
// Editor scroll drives the article: keep the rendered page at the same
|
// and the window (the article's scroller, also while editing). Both
|
||||||
// proportional position as the cursor area in the editor. While editing
|
// directions apply instantly (never smooth — a smooth window scroll feeds
|
||||||
// the window scroll is locked and #main is the scrolling element.
|
// its intermediate positions back into the editor and fights the user's
|
||||||
|
// scrolling) and coalesce to one update per frame. Loops are broken two
|
||||||
|
// ways: a driver flag held until one frame AFTER the write (the scroll
|
||||||
|
// event a programmatic write dispatches arrives asynchronously — clearing
|
||||||
|
// the flag in the writing frame would let the echo through and the two
|
||||||
|
// directions would chase each other, which showed up as random jumping
|
||||||
|
// whenever layout shifted the proportional targets mid-scroll), and a 1px
|
||||||
|
// tolerance so residual rounding is a no-op. When the panel's height
|
||||||
|
// changes mid-scroll (its top tracks the banner), the page is the driver:
|
||||||
|
// the editor is re-matched to the page's position, never vice versa.
|
||||||
|
function syncWindowToEditor() {
|
||||||
if (syncingScroll || !view) return
|
if (syncingScroll || !view) return
|
||||||
const main = document.getElementById('main')
|
|
||||||
if (!main) return
|
|
||||||
syncingScroll = true
|
syncingScroll = true
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
const scroller = view.scrollDOM
|
const scroller = view.scrollDOM
|
||||||
const max = scroller.scrollHeight - scroller.clientHeight
|
const max = scroller.scrollHeight - scroller.clientHeight
|
||||||
const pct = max > 0 ? scroller.scrollTop / max : 0
|
const pct = max > 0 ? scroller.scrollTop / max : 0
|
||||||
main.scrollTop = pct * (main.scrollHeight - main.clientHeight)
|
const y = pct * Math.max(0, document.documentElement.scrollHeight - innerHeight)
|
||||||
syncingScroll = false
|
if (Math.abs(scrollY - y) > 1) scrollTo({ top: y, behavior: 'instant' })
|
||||||
|
requestAnimationFrame(() => { syncingScroll = false })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncEditorToWindow() {
|
||||||
|
if (syncingScroll || !view) return
|
||||||
|
syncingScroll = true
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
const scroller = view.scrollDOM
|
||||||
|
const pageMax = Math.max(0, document.documentElement.scrollHeight - innerHeight)
|
||||||
|
const pct = pageMax > 0 ? scrollY / pageMax : 0
|
||||||
|
const top = pct * Math.max(0, scroller.scrollHeight - scroller.clientHeight)
|
||||||
|
if (Math.abs(scroller.scrollTop - top) > 1) scroller.scrollTop = top
|
||||||
|
requestAnimationFrame(() => { syncingScroll = false })
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,7 +403,11 @@ onMounted(() => {
|
|||||||
}),
|
}),
|
||||||
parent: editorEl.value,
|
parent: editorEl.value,
|
||||||
})
|
})
|
||||||
view.scrollDOM.addEventListener('scroll', syncScroll)
|
view.scrollDOM.addEventListener('scroll', syncWindowToEditor)
|
||||||
|
// Page → editor: window scroll (and resizes, e.g. the panel growing when
|
||||||
|
// the banner scrolls away) re-match the editor to the page's position.
|
||||||
|
addEventListener('scroll', syncEditorToWindow, { passive: true })
|
||||||
|
addEventListener('resize', syncEditorToWindow)
|
||||||
// Opening the editor means you want to write: start focused.
|
// Opening the editor means you want to write: start focused.
|
||||||
view.focus()
|
view.focus()
|
||||||
window.__pageritePageEditor = {
|
window.__pageritePageEditor = {
|
||||||
@@ -399,6 +427,8 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
view?.destroy()
|
view?.destroy()
|
||||||
delete window.__pageritePageEditor
|
delete window.__pageritePageEditor
|
||||||
|
removeEventListener('scroll', syncEditorToWindow)
|
||||||
|
removeEventListener('resize', syncEditorToWindow)
|
||||||
removeEventListener('keydown', onKeydown)
|
removeEventListener('keydown', onKeydown)
|
||||||
removeEventListener('pagerite:editor-shown', onEditorShown)
|
removeEventListener('pagerite:editor-shown', onEditorShown)
|
||||||
})
|
})
|
||||||
@@ -606,7 +636,7 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
/* CodeMirror sits inside a bordered box, like a dialog's input area, with
|
/* CodeMirror sits inside a bordered box, like a dialog's input area, with
|
||||||
a slight margin to the panel edges. Wheel scroll stays in the editor and
|
a slight margin to the panel edges. Wheel scroll stays in the editor and
|
||||||
drives the article (syncScroll) instead of double-scrolling. */
|
drives the article (syncWindowToEditor) instead of double-scrolling. */
|
||||||
.editor {
|
.editor {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { EditorState } from '@codemirror/state'
|
|||||||
import { css } from '@codemirror/lang-css'
|
import { css } from '@codemirror/lang-css'
|
||||||
import { html } from '@codemirror/lang-html'
|
import { html } from '@codemirror/lang-html'
|
||||||
import { cmHighlight, cmTheme } from './cmtheme'
|
import { cmHighlight, cmTheme } from './cmtheme'
|
||||||
import { loadPlain, runScripts } from './swapdoc'
|
import { dropPageCache, loadPlain, runScripts } from './swapdoc'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
pagePath: { type: String, default: '' },
|
pagePath: { type: String, default: '' },
|
||||||
@@ -110,6 +110,7 @@ async function uploadFavicon(file) {
|
|||||||
const { path: url } = await res.json()
|
const { path: url } = await res.json()
|
||||||
favicon.value = url
|
favicon.value = url
|
||||||
applyFavicon(url)
|
applyFavicon(url)
|
||||||
|
dropPageCache()
|
||||||
} else {
|
} else {
|
||||||
saveError.value = `⚠️ ${await errorDetail(res)}`
|
saveError.value = `⚠️ ${await errorDetail(res)}`
|
||||||
}
|
}
|
||||||
@@ -234,6 +235,7 @@ async function saveSettings(opts = {}) {
|
|||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
saveError.value = ''
|
saveError.value = ''
|
||||||
|
dropPageCache()
|
||||||
} else {
|
} else {
|
||||||
saveError.value = '⚠️ changes could not be saved'
|
saveError.value = '⚠️ changes could not be saved'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
import { inject, onActivated, onMounted, onUnmounted, provide, ref, watch } from 'vue'
|
import { inject, onActivated, onMounted, onUnmounted, provide, ref, watch } from 'vue'
|
||||||
import StructureTree from './StructureTree.vue'
|
import StructureTree from './StructureTree.vue'
|
||||||
import { slugify } from './slugify'
|
import { slugify } from './slugify'
|
||||||
import { loadPlain } from './swapdoc'
|
import { dropPageCache, loadPlain } from './swapdoc'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
pagePath: { type: String, default: '' },
|
pagePath: { type: String, default: '' },
|
||||||
@@ -144,6 +144,7 @@ async function commitPending() {
|
|||||||
}
|
}
|
||||||
pending.value = null
|
pending.value = null
|
||||||
await refreshPages()
|
await refreshPages()
|
||||||
|
dropPageCache()
|
||||||
await navigate(newPath)
|
await navigate(newPath)
|
||||||
// Hand over to the page editor tab for the actual writing.
|
// Hand over to the page editor tab for the actual writing.
|
||||||
shell?.switchMode('page')
|
shell?.switchMode('page')
|
||||||
@@ -171,6 +172,8 @@ async function postStructure(op) {
|
|||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
saveError.value = ''
|
saveError.value = ''
|
||||||
|
// Structure changes alter navigation on every page; drop prefetches.
|
||||||
|
dropPageCache()
|
||||||
loadPlain(path.value) // refresh menus and content from the server
|
loadPlain(path.value) // refresh menus and content from the server
|
||||||
} else {
|
} else {
|
||||||
saveError.value = `⚠️ ${await errorDetail(res)}`
|
saveError.value = `⚠️ ${await errorDetail(res)}`
|
||||||
@@ -234,6 +237,7 @@ async function removePage(node) {
|
|||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
saveError.value = ''
|
saveError.value = ''
|
||||||
refreshPages()
|
refreshPages()
|
||||||
|
dropPageCache()
|
||||||
const p = node.path
|
const p = node.path
|
||||||
if (p === path.value || (p && path.value.startsWith(`${p}/`))) {
|
if (p === path.value || (p && path.value.startsWith(`${p}/`))) {
|
||||||
// The current page was deleted — or reduced to a category, which now
|
// The current page was deleted — or reduced to a category, which now
|
||||||
|
|||||||
@@ -1,18 +1,33 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { formatCount } from './analytics/format.js'
|
import { computed } from 'vue'
|
||||||
|
import { formatCount, formatReadTime } from './analytics/format.js'
|
||||||
|
|
||||||
defineProps({
|
const props = defineProps({
|
||||||
step: { type: Object, required: true },
|
step: { type: Object, required: true },
|
||||||
count: { type: Number, default: 0 },
|
count: { type: Number, default: 0 },
|
||||||
})
|
})
|
||||||
|
|
||||||
defineEmits(['close'])
|
defineEmits(['close'])
|
||||||
|
|
||||||
|
const hasError = computed(() => props.step.status >= 400)
|
||||||
|
|
||||||
|
const title = computed(() => {
|
||||||
|
const parts = [props.step.title]
|
||||||
|
if (props.step.readSeconds > 0) {
|
||||||
|
parts.push(formatReadTime(props.step.readSeconds))
|
||||||
|
}
|
||||||
|
if (hasError.value) {
|
||||||
|
parts.push(`${props.step.status}`)
|
||||||
|
}
|
||||||
|
return parts.filter(Boolean).join(' — ')
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<a class="trail-link"
|
<a class="trail-link"
|
||||||
|
:class="{ error: hasError }"
|
||||||
:href="step.path"
|
:href="step.path"
|
||||||
:title="count > 1 ? `${step.title} (${count} hits)` : step.title"
|
:title="title"
|
||||||
:target="step.external ? '_blank' : undefined"
|
:target="step.external ? '_blank' : undefined"
|
||||||
:rel="step.external ? 'noopener' : undefined"
|
:rel="step.external ? 'noopener' : undefined"
|
||||||
@click="(e) => { if (!step.external) $emit('close') }">
|
@click="(e) => { if (!step.external) $emit('close') }">
|
||||||
|
|||||||
+137
-112
@@ -1,165 +1,169 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
/**
|
/**
|
||||||
* Radial transition map filtered to the selected time range.
|
* Radial transition map for a pre-filtered time range.
|
||||||
*
|
*
|
||||||
* Transitions are stored per 5-minute bucket (from -> to -> bucket ->
|
* The parent filters transitions, views and visits to the selected range
|
||||||
* count), so the graph sums the buckets falling inside the selected
|
* before passing them in; `window` carries the absolute [t0, t1) window
|
||||||
* range, exactly like the charts and per-page views do.
|
* so the visual scale can normalize against a one-week reference.
|
||||||
*/
|
*/
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'
|
||||||
import { rangeWindow, WEEK } from './analytics/time.js'
|
import { DAY } from './analytics/time.js'
|
||||||
import { formatCount } from './analytics/format.js'
|
import { formatCount, formatReadTime } from './analytics/format.js'
|
||||||
import {
|
import {
|
||||||
TNODE_W,
|
TNODE_W,
|
||||||
TNODE_H,
|
TNODE_H,
|
||||||
BEAD_R,
|
BEAD_R,
|
||||||
BEAD_SPEED,
|
|
||||||
buildTransitionGraph,
|
buildTransitionGraph,
|
||||||
filterTransitionsByRange,
|
|
||||||
filterViewsByRange,
|
|
||||||
filterVisitsByRange,
|
|
||||||
} from './analytics/transitions.js'
|
} from './analytics/transitions.js'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
data: { type: Object, default: null },
|
data: { type: Object, default: null },
|
||||||
range: { type: String, required: true },
|
window: { type: Object, required: true },
|
||||||
pageTree: { type: Array, default: null },
|
pageTree: { type: Array, default: null },
|
||||||
})
|
})
|
||||||
|
|
||||||
const window = computed(() => rangeWindow(props.range))
|
const dayScale = computed(() => {
|
||||||
|
const { t0, t1 } = props.window
|
||||||
const visualScale = computed(() => {
|
// Convert raw counts to a daily hit rate (hits/day).
|
||||||
const { t0, t1 } = window.value
|
if (t0 != null && t1 != null) return DAY / (t1 - t0)
|
||||||
if (t0 != null && t1 != null) return WEEK / (t1 - t0)
|
// 'all': scale by the actual data span, but never less than the 30-day
|
||||||
// 'all': scale by the actual data span.
|
// minimum the plot enforces, so sparse young data is not over-amplified.
|
||||||
const times = new Set()
|
const times = new Set()
|
||||||
for (const buckets of Object.values(props.data?.views || {})) {
|
for (const buckets of Object.values(props.data?.views || {})) {
|
||||||
for (const k of Object.keys(buckets)) times.add(Date.parse(k))
|
for (const k of Object.keys(buckets)) times.add(Date.parse(k))
|
||||||
}
|
}
|
||||||
const arr = [...times]
|
const arr = [...times]
|
||||||
if (arr.length < 2) return 1
|
if (arr.length < 2) return 1
|
||||||
return WEEK / (Math.max(...arr) - Math.min(...arr))
|
const span = Math.max(...arr) - Math.min(...arr)
|
||||||
|
return DAY / Math.max(span, 30 * DAY)
|
||||||
})
|
})
|
||||||
|
|
||||||
const filteredData = computed(() => {
|
|
||||||
if (!props.data) return null
|
|
||||||
const { t0, t1 } = window.value
|
|
||||||
return {
|
|
||||||
transitions: filterTransitionsByRange(props.data.transitions, t0, t1),
|
|
||||||
views: filterViewsByRange(props.data.views, t0, t1),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const filteredVisits = computed(() =>
|
|
||||||
filterVisitsByRange(props.data?.visits, window.value.t0, window.value.t1),
|
|
||||||
)
|
|
||||||
|
|
||||||
const graph = computed(() =>
|
const graph = computed(() =>
|
||||||
filteredData.value
|
props.data
|
||||||
? buildTransitionGraph(filteredData.value, props.pageTree, filteredVisits.value, visualScale.value)
|
? buildTransitionGraph(props.data, props.pageTree, props.data.visits || [], dayScale.value)
|
||||||
: null,
|
: null,
|
||||||
)
|
)
|
||||||
|
|
||||||
// Bead animation: every bead is simulated independently in JS. Each flow
|
// Bead animation: every bead is simulated independently in JS. Each flow
|
||||||
// (one per edge direction) emits a bead every `interval` seconds; beads
|
// (one per edge direction) emits a bead every `interval` seconds; beads
|
||||||
// travel at BEAD_SPEED along the segment and are dropped at the end.
|
// cross their segment in a constant TRAVERSAL_S seconds (speed relative
|
||||||
|
// to span length) and are dropped at the end.
|
||||||
// There is deliberately no cap on beads in flight.
|
// There is deliberately no cap on beads in flight.
|
||||||
|
// Emitters persist across data reloads, keyed by flow.key: an unchanged
|
||||||
|
// link keeps its emission phase and in-flight beads (tracked by progress,
|
||||||
|
// not absolute time), so a count change elsewhere never reshuffles them.
|
||||||
const beads = shallowRef([])
|
const beads = shallowRef([])
|
||||||
let rafId = 0
|
let rafId = 0
|
||||||
|
const emitters = new Map() // flow.key -> { flow, interval, next, alive }
|
||||||
|
const live = [] // { e, p } — beads in flight, p = progress 0..1
|
||||||
|
let lastTick = 0
|
||||||
|
|
||||||
const MAX_BEAD_RATE = 120 // upper bound on total beads per second
|
const MAX_BEAD_RATE = 120 // upper bound on total beads per second
|
||||||
|
const TRAVERSAL_S = 0.4 // seconds to cross any segment, end to end
|
||||||
|
|
||||||
const startBeads = (flows) => {
|
const syncBeads = (flows) => {
|
||||||
cancelAnimationFrame(rafId)
|
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||||
|
if (!flows?.length || reduced) {
|
||||||
|
emitters.clear()
|
||||||
|
live.length = 0
|
||||||
beads.value = []
|
beads.value = []
|
||||||
if (!flows?.length) return
|
return
|
||||||
if (matchMedia('(prefers-reduced-motion: reduce)').matches) return
|
}
|
||||||
|
|
||||||
// Cap the total bead emission rate so a busy range cannot spawn enough
|
// Cap the total bead emission rate so a busy range cannot spawn enough
|
||||||
// beads to kill the page. Existing per-range time scaling is preserved;
|
// beads to kill the page. Existing per-range time scaling is preserved;
|
||||||
// this is only a proportional emergency throttle when the limit is hit.
|
// this is only a proportional emergency throttle when the limit is hit.
|
||||||
const totalRate = flows.reduce((s, f) => s + 1 / f.interval, 0)
|
const totalRate = flows.reduce((s, f) => s + 1 / f.interval, 0)
|
||||||
const scale = totalRate > MAX_BEAD_RATE ? MAX_BEAD_RATE / totalRate : 1
|
const scale = totalRate > MAX_BEAD_RATE ? MAX_BEAD_RATE / totalRate : 1
|
||||||
|
|
||||||
const live = [] // { flow, t0 } — one entry per bead in flight
|
|
||||||
const now = performance.now()
|
const now = performance.now()
|
||||||
const emitters = flows.map((flow) => {
|
const seen = new Set()
|
||||||
|
for (const flow of flows) {
|
||||||
|
seen.add(flow.key)
|
||||||
const interval = (flow.interval / scale) * 1000
|
const interval = (flow.interval / scale) * 1000
|
||||||
// Pre-fill the traversal with evenly spaced beads (random phase), so
|
const e = emitters.get(flow.key)
|
||||||
// the flow appears already running instead of starting empty.
|
if (e) {
|
||||||
|
e.flow = flow // pick up new geometry/rate, keep the phase
|
||||||
|
e.interval = interval
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// New emitter: pre-fill the traversal with evenly spaced beads (random
|
||||||
|
// phase), so the flow appears already running instead of empty.
|
||||||
const phase = Math.random() * interval
|
const phase = Math.random() * interval
|
||||||
for (let t = now - (flow.len / BEAD_SPEED) * 1000 + phase; t <= now; t += interval) {
|
const dp = interval / 1000 / TRAVERSAL_S
|
||||||
live.push({ flow, t0: t })
|
const ne = { flow, interval, next: now + phase, alive: true }
|
||||||
|
for (let p = 1 - phase / 1000 / TRAVERSAL_S; p > 0; p -= dp) {
|
||||||
|
live.push({ e: ne, p })
|
||||||
|
}
|
||||||
|
emitters.set(flow.key, ne)
|
||||||
|
}
|
||||||
|
for (const [key, e] of emitters) {
|
||||||
|
if (!seen.has(key)) {
|
||||||
|
e.alive = false
|
||||||
|
emitters.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let i = live.length - 1; i >= 0; i--) {
|
||||||
|
if (!live[i].e.alive) live.splice(i, 1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return { flow, interval, next: now + phase }
|
|
||||||
})
|
|
||||||
|
|
||||||
const tick = (t) => {
|
const tick = (t) => {
|
||||||
for (const e of emitters) {
|
const dt = lastTick ? (t - lastTick) / 1000 : 0
|
||||||
|
lastTick = t
|
||||||
|
for (const e of emitters.values()) {
|
||||||
while (e.next <= t) {
|
while (e.next <= t) {
|
||||||
live.push({ flow: e.flow, t0: e.next })
|
live.push({ e, p: 0 })
|
||||||
e.next += e.interval
|
e.next += e.interval
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const out = []
|
const out = []
|
||||||
for (let i = live.length - 1; i >= 0; i--) {
|
for (let i = live.length - 1; i >= 0; i--) {
|
||||||
const b = live[i]
|
const b = live[i]
|
||||||
const p = ((t - b.t0) / 1000) * BEAD_SPEED / b.flow.len
|
b.p += dt / TRAVERSAL_S
|
||||||
if (p >= 1) {
|
if (b.p >= 1) {
|
||||||
live.splice(i, 1)
|
live.splice(i, 1)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out.push({
|
const f = b.e.flow
|
||||||
x: b.flow.x1 + (b.flow.x2 - b.flow.x1) * p,
|
out.push({ x: f.x1 + (f.x2 - f.x1) * b.p, y: f.y1 + (f.y2 - f.y1) * b.p })
|
||||||
y: b.flow.y1 + (b.flow.y2 - b.flow.y1) * p,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
beads.value = out
|
beads.value = out
|
||||||
rafId = requestAnimationFrame(tick)
|
rafId = requestAnimationFrame(tick)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
watch(() => graph.value?.flows, syncBeads, { immediate: true })
|
||||||
|
onMounted(() => {
|
||||||
|
if (!matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||||
rafId = requestAnimationFrame(tick)
|
rafId = requestAnimationFrame(tick)
|
||||||
}
|
}
|
||||||
|
})
|
||||||
watch(() => graph.value?.flows, startBeads, { immediate: true })
|
|
||||||
onBeforeUnmount(() => cancelAnimationFrame(rafId))
|
onBeforeUnmount(() => cancelAnimationFrame(rafId))
|
||||||
|
|
||||||
// Text in the graph must render at a constant screen size regardless of
|
// The svg never renders larger than its natural size (1 viewBox unit = 1
|
||||||
// how far the enlarged graph's viewBox is scaled down to fit the panel:
|
// px, max-width below): the layout geometry is designed in pixel-like
|
||||||
// measure the unit→pixel ratio and expose it as --u on the svg, which the
|
// units, and upscaling would blow up the pills around their text. Narrow
|
||||||
// font-size rules divide by. Falls back to 1 (raw units) until measured.
|
// panels scale the graph down to fit (width: 100%), text along with it.
|
||||||
const svgEl = ref(null)
|
|
||||||
const pxPerUnit = ref(1)
|
|
||||||
let resizeObs = null
|
|
||||||
|
|
||||||
function updateScale() {
|
// Pill text is not truncated: text is clipped at the pill's rounded border
|
||||||
const el = svgEl.value
|
// (clipPath per node, inset a few units for padding). Captions center when
|
||||||
if (el && el.viewBox.baseVal.width) {
|
// they fit; overlong ones anchor left so their beginning (not their
|
||||||
pxPerUnit.value = el.clientWidth / el.viewBox.baseVal.width
|
// middle) survives the clip. Width estimate: ~0.52 em per glyph.
|
||||||
}
|
const fitsPill = (label, fontPx = 19) => label.length * 0.52 * fontPx <= TNODE_W - 16
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
const countLabel = (n) =>
|
||||||
resizeObs = new ResizeObserver(updateScale)
|
n.readSec ? `${formatCount(n.views)}×${formatReadTime(n.readSec)}` : formatCount(n.views)
|
||||||
})
|
|
||||||
watch(svgEl, (el) => {
|
|
||||||
resizeObs?.disconnect()
|
|
||||||
if (el) resizeObs?.observe(el)
|
|
||||||
})
|
|
||||||
watch(() => graph.value?.bounds, updateScale)
|
|
||||||
onBeforeUnmount(() => resizeObs?.disconnect())
|
|
||||||
|
|
||||||
// Font size (px) that fits a label inside the pill width at the current
|
|
||||||
// zoom: ~0.52 em average glyph width, 12 px padding per side, capped.
|
|
||||||
const fitPx = (label) =>
|
|
||||||
Math.min(15, (TNODE_W * pxPerUnit.value - 24) / (0.52 * Math.max(label.length, 1)))
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section v-if="graph">
|
<section v-if="graph">
|
||||||
<svg ref="svgEl" class="tmap" :style="{ '--u': pxPerUnit }" :viewBox="`${graph.bounds.x0} ${graph.bounds.y0} ${graph.bounds.x1 - graph.bounds.x0} ${graph.bounds.y1 - graph.bounds.y0}`"
|
<svg class="tmap" :style="{ maxWidth: `${graph.bounds.x1 - graph.bounds.x0}px` }" :viewBox="`${graph.bounds.x0} ${graph.bounds.y0} ${graph.bounds.x1 - graph.bounds.x0} ${graph.bounds.y1 - graph.bounds.y0}`"
|
||||||
role="img" aria-label="map of transitions between pages">
|
role="img" aria-label="map of transitions between pages">
|
||||||
<path v-for="(a, i) in graph.arcs" :key="'a' + i"
|
<path v-for="(a, i) in graph.arcs" :key="'a' + i"
|
||||||
:d="a.d" class="tarc" />
|
:id="`tarc${i}`" :d="a.d" :class="['tarc', a.top && 'tarc-top']" />
|
||||||
|
<template v-for="(a, i) in graph.arcs" :key="'t' + i">
|
||||||
|
<path v-if="a.ld" :id="`tarcl${i}`" :d="a.ld" fill="none" stroke="none" />
|
||||||
|
<text v-if="a.ld" class="tarclabel" :class="{ 'tarclabel-top': a.top }"><textPath :href="`#tarcl${i}`" startOffset="0">{{ a.label }}</textPath></text>
|
||||||
|
</template>
|
||||||
<path v-for="(e, i) in graph.edges" :key="'e' + i"
|
<path v-for="(e, i) in graph.edges" :key="'e' + i"
|
||||||
:d="e.d" :class="['tconn', e.external && 'tconn-exit']">
|
:d="e.d" :class="['tconn', e.external && 'tconn-exit']">
|
||||||
<title>{{ e.title }}</title>
|
<title>{{ e.title }}</title>
|
||||||
@@ -167,35 +171,44 @@ const fitPx = (label) =>
|
|||||||
<circle v-for="(b, i) in beads" :key="'b' + i"
|
<circle v-for="(b, i) in beads" :key="'b' + i"
|
||||||
:cx="b.x" :cy="b.y" :r="BEAD_R" class="tbead" />
|
:cx="b.x" :cy="b.y" :r="BEAD_R" class="tbead" />
|
||||||
<g v-for="(x, i) in graph.extNodes" :key="'x' + i">
|
<g v-for="(x, i) in graph.extNodes" :key="'x' + i">
|
||||||
|
<clipPath :id="`xclip${i}`">
|
||||||
|
<rect :x="x.x - TNODE_W/2 + 6" :y="x.y - TNODE_H/2" :width="TNODE_W - 12"
|
||||||
|
:height="TNODE_H" :rx="TNODE_H/2 - 4" />
|
||||||
|
</clipPath>
|
||||||
<a v-if="x.href" :href="x.href" target="_blank" rel="noopener">
|
<a v-if="x.href" :href="x.href" target="_blank" rel="noopener">
|
||||||
<title>{{ x.path }}</title>
|
<title>{{ x.path }}</title>
|
||||||
<rect :x="x.x - TNODE_W/2" :y="x.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2"
|
<rect :x="x.x - TNODE_W/2" :y="x.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2"
|
||||||
:class="['txnode', x.kind === 'source' ? 'txnode-source' : 'txnode-exit']" />
|
:class="['txnode', x.kind === 'source' ? 'txnode-source' : 'txnode-exit']" />
|
||||||
<text :x="x.x" :y="x.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle"
|
<g :clip-path="`url(#xclip${i})`">
|
||||||
:style="{ '--slug-px': `${fitPx(x.label)}px` }">{{ x.label }}</text>
|
<text :x="fitsPill(x.label) ? x.x : x.x - TNODE_W/2 + 8" :y="x.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle" :style="{ textAnchor: fitsPill(x.label) ? 'middle' : 'start' }">{{ x.label }}</text>
|
||||||
<text :x="x.x" :y="x.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">{{ formatCount(x.count) }}</text>
|
<text :x="x.x" :y="x.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">{{ formatCount(x.count) }}</text>
|
||||||
|
</g>
|
||||||
</a>
|
</a>
|
||||||
<g v-else>
|
<g v-else>
|
||||||
<title>{{ x.path }}</title>
|
<title>{{ x.path }}</title>
|
||||||
<rect :x="x.x - TNODE_W/2" :y="x.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2"
|
<rect :x="x.x - TNODE_W/2" :y="x.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2"
|
||||||
:class="['txnode', x.kind === 'source' ? 'txnode-source' : 'txnode-exit']" />
|
:class="['txnode', x.kind === 'source' ? 'txnode-source' : 'txnode-exit']" />
|
||||||
<text :x="x.x" :y="x.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle"
|
<g :clip-path="`url(#xclip${i})`">
|
||||||
:style="{ '--slug-px': `${fitPx(x.label)}px` }">{{ x.label }}</text>
|
<text :x="fitsPill(x.label) ? x.x : x.x - TNODE_W/2 + 8" :y="x.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle" :style="{ textAnchor: fitsPill(x.label) ? 'middle' : 'start' }">{{ x.label }}</text>
|
||||||
<text :x="x.x" :y="x.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">{{ formatCount(x.count) }}</text>
|
<text :x="x.x" :y="x.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">{{ formatCount(x.count) }}</text>
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
<g v-for="n in graph.nodes" :key="n.path">
|
</g>
|
||||||
|
<g v-for="(n, i) in graph.nodes" :key="n.path">
|
||||||
|
<clipPath :id="`nclip${i}`">
|
||||||
|
<rect :x="n.x - TNODE_W/2 + 6" :y="n.y - TNODE_H/2" :width="TNODE_W - 12"
|
||||||
|
:height="TNODE_H" :rx="TNODE_H/2 - 4" />
|
||||||
|
</clipPath>
|
||||||
<a :href="n.path">
|
<a :href="n.path">
|
||||||
<title>{{ n.title }}</title>
|
<title>{{ n.title }}</title>
|
||||||
<rect :x="n.x - TNODE_W/2" :y="n.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2" class="tnode" />
|
<rect :x="n.x - TNODE_W/2" :y="n.y - TNODE_H/2" :width="TNODE_W" :height="TNODE_H" :rx="TNODE_H/2" class="tnode" />
|
||||||
<text :x="n.x" :y="n.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle"
|
<g :clip-path="`url(#nclip${i})`">
|
||||||
:style="{ '--slug-px': `${fitPx(n.label)}px` }">{{ n.label }}</text>
|
<text :x="fitsPill(n.label) ? n.x : n.x - TNODE_W/2 + 8" :y="n.y - TNODE_H*0.16" class="tnodeslug" dominant-baseline="middle" :style="{ textAnchor: fitsPill(n.label) ? 'middle' : 'start' }">{{ n.label }}</text>
|
||||||
<text :x="n.x" :y="n.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">
|
<text :x="n.x" :y="n.y + TNODE_H*0.24" class="tnodecount" dominant-baseline="middle">
|
||||||
{{ n.readMin ? `${formatCount(n.views)}×${n.readMin}m` : formatCount(n.views) }}
|
{{ countLabel(n) }}
|
||||||
</text>
|
</text>
|
||||||
|
</g>
|
||||||
</a>
|
</a>
|
||||||
<text v-if="n.crumb" :x="n.x" :y="n.y - TNODE_H/2 - 10"
|
|
||||||
:class="['tnodepath', n.path === '/' && 'tnodepath-home']">{{ n.crumb }}</text>
|
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
</section>
|
</section>
|
||||||
@@ -206,7 +219,9 @@ const fitPx = (label) =>
|
|||||||
.tmap {
|
.tmap {
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-width: 100%;
|
/* max-width is set inline to the natural content width (px = viewBox
|
||||||
|
units), so wide panels never upscale the graph beyond 1:1. */
|
||||||
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
.tmap .tconn {
|
.tmap .tconn {
|
||||||
fill: var(--accent);
|
fill: var(--accent);
|
||||||
@@ -226,36 +241,46 @@ const fitPx = (label) =>
|
|||||||
}
|
}
|
||||||
.tmap .txnode-source { fill: var(--text); }
|
.tmap .txnode-source { fill: var(--text); }
|
||||||
.tmap .txnode-exit { fill: var(--text); }
|
.tmap .txnode-exit { fill: var(--text); }
|
||||||
|
/* Branch lanes: one wide concentric arc per path prefix, running behind
|
||||||
|
the node pills around the fan's circle center; parent levels sit one
|
||||||
|
indent (radius step) outward. Each lane's label follows a short guide
|
||||||
|
arc across the first inter-node gap (the part pills never cover). */
|
||||||
.tmap .tarc {
|
.tmap .tarc {
|
||||||
fill: none;
|
fill: none;
|
||||||
stroke: var(--line);
|
stroke: var(--muted);
|
||||||
stroke-width: 1;
|
stroke-width: 16;
|
||||||
|
opacity: 0.25;
|
||||||
|
}
|
||||||
|
.tmap .tarc-top { stroke-width: 24; }
|
||||||
|
/* Lane labels are left-aligned: each guide arc starts just past the source
|
||||||
|
pill's edge, the earliest point where the text is visible. */
|
||||||
|
.tmap .tarclabel {
|
||||||
|
fill: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
text-anchor: start;
|
||||||
|
}
|
||||||
|
/* The top lane is 50% thicker; its 🏠︎ label scales along. */
|
||||||
|
.tmap .tarclabel-top {
|
||||||
|
font-size: 19.5px;
|
||||||
}
|
}
|
||||||
.tmap .tnode {
|
.tmap .tnode {
|
||||||
fill: var(--accent);
|
fill: var(--accent);
|
||||||
stroke: none;
|
stroke: none;
|
||||||
}
|
}
|
||||||
/* Text renders at a constant screen size: --u (set from JS) is the
|
/* Text sizes are viewBox units: they shrink along with the graph on
|
||||||
viewBox-unit → pixel ratio of the rendered svg, so dividing by it makes
|
narrow panels. Overlong labels are clipped at the pill border. */
|
||||||
the sizes independent of how far the graph is scaled down. */
|
|
||||||
.tmap .tnodeslug {
|
.tmap .tnodeslug {
|
||||||
fill: var(--bg, Canvas);
|
fill: var(--bg, Canvas);
|
||||||
font-size: calc(var(--slug-px, 15px) / var(--u, 1));
|
font-size: 19px;
|
||||||
text-anchor: middle;
|
text-anchor: start;
|
||||||
}
|
}
|
||||||
.tmap a { cursor: pointer; }
|
.tmap a { cursor: pointer; }
|
||||||
.tmap .tnodecount {
|
.tmap .tnodecount {
|
||||||
fill: var(--bg, Canvas);
|
fill: var(--bg, Canvas);
|
||||||
opacity: 0.75;
|
opacity: 0.75;
|
||||||
font-size: calc(13px / var(--u, 1));
|
font-size: 15px;
|
||||||
text-anchor: middle;
|
text-anchor: middle;
|
||||||
}
|
}
|
||||||
.tmap .tnodepath {
|
|
||||||
fill: var(--muted);
|
|
||||||
font-size: calc(11px / var(--u, 1));
|
|
||||||
text-anchor: middle;
|
|
||||||
}
|
|
||||||
.tmap .tnodepath-home { font-size: calc(17px / var(--u, 1)); }
|
|
||||||
|
|
||||||
section { margin-top: 1.8rem; }
|
section { margin-top: 1.8rem; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -4,10 +4,23 @@
|
|||||||
*/
|
*/
|
||||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||||
import { makeSeries } from './analytics/time.js'
|
import { makeSeries } from './analytics/time.js'
|
||||||
import { CHART_H, CHART_W, buildChart, fmtY } from './analytics/chart.js'
|
import {
|
||||||
|
CHART_H,
|
||||||
|
CHART_W,
|
||||||
|
MARGIN_B,
|
||||||
|
MARGIN_L,
|
||||||
|
VIEW_H,
|
||||||
|
VIEW_W,
|
||||||
|
buildChart,
|
||||||
|
} from './analytics/chart.js'
|
||||||
|
|
||||||
const DAY_REFRESH_MS = 15000
|
const DAY_REFRESH_MS = 15000
|
||||||
|
|
||||||
|
// Keep the whole svg within page bounds: full width below the natural
|
||||||
|
// size, centered with equal side margins above it (max() clamps the
|
||||||
|
// centering margin to 0 at the breakpoint, so the rule is continuous).
|
||||||
|
const CHART_MARGIN = `max(0px, calc(50% - ${VIEW_W / 2}px))`
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
data: { type: Object, default: null },
|
data: { type: Object, default: null },
|
||||||
range: { type: String, required: true },
|
range: { type: String, required: true },
|
||||||
@@ -29,6 +42,17 @@ function freqLabel(unit) {
|
|||||||
return unit === '5min' ? '5 min' : unit === 'hour' ? 'hourly' : 'daily'
|
return unit === '5min' ? '5 min' : unit === 'hour' ? 'hourly' : 'daily'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Vertical axis caption: "visits / 5 min" on the day view, else "hourly visits" style. */
|
||||||
|
function axisLabel(unit, ylabel) {
|
||||||
|
return unit === '5min' ? `${ylabel} / 5 min` : `${freqLabel(unit)} ${ylabel}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Legend label for the overlaid past weeks: "Week M" or "Week M–N". */
|
||||||
|
function pastLabel(series) {
|
||||||
|
const oldest = series.at(-1).label.slice(5) // strip "Week "
|
||||||
|
return series.length > 2 ? `Week ${oldest}–${series[1].label.slice(5)}` : `Week ${oldest}`
|
||||||
|
}
|
||||||
|
|
||||||
const now = ref(Date.now())
|
const now = ref(Date.now())
|
||||||
let refreshInterval = null
|
let refreshInterval = null
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
@@ -44,16 +68,13 @@ const viewChart = computed(() => buildChart(viewSeries.value, now.value))
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section v-for="c in [
|
<section v-for="c in [
|
||||||
{ ylabel: 'visits', chart: visitChart, empty: 'no visits recorded yet' },
|
{ ylabel: 'visits', chart: visitChart, legend: true },
|
||||||
{ ylabel: 'views', chart: viewChart, empty: 'no views recorded yet' },
|
{ ylabel: 'views', chart: viewChart, legend: false },
|
||||||
]" :key="c.ylabel">
|
]" :key="c.ylabel">
|
||||||
<template v-if="c.chart">
|
<template v-if="c.chart">
|
||||||
<div class="chartwrap">
|
<svg class="chart" :viewBox="`${-MARGIN_L} 0 ${VIEW_W} ${VIEW_H}`"
|
||||||
<div class="plot">
|
:style="{ maxWidth: `${VIEW_W}px`, marginLeft: CHART_MARGIN }"
|
||||||
<div class="plotarea">
|
role="img" :aria-label="axisLabel(c.chart.unit, c.ylabel)">
|
||||||
<span class="yaxis-label">{{ freqLabel(c.chart.unit) }} {{ c.ylabel }}</span>
|
|
||||||
<svg class="chart" :viewBox="`0 0 ${CHART_W} ${CHART_H}`"
|
|
||||||
preserveAspectRatio="none" role="img" :aria-label="`${freqLabel(c.chart.unit)} ${c.ylabel}`">
|
|
||||||
<line v-for="g in c.chart.majors.slice(1)" :key="'j' + g.value"
|
<line v-for="g in c.chart.majors.slice(1)" :key="'j' + g.value"
|
||||||
:x1="0" :x2="CHART_W" :y1="g.y" :y2="g.y" class="major" />
|
:x1="0" :x2="CHART_W" :y1="g.y" :y2="g.y" class="major" />
|
||||||
<template v-for="t in c.chart.xticks" :key="'t' + t.x">
|
<template v-for="t in c.chart.xticks" :key="'t' + t.x">
|
||||||
@@ -66,85 +87,67 @@ const viewChart = computed(() => buildChart(viewSeries.value, now.value))
|
|||||||
<path :d="c.chart.skyline" class="line" />
|
<path :d="c.chart.skyline" class="line" />
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<template v-for="(s, i) in c.chart.series" :key="i">
|
<!-- Oldest overlay weeks first so the current week paints on top. -->
|
||||||
|
<template v-for="(s, i) in [...c.chart.series].reverse()" :key="i">
|
||||||
<path v-if="s.area" :d="s.area" class="area" />
|
<path v-if="s.area" :d="s.area" class="area" />
|
||||||
<path :d="s.line" class="line" :style="{ opacity: s.opacity }" />
|
<path :d="s.line" class="line" :class="{ past: s.past }"
|
||||||
|
:style="{ opacity: s.opacity }" />
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
<line :x1="0" :x2="CHART_W" :y1="CHART_H - 0.5" :y2="CHART_H - 0.5"
|
<line :x1="0" :x2="CHART_W" :y1="CHART_H - 0.5" :y2="CHART_H - 0.5"
|
||||||
class="axis" />
|
class="axis" />
|
||||||
|
<text v-for="g in c.chart.majors" :key="'y' + g.value" x="-5" :y="g.y"
|
||||||
|
text-anchor="end" dominant-baseline="middle" class="ylab">{{ g.label }}</text>
|
||||||
|
<text :x="-(MARGIN_L - 10)" :y="CHART_H / 2" text-anchor="middle"
|
||||||
|
:transform="`rotate(-90 ${-(MARGIN_L - 10)} ${CHART_H / 2})`"
|
||||||
|
class="yaxis-label">{{ axisLabel(c.chart.unit, c.ylabel) }}</text>
|
||||||
|
<text v-for="t in c.chart.xticks" :key="'x' + t.x" :x="t.x" :y="CHART_H + MARGIN_B - 8"
|
||||||
|
text-anchor="middle" class="xlab">{{ t.label }}</text>
|
||||||
|
<!-- Week overlay legend, top right inside the plot: current week in
|
||||||
|
accent, one muted specimen for the whole past range. -->
|
||||||
|
<g v-if="c.legend && c.chart.series.length > 1">
|
||||||
|
<line :x1="CHART_W - 98" :x2="CHART_W - 78" y1="10" y2="10" class="line" />
|
||||||
|
<text :x="CHART_W - 72" y="10" dominant-baseline="middle"
|
||||||
|
class="leglab">{{ c.chart.series[0].label }}</text>
|
||||||
|
<line :x1="CHART_W - 98" :x2="CHART_W - 78" y1="25" y2="25"
|
||||||
|
class="line past" style="opacity: 0.6" />
|
||||||
|
<text :x="CHART_W - 72" y="25" dominant-baseline="middle"
|
||||||
|
class="leglab">{{ pastLabel(c.chart.series) }}</text>
|
||||||
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
<span v-for="g in c.chart.majors" :key="g.value" class="ylab"
|
|
||||||
:style="{ bottom: g.bottom + '%' }">{{ fmtY(g.value) }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="xlabels">
|
|
||||||
<span v-for="t in c.chart.xticks" :key="t.x" class="xlab"
|
|
||||||
:style="{ left: t.left + '%' }">{{ t.label }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-if="c.chart.series && c.chart.series.length > 1" class="legend">
|
|
||||||
<span v-for="(s, i) in c.chart.series" :key="i" :style="{ opacity: s.opacity }">
|
|
||||||
● {{ s.label }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
<p v-else class="empty">{{ c.empty }}</p>
|
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
/* The svg is stretched (preserveAspectRatio none), so all text lives in
|
/* Each chart is a self-contained SVG: the viewBox includes the axis label
|
||||||
HTML overlays positioned by the same fractions the geometry uses. */
|
margins, so nothing is positioned with HTML overlays. Never upscale past
|
||||||
.chartwrap {
|
the natural size (1 viewBox unit = 1 px, max-width set inline) — that
|
||||||
padding-left: 2.8rem; /* y labels */
|
would blow up the constant-size text; smaller panels still scale the
|
||||||
}
|
chart down to fit. The margin-left (set inline) centers the chart above
|
||||||
|
its natural width; the svg always stays within page bounds.
|
||||||
.plot {
|
overflow: visible lets wider fonts extend past the viewBox instead of
|
||||||
display: flex;
|
clipping. */
|
||||||
flex-direction: column;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.plotarea {
|
|
||||||
position: relative;
|
|
||||||
height: 8rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.xlabels {
|
|
||||||
position: relative;
|
|
||||||
height: 1.2rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chart {
|
.chart {
|
||||||
display: block;
|
display: block;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: auto;
|
||||||
|
overflow: visible;
|
||||||
}
|
}
|
||||||
|
|
||||||
.ylab {
|
.chart .ylab,
|
||||||
position: absolute;
|
.chart .xlab,
|
||||||
left: -2.8rem;
|
.chart .yaxis-label,
|
||||||
width: 2.6rem;
|
.chart .leglab {
|
||||||
text-align: right;
|
font-family: system-ui, sans-serif; /* theme fonts can be overly styled */
|
||||||
transform: translateY(50%);
|
font-size: 11px;
|
||||||
font-size: 0.75rem;
|
fill: var(--muted);
|
||||||
color: var(--muted);
|
}
|
||||||
|
|
||||||
|
.chart .ylab {
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
}
|
}
|
||||||
|
|
||||||
.xlab {
|
|
||||||
position: absolute;
|
|
||||||
top: 0.25rem;
|
|
||||||
transform: translateX(-50%);
|
|
||||||
font-size: 0.75rem;
|
|
||||||
color: var(--muted);
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.xlabels .xlab:first-child { transform: none; }
|
|
||||||
.xlabels .xlab:last-child { transform: translateX(-100%); }
|
|
||||||
|
|
||||||
.chart .minor {
|
.chart .minor {
|
||||||
stroke: var(--line);
|
stroke: var(--line);
|
||||||
stroke-width: 1;
|
stroke-width: 1;
|
||||||
@@ -189,28 +192,10 @@ const viewChart = computed(() => buildChart(viewSeries.value, now.value))
|
|||||||
stroke-linecap: round;
|
stroke-linecap: round;
|
||||||
}
|
}
|
||||||
|
|
||||||
.legend {
|
/* Past overlay weeks contrast with the current week's accent color. */
|
||||||
display: flex;
|
.chart .line.past {
|
||||||
gap: 1.2rem;
|
stroke: var(--muted);
|
||||||
margin-top: 0.4rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.legend span { color: var(--accent); }
|
|
||||||
|
|
||||||
.yaxis-label {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
left: -2.8rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
color: var(--muted);
|
|
||||||
writing-mode: vertical-rl;
|
|
||||||
white-space: nowrap;
|
|
||||||
transform: translateY(-50%) rotate(180deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
section { margin-top: 1.8rem; }
|
|
||||||
|
|
||||||
.empty { color: var(--muted); }
|
.empty { color: var(--muted); }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+69
-100
@@ -1,16 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* Chart geometry, smoothing, and SVG path generation for analytics charts.
|
* Chart geometry, smoothing, and SVG path generation for analytics charts.
|
||||||
*
|
*
|
||||||
* Fixed 720x180 viewBox, stretched to the panel width; values are per-unit
|
* Fixed 720x180 plot area inside a larger viewBox that also holds the axis
|
||||||
* rates (hour on the week view, day on month+).
|
* labels, so each chart SVG is self-contained; values are per-unit rates
|
||||||
|
* (hour on the week view, day on month+).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { DAY, HOUR, MIN5, WEEK, mondayUTC } from './time.js'
|
import { DAY, HOUR, MIN5, WEEK, mondayUTC } from './time.js'
|
||||||
import { formatCount } from './format.js'
|
import { formatCount } from './format.js'
|
||||||
|
|
||||||
export const CHART_W = 720
|
export const CHART_W = 1000
|
||||||
export const CHART_H = 180
|
export const CHART_H = 150
|
||||||
export const PAD_TOP = 14 // room above the highest point
|
export const PAD_TOP = 14 // room above the highest point
|
||||||
|
export const MARGIN_L = 40 // y tick labels + vertical axis label
|
||||||
|
export const MARGIN_B = 24 // x tick labels
|
||||||
|
export const VIEW_W = MARGIN_L + CHART_W + 8
|
||||||
|
export const VIEW_H = CHART_H + MARGIN_B
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Y always starts at 0; the max is a multiple of a 1-2-5 major step with at
|
* Y always starts at 0; the max is a multiple of a 1-2-5 major step with at
|
||||||
@@ -37,24 +42,21 @@ export function yScale(maxValue) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Edge-aware adaptive Gaussian smoothing. A change-point detector first
|
* Edge-aware Gaussian smoothing with a fixed bandwidth. A change-point
|
||||||
* finds traffic-level shifts (two-unit totals compared on both sides of
|
* detector first finds traffic-level shifts (two-unit totals compared on
|
||||||
* each bucket; strong ratio + significance marks a candidate, and each run
|
* both sides of each bucket; strong ratio + significance marks a candidate,
|
||||||
* of candidates keeps only its best-scoring bucket as an edge). Each
|
* and each run of candidates keeps only its best-scoring bucket as an
|
||||||
* edge-delimited segment is then smoothed independently: a broad two-unit
|
* edge). Each edge-delimited segment is then smoothed independently: every
|
||||||
* pilot estimates the local traffic rate, which ramps the Gaussian sigma
|
* bucket spreads its count with a fixed Gaussian sigma chosen so N events
|
||||||
* from ~0.4 units (isolated events stay narrow, peaking at ~1 event/unit)
|
* in a single bucket peak at N events per unit. Mass past a detected change
|
||||||
* up to 1 unit (busy traffic gets full smoothing), and every bucket spreads
|
* point is dropped (kernel renormalized); mass past a true series edge is
|
||||||
* its count with its local sigma, clipped to the segment and renormalized
|
* mirrored back, so the curve doesn't fall where data simply ends. Either
|
||||||
* so total visitor count is preserved exactly. The unit is one hour on the
|
* way total visitor count is preserved exactly. The unit is
|
||||||
* week view and one day on the month+ views, so the smoothing time scale
|
* one hour on the week view and one day on the month+ views, so the
|
||||||
* follows the range (month+ sigmas are 24x the hourly ones). The raw series
|
* smoothing time scale follows the range. The raw series is drawn faintly
|
||||||
* is drawn faintly behind the curve for reference. Operates on raw counts.
|
* behind the curve for reference. Operates on raw counts.
|
||||||
*/
|
*/
|
||||||
export function smooth(counts, binMinutes, unitMinutes, {
|
export function smooth(counts, binMinutes, unitMinutes, {
|
||||||
minSigmaMinutes = unitMinutes / Math.sqrt(2 * Math.PI),
|
|
||||||
maxSigmaMinutes = unitMinutes,
|
|
||||||
pilotSigmaMinutes = 2 * unitMinutes,
|
|
||||||
detectorWindowMinutes = 2 * unitMinutes,
|
detectorWindowMinutes = 2 * unitMinutes,
|
||||||
// Count thresholds are defined per hour and scale with the unit, so
|
// Count thresholds are defined per hour and scale with the unit, so
|
||||||
// "low traffic" means the same thing on hourly and daily views
|
// "low traffic" means the same thing on hourly and daily views
|
||||||
@@ -62,8 +64,6 @@ export function smooth(counts, binMinutes, unitMinutes, {
|
|||||||
highTrafficEvents = 10 * unitMinutes / 60,
|
highTrafficEvents = 10 * unitMinutes / 60,
|
||||||
minRatio = 2.5,
|
minRatio = 2.5,
|
||||||
minSignificance = 4,
|
minSignificance = 4,
|
||||||
sigmaRampStart = 5 * unitMinutes / 60,
|
|
||||||
sigmaRampEnd = 20 * unitMinutes / 60,
|
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const n = counts.length
|
const n = counts.length
|
||||||
if (!n) return counts
|
if (!n) return counts
|
||||||
@@ -105,78 +105,49 @@ export function smooth(counts, binMinutes, unitMinutes, {
|
|||||||
i = j
|
i = j
|
||||||
}
|
}
|
||||||
|
|
||||||
const reflectIndex = (i, length) => {
|
// Fixed sigma: N events in one bucket peak at N events per unit.
|
||||||
while (i < 0 || i >= length) {
|
// sigma_bins * sqrt(2*pi) = rate = unitMinutes / binMinutes.
|
||||||
i = i < 0 ? -i - 1 : 2 * length - i - 1
|
const sigmaBins = unitMinutes / (binMinutes * Math.sqrt(2 * Math.PI))
|
||||||
}
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
|
|
||||||
const gaussianFilterReflect = (values, sigmaBins) => {
|
|
||||||
const length = values.length
|
|
||||||
const radius = Math.ceil(4 * sigmaBins)
|
const radius = Math.ceil(4 * sigmaBins)
|
||||||
const kernel = new Float64Array(radius * 2 + 1)
|
|
||||||
let sum = 0
|
|
||||||
for (let k = -radius; k <= radius; k++) {
|
|
||||||
const w = Math.exp(-0.5 * (k / sigmaBins) ** 2)
|
|
||||||
kernel[k + radius] = w
|
|
||||||
sum += w
|
|
||||||
}
|
|
||||||
for (let i = 0; i < kernel.length; i++) kernel[i] /= sum
|
|
||||||
const out = new Float64Array(length)
|
|
||||||
for (let i = 0; i < length; i++) {
|
|
||||||
let value = 0
|
|
||||||
for (let k = -radius; k <= radius; k++) {
|
|
||||||
value += values[reflectIndex(i + k, length)] * kernel[k + radius]
|
|
||||||
}
|
|
||||||
out[i] = value
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process each discontinuity-delimited regime independently so neither
|
// Process each discontinuity-delimited regime independently so the
|
||||||
// the pilot nor the final Gaussian can see through a detected boundary.
|
// Gaussian cannot see through a detected boundary. Each input bin spreads
|
||||||
|
// its count with the fixed sigma. Mass that would fall past a detected
|
||||||
|
// change point is dropped and the kernel renormalized; mass that would
|
||||||
|
// fall past a true series edge (first/last bin) is mirrored back into the
|
||||||
|
// segment, as if the data continued as its own reflection, so constant or
|
||||||
|
// rising data doesn't produce a spurious falling edge. Total visitor count
|
||||||
|
// is preserved apart from floating-point error.
|
||||||
const bounds = [0, ...edges, n]
|
const bounds = [0, ...edges, n]
|
||||||
const smoothed = new Float64Array(n)
|
const smoothed = new Float64Array(n)
|
||||||
for (let b = 0; b < bounds.length - 1; b++) {
|
for (let b = 0; b < bounds.length - 1; b++) {
|
||||||
const lo = bounds[b]
|
const lo = bounds[b]
|
||||||
const length = bounds[b + 1] - lo
|
const length = bounds[b + 1] - lo
|
||||||
|
const mirrorLeft = lo === 0
|
||||||
|
const mirrorRight = lo + length === n
|
||||||
const segment = counts.slice(lo, lo + length)
|
const segment = counts.slice(lo, lo + length)
|
||||||
|
|
||||||
// Broad pilot estimates only the generic local traffic level used for
|
|
||||||
// choosing sigma; it is not the final displayed curve.
|
|
||||||
const pilot = gaussianFilterReflect(segment, pilotSigmaMinutes / binMinutes)
|
|
||||||
|
|
||||||
// Keep isolated/sparse traffic at the minimum bandwidth through
|
|
||||||
// sigmaRampStart events, then ramp toward maxSigmaMinutes (thresholds
|
|
||||||
// are per-hour rates scaled to the unit: low traffic is low traffic
|
|
||||||
// on every range).
|
|
||||||
const sigmaMinutes = new Float64Array(length)
|
|
||||||
for (let i = 0; i < length; i++) {
|
|
||||||
const ratePerUnit = pilot[i] * unitMinutes / binMinutes
|
|
||||||
let mix = (ratePerUnit - sigmaRampStart) / (sigmaRampEnd - sigmaRampStart)
|
|
||||||
mix = Math.sqrt(Math.max(0, Math.min(1, mix)))
|
|
||||||
sigmaMinutes[i] = minSigmaMinutes + mix * (maxSigmaMinutes - minSigmaMinutes)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each input bin spreads its own count using its local sigma. The
|
|
||||||
// per-bin kernel is renormalized after clipping to the segment,
|
|
||||||
// preserving total visitor count apart from floating-point error.
|
|
||||||
for (let j = 0; j < length; j++) {
|
for (let j = 0; j < length; j++) {
|
||||||
const count = segment[j]
|
const count = segment[j]
|
||||||
if (!count) continue
|
if (!count) continue
|
||||||
const sigmaBins = sigmaMinutes[j] / binMinutes
|
// Collect (target bin, weight) pairs over the full kernel, folding
|
||||||
const radius = Math.ceil(4 * sigmaBins)
|
// mirrored mass at series edges and dropping mass past change points.
|
||||||
const start = Math.max(0, j - radius)
|
const spread = new Map()
|
||||||
const end = Math.min(length, j + radius + 1)
|
|
||||||
let weightSum = 0
|
let weightSum = 0
|
||||||
for (let i = start; i < end; i++) {
|
for (let i = j - radius; i <= j + radius; i++) {
|
||||||
const d = i - j
|
let k = i
|
||||||
weightSum += Math.exp(-0.5 * (d / sigmaBins) ** 2)
|
// Fold repeatedly for segments shorter than the kernel radius.
|
||||||
|
while (k < 0 || k >= length) {
|
||||||
|
if (k < 0 && mirrorLeft) k = -k - 1
|
||||||
|
else if (k >= length && mirrorRight) k = 2 * length - 1 - k
|
||||||
|
else { k = null; break }
|
||||||
}
|
}
|
||||||
for (let i = start; i < end; i++) {
|
if (k === null) continue
|
||||||
const d = i - j
|
const w = Math.exp(-0.5 * ((i - j) / sigmaBins) ** 2)
|
||||||
smoothed[lo + i] += count * Math.exp(-0.5 * (d / sigmaBins) ** 2) / weightSum
|
spread.set(k, (spread.get(k) || 0) + w)
|
||||||
|
weightSum += w
|
||||||
|
}
|
||||||
|
for (const [k, w] of spread) {
|
||||||
|
smoothed[lo + k] += count * w / weightSum
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -240,7 +211,7 @@ export function buildChart(input, now = Date.now()) {
|
|||||||
const nMajor = Math.round(max / step)
|
const nMajor = Math.round(max / step)
|
||||||
for (let k = 0; k <= nMajor; k++) {
|
for (let k = 0; k <= nMajor; k++) {
|
||||||
const v = k * step
|
const v = k * step
|
||||||
majors.push({ value: v, y: y(v), bottom: (1 - PAD_TOP / CHART_H) * (v / max) * 100 })
|
majors.push({ value: v, y: y(v), label: fmtY(v) })
|
||||||
}
|
}
|
||||||
if (minor) {
|
if (minor) {
|
||||||
for (let v = minor; v < max; v += minor) {
|
for (let v = minor; v < max; v += minor) {
|
||||||
@@ -254,37 +225,37 @@ export function buildChart(input, now = Date.now()) {
|
|||||||
// ranges: boundary lines at Mondays / months / years.
|
// ranges: boundary lines at Mondays / months / years.
|
||||||
const isWeek = t1 - t0 === WEEK
|
const isWeek = t1 - t0 === WEEK
|
||||||
const isMonth = !isWeek && t1 - t0 <= 31 * DAY
|
const isMonth = !isWeek && t1 - t0 <= 31 * DAY
|
||||||
const xticks = isWeek
|
let xticks
|
||||||
? Array.from({ length: 7 }, (_, d) => {
|
if (isWeek) {
|
||||||
|
xticks = Array.from({ length: 7 }, (_, d) => {
|
||||||
const t = t0 + d * DAY + 12 * HOUR
|
const t = t0 + d * DAY + 12 * HOUR
|
||||||
return {
|
return {
|
||||||
x: x(t), left: ((t - t0) / (t1 - t0)) * 100,
|
x: x(t),
|
||||||
label: new Date(t).toLocaleDateString(undefined, {
|
label: new Date(t).toLocaleDateString(undefined, {
|
||||||
weekday: 'short', timeZone: 'UTC',
|
weekday: 'short', timeZone: 'UTC',
|
||||||
}),
|
}),
|
||||||
line: false,
|
line: false,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
: isMonth
|
} else if (isMonth) {
|
||||||
? Array.from(
|
// t0 is day-aligned; label every day whose noon falls inside the range.
|
||||||
{ length: Math.floor((t1 - Math.ceil(t0 / DAY) * DAY) / DAY) },
|
xticks = []
|
||||||
(_, d) => {
|
for (let day = t0; day + 12 * HOUR < t1; day += DAY) {
|
||||||
const day = Math.ceil(t0 / DAY) * DAY + d * DAY
|
|
||||||
const date = new Date(day)
|
const date = new Date(day)
|
||||||
const t = day + 12 * HOUR
|
const t = day + 12 * HOUR
|
||||||
return {
|
xticks.push({
|
||||||
x: x(t), left: ((t - t0) / (t1 - t0)) * 100,
|
x: x(t),
|
||||||
label: date.getUTCDate() === 1
|
label: date.getUTCDate() === 1
|
||||||
? date.toLocaleDateString(undefined, { month: 'short', timeZone: 'UTC' })
|
? date.toLocaleDateString(undefined, { month: 'short', timeZone: 'UTC' })
|
||||||
: String(date.getUTCDate()),
|
: String(date.getUTCDate()),
|
||||||
line: false,
|
line: false,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
},
|
} else {
|
||||||
)
|
xticks = xticksFor(t0, t1).map((t) => ({
|
||||||
: xticksFor(t0, t1).map((t) => ({
|
x: x(t), label: fmtTick(t, t1 - t0), line: true,
|
||||||
x: x(t), left: ((t - t0) / (t1 - t0)) * 100,
|
|
||||||
label: fmtTick(t, t1 - t0), line: true,
|
|
||||||
}))
|
}))
|
||||||
|
}
|
||||||
return { max, majors, minors, series: drawn, xticks, unit }
|
return { max, majors, minors, series: drawn, xticks, unit }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,7 +318,7 @@ export function buildDayChart(input, now = Date.now()) {
|
|||||||
const nMajor = Math.round(max / step)
|
const nMajor = Math.round(max / step)
|
||||||
for (let k = 0; k <= nMajor; k++) {
|
for (let k = 0; k <= nMajor; k++) {
|
||||||
const v = k * step
|
const v = k * step
|
||||||
majors.push({ value: v, y: y(v), bottom: (1 - PAD_TOP / CHART_H) * (v / max) * 100 })
|
majors.push({ value: v, y: y(v), label: fmtY(v) })
|
||||||
}
|
}
|
||||||
if (minor) {
|
if (minor) {
|
||||||
for (let v = minor; v < max; v += minor) {
|
for (let v = minor; v < max; v += minor) {
|
||||||
@@ -363,12 +334,10 @@ export function buildDayChart(input, now = Date.now()) {
|
|||||||
const d = new Date(t)
|
const d = new Date(t)
|
||||||
xticks.push({
|
xticks.push({
|
||||||
x: ((t - t0) / (t1 - t0)) * CHART_W,
|
x: ((t - t0) / (t1 - t0)) * CHART_W,
|
||||||
left: ((t - t0) / (t1 - t0)) * 100,
|
|
||||||
label: `${String(d.getUTCHours()).padStart(2, '0')}:00`,
|
label: `${String(d.getUTCHours()).padStart(2, '0')}:00`,
|
||||||
line: false,
|
line: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return { bars, skyline: skyline.trim(), max, majors, minors, xticks, unit: '5min', series: [] }
|
return { bars, skyline: skyline.trim(), max, majors, minors, xticks, unit: '5min', series: [] }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -80,17 +80,27 @@ export function calcTotalViews(views) {
|
|||||||
// Very short reads are navigation/skims, not real reading time.
|
// Very short reads are navigation/skims, not real reading time.
|
||||||
export const MIN_READ_SECONDS = 10
|
export const MIN_READ_SECONDS = 10
|
||||||
|
|
||||||
|
/** path -> accumulated read seconds for a visit, derived from its trail. */
|
||||||
|
export function readMapOf(v) {
|
||||||
|
const map = {}
|
||||||
|
for (const item of Object.values(v.trail || {})) {
|
||||||
|
if (item.read) map[item.to] = (map[item.to] || 0) + item.read
|
||||||
|
}
|
||||||
|
return map
|
||||||
|
}
|
||||||
|
|
||||||
/** Average minutes per visit and average of per-article median read minutes. */
|
/** Average minutes per visit and average of per-article median read minutes. */
|
||||||
export function calcReadStats(visits) {
|
export function calcReadStats(visits) {
|
||||||
const perArticle = {}
|
const perArticle = {}
|
||||||
let totalVisitSeconds = 0
|
let totalVisitSeconds = 0
|
||||||
let visitCount = 0
|
let visitCount = 0
|
||||||
for (const v of visits || []) {
|
for (const v of visits || []) {
|
||||||
const secs = Object.values(v.read || {}).filter((s) => s >= MIN_READ_SECONDS)
|
const read = readMapOf(v)
|
||||||
|
const secs = Object.values(read).filter((s) => s >= MIN_READ_SECONDS)
|
||||||
if (!secs.length) continue
|
if (!secs.length) continue
|
||||||
visitCount++
|
visitCount++
|
||||||
totalVisitSeconds += secs.reduce((a, b) => a + b, 0)
|
totalVisitSeconds += secs.reduce((a, b) => a + b, 0)
|
||||||
for (const [path, s] of Object.entries(v.read || {})) {
|
for (const [path, s] of Object.entries(read)) {
|
||||||
if (s >= MIN_READ_SECONDS) {
|
if (s >= MIN_READ_SECONDS) {
|
||||||
; (perArticle[path] || (perArticle[path] = [])).push(s)
|
; (perArticle[path] || (perArticle[path] = [])).push(s)
|
||||||
}
|
}
|
||||||
@@ -240,6 +250,14 @@ export function formatWhenIso(ts) {
|
|||||||
return `${new Date(ts).toISOString().split('.')[0]}Z`
|
return `${new Date(ts).toISOString().split('.')[0]}Z`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compact read time for tooltips: "50s" under a minute, "1m23s" otherwise.
|
||||||
|
*/
|
||||||
|
export function formatReadTime(seconds) {
|
||||||
|
if (seconds < 60) return `${seconds}s`
|
||||||
|
return `${Math.floor(seconds / 60)}m${seconds % 60}s`
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compact visitor counts: plain below 1k, then 1.2k / 10k / 1.2M.
|
* Compact visitor counts: plain below 1k, then 1.2k / 10k / 1.2M.
|
||||||
* Truncated, not rounded.
|
* Truncated, not rounded.
|
||||||
@@ -263,7 +281,7 @@ export function formatRecentVisits(visits, pageTree, limit = 50) {
|
|||||||
.reverse()
|
.reverse()
|
||||||
.map((v) => ({
|
.map((v) => ({
|
||||||
when: new Date(v.start).toLocaleString(),
|
when: new Date(v.start).toLocaleString(),
|
||||||
steps: [v.referer, v.entry, ...(v.trail || [])]
|
steps: [v.referer, ...Object.values(v.trail || {}).map((t) => t.to)]
|
||||||
.map((p) => stepOf(p, titles))
|
.map((p) => stepOf(p, titles))
|
||||||
.filter(Boolean),
|
.filter(Boolean),
|
||||||
}))
|
}))
|
||||||
@@ -341,8 +359,8 @@ export function mainDomain(host, limit = 24) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Group raw crawler hits by client hash and format each group as a row showing
|
* Group raw crawler hits by client hash and format each group as a row showing
|
||||||
* every internal page that crawler visited. Rows are sorted by total hits,
|
* every internal page that crawler visited. Rows are sorted by most recent hit
|
||||||
* most active crawler first, rather than by most recent hit.
|
* first, with total hits as a tie-breaker.
|
||||||
* ``clients`` maps client hashes to client records.
|
* ``clients`` maps client hashes to client records.
|
||||||
*/
|
*/
|
||||||
export function formatCrawlerRows(crawlers, clients, pageTree, now = Date.now()) {
|
export function formatCrawlerRows(crawlers, clients, pageTree, now = Date.now()) {
|
||||||
@@ -359,17 +377,20 @@ export function formatCrawlerRows(crawlers, clients, pageTree, now = Date.now())
|
|||||||
const start = new Date(c.start).getTime()
|
const start = new Date(c.start).getTime()
|
||||||
if (start > g.lastStart) g.lastStart = start
|
if (start > g.lastStart) g.lastStart = start
|
||||||
if (c.entry?.startsWith('/')) {
|
if (c.entry?.startsWith('/')) {
|
||||||
g.pages.set(c.entry, (g.pages.get(c.entry) || 0) + 1)
|
const existing = g.pages.get(c.entry) || { count: 0, status: c.status || 200 }
|
||||||
|
existing.count += 1
|
||||||
|
if (c.status != null) existing.status = c.status
|
||||||
|
g.pages.set(c.entry, existing)
|
||||||
}
|
}
|
||||||
groups.set(c.client, g)
|
groups.set(c.client, g)
|
||||||
}
|
}
|
||||||
const totalHits = (g) => {
|
const totalHits = (g) => {
|
||||||
let n = 0
|
let n = 0
|
||||||
for (const c of g.pages.values()) n += c
|
for (const p of g.pages.values()) n += p.count
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
return [...groups.values()]
|
return [...groups.values()]
|
||||||
.sort((a, b) => totalHits(b) - totalHits(a) || b.lastStart - a.lastStart)
|
.sort((a, b) => b.lastStart - a.lastStart || totalHits(b) - totalHits(a))
|
||||||
.slice(0, 10)
|
.slice(0, 10)
|
||||||
.map((g) => {
|
.map((g) => {
|
||||||
const client = g.client || {}
|
const client = g.client || {}
|
||||||
@@ -380,8 +401,8 @@ export function formatCrawlerRows(crawlers, clients, pageTree, now = Date.now())
|
|||||||
lastSeenIso: formatWhenIso(g.lastStart),
|
lastSeenIso: formatWhenIso(g.lastStart),
|
||||||
lastSeenLocal: formatWhenLocal(g.lastStart),
|
lastSeenLocal: formatWhenLocal(g.lastStart),
|
||||||
pages: [...g.pages.entries()]
|
pages: [...g.pages.entries()]
|
||||||
.sort((a, b) => b[1] - a[1])
|
.sort((a, b) => b[1].count - a[1].count)
|
||||||
.map(([path, count]) => ({ ...stepOf(path, titles), count })),
|
.map(([path, info]) => ({ ...stepOf(path, titles), count: info.count, status: info.status })),
|
||||||
ip: client.ip || '',
|
ip: client.ip || '',
|
||||||
ipDisplay: isHost ? mainDomain(host) : hostIP(client.ip) || client.ip || '—',
|
ipDisplay: isHost ? mainDomain(host) : hostIP(client.ip) || client.ip || '—',
|
||||||
isHost,
|
isHost,
|
||||||
@@ -499,8 +520,15 @@ export function formatVisitRows(visits, clients, pageTree, now = Date.now()) {
|
|||||||
const titles = buildTitleMap(pageTree)
|
const titles = buildTitleMap(pageTree)
|
||||||
return [...(visits || [])].reverse().slice(0, 20).map((v) => {
|
return [...(visits || [])].reverse().slice(0, 20).map((v) => {
|
||||||
const client = (clients || {})[v.client] || {}
|
const client = (clients || {})[v.client] || {}
|
||||||
const trail = [v.entry, ...(v.trail || [])]
|
const trail = Object.values(v.trail || {})
|
||||||
.map((p) => stepOf(p, titles))
|
.map((item) => {
|
||||||
|
const step = stepOf(item.to, titles)
|
||||||
|
if (step) {
|
||||||
|
if (item.read) step.readSeconds = item.read
|
||||||
|
if (item.status) step.status = item.status
|
||||||
|
}
|
||||||
|
return step
|
||||||
|
})
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
const utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
|
const utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']
|
||||||
const utmValues = utmKeys.map((k) => (v.utm || {})[k]).filter(Boolean)
|
const utmValues = utmKeys.map((k) => (v.utm || {})[k]).filter(Boolean)
|
||||||
|
|||||||
+118
-21
@@ -26,6 +26,15 @@ export function mondayUTC(t) {
|
|||||||
return (d - ((d + 3) % 7)) * DAY
|
return (d - ((d + 3) % 7)) * DAY
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** ISO 8601 week number of the week containing t (via its Thursday). */
|
||||||
|
export function isoWeek(t) {
|
||||||
|
const d = new Date(t)
|
||||||
|
d.setUTCHours(0, 0, 0, 0)
|
||||||
|
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7))
|
||||||
|
const yearStart = Date.UTC(d.getUTCFullYear(), 0, 1)
|
||||||
|
return Math.ceil(((d - yearStart) / DAY + 1) / 7)
|
||||||
|
}
|
||||||
|
|
||||||
/** Parse sparse timestamp buckets into a { epochMs: count } map. */
|
/** Parse sparse timestamp buckets into a { epochMs: count } map. */
|
||||||
export function rawTimes(buckets) {
|
export function rawTimes(buckets) {
|
||||||
const raw = {}
|
const raw = {}
|
||||||
@@ -44,7 +53,9 @@ export function sumRange(raw, t0, t1) {
|
|||||||
/**
|
/**
|
||||||
* One series per overlaid week: [this week, 1 week ago, ...], at native
|
* One series per overlaid week: [this week, 1 week ago, ...], at native
|
||||||
* 5-minute resolution, up to 8 weeks back (and only weeks that overlap the
|
* 5-minute resolution, up to 8 weeks back (and only weeks that overlap the
|
||||||
* recorded data at all). The current week is truncated at the current bucket
|
* recorded data at all). Each older week's timestamps are shifted forward
|
||||||
|
* onto the current week's axis so all curves overlay inside the plot.
|
||||||
|
* The current week is truncated at the current bucket
|
||||||
* — no fake zeroes drawn for the future. Counts are rates per hour
|
* — no fake zeroes drawn for the future. Counts are rates per hour
|
||||||
* (bucket count * 12): a lone visit in a 5-minute bucket reads as "12/h".
|
* (bucket count * 12): a lone visit in a 5-minute bucket reads as "12/h".
|
||||||
* The coarser ranges use per-day rates instead (unitMinutes = 24*60).
|
* The coarser ranges use per-day rates instead (unitMinutes = 24*60).
|
||||||
@@ -52,9 +63,24 @@ export function sumRange(raw, t0, t1) {
|
|||||||
export function weeklySeries(buckets) {
|
export function weeklySeries(buckets) {
|
||||||
const raw = rawTimes(buckets)
|
const raw = rawTimes(buckets)
|
||||||
const times = Object.keys(raw).map(Number)
|
const times = Object.keys(raw).map(Number)
|
||||||
if (!times.length) return null
|
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
const thisMonday = mondayUTC(now)
|
const thisMonday = mondayUTC(now)
|
||||||
|
if (!times.length) {
|
||||||
|
const points = []
|
||||||
|
const end = Math.min(thisMonday + WEEK, Math.floor(now / MIN5) * MIN5 + MIN5)
|
||||||
|
for (let t = thisMonday; t < end; t += MIN5) {
|
||||||
|
points.push({ t, count: 0 })
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
series: [{ points, label: `Week ${isoWeek(thisMonday)}`, opacity: 1, area: true }],
|
||||||
|
t0: thisMonday,
|
||||||
|
t1: thisMonday + WEEK,
|
||||||
|
rate: HOUR / MIN5,
|
||||||
|
binMinutes: 5,
|
||||||
|
unitMinutes: 60,
|
||||||
|
unit: 'hour',
|
||||||
|
}
|
||||||
|
}
|
||||||
const oldest = Math.min(...times)
|
const oldest = Math.min(...times)
|
||||||
// Weeks back as far as the data reaches: difference in Monday indices.
|
// Weeks back as far as the data reaches: difference in Monday indices.
|
||||||
const available = (thisMonday - mondayUTC(oldest)) / WEEK + 1
|
const available = (thisMonday - mondayUTC(oldest)) / WEEK + 1
|
||||||
@@ -67,12 +93,13 @@ export function weeklySeries(buckets) {
|
|||||||
: start + WEEK
|
: start + WEEK
|
||||||
const points = []
|
const points = []
|
||||||
for (let t = start; t < end; t += MIN5) {
|
for (let t = start; t < end; t += MIN5) {
|
||||||
points.push({ t, count: raw[t] || 0 })
|
points.push({ t: t + back * WEEK, count: raw[t] || 0 })
|
||||||
}
|
}
|
||||||
out.push({
|
out.push({
|
||||||
points,
|
points,
|
||||||
label: back === 0 ? 'this week' : `${back}w ago`,
|
label: `Week ${isoWeek(start)}`,
|
||||||
opacity: Math.max(0.15, 1 - back * 0.25),
|
opacity: Math.max(0.15, 1 - back * 0.25),
|
||||||
|
past: back > 0,
|
||||||
area: back === 0,
|
area: back === 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -92,27 +119,52 @@ export function weeklySeries(buckets) {
|
|||||||
* to per-day rates (the unit the month+ charts are read in).
|
* to per-day rates (the unit the month+ charts are read in).
|
||||||
* Ranges without a fixed span use the full data reach, but never less than
|
* Ranges without a fixed span use the full data reach, but never less than
|
||||||
* their configured minSpan so the chart keeps a readable minimum x scale.
|
* their configured minSpan so the chart keeps a readable minimum x scale.
|
||||||
|
* t0 is aligned to the UTC day so the x labels cover the whole range;
|
||||||
|
* t1 is now, so the scale never extends into the future. The bucket size
|
||||||
|
* follows the resulting window (6h up to 31 days, daily beyond), so ranges
|
||||||
|
* covering the same window — "all" at its 30-day minimum vs "month" —
|
||||||
|
* render the identical curve.
|
||||||
*/
|
*/
|
||||||
export function rollingSeries(buckets, rangeKey) {
|
export function rollingSeries(buckets, rangeKey) {
|
||||||
const raw = rawTimes(buckets)
|
const raw = rawTimes(buckets)
|
||||||
const times = Object.keys(raw).map(Number)
|
const times = Object.keys(raw).map(Number)
|
||||||
if (!times.length) return null
|
|
||||||
const { span, bucket, minSpan = 0 } = RANGES[rangeKey]
|
const { span, bucket, minSpan = 0 } = RANGES[rangeKey]
|
||||||
const t1 = Math.floor(Date.now() / bucket) * bucket + bucket
|
const t1 = Date.now()
|
||||||
const earliest = Math.floor(Math.min(...times) / bucket) * bucket
|
const t0 = Math.floor((span != null
|
||||||
const t0 = span != null
|
|
||||||
? t1 - span
|
? t1 - span
|
||||||
: Math.min(earliest, t1 - minSpan)
|
: Math.min(times.length ? Math.min(...times) : Infinity, t1 - minSpan)) / DAY) * DAY
|
||||||
|
if (!times.length) {
|
||||||
|
const bucketMs = t1 - t0 <= 31 * DAY ? Math.min(bucket, 6 * HOUR) : bucket
|
||||||
const points = []
|
const points = []
|
||||||
for (let t = t0; t < t1; t += bucket) {
|
for (let t = t0; t < t1; t += bucketMs) {
|
||||||
points.push({ t, count: sumRange(raw, t, t + bucket) })
|
points.push({ t, count: 0 })
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
series: [{ points, label: '', opacity: 1, area: true }],
|
series: [{ points, label: '', opacity: 1, area: true }],
|
||||||
t0,
|
t0,
|
||||||
t1,
|
t1,
|
||||||
rate: DAY / bucket,
|
rate: DAY / bucketMs,
|
||||||
binMinutes: bucket / 60e3,
|
binMinutes: bucketMs / 60e3,
|
||||||
|
unitMinutes: 24 * 60,
|
||||||
|
unit: 'day',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The bucket follows the actual window length, not the range key: when
|
||||||
|
// "all" is capped to its 30-day minimum it covers the very window "month"
|
||||||
|
// does, and daily bins would draw a different curve over the same data
|
||||||
|
// (coarser edge detection, points a day apart plotted at bin starts, the
|
||||||
|
// last point stuck at today's midnight instead of reaching now).
|
||||||
|
const bucketMs = t1 - t0 <= 31 * DAY ? Math.min(bucket, 6 * HOUR) : bucket
|
||||||
|
const points = []
|
||||||
|
for (let t = t0; t < t1; t += bucketMs) {
|
||||||
|
points.push({ t, count: sumRange(raw, t, t + bucketMs) })
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
series: [{ points, label: '', opacity: 1, area: true }],
|
||||||
|
t0,
|
||||||
|
t1,
|
||||||
|
rate: DAY / bucketMs,
|
||||||
|
binMinutes: bucketMs / 60e3,
|
||||||
unitMinutes: 24 * 60,
|
unitMinutes: 24 * 60,
|
||||||
unit: 'day',
|
unit: 'day',
|
||||||
}
|
}
|
||||||
@@ -152,19 +204,64 @@ export function makeSeries(buckets, rangeKey) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Absolute UTC time window for a given range key. Used to filter visits,
|
* Absolute UTC time window for a given range key. Used to filter visits,
|
||||||
* transitions and views to the same period the charts are showing.
|
* transitions and views for the non-chart stats on the analytics page.
|
||||||
|
* Every bounded range is a rolling span ending at now; the charts instead
|
||||||
|
* align week to Monday 00:00 UTC (overlaying previous weeks) and month+
|
||||||
|
* to UTC day boundaries, so their x windows differ from the stats range
|
||||||
|
* on purpose.
|
||||||
* Returns { t0, t1 } where null means unbounded.
|
* Returns { t0, t1 } where null means unbounded.
|
||||||
*/
|
*/
|
||||||
export function rangeWindow(rangeKey) {
|
export function rangeWindow(rangeKey) {
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
if (rangeKey === 'week') {
|
|
||||||
const start = mondayUTC(now)
|
|
||||||
return { t0: start, t1: start + WEEK }
|
|
||||||
}
|
|
||||||
if (rangeKey === 'all') {
|
if (rangeKey === 'all') {
|
||||||
return { t0: null, t1: null }
|
return { t0: null, t1: null }
|
||||||
}
|
}
|
||||||
const { span, bucket } = RANGES[rangeKey]
|
const span = rangeKey === 'week' ? WEEK : RANGES[rangeKey].span
|
||||||
const t1 = Math.floor(now / bucket) * bucket + bucket
|
return { t0: now - span, t1: now }
|
||||||
return { t0: t1 - span, t1 }
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sum the bucketed transition matrix (from -> to -> bucket ISO -> count)
|
||||||
|
* into a plain from -> to -> count matrix for the window [t0, t1).
|
||||||
|
*/
|
||||||
|
export function filterTransitionsByRange(transitions, t0, t1) {
|
||||||
|
const out = {}
|
||||||
|
for (const [fr, tos] of Object.entries(transitions || {})) {
|
||||||
|
for (const [to, buckets] of Object.entries(tos)) {
|
||||||
|
let n = 0
|
||||||
|
for (const [k, c] of Object.entries(buckets)) {
|
||||||
|
const t = Date.parse(k)
|
||||||
|
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) n += c
|
||||||
|
}
|
||||||
|
if (n) {
|
||||||
|
out[fr] = out[fr] || {}
|
||||||
|
out[fr][to] = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep only the 5-minute view buckets that fall inside [t0, t1). */
|
||||||
|
export function filterViewsByRange(views, t0, t1) {
|
||||||
|
const filtered = {}
|
||||||
|
for (const [path, buckets] of Object.entries(views || {})) {
|
||||||
|
const out = {}
|
||||||
|
for (const [k, c] of Object.entries(buckets)) {
|
||||||
|
const t = Date.parse(k)
|
||||||
|
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) out[k] = c
|
||||||
|
}
|
||||||
|
if (Object.keys(out).length) filtered[path] = out
|
||||||
|
}
|
||||||
|
return filtered
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep only records whose start time falls inside [t0, t1). */
|
||||||
|
export function filterRecordsByRange(records, t0, t1) {
|
||||||
|
const out = []
|
||||||
|
for (const r of records || []) {
|
||||||
|
const t = Date.parse(r.start)
|
||||||
|
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) out.push(r)
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,9 @@
|
|||||||
* directions into straight connections (middle width = total
|
* directions into straight connections (middle width = total
|
||||||
* count; connectors flare into the node pills at both ends and wrap
|
* count; connectors flare into the node pills at both ends and wrap
|
||||||
* around their backs, surrounding them; the pills are drawn on top). Connection width grows
|
* around their backs, surrounding them; the pills are drawn on top). Connection width grows
|
||||||
* logarithmically with the count (a single count renders as a ~1 px
|
* logarithmically with the daily hit rate (base-2 log, one hit/day
|
||||||
* line, uncapped growth); connections carrying less than 1% of the total
|
* renders zero width, each doubling adds a fixed step, uncapped);
|
||||||
|
* connections carrying less than 1% of the total
|
||||||
* traffic are pruned, which naturally keeps the graph under ~100
|
* traffic are pruned, which naturally keeps the graph under ~100
|
||||||
* connections. Animated beads flow along every edge in each direction,
|
* connections. Animated beads flow along every edge in each direction,
|
||||||
* emitted at time intervals inversely proportional (linear) to the
|
* emitted at time intervals inversely proportional (linear) to the
|
||||||
@@ -22,12 +23,13 @@
|
|||||||
* referer, then other utm_* tags. Visits with a UTM tag are grouped under
|
* referer, then other utm_* tags. Visits with a UTM tag are grouped under
|
||||||
* that tag's value, not under the referer domain. A UTM source node only
|
* that tag's value, not under the referer domain. A UTM source node only
|
||||||
* becomes a clickable link when every visit carrying that UTM tag came
|
* becomes a clickable link when every visit carrying that UTM tag came
|
||||||
* from the same referer. External exits are full-size nodes just outside
|
* from the same referer. External exits are full-size nodes in a row below
|
||||||
* their source page, angled away from the center. Each distinct full exit
|
* the map, mirroring the source row, so the site itself stays in the
|
||||||
* URL is its own node. Self-loops (reload pings) are skipped.
|
* middle. Each distinct full exit URL is its own node. Self-loops (reload
|
||||||
|
* pings) are skipped.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { MIN_READ_SECONDS } from './format.js'
|
import { MIN_READ_SECONDS, readMapOf } from './format.js'
|
||||||
|
|
||||||
// Nodes are constant-size pills (stadium rects) holding the slug and the
|
// Nodes are constant-size pills (stadium rects) holding the slug and the
|
||||||
// view count on two centered lines. TNODE_BOUND is the pill's bounding
|
// view count on two centered lines. TNODE_BOUND is the pill's bounding
|
||||||
@@ -121,29 +123,33 @@ const pillTangent = (s, margin = 0) => {
|
|||||||
return [(x2 - x1) / m, (y2 - y1) / m]
|
return [(x2 - x1) / m, (y2 - y1) / m]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edge width (half-width of the thin middle) grows logarithmically with
|
// Edge width: half-width = WIDTH_GROWTH * log2(daily / DAILY_REF),
|
||||||
// the count. The constants are scaled down by ~10× so busy ranges (day,
|
// where `daily` is the connection's hit rate in hits/day (callers scale
|
||||||
// year) do not overwhelm the graph with fat connectors. A single recorded
|
// raw counts by DAY / range). DAILY_REF hits/day renders zero width;
|
||||||
// transition still renders as a faint ~0.4 px line. Connections carrying
|
// WIDTH_GROWTH is the half-width added per doubling of the rate.
|
||||||
// less than PRUNE_FRACTION of the total traffic are not drawn at all (this
|
// Connections whose thin middle would render below MIN_WMID are culled
|
||||||
// also keeps the graph under ~100 connections).
|
// entirely (fainter strands are practically invisible), as are those
|
||||||
const WMID_MIN = 0.2
|
// carrying less than PRUNE_FRACTION of the total traffic (this also
|
||||||
const WIDTH_GROWTH = 0.15
|
// keeps the graph under ~100 connections).
|
||||||
|
const WIDTH_GROWTH = 1.4 // half-width px per doubling of the daily rate
|
||||||
|
const DAILY_REF = 0.8 // hits/day at which the width is zero
|
||||||
const PRUNE_FRACTION = 0.01
|
const PRUNE_FRACTION = 0.01
|
||||||
|
// ~0.8 px full width at natural size (1 viewBox unit = 1 px).
|
||||||
|
const MIN_WMID = 0.4
|
||||||
|
|
||||||
// Beads: each edge direction emits beads at count * BEAD_RATE beads per
|
// Beads: each edge direction emits beads at dailyRate * BEAD_RATE beads
|
||||||
// second (linear in the count). The rate is reduced ~10× across all time
|
// per second (linear in the daily hit rate). The rate is much reduced
|
||||||
// scales to keep the animation lightweight. The component simulates every
|
// from real time to keep the animation lightweight. The component
|
||||||
// bead independently in JS at BEAD_SPEED along the edge, with no limit on
|
// simulates every bead independently in JS with a constant traversal
|
||||||
// beads in flight.
|
// time per edge (speed relative to span length), with no limit on beads
|
||||||
export const BEAD_SPEED = 180 // svg units per second
|
// in flight.
|
||||||
export const BEAD_R = 3.2
|
export const BEAD_R = 3.2
|
||||||
const BEAD_RATE = 0.012 // beads per second per recorded transition
|
const BEAD_RATE = 0.0084 // beads per second per hit/day
|
||||||
const FLOW_OFFSET = 3 // lane offset to the right of the travel direction
|
const FLOW_OFFSET = 3 // lane offset to the right of the travel direction
|
||||||
|
|
||||||
const MAX_EXT_IN = 8 // referer nodes in the top row
|
const MAX_EXT_IN = 8 // referer nodes in the top row
|
||||||
const MAX_EXT_OUT = 12 // exit nodes, at most MAX_EXT_OUT_PER_PAGE per page
|
const MAX_EXT_OUT = 12 // exit nodes in the bottom row
|
||||||
const MAX_EXT_OUT_PER_PAGE = 3
|
const EXT_GAP = 12 // vertical margin of the source/exit rows to the map
|
||||||
|
|
||||||
/** Flatten the site tree into navigation order via DFS. */
|
/** Flatten the site tree into navigation order via DFS. */
|
||||||
function buildNavigationOrder(pageTree) {
|
function buildNavigationOrder(pageTree) {
|
||||||
@@ -184,14 +190,13 @@ function collectInternalTransitions(transitions) {
|
|||||||
return internal
|
return internal
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Domain-only label for an external origin (path and www. removed). */
|
/** Domain-only label for an external origin (path and www. removed).
|
||||||
|
* Pills clip the text at their border; no length cap needed. */
|
||||||
function extLabel(ext) {
|
function extLabel(ext) {
|
||||||
try {
|
try {
|
||||||
const host = new URL(ext).hostname.replace(/^www\./, '')
|
return new URL(ext).hostname.replace(/^www\./, '')
|
||||||
return host.length > 25 ? `${host.slice(0, 24)}…` : host
|
|
||||||
} catch {
|
} catch {
|
||||||
const s = ext.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0]
|
return ext.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0]
|
||||||
return s.length > 25 ? `${s.slice(0, 24)}…` : s
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,29 +259,29 @@ function sortByNav(root, navOrder) {
|
|||||||
walk(root)
|
walk(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Compute median reading time per article in whole minutes. */
|
/** Compute median reading time per article in seconds. */
|
||||||
function buildReadMinutes(visits) {
|
function buildReadSeconds(visits) {
|
||||||
const times = {}
|
const times = {}
|
||||||
for (const v of visits || []) {
|
for (const v of visits || []) {
|
||||||
for (const [path, sec] of Object.entries(v.read || {})) {
|
for (const [path, sec] of Object.entries(readMapOf(v))) {
|
||||||
if (sec >= MIN_READ_SECONDS) {
|
if (sec >= MIN_READ_SECONDS) {
|
||||||
; (times[path] || (times[path] = [])).push(sec)
|
; (times[path] || (times[path] = [])).push(sec)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const minutes = {}
|
const seconds = {}
|
||||||
for (const [path, arr] of Object.entries(times)) {
|
for (const [path, arr] of Object.entries(times)) {
|
||||||
arr.sort((a, b) => a - b)
|
arr.sort((a, b) => a - b)
|
||||||
const mid = Math.floor(arr.length / 2)
|
const mid = Math.floor(arr.length / 2)
|
||||||
const median =
|
const median =
|
||||||
arr.length % 2 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2
|
arr.length % 2 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2
|
||||||
minutes[path] = Math.max(1, Math.round(median / 60))
|
seconds[path] = Math.round(median)
|
||||||
}
|
}
|
||||||
return minutes
|
return seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Compute view counts, labels and hidden flags for each node. */
|
/** Compute view counts, labels and hidden flags for each node. */
|
||||||
function annotateNodes(nodes, viewsData, titles, readMinutes) {
|
function annotateNodes(nodes, viewsData, titles, readSeconds) {
|
||||||
const viewCount = (p) => {
|
const viewCount = (p) => {
|
||||||
let n = 0
|
let n = 0
|
||||||
for (const c of Object.values(viewsData?.[p] || {})) n += c
|
for (const c of Object.values(viewsData?.[p] || {})) n += c
|
||||||
@@ -285,18 +290,10 @@ function annotateNodes(nodes, viewsData, titles, readMinutes) {
|
|||||||
|
|
||||||
for (const n of nodes) {
|
for (const n of nodes) {
|
||||||
n.views = viewCount(n.path)
|
n.views = viewCount(n.path)
|
||||||
n.readMin = readMinutes[n.path] || 0
|
n.readSec = readSeconds[n.path] || 0
|
||||||
// Article title inside the pill (shortened with ellipsis as needed),
|
// Article title inside the pill (clipped at the pill border on
|
||||||
// slug as fallback for pages missing from the site tree. The short
|
// render), slug as fallback for pages missing from the site tree.
|
||||||
// path (last two segments, no leading /) renders above the pill; the
|
n.label = titles.get(n.path) || (n.path === '/' ? '🏠︎' : n.path.split('/').pop())
|
||||||
// front page shows a home symbol there instead (larger).
|
|
||||||
const slug = n.path.split('/').pop()
|
|
||||||
const label = titles.get(n.path) || (n.path === '/' ? '🏠︎' : slug)
|
|
||||||
n.label = label.length > 24 ? `${label.slice(0, 23)}…` : label
|
|
||||||
const segs = n.path.split('/').filter(Boolean)
|
|
||||||
n.crumb = n.path === '/'
|
|
||||||
? '🏠︎'
|
|
||||||
: segs.length > 2 ? `…/${segs.slice(-2).join('/')}` : segs.join('/')
|
|
||||||
n.title = titles.get(n.path) || ''
|
n.title = titles.get(n.path) || ''
|
||||||
// Category (non-leaf) pages with no views in this window are omitted:
|
// Category (non-leaf) pages with no views in this window are omitted:
|
||||||
// their children move up in their place (see layoutGroups).
|
// their children move up in their place (see layoutGroups).
|
||||||
@@ -310,15 +307,13 @@ function annotateNodes(nodes, viewsData, titles, readMinutes) {
|
|||||||
* the row following a shallow circular sag (center lowest) so connections
|
* the row following a shallow circular sag (center lowest) so connections
|
||||||
* between neighbors do not overlap the pills in between. Each top item's
|
* between neighbors do not overlap the pills in between. Each top item's
|
||||||
* whole subtree fans out from it in menu (DFS preorder) order along a
|
* whole subtree fans out from it in menu (DFS preorder) order along a
|
||||||
* parabola that leaves the parent heading straight down and gradually
|
* large-radius circular arc that leaves the parent heading straight down
|
||||||
* bends to the right — no horizontal space is reserved for fans, they
|
* and gradually bends to the right — no horizontal space is reserved for fans, they
|
||||||
* extend under the slots to their right. Hidden index pages are omitted
|
* extend under the slots to their right. Hidden index pages are omitted
|
||||||
* from the fan; when the top item itself is hidden, the fan shifts one
|
* from the fan; when the top item itself is hidden, the fan shifts one
|
||||||
* slot up, the first visible child taking the top position. The short
|
* slot up, the first visible child taking the top position. Branch lanes
|
||||||
* path shown above each pill (last two segments) keeps the omitted menu
|
* labeled with the branch slug (see the branch-lane pass at the end)
|
||||||
* level visible.
|
* keep the omitted menu levels visible.
|
||||||
* Also returns curved spoke paths tracing each fan: top slot to first
|
|
||||||
* member, then member to member in menu order, each bowed to the right.
|
|
||||||
*/
|
*/
|
||||||
function layoutGroups(root) {
|
function layoutGroups(root) {
|
||||||
// Top slots are spaced well over one pill width apart regardless of
|
// Top slots are spaced well over one pill width apart regardless of
|
||||||
@@ -328,8 +323,10 @@ function layoutGroups(root) {
|
|||||||
|
|
||||||
// First pass: visible members per group, in menu order. Hidden index
|
// First pass: visible members per group, in menu order. Hidden index
|
||||||
// pages are skipped, but their children still appear. The front page
|
// pages are skipped, but their children still appear. The front page
|
||||||
// forms its own group.
|
// forms its own group. groupRoots keeps each group's subtree root for
|
||||||
|
// the branch-curve pass below.
|
||||||
const groups = []
|
const groups = []
|
||||||
|
const groupRoots = []
|
||||||
for (const g of [root, ...root.children]) {
|
for (const g of [root, ...root.children]) {
|
||||||
const members = []
|
const members = []
|
||||||
if (g === root) {
|
if (g === root) {
|
||||||
@@ -341,53 +338,139 @@ function layoutGroups(root) {
|
|||||||
}
|
}
|
||||||
walk(g)
|
walk(g)
|
||||||
}
|
}
|
||||||
if (members.length) groups.push(members)
|
if (members.length) {
|
||||||
|
groups.push(members)
|
||||||
|
groupRoots.push(g)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Top row on a true circular sag: center lowest, edges raised by SAG.
|
// Top row on a large-radius circular arc whose bottom point is the
|
||||||
|
// LAST top item: each earlier item sits a bit higher (drop = 15% of
|
||||||
|
// the row span). Flat row when there is a single group.
|
||||||
const half = ((groups.length - 1) * SLOT) / 2 || 1
|
const half = ((groups.length - 1) * SLOT) / 2 || 1
|
||||||
const SAG = TNODE_H * 0.6
|
const span = (groups.length - 1) * SLOT
|
||||||
const Rc = (half * half + SAG * SAG) / (2 * SAG)
|
const topD = span * 0.15
|
||||||
const topY = (x) => SAG - Rc + Math.sqrt(Rc * Rc - x * x)
|
const R_T = span ? (span * span + topD * topD) / (2 * topD) : 0
|
||||||
|
const topY = span
|
||||||
|
? (x) => topD - R_T + Math.sqrt(R_T * R_T - (x - half) * (x - half))
|
||||||
|
: () => 0
|
||||||
|
|
||||||
// Second pass: place groups. Fan members follow a right-opening cubic
|
// Second pass: place groups. Fan members follow a circular arc of
|
||||||
// p(t) = (gx + B t³, y0 + t): the tangent stays vertical near the
|
// large radius FAN_R centered at (gx + FAN_R, y0): the trail leaves
|
||||||
// parent (leaving almost straight down) and bends right gently,
|
// the top node heading straight down (vertical tangent) and bends
|
||||||
// reaching ~50° from vertical at the last member. Member spacing along
|
// right gently, member i at arc angle π − i·CLEAR/FAN_R (spaced by
|
||||||
// the curve is the pill clearance (dt integrated against curve speed).
|
// arc length CLEAR). A circle — not a spline — so the branch lanes
|
||||||
const spokePairs = [] // [from node, to node] — paths emitted below
|
// below can be concentric arcs: identical forms, only radii differ.
|
||||||
|
const FAN_R = 1000
|
||||||
groups.forEach((members, gi) => {
|
groups.forEach((members, gi) => {
|
||||||
const gx = gi * SLOT - half
|
const gx = gi * SLOT - half
|
||||||
const y0 = topY(gx)
|
const y0 = topY(gx)
|
||||||
members[0].x = gx
|
members[0].x = gx
|
||||||
members[0].y = y0
|
members[0].y = y0
|
||||||
const m = members.length - 1
|
for (let i = 1; i < members.length; i++) {
|
||||||
if (!m) return
|
const th = Math.PI - (i * CLEAR) / FAN_R
|
||||||
const tMax = m * CLEAR * 0.9
|
members[i].x = gx + FAN_R * (1 + Math.cos(th))
|
||||||
const B = 0.4 / (tMax * tMax)
|
members[i].y = y0 + FAN_R * Math.sin(th)
|
||||||
let t = 0
|
|
||||||
for (let i = 1; i <= m; i++) {
|
|
||||||
const bend = 3 * B * t * t
|
|
||||||
t += CLEAR / Math.hypot(bend, 1)
|
|
||||||
const n = members[i]
|
|
||||||
n.x = gx + B * t * t * t
|
|
||||||
n.y = y0 + t
|
|
||||||
spokePairs.push([members[i - 1], n])
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Fan spokes bow to the right via a quadratic control point pushed
|
// Branch lanes: one wide arc per path prefix (slug depth ≥ 1) whose
|
||||||
// rightward from the segment midpoint.
|
// subtree holds at least two visible nodes (a branch's visible nodes
|
||||||
const spokes = spokePairs.map(([p, n]) => {
|
// form one contiguous run in the fan's DFS preorder). Every lane of a
|
||||||
const mx = (p.x + n.x) / 2
|
// group is an arc around the group's fan center with a radius one
|
||||||
const my = (p.y + n.y) / 2
|
// INDENT larger per parent level — concentric circles, so all lanes
|
||||||
const bow = Math.hypot(n.x - p.x, n.y - p.y) * 0.18
|
// share exactly one form. Lanes span their branch's nodes plus a
|
||||||
return {
|
// little extra tucked under the first/last pill (so the line caps are
|
||||||
d: `M ${p.x.toFixed(2)} ${p.y.toFixed(2)} `
|
// never visible) and run behind the pills. A label arc carries the
|
||||||
+ `Q ${(mx + bow).toFixed(2)} ${my.toFixed(2)} ${n.x.toFixed(2)} ${n.y.toFixed(2)}`,
|
// branch slug, left-aligned just past the first pill and free to run
|
||||||
|
// to the lane's end — longer text simply passes under later pills,
|
||||||
|
// which are drawn on top. Hidden (unplaced) index pages still
|
||||||
|
// define a lane: it follows their promoted children, so lanes reflect
|
||||||
|
// the path structure rather than page existence.
|
||||||
|
const INDENT = 20 // lane spacing (radius) per nesting level (> lane width)
|
||||||
|
const END_TUCK = 22 // arc units tucked under the first/last pill
|
||||||
|
const GAP_TRIM = 32 // label arc clearance from the pills
|
||||||
|
// Labels are left-aligned on their guide: the guide starts just past the
|
||||||
|
// source pill's edge, the earliest point where the text is visible.
|
||||||
|
const LABEL_PAD = 6
|
||||||
|
// The label guide rides GUIDE_OFF outward of the lane centerline: the
|
||||||
|
// text's alphabetic baseline sits on the guide, so this puts the
|
||||||
|
// glyph middle (not the baseline) on the lane center at any zoom —
|
||||||
|
// dominant-baseline tricks are em-based and break under downscale.
|
||||||
|
const GUIDE_OFF = 3.5
|
||||||
|
const branches = []
|
||||||
|
groups.forEach((members, gi) => {
|
||||||
|
const g = groupRoots[gi]
|
||||||
|
if (g === root || members.length < 2) return
|
||||||
|
const idx = new Map(members.map((n, i) => [n, i]))
|
||||||
|
const C = [gi * SLOT - half + FAN_R, topY(gi * SLOT - half)]
|
||||||
|
const walk = (n) => {
|
||||||
|
let first = Infinity
|
||||||
|
let last = -1
|
||||||
|
const span = (m) => {
|
||||||
|
const k = idx.get(m)
|
||||||
|
if (k !== undefined) {
|
||||||
|
first = Math.min(first, k)
|
||||||
|
last = Math.max(last, k)
|
||||||
}
|
}
|
||||||
|
m.children.forEach(span)
|
||||||
|
}
|
||||||
|
span(n)
|
||||||
|
if (n.depth >= 1 && last > first) {
|
||||||
|
branches.push({ depth: n.depth, name: n.path.split('/').pop(), C, first, last })
|
||||||
|
}
|
||||||
|
n.children.forEach(walk)
|
||||||
|
}
|
||||||
|
walk(g)
|
||||||
})
|
})
|
||||||
return { GAP: TNODE_H * 2.6, spokes }
|
const depthMax = branches.reduce((d, b) => Math.max(d, b.depth), 1)
|
||||||
|
let arcLeft = Infinity // leftmost lane point, for the bounding box
|
||||||
|
const arcs = branches.map(({ depth, name, C, first, last }) => {
|
||||||
|
const R = FAN_R + (depthMax - depth) * INDENT
|
||||||
|
const th = (i) => Math.PI - (i * CLEAR) / FAN_R
|
||||||
|
const pt = (a, r) => [C[0] + r * Math.cos(a), C[1] + r * Math.sin(a)]
|
||||||
|
// Arc from angle a down to angle b (a > b; visually counterclockwise
|
||||||
|
// from the west point downward, hence sweep flag 0).
|
||||||
|
const arc = (a, b, r) => {
|
||||||
|
const [x0, y0] = pt(a, r)
|
||||||
|
const [x1, y1] = pt(b, r)
|
||||||
|
return `M ${x0.toFixed(2)} ${y0.toFixed(2)} A ${r.toFixed(2)} ${r.toFixed(2)} 0 0 0 ${x1.toFixed(2)} ${y1.toFixed(2)}`
|
||||||
|
}
|
||||||
|
const d = arc(th(first) + END_TUCK / R, th(last) - END_TUCK / R, R)
|
||||||
|
// Start just past the first pill: lanes leave the source node nearly
|
||||||
|
// vertically, so the pill's extent along the arc is its half height.
|
||||||
|
// The guide runs to the lane's end so long slugs are never cut off.
|
||||||
|
const ld = arc(th(first) - (TNODE_H / 2 + LABEL_PAD) / R,
|
||||||
|
th(last) - END_TUCK / R, R + GUIDE_OFF)
|
||||||
|
arcLeft = Math.min(arcLeft, pt(th(first) + END_TUCK / R, R)[0])
|
||||||
|
return { d, ld, label: name }
|
||||||
|
})
|
||||||
|
// Top lane: an arc along the top row's own circle, connecting
|
||||||
|
// the top nodes of all groups and tucked under the first and last of
|
||||||
|
// them (the arc bottoms at the last item, so it continues rightward
|
||||||
|
// under its pill). Drawn 50% thicker than branch lanes. A 🏠︎ label
|
||||||
|
// marks the lane right after the home pill, on a guide arc like
|
||||||
|
// the branch labels but with the offset and clearance scaled up by the
|
||||||
|
// same 50% to keep the glyph centered on the wider lane.
|
||||||
|
if (span) {
|
||||||
|
const d = `M ${(-half - END_TUCK).toFixed(2)} ${topY(-half - END_TUCK).toFixed(2)} `
|
||||||
|
+ `A ${R_T.toFixed(2)} ${R_T.toFixed(2)} 0 0 0 ${(half + END_TUCK).toFixed(2)} ${topY(half + END_TUCK).toFixed(2)}`
|
||||||
|
const rG = R_T + GUIDE_OFF * 1.5
|
||||||
|
const ptG = (x) => [x, topD - R_T + Math.sqrt(rG * rG - (x - half) ** 2)]
|
||||||
|
// Left-aligned like the branch labels: the guide starts just past the
|
||||||
|
// home pill's edge (scaled with the lane thickness).
|
||||||
|
const g0 = -half + TNODE_W / 2 + LABEL_PAD * 1.5
|
||||||
|
const g1 = SLOT - half - TNODE_W / 2 - GAP_TRIM * 1.5
|
||||||
|
const [gx0, gy0] = ptG(g0)
|
||||||
|
const [gx1, gy1] = ptG(g1)
|
||||||
|
arcs.unshift({
|
||||||
|
d,
|
||||||
|
ld: `M ${gx0.toFixed(2)} ${gy0.toFixed(2)} A ${rG.toFixed(2)} ${rG.toFixed(2)} 0 0 0 ${gx1.toFixed(2)} ${gy1.toFixed(2)}`,
|
||||||
|
label: '🏠︎',
|
||||||
|
top: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { arcs, arcLeft }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Collapse opposite transition directions into one unordered pair per page pair. */
|
/** Collapse opposite transition directions into one unordered pair per page pair. */
|
||||||
@@ -541,12 +624,12 @@ function buildRibbon(a, b, ab, ba, wMid, external = false) {
|
|||||||
* to inside the target node (beads render under the node pills, so
|
* to inside the target node (beads render under the node pills, so
|
||||||
* they emerge from and vanish beneath the nodes rather than popping in
|
* they emerge from and vanish beneath the nodes rather than popping in
|
||||||
* at the surround), plus the emission interval (seconds between beads,
|
* at the surround), plus the emission interval (seconds between beads,
|
||||||
* inverse of count * BEAD_RATE). Each segment is offset to the
|
* inverse of the daily hit rate * BEAD_RATE). Each segment is offset to the
|
||||||
* right-hand side of its travel direction, so opposing flows on the same
|
* right-hand side of its travel direction, so opposing flows on the same
|
||||||
* edge run on parallel lanes instead of colliding. The component turns
|
* edge run on parallel lanes instead of colliding. The component turns
|
||||||
* these into independently simulated beads.
|
* these into independently simulated beads.
|
||||||
*/
|
*/
|
||||||
function buildFlows(a, b, ab, ba, visualScale = 1) {
|
function buildFlows(a, b, ab, ba, dayScale = 1) {
|
||||||
const len = Math.hypot(b.x - a.x, b.y - a.y) || 1
|
const len = Math.hypot(b.x - a.x, b.y - a.y) || 1
|
||||||
const ux = (b.x - a.x) / len
|
const ux = (b.x - a.x) / len
|
||||||
const uy = (b.y - a.y) / len
|
const uy = (b.y - a.y) / len
|
||||||
@@ -569,24 +652,26 @@ function buildFlows(a, b, ab, ba, visualScale = 1) {
|
|||||||
x2: a.x + toT * ux + s * rx,
|
x2: a.x + toT * ux + s * rx,
|
||||||
y2: a.y + toT * uy + s * ry,
|
y2: a.y + toT * uy + s * ry,
|
||||||
len: span,
|
len: span,
|
||||||
interval: 1 / (count * BEAD_RATE * visualScale),
|
interval: 1 / (count * BEAD_RATE * dayScale),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const flows = []
|
const flows = []
|
||||||
if (ab) flows.push(flow(ab, t0, t1))
|
// Stable key per edge direction so the component's bead simulation can
|
||||||
if (ba) flows.push(flow(ba, t1, t0))
|
// match flows across data reloads and keep bead phases/positions.
|
||||||
|
if (ab) flows.push({ ...flow(ab, t0, t1), key: `${a.path} ${b.path}` })
|
||||||
|
if (ba) flows.push({ ...flow(ba, t1, t0), key: `${b.path} ${a.path}` })
|
||||||
return flows
|
return flows
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Half-width for a connection middle: logarithmic in the count, anchored
|
* Half-width for a connection middle: base-2 logarithmic in the daily
|
||||||
* so a single count lands exactly at WMID_MIN (~1 px line), uncapped.
|
* hit rate, zero at DAILY_REF hits/day, uncapped. Absolute on purpose —
|
||||||
* Absolute on purpose — cool routes stay visible regardless of how hot
|
* cool routes stay visible regardless of how hot the hottest connection
|
||||||
* the hottest connection is.
|
* is. Callers cull results below MIN_WMID.
|
||||||
*/
|
*/
|
||||||
const scaledWidth = (count) => {
|
const scaledWidth = (daily) => {
|
||||||
if (count <= 0) return 0
|
if (daily <= 0) return 0
|
||||||
return WMID_MIN + WIDTH_GROWTH * Math.log1p(count - 1)
|
return WIDTH_GROWTH * Math.log2(daily / DAILY_REF)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -594,7 +679,7 @@ const scaledWidth = (count) => {
|
|||||||
* pair. Pairs carrying less than PRUNE_FRACTION of the total internal
|
* pair. Pairs carrying less than PRUNE_FRACTION of the total internal
|
||||||
* traffic are pruned (this naturally bounds the graph to ~100 edges).
|
* traffic are pruned (this naturally bounds the graph to ~100 edges).
|
||||||
*/
|
*/
|
||||||
function buildInternalEdges(pairs, byPath, visualScale = 1) {
|
function buildInternalEdges(pairs, byPath, dayScale = 1) {
|
||||||
let total = 0
|
let total = 0
|
||||||
for (const [, [ab, ba]] of pairs) total += ab + ba
|
for (const [, [ab, ba]] of pairs) total += ab + ba
|
||||||
const minCount = total * PRUNE_FRACTION
|
const minCount = total * PRUNE_FRACTION
|
||||||
@@ -607,60 +692,14 @@ function buildInternalEdges(pairs, byPath, visualScale = 1) {
|
|||||||
const a = byPath.get(pf)
|
const a = byPath.get(pf)
|
||||||
const b = byPath.get(pt)
|
const b = byPath.get(pt)
|
||||||
if (a.hidden || b.hidden) continue // unplaced index pages are omitted
|
if (a.hidden || b.hidden) continue // unplaced index pages are omitted
|
||||||
const wMid = scaledWidth((ab + ba) * visualScale)
|
const wMid = scaledWidth((ab + ba) * dayScale)
|
||||||
if (wMid <= 0) continue
|
if (wMid < MIN_WMID) continue
|
||||||
edges.push(buildRibbon(a, b, ab, ba, wMid))
|
edges.push(buildRibbon(a, b, ab, ba, wMid))
|
||||||
flows.push(...buildFlows(a, b, ab, ba, visualScale))
|
flows.push(...buildFlows(a, b, ab, ba, dayScale))
|
||||||
}
|
}
|
||||||
return { edges, flows }
|
return { edges, flows }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Sum the bucketed transition matrix (from -> to -> bucket ISO -> count)
|
|
||||||
* into a plain from -> to -> count matrix for the window [t0, t1).
|
|
||||||
*/
|
|
||||||
export function filterTransitionsByRange(transitions, t0, t1) {
|
|
||||||
const out = {}
|
|
||||||
for (const [fr, tos] of Object.entries(transitions || {})) {
|
|
||||||
for (const [to, buckets] of Object.entries(tos)) {
|
|
||||||
let n = 0
|
|
||||||
for (const [k, c] of Object.entries(buckets)) {
|
|
||||||
const t = Date.parse(k)
|
|
||||||
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) n += c
|
|
||||||
}
|
|
||||||
if (n) {
|
|
||||||
out[fr] = out[fr] || {}
|
|
||||||
out[fr][to] = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Keep only the 5-minute view buckets that fall inside [t0, t1). */
|
|
||||||
export function filterViewsByRange(views, t0, t1) {
|
|
||||||
const filtered = {}
|
|
||||||
for (const [path, buckets] of Object.entries(views || {})) {
|
|
||||||
const out = {}
|
|
||||||
for (const [k, c] of Object.entries(buckets)) {
|
|
||||||
const t = Date.parse(k)
|
|
||||||
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) out[k] = c
|
|
||||||
}
|
|
||||||
if (Object.keys(out).length) filtered[path] = out
|
|
||||||
}
|
|
||||||
return filtered
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Keep only visits whose start time falls inside [t0, t1). */
|
|
||||||
export function filterVisitsByRange(visits, t0, t1) {
|
|
||||||
const out = []
|
|
||||||
for (const v of visits || []) {
|
|
||||||
const t = Date.parse(v.start)
|
|
||||||
if ((t0 == null || t >= t0) && (t1 == null || t < t1)) out.push(v)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
const UTM_PRIORITY = ['utm_campaign', 'utm_source']
|
const UTM_PRIORITY = ['utm_campaign', 'utm_source']
|
||||||
const UTM_FALLBACK = ['utm_medium', 'utm_content', 'utm_term', 'utm_id']
|
const UTM_FALLBACK = ['utm_medium', 'utm_content', 'utm_term', 'utm_id']
|
||||||
|
|
||||||
@@ -726,11 +765,13 @@ function collectSourcePairs(visits) {
|
|||||||
* flows.
|
* flows.
|
||||||
* Sources (incoming links) are derived from visit UTM/referer data and form
|
* Sources (incoming links) are derived from visit UTM/referer data and form
|
||||||
* a row centered above the map, hottest first; exits come from the
|
* a row centered above the map, hottest first; exits come from the
|
||||||
* transition matrix and sit just outside their source page.
|
* transition matrix and form a matching row centered below the map, so
|
||||||
|
* the site itself stays in the middle. Both rows sit EXT_GAP beyond the
|
||||||
|
* map's bounds.
|
||||||
* Widths and pruning use the same log scale and traffic-share rule as
|
* Widths and pruning use the same log scale and traffic-share rule as
|
||||||
* internal connections.
|
* internal connections.
|
||||||
*/
|
*/
|
||||||
function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale = 1) {
|
function buildExternal({ sources, exits }, byPath, innerBounds, dayScale = 1) {
|
||||||
const extNodes = []
|
const extNodes = []
|
||||||
const edges = []
|
const edges = []
|
||||||
const flows = []
|
const flows = []
|
||||||
@@ -742,19 +783,11 @@ function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale
|
|||||||
const liveExits = exits.filter((p) => byPath.has(p.page))
|
const liveExits = exits.filter((p) => byPath.has(p.page))
|
||||||
if (!liveSources.length && !liveExits.length) return { extNodes, edges, flows }
|
if (!liveSources.length && !liveExits.length) return { extNodes, edges, flows }
|
||||||
|
|
||||||
const width = (count) => scaledWidth(count * visualScale)
|
const width = (count) => scaledWidth(count * dayScale)
|
||||||
|
|
||||||
// Pill-shape overlap test (axis-aligned pills): much tighter than the
|
|
||||||
// bounding-circle test, so diagonal placements can sit close.
|
|
||||||
const overlaps = (x, y) =>
|
|
||||||
[...byPath.values(), ...extNodes].some(
|
|
||||||
(n) => !n.hidden
|
|
||||||
&& Math.abs(n.x - x) < TNODE_W + 12
|
|
||||||
&& Math.abs(n.y - y) < TNODE_H + 12,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Incoming: one source node per identified source, in a row centered
|
// Incoming: one source node per identified source, in a row centered
|
||||||
// above the map, with an edge to each page that source led to.
|
// above the map, with an edge to each page that source led to. A source
|
||||||
|
// whose connectors are all culled (below MIN_WMID) is dropped itself.
|
||||||
const bySource = new Map() // source -> pairs, sorted by total incoming count
|
const bySource = new Map() // source -> pairs, sorted by total incoming count
|
||||||
for (const p of liveSources.filter((p) => p.in >= minCount)) {
|
for (const p of liveSources.filter((p) => p.in >= minCount)) {
|
||||||
const g = bySource.get(p.source) || []
|
const g = bySource.get(p.source) || []
|
||||||
@@ -771,9 +804,11 @@ function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale
|
|||||||
}))
|
}))
|
||||||
.sort((a, b) => b.total - a.total)
|
.sort((a, b) => b.total - a.total)
|
||||||
.slice(0, MAX_EXT_IN)
|
.slice(0, MAX_EXT_IN)
|
||||||
|
.filter(({ ps }) =>
|
||||||
|
ps.some((p) => !byPath.get(p.page).hidden && width(p.in) >= MIN_WMID))
|
||||||
if (origins.length) {
|
if (origins.length) {
|
||||||
const cx = (innerBounds.x0 + innerBounds.x1) / 2
|
const cx = (innerBounds.x0 + innerBounds.x1) / 2
|
||||||
const y = innerBounds.y0 - TNODE_BOUND - 64
|
const y = innerBounds.y0 - TNODE_BOUND - EXT_GAP
|
||||||
const spacing = TNODE_W + 44
|
const spacing = TNODE_W + 44
|
||||||
const x0 = cx - ((origins.length - 1) * spacing) / 2
|
const x0 = cx - ((origins.length - 1) * spacing) / 2
|
||||||
origins.forEach(({ source, ps, total, href, isUtm }, i) => {
|
origins.forEach(({ source, ps, total, href, isUtm }, i) => {
|
||||||
@@ -781,7 +816,7 @@ function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale
|
|||||||
const xn = {
|
const xn = {
|
||||||
path: source,
|
path: source,
|
||||||
href,
|
href,
|
||||||
label: label.length > 25 ? `${label.slice(0, 24)}…` : label,
|
label, // clipped at the pill border on render
|
||||||
x: x0 + i * spacing,
|
x: x0 + i * spacing,
|
||||||
y,
|
y,
|
||||||
count: total,
|
count: total,
|
||||||
@@ -792,79 +827,56 @@ function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale
|
|||||||
const page = byPath.get(p.page)
|
const page = byPath.get(p.page)
|
||||||
if (page.hidden) continue
|
if (page.hidden) continue
|
||||||
const wMid = width(p.in)
|
const wMid = width(p.in)
|
||||||
if (wMid <= 0) continue
|
if (wMid < MIN_WMID) continue
|
||||||
edges.push(buildRibbon(xn, page, p.in, 0, wMid, true))
|
edges.push(buildRibbon(xn, page, p.in, 0, wMid, true))
|
||||||
flows.push(...buildFlows(xn, page, p.in, 0, visualScale))
|
flows.push(...buildFlows(xn, page, p.in, 0, dayScale))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Outgoing: group by full URL so several links to the same domain stay
|
// Outgoing: one exit node per distinct full URL (so several links to
|
||||||
// distinct; each shows the total count across all pages linking to it.
|
// the same domain stay distinct), showing the total count across all
|
||||||
// Placement looks for empty space around the source page, always
|
// pages linking to it, in a row centered below the map (hottest
|
||||||
// leftward: diagonal down-left first (often right beside the source,
|
// first), mirroring the source row above. Each (URL, page) pair
|
||||||
// no need to drop below the fans), then left, up-left, and steeper
|
// contributes an edge from that page. An exit whose connectors are all
|
||||||
// fallbacks; the distance grows until a spot is free. Several exits of
|
// culled (below MIN_WMID) is dropped itself.
|
||||||
// one page start at different directions.
|
const byExt = new Map() // full URL -> { ext, out, pairs }
|
||||||
const GAP = gap
|
for (const p of liveExits.filter((p) => p.out >= minCount)) {
|
||||||
const DIRS = [
|
const g = byExt.get(p.ext) || { ext: p.ext, out: 0, pairs: [] }
|
||||||
(3 * Math.PI) / 4, // diagonal down-left
|
g.out += p.out
|
||||||
Math.PI, // left
|
g.pairs.push(p)
|
||||||
(5 * Math.PI) / 4, // diagonal up-left
|
byExt.set(p.ext, g)
|
||||||
Math.PI / 2 + 0.35, // steep down-left
|
}
|
||||||
Math.PI - 0.35, // shallow up-left
|
const targets = [...byExt.values()]
|
||||||
(3 * Math.PI) / 4 + 0.5, // far down-left
|
|
||||||
]
|
|
||||||
const outgoing = liveExits.filter((p) => p.out >= minCount)
|
|
||||||
.sort((a, b) => b.out - a.out)
|
.sort((a, b) => b.out - a.out)
|
||||||
const perPage = new Map()
|
.slice(0, MAX_EXT_OUT)
|
||||||
const selected = []
|
.filter(({ pairs }) =>
|
||||||
for (const p of outgoing) {
|
pairs.some((p) => !byPath.get(p.page).hidden && width(p.out) >= MIN_WMID))
|
||||||
const used = perPage.get(p.page) || 0
|
if (targets.length) {
|
||||||
if (used >= MAX_EXT_OUT_PER_PAGE) continue
|
const cx = (innerBounds.x0 + innerBounds.x1) / 2
|
||||||
perPage.set(p.page, used + 1)
|
const y = innerBounds.y1 + TNODE_BOUND + EXT_GAP
|
||||||
selected.push(p)
|
const spacing = TNODE_W + 44
|
||||||
if (selected.length >= MAX_EXT_OUT) break
|
const x0 = cx - ((targets.length - 1) * spacing) / 2
|
||||||
}
|
targets.forEach(({ ext, out, pairs }, i) => {
|
||||||
|
const xn = {
|
||||||
const exitNodes = new Map() // full URL -> node
|
path: ext,
|
||||||
const placedPerPage = new Map() // for the placement direction offset
|
href: ext,
|
||||||
for (const p of selected) {
|
label: extLabel(ext),
|
||||||
const page = byPath.get(p.page)
|
x: x0 + i * spacing,
|
||||||
if (page.hidden) continue
|
|
||||||
let xn = exitNodes.get(p.ext)
|
|
||||||
if (!xn) {
|
|
||||||
const used = placedPerPage.get(p.page) || 0
|
|
||||||
placedPerPage.set(p.page, used + 1)
|
|
||||||
let x = 0
|
|
||||||
let y = 0
|
|
||||||
let found = false
|
|
||||||
for (let di = 0; di < DIRS.length && !found; di++) {
|
|
||||||
const ang = DIRS[(used + di) % DIRS.length]
|
|
||||||
for (let dist = GAP; dist <= GAP * 3.5; dist += GAP * 0.4) {
|
|
||||||
x = page.x + Math.cos(ang) * dist
|
|
||||||
y = page.y + Math.sin(ang) * dist
|
|
||||||
if (!overlaps(x, y)) { found = true; break }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!found) continue // no empty space near the page: leave it out
|
|
||||||
xn = {
|
|
||||||
path: p.ext,
|
|
||||||
href: p.ext,
|
|
||||||
label: extLabel(p.ext),
|
|
||||||
x,
|
|
||||||
y,
|
y,
|
||||||
count: 0,
|
count: out,
|
||||||
kind: 'exit',
|
kind: 'exit',
|
||||||
}
|
}
|
||||||
exitNodes.set(p.ext, xn)
|
|
||||||
extNodes.push(xn)
|
extNodes.push(xn)
|
||||||
}
|
for (const p of pairs) {
|
||||||
xn.count += p.out
|
const page = byPath.get(p.page)
|
||||||
|
if (page.hidden) continue
|
||||||
const wMid = width(p.out)
|
const wMid = width(p.out)
|
||||||
if (wMid <= 0) continue
|
if (wMid < MIN_WMID) continue
|
||||||
edges.push(buildRibbon(page, xn, p.out, 0, wMid, true))
|
edges.push(buildRibbon(page, xn, p.out, 0, wMid, true))
|
||||||
flows.push(...buildFlows(page, xn, p.out, 0, visualScale))
|
flows.push(...buildFlows(page, xn, p.out, 0, dayScale))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return { extNodes, edges, flows }
|
return { extNodes, edges, flows }
|
||||||
@@ -873,44 +885,51 @@ function buildExternal({ sources, exits }, byPath, gap, innerBounds, visualScale
|
|||||||
/**
|
/**
|
||||||
* Build the transition map model.
|
* Build the transition map model.
|
||||||
* Returns { nodes, edges, flows, extNodes, arcs, bounds } or null when
|
* Returns { nodes, edges, flows, extNodes, arcs, bounds } or null when
|
||||||
* there is nothing to show. `arcs` holds the family spokes; `nodes` only
|
* there is nothing to show. `arcs` holds the branch curves; `nodes` only
|
||||||
* contains placed (visible) nodes.
|
* contains placed (visible) nodes. `dayScale` converts raw counts to a
|
||||||
|
* daily hit rate (DAY / range ms) for edge widths and bead rates.
|
||||||
*/
|
*/
|
||||||
export function buildTransitionGraph(data, pageTree, visits = [], visualScale = 1) {
|
export function buildTransitionGraph(data, pageTree, visits = [], dayScale = 1) {
|
||||||
const internal = collectInternalTransitions(data?.transitions)
|
const internal = collectInternalTransitions(data?.transitions)
|
||||||
const sources = collectSourcePairs(visits)
|
const sources = collectSourcePairs(visits)
|
||||||
const exits = collectExitPairs(data?.transitions)
|
const exits = collectExitPairs(data?.transitions)
|
||||||
const navOrder = buildNavigationOrder(pageTree)
|
const navOrder = buildNavigationOrder(pageTree)
|
||||||
const titles = buildTitleMap(pageTree)
|
const titles = buildTitleMap(pageTree)
|
||||||
const readMinutes = buildReadMinutes(visits)
|
const readSeconds = buildReadSeconds(visits)
|
||||||
|
|
||||||
if (!internal.length && !navOrder.size) return null
|
if (!internal.length && !navOrder.size) return null
|
||||||
|
|
||||||
const { nodes, byPath, root } = buildNodeTree(internal, navOrder)
|
const { nodes, byPath, root } = buildNodeTree(internal, navOrder)
|
||||||
sortByNav(root, navOrder)
|
sortByNav(root, navOrder)
|
||||||
annotateNodes(nodes, data?.views, titles, readMinutes)
|
annotateNodes(nodes, data?.views, titles, readSeconds)
|
||||||
const { GAP, spokes } = layoutGroups(root)
|
const { arcs, arcLeft } = layoutGroups(root)
|
||||||
const placed = nodes.filter((n) => !n.hidden)
|
const placed = nodes.filter((n) => !n.hidden)
|
||||||
const pairs = aggregatePairs(internal)
|
const pairs = aggregatePairs(internal)
|
||||||
const { edges, flows } = buildInternalEdges(pairs, byPath, visualScale)
|
const { edges, flows } = buildInternalEdges(pairs, byPath, dayScale)
|
||||||
|
|
||||||
// Tight bounding box of the placed page nodes; external nodes extend it.
|
// Tight bounding box of the placed page nodes, extended to cover the
|
||||||
const pad = 16
|
// branch curves running left of the pills; external nodes extend it.
|
||||||
|
// Margins cover just the ribbon surround (pill outline + flare margin
|
||||||
|
// S=4) plus a small pad: the pill's half width/height, not its diagonal
|
||||||
|
// radius, so the map crops tight especially at top and bottom.
|
||||||
|
const pad = 8
|
||||||
|
const MX = TNODE_W / 2 + 4 + pad
|
||||||
|
const MY = TNODE_H / 2 + 4 + pad
|
||||||
const xs = placed.map((n) => n.x)
|
const xs = placed.map((n) => n.x)
|
||||||
const ys = placed.map((n) => n.y)
|
const ys = placed.map((n) => n.y)
|
||||||
const bounds = {
|
const bounds = {
|
||||||
x0: Math.min(...xs) - TNODE_BOUND - pad,
|
x0: Math.min(Math.min(...xs) - MX, arcLeft - pad),
|
||||||
y0: Math.min(...ys) - TNODE_BOUND - pad,
|
y0: Math.min(...ys) - MY,
|
||||||
x1: Math.max(...xs) + TNODE_BOUND + pad,
|
x1: Math.max(...xs) + MX,
|
||||||
y1: Math.max(...ys) + TNODE_BOUND + pad,
|
y1: Math.max(...ys) + MY,
|
||||||
}
|
}
|
||||||
|
|
||||||
const ext = buildExternal({ sources, exits }, byPath, GAP, bounds, visualScale)
|
const ext = buildExternal({ sources, exits }, byPath, bounds, dayScale)
|
||||||
for (const xn of ext.extNodes) {
|
for (const xn of ext.extNodes) {
|
||||||
bounds.x0 = Math.min(bounds.x0, xn.x - TNODE_BOUND - pad)
|
bounds.x0 = Math.min(bounds.x0, xn.x - MX)
|
||||||
bounds.y0 = Math.min(bounds.y0, xn.y - TNODE_BOUND - pad)
|
bounds.y0 = Math.min(bounds.y0, xn.y - MY)
|
||||||
bounds.x1 = Math.max(bounds.x1, xn.x + TNODE_BOUND + pad)
|
bounds.x1 = Math.max(bounds.x1, xn.x + MX)
|
||||||
bounds.y1 = Math.max(bounds.y1, xn.y + TNODE_BOUND + pad)
|
bounds.y1 = Math.max(bounds.y1, xn.y + MY)
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -918,7 +937,7 @@ export function buildTransitionGraph(data, pageTree, visits = [], visualScale =
|
|||||||
edges: [...edges, ...ext.edges],
|
edges: [...edges, ...ext.edges],
|
||||||
flows: [...flows, ...ext.flows],
|
flows: [...flows, ...ext.flows],
|
||||||
extNodes: ext.extNodes,
|
extNodes: ext.extNodes,
|
||||||
arcs: spokes,
|
arcs,
|
||||||
bounds,
|
bounds,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,11 @@
|
|||||||
/* The brand follows the heading font unless overridden separately. */
|
/* The brand follows the heading font unless overridden separately. */
|
||||||
--font-brand: var(--font-heading);
|
--font-brand: var(--font-heading);
|
||||||
--font-code: var(--font-fira-code);
|
--font-code: var(--font-fira-code);
|
||||||
|
/* Target x-height ratio for code text: set to the body font's ratio
|
||||||
|
(here Source Sans 3's 0.478) so font-size-adjust can scale the code
|
||||||
|
font to the same optical height. Themes retune it to their body font
|
||||||
|
(measured: Literata 0.507, Inter 0.546, Montserrat 0.517, Cause 0.5). */
|
||||||
|
--code-x-height: 0.478;
|
||||||
/* Width of the docked editor panel (used both here for shifting the page
|
/* Width of the docked editor panel (used both here for shifting the page
|
||||||
and in the Vue editor's own styles). */
|
and in the Vue editor's own styles). */
|
||||||
--editor-w: min(46rem, 50vw);
|
--editor-w: min(46rem, 50vw);
|
||||||
@@ -65,6 +70,11 @@
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
::selection {
|
||||||
|
background: color-mix(var(--accent) 30%, transparent);
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
/* Links never underline — including SVG link text, which the UA stylesheet
|
/* Links never underline — including SVG link text, which the UA stylesheet
|
||||||
underlines by default. */
|
underlines by default. */
|
||||||
a {
|
a {
|
||||||
@@ -73,6 +83,10 @@ a {
|
|||||||
|
|
||||||
html {
|
html {
|
||||||
scroll-behavior: smooth;
|
scroll-behavior: smooth;
|
||||||
|
/* No rubber-band bounce past the page ends (macOS trackpads): the banner
|
||||||
|
parallax in --pry is driven by scrollY and overscroll would let the
|
||||||
|
artwork drift beyond its designed range. */
|
||||||
|
overscroll-behavior: none;
|
||||||
/* Native-scrollbar fallback styling (JS off or before pagerite.js runs):
|
/* Native-scrollbar fallback styling (JS off or before pagerite.js runs):
|
||||||
thin, theme-muted thumb on a transparent track. With JS the scrollbars
|
thin, theme-muted thumb on a transparent track. With JS the scrollbars
|
||||||
are replaced by OverlayScrollbars (see pagerite.js) — floating,
|
are replaced by OverlayScrollbars (see pagerite.js) — floating,
|
||||||
@@ -122,7 +136,11 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
min-height: 11rem;
|
/* Height scales down proportionally on small screens: 13rem at 800px
|
||||||
|
(50rem) viewport, shrinking with the smaller of viewport width/height
|
||||||
|
(vmin) below that, floored at 8rem. */
|
||||||
|
height: clamp(8rem, 26vmin, 13rem);
|
||||||
|
box-sizing: content-box;
|
||||||
background: linear-gradient(135deg, var(--surface), var(--bg));
|
background: linear-gradient(135deg, var(--surface), var(--bg));
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 1px solid var(--line);
|
||||||
}
|
}
|
||||||
@@ -187,11 +205,17 @@ body {
|
|||||||
#brand {
|
#brand {
|
||||||
font-family: var(--font-brand);
|
font-family: var(--font-brand);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-size: 2.4rem;
|
/* Scales down proportionally on small screens, same curve as the banner
|
||||||
|
height: 2.4rem at 800px, shrinking with vmin below that. */
|
||||||
|
font-size: clamp(1.4rem, 4.8vmin, 2.4rem);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
/* One line always: pagerite.js shrinks the font size to fit instead of
|
/* One line always: pagerite.js shrinks the font size to fit instead of
|
||||||
wrapping (the themed size is the maximum). */
|
wrapping (the themed size is the maximum). */
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
/* Shrink-wrap to the text: as a flex child of the column-direction
|
||||||
|
#banner it would otherwise stretch full-width, making the empty banner
|
||||||
|
area beside the text a link to the front page. */
|
||||||
|
align-self: flex-start;
|
||||||
margin: auto 1.25rem 0;
|
margin: auto 1.25rem 0;
|
||||||
padding-top: 1.5rem;
|
padding-top: 1.5rem;
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
@@ -249,8 +273,6 @@ body {
|
|||||||
position: relative;
|
position: relative;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(0, 1fr) minmax(0, 78rem) minmax(0, 1fr);
|
grid-template-columns: minmax(0, 1fr) minmax(0, 78rem) minmax(0, 1fr);
|
||||||
/* The docked editor pushes the content (not the header) right. */
|
|
||||||
transition: margin-left 0.25s ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Long articles (.multicol is added by pagerite.js based on content length)
|
/* Long articles (.multicol is added by pagerite.js based on content length)
|
||||||
@@ -265,10 +287,9 @@ body:has(.multicol) #content {
|
|||||||
|
|
||||||
body.editing #content {
|
body.editing #content {
|
||||||
margin-left: var(--editor-w);
|
margin-left: var(--editor-w);
|
||||||
padding-left: 1rem;
|
/* No padding/gap here: the article area starts flush at the panel's right
|
||||||
/* gap between the docked editor and the content */
|
edge so that full-bleed .wide images (anchored to that edge below) line
|
||||||
/* No overflow clipping here: .editor-host lives outside this box
|
up with it exactly. */
|
||||||
(negative left), and .wide shrink-wraps to the remaining space. */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The sidebar's gutter space is needed by the editor instead. */
|
/* The sidebar's gutter space is needed by the editor instead. */
|
||||||
@@ -276,34 +297,23 @@ body.editing #sidebar {
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* While editing, the window itself does not scroll: the editor panel is
|
/* While editing, the window keeps scrolling normally (the overlay
|
||||||
exactly the remaining window height, and only the article area (#main)
|
scrollbars take no layout space, so the vw-based .wide bleed stays exact
|
||||||
scrolls. Without the editor, normal full-page scroll applies. */
|
and no horizontal scrollbar appears). The editor panel is fixed to the
|
||||||
body.editing {
|
viewport's left edge; main.js sets its top each scroll frame — the
|
||||||
height: 100vh;
|
banner's bottom edge while the banner is visible, else the viewport top.
|
||||||
overflow: hidden;
|
The panel scrolls internally. */
|
||||||
}
|
|
||||||
|
|
||||||
body.editing #content {
|
|
||||||
min-height: 0;
|
|
||||||
grid-template-rows: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
body.editing #main {
|
|
||||||
height: 100%;
|
|
||||||
min-height: 0;
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The editor host lives inside #content: it starts below the banner and
|
|
||||||
ends above the footer. With the page scroll locked while editing, the
|
|
||||||
panel exactly fills that space — the full available window height. */
|
|
||||||
.editor-host {
|
.editor-host {
|
||||||
position: absolute;
|
position: fixed;
|
||||||
top: 0;
|
top: 0;
|
||||||
|
/* main.js: banner bottom while visible, else 0 */
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
left: calc(0px - var(--editor-w));
|
left: 0;
|
||||||
width: var(--editor-w);
|
width: var(--editor-w);
|
||||||
|
/* Above the sidebar, .edit-link and the banner's top-right pens
|
||||||
|
(z-index 10) while sliding in/out (the host now lives at the end of
|
||||||
|
<body>, so it needs its own stacking level). */
|
||||||
|
z-index: 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
.editor-root.overlay {
|
.editor-root.overlay {
|
||||||
@@ -381,7 +391,7 @@ body.editing #main {
|
|||||||
#sidebar ul ul {
|
#sidebar ul ul {
|
||||||
gap: 0.5em;
|
gap: 0.5em;
|
||||||
margin-top: 0.5em;
|
margin-top: 0.5em;
|
||||||
padding-inline-start: 1em;
|
padding-inline-start: 1.8em;
|
||||||
}
|
}
|
||||||
|
|
||||||
#sidebar ul ul li::before {
|
#sidebar ul ul li::before {
|
||||||
@@ -414,7 +424,10 @@ main {
|
|||||||
|
|
||||||
article h1,
|
article h1,
|
||||||
article h2,
|
article h2,
|
||||||
article h3 {
|
article h3,
|
||||||
|
article h4,
|
||||||
|
article h5,
|
||||||
|
article h6 {
|
||||||
font-family: var(--font-heading);
|
font-family: var(--font-heading);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
line-height: 1.25;
|
line-height: 1.25;
|
||||||
@@ -434,13 +447,31 @@ article dl,
|
|||||||
article blockquote,
|
article blockquote,
|
||||||
article pre,
|
article pre,
|
||||||
article figure,
|
article figure,
|
||||||
article table {
|
article table,
|
||||||
|
article h3,
|
||||||
|
article h4,
|
||||||
|
article h5,
|
||||||
|
article h6 {
|
||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
article h3 {
|
/* Headings separate from the text above via a top margin on the sibling
|
||||||
margin: 1.4rem 0 0.4rem;
|
combinator: a heading that is the first child of a container (e.g. the
|
||||||
|
top of a .colseg column segment) gets no gap, and browsers truncate the
|
||||||
|
margin at column breaks, so column tops stay aligned. */
|
||||||
|
article h3,
|
||||||
|
article h4,
|
||||||
|
article h5,
|
||||||
|
article h6 {
|
||||||
|
margin-bottom: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
article * + h3,
|
||||||
|
article * + h4,
|
||||||
|
article * + h5,
|
||||||
|
article * + h6 {
|
||||||
|
margin-top: 1.4rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Lists: small diamond emoji markers — blue 🔹 on odd nesting levels,
|
/* Lists: small diamond emoji markers — blue 🔹 on odd nesting levels,
|
||||||
@@ -448,7 +479,7 @@ article h3 {
|
|||||||
lines align. */
|
lines align. */
|
||||||
article ul {
|
article ul {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
padding-inline-start: 1em;
|
padding-inline-start: 1.8em;
|
||||||
}
|
}
|
||||||
|
|
||||||
article ul li::before {
|
article ul li::before {
|
||||||
@@ -531,9 +562,10 @@ article dd {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Multi-column reading, but only for long articles (pagerite.js adds
|
/* Multi-column reading, but only for long articles (pagerite.js adds
|
||||||
.multicol based on content length and splits the body into .colseg segments
|
.multicol based on content length — code blocks excluded — and splits
|
||||||
separated by full-width h2s and wide figures; only segments with enough
|
the body into .colseg segments separated by full-width h2s and .wide
|
||||||
text get .cols). No fixed breakpoint: `columns: 30rem` lets CSS fit as
|
elements; only segments with enough text get .cols, and a ::: nocols
|
||||||
|
container opts its section out). No fixed breakpoint: `columns: 30rem` lets CSS fit as
|
||||||
many columns of at least 30rem as the article's current width allows —
|
many columns of at least 30rem as the article's current width allows —
|
||||||
since .multicol also uncaps the article width (see #content above), a
|
since .multicol also uncaps the article width (see #content above), a
|
||||||
wider window simply yields more columns. */
|
wider window simply yields more columns. */
|
||||||
@@ -546,6 +578,13 @@ article dd {
|
|||||||
.multicol .colseg {
|
.multicol .colseg {
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
|
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
break-after: avoid-column;
|
||||||
|
}
|
||||||
|
|
||||||
p,
|
p,
|
||||||
li {
|
li {
|
||||||
break-inside: avoid-column;
|
break-inside: avoid-column;
|
||||||
@@ -555,7 +594,9 @@ article dd {
|
|||||||
pre,
|
pre,
|
||||||
blockquote,
|
blockquote,
|
||||||
table,
|
table,
|
||||||
dl {
|
dl,
|
||||||
|
.admonition,
|
||||||
|
.markdown-alert {
|
||||||
break-inside: avoid;
|
break-inside: avoid;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -575,10 +616,11 @@ article a:hover {
|
|||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Blockquotes: inner paragraphs carry no margins (spacing comes from the
|
/* Blockquotes: spacing comes from the blockquote itself (bottom-only like
|
||||||
blockquote itself, bottom-only like everything else in articles). The
|
everything else in articles); inner paragraphs keep only the gap between
|
||||||
negative left margin pushes the bar out past the text edge, so quoted
|
them. The negative left margin pushes the bar out past the text edge, so
|
||||||
text aligns with the surrounding paragraphs — same trick as code blocks. */
|
quoted text aligns with the surrounding paragraphs — same trick as code
|
||||||
|
blocks. */
|
||||||
blockquote {
|
blockquote {
|
||||||
margin: 0 0 1rem -0.5rem;
|
margin: 0 0 1rem -0.5rem;
|
||||||
padding: 0 0 0 0.25rem;
|
padding: 0 0 0 0.25rem;
|
||||||
@@ -590,42 +632,128 @@ blockquote p {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Admonitions (markdown !!! note/warning/...): a lightweight callout in
|
blockquote p + p {
|
||||||
the blockquote idiom — accent bar and a faint wash, recolored per type.
|
margin-top: 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Admonitions (markdown !!! note/warning/...) and GitHub-style alerts
|
||||||
|
(> [!NOTE] ...): a lightweight callout in the blockquote idiom — accent
|
||||||
|
bar and a faint wash, recolored per type, with a type emoji on the
|
||||||
|
title. The negative left margin pushes bar and wash out past the text
|
||||||
|
edge so the inner text aligns with surrounding paragraphs — same trick
|
||||||
|
as blockquotes and code blocks (margin-left = border + padding-left).
|
||||||
Bottom-only margins like everything else in articles; inner paragraphs
|
Bottom-only margins like everything else in articles; inner paragraphs
|
||||||
carry no margins of their own. */
|
carry no margins of their own. */
|
||||||
.admonition {
|
.admonition,
|
||||||
margin: 0 0 1rem;
|
.markdown-alert {
|
||||||
|
margin: 0 0 1rem -1.15rem;
|
||||||
padding: 0.4rem 0.9rem;
|
padding: 0.4rem 0.9rem;
|
||||||
border-left: 0.25rem solid var(--admonition-color, var(--accent));
|
border-left: 0.25rem solid var(--admonition-color, var(--accent));
|
||||||
border-radius: 0 0.3rem 0.3rem 0;
|
border-radius: 0 0.3rem 0.3rem 0;
|
||||||
background: color-mix(in srgb, var(--admonition-color, var(--accent)) 7%, transparent);
|
background: color-mix(in srgb, var(--admonition-color, var(--accent)) 7%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.admonition> :last-child {
|
.admonition> :last-child,
|
||||||
|
.markdown-alert> :last-child {
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admonition-title {
|
.admonition-title,
|
||||||
|
.markdown-alert-title {
|
||||||
margin: 0 0 0.2rem;
|
margin: 0 0 0.2rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--admonition-color, var(--accent));
|
color: var(--admonition-color, var(--accent));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.admonition-title::before,
|
||||||
|
.markdown-alert-title::before {
|
||||||
|
padding-right: 0.35em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.note .admonition-title::before,
|
||||||
|
.markdown-alert-note .markdown-alert-title::before {
|
||||||
|
content: "ℹ️";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.tip .admonition-title::before,
|
||||||
|
.admonition.hint .admonition-title::before,
|
||||||
|
.markdown-alert-tip .markdown-alert-title::before {
|
||||||
|
content: "✨";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.important .admonition-title::before,
|
||||||
|
.markdown-alert-important .markdown-alert-title::before {
|
||||||
|
content: "❗";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.success .admonition-title::before {
|
||||||
|
content: "✅";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.warning .admonition-title::before,
|
||||||
|
.markdown-alert-warning .markdown-alert-title::before {
|
||||||
|
content: "⚠️";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.caution .admonition-title::before,
|
||||||
|
.markdown-alert-caution .markdown-alert-title::before {
|
||||||
|
content: "🔥";
|
||||||
|
}
|
||||||
|
|
||||||
|
.admonition.danger .admonition-title::before,
|
||||||
|
.admonition.failure .admonition-title::before {
|
||||||
|
content: "⛔";
|
||||||
|
}
|
||||||
|
|
||||||
.admonition.tip,
|
.admonition.tip,
|
||||||
.admonition.important,
|
.admonition.important,
|
||||||
.admonition.hint,
|
.admonition.hint,
|
||||||
.admonition.success {
|
.admonition.success,
|
||||||
|
.markdown-alert-tip,
|
||||||
|
.markdown-alert-important {
|
||||||
--admonition-color: var(--accent2);
|
--admonition-color: var(--accent2);
|
||||||
}
|
}
|
||||||
|
|
||||||
.admonition.warning,
|
.admonition.warning,
|
||||||
.admonition.caution,
|
.admonition.caution,
|
||||||
.admonition.danger,
|
.admonition.danger,
|
||||||
.admonition.failure {
|
.admonition.failure,
|
||||||
|
.markdown-alert-warning,
|
||||||
|
.markdown-alert-caution {
|
||||||
--admonition-color: var(--accent3);
|
--admonition-color: var(--accent3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Asides (::: aside): a floated side box in the floated-figure idiom;
|
||||||
|
consecutive asides stack (clear: right). On wide single-column pages it
|
||||||
|
leans into the empty right gutter (below 104rem the gutter cannot hold
|
||||||
|
the box; multicol pages have no right gutter at all, and while editing
|
||||||
|
the docked panel reshapes the gutters — in all these it stays a plain
|
||||||
|
float). Headings already clear floats, so asides never bleed into the
|
||||||
|
next section. */
|
||||||
|
.aside {
|
||||||
|
float: right;
|
||||||
|
clear: right;
|
||||||
|
width: 30%;
|
||||||
|
max-width: 20rem;
|
||||||
|
margin: 0.3rem 0 1rem 1.2rem;
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
background: color-mix(in srgb, var(--accent) 6%, transparent);
|
||||||
|
border-radius: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.aside> :last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 104rem) {
|
||||||
|
body:not(.editing):not(:has(.multicol)) .aside {
|
||||||
|
width: 12rem;
|
||||||
|
margin-right: -13rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pre {
|
pre {
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
padding: 0.5rem 0.8rem;
|
padding: 0.5rem 0.8rem;
|
||||||
@@ -639,10 +767,15 @@ pre {
|
|||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Inline code integrates with the text, no box of its own */
|
/* Inline code integrates with the text, no box of its own. Instead of a
|
||||||
p code,
|
fixed em shrink (which can't fit every body/code font pairing — Fira
|
||||||
li code {
|
Code's x-height ratio 0.525 is taller than Source Sans 3's 0.478 yet
|
||||||
font-size: 0.85em;
|
shorter than Inter's 0.546), font-size-adjust scales whatever code font
|
||||||
|
is in use so its x-height matches the body font's ratio. Browsers
|
||||||
|
without font-size-adjust get unadjusted 1em code, which is fine. */
|
||||||
|
code {
|
||||||
|
font-family: var(--font-code);
|
||||||
|
font-size-adjust: ex-height var(--code-x-height);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Click-to-copy button (added by pagerite.js) */
|
/* Click-to-copy button (added by pagerite.js) */
|
||||||
@@ -671,11 +804,6 @@ pre:hover .copy,
|
|||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
code {
|
|
||||||
font-family: var(--font-code);
|
|
||||||
font-size: 0.88em;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Tables separate by color, not lines: the header is a soft vertical
|
/* Tables separate by color, not lines: the header is a soft vertical
|
||||||
gradient tinted with the theme's accent (themes can override the
|
gradient tinted with the theme's accent (themes can override the
|
||||||
--table-head-* stops outright), body cells carry a very faint diagonal
|
--table-head-* stops outright), body cells carry a very faint diagonal
|
||||||
@@ -799,18 +927,19 @@ figure:has(img[width]) {
|
|||||||
is not viewport-centered; each just overrides width/margin-inline, and
|
is not viewport-centered; each just overrides width/margin-inline, and
|
||||||
later rules win at equal specificity. The analytics dashboard uses the
|
later rules win at equal specificity. The analytics dashboard uses the
|
||||||
same breakout directly on its container (div.wide — it is the page's
|
same breakout directly on its container (div.wide — it is the page's
|
||||||
whole content, not a figure). */
|
whole content, not a figure), and code blocks via a trailing {.wide}
|
||||||
|
line (fence block attrs land on <pre> itself). */
|
||||||
figure:has(.wide),
|
figure:has(.wide),
|
||||||
div.wide {
|
div.wide,
|
||||||
|
pre.wide {
|
||||||
width: 100vw;
|
width: 100vw;
|
||||||
max-width: none;
|
max-width: none;
|
||||||
margin-inline: calc(50% - 50vw);
|
margin-inline: calc(50% - 50vw);
|
||||||
/* Follow the docked editor's margin-left transition smoothly. */
|
|
||||||
transition: margin-left 0.25s ease;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Full bleed means edge to edge — no rounded corners. */
|
/* Full bleed means edge to edge — no rounded corners. */
|
||||||
figure:has(.wide) img {
|
figure:has(.wide) img,
|
||||||
|
pre.wide {
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -818,22 +947,25 @@ figure:has(.wide) img {
|
|||||||
gutter), so the bleed anchors at the left gutter — the 1fr share of the
|
gutter), so the bleed anchors at the left gutter — the 1fr share of the
|
||||||
1fr + 4fr grid, i.e. 20vw — plus main's padding, and spans on to the
|
1fr + 4fr grid, i.e. 20vw — plus main's padding, and spans on to the
|
||||||
right viewport edge. */
|
right viewport edge. */
|
||||||
body:has(.multicol) figure:has(.wide) {
|
body:has(.multicol) figure:has(.wide),
|
||||||
|
body:has(.multicol) pre.wide {
|
||||||
margin-inline: calc(-20vw - 1.25rem) 0;
|
margin-inline: calc(-20vw - 1.25rem) 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Editing: shrink the bleed to the space right of the docked editor. */
|
/* Editing: shrink the bleed to the space right of the docked editor. The
|
||||||
body.editing figure:has(.wide) {
|
window keeps its overlay scrollbars while editing, so — unlike a classic
|
||||||
|
scrollbar — they take no layout space and the vw math stays exact. */
|
||||||
|
body.editing figure:has(.wide),
|
||||||
|
body.editing pre.wide {
|
||||||
width: calc(100vw - var(--editor-w));
|
width: calc(100vw - var(--editor-w));
|
||||||
margin-inline: calc(50% - (100vw - var(--editor-w)) / 2);
|
margin-inline: calc(50% - (100vw - var(--editor-w)) / 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Editing + multicol: the left gutter is 1/5 of the space right of the
|
/* Editing + multicol: the left gutter is 1/5 of the space right of the
|
||||||
editor, and the bleed also crosses #content's 1rem editing gap plus
|
editor, and the bleed also crosses main's 1.25rem left padding. */
|
||||||
main's 1.25rem left padding (the gutter shrink from the padding roughly
|
body.editing:has(.multicol) figure:has(.wide),
|
||||||
cancels the rounding): −2rem in total. */
|
body.editing:has(.multicol) pre.wide {
|
||||||
body.editing:has(.multicol) figure:has(.wide) {
|
margin-inline: calc((100vw - var(--editor-w)) / -5 - 1.25rem) 0;
|
||||||
margin-inline: calc((100vw - var(--editor-w)) / -5 - 2rem) 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Narrow windows with a sidebar: below 102rem the symmetric gutters can no
|
/* Narrow windows with a sidebar: below 102rem the symmetric gutters can no
|
||||||
@@ -844,7 +976,8 @@ body.editing:has(.multicol) figure:has(.wide) {
|
|||||||
entirely on pages without sub-navigation, and excluded while editing,
|
entirely on pages without sub-navigation, and excluded while editing,
|
||||||
where the editing rules above apply instead. */
|
where the editing rules above apply instead. */
|
||||||
@media (max-width: 102rem) {
|
@media (max-width: 102rem) {
|
||||||
body:has(#sidebar):not(.editing) figure:has(.wide) {
|
body:has(#sidebar):not(.editing) figure:has(.wide),
|
||||||
|
body:has(#sidebar):not(.editing) pre.wide {
|
||||||
margin-inline: -13.25rem 0;
|
margin-inline: -13.25rem 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -907,6 +1040,42 @@ article h2 {
|
|||||||
(explicit img widths still shrink-wrap), while .wide keeps its full
|
(explicit img widths still shrink-wrap), while .wide keeps its full
|
||||||
viewport bleed. */
|
viewport bleed. */
|
||||||
@media (max-width: 48rem) {
|
@media (max-width: 48rem) {
|
||||||
|
|
||||||
|
/* Nav type shrinks fluidly as space runs out. The nav font-size is
|
||||||
|
em-based both in base and in every theme override, so scaling the
|
||||||
|
banner's font-size (nothing else in the banner is em-sized — brand and
|
||||||
|
gaps use rem) reaches the nav through all themes with a single rule.
|
||||||
|
2.6vw crosses 1rem at ≈38.5rem, so only genuinely narrow viewports
|
||||||
|
shrink. */
|
||||||
|
#banner {
|
||||||
|
font-size: clamp(0.65rem, 2.6vw, 1rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Tighter margins/padding/gaps: the 1.25rem side gutter is wasted space
|
||||||
|
on a phone. */
|
||||||
|
#brand {
|
||||||
|
margin-inline: 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#nav {
|
||||||
|
padding: 0.25rem 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#nav ul {
|
||||||
|
gap: 0.15rem 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The editor panel takes over the entire viewport: no space left for
|
||||||
|
the banner or the page content (main.js pins its top to 0 at these
|
||||||
|
widths). */
|
||||||
|
body.editing #content {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.editor-host {
|
||||||
|
width: 100vw;
|
||||||
|
}
|
||||||
|
|
||||||
#content {
|
#content {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -918,7 +1087,11 @@ article h2 {
|
|||||||
max-height: none;
|
max-height: none;
|
||||||
overflow-y: visible;
|
overflow-y: visible;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
padding: 0.5rem 1rem;
|
padding: 0.4rem 0.8rem;
|
||||||
|
/* Smaller type: the horizontal link strip fits roughly a third more
|
||||||
|
items per line. The nested-list gaps below are em-based and shrink
|
||||||
|
along. */
|
||||||
|
font-size: 0.8rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Only the main level becomes a horizontal wrapping strip; submenus stay
|
/* Only the main level becomes a horizontal wrapping strip; submenus stay
|
||||||
@@ -926,7 +1099,7 @@ article h2 {
|
|||||||
#sidebar>ul {
|
#sidebar>ul {
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 0.5rem 1.2rem;
|
gap: 0.3rem 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
figure:has(.right),
|
figure:has(.right),
|
||||||
@@ -1001,11 +1174,11 @@ footer {
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Rotating-cube page transition, adapted from termotohtori.fi.
|
/* Rotating-cube page transition. */
|
||||||
FRAGILE: do not tweak; the view-transition pseudo-tree is picky. */
|
|
||||||
::view-transition {
|
::view-transition {
|
||||||
perspective: 1000px;
|
perspective: 1000px;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
|
background: color-mix(var(--bg) 50%, black 50%);
|
||||||
}
|
}
|
||||||
|
|
||||||
::view-transition-group(root),
|
::view-transition-group(root),
|
||||||
|
|||||||
+65
-5
@@ -22,6 +22,57 @@ let host = null
|
|||||||
let app = null
|
let app = null
|
||||||
let savedTitle = null
|
let savedTitle = null
|
||||||
let visible = false
|
let visible = false
|
||||||
|
let slideAnimation = null
|
||||||
|
|
||||||
|
const SLIDE_MS = 250 // keep in sync with the panel slide in pagerite.css
|
||||||
|
|
||||||
|
// The layout switches instantly when .editing toggles — no margin/width
|
||||||
|
// transitions anywhere, so viewport resizes (and the vw-based .wide bleed)
|
||||||
|
// always stay instant. The visible slide is a compositor-only FLIP
|
||||||
|
// transform on #content, running in sync with the panel's own slide
|
||||||
|
// (editor-slide-in / .closing in pagerite.css): both move by --editor-w
|
||||||
|
// over the same duration and easing, so .wide's left edge tracks the
|
||||||
|
// panel's right edge exactly throughout.
|
||||||
|
function setEditingClass(enable) {
|
||||||
|
const content = document.getElementById('content')
|
||||||
|
const before = content.getBoundingClientRect().left
|
||||||
|
document.body.classList.toggle('editing', enable)
|
||||||
|
const delta = before - content.getBoundingClientRect().left
|
||||||
|
slideAnimation?.cancel()
|
||||||
|
if (delta) {
|
||||||
|
slideAnimation = content.animate(
|
||||||
|
{ transform: [`translateX(${delta}px)`, 'translateX(0)'] },
|
||||||
|
{ duration: SLIDE_MS, easing: 'ease' }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The panel is fixed to the viewport's left edge (pagerite.css) but tracks
|
||||||
|
// the page: its top is the banner's bottom edge while the banner is visible
|
||||||
|
// (= #content's top edge), and the viewport top once the banner has
|
||||||
|
// scrolled away. The window keeps scrolling normally while editing.
|
||||||
|
// Below 48rem the panel covers the entire viewport (pagerite.css), so its
|
||||||
|
// top stays 0 regardless of the banner.
|
||||||
|
const narrow = matchMedia('(max-width: 48rem)')
|
||||||
|
function trackPanelTop() {
|
||||||
|
const content = document.getElementById('content')
|
||||||
|
if (host && content) {
|
||||||
|
host.style.top = narrow.matches
|
||||||
|
? '0px'
|
||||||
|
: `${Math.max(0, content.getBoundingClientRect().top)}px`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startTrackingPanel() {
|
||||||
|
trackPanelTop()
|
||||||
|
addEventListener('scroll', trackPanelTop, { passive: true })
|
||||||
|
addEventListener('resize', trackPanelTop)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopTrackingPanel() {
|
||||||
|
removeEventListener('scroll', trackPanelTop)
|
||||||
|
removeEventListener('resize', trackPanelTop)
|
||||||
|
}
|
||||||
|
|
||||||
export function openEditor(path, { mode = 'page' } = {}) {
|
export function openEditor(path, { mode = 'page' } = {}) {
|
||||||
if (app) {
|
if (app) {
|
||||||
@@ -36,9 +87,13 @@ export function openEditor(path, { mode = 'page' } = {}) {
|
|||||||
savedTitle = document.title
|
savedTitle = document.title
|
||||||
host = document.createElement('div')
|
host = document.createElement('div')
|
||||||
host.className = 'editor-host'
|
host.className = 'editor-host'
|
||||||
// Docked inside #content: below the banner, next to the article only.
|
// Appended to <body>, not #content: the open/close slide transforms
|
||||||
document.getElementById('content').prepend(host)
|
// #content (setEditingClass), and a transformed element becomes the
|
||||||
document.body.classList.add('editing')
|
// containing block for fixed-position descendants — the panel would be
|
||||||
|
// dragged along with the content instead of sliding on its own.
|
||||||
|
document.body.append(host)
|
||||||
|
setEditingClass(true)
|
||||||
|
startTrackingPanel()
|
||||||
// Which tab is active; pagerite.js uses this to decide whether a pen click
|
// Which tab is active; pagerite.js uses this to decide whether a pen click
|
||||||
// closes the panel or switches tabs.
|
// closes the panel or switches tabs.
|
||||||
document.body.dataset.editorMode = mode
|
document.body.dataset.editorMode = mode
|
||||||
@@ -64,7 +119,8 @@ function showEditor() {
|
|||||||
savedTitle = document.title
|
savedTitle = document.title
|
||||||
host.style.display = ''
|
host.style.display = ''
|
||||||
host.firstElementChild?.classList.remove('closing')
|
host.firstElementChild?.classList.remove('closing')
|
||||||
document.body.classList.add('editing')
|
setEditingClass(true)
|
||||||
|
startTrackingPanel()
|
||||||
visible = true
|
visible = true
|
||||||
dispatchEvent(new CustomEvent('pagerite:editor-shown'))
|
dispatchEvent(new CustomEvent('pagerite:editor-shown'))
|
||||||
}
|
}
|
||||||
@@ -72,7 +128,8 @@ function showEditor() {
|
|||||||
export function closeEditor() {
|
export function closeEditor() {
|
||||||
if (!visible) return
|
if (!visible) return
|
||||||
visible = false
|
visible = false
|
||||||
document.body.classList.remove('editing')
|
stopTrackingPanel()
|
||||||
|
setEditingClass(false)
|
||||||
// dataset.editorMode is kept while hidden: the tabs use it to tell whether
|
// dataset.editorMode is kept while hidden: the tabs use it to tell whether
|
||||||
// a pagerite:editor-shown event targets them.
|
// a pagerite:editor-shown event targets them.
|
||||||
// Slide the panel out in sync with the page shifting back, then hide it.
|
// Slide the panel out in sync with the page shifting back, then hide it.
|
||||||
@@ -80,6 +137,9 @@ export function closeEditor() {
|
|||||||
const h = host
|
const h = host
|
||||||
setTimeout(() => { h.style.display = 'none' }, 250)
|
setTimeout(() => { h.style.display = 'none' }, 250)
|
||||||
dispatchEvent(new CustomEvent('pagerite:editor-hidden'))
|
dispatchEvent(new CustomEvent('pagerite:editor-hidden'))
|
||||||
|
// The editor may have dropped the prefetch cache; warm it again for the
|
||||||
|
// now-final page so navigation stays instant.
|
||||||
|
dispatchEvent(new CustomEvent('pagerite:preload-pages'))
|
||||||
// Restore the server-rendered title for the current URL. Re-fetching makes
|
// Restore the server-rendered title for the current URL. Re-fetching makes
|
||||||
// sure a brand change in the site editor or an in-place navigation leaves
|
// sure a brand change in the site editor or an in-place navigation leaves
|
||||||
// the correct public title behind.
|
// the correct public title behind.
|
||||||
|
|||||||
+157
-74
@@ -53,6 +53,7 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
// pageshow handler below re-probes auth to refresh the pens).
|
// pageshow handler below re-probes auth to refresh the pens).
|
||||||
let ssoAvailable = false;
|
let ssoAvailable = false;
|
||||||
let isAdmin = false;
|
let isAdmin = false;
|
||||||
|
let authReady = false;
|
||||||
let editorMeta = null;
|
let editorMeta = null;
|
||||||
|
|
||||||
// Asset URLs for the on-demand bundles. Dev renders them as
|
// Asset URLs for the on-demand bundles. Dev renders them as
|
||||||
@@ -106,7 +107,19 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function removePens() {
|
||||||
|
document.querySelectorAll(".editor-pens, #main article button.edit-link")
|
||||||
|
.forEach((el) => el.remove());
|
||||||
|
}
|
||||||
|
|
||||||
function renderAuthUi() {
|
function renderAuthUi() {
|
||||||
|
// Always start from a clean slate: if the auth probe is still running we
|
||||||
|
// must not show any admin UI, and if it came back negative we must drop
|
||||||
|
// pens that may have been injected while the browser cache made us look
|
||||||
|
// authenticated.
|
||||||
|
removePens();
|
||||||
|
if (!authReady) return;
|
||||||
|
|
||||||
// Editing is open for admins and, as a dev/no-proxy fallback, when no
|
// Editing is open for admins and, as a dev/no-proxy fallback, when no
|
||||||
// Paskia SSO is detected at all.
|
// Paskia SSO is detected at all.
|
||||||
const canEdit = isAdmin || !ssoAvailable;
|
const canEdit = isAdmin || !ssoAvailable;
|
||||||
@@ -115,8 +128,6 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
const onAnalytics = currentPath === "/_a";
|
const onAnalytics = currentPath === "/_a";
|
||||||
const banner = document.getElementById("page-banner");
|
const banner = document.getElementById("page-banner");
|
||||||
if (banner) {
|
if (banner) {
|
||||||
const old = banner.parentElement.querySelector(".editor-pens");
|
|
||||||
if (old) old.remove();
|
|
||||||
const pens = document.createElement("div");
|
const pens = document.createElement("div");
|
||||||
pens.className = "editor-pens";
|
pens.className = "editor-pens";
|
||||||
if (canEdit && !onAnalytics) {
|
if (canEdit && !onAnalytics) {
|
||||||
@@ -137,8 +148,11 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function setupAuth() {
|
async function setupAuth() {
|
||||||
|
authReady = false;
|
||||||
|
renderAuthUi();
|
||||||
|
|
||||||
const src = assets["pagerite:editor-src"];
|
const src = assets["pagerite:editor-src"];
|
||||||
if (!src) { pingEntryOnce(); return; }
|
if (!src) { authReady = true; renderAuthUi(); pingEntryOnce(); return; }
|
||||||
editorMeta = {
|
editorMeta = {
|
||||||
src,
|
src,
|
||||||
css: assets["pagerite:editor-css"],
|
css: assets["pagerite:editor-css"],
|
||||||
@@ -180,7 +194,9 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
authReady = true;
|
||||||
renderAuthUi();
|
renderAuthUi();
|
||||||
|
placeEditPen();
|
||||||
pingEntryOnce();
|
pingEntryOnce();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,9 +235,26 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
btn.textContent = "copy";
|
btn.textContent = "copy";
|
||||||
btn.addEventListener("click", async () => {
|
btn.addEventListener("click", async () => {
|
||||||
const code = pre.querySelector("code");
|
const code = pre.querySelector("code");
|
||||||
await navigator.clipboard.writeText(
|
const text = (code || pre).textContent.replace(/\n$/, "");
|
||||||
(code || pre).textContent.replace(/\n$/, ""),
|
// navigator.clipboard exists only in secure contexts (https or
|
||||||
);
|
// localhost); viewing over plain http needs the textarea fallback.
|
||||||
|
try {
|
||||||
|
if (navigator.clipboard) {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
} else {
|
||||||
|
const ta = document.createElement("textarea");
|
||||||
|
ta.value = text;
|
||||||
|
ta.style.cssText = "position:fixed;opacity:0";
|
||||||
|
document.body.append(ta);
|
||||||
|
ta.select();
|
||||||
|
document.execCommand("copy");
|
||||||
|
ta.remove();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
btn.textContent = "failed";
|
||||||
|
setTimeout(() => (btn.textContent = "copy"), 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
btn.textContent = "copied";
|
btn.textContent = "copied";
|
||||||
btn.classList.add("copied");
|
btn.classList.add("copied");
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -253,34 +286,40 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
// created page has no pen for commitPending's handover click.
|
// created page has no pen for commitPending's handover click.
|
||||||
renderAuthUi();
|
renderAuthUi();
|
||||||
placeEditPen();
|
placeEditPen();
|
||||||
|
// Preview swaps also wipe the .colseg wrappers (the server render has
|
||||||
|
// none), which would drop the multi-column layout until a full reload;
|
||||||
|
// re-split so columns survive both live editing and closing the editor.
|
||||||
|
const main = document.getElementById("main");
|
||||||
|
if (main) applyMulticol(main);
|
||||||
});
|
});
|
||||||
|
|
||||||
function applyEffects() {
|
|
||||||
(window.requestIdleCallback || setTimeout)(preload);
|
|
||||||
const main = document.getElementById("main");
|
|
||||||
addCopyButtons(main);
|
|
||||||
// Fetch-navigation swaps #main, discarding the article pen and corner
|
|
||||||
// buttons; re-add whichever auth UI is appropriate for this session.
|
|
||||||
renderAuthUi();
|
|
||||||
placeEditPen();
|
|
||||||
fitNav();
|
|
||||||
// Multi-column layout only when there is enough text to justify it.
|
// Multi-column layout only when there is enough text to justify it.
|
||||||
// Split the body into columned segments: h1s, h2s and wide figures are
|
// Split the body into columned segments: h1s, h2s and wide elements are
|
||||||
// full-width separators and never go inside columns.
|
// full-width separators and never go inside columns.
|
||||||
|
function applyMulticol(main) {
|
||||||
const article = main.querySelector("article");
|
const article = main.querySelector("article");
|
||||||
if (article) {
|
if (!article) return;
|
||||||
const body = article.querySelector(".body");
|
const body = article.querySelector(".body");
|
||||||
|
// Code blocks don't read as flowing text and are often generated
|
||||||
|
// filler; exclude them when measuring whether the text justifies
|
||||||
|
// columns.
|
||||||
|
const textLen = (el) => {
|
||||||
|
let n = el.textContent.trim().length;
|
||||||
|
for (const pre of el.querySelectorAll("pre")) n -= pre.textContent.length;
|
||||||
|
return n;
|
||||||
|
};
|
||||||
article.classList.toggle(
|
article.classList.toggle(
|
||||||
"multicol",
|
"multicol",
|
||||||
!!body && body.textContent.trim().length > 1800,
|
!!body && textLen(body) > 1800,
|
||||||
);
|
);
|
||||||
if (body && article.classList.contains("multicol")
|
if (body && article.classList.contains("multicol")
|
||||||
&& !body.querySelector(".colseg")) {
|
&& !body.querySelector(".colseg")) {
|
||||||
// h1s, h2s and anything holding a wide image are full-width
|
// h1s, h2s and wide elements (a {.wide} block or anything holding
|
||||||
// separators
|
// one, e.g. a figure with a wide image) are full-width separators
|
||||||
const isSeparator = (el) =>
|
const isSeparator = (el) =>
|
||||||
el.tagName === "H1" || el.tagName === "H2"
|
el.tagName === "H1" || el.tagName === "H2"
|
||||||
|| el.querySelector("img.wide") !== null;
|
|| el.classList.contains("wide")
|
||||||
|
|| el.querySelector(".wide") !== null;
|
||||||
let seg = null;
|
let seg = null;
|
||||||
for (const el of [...body.children]) {
|
for (const el of [...body.children]) {
|
||||||
if (isSeparator(el)) {
|
if (isSeparator(el)) {
|
||||||
@@ -296,12 +335,27 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Columns are per section: only segments with enough text get them,
|
// Columns are per section: only segments with enough text get them,
|
||||||
// so a short ingress or a brief section stays single-column.
|
// so a short ingress or a brief section stays single-column. A
|
||||||
|
// .nocols container (::: nocols) opts its whole section out.
|
||||||
for (const s of body.querySelectorAll(".colseg")) {
|
for (const s of body.querySelectorAll(".colseg")) {
|
||||||
s.classList.toggle("cols", s.textContent.trim().length > 600);
|
s.classList.toggle(
|
||||||
|
"cols",
|
||||||
|
s.querySelector(".nocols") === null && textLen(s) > 600,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function applyEffects() {
|
||||||
|
(window.requestIdleCallback || setTimeout)(preload);
|
||||||
|
const main = document.getElementById("main");
|
||||||
|
addCopyButtons(main);
|
||||||
|
// Fetch-navigation swaps #main, discarding the article pen and corner
|
||||||
|
// buttons; re-add whichever auth UI is appropriate for this session.
|
||||||
|
renderAuthUi();
|
||||||
|
placeEditPen();
|
||||||
|
fitNav();
|
||||||
|
applyMulticol(main);
|
||||||
if (reduceMotion.matches) return;
|
if (reduceMotion.matches) return;
|
||||||
for (const el of main.querySelectorAll(
|
for (const el of main.querySelectorAll(
|
||||||
"h2, h3, figure, img, pre, blockquote, table, dl, .task-list-item",
|
"h2, h3, figure, img, pre, blockquote, table, dl, .task-list-item",
|
||||||
@@ -328,6 +382,21 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
pageCache.set(new URL(ev.detail.url, location.href).pathname, ev.detail.html);
|
pageCache.set(new URL(ev.detail.url, location.href).pathname, ev.detail.html);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Editors mutate site-wide state (theme, structure, headings, banners),
|
||||||
|
// which can change the rendered HTML of every cached page. Drop the whole
|
||||||
|
// cache so stale prefetches are never served; the current page is re-fetched
|
||||||
|
// by the editor's own loadPlain and re-cached afterwards. Re-preloading is
|
||||||
|
// deferred until the editor panel closes to avoid hammering the server.
|
||||||
|
addEventListener("pagerite:drop-page-cache", () => {
|
||||||
|
pageCache.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
// When the editor panel closes, warm the cache again for the visible links
|
||||||
|
// on the (now final) page so subsequent navigation stays instant.
|
||||||
|
addEventListener("pagerite:preload-pages", () => {
|
||||||
|
preload();
|
||||||
|
});
|
||||||
|
|
||||||
function preload() {
|
function preload() {
|
||||||
const urls = new Set();
|
const urls = new Set();
|
||||||
for (const a of document.querySelectorAll(
|
for (const a of document.querySelectorAll(
|
||||||
@@ -362,55 +431,76 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
// themes for their own effects (e.g. the purple sun rising faster than
|
// themes for their own effects (e.g. the purple sun rising faster than
|
||||||
// the drift). Event-driven only: perfectly still when the page is idle.
|
// the drift). Event-driven only: perfectly still when the page is idle.
|
||||||
if (!reduceMotion.matches) {
|
if (!reduceMotion.matches) {
|
||||||
let ticking = false;
|
// rAF loop that eases the value toward the live scroll position. Reading
|
||||||
|
// scrollY every frame (rather than only on scroll events) also picks up
|
||||||
|
// the in-between positions of Chrome/macOS momentum scrolling, whose
|
||||||
|
// scroll events fire late and coarsely. The loop idles once settled.
|
||||||
|
let value = Math.min(scrollY * 0.1, 30);
|
||||||
|
let running = false;
|
||||||
const drift = () => {
|
const drift = () => {
|
||||||
ticking = false;
|
const target = Math.min(scrollY * 0.1, 30);
|
||||||
document.documentElement.style.setProperty(
|
value += (target - value) * 0.12;
|
||||||
"--pry", `${Math.min(scrollY * 0.1, 30)}px`,
|
if (Math.abs(target - value) < 0.05) {
|
||||||
);
|
value = target;
|
||||||
|
running = false;
|
||||||
|
}
|
||||||
|
document.documentElement.style.setProperty("--pry", `${value}px`);
|
||||||
|
if (running) requestAnimationFrame(drift);
|
||||||
};
|
};
|
||||||
addEventListener("scroll", () => {
|
addEventListener("scroll", () => {
|
||||||
if (!ticking) {
|
if (!running) {
|
||||||
ticking = true;
|
running = true;
|
||||||
requestAnimationFrame(drift);
|
requestAnimationFrame(drift);
|
||||||
}
|
}
|
||||||
}, { passive: true });
|
}, { passive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Analytics pings ---------------------------------------------------
|
// --- Analytics pings ---------------------------------------------------
|
||||||
// Fire-and-forget POST /_a {fr, to, read}: on the initial page load
|
// Fire-and-forget POSTs to /_a with the fields as query parameters (a
|
||||||
// (starts the visit — the server counts nothing from the document GET
|
// beacon can carry no body, and query args show in server logs next to
|
||||||
// alone), for internal fetch-navigations, for external https exits, and
|
// the document GET they refer to): on the initial page load (starts the
|
||||||
// on window close. ``read`` is the active time (ms) spent on ``fr``.
|
// visit — the server counts nothing from the document GET alone), for
|
||||||
|
// internal fetch-navigations, for external https exits, and on window
|
||||||
|
// close. ``read`` is the active time (ms) spent on ``fr``.
|
||||||
// Reading time pauses after 1 minute of inactivity and resumes on the
|
// Reading time pauses after 1 minute of inactivity and resumes on the
|
||||||
// next mouse/touch/scroll/keyboard event.
|
// next mouse/touch/scroll/keyboard event.
|
||||||
// Excluded: back/forward (popstate never pings), everything while the
|
// Excluded: back/forward (popstate never pings), everything while the
|
||||||
// editor is open (body.editing — admin noise, not visits), and the
|
// editor is open (body.editing — admin noise, not visits), and
|
||||||
// analytics page itself (/_a), even though fetch-navigation treats it
|
// navigations TO the analytics page (/_a — admin machinery, and the
|
||||||
// like a normal article.
|
// server rejects it as a ping target anyway). Navigations AWAY from /_a
|
||||||
|
// must ping: load() already fetched the target page without the preload
|
||||||
|
// header, and without the ping that GET would flush to the crawler list.
|
||||||
// Admins (when SSO is actually in use — with no auth proxy "admin" is
|
// Admins (when SSO is actually in use — with no auth proxy "admin" is
|
||||||
// everyone's state) ping normally but with hide=1: the server then
|
// everyone's state) ping normally but with hide=1: the server then
|
||||||
// records nothing and scrubs any session the same browser accumulated
|
// records nothing and scrubs any session the same browser accumulated
|
||||||
// before logging in, so admins never show up as visits or crawlers.
|
// before logging in, so admins never show up as visits or crawlers.
|
||||||
// See docs/analytics.md.
|
// See docs/analytics.md.
|
||||||
function ping(to, fr = currentPath, read = 0) {
|
|
||||||
if (document.body.classList.contains("editing")) return;
|
// fetch wrapper: every key of ``params`` becomes a query arg on /_a
|
||||||
if ((to && to === "/_a") || fr === "/_a") return;
|
// (falsy values are omitted). Admins get hide=1. ``beacon`` uses
|
||||||
const hide = ssoAvailable && isAdmin ? 1 : 0;
|
// sendBeacon when available, for unload-time pings.
|
||||||
const body = JSON.stringify({
|
function pingFetch(params, { beacon = false } = {}) {
|
||||||
fr, to, hide,
|
const query = new URLSearchParams();
|
||||||
read: Math.max(0, Math.round(read / 1000)),
|
if (ssoAvailable && isAdmin) params = { ...params, hide: 1 };
|
||||||
});
|
for (const [key, value] of Object.entries(params)) {
|
||||||
|
if (value) query.set(key, value);
|
||||||
|
}
|
||||||
|
const url = `/_a?${query}`;
|
||||||
try {
|
try {
|
||||||
fetch("/_a", {
|
if (beacon && navigator.sendBeacon) {
|
||||||
method: "POST",
|
navigator.sendBeacon(url);
|
||||||
keepalive: true,
|
} else {
|
||||||
headers: { "content-type": "application/json" },
|
fetch(url, { method: "POST", keepalive: true });
|
||||||
body,
|
}
|
||||||
});
|
|
||||||
} catch { /* analytics must never break navigation */ }
|
} catch { /* analytics must never break navigation */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ping({ to, fr = currentPath, read = 0, beacon = false } = {}) {
|
||||||
|
if (document.body.classList.contains("editing")) return;
|
||||||
|
if (to === "/_a") return;
|
||||||
|
pingFetch({ fr, to, read: Math.round(read / 1000) }, { beacon });
|
||||||
|
}
|
||||||
|
|
||||||
// Active reading time for the current page. The clock stops after 1 minute
|
// Active reading time for the current page. The clock stops after 1 minute
|
||||||
// without activity and restarts on the next mouse/touch/scroll/keyboard
|
// without activity and restarts on the next mouse/touch/scroll/keyboard
|
||||||
// event.
|
// event.
|
||||||
@@ -454,24 +544,10 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
|
|
||||||
function sendClosePing() {
|
function sendClosePing() {
|
||||||
if (closePingedFor === currentPath) return;
|
if (closePingedFor === currentPath) return;
|
||||||
const read = Math.max(0, Math.round(takeReadTime() / 1000));
|
|
||||||
if (read <= 0) return;
|
|
||||||
const hide = ssoAvailable && isAdmin ? 1 : 0;
|
|
||||||
const body = JSON.stringify({ fr: currentPath, hide, read });
|
|
||||||
const blob = new Blob([body], { type: "application/json" });
|
|
||||||
try {
|
|
||||||
if (navigator.sendBeacon) {
|
|
||||||
navigator.sendBeacon("/_a", blob);
|
|
||||||
} else {
|
|
||||||
fetch("/_a", {
|
|
||||||
method: "POST",
|
|
||||||
keepalive: true,
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch { /* analytics must never break navigation */ }
|
|
||||||
closePingedFor = currentPath;
|
closePingedFor = currentPath;
|
||||||
|
const read = takeReadTime();
|
||||||
|
if (Math.round(read / 1000) <= 0) return;
|
||||||
|
ping({ read, beacon: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const ev of ["mousemove", "mousedown", "touchstart", "touchmove", "scroll", "keydown"]) {
|
for (const ev of ["mousemove", "mousedown", "touchstart", "touchmove", "scroll", "keydown"]) {
|
||||||
@@ -481,6 +557,10 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
|
|
||||||
// The initial page load pings too — it is what starts the visit and
|
// The initial page load pings too — it is what starts the visit and
|
||||||
// counts the entry page view (the document GET alone records nothing).
|
// counts the entry page view (the document GET alone records nothing).
|
||||||
|
// It carries only ``to``: the server attributes the entry to the referer
|
||||||
|
// it saw on the document GET (unavailable to JS once loaded), and an
|
||||||
|
// ``fr`` equal to ``to`` would log a bogus self-transition when a
|
||||||
|
// session already exists (e.g. a second tab).
|
||||||
// Sent once per load, after the auth probes so the admin gate applies;
|
// Sent once per load, after the auth probes so the admin gate applies;
|
||||||
// the pageshow re-probe must not ping again. Reloads are not visits:
|
// the pageshow re-probe must not ping again. Reloads are not visits:
|
||||||
// pinging them would double-count the view and log a self-transition.
|
// pinging them would double-count the view and log a self-transition.
|
||||||
@@ -490,7 +570,7 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
entryPinged = true;
|
entryPinged = true;
|
||||||
const nav = performance.getEntriesByType?.("navigation")[0];
|
const nav = performance.getEntriesByType?.("navigation")[0];
|
||||||
if (nav ? nav.type === "reload" : performance.navigation?.type === 1) return;
|
if (nav ? nav.type === "reload" : performance.navigation?.type === 1) return;
|
||||||
ping(currentPath);
|
ping({ to: currentPath, fr: "" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Analytics page mount/unmount --------------------------------------
|
// --- Analytics page mount/unmount --------------------------------------
|
||||||
@@ -536,14 +616,17 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
// --- Fetch navigation ------------------------------------------------
|
// --- Fetch navigation ------------------------------------------------
|
||||||
async function load(url, push = true, back = false) {
|
async function load(url, push = true, back = false) {
|
||||||
// Navigating with the editor open closes it; unsaved edits are lost
|
// Navigating with the editor open closes it; unsaved edits are lost
|
||||||
// (the region swap discards the previewed changes anyway).
|
// (the region swap discards the previewed changes anyway). Cache must be
|
||||||
if (document.body.classList.contains("editing")) {
|
// bypassed for this navigation because the editor may have invalidated
|
||||||
|
// the prefetched copies of other pages.
|
||||||
|
const editing = document.body.classList.contains("editing");
|
||||||
|
if (editing) {
|
||||||
editorModule?.then((m) => m.closeEditor());
|
editorModule?.then((m) => m.closeEditor());
|
||||||
}
|
}
|
||||||
teardownAnalytics();
|
teardownAnalytics();
|
||||||
let doc;
|
let doc;
|
||||||
let finalUrl = url;
|
let finalUrl = url;
|
||||||
const cached = pageCache.get(new URL(url, location.href).pathname);
|
const cached = !editing && pageCache.get(new URL(url, location.href).pathname);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
doc = new DOMParser().parseFromString(cached, "text/html");
|
doc = new DOMParser().parseFromString(cached, "text/html");
|
||||||
} else {
|
} else {
|
||||||
@@ -688,7 +771,7 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
// different links to the same domain stay distinct in analytics.
|
// different links to the same domain stay distinct in analytics.
|
||||||
if (url.protocol === "https:") {
|
if (url.protocol === "https:") {
|
||||||
closePingedFor = currentPath;
|
closePingedFor = currentPath;
|
||||||
ping(url.href, currentPath, takeReadTime());
|
ping({ to: url.href, read: takeReadTime() });
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -704,7 +787,7 @@ import "overlayscrollbars/overlayscrollbars.css";
|
|||||||
load(url).then((ok) => {
|
load(url).then((ok) => {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
closePingedFor = null;
|
closePingedFor = null;
|
||||||
ping(url.pathname, from, takeReadTime());
|
ping({ to: url.pathname, fr: from, read: takeReadTime() });
|
||||||
resetReadTime();
|
resetReadTime();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,14 @@
|
|||||||
// Used by BannerEditor (banner design changes), SiteEditor (theme changes)
|
// Used by BannerEditor (banner design changes), SiteEditor (theme changes)
|
||||||
// and StructureEditor (tree navigation).
|
// and StructureEditor (tree navigation).
|
||||||
|
|
||||||
|
// Drop the public page runtime's in-memory prefetch cache. Editors call this
|
||||||
|
// whenever a site-wide or page change invalidates the cached HTML of other
|
||||||
|
// pages (theme, headings, structure, banner, etc.). The cache is rebuilt by
|
||||||
|
// re-preloading visible links once the editor panel closes.
|
||||||
|
export function dropPageCache() {
|
||||||
|
dispatchEvent(new CustomEvent('pagerite:drop-page-cache'))
|
||||||
|
}
|
||||||
|
|
||||||
export function runScripts(root) {
|
export function runScripts(root) {
|
||||||
// Scripts injected via innerHTML do not execute; re-create them.
|
// Scripts injected via innerHTML do not execute; re-create them.
|
||||||
if (!root) return
|
if (!root) return
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ def main() -> None:
|
|||||||
"pagerite.app:app",
|
"pagerite.app:app",
|
||||||
listen=args.listen,
|
listen=args.listen,
|
||||||
default_port=DEFAULT_PORT,
|
default_port=DEFAULT_PORT,
|
||||||
|
server_header=False,
|
||||||
**dev,
|
**dev,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+167
-83
@@ -12,8 +12,13 @@ away (``_is_bot_ua``) and their pings are ignored, so they land in the
|
|||||||
crawler list too. Idle-time link preloads from pagerite.js carry an
|
crawler list too. Idle-time link preloads from pagerite.js carry an
|
||||||
``x-pagerite-preload`` header and are not tracked at all — the ping sent
|
``x-pagerite-preload`` header and are not tracked at all — the ping sent
|
||||||
when the user actually navigates does the counting.
|
when the user actually navigates does the counting.
|
||||||
Admin clients ping with ``hide=1``, which records nothing and removes any
|
Admin clients ping with ``hide=1``: the client record is flagged ``hide``,
|
||||||
visit the session accumulated before logging in. Scanner telltale 404s
|
which covers everything that client ever did — visits and crawler hits
|
||||||
|
from before the login included. Aggregates (site visits, page views,
|
||||||
|
transitions) are not stored; they are computed at display time from the
|
||||||
|
visit records, excluding hidden clients, and hidden clients' visits,
|
||||||
|
crawler hits, abuse hits and metadata are left out of the viewer payload
|
||||||
|
entirely. Scanner telltale 404s
|
||||||
(dotpaths, *.php) classify the source IP as abuse; its hits — including
|
(dotpaths, *.php) classify the source IP as abuse; its hits — including
|
||||||
earlier crawler hits — are moved to the abuse list, which the viewer
|
earlier crawler hits — are moved to the abuse list, which the viewer
|
||||||
groups by IP with full request paths. Client metadata (IP, UA, language,
|
groups by IP with full request paths. Client metadata (IP, UA, language,
|
||||||
@@ -87,15 +92,47 @@ class Client(msgspec.Struct, omit_defaults=True):
|
|||||||
ua: str = ""
|
ua: str = ""
|
||||||
#: Compact display form of ``ua`` (browser/OS/device) when parsable.
|
#: Compact display form of ``ua`` (browser/OS/device) when parsable.
|
||||||
ua_pretty: str = ""
|
ua_pretty: str = ""
|
||||||
|
#: True for admin clients (hide=1 ping): their visits, crawler hits and
|
||||||
|
#: abuse hits are recorded but excluded from all statistics and from
|
||||||
|
#: the viewer payload.
|
||||||
|
hide: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class Nav(msgspec.Struct, omit_defaults=True):
|
||||||
|
"""One navigation inside a visit: from ``fr`` to ``to``.
|
||||||
|
|
||||||
|
``to`` is an internal page path or an external https exit URL. Every
|
||||||
|
navigation is logged (repeats included), keyed by its timestamp in
|
||||||
|
``Visit.navs``, so display-time aggregates can count views and
|
||||||
|
transitions; ``Visit.trail`` keeps the first-seen order.
|
||||||
|
"""
|
||||||
|
|
||||||
|
fr: str
|
||||||
|
to: str
|
||||||
|
|
||||||
|
|
||||||
|
class TrailItem(msgspec.Struct, omit_defaults=True):
|
||||||
|
"""One first-seen target in a visit trail: a page or external exit URL.
|
||||||
|
|
||||||
|
``read`` accumulates active reading time (seconds) across the whole
|
||||||
|
visit; ``status`` is the most recent HTTP status seen for the target.
|
||||||
|
"""
|
||||||
|
|
||||||
|
to: str
|
||||||
|
#: Accumulated active reading time in seconds.
|
||||||
|
read: int = 0
|
||||||
|
#: Most recent HTTP status of the response (200 or 404).
|
||||||
|
status: int = 200
|
||||||
|
|
||||||
|
|
||||||
class Visit(msgspec.Struct, omit_defaults=True):
|
class Visit(msgspec.Struct, omit_defaults=True):
|
||||||
"""One visit: the initial-load data plus everything seen afterwards.
|
"""One visit: the initial-load data plus everything seen afterwards.
|
||||||
|
|
||||||
``trail`` holds page paths and external exit URLs in first-seen
|
``trail`` holds the entry page and everything seen afterwards, keyed by
|
||||||
order; re-visiting an already seen page does not append. The entry
|
the timestamp of first sight (insertion order = first-seen order);
|
||||||
page itself is in ``entry``, not in the trail. Client metadata is
|
re-visiting an already seen target updates its item instead of
|
||||||
held in ``Analytics.clients`` keyed by ``client``.
|
appending. Client metadata is held in ``Analytics.clients`` keyed by
|
||||||
|
``client``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
start: datetime
|
start: datetime
|
||||||
@@ -104,11 +141,13 @@ class Visit(msgspec.Struct, omit_defaults=True):
|
|||||||
referer: str = ""
|
referer: str = ""
|
||||||
#: 6-byte blake3 hash referencing ``Analytics.clients``.
|
#: 6-byte blake3 hash referencing ``Analytics.clients``.
|
||||||
client: bytes = b""
|
client: bytes = b""
|
||||||
trail: list[str] = []
|
#: First-seen targets keyed by their timestamp (entry included).
|
||||||
|
trail: dict[datetime, TrailItem] = {}
|
||||||
|
#: Every navigation ping (repeats included) keyed by its timestamp; the
|
||||||
|
#: aggregates are computed from this log at display time.
|
||||||
|
navs: dict[datetime, Nav] = {}
|
||||||
#: UTM query parameters from the landing URL, keyed by parameter name.
|
#: UTM query parameters from the landing URL, keyed by parameter name.
|
||||||
utm: dict[str, str] = {}
|
utm: dict[str, str] = {}
|
||||||
#: Active reading time per path (seconds), keyed by path.
|
|
||||||
read: dict[str, int] = {}
|
|
||||||
|
|
||||||
|
|
||||||
class CrawlerHit(msgspec.Struct, omit_defaults=True):
|
class CrawlerHit(msgspec.Struct, omit_defaults=True):
|
||||||
@@ -125,6 +164,8 @@ class CrawlerHit(msgspec.Struct, omit_defaults=True):
|
|||||||
referer: str = ""
|
referer: str = ""
|
||||||
#: Raw query string of the landing URL (UTM tags can be parsed from it).
|
#: Raw query string of the landing URL (UTM tags can be parsed from it).
|
||||||
query: str = ""
|
query: str = ""
|
||||||
|
#: HTTP status of the served response (200 or 404 for content pages).
|
||||||
|
status: int = 200
|
||||||
|
|
||||||
|
|
||||||
class AbuseHit(msgspec.Struct, omit_defaults=True):
|
class AbuseHit(msgspec.Struct, omit_defaults=True):
|
||||||
@@ -162,6 +203,22 @@ class Analytics(msgspec.Struct, omit_defaults=True):
|
|||||||
clients: dict[bytes, Client] = {}
|
clients: dict[bytes, Client] = {}
|
||||||
#: IPs classified as scanners/abusers (keys; values always True).
|
#: IPs classified as scanners/abusers (keys; values always True).
|
||||||
abuse_ips: dict[str, bool] = {}
|
abuse_ips: dict[str, bool] = {}
|
||||||
|
|
||||||
|
|
||||||
|
class Display(msgspec.Struct, omit_defaults=True):
|
||||||
|
"""The viewer payload: visible data plus display-time aggregates.
|
||||||
|
|
||||||
|
Hidden clients are excluded everywhere: their visits, crawler hits,
|
||||||
|
abuse hits and metadata are dropped, and the aggregates are computed
|
||||||
|
from the visible visits only.
|
||||||
|
The aggregate shapes match what the viewer consumes: sparse 5-minute
|
||||||
|
buckets keyed by their floored ISO timestamp.
|
||||||
|
"""
|
||||||
|
|
||||||
|
visits: list[Visit] = []
|
||||||
|
crawlers: list[CrawlerHit] = []
|
||||||
|
abuse: list[AbuseHit] = []
|
||||||
|
clients: dict[bytes, Client] = {}
|
||||||
#: Page transitions per 5-minute bucket (sparse):
|
#: Page transitions per 5-minute bucket (sparse):
|
||||||
#: from -> to -> bucket ISO -> count. ``from`` is the referer origin or
|
#: from -> to -> bucket ISO -> count. ``from`` is the referer origin or
|
||||||
#: "(direct)" for initial loads, a page path for pings.
|
#: "(direct)" for initial loads, a page path for pings.
|
||||||
@@ -246,15 +303,15 @@ def _utm_tags(query: str) -> dict[str, str]:
|
|||||||
_CRAWLER_TIMEOUT = timedelta(seconds=10)
|
_CRAWLER_TIMEOUT = timedelta(seconds=10)
|
||||||
|
|
||||||
#: UAs of JS-running crawlers, which would register as visitors on their
|
#: UAs of JS-running crawlers, which would register as visitors on their
|
||||||
#: ping. Anything calling itself a "bot" matches; known crawlers without
|
#: ping. Anything calling itself a "bot" or "spider" matches; known crawlers
|
||||||
#: that token (GoogleOther) are listed as extra alternates. No source
|
#: without those tokens (GoogleOther) are listed as extra alternates. No
|
||||||
#: verification: a spoofed bot UA just lands in the crawler list, and
|
#: source verification: a spoofed bot UA just lands in the crawler list, and
|
||||||
#: scanners that probe telltale paths are caught by the abuse rules anyway.
|
#: scanners that probe telltale paths are caught by the abuse rules anyway.
|
||||||
_BOT_UA = re.compile(r"bot|googleother", re.IGNORECASE)
|
_BOT_UA = re.compile(r"bot|spider|googleother", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
def _is_bot_ua(ua: str) -> bool:
|
def _is_bot_ua(ua: str) -> bool:
|
||||||
"""True when the UA claims a crawler identity (Googlebot, Applebot, ...)."""
|
"""True when the UA claims a crawler identity (bot or spider)."""
|
||||||
return bool(_BOT_UA.search(ua))
|
return bool(_BOT_UA.search(ua))
|
||||||
|
|
||||||
#: Plain-404 count per IP that classifies it as abuse even without a
|
#: Plain-404 count per IP that classifies it as abuse even without a
|
||||||
@@ -324,6 +381,9 @@ class Store:
|
|||||||
#: Document GETs that have not yet been matched by a ping. Kept
|
#: Document GETs that have not yet been matched by a ping. Kept
|
||||||
#: in RAM only; expired entries are written to ``data.crawlers``.
|
#: in RAM only; expired entries are written to ``data.crawlers``.
|
||||||
self.pending_crawlers: list[CrawlerHit] = []
|
self.pending_crawlers: list[CrawlerHit] = []
|
||||||
|
#: client hash -> {path: status} for recent document GETs, consumed
|
||||||
|
#: by the matching ping to record the status of each visited path.
|
||||||
|
self.pending_statuses: dict[bytes, dict[str, int]] = {}
|
||||||
#: ip -> number of plain (non-telltale) 404s seen, in RAM only;
|
#: ip -> number of plain (non-telltale) 404s seen, in RAM only;
|
||||||
#: reaching ``_ABUSE_404_THRESHOLD`` classifies the IP as abuse.
|
#: reaching ``_ABUSE_404_THRESHOLD`` classifies the IP as abuse.
|
||||||
self.not_found_counts: dict[str, int] = {}
|
self.not_found_counts: dict[str, int] = {}
|
||||||
@@ -362,6 +422,9 @@ class Store:
|
|||||||
def _flush_crawlers(self, now: datetime | None = None) -> list[bytes]:
|
def _flush_crawlers(self, now: datetime | None = None) -> list[bytes]:
|
||||||
"""Move expired pending crawler hits into persistent ``data.crawlers``.
|
"""Move expired pending crawler hits into persistent ``data.crawlers``.
|
||||||
|
|
||||||
|
Hits from a hidden client (admin) are discarded instead of
|
||||||
|
persisted — admin browsing must not land in the crawler list.
|
||||||
|
|
||||||
Returns the client hashes of the newly flushed hits so callers can
|
Returns the client hashes of the newly flushed hits so callers can
|
||||||
schedule async enrichment.
|
schedule async enrichment.
|
||||||
"""
|
"""
|
||||||
@@ -372,59 +435,63 @@ class Store:
|
|||||||
expired: list[CrawlerHit] = []
|
expired: list[CrawlerHit] = []
|
||||||
remaining: list[CrawlerHit] = []
|
remaining: list[CrawlerHit] = []
|
||||||
for hit in self.pending_crawlers:
|
for hit in self.pending_crawlers:
|
||||||
(expired if hit.start <= cutoff else remaining).append(hit)
|
if hit.start > cutoff:
|
||||||
|
remaining.append(hit)
|
||||||
|
continue
|
||||||
|
client = self.data.clients.get(hit.client)
|
||||||
|
if client is not None and client.hide:
|
||||||
|
continue # hidden admin client: not a crawler
|
||||||
|
expired.append(hit)
|
||||||
if not expired:
|
if not expired:
|
||||||
|
self.pending_crawlers = remaining
|
||||||
return []
|
return []
|
||||||
self.pending_crawlers = remaining
|
self.pending_crawlers = remaining
|
||||||
self.data.crawlers.extend(expired)
|
self.data.crawlers.extend(expired)
|
||||||
self._save()
|
self._save()
|
||||||
return [hit.client for hit in expired]
|
return [hit.client for hit in expired]
|
||||||
|
|
||||||
def _count(self, table: dict[str, int], key: str) -> None:
|
def _hidden(self, client_hash: bytes) -> bool:
|
||||||
table[key] = table.get(key, 0) + 1
|
"""True when the client record is flagged hidden (admin)."""
|
||||||
|
client = self.data.clients.get(client_hash)
|
||||||
|
return client is not None and client.hide
|
||||||
|
|
||||||
def _count_transition(self, fr: str, to: str, now: datetime) -> None:
|
def display(self) -> Display:
|
||||||
"""Count one transition in its 5-minute bucket (sparse matrix)."""
|
"""Build the viewer payload, excluding hidden clients.
|
||||||
buckets = self.data.transitions.setdefault(fr, {}).setdefault(to, {})
|
|
||||||
self._count(buckets, _bucket(now))
|
|
||||||
|
|
||||||
def _uncount(self, table: dict[str, int], key: str) -> None:
|
The aggregates (site visits, page views, transitions) are computed
|
||||||
"""Reverse one ``_count``: decrement and drop empty keys."""
|
here from the visit records rather than stored, so a client that
|
||||||
if key in table:
|
becomes hidden after navigations were already logged disappears
|
||||||
table[key] -= 1
|
from every statistic. Internal-path navigations count as page
|
||||||
if table[key] <= 0:
|
views; external https targets are transitions only.
|
||||||
del table[key]
|
|
||||||
|
|
||||||
def _remove_visit(self, index: int) -> None:
|
|
||||||
"""Delete a visit and reverse the counts its creation recorded.
|
|
||||||
|
|
||||||
Used when a known visitor turns out to be an admin (hide=1 ping):
|
|
||||||
the session is scrubbed from the stats. Views/transitions logged
|
|
||||||
by later pings inside the visit lack per-event timestamps and are
|
|
||||||
left as-is.
|
|
||||||
"""
|
"""
|
||||||
visit = self.data.visits[index]
|
visits = [v for v in self.data.visits if not self._hidden(v.client)]
|
||||||
|
display = Display(
|
||||||
|
visits=visits,
|
||||||
|
crawlers=[h for h in self.data.crawlers if not self._hidden(h.client)],
|
||||||
|
abuse=[h for h in self.data.abuse if not self._hidden(h.client)],
|
||||||
|
clients={h: c for h, c in self.data.clients.items() if not c.hide},
|
||||||
|
)
|
||||||
|
for visit in visits:
|
||||||
bucket = _bucket(visit.start)
|
bucket = _bucket(visit.start)
|
||||||
self._uncount(self.data.site_visits, bucket)
|
site = display.site_visits
|
||||||
views = self.data.views.get(visit.entry)
|
site[bucket] = site.get(bucket, 0) + 1
|
||||||
if views is not None:
|
entry_views = display.views.setdefault(visit.entry, {})
|
||||||
self._uncount(views, bucket)
|
entry_views[bucket] = entry_views.get(bucket, 0) + 1
|
||||||
if not views:
|
fr = visit.referer or "(direct)"
|
||||||
del self.data.views[visit.entry]
|
buckets = display.transitions.setdefault(fr, {}).setdefault(visit.entry, {})
|
||||||
fr_map = self.data.transitions.get(visit.referer or "(direct)")
|
buckets[bucket] = buckets.get(bucket, 0) + 1
|
||||||
if fr_map is not None:
|
for t, nav in visit.navs.items():
|
||||||
buckets = fr_map.get(visit.entry)
|
nb = _bucket(t)
|
||||||
if buckets is not None:
|
if nav.to.startswith("/"):
|
||||||
self._uncount(buckets, bucket)
|
nav_views = display.views.setdefault(nav.to, {})
|
||||||
if not buckets:
|
nav_views[nb] = nav_views.get(nb, 0) + 1
|
||||||
del fr_map[visit.entry]
|
nbuckets = display.transitions.setdefault(nav.fr, {}).setdefault(nav.to, {})
|
||||||
if not fr_map:
|
nbuckets[nb] = nbuckets.get(nb, 0) + 1
|
||||||
del self.data.transitions[visit.referer or "(direct)"]
|
return display
|
||||||
del self.data.visits[index]
|
|
||||||
# Sessions store list indices; shift the ones past the removed visit.
|
def display_json(self) -> str:
|
||||||
for key, i in list(self.sessions.items()):
|
"""The ``display()`` payload as a JSON string for the WebSocket."""
|
||||||
if i > index:
|
return msgspec.json.encode(self.display()).decode()
|
||||||
self.sessions[key] = i - 1
|
|
||||||
|
|
||||||
def _client_ip(self, client_hash: bytes) -> str:
|
def _client_ip(self, client_hash: bytes) -> str:
|
||||||
"""Return the IP stored for ``client_hash``, or "" if missing."""
|
"""Return the IP stored for ``client_hash``, or "" if missing."""
|
||||||
@@ -571,6 +638,7 @@ class Store:
|
|||||||
referer: str,
|
referer: str,
|
||||||
client_hash: bytes,
|
client_hash: bytes,
|
||||||
utm: dict[str, str] | None = None,
|
utm: dict[str, str] | None = None,
|
||||||
|
status: int = 200,
|
||||||
) -> Visit:
|
) -> Visit:
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
visit = Visit(
|
visit = Visit(
|
||||||
@@ -580,11 +648,9 @@ class Store:
|
|||||||
client=client_hash,
|
client=client_hash,
|
||||||
utm=utm or {},
|
utm=utm or {},
|
||||||
)
|
)
|
||||||
|
visit.trail[now] = TrailItem(to=entry, status=status)
|
||||||
self.data.visits.append(visit)
|
self.data.visits.append(visit)
|
||||||
self.sessions[client_hash] = len(self.data.visits) - 1
|
self.sessions[client_hash] = len(self.data.visits) - 1
|
||||||
self._count(self.data.site_visits, _bucket(now))
|
|
||||||
self._count(self.data.views.setdefault(entry, {}), _bucket(now))
|
|
||||||
self._count_transition(referer or "(direct)", entry, now)
|
|
||||||
return visit
|
return visit
|
||||||
|
|
||||||
def track_entry(
|
def track_entry(
|
||||||
@@ -595,6 +661,8 @@ class Store:
|
|||||||
ua: str,
|
ua: str,
|
||||||
full_path: str,
|
full_path: str,
|
||||||
accept_language: str = "",
|
accept_language: str = "",
|
||||||
|
*,
|
||||||
|
status: int = 200,
|
||||||
) -> list[bytes]:
|
) -> list[bytes]:
|
||||||
"""Stash the entry referer/UTM tags and queue a pending crawler hit.
|
"""Stash the entry referer/UTM tags and queue a pending crawler hit.
|
||||||
|
|
||||||
@@ -642,8 +710,10 @@ class Store:
|
|||||||
client=client_hash,
|
client=client_hash,
|
||||||
referer=self.pending_referers.get(ip, ""),
|
referer=self.pending_referers.get(ip, ""),
|
||||||
query=query,
|
query=query,
|
||||||
|
status=status,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
self.pending_statuses.setdefault(client_hash, {})[entry] = status
|
||||||
return flushed
|
return flushed
|
||||||
|
|
||||||
def _add_read(self, client_hash: bytes, path: str, seconds: int) -> None:
|
def _add_read(self, client_hash: bytes, path: str, seconds: int) -> None:
|
||||||
@@ -654,7 +724,10 @@ class Store:
|
|||||||
if index is None or index >= len(self.data.visits):
|
if index is None or index >= len(self.data.visits):
|
||||||
return
|
return
|
||||||
visit = self.data.visits[index]
|
visit = self.data.visits[index]
|
||||||
visit.read[path] = visit.read.get(path, 0) + seconds
|
for item in visit.trail.values():
|
||||||
|
if item.to == path:
|
||||||
|
item.read += seconds
|
||||||
|
return
|
||||||
|
|
||||||
def ping(
|
def ping(
|
||||||
self,
|
self,
|
||||||
@@ -677,10 +750,11 @@ class Store:
|
|||||||
A ping with no known session starts a fresh visit, consuming the
|
A ping with no known session starts a fresh visit, consuming the
|
||||||
referer and UTM tags stashed by the document GET if there are any.
|
referer and UTM tags stashed by the document GET if there are any.
|
||||||
|
|
||||||
``hide`` is set by admin clients: the ping cancels pending crawler
|
``hide`` is set by admin clients: the client record is flagged
|
||||||
hits as usual, and any existing visit for this client session is
|
``hide`` — which covers everything it ever did, including visits and
|
||||||
removed from the stats (the admin browsed anonymously before logging
|
crawler hits from before the login — and the navigation is recorded
|
||||||
in). Nothing new is recorded.
|
normally. Hidden clients are excluded from every statistic and list
|
||||||
|
at display time, and their pending crawler hits are discarded.
|
||||||
|
|
||||||
Pings from IPs classified as abuse, and pings whose User-Agent
|
Pings from IPs classified as abuse, and pings whose User-Agent
|
||||||
claims a JS-running crawler identity (``_is_bot_ua``), are ignored
|
claims a JS-running crawler identity (``_is_bot_ua``), are ignored
|
||||||
@@ -693,25 +767,27 @@ class Store:
|
|||||||
"""
|
"""
|
||||||
flushed = self._flush_crawlers()
|
flushed = self._flush_crawlers()
|
||||||
lang, country = _parse_accept_language(accept_language)
|
lang, country = _parse_accept_language(accept_language)
|
||||||
client_hash = _client_hash(ip, ua, lang)
|
|
||||||
if hide:
|
if hide:
|
||||||
# Admin ping: cancel pending crawler hits and scrub the session.
|
# Admin ping: flag the client hidden and never a crawler hit.
|
||||||
|
# The flag lives on the client record, so it covers visits and
|
||||||
|
# crawler hits from before the login too; display-time
|
||||||
|
# aggregation excludes hidden clients from every statistic.
|
||||||
|
client_hash = self._ensure_client(ip, ua, lang, country=country)
|
||||||
|
self.data.clients[client_hash].hide = True
|
||||||
self.pending_crawlers = [
|
self.pending_crawlers = [
|
||||||
hit for hit in self.pending_crawlers if hit.client == client_hash
|
hit for hit in self.pending_crawlers if hit.client != client_hash
|
||||||
]
|
]
|
||||||
index = self.sessions.pop(client_hash, None)
|
else:
|
||||||
if index is not None and index < len(self.data.visits):
|
client_hash = _client_hash(ip, ua, lang)
|
||||||
self._remove_visit(index)
|
|
||||||
self._save()
|
|
||||||
return None, flushed
|
|
||||||
if ip in self.data.abuse_ips:
|
if ip in self.data.abuse_ips:
|
||||||
return None, flushed
|
return None, flushed
|
||||||
if _is_bot_ua(ua):
|
if _is_bot_ua(ua):
|
||||||
# A JS-running crawler (Googlebot, GoogleOther, Applebot execute
|
# A JS-running crawler (Googlebot, GoogleOther, Applebot
|
||||||
# JS and ping): never a visit. Its pending crawler hits are
|
# execute JS and ping): never a visit. Its pending crawler
|
||||||
# kept and flush to ``data.crawlers`` normally.
|
# hits are kept and flush to ``data.crawlers`` normally.
|
||||||
return None, flushed
|
return None, flushed
|
||||||
# A real visitor ping cancels any pending crawler hits from this client.
|
# A real visitor ping cancels any pending crawler hits from
|
||||||
|
# this client.
|
||||||
self.pending_crawlers = [
|
self.pending_crawlers = [
|
||||||
hit for hit in self.pending_crawlers if hit.client != client_hash
|
hit for hit in self.pending_crawlers if hit.client != client_hash
|
||||||
]
|
]
|
||||||
@@ -719,7 +795,7 @@ class Store:
|
|||||||
if fr_path and read > 0:
|
if fr_path and read > 0:
|
||||||
self._add_read(client_hash, fr_path, read)
|
self._add_read(client_hash, fr_path, read)
|
||||||
if not to:
|
if not to:
|
||||||
if read > 0:
|
if read > 0 or hide:
|
||||||
self._save()
|
self._save()
|
||||||
return None, flushed
|
return None, flushed
|
||||||
if to.startswith("/") and not to.startswith("//"):
|
if to.startswith("/") and not to.startswith("//"):
|
||||||
@@ -730,6 +806,10 @@ class Store:
|
|||||||
return None, flushed
|
return None, flushed
|
||||||
index = self.sessions.get(client_hash)
|
index = self.sessions.get(client_hash)
|
||||||
fr = fr_path or "(direct)"
|
fr = fr_path or "(direct)"
|
||||||
|
statuses = self.pending_statuses.setdefault(client_hash, {})
|
||||||
|
target_status = statuses.pop(target, None) or 200
|
||||||
|
if not statuses:
|
||||||
|
self.pending_statuses.pop(client_hash, None)
|
||||||
if index is None or index >= len(self.data.visits):
|
if index is None or index >= len(self.data.visits):
|
||||||
# No known session: the initial ping of a fresh page load (or
|
# No known session: the initial ping of a fresh page load (or
|
||||||
# missing data after a server restart) — start a visit.
|
# missing data after a server restart) — start a visit.
|
||||||
@@ -740,16 +820,20 @@ class Store:
|
|||||||
self.pending_referers.pop(ip, ""),
|
self.pending_referers.pop(ip, ""),
|
||||||
client_hash,
|
client_hash,
|
||||||
utm=self.pending_utms.pop(ip, {}),
|
utm=self.pending_utms.pop(ip, {}),
|
||||||
|
status=target_status,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
visit = self.data.visits[index]
|
visit = self.data.visits[index]
|
||||||
now = datetime.now(UTC)
|
now = datetime.now(UTC)
|
||||||
if target.startswith("/"):
|
visit.navs[now] = Nav(fr=fr, to=target)
|
||||||
self._count(self.data.views.setdefault(target, {}), _bucket(now))
|
# First-seen only: repeat pages and repeated exits update the
|
||||||
self._count_transition(fr, target, now)
|
# existing trail item (most recent status) instead of appending.
|
||||||
# First-seen only: repeat pages and repeated exits don't append.
|
for item in visit.trail.values():
|
||||||
if visit.entry != target and target not in visit.trail:
|
if item.to == target:
|
||||||
visit.trail.append(target)
|
item.status = target_status
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
visit.trail[now] = TrailItem(to=target, status=target_status)
|
||||||
self._save()
|
self._save()
|
||||||
visit_index = index if index is not None and index < len(self.data.visits) else None
|
visit_index = index if index is not None and index < len(self.data.visits) else None
|
||||||
return visit_index, flushed
|
return visit_index, flushed
|
||||||
|
|||||||
+32
-24
@@ -31,7 +31,14 @@ from xml.sax.saxutils import escape as xml_escape
|
|||||||
|
|
||||||
import blake3
|
import blake3
|
||||||
import msgspec
|
import msgspec
|
||||||
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
|
from fastapi import (
|
||||||
|
FastAPI,
|
||||||
|
HTTPException,
|
||||||
|
Query,
|
||||||
|
Request,
|
||||||
|
WebSocket,
|
||||||
|
WebSocketDisconnect,
|
||||||
|
)
|
||||||
from fastapi.responses import RedirectResponse, Response
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from fastapi_vue import Frontend
|
from fastapi_vue import Frontend
|
||||||
from kanta import Kanta
|
from kanta import Kanta
|
||||||
@@ -775,7 +782,7 @@ async def _broadcast_analytics() -> None:
|
|||||||
"""Send the current analytics snapshot to every connected WS client."""
|
"""Send the current analytics snapshot to every connected WS client."""
|
||||||
if not _analytics_ws_clients:
|
if not _analytics_ws_clients:
|
||||||
return
|
return
|
||||||
payload = msgspec.json.encode(analytics_store.data).decode()
|
payload = analytics_store.display_json()
|
||||||
closed = set()
|
closed = set()
|
||||||
for ws in _analytics_ws_clients:
|
for ws in _analytics_ws_clients:
|
||||||
try:
|
try:
|
||||||
@@ -802,17 +809,6 @@ def _schedule_analytics_broadcast() -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class AnalyticsPing(BaseModel):
|
|
||||||
"""Navigation ping from pagerite.js (see docs/analytics.md)."""
|
|
||||||
|
|
||||||
fr: str = ""
|
|
||||||
to: str | None = None
|
|
||||||
#: 1 from admin clients: scrub the session instead of recording it.
|
|
||||||
hide: int = 0
|
|
||||||
#: Active reading time on ``fr`` (ms), if any.
|
|
||||||
read: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/_a", response_model=None)
|
@app.get("/_a", response_model=None)
|
||||||
async def analytics_page(request: Request) -> Response:
|
async def analytics_page(request: Request) -> Response:
|
||||||
"""Render the analytics viewer as a normal site page at /_a.
|
"""Render the analytics viewer as a normal site page at /_a.
|
||||||
@@ -831,21 +827,31 @@ async def analytics_page(request: Request) -> Response:
|
|||||||
|
|
||||||
|
|
||||||
@app.post("/_a", status_code=204)
|
@app.post("/_a", status_code=204)
|
||||||
async def analytics_ping(ping: AnalyticsPing, request: Request) -> None:
|
async def analytics_ping(
|
||||||
"""Record a navigation ping ({fr, to}); fire-and-forget, never fails.
|
request: Request,
|
||||||
|
fr: str = Query(""),
|
||||||
|
to: str | None = Query(None),
|
||||||
|
hide: int = Query(0),
|
||||||
|
read: int = Query(0),
|
||||||
|
) -> None:
|
||||||
|
"""Record a navigation ping (?fr=&to=&hide=&read=); fire-and-forget.
|
||||||
|
|
||||||
|
The initial page-load ping carries only ``to``: the entry is attributed
|
||||||
|
to the referer/UTM tags stashed by the document GET (see _track_entry),
|
||||||
|
which JS cannot see once the page has loaded.
|
||||||
|
|
||||||
The reverse-DNS and DB-IP geoip lookups happen in a background task so
|
The reverse-DNS and DB-IP geoip lookups happen in a background task so
|
||||||
the response is never delayed by slow DNS or the first MMDB decompress.
|
the response is never delayed by slow DNS or the first MMDB decompress.
|
||||||
"""
|
"""
|
||||||
ip = _client_ip(request)
|
ip = _client_ip(request)
|
||||||
visit_index, flushed_clients = analytics_store.ping(
|
visit_index, flushed_clients = analytics_store.ping(
|
||||||
ping.fr,
|
fr,
|
||||||
ping.to,
|
to,
|
||||||
ip,
|
ip,
|
||||||
request.headers.get("user-agent", ""),
|
request.headers.get("user-agent", ""),
|
||||||
request.headers.get("accept-language", ""),
|
request.headers.get("accept-language", ""),
|
||||||
hide=bool(ping.hide),
|
hide=bool(hide),
|
||||||
read=ping.read,
|
read=read,
|
||||||
)
|
)
|
||||||
if visit_index is not None:
|
if visit_index is not None:
|
||||||
visit = analytics_store.data.visits[visit_index]
|
visit = analytics_store.data.visits[visit_index]
|
||||||
@@ -853,13 +859,14 @@ async def analytics_ping(ping: AnalyticsPing, request: Request) -> None:
|
|||||||
_schedule_client_enrichment(flushed_clients)
|
_schedule_client_enrichment(flushed_clients)
|
||||||
|
|
||||||
|
|
||||||
def _track_entry(path: str, request: Request) -> list[bytes]:
|
def _track_entry(path: str, request: Request, *, status: int = 200) -> list[bytes]:
|
||||||
"""Stash the referer/UTM tags and queue a pending crawler hit for the GET.
|
"""Stash the referer/UTM tags and queue a pending crawler hit for the GET.
|
||||||
|
|
||||||
Nothing is counted on the GET itself — the client's /_a ping starts the
|
Nothing is counted on the GET itself — the client's /_a ping starts the
|
||||||
visit, so bots never register as visits (JS-running crawlers ping too,
|
visit, so bots never register as visits (JS-running crawlers ping too,
|
||||||
but the ping handler ignores known bot UAs). (Admin clients ping too,
|
but the ping handler ignores known bot UAs). (Admin clients ping too,
|
||||||
but with hide=1, which scrubs their session instead of recording it.)
|
but with hide=1, which flags their visit hidden: it is recorded but
|
||||||
|
excluded from all statistics and from the crawler list.)
|
||||||
|
|
||||||
The devserver's health probe (``GET /?from=devserver.py`` from
|
The devserver's health probe (``GET /?from=devserver.py`` from
|
||||||
``127.0.0.1``) is ignored: it is not real traffic and would otherwise be
|
``127.0.0.1``) is ignored: it is not real traffic and would otherwise be
|
||||||
@@ -890,6 +897,7 @@ def _track_entry(path: str, request: Request) -> list[bytes]:
|
|||||||
request.headers.get("user-agent", ""),
|
request.headers.get("user-agent", ""),
|
||||||
full_path,
|
full_path,
|
||||||
request.headers.get("accept-language", ""),
|
request.headers.get("accept-language", ""),
|
||||||
|
status=status,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -934,7 +942,7 @@ async def analytics_websocket(ws: WebSocket) -> None:
|
|||||||
endpoint. Powers the analytics viewer rendered at /_a.
|
endpoint. Powers the analytics viewer rendered at /_a.
|
||||||
"""
|
"""
|
||||||
await ws.accept()
|
await ws.accept()
|
||||||
await ws.send_text(msgspec.json.encode(analytics_store.data).decode())
|
await ws.send_text(analytics_store.display_json())
|
||||||
_analytics_ws_clients.add(ws)
|
_analytics_ws_clients.add(ws)
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
@@ -1228,7 +1236,7 @@ async def show_page(request: Request, path: str) -> Response:
|
|||||||
# Category label without a landing page: placeholder with the pen
|
# Category label without a landing page: placeholder with the pen
|
||||||
# to create it (404 — no page here, but the node is real).
|
# to create it (404 — no page here, but the node is real).
|
||||||
if _is_trackable_path(path):
|
if _is_trackable_path(path):
|
||||||
flushed = _track_entry(path, request)
|
flushed = _track_entry(path, request, status=404)
|
||||||
_schedule_client_enrichment(flushed)
|
_schedule_client_enrichment(flushed)
|
||||||
return _html_response(
|
return _html_response(
|
||||||
request,
|
request,
|
||||||
@@ -1254,6 +1262,6 @@ async def show_page(request: Request, path: str) -> Response:
|
|||||||
accept_language,
|
accept_language,
|
||||||
)
|
)
|
||||||
asyncio.create_task(_enrich_client(client_hash))
|
asyncio.create_task(_enrich_client(client_hash))
|
||||||
flushed = _track_entry(path, request)
|
flushed = _track_entry(path, request, status=404)
|
||||||
_schedule_client_enrichment(flushed)
|
_schedule_client_enrichment(flushed)
|
||||||
return _html_response(request, "not-found", path, 404)
|
return _html_response(request, "not-found", path, 404)
|
||||||
|
|||||||
+149
-2
@@ -4,8 +4,19 @@ Raw HTML (including inline scripts) is passed through unfiltered: the
|
|||||||
single author is trusted. Extensions: tables and strikethrough (from the
|
single author is trusted. Extensions: tables and strikethrough (from the
|
||||||
"default" preset), footnotes, definition lists, task lists,
|
"default" preset), footnotes, definition lists, task lists,
|
||||||
brace-attributes (`{.class width=300}` on any element, images in
|
brace-attributes (`{.class width=300}` on any element, images in
|
||||||
particular) and admonitions (``!!! note Title`` with an indented body —
|
particular), admonitions (``!!! note Title`` with an indented body —
|
||||||
note/tip/warning/etc., the title optional). Bare URLs autolink (GFM), with
|
note/tip/warning/etc., the title optional) and GitHub-style alerts
|
||||||
|
(``> [!NOTE]`` / TIP / IMPORTANT / WARNING / CAUTION, rendered in the
|
||||||
|
same callout styling). ``::: name`` opens a generic container rendered
|
||||||
|
as ``<div class="name">`` and closed by a matching ``:::`` (nest by
|
||||||
|
giving the outer container more colons, e.g. `::::`); the name may be
|
||||||
|
followed by brace attributes (``::: aside {.right}``). ``::: aside``
|
||||||
|
floats as a side box beside the text and ``::: nocols`` opts its
|
||||||
|
section out of the column layout. A brace-attribute
|
||||||
|
line as a block's last line (no blank line between) applies to the whole
|
||||||
|
block, e.g. a paragraph ending with ``{.wide}`` breaks out of the column
|
||||||
|
layout as a full-width element; written after a block (code fence,
|
||||||
|
heading, container, ...) it applies to that preceding block. Bare URLs autolink (GFM), with
|
||||||
the ``https://`` scheme hidden in the link text (``http://`` and other
|
the ``https://`` scheme hidden in the link text (``http://`` and other
|
||||||
schemes stay visible; manually labelled links are untouched), and
|
schemes stay visible; manually labelled links are untouched), and
|
||||||
``H~2~O`` / ``x^2^`` give sub/superscripts.
|
``H~2~O`` / ``x^2^`` give sub/superscripts.
|
||||||
@@ -33,6 +44,8 @@ from markdown_it.common.utils import escapeHtml
|
|||||||
from markdown_it.renderer import RendererHTML
|
from markdown_it.renderer import RendererHTML
|
||||||
from mdit_py_plugins.admon import admon_plugin
|
from mdit_py_plugins.admon import admon_plugin
|
||||||
from mdit_py_plugins.attrs import attrs_plugin
|
from mdit_py_plugins.attrs import attrs_plugin
|
||||||
|
from mdit_py_plugins.attrs.parse import ParseError, parse as parse_attrs
|
||||||
|
from mdit_py_plugins.container import container_plugin
|
||||||
from mdit_py_plugins.deflist import deflist_plugin
|
from mdit_py_plugins.deflist import deflist_plugin
|
||||||
from mdit_py_plugins.footnote import footnote_plugin
|
from mdit_py_plugins.footnote import footnote_plugin
|
||||||
from mdit_py_plugins.gfm_autolink import gfm_autolink_plugin
|
from mdit_py_plugins.gfm_autolink import gfm_autolink_plugin
|
||||||
@@ -65,6 +78,31 @@ def _highlight(text: str, lang: str, _attrs: str) -> str:
|
|||||||
return highlight(text, lexer, _formatter)
|
return highlight(text, lexer, _formatter)
|
||||||
|
|
||||||
|
|
||||||
|
def _fence_rule(
|
||||||
|
self: RendererHTML,
|
||||||
|
tokens,
|
||||||
|
idx: int,
|
||||||
|
options,
|
||||||
|
env: dict,
|
||||||
|
) -> str:
|
||||||
|
"""Render a fenced code block.
|
||||||
|
|
||||||
|
Like the default fence rule, but block attributes (a trailing `{...}`
|
||||||
|
line, applied to the fence token by _block_attrs) go on the <pre> — the
|
||||||
|
block element — instead of the <code>, which keeps only the language
|
||||||
|
class. This is what makes e.g. `{.wide}` or `{style="..."}` after a
|
||||||
|
code fence style the block itself.
|
||||||
|
"""
|
||||||
|
token = tokens[idx]
|
||||||
|
info = token.info.strip() if token.info else ""
|
||||||
|
lang = info.split(maxsplit=1)[0] if info else ""
|
||||||
|
highlighted = (_highlight(token.content, lang, "")
|
||||||
|
or escapeHtml(token.content))
|
||||||
|
code_class = f' class="{options.langPrefix}{lang}"' if lang else ""
|
||||||
|
return (f"<pre{self.renderAttrs(token)}><code{code_class}>"
|
||||||
|
f"{highlighted}</code></pre>\n")
|
||||||
|
|
||||||
|
|
||||||
def _image_rule(
|
def _image_rule(
|
||||||
self: RendererHTML,
|
self: RendererHTML,
|
||||||
tokens,
|
tokens,
|
||||||
@@ -107,6 +145,10 @@ def _unwrap_lone_figures(state) -> None:
|
|||||||
if child and child.type == "image":
|
if child and child.type == "image":
|
||||||
if (tokens[i - 1].type == "paragraph_open"
|
if (tokens[i - 1].type == "paragraph_open"
|
||||||
and tokens[i + 1].type == "paragraph_close"):
|
and tokens[i + 1].type == "paragraph_close"):
|
||||||
|
# A lone image becomes a <figure> (see _image_rule); block
|
||||||
|
# attrs on the paragraph (e.g. a trailing {.wide} line) move
|
||||||
|
# onto the image so they survive the unwrap.
|
||||||
|
_apply_attrs(child, tokens[i - 1].attrs or {})
|
||||||
tokens[i - 1].hidden = True
|
tokens[i - 1].hidden = True
|
||||||
tokens[i + 1].hidden = True
|
tokens[i + 1].hidden = True
|
||||||
|
|
||||||
@@ -149,6 +191,104 @@ def _shorten_autolinks(state) -> None:
|
|||||||
text.content = text.content.removeprefix("https://")
|
text.content = text.content.removeprefix("https://")
|
||||||
|
|
||||||
|
|
||||||
|
_CONTAINER_NAME_RE = re.compile(r"[a-zA-Z][\w-]*")
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_attrs(token, attrs: dict) -> None:
|
||||||
|
"""Join/set parsed brace attributes (`{.class key=value}`) on a token."""
|
||||||
|
for key, value in attrs.items():
|
||||||
|
if key == "class":
|
||||||
|
token.attrJoin("class", value)
|
||||||
|
else:
|
||||||
|
token.attrSet(key, value)
|
||||||
|
|
||||||
|
|
||||||
|
def _container_validate(params: str, _markup: str) -> bool:
|
||||||
|
"""`::: name`, optionally followed by brace attrs (`::: aside {.right}`)."""
|
||||||
|
name, _, rest = params.strip().partition(" ")
|
||||||
|
if not _CONTAINER_NAME_RE.fullmatch(name):
|
||||||
|
return False
|
||||||
|
rest = rest.strip()
|
||||||
|
if not rest:
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
pos, _ = parse_attrs(rest)
|
||||||
|
except ParseError:
|
||||||
|
return False
|
||||||
|
# parse() stops at (returns the index of) the closing brace.
|
||||||
|
return pos == len(rest) - 1
|
||||||
|
|
||||||
|
|
||||||
|
def _container_render(self, tokens, idx, options, env):
|
||||||
|
"""Render `::: name {attrs}` containers as `<div class="name">`."""
|
||||||
|
token = tokens[idx]
|
||||||
|
if token.nesting == 1:
|
||||||
|
name, _, rest = token.info.strip().partition(" ")
|
||||||
|
token.attrJoin("class", name)
|
||||||
|
if rest.strip():
|
||||||
|
_, attrs = parse_attrs(rest.strip())
|
||||||
|
_apply_attrs(token, attrs)
|
||||||
|
return self.renderToken(tokens, idx, options, env)
|
||||||
|
|
||||||
|
|
||||||
|
def _block_attrs(state) -> None:
|
||||||
|
"""Apply `{.class key=value}` on a block's last line to the block.
|
||||||
|
|
||||||
|
The inline attrs plugin only covers attributes right after an image,
|
||||||
|
code span or link; this extends the same brace syntax to whole blocks,
|
||||||
|
e.g. a paragraph ending with a `{.wide}` line (no blank line between)
|
||||||
|
gets the `wide` class and thereby breaks out of the column layout.
|
||||||
|
A lone `{...}` paragraph applies to the previous block instead (this
|
||||||
|
is how headings take attributes, since a heading's next line always
|
||||||
|
starts a new paragraph). Runs before the typographer so quotes inside
|
||||||
|
attributes stay straight.
|
||||||
|
"""
|
||||||
|
tokens = state.tokens
|
||||||
|
for i, token in enumerate(tokens):
|
||||||
|
if token.type != "inline" or not token.children:
|
||||||
|
continue
|
||||||
|
text = token.children[-1]
|
||||||
|
if (text.type != "text" or not text.content.startswith("{")
|
||||||
|
or not text.content.endswith("}")):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
_, attrs = parse_attrs(text.content.strip())
|
||||||
|
except ParseError:
|
||||||
|
continue
|
||||||
|
standalone = len(token.children) == 1
|
||||||
|
if not standalone and token.children[-2].type != "softbreak":
|
||||||
|
continue
|
||||||
|
# The target: the enclosing block for a trailing attrs line, or the
|
||||||
|
# previous same-level block for a standalone attrs paragraph —
|
||||||
|
# including self-contained blocks like code fences and <hr>. Never
|
||||||
|
# a hidden token (tight-list paragraphs render no tag to hold the
|
||||||
|
# attributes) — in that case leave the text untouched instead of
|
||||||
|
# silently swallowing it.
|
||||||
|
own = i - 1 # standalone: the attrs paragraph's own opening token
|
||||||
|
j = i - 1
|
||||||
|
while j >= 0:
|
||||||
|
target = tokens[j]
|
||||||
|
if target.hidden:
|
||||||
|
pass
|
||||||
|
elif standalone:
|
||||||
|
if (j != own and target.level == tokens[own].level
|
||||||
|
and (target.nesting == 1
|
||||||
|
or target.type in ("fence", "code_block", "hr"))):
|
||||||
|
break
|
||||||
|
elif target.nesting == 1:
|
||||||
|
break
|
||||||
|
j -= 1
|
||||||
|
if j < 0:
|
||||||
|
continue
|
||||||
|
_apply_attrs(tokens[j], attrs)
|
||||||
|
if standalone:
|
||||||
|
tokens[own].hidden = True
|
||||||
|
token.children = []
|
||||||
|
tokens[i + 1].hidden = True
|
||||||
|
else:
|
||||||
|
del token.children[-2:]
|
||||||
|
|
||||||
|
|
||||||
md = (
|
md = (
|
||||||
MarkdownIt(
|
MarkdownIt(
|
||||||
"default",
|
"default",
|
||||||
@@ -161,6 +301,8 @@ md = (
|
|||||||
)
|
)
|
||||||
.use(attrs_plugin)
|
.use(attrs_plugin)
|
||||||
.use(admon_plugin)
|
.use(admon_plugin)
|
||||||
|
.use(container_plugin, "block", validate=_container_validate,
|
||||||
|
render=_container_render)
|
||||||
.use(footnote_plugin)
|
.use(footnote_plugin)
|
||||||
.use(deflist_plugin)
|
.use(deflist_plugin)
|
||||||
.use(tasklists_plugin, enabled=True)
|
.use(tasklists_plugin, enabled=True)
|
||||||
@@ -169,6 +311,11 @@ md = (
|
|||||||
.use(superscript_plugin)
|
.use(superscript_plugin)
|
||||||
)
|
)
|
||||||
md.add_render_rule("image", _image_rule)
|
md.add_render_rule("image", _image_rule)
|
||||||
|
md.add_render_rule("fence", _fence_rule)
|
||||||
|
# GFM alerts (`> [!NOTE]` etc.), built into markdown-it-py's blockquote rule.
|
||||||
|
md.options["alerts"] = True
|
||||||
|
# Block attrs must be stripped before the typographer curlifies their quotes.
|
||||||
|
md.core.ruler.before("replacements", "block_attrs", _block_attrs)
|
||||||
md.core.ruler.push("unwrap_lone_figures", _unwrap_lone_figures)
|
md.core.ruler.push("unwrap_lone_figures", _unwrap_lone_figures)
|
||||||
md.core.ruler.push("tag_task_checkboxes", _tag_task_checkboxes)
|
md.core.ruler.push("tag_task_checkboxes", _tag_task_checkboxes)
|
||||||
md.core.ruler.push("shorten_autolinks", _shorten_autolinks)
|
md.core.ruler.push("shorten_autolinks", _shorten_autolinks)
|
||||||
|
|||||||
@@ -3,11 +3,6 @@
|
|||||||
SVG from the active palette (var(--accent)), so one SVG serves light
|
SVG from the active palette (var(--accent)), so one SVG serves light
|
||||||
and dark — and other themes too. */
|
and dark — and other themes too. */
|
||||||
|
|
||||||
#banner {
|
|
||||||
min-height: 15rem;
|
|
||||||
border-bottom: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Artwork colors, light mode */
|
/* Artwork colors, light mode */
|
||||||
.cb-bg0 {
|
.cb-bg0 {
|
||||||
stop-color: #ffffff;
|
stop-color: #ffffff;
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
--line: #12203f14;
|
--line: #12203f14;
|
||||||
--font-body: var(--font-inter);
|
--font-body: var(--font-inter);
|
||||||
--font-heading: var(--font-montserrat);
|
--font-heading: var(--font-montserrat);
|
||||||
|
--code-x-height: 0.546; /* Inter's x-height ratio */
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
@@ -32,18 +33,13 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
::selection {
|
|
||||||
background: var(--accent);
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Genuinely large solid brand with a soft blue shadow overlapping the
|
/* Genuinely large solid brand with a soft blue shadow overlapping the
|
||||||
artwork — conservative, but unmissable. */
|
artwork — conservative, but unmissable. */
|
||||||
#brand {
|
#brand {
|
||||||
font-size: clamp(4rem, 11vw, 8.5rem);
|
font-size: clamp(4rem, 11vw, 8.5rem);
|
||||||
font-weight: 800;
|
font-weight: 800;
|
||||||
letter-spacing: -0.04em;
|
letter-spacing: -0.04em;
|
||||||
line-height: 1;
|
line-height: 1.1;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
color: var(--accent2);
|
color: var(--accent2);
|
||||||
filter: drop-shadow(0 0.4rem 1.4rem rgb(10 92 255 / 0.3));
|
filter: drop-shadow(0 0.4rem 1.4rem rgb(10 92 255 / 0.3));
|
||||||
@@ -112,7 +108,6 @@ article h3 {
|
|||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
letter-spacing: 0.08em;
|
letter-spacing: 0.08em;
|
||||||
text-transform: uppercase;
|
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +135,3 @@ pre {
|
|||||||
img {
|
img {
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
::view-transition {
|
|
||||||
background: var(--bg);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
/* Eyes banner design: a canvas critter watching the cursor from the
|
/* Eyes banner design: a canvas critter watching the cursor from the
|
||||||
grass (banner.html — markup + styles + script inlined by the backend
|
grass (banner.html — markup + styles + script inlined by the backend
|
||||||
into #page-banner). Fixed-height stage matching the canvas. */
|
into #page-banner). The canvas fills the banner; the scene composes
|
||||||
|
against the 13rem layout box and extends flat grass into any overflow
|
||||||
|
a theme adds below (summer's cross-fade strip). */
|
||||||
|
|
||||||
#banner {
|
/* Opt out of the base parallax (scale overscan + --pry drift): it lands on
|
||||||
height: 240px;
|
the design wrapper the backend puts around banner.html, and scaling from
|
||||||
|
the bottom edge would crop the top of the composed scene — pushing the
|
||||||
|
critter out of view — while this canvas animates on its own. */
|
||||||
|
#page-banner>[data-design="eyes"] {
|
||||||
|
transform: none;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,13 @@
|
|||||||
<style>
|
<style>
|
||||||
#eyes {
|
#eyes {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 240px;
|
/* 13rem — the banner's layout height, correct from the first frame,
|
||||||
|
before any external stylesheet has sized #page-banner. Themes that
|
||||||
|
extend the banner past the layout box (summer's overflow fade) raise
|
||||||
|
--eyes-h to 100% so the canvas follows the taller stage; the script
|
||||||
|
still composes the scene against the 13rem box and only extends the
|
||||||
|
meadow, so the scene itself never shifts. */
|
||||||
|
height: var(--eyes-h, 13rem);
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -10,32 +16,51 @@
|
|||||||
(() => {
|
(() => {
|
||||||
const c = document.getElementById('eyes')
|
const c = document.getElementById('eyes')
|
||||||
const ctx = c.getContext('2d')
|
const ctx = c.getContext('2d')
|
||||||
const DPR = devicePixelRatio || 1
|
|
||||||
|
|
||||||
const fit = () => {
|
// Sync the backing store to the canvas' laid-out size. Checked every
|
||||||
const w = Math.max(1, c.clientWidth)
|
// frame: this inline script runs before the stylesheets that size
|
||||||
const h = Math.max(1, c.clientHeight)
|
// #page-banner, so observers/load events can still miss the transition.
|
||||||
c.width = Math.round(w * DPR)
|
// Assigning width/height also clears the canvas. DPR is read here, not
|
||||||
c.height = Math.round(h * DPR)
|
// captured: it changes with browser zoom.
|
||||||
|
const syncSize = () => {
|
||||||
|
const DPR = devicePixelRatio || 1
|
||||||
|
const w = Math.round(Math.max(1, c.clientWidth) * DPR)
|
||||||
|
const h = Math.round(Math.max(1, c.clientHeight) * DPR)
|
||||||
|
if (c.width !== w || c.height !== h) {
|
||||||
|
c.width = w
|
||||||
|
c.height = h
|
||||||
|
}
|
||||||
ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
|
ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fit()
|
|
||||||
addEventListener('resize', fit)
|
|
||||||
|
|
||||||
let mx = 0
|
let mx = 0
|
||||||
let my = 0
|
let my = 0
|
||||||
let lastMove = 0
|
let lastMove = 0
|
||||||
|
|
||||||
addEventListener('mousemove', e => {
|
// Mouse and touch tracked with separate listeners (pointer events arrive
|
||||||
|
// too late on some mobile browsers). Passive listeners: a drag on the
|
||||||
|
// banner still scrolls the page — on browsers that stop delivering
|
||||||
|
// touchmove once scrolling takes over, the gaze just follows until then.
|
||||||
|
const track = (x, y) => {
|
||||||
const r = c.getBoundingClientRect()
|
const r = c.getBoundingClientRect()
|
||||||
|
|
||||||
// Convert viewport coordinates into the canvas' CSS-pixel coordinate
|
// Convert viewport coordinates into the canvas' CSS-pixel coordinate
|
||||||
// system. This remains correct with browser zoom, CSS transforms, etc.
|
// system. This remains correct with browser zoom, CSS transforms, etc.
|
||||||
mx = (e.clientX - r.left) * c.clientWidth / r.width
|
mx = (x - r.left) * c.clientWidth / r.width
|
||||||
my = (e.clientY - r.top) * c.clientHeight / r.height
|
my = (y - r.top) * c.clientHeight / r.height
|
||||||
lastMove = performance.now()
|
lastMove = performance.now()
|
||||||
})
|
}
|
||||||
|
|
||||||
|
addEventListener('mousemove', e => track(e.clientX, e.clientY))
|
||||||
|
|
||||||
|
const trackTouch = e => {
|
||||||
|
const t = e.touches[0]
|
||||||
|
|
||||||
|
if (t) track(t.clientX, t.clientY)
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener('touchstart', trackTouch, { passive: true })
|
||||||
|
addEventListener('touchmove', trackTouch, { passive: true })
|
||||||
|
|
||||||
let gx = 0.5
|
let gx = 0.5
|
||||||
let gy = 0.5
|
let gy = 0.5
|
||||||
@@ -54,7 +79,7 @@
|
|||||||
]
|
]
|
||||||
|
|
||||||
const ridgeY = (x, w, h) =>
|
const ridgeY = (x, w, h) =>
|
||||||
h * 0.72 +
|
h * 0.83 +
|
||||||
Math.sin(x * 0.012) * 10 +
|
Math.sin(x * 0.012) * 10 +
|
||||||
Math.sin(x * 0.003 + 1.4) * 16 +
|
Math.sin(x * 0.003 + 1.4) * 16 +
|
||||||
Math.sin(x * 0.02 + 0.7) * 3
|
Math.sin(x * 0.02 + 0.7) * 3
|
||||||
@@ -114,7 +139,7 @@
|
|||||||
|
|
||||||
for (let i = 0; i < 5; i++) {
|
for (let i = 0; i < 5; i++) {
|
||||||
const x = (i + 0.5) * w / 5
|
const x = (i + 0.5) * w / 5
|
||||||
const y = h * 0.58 + Math.sin(i * 1.7) * 8
|
const y = h * 0.69 + Math.sin(i * 1.7) * 8
|
||||||
|
|
||||||
ctx.fillStyle = '#5f8d4e'
|
ctx.fillStyle = '#5f8d4e'
|
||||||
ctx.beginPath()
|
ctx.beginPath()
|
||||||
@@ -307,7 +332,10 @@
|
|||||||
ctx.moveTo(0, h)
|
ctx.moveTo(0, h)
|
||||||
ctx.lineTo(0, ridgeY(0, w, h))
|
ctx.lineTo(0, ridgeY(0, w, h))
|
||||||
|
|
||||||
for (let x = 0; x <= w; x += 8)
|
// Sample one step PAST the right edge (x <= w + 8): stopping at w would
|
||||||
|
// leave the path closing with a visible vertical drop at the edge
|
||||||
|
// whenever the width isn't a multiple of the 8px step.
|
||||||
|
for (let x = 0; x <= w + 8; x += 8)
|
||||||
ctx.lineTo(x, ridgeY(x, w, h))
|
ctx.lineTo(x, ridgeY(x, w, h))
|
||||||
|
|
||||||
ctx.lineTo(w, h)
|
ctx.lineTo(w, h)
|
||||||
@@ -319,7 +347,7 @@
|
|||||||
ctx.moveTo(0, h)
|
ctx.moveTo(0, h)
|
||||||
ctx.lineTo(0, ridgeY(0, w, h) + 10)
|
ctx.lineTo(0, ridgeY(0, w, h) + 10)
|
||||||
|
|
||||||
for (let x = 0; x <= w; x += 8)
|
for (let x = 0; x <= w + 8; x += 8)
|
||||||
ctx.lineTo(x, ridgeY(x, w, h) + 10)
|
ctx.lineTo(x, ridgeY(x, w, h) + 10)
|
||||||
|
|
||||||
ctx.lineTo(w, h)
|
ctx.lineTo(w, h)
|
||||||
@@ -362,8 +390,17 @@
|
|||||||
const dt = Math.min(now - prev, 100) / 16.7
|
const dt = Math.min(now - prev, 100) / 16.7
|
||||||
prev = now
|
prev = now
|
||||||
|
|
||||||
|
syncSize()
|
||||||
|
|
||||||
const w = c.clientWidth
|
const w = c.clientWidth
|
||||||
const h = c.clientHeight
|
// Compose the scene against the banner's layout box, not the canvas:
|
||||||
|
// a theme may extend #page-banner past #banner (e.g. summer overflows
|
||||||
|
// the artwork into the page for a masked cross-fade), and the critter
|
||||||
|
// must stay in the visible part. The overflow strip is filled with the
|
||||||
|
// flat meadow color below — a hard canvas edge would show through the
|
||||||
|
// fade, a grass extension just blends.
|
||||||
|
const h = Math.min(c.clientHeight,
|
||||||
|
c.closest('#banner')?.clientHeight || c.clientHeight)
|
||||||
const R = Math.min(h * 0.11, 38)
|
const R = Math.min(h * 0.11, 38)
|
||||||
|
|
||||||
if (now > nextMove && !hidePhase) {
|
if (now > nextMove && !hidePhase) {
|
||||||
@@ -399,6 +436,16 @@
|
|||||||
vy *= Math.pow(0.85, dt)
|
vy *= Math.pow(0.85, dt)
|
||||||
yoff += vy * dt
|
yoff += vy * dt
|
||||||
|
|
||||||
|
// Clip the scene to the composed area: the ducking critter travels
|
||||||
|
// below it, and the overflow strip is only flat meadow painted after —
|
||||||
|
// without the clip the critter would leave trails there as it sinks.
|
||||||
|
// Clipping against grass-on-grass is invisible, so the duck still
|
||||||
|
// reads as sinking into the meadow.
|
||||||
|
ctx.save()
|
||||||
|
ctx.beginPath()
|
||||||
|
ctx.rect(0, 0, w, h)
|
||||||
|
ctx.clip()
|
||||||
|
|
||||||
drawBackground(w, h)
|
drawBackground(w, h)
|
||||||
|
|
||||||
const cx0 = gx * w
|
const cx0 = gx * w
|
||||||
@@ -415,6 +462,18 @@
|
|||||||
drawCritter(cx0, eyeY, R, now, dt)
|
drawCritter(cx0, eyeY, R, now, dt)
|
||||||
drawForeground(w, h)
|
drawForeground(w, h)
|
||||||
|
|
||||||
|
ctx.restore()
|
||||||
|
|
||||||
|
// Extend the meadow into any overflow below the composed scene, with
|
||||||
|
// the same two layers drawForeground leaves at the bottom (base grass
|
||||||
|
// plus the dark under-band) so the joint is invisible.
|
||||||
|
if (c.clientHeight > h) {
|
||||||
|
ctx.fillStyle = '#69ae4b'
|
||||||
|
ctx.fillRect(0, h, w, c.clientHeight - h)
|
||||||
|
ctx.fillStyle = 'rgba(48,102,34,0.18)'
|
||||||
|
ctx.fillRect(0, h, w, c.clientHeight - h)
|
||||||
|
}
|
||||||
|
|
||||||
requestAnimationFrame(frame)
|
requestAnimationFrame(frame)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,13 +2,6 @@
|
|||||||
(inlined by the backend into #page-banner), in neutral dark greys that
|
(inlined by the backend into #page-banner), in neutral dark greys that
|
||||||
follow the page's color scheme. */
|
follow the page's color scheme. */
|
||||||
|
|
||||||
/* Bezier-swept banner with wide orange stripes (inlined SVG), separated
|
|
||||||
from the page by a straight orange blade. */
|
|
||||||
#banner {
|
|
||||||
height: 13rem;
|
|
||||||
border-bottom: 4px solid var(--accent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Banner artwork dark tones: neutral greys in light mode (retinted to the
|
/* Banner artwork dark tones: neutral greys in light mode (retinted to the
|
||||||
page's violet family by the dark-scheme block below). */
|
page's violet family by the dark-scheme block below). */
|
||||||
.nb-base {
|
.nb-base {
|
||||||
@@ -44,6 +37,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
|
|
||||||
/* Banner dark tones tinted to the same violet family as the page. */
|
/* Banner dark tones tinted to the same violet family as the page. */
|
||||||
.nb-base {
|
.nb-base {
|
||||||
fill: #100d18;
|
fill: #100d18;
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
|
|
||||||
--font-body: var(--font-montserrat);
|
--font-body: var(--font-montserrat);
|
||||||
--font-heading: var(--font-literata);
|
--font-heading: var(--font-literata);
|
||||||
|
--code-x-height: 0.517; /* Montserrat's x-height ratio */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Dark scheme: same identity, but the page goes deep violet (never muddy
|
/* Dark scheme: same identity, but the page goes deep violet (never muddy
|
||||||
@@ -63,13 +64,19 @@
|
|||||||
|
|
||||||
::selection {
|
::selection {
|
||||||
background: var(--accent);
|
background: var(--accent);
|
||||||
color: var(--ink);
|
}
|
||||||
|
|
||||||
|
/* Any banner used is separated from page by a thick orange line */
|
||||||
|
#banner {
|
||||||
|
border-bottom: 4px solid var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Oversized outlined brand, spilling off the banner edge: orange stroke,
|
/* Oversized outlined brand, spilling off the banner edge: orange stroke,
|
||||||
solid black fill. */
|
solid black fill. */
|
||||||
#brand {
|
#brand {
|
||||||
font-size: 10rem;
|
/* Scales down proportionally below ~1000px: 10rem at a 62.5rem viewport,
|
||||||
|
shrinking with vmin (smaller of viewport width/height) below that. */
|
||||||
|
font-size: clamp(2.5rem, 16vmin, 10rem);
|
||||||
line-height: 1.2;
|
line-height: 1.2;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
@@ -131,14 +138,9 @@
|
|||||||
|
|
||||||
/* Console-style headings: uppercase monospace. h1 in the page text color
|
/* Console-style headings: uppercase monospace. h1 in the page text color
|
||||||
with a hazard-stripe underline, h2 deep orange, h3 cyan. */
|
with a hazard-stripe underline, h2 deep orange, h3 cyan. */
|
||||||
article h1,
|
article h1 {
|
||||||
article h2,
|
|
||||||
article h3 {
|
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.02em;
|
letter-spacing: 0.02em;
|
||||||
}
|
|
||||||
|
|
||||||
article h1 {
|
|
||||||
color: var(--text);
|
color: var(--text);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
padding-bottom: 0.5rem;
|
padding-bottom: 0.5rem;
|
||||||
@@ -206,7 +208,3 @@ pre {
|
|||||||
img {
|
img {
|
||||||
border-radius: 3px;
|
border-radius: 3px;
|
||||||
}
|
}
|
||||||
|
|
||||||
::view-transition {
|
|
||||||
background: var(--bg);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -15,7 +15,3 @@
|
|||||||
.banner-fade {
|
.banner-fade {
|
||||||
stop-color: var(--bg);
|
stop-color: var(--bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
#banner {
|
|
||||||
min-height: 13rem;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -17,11 +17,7 @@
|
|||||||
--line: #ffffff1c;
|
--line: #ffffff1c;
|
||||||
--font-body: var(--font-literata);
|
--font-body: var(--font-literata);
|
||||||
--font-heading: var(--font-fraunces);
|
--font-heading: var(--font-fraunces);
|
||||||
}
|
--code-x-height: 0.507; /* Literata's x-height ratio */
|
||||||
|
|
||||||
::selection {
|
|
||||||
background: var(--accent2);
|
|
||||||
color: #fff;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Oversized tilted brand in the sky→violet gradient. */
|
/* Oversized tilted brand in the sky→violet gradient. */
|
||||||
@@ -91,7 +87,3 @@ blockquote {
|
|||||||
pre {
|
pre {
|
||||||
--code-bg: var(--surface);
|
--code-bg: var(--surface);
|
||||||
}
|
}
|
||||||
|
|
||||||
::view-transition {
|
|
||||||
background: #000;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/* Stars banner design: a drifting starfield (banner.html — canvas + script
|
/* Stars banner design: a drifting starfield (banner.html — canvas + script
|
||||||
inlined by the backend into #page-banner). Fixed-height stage matching
|
inlined by the backend into #page-banner). The canvas takes the banner's
|
||||||
the canvas. */
|
13rem layout height directly so it never renders unclipped before the
|
||||||
|
main stylesheet loads; the starfield scales to any height. The design's
|
||||||
#banner {
|
opt-out of theme banner overflow/fade effects also lives in banner.html's
|
||||||
height: 240px;
|
inline <style>, so it applies atomically with the markup (this file would
|
||||||
}
|
load a beat later and let the overflow flash through mid-transition). */
|
||||||
|
|||||||
@@ -2,27 +2,47 @@
|
|||||||
<style>
|
<style>
|
||||||
#stars {
|
#stars {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 240px;
|
/* 13rem — the banner's layout height, not 100%: a percentage only
|
||||||
|
resolves after the main stylesheet sizes #page-banner, and until
|
||||||
|
then the canvas would render at its intrinsic height, unclipped,
|
||||||
|
over the page. (This design always opts out of theme overflows —
|
||||||
|
below — so the layout height is always the right one.) */
|
||||||
|
height: 13rem;
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The night sky stays a windowed stage: undo the summer theme's banner
|
||||||
|
overflow/cross-fade — a starfield must not bleed into a daylit page.
|
||||||
|
Kept in this inlined <style> (not banner.css) so the opt-out applies
|
||||||
|
atomically with the markup; a separate stylesheet can arrive a beat
|
||||||
|
later and let the overflow flash through mid-transition. Later in
|
||||||
|
document order than theme.css, so same-specificity rules win. */
|
||||||
|
#page-banner {
|
||||||
|
inset: 0;
|
||||||
|
mask-image: none;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
<script><!--
|
<script><!--
|
||||||
(() => {
|
(() => {
|
||||||
const c = document.getElementById('stars')
|
const c = document.getElementById('stars')
|
||||||
const ctx = c.getContext('2d')
|
const ctx = c.getContext('2d')
|
||||||
const DPR = devicePixelRatio || 1
|
|
||||||
|
|
||||||
const fit = () => {
|
// Sync the backing store to the canvas' laid-out size. Checked every
|
||||||
const w = Math.max(1, c.clientWidth)
|
// frame: this inline script runs before the stylesheets that size
|
||||||
const h = Math.max(1, c.clientHeight)
|
// #page-banner, so observers/load events can still miss the transition.
|
||||||
c.width = Math.round(w * DPR)
|
// Assigning width/height also clears the canvas. DPR is read here, not
|
||||||
c.height = Math.round(h * DPR)
|
// captured: it changes with browser zoom.
|
||||||
|
const syncSize = () => {
|
||||||
|
const DPR = devicePixelRatio || 1
|
||||||
|
const w = Math.round(Math.max(1, c.clientWidth) * DPR)
|
||||||
|
const h = Math.round(Math.max(1, c.clientHeight) * DPR)
|
||||||
|
if (c.width !== w || c.height !== h) {
|
||||||
|
c.width = w
|
||||||
|
c.height = h
|
||||||
|
}
|
||||||
ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
|
ctx.setTransform(DPR, 0, 0, DPR, 0, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
fit()
|
|
||||||
addEventListener('resize', fit)
|
|
||||||
|
|
||||||
const stars = Array.from({ length: 110 }, () => ({
|
const stars = Array.from({ length: 110 }, () => ({
|
||||||
x: Math.random(),
|
x: Math.random(),
|
||||||
y: Math.random(),
|
y: Math.random(),
|
||||||
@@ -33,6 +53,7 @@
|
|||||||
let prev = performance.now()
|
let prev = performance.now()
|
||||||
;(function frame(now) {
|
;(function frame(now) {
|
||||||
if (!c.isConnected) return
|
if (!c.isConnected) return
|
||||||
|
syncSize()
|
||||||
const w = c.clientWidth
|
const w = c.clientWidth
|
||||||
const h = c.clientHeight
|
const h = c.clientHeight
|
||||||
const dt = Math.min(now - prev, 100)
|
const dt = Math.min(now - prev, 100)
|
||||||
|
|||||||
@@ -2,10 +2,6 @@
|
|||||||
backend into #page-banner) — rolling hills, leafy bushes, swaying
|
backend into #page-banner) — rolling hills, leafy bushes, swaying
|
||||||
flowers, drifting clouds and a sun that rises as you scroll. */
|
flowers, drifting clouds and a sun that rises as you scroll. */
|
||||||
|
|
||||||
#banner {
|
|
||||||
min-height: 15rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* The artwork fades into the page background at its bottom edge. */
|
/* The artwork fades into the page background at its bottom edge. */
|
||||||
.summer-fade {
|
.summer-fade {
|
||||||
stop-color: var(--bg);
|
stop-color: var(--bg);
|
||||||
@@ -44,9 +40,17 @@
|
|||||||
animation: summer-sun 9s ease-in-out infinite alternate;
|
animation: summer-sun 9s ease-in-out infinite alternate;
|
||||||
}
|
}
|
||||||
|
|
||||||
#page-banner .cloud-a { animation: summer-drift 56s ease-in-out infinite alternate; }
|
#page-banner .cloud-a {
|
||||||
#page-banner .cloud-b { animation: summer-drift 73s ease-in-out infinite alternate-reverse; }
|
animation: summer-drift 56s ease-in-out infinite alternate;
|
||||||
#page-banner .cloud-c { animation: summer-drift 64s ease-in-out infinite alternate; }
|
}
|
||||||
|
|
||||||
|
#page-banner .cloud-b {
|
||||||
|
animation: summer-drift 73s ease-in-out infinite alternate-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
#page-banner .cloud-c {
|
||||||
|
animation: summer-drift 64s ease-in-out infinite alternate;
|
||||||
|
}
|
||||||
|
|
||||||
#page-banner .flower {
|
#page-banner .flower {
|
||||||
transform-box: fill-box;
|
transform-box: fill-box;
|
||||||
@@ -55,21 +59,42 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Stagger the sway so the meadow doesn't move in lockstep. */
|
/* Stagger the sway so the meadow doesn't move in lockstep. */
|
||||||
#page-banner .flower:nth-child(3n) { animation-delay: -1.7s; }
|
#page-banner .flower:nth-child(3n) {
|
||||||
#page-banner .flower:nth-child(3n + 1) { animation-delay: -3.1s; animation-duration: 6s; }
|
animation-delay: -1.7s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#page-banner .flower:nth-child(3n + 1) {
|
||||||
|
animation-delay: -3.1s;
|
||||||
|
animation-duration: 6s;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes summer-sun {
|
@keyframes summer-sun {
|
||||||
from { opacity: 0.22; }
|
from {
|
||||||
to { opacity: 0.38; }
|
opacity: 0.22;
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
opacity: 0.38;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes summer-drift {
|
@keyframes summer-drift {
|
||||||
from { transform: translateX(-1.6%); }
|
from {
|
||||||
to { transform: translateX(1.6%); }
|
transform: translateX(-1.6%);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
transform: translateX(1.6%);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes summer-sway {
|
@keyframes summer-sway {
|
||||||
from { transform: rotate(-2.6deg); }
|
from {
|
||||||
to { transform: rotate(2.6deg); }
|
transform: rotate(-2.6deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
transform: rotate(2.6deg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
|
|
||||||
/* Every color is sampled (or text-darkened) from banner.svg. */
|
/* Every color is sampled (or text-darkened) from banner.svg. */
|
||||||
--bg: #e6f4cf;
|
--bg: #e6f4cf;
|
||||||
|
--sky: #d9f1ff;
|
||||||
/* pale meadow — the banner fades into this */
|
/* pale meadow — the banner fades into this */
|
||||||
--surface: #f8fbf0;
|
--surface: #f8fbf0;
|
||||||
--text: #2c4a2f;
|
--text: #2c4a2f;
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
--font-body: var(--font-cause);
|
--font-body: var(--font-cause);
|
||||||
--font-heading: var(--font-new-rocker);
|
--font-heading: var(--font-new-rocker);
|
||||||
--font-brand: var(--font-cause);
|
--font-brand: var(--font-cause);
|
||||||
|
--code-x-height: 0.5; /* Cause's x-height ratio */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The page is the same landscape the banner paints: hazy sky light up top
|
/* The page is the same landscape the banner paints: hazy sky light up top
|
||||||
@@ -56,15 +58,33 @@ body {
|
|||||||
color: var(--text);
|
color: var(--text);
|
||||||
}
|
}
|
||||||
|
|
||||||
::selection {
|
/* No separation between banner and page: the frame loses its background,
|
||||||
background: var(--sun);
|
border and shadow, and the artwork overflows into the document below,
|
||||||
color: #3d5223;
|
masked by a transparency gradient so it cross-fades into the body's fixed
|
||||||
|
meadow gradient. A plain color match is impossible — both sides are
|
||||||
|
gradients, and the parallax drift keeps the banner side moving. */
|
||||||
|
#banner {
|
||||||
|
background: none;
|
||||||
|
border-bottom: 0;
|
||||||
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The banner frame ties into the meadow beneath it. */
|
#page-banner {
|
||||||
#banner {
|
inset: 0 0 -6rem;
|
||||||
border-bottom-color: #4f913b30;
|
/* Paints over the page background in the overlap, but never swallows its
|
||||||
box-shadow: 0 0.3rem 1rem #4f913b22;
|
clicks. */
|
||||||
|
pointer-events: none;
|
||||||
|
mask-image: linear-gradient(180deg, #000 calc(100% - 6rem), transparent);
|
||||||
|
/* Canvas banner designs (eyes) default to the 13rem layout height; here
|
||||||
|
they must fill the taller overflow stage so their meadow extension
|
||||||
|
reaches through the fade strip. */
|
||||||
|
--eyes-h: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The mask above replaced the SVG's flat-color bottom fade (meadowFade) —
|
||||||
|
fading to a single --bg would reintroduce a seam against the gradient. */
|
||||||
|
#page-banner .summer-fade {
|
||||||
|
stop-opacity: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Cheerful oversized tilted brand in a sky→grass→flower gradient. */
|
/* Cheerful oversized tilted brand in a sky→grass→flower gradient. */
|
||||||
@@ -114,14 +134,26 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Content sits in a soft wash of sunlit meadow rather than on a white
|
/* Content sits in a soft wash of sunlit meadow rather than on a white
|
||||||
card. */
|
card. The wash lives on a pseudo-element so it can carry a vertical
|
||||||
|
mask: it fades in from transparent over the strip where the banner
|
||||||
|
artwork overflows into the page, so the two never fight — no matter
|
||||||
|
which side paints on top. */
|
||||||
main {
|
main {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
main::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: -1;
|
||||||
background: linear-gradient(90deg,
|
background: linear-gradient(90deg,
|
||||||
transparent,
|
transparent,
|
||||||
#f0f8dc80 15%,
|
#f0f8dc80 15%,
|
||||||
#f0f8dc8c 50%,
|
#f0f8dc8c 50%,
|
||||||
#f0f8dc80 85%,
|
#f0f8dc80 85%,
|
||||||
transparent);
|
transparent);
|
||||||
|
mask-image: linear-gradient(180deg, transparent, #000 6rem);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The sidebar is a piece of the same meadow: glassy green with a light
|
/* The sidebar is a piece of the same meadow: glassy green with a light
|
||||||
@@ -131,6 +163,8 @@ main {
|
|||||||
border-right: 1px solid #ffffff80;
|
border-right: 1px solid #ffffff80;
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 1px solid var(--line);
|
||||||
box-shadow: 0 0.3rem 1rem #4f913b1f;
|
box-shadow: 0 0.3rem 1rem #4f913b1f;
|
||||||
|
border-radius: 1rem;
|
||||||
|
margin-inline: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#sidebar a {
|
#sidebar a {
|
||||||
@@ -260,8 +294,7 @@ figcaption,
|
|||||||
background: linear-gradient(160deg, #eef7dd, #d9eec5);
|
background: linear-gradient(160deg, #eef7dd, #d9eec5);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The page transition exposes summer color around the rotating
|
|
||||||
snapshots. */
|
|
||||||
::view-transition {
|
::view-transition {
|
||||||
background: var(--bg);
|
/* Override to mid sky shade instead of the darker --bg we otherwise get */
|
||||||
|
background: var(--sky);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user