fix(admin): clamp tooltips into the viewport

The portal kept cards out of table overflow but nothing kept them on screen:
centred on a fixed-width card, any trigger near an edge lost text -- reported
on Sessions' right-aligned Generate button. The shared Tooltip now measures the
card, clamps it to the viewport, flips below when there is no room above, and
keeps the arrow aimed at the trigger. No more CSS centreing transform, JS owns
the coordinates.

New tooltip-containment.spec.ts (4 tests) asserts the measured rectangle, no
document widening and arrow alignment at wide/narrow/short viewports; verified
it catches the bug by reverting the fix (3 of 4 fail). Full serial e2e: 211
passed, 0 failed.
This commit is contained in:
Lago committed 2026-10-19 21:19:30 +02:00
1 parent 5e13c8ec1d
commit 184449adb6
5 files changed
+250 -8

No files matched your search

+57 -5
View File
@@ -124,13 +124,62 @@ export function Tooltip({ content, title, children }: {
children: ReactNode; children: ReactNode;
}) { }) {
const anchor = useRef<HTMLSpanElement>(null); const anchor = useRef<HTMLSpanElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
const id = useId(); const id = useId();
const [pos, setPos] = useState<{ x: number; y: number } | null>(null); // left/top are the card's real viewport coordinates (the card carries no CSS
// transform), so the clamping below and the rendered position cannot disagree.
const [pos, setPos] = useState<{ left: number; top: number; arrow: number; below: boolean } | null>(null);
const hide = () => setPos(null);
/**
* Compute the card's viewport position so it stays entirely on screen.
*
* It is portal-rendered so no table's `overflow` can clip it, but nothing used
* to keep it inside the *screen*: centred on its trigger, the tooltip on a
* right-aligned button (Sessions' "Generate AI Feedback Summary") ran past the
* right edge and lost half its text. A trigger near the top also has nowhere to
* put the card, so it flips below.
*
* `below` is derived from the card's height rather than passed in, so the
* caller does not have to guess it — which matters because the height is only
* knowable once the card is in the DOM.
*/
const compute = (
w: number, h: number,
trigger: { x: number; top: number; bottom: number },
) => {
const gap = 10;
// Keep this in sync with the `inset` in @keyframes tip-in: the card starts
// 6px lower and slides up, so reserving 6px more keeps a flipped card from
// briefly overlapping the control it describes.
const slide = 6;
const vw = window.innerWidth;
const edge = Math.min(8, Math.max(0, (vw - w) / 2));
let left = trigger.x - w / 2;
if (left + w > vw - edge) left = vw - edge - w;
if (left < edge) left = edge;
// Flip below when there is not enough room above, including the arrow gap.
const below = trigger.top - h - gap - slide < edge;
const top = below ? trigger.bottom + gap : trigger.top - h - gap;
// The arrow tracks the trigger even after the card slides sideways, but
// stays inside the card so the two never look disconnected.
const arrow = Math.max(18, Math.min(trigger.x - left, w - 18));
return { left, top, arrow, below };
};
const show = () => { const show = () => {
const r = anchor.current?.getBoundingClientRect(); const r = anchor.current?.getBoundingClientRect();
if (r) setPos({ x: r.left + r.width / 2, y: r.top }); if (!r) return;
const trigger = { x: r.left + r.width / 2, top: r.top, bottom: r.bottom };
// The card is unmounted between hovers, so its size is unknown until it is
// in the DOM. Mount it at a provisional spot, then measure and correct: two
// passes total, no recursion, nothing that can loop.
setPos(compute(cardRef.current?.offsetWidth || 250, cardRef.current?.offsetHeight || 96, trigger));
requestAnimationFrame(() => {
const card = cardRef.current;
if (card) setPos(compute(card.offsetWidth, card.offsetHeight, trigger));
});
}; };
const hide = () => setPos(null);
// Point the control at the card so screen readers announce the explanation // Point the control at the card so screen readers announce the explanation
// when it is focused (focus also reveals it visually). // when it is focused (focus also reveals it visually).
const child = isValidElement(children) const child = isValidElement(children)
@@ -140,7 +189,10 @@ export function Tooltip({ content, title, children }: {
<span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}> <span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
{child} {child}
{pos && createPortal( {pos && createPortal(
<div className="tip-card" role="tooltip" id={id} style={{ left: pos.x, top: pos.y - 10 }}> <div
className={`tip-card${pos.below ? ' tip-below' : ''}`} role="tooltip" id={id} ref={cardRef}
style={{ left: pos.left, top: pos.top, ['--tip-arrow' as string]: `${pos.arrow}px` }}
>
{title && ( {title && (
<div className="tip-head"> <div className="tip-head">
<span className="tip-ico" aria-hidden="true"> <span className="tip-ico" aria-hidden="true">
@@ -152,7 +204,7 @@ export function Tooltip({ content, title, children }: {
</div> </div>
)} )}
<p>{content}</p> <p>{content}</p>
<span className="tip-arrow" aria-hidden="true" /> <span className="tip-arrow" style={{ left: pos.arrow }} aria-hidden="true" />
</div>, </div>,
document.body, document.body,
)} )}
+14 -3
View File
@@ -205,13 +205,16 @@ body {
.tip-anchor > button:disabled { pointer-events: none; } .tip-anchor > button:disabled { pointer-events: none; }
.tip-anchor:has(> button:disabled) { cursor: not-allowed; } .tip-anchor:has(> button:disabled) { cursor: not-allowed; }
.tip-card { .tip-card {
position: fixed; transform: translate(-50%, -100%); width: 250px; padding: 13px 15px; /* left/top are computed in JS against the viewport, so the card carries no
centring transform — that transform is what made the clamp math lie about
where the card actually was. */
position: fixed; width: 250px; max-width: calc(100vw - 16px); padding: 13px 15px;
background: linear-gradient(135deg, rgba(17,24,39,.97), rgba(31,41,55,.97)); background: linear-gradient(135deg, rgba(17,24,39,.97), rgba(31,41,55,.97));
backdrop-filter: blur(8px); border: 1px solid rgba(213,0,0,.35); border-radius: 14px; backdrop-filter: blur(8px); border: 1px solid rgba(213,0,0,.35); border-radius: 14px;
box-shadow: 0 0 26px rgba(213,0,0,.18), 0 14px 34px rgba(0,0,0,.35); box-shadow: 0 0 26px rgba(213,0,0,.18), 0 14px 34px rgba(0,0,0,.35);
z-index: 120; pointer-events: none; animation: tip-in .18s ease; z-index: 120; pointer-events: none; animation: tip-in .18s ease;
} }
@keyframes tip-in { from { opacity: 0; transform: translate(-50%, calc(-100% + 6px)); } to { opacity: 1; transform: translate(-50%, -100%); } } @keyframes tip-in { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } }
.tip-card .tip-head { display: flex; align-items: center; gap: 9px; margin-bottom: 6px; } .tip-card .tip-head { display: flex; align-items: center; gap: 9px; margin-bottom: 6px; }
.tip-card .tip-head strong { font-size: 13px; font-weight: 700; color: #fff; } .tip-card .tip-head strong { font-size: 13px; font-weight: 700; color: #fff; }
.tip-card .tip-ico { .tip-card .tip-ico {
@@ -220,10 +223,18 @@ body {
} }
.tip-card p { margin: 0; font-size: 12.5px; line-height: 1.5; color: #d1d5db; } .tip-card p { margin: 0; font-size: 12.5px; line-height: 1.5; color: #d1d5db; }
.tip-card .tip-arrow { .tip-card .tip-arrow {
position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%) rotate(45deg); /* left comes from JS (the trigger's centre, clamped inside the card), so the
arrow still points at the control after the card is pushed sideways. */
position: absolute; bottom: -6px; margin-left: -6px; transform: rotate(45deg);
width: 12px; height: 12px; background: rgba(31,41,55,.97); width: 12px; height: 12px; background: rgba(31,41,55,.97);
border-right: 1px solid rgba(213,0,0,.35); border-bottom: 1px solid rgba(213,0,0,.35); border-right: 1px solid rgba(213,0,0,.35); border-bottom: 1px solid rgba(213,0,0,.35);
} }
/* Flipped under a trigger that has no room above it: the arrow moves to the
top edge and points up instead. */
.tip-card.tip-below .tip-arrow {
bottom: auto; top: -6px; border: 0;
border-left: 1px solid rgba(213,0,0,.35); border-top: 1px solid rgba(213,0,0,.35);
}
/* sponsor tiers */ /* sponsor tiers */
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); } .pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; } .pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
+11
View File
@@ -198,6 +198,17 @@ portal so it is never clipped by the table's `overflow: hidden`. The shared badg
renderer lives in `components/BadgeRender.tsx`, used by both the editor and this renderer lives in `components/BadgeRender.tsx`, used by both the editor and this
preview. preview.
> **Portalling is not enough on its own.** It stops an `overflow` ancestor
> clipping the card, but nothing used to keep the card inside the **viewport**: it
> was centred on its trigger with a fixed 250px width, so any tooltip on a
> right-aligned control ran off the right edge — which is exactly what happened to
> Sessions' “Generate AI Feedback Summary”, whose card sat half off screen. The
> component now measures the laid-out card and clamps it to the viewport, flips it
> **below** a trigger that has no room above it, and re-aims the arrow so it still
> points at the control after the card has been pushed sideways. The card carries
> **no CSS transform**: `left`/`top` are its real viewport coordinates, because a
> centring transform makes the clamp arithmetic disagree with what is painted.
### Printing ### Printing
The **Printing** view is the badge-print control center; the queue, stations and The **Printing** view is the badge-print control center; the queue, stations and
+23
View File
@@ -616,3 +616,26 @@ both apps + sidecar) and the verdict fix (`d14e1c2`, admin + sidecar only).
- **Not run against prod**: the browser suites. They provision and delete real - **Not run against prod**: the browser suites. They provision and delete real
contacts/registrations (`checkin-points.spec.ts` deletes by email), which on this contacts/registrations (`checkin-points.spec.ts` deletes by email), which on this
database would collide with imported pretix data. Local only, as before. database would collide with imported pretix data. Local only, as before.
## Post-deploy: tooltip ran off the viewport (user-reported)
The Sessions "Generate AI Feedback Summary" tooltip rendered half off the right
edge. The card is portal-rendered (so tables cannot clip it) but was centred on
its trigger with a fixed 250px width and no viewport clamp — every trigger near a
screen edge overflowed; Sessions' right-aligned toolbar just made it obvious.
Fix in the shared `Tooltip`: measure the laid-out card, clamp `left`/`top` to the
viewport, flip below when there is no room above, and re-aim the arrow at the
trigger after any sideways shift. The card no longer carries a centring
transform — JS owns the final coordinates. All 6 call sites benefit.
- `e2e/tests/tooltip-containment.spec.ts` (4 tests) asserts the measured card
rectangle is inside the viewport, the document never widens, and the arrow
still points at the control — at wide, narrow (700px) and short (260px)
viewports, plus the Registrations "no points" tooltip. **Validated by
temporarily reverting the fix: 3 of 4 fail on the old code.**
- Mock gotcha recorded in the spec: the auth path reads the contact with
`maybeSingle()`, so the `?email=eq.…` route must answer an **object** —
answering with an array silently drops the app to the login screen, which
looks exactly like a broken tooltip.
- Full serial e2e: **211 passed, 0 failed.**
+145
View File
@@ -0,0 +1,145 @@
import { test, expect, type Page, type Route } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
/**
* Tooltips are portal-rendered, which stops a table's `overflow` from clipping
* them — but nothing kept them inside the VIEWPORT. The card was centred on its
* trigger with a fixed width, so every tooltip attached to a right-aligned
* control (Sessions' "Generate AI Feedback Summary", Registrations' points
* explanation) ran off the right edge and its text was unreachable.
*
* These tests assert the measured rectangle of the rendered card, because
* "fully inside the viewport" is the whole requirement and only geometry can
* prove it.
*/
const sessionsEvent = {
id: eventId, name: 'Tooltip Conf', company: 'APPE', is_active: true, location: null,
start_date: '2026-11-01', end_date: '2026-11-01', use_realtime_clock: false, sessionize_endpoint: null,
pretix_organizer: null, pretix_event_slug: null, pretix_api_key: null, last_synced_at: null,
talk_networking_bonus: 2, badge_copies: 1, num_registrations: 1, num_checked_in_registrations: 0,
num_sessions: 1, num_speakers: 1, avg_feedback: null, created_at: 'x',
};
const slot = { id: 's1', event_id: eventId, date: '2026-11-01', start_time: '10:15:00', end_time: '11:00:00', type: 'talk', title: null };
const session = { id: 't1', event_id: eventId, slot_id: 's1', title: 'A Talk With A Very Long Title Indeed', description: 'desc', room: 'Main Stage', level: '300', area: 'Power Apps', session_material: null, is_service_session: false, external_id: 'x' };
const speakerContact = { email: '[email protected]', full_name: 'Ann Speaker', linkedin_url: null, show_email: true, show_linkedin: false, is_admin: false, created_at: 'x' };
async function openAdmin(page: Page, view: 'Sessions' | 'Registrations') {
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session_ = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'r', expires_in: 3600, token_type: 'bearer' };
const contacts = [
{ email: user.email, full_name: 'Admin User', linkedin_url: null, show_email: true, show_linkedin: true, is_admin: true, created_at: 'x' },
speakerContact,
];
// `maybeSingle()` in the auth path expects an OBJECT for the ?email=eq.… lookup;
// answering that with an array makes the admin check fail and the app falls back
// to the login screen, which looks like a broken tooltip rather than a bad mock.
const contactsFor = (u: URL) => (u.searchParams.has('email')
? contacts.find((c) => c.email === decodeURIComponent((u.searchParams.get('email') || '').replace(/^eq./, ''))) ?? null
: contacts);
const registrations = [
{ id: 'r1', event_id: eventId, contact_email: '[email protected]', type: 'attendee', qr_token: 'CV-A', external_id: null, import_source: null, checked_in: false, points: 40, created_at: 'x' },
{ id: 'r2', event_id: eventId, contact_email: '[email protected]', type: 'staff', qr_token: 'CV-B', external_id: null, import_source: null, checked_in: false, points: 0, created_at: 'x' },
];
await page.route('**/auth/v1/**', (r) => r.fulfill({ json: new URL(r.request().url()).pathname.endsWith('/user') ? user : session_ }));
await page.route('**/rest/v1/**', async (route: Route) => {
const u = new URL(route.request().url());
const t = u.pathname.split('/').pop();
if (t === 'contacts') return route.fulfill({ json: contactsFor(u) });
if (t === 'events') return route.fulfill({ json: new URL(route.request().url()).searchParams.has('is_active') ? sessionsEvent : [sessionsEvent] });
if (t === 'slots') return route.fulfill({ json: [slot] });
if (t === 'sessions') return route.fulfill({ json: [session] });
if (t === 'session_speakers') return route.fulfill({ json: [{ session_id: 't1', contact_email: '[email protected]' }] });
if (t === 'checkins') return route.fulfill({ json: [] });
if (t === 'feedback') return route.fulfill({ json: [{ session_id: 't1', rating: 5, comment: 'great', created_at: 'x' }] });
if (t === 'feedback_summaries') return route.fulfill({ json: [] });
if (t === 'registrations') return route.fulfill({ json: registrations });
if (t === 'badge_layouts') return route.fulfill({ json: [] });
return route.fulfill({ json: [] });
});
await page.route('**/sidecar/llm-settings', (r) => r.fulfill({ json: { endpoint: 'https://x.test', model: 'M', has_api_key: true } }));
await page.goto(`${adminUrl}/auth/callback#access_token=${session_.access_token}&refresh_token=r&type=magiclink`);
await expect(page.locator('.nav')).toBeVisible();
await page.locator('.nav').getByRole('button', { name: new RegExp(view) }).click();
}
/** The card must be wholly inside the viewport, with its arrow over the trigger. */
async function expectCardInsideViewport(page: Page, trigger: ReturnType<Page['locator']>) {
const card = page.locator('.tip-card');
await expect(card).toBeVisible();
const box = await card.boundingBox();
const vp = page.viewportSize()!;
expect(box, 'the tooltip card rendered').not.toBeNull();
const b = box!;
expect(b.x, 'card left edge is on screen').toBeGreaterThanOrEqual(0);
expect(b.y, 'card top edge is on screen').toBeGreaterThanOrEqual(0);
expect(b.x + b.width, 'card right edge is on screen').toBeLessThanOrEqual(vp.width);
expect(b.y + b.height, 'card bottom edge is on screen').toBeLessThanOrEqual(vp.height);
// No horizontal page overflow caused by the card.
const doc = await page.evaluate(() => ({ sw: document.documentElement.scrollWidth, cw: document.documentElement.clientWidth }));
expect(doc.sw, 'the card must not widen the document').toBeLessThanOrEqual(doc.cw);
// The arrow must still sit over the card (it tracks the trigger, which may be
// far from the card's centre once the card is pushed sideways).
const arrow = await card.locator('.tip-arrow').boundingBox();
expect(arrow).not.toBeNull();
expect(arrow!.x, 'arrow stays inside the card').toBeGreaterThanOrEqual(b.x);
expect(arrow!.x + arrow!.width, 'arrow stays inside the card').toBeLessThanOrEqual(b.x + b.width);
// And it must not have drifted away from the control it explains.
const tb = await trigger.boundingBox();
const triggerCentre = tb!.x + tb!.width / 2;
expect(Math.abs(arrow!.x + arrow!.width / 2 - triggerCentre), 'arrow points at the trigger').toBeLessThanOrEqual(Math.max(tb!.width / 2, 24));
}
test.describe('Tooltip viewport containment', () => {
test('a right-aligned trigger keeps its tooltip fully on screen', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 800 });
await openAdmin(page, 'Sessions');
const btn = page.getByTestId('generate-all-summaries');
await expect(btn).toBeVisible();
const box = await btn.boundingBox();
// Precondition that makes this test meaningful: the control really is against
// the right edge, which is what used to push the card off screen.
expect(box!.x + box!.width).toBeGreaterThan(1280 - 250);
await btn.hover();
await expectCardInsideViewport(page, btn);
// The point of a tooltip: the explanation is readable.
await expect(page.locator('.tip-card')).toContainText(/one per session that has feedback/i);
});
test('a narrow viewport does not clip it either', async ({ page }) => {
await page.setViewportSize({ width: 700, height: 800 });
await openAdmin(page, 'Sessions');
const btn = page.getByTestId('generate-all-summaries');
await btn.hover();
await expectCardInsideViewport(page, btn);
});
test('a trigger near the top flips the card below instead of off the top', async ({ page }) => {
await page.setViewportSize({ width: 1280, height: 260 });
await openAdmin(page, 'Sessions');
const btn = page.getByTestId('generate-all-summaries');
await expect(btn).toBeVisible();
const tb = await btn.boundingBox();
// Short viewport: there is genuinely not room for the card above the button.
expect(tb!.y).toBeLessThan(200);
await btn.hover();
await expectCardInsideViewport(page, btn);
const after = await btn.boundingBox();
const card = await page.locator('.tip-card').boundingBox();
expect(card!.y, 'card sits below the trigger').toBeGreaterThanOrEqual(after!.y + after!.height - 1);
});
test('the Registrations points tooltip is contained too', async ({ page }) => {
await page.setViewportSize({ width: 1100, height: 800 });
await openAdmin(page, 'Registrations');
const mark = page.getByTestId('points-exempt-r2');
await expect(mark).toBeVisible();
await mark.hover();
await expectCardInsideViewport(page, mark);
await expect(page.locator('.tip-card')).toContainText(/not eligible|staff/i);
});
});