feat(v2): stack event details on phones and search as you type

- On a phone each event lists its title, detail, author and where from,
  in that order; the title and detail wrap to two lines, and the list
  sizes every row from how its text wraps at the row's width and fonts.
- The event's icon sits on a solid disc of its category's color.
- The event search runs once typing pauses, like the gallery's, instead
  of waiting for a Search button; Enter still searches straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
zurdi
2026-09-24 10:14:01 +02:00
parent 5cccceea60
commit 1e8dba617f
8 changed files with 365 additions and 79 deletions

View File

@@ -90,23 +90,36 @@ describe("EventLog", () => {
expect(text).toContain("Steam Deck");
});
it("searches when asked, not on every keystroke", async () => {
const wrapper = render();
await flushPromises();
getAuditEvents.mockClear();
it("searches once typing pauses, or straight away on Enter", async () => {
// lodash's debounce reads the clock; setImmediate stays real for flushPromises.
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
try {
const wrapper = render();
await flushPromises();
getAuditEvents.mockClear();
const input = wrapper.find('input[placeholder="Search events"]');
await wrapper
.find('input[placeholder="Search events"]')
.setValue("192.168");
await flushPromises();
expect(getAuditEvents).not.toHaveBeenCalled();
await input.setValue("192");
await input.setValue("192.168");
await flushPromises();
expect(getAuditEvents).not.toHaveBeenCalled();
const button = wrapper.findAll("button").find((b) => b.text() === "Search");
await button?.trigger("click");
await flushPromises();
vi.advanceTimersByTime(300);
await flushPromises();
expect(getAuditEvents).toHaveBeenCalledOnce();
expect(getAuditEvents).toHaveBeenCalledWith(
expect.objectContaining({ search: "192.168" }),
);
expect(getAuditEvents).toHaveBeenCalledWith(
expect.objectContaining({ search: "192.168" }),
);
getAuditEvents.mockClear();
await input.setValue("steam");
await input.trigger("keyup", { key: "Enter" });
await flushPromises();
expect(getAuditEvents).toHaveBeenCalledWith(
expect.objectContaining({ search: "steam" }),
);
} finally {
vi.useRealTimers();
}
});
});

View File

@@ -12,15 +12,29 @@ import {
RVirtualScroller,
} from "@v2/lib";
import { isToday, isYesterday } from "date-fns";
import { debounce } from "lodash";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref, watch } from "vue";
import {
computed,
onBeforeUnmount,
onMounted,
ref,
shallowRef,
watch,
} from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import type { AuditCategory, AuditEventSchema } from "@/__generated__";
import storeUsers from "@/stores/users";
import { toBrowserLocale } from "@/utils";
import EventLogRow from "@/v2/components/Settings/EventLogRow.vue";
import {
EVENT_ROW_HEIGHT,
PHONE_EVENT_ROW,
phoneEventRowHeight,
} from "@/v2/components/Settings/eventLogLayout";
import { useAuditLog } from "@/v2/composables/useAuditLog";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useGridNav } from "@/v2/composables/useGridNav";
import { useLoadingPhase } from "@/v2/composables/useLoadingPhase";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -30,6 +44,7 @@ import {
type AuditEventView,
} from "@/v2/utils/auditEvents";
import { syncQueryParam } from "@/v2/utils/routeQuery";
import { canvasMeasure, wrappedLineCount } from "@/v2/utils/textLines";
const { t, locale } = useI18n();
const route = useRoute();
@@ -98,10 +113,12 @@ const untilDate = computed({
set: (date) => (until.value = dateToDay(date)),
});
// Emptying the box shows everything again; anything else waits for a search.
watch(search, (value) => {
if (!value.trim()) appliedSearch.value = "";
});
// Typing searches once it pauses, as the gallery's search does.
const applySearch = debounce(() => {
appliedSearch.value = search.value.trim();
}, 300);
watch(search, applySearch);
onBeforeUnmount(() => applySearch.cancel());
const hasFilters = computed(
() =>
@@ -135,7 +152,8 @@ async function refresh() {
}
}
function submitSearch() {
function searchNow() {
applySearch.cancel();
const next = search.value.trim();
// Searching the same text again reloads, picking up newer events.
if (next === appliedSearch.value) void refresh();
@@ -227,6 +245,7 @@ interface EventItem {
view: AuditEventView;
first: boolean;
last: boolean;
height: number;
}
interface DayItem {
@@ -237,12 +256,79 @@ interface DayItem {
type Item = DayItem | EventItem | { kind: "more"; key: "more" };
// Kept in step with EventLogRow and the day and "more" rows below.
const ITEM_HEIGHTS: Record<Item["kind"], number> = {
day: 44,
event: 62,
more: 56,
};
// Kept in step with the day and "more" rows below.
const ROW_HEIGHTS = { day: 44, more: 56 } as const;
// A phone wraps each event's title and detail, so its row's height depends on
// how they wrap in the fonts and width of a row already on screen.
interface TextMetrics {
width: number;
fonts: string;
title: (run: string) => number;
detail: (run: string) => number;
}
const listRoot = ref<HTMLElement | null>(null);
const { xs } = useBreakpoint();
const textMetrics = shallowRef<TextMetrics | null>(null);
function readTextMetrics(force = false) {
if (!xs.value) return;
const body = listRoot.value?.querySelector<HTMLElement>(
".r-v2-audit-event__body",
);
const title = body?.querySelector<HTMLElement>(".r-v2-audit-event__title");
const meta = body?.querySelector<HTMLElement>(".r-v2-audit-event__meta");
if (!body || !title || !meta) return;
const titleFont = getComputedStyle(title).font;
const metaFont = getComputedStyle(meta).font;
const fonts = `${titleFont}|${metaFont}`;
const width = body.clientWidth;
const current = textMetrics.value;
if (!force && current?.width === width && current.fonts === fonts) return;
const measureTitle = canvasMeasure(titleFont);
const measureDetail = canvasMeasure(metaFont);
if (!measureTitle || !measureDetail) return;
textMetrics.value = {
width,
fonts,
title: measureTitle,
detail: measureDetail,
};
}
function phoneLines(text: string, measure?: (run: string) => number): number {
const width = textMetrics.value?.width;
if (!width || !measure) return 1;
// Measured a little short, so a line that only just fits counts as wrapped:
// a spare line is better than one cut off.
return Math.min(
PHONE_EVENT_ROW.maxLines,
wrappedLineCount(text, width - 2, measure),
);
}
// Like the sentences, heights are kept until the fonts or the width change.
const heights = computed(() => {
void xs.value;
void textMetrics.value;
return new WeakMap<AuditEventView, number>();
});
function eventHeight(event: AuditEventSchema, view: AuditEventView): number {
if (!xs.value) return EVENT_ROW_HEIGHT;
let height = heights.value.get(view);
if (height === undefined) {
const metrics = textMetrics.value;
height = phoneEventRowHeight({
title: phoneLines(view.title, metrics?.title),
detail: view.detail ? phoneLines(view.detail, metrics?.detail) : 0,
where: !!(event.device_name || event.ip_address),
});
heights.value.set(view, height);
}
return height;
}
// Events arrive newest first, so each local day is one run of them. Nothing is
// handed to the scroller until the list is shown.
@@ -261,13 +347,15 @@ const items = computed<Item[]>(() => {
dayKey = key;
out.push({ kind: "day", key: `day-${key}`, label: dayLabel(date, year) });
}
const view = describe(event);
previous = {
kind: "event",
key: event.id,
event,
view: describe(event),
view,
first: startsDay,
last: false,
height: eventHeight(event, view),
};
out.push(previous);
}
@@ -277,7 +365,8 @@ const items = computed<Item[]>(() => {
});
function itemHeight(item: unknown): number {
return ITEM_HEIGHTS[(item as Item).kind];
const row = item as Item;
return row.kind === "event" ? row.height : ROW_HEIGHTS[row.kind];
}
function itemKey(item: unknown): string | number {
@@ -290,11 +379,20 @@ function onViewportRange({ last }: { first: number; last: number }) {
}
}
const listRoot = ref<HTMLElement | null>(null);
useGridNav(listRoot, {
rowSelector: ".r-v2-audit-event",
getCells: (row) => Array.from(row.querySelectorAll<HTMLElement>("a")),
});
watch(items, () => readTextMetrics(), { flush: "post" });
let listObserver: ResizeObserver | null = null;
onMounted(() => {
listObserver = new ResizeObserver(() => readTextMetrics());
if (listRoot.value) listObserver.observe(listRoot.value);
// A web font that arrives late measures differently under the same name.
void document.fonts?.ready.then(() => readTextMetrics(true));
});
onBeforeUnmount(() => listObserver?.disconnect());
</script>
<template>
@@ -364,17 +462,8 @@ useGridNav(listRoot, {
prepend-inner-icon="mdi-magnify"
:placeholder="t('audit.search-placeholder')"
:aria-label="t('audit.search-placeholder')"
@keyup.enter="submitSearch"
@keyup.enter="searchNow"
/>
<RBtn
variant="flat"
color="primary"
prepend-icon="mdi-magnify"
:loading="loading"
@click="submitSearch"
>
{{ t("common.search") }}
</RBtn>
</div>
<div v-if="phase === 'skeleton'" class="r-v2-audit__skeleton">
@@ -417,6 +506,7 @@ useGridNav(listRoot, {
:view="(item as EventItem).view"
:first="(item as EventItem).first"
:last="(item as EventItem).last"
:height="(item as EventItem).height"
:time="
timeFormat.format(new Date((item as EventItem).event.occurred_at))
"

View File

@@ -1,12 +1,13 @@
<script setup lang="ts">
// EventLogRow: one event on the event log's timeline, a fixed height so the
// list can window it.
// EventLogRow: one event on the event log's timeline, at the height the list
// windows it at.
import { RAvatar, RIcon } from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RouterLink } from "vue-router";
import type { AuditEventSchema } from "@/__generated__";
import { formatTimestamp } from "@/utils";
import { PHONE_EVENT_ROW } from "@/v2/components/Settings/eventLogLayout";
import type { AuditEventView } from "@/v2/utils/auditEvents";
import { userAvatarUrl } from "@/v2/utils/userAvatar";
@@ -18,8 +19,18 @@ const props = defineProps<{
last: boolean;
/** The time of day it happened, formatted by the list for all its rows. */
time: string;
height: number;
}>();
const PHONE_GEOMETRY = {
"--r-audit-phone-pad": `${PHONE_EVENT_ROW.paddingBlock}px`,
"--r-audit-title-offset": `${PHONE_EVENT_ROW.titleOffset}px`,
"--r-audit-title-line": `${PHONE_EVENT_ROW.titleLine}px`,
"--r-audit-meta-line": `${PHONE_EVENT_ROW.metaLine}px`,
"--r-audit-gap": `${PHONE_EVENT_ROW.gap}px`,
"--r-audit-max-lines": PHONE_EVENT_ROW.maxLines,
};
const { t, locale } = useI18n();
const actorName = computed(() => {
@@ -54,6 +65,7 @@ const actorAvatar = computed(() => {
'r-v2-audit-event--first': first,
'r-v2-audit-event--last': last,
}"
:style="{ height: `${height}px`, ...PHONE_GEOMETRY }"
>
<time
class="r-v2-audit-event__time"
@@ -63,13 +75,12 @@ const actorAvatar = computed(() => {
{{ time }}
</time>
<span class="r-v2-audit-event__rail">
<RAvatar
:icon="view.icon"
:color="view.tone"
variant="translucent"
size="28"
<span
class="r-v2-audit-event__dot"
/>
:style="{ '--r-audit-tone': view.tone }"
>
<RIcon :icon="view.icon" size="16" />
</span>
</span>
<span class="r-v2-audit-event__body">
<component
@@ -80,25 +91,31 @@ const actorAvatar = computed(() => {
{{ view.title }}
</component>
<span class="r-v2-audit-event__meta">
<span class="r-v2-audit-event__meta-item">
<span class="r-v2-audit-event__item r-v2-audit-event__actor">
<RAvatar
:image="actorAvatar"
:icon="actorIcon"
variant="translucent"
size="16"
/>
{{ actorName }}
<span class="r-v2-audit-event__text">{{ actorName }}</span>
</span>
<span v-if="view.detail" class="r-v2-audit-event__meta-item">
{{ view.detail }}
<span
v-if="view.detail"
class="r-v2-audit-event__item r-v2-audit-event__detail"
>
<span class="r-v2-audit-event__text">{{ view.detail }}</span>
</span>
<span v-if="event.device_name" class="r-v2-audit-event__meta-item">
<span
v-if="event.device_name"
class="r-v2-audit-event__item r-v2-audit-event__device"
>
<RIcon icon="mdi-devices" size="14" />
{{ event.device_name }}
<span class="r-v2-audit-event__text">{{ event.device_name }}</span>
</span>
<span
v-if="event.ip_address"
class="r-v2-audit-event__meta-item r-v2-audit-event__ip"
class="r-v2-audit-event__item r-v2-audit-event__ip"
>
<RIcon icon="mdi-ip-network-outline" size="14" />
{{ event.ip_address }}
@@ -112,12 +129,12 @@ const actorAvatar = computed(() => {
/* Each day reads as one panel: its first and last rows round the corners. */
.r-v2-audit-event {
--r-audit-dot: 28px;
--r-audit-pad-block: var(--r-space-2);
display: grid;
grid-template-columns: 3.25rem var(--r-audit-dot) minmax(0, 1fr);
column-gap: var(--r-space-3);
box-sizing: border-box;
height: 62px;
padding: var(--r-space-2) var(--r-space-4);
padding: var(--r-audit-pad-block) var(--r-space-4);
background: var(--r-color-surface);
border-inline: 1px solid var(--r-color-border);
}
@@ -149,8 +166,8 @@ const actorAvatar = computed(() => {
.r-v2-audit-event__rail::before {
content: "";
position: absolute;
top: calc(-1 * var(--r-space-2));
bottom: calc(-1 * var(--r-space-2));
top: calc(-1 * var(--r-audit-pad-block));
bottom: calc(-1 * var(--r-audit-pad-block));
left: 50%;
width: 2px;
transform: translateX(-50%);
@@ -163,11 +180,17 @@ const actorAvatar = computed(() => {
bottom: calc(100% - var(--r-audit-dot) / 2);
}
/* An opaque disc under the translucent icon keeps the rail from showing through. */
/* The page's own background is the one color that reads on every tone. */
.r-v2-audit-event__dot {
position: relative;
box-shadow: 0 0 0 3px var(--r-color-surface);
background-color: var(--r-color-surface);
display: flex;
align-items: center;
justify-content: center;
width: var(--r-audit-dot);
height: var(--r-audit-dot);
border-radius: 50%;
background: var(--r-audit-tone);
color: var(--r-color-bg);
}
.r-v2-audit-event__body {
@@ -192,23 +215,32 @@ a.r-v2-audit-event__title:hover {
text-decoration: underline;
}
/* One line, so every row keeps the height the windowing counts on. */
/* Who, what, and where from, on one line; long names shorten rather than
push what follows off the end. */
.r-v2-audit-event__meta {
display: flex;
gap: var(--r-space-3);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--r-font-size-sm);
color: var(--r-color-fg-secondary);
}
.r-v2-audit-event__meta-item {
.r-v2-audit-event__item {
display: inline-flex;
align-items: center;
gap: 6px;
vertical-align: middle;
min-width: 0;
}
.r-v2-audit-event__meta-item + .r-v2-audit-event__meta-item {
margin-inline-start: var(--r-space-3);
.r-v2-audit-event__actor,
.r-v2-audit-event__ip {
flex-shrink: 0;
}
.r-v2-audit-event__text {
overflow: hidden;
text-overflow: ellipsis;
}
.r-v2-audit-event__ip {
@@ -220,4 +252,43 @@ html[data-bp~="xs"] .r-v2-audit-event {
column-gap: var(--r-space-2);
padding-inline: var(--r-space-3);
}
/* A phone stacks the title, the detail, who, and where from, in that order
on every row; the list sizes each row for how its title and detail wrap. */
html[data-bp~="xs"] .r-v2-audit-event {
--r-audit-pad-block: var(--r-audit-phone-pad);
}
html[data-bp~="xs"] .r-v2-audit-event__body {
gap: var(--r-audit-gap);
padding-top: var(--r-audit-title-offset);
}
html[data-bp~="xs"] .r-v2-audit-event__title,
html[data-bp~="xs"] .r-v2-audit-event__detail .r-v2-audit-event__text {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: var(--r-audit-max-lines);
line-clamp: var(--r-audit-max-lines);
white-space: normal;
overflow-wrap: anywhere;
}
html[data-bp~="xs"] .r-v2-audit-event__title {
line-height: var(--r-audit-title-line);
}
html[data-bp~="xs"] .r-v2-audit-event__meta {
flex-wrap: wrap;
gap: var(--r-audit-gap) var(--r-space-3);
line-height: var(--r-audit-meta-line);
}
html[data-bp~="xs"] .r-v2-audit-event__actor,
html[data-bp~="xs"] .r-v2-audit-event__detail {
flex: 0 0 100%;
}
html[data-bp~="xs"] .r-v2-audit-event__detail {
order: -1;
}
/* No basis, so a long device name shortens beside the address instead of
wrapping it onto a line of its own. */
html[data-bp~="xs"] .r-v2-audit-event__device {
flex: 1 1 0;
max-width: max-content;
}
</style>

View File

@@ -0,0 +1,43 @@
// The event log row's geometry, shared by EventLogRow's styles and the list's
// windowing, which has to know every row's height before it renders.
/** A row with its title and details each on one line. */
export const EVENT_ROW_HEIGHT = 62;
/** On a phone, a row stacks its title, detail, author and where from. */
export const PHONE_EVENT_ROW = {
paddingBlock: 8,
/** Drops the title's first line to the middle of the event's icon. */
titleOffset: 4,
titleLine: 19,
metaLine: 17,
gap: 2,
/** The title and the detail each wrap to at most this many lines. */
maxLines: 2,
} as const;
export interface PhoneEventLines {
title: number;
/** 0 when the event has no detail. */
detail: number;
/** Whether it names a device or an address. */
where: boolean;
}
export function phoneEventRowHeight({
title,
detail,
where,
}: PhoneEventLines): number {
const { paddingBlock, titleOffset, titleLine, metaLine, gap } =
PHONE_EVENT_ROW;
const blocks = [title > 0, detail > 0, true, where].filter(Boolean).length;
const lines = detail + 1 + (where ? 1 : 0);
return (
2 * paddingBlock +
titleOffset +
title * titleLine +
lines * metaLine +
(blocks - 1) * gap
);
}

View File

@@ -125,12 +125,12 @@ describe("describeAuditEvent", () => {
it("colors a failure apart from its category", () => {
expect(
describeAuditEvent(event("rom.play", { category: "consumption" })).tone,
).toBe("primary");
).toBe("var(--r-color-brand-primary)");
expect(
describeAuditEvent(
event("auth.login_failed", { category: "security", data: {} }),
).tone,
).toBe("danger");
).toBe("var(--r-color-danger)");
});
it("names a failed sign-in only by an account's own name", () => {

View File

@@ -16,7 +16,7 @@ import { formatPlaytime } from "@/v2/utils/time";
export interface AuditEventView {
icon: string;
/** An RAvatar color: the category's, or danger for something that failed. */
/** A color token: the category's, or danger for something that failed. */
tone: string;
title: string;
detail: string | null;
@@ -374,18 +374,20 @@ const DESCRIBERS: Record<AuditAction, Describer> = {
};
const CATEGORY_TONES: Record<AuditCategory, string> = {
consumption: "primary",
library: "info",
collections: "accent",
operations: "secondary",
security: "warning",
consumption: "var(--r-color-brand-primary)",
library: "var(--r-color-info)",
collections: "var(--r-color-brand-accent)",
operations: "var(--r-color-brand-secondary)",
security: "var(--r-color-warning)",
};
function toneOf(event: AuditEventSchema): string {
if (event.action === "auth.login_failed" || event.data.status === "failed") {
return "danger";
return "var(--r-color-danger)";
}
return event.category ? CATEGORY_TONES[event.category] : "secondary";
return event.category
? CATEGORY_TONES[event.category]
: CATEGORY_TONES.operations;
}
function targetRoute(event: AuditEventSchema): RouteLocationRaw | null {
@@ -411,7 +413,7 @@ function targetRoute(event: AuditEventSchema): RouteLocationRaw | null {
function fallback(event: AuditEventSchema, target: string): AuditEventView {
return {
icon: "mdi-help-circle-outline",
tone: "secondary",
tone: CATEGORY_TONES.operations,
title: [event.action, target].filter(Boolean).join(" "),
detail: null,
to: null,

View File

@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { wrappedLineCount } from "@/v2/utils/textLines";
// Every character is 10px wide.
const measure = (run: string) => run.length * 10;
describe("wrappedLineCount", () => {
it("keeps text that fits on one line", () => {
expect(wrappedLineCount("Signed in", 100, measure)).toBe(1);
});
it("moves the word that doesn't fit to the next line", () => {
expect(wrappedLineCount("Played Metroid today", 140, measure)).toBe(2);
expect(wrappedLineCount("aaaa bbbb cccc dddd", 90, measure)).toBe(2);
expect(wrappedLineCount("aaaa bbbb cccc dddd", 80, measure)).toBe(4);
});
it("breaks a word longer than a line wherever it must", () => {
expect(
wrappedLineCount("不明なユーザ名でのログインに失敗しました", 50, measure),
).toBe(4);
expect(wrappedLineCount("go aaaaaaaaaaaa", 50, measure)).toBe(4);
});
it("counts one line for no text or no room", () => {
expect(wrappedLineCount("", 100, measure)).toBe(1);
expect(wrappedLineCount("Signed in", 0, measure)).toBe(1);
});
});

View File

@@ -0,0 +1,38 @@
/**
* How many lines `text` wraps to in `width` pixels, breaking between words the
* way the browser does, and inside a word only when it can't fit a line alone.
*
* Args:
* measure: The width of a run of text in the font it's set in.
*/
export function wrappedLineCount(
text: string,
width: number,
measure: (run: string) => number,
): number {
if (width <= 0) return 1;
const space = measure(" ");
let lines = 1;
let line = 0;
for (const word of text.split(/\s+/).filter(Boolean)) {
const w = measure(word);
const next = line === 0 ? w : line + space + w;
if (next <= width) {
line = next;
continue;
}
if (line > 0) lines += 1;
const extra = Math.max(0, Math.ceil(w / width) - 1);
lines += extra;
line = w - extra * width;
}
return lines;
}
/** Measures text in a CSS `font`, or null where there's no canvas to do it. */
export function canvasMeasure(font: string): ((run: string) => number) | null {
const context = document.createElement("canvas").getContext("2d");
if (!context) return null;
context.font = font;
return (run) => context.measureText(run).width;
}