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.
301 lines
11 KiB
TypeScript
301 lines
11 KiB
TypeScript
import { cloneElement, isValidElement, useEffect, useRef, useState, useId, type ReactElement, type ReactNode } from 'react';
|
|
import { createPortal } from 'react-dom';
|
|
import { Filter } from 'lucide-react';
|
|
import { QRCodeSVG } from 'qrcode.react';
|
|
|
|
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
|
|
|
|
export function initials(name: string): string {
|
|
return name
|
|
.split(' ')
|
|
.map((w) => w[0])
|
|
.slice(0, 2)
|
|
.join('')
|
|
.toUpperCase();
|
|
}
|
|
|
|
export function avColor(seed: string): string {
|
|
let h = 0;
|
|
for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
|
return AV_COLORS[h % AV_COLORS.length];
|
|
}
|
|
|
|
export function Avatar({ name, id, size = 40, fs = 14 }: { name: string; id: string; size?: number; fs?: number }) {
|
|
return (
|
|
<span className="avatar" style={{ width: size, height: size, fontSize: fs, background: avColor(id) }}>
|
|
{initials(name)}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
export function Spinner() {
|
|
return <span className="spinner" />;
|
|
}
|
|
|
|
export function Empty({ icon, text }: { icon: string; text: string }) {
|
|
return (
|
|
<div className="empty">
|
|
<div className="big">{icon}</div>
|
|
{text}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Centered modal dialog (desktop-first). */
|
|
export function Modal({
|
|
open,
|
|
onClose,
|
|
title,
|
|
children,
|
|
footer,
|
|
}: {
|
|
open: boolean;
|
|
onClose: () => void;
|
|
title: string;
|
|
children: ReactNode;
|
|
footer?: ReactNode;
|
|
}) {
|
|
if (!open) return null;
|
|
return (
|
|
<div className="backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
|
<div className="modal" role="dialog" aria-modal="true" aria-label={title}>
|
|
<div className="modal-head">
|
|
<h3>{title}</h3>
|
|
<button className="icon-btn" onClick={onClose} aria-label="Close">
|
|
✕
|
|
</button>
|
|
</div>
|
|
<div className="modal-body">{children}</div>
|
|
{footer && <div className="modal-foot">{footer}</div>}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Render a string (e.g. a QR token) as a scannable QR code. */
|
|
export function QrImage({ value, size = 180 }: { value: string; size?: number }) {
|
|
return (
|
|
<div className="qr-frame">
|
|
<QRCodeSVG value={value} size={size} level="M" marginSize={0} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Small colored badge for a registration / sponsor type. */
|
|
export function TypeBadge({ type }: { type: string }) {
|
|
// "service_session" -> "Service Session" (capitalize each word).
|
|
const label = type.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
|
|
return <span className={`pill ${type}`}>{label}</span>;
|
|
}
|
|
|
|
/** A small on/off toggle switch. */
|
|
export function Toggle({
|
|
checked,
|
|
onChange,
|
|
label,
|
|
disabled = false,
|
|
}: {
|
|
checked: boolean;
|
|
onChange: (v: boolean) => void;
|
|
label?: string;
|
|
disabled?: boolean;
|
|
}) {
|
|
return (
|
|
<label className="toggle" title={label}>
|
|
<input type="checkbox" checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
|
|
<span className="track">
|
|
<span className="knob" />
|
|
</span>
|
|
{label && <span className="toggle-lbl">{label}</span>}
|
|
</label>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Hover/focus tooltip rendered through a portal, so it is never clipped by
|
|
* scrollable or `overflow: hidden` ancestors (e.g. data tables). The card
|
|
* visual follows the Uiverse dark-glass tooltip already used in Interfaces,
|
|
* re-themed to the APPE red accent. Wrap any element — including a disabled
|
|
* button, whose own mouse events browsers suppress.
|
|
*/
|
|
export function Tooltip({ content, title, children }: {
|
|
content: ReactNode;
|
|
title?: string;
|
|
children: ReactNode;
|
|
}) {
|
|
const anchor = useRef<HTMLSpanElement>(null);
|
|
const cardRef = useRef<HTMLDivElement>(null);
|
|
const id = useId();
|
|
// 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 r = anchor.current?.getBoundingClientRect();
|
|
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));
|
|
});
|
|
};
|
|
// Point the control at the card so screen readers announce the explanation
|
|
// when it is focused (focus also reveals it visually).
|
|
const child = isValidElement(children)
|
|
? cloneElement(children as ReactElement<{ 'aria-describedby'?: string }>, { 'aria-describedby': id })
|
|
: children;
|
|
return (
|
|
<span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
|
|
{child}
|
|
{pos && createPortal(
|
|
<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 && (
|
|
<div className="tip-head">
|
|
<span className="tip-ico" aria-hidden="true">
|
|
<svg viewBox="0 0 20 20" fill="currentColor" width="15" height="15">
|
|
<path clipRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" fillRule="evenodd" />
|
|
</svg>
|
|
</span>
|
|
<strong>{title}</strong>
|
|
</div>
|
|
)}
|
|
<p>{content}</p>
|
|
<span className="tip-arrow" style={{ left: pos.arrow }} aria-hidden="true" />
|
|
</div>,
|
|
document.body,
|
|
)}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/** One selectable value inside a `ColumnFilter`, with a live result count. */
|
|
export interface ColumnFilterOption {
|
|
value: string;
|
|
label: string;
|
|
count: number;
|
|
}
|
|
|
|
/**
|
|
* Excel-style multi-select filter for a table column. Rendered through a portal
|
|
* so the dropdown is never clipped by the table's `overflow: hidden`. An empty
|
|
* selection means "no filter" (everything matches).
|
|
*/
|
|
export function ColumnFilter({ label, options, selected, onChange }: {
|
|
label: string;
|
|
options: ColumnFilterOption[];
|
|
selected: string[];
|
|
onChange: (next: string[]) => void;
|
|
}) {
|
|
const btnRef = useRef<HTMLButtonElement>(null);
|
|
const popRef = useRef<HTMLDivElement>(null);
|
|
const [open, setOpen] = useState(false);
|
|
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
|
|
const active = selected.length > 0;
|
|
|
|
const toggleOpen = () => {
|
|
if (!open) {
|
|
const r = btnRef.current?.getBoundingClientRect();
|
|
if (r) setPos({ left: Math.min(Math.max(8, r.left), window.innerWidth - 240), top: r.bottom + 6 });
|
|
}
|
|
setOpen((o) => !o);
|
|
};
|
|
const toggleValue = (value: string) =>
|
|
onChange(selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
const onDown = (e: MouseEvent) => {
|
|
const t = e.target as Node;
|
|
if (popRef.current?.contains(t) || btnRef.current?.contains(t)) return;
|
|
setOpen(false);
|
|
};
|
|
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
|
|
const onScroll = () => setOpen(false);
|
|
window.addEventListener('mousedown', onDown);
|
|
window.addEventListener('keydown', onKey);
|
|
window.addEventListener('scroll', onScroll, true);
|
|
return () => {
|
|
window.removeEventListener('mousedown', onDown);
|
|
window.removeEventListener('keydown', onKey);
|
|
window.removeEventListener('scroll', onScroll, true);
|
|
};
|
|
}, [open]);
|
|
|
|
return (
|
|
<span className="colfilter">
|
|
<button
|
|
ref={btnRef}
|
|
type="button"
|
|
className={`colfilter-btn ${active ? 'on' : ''}`}
|
|
onClick={toggleOpen}
|
|
aria-label={`Filter ${label}`}
|
|
aria-expanded={open}
|
|
title={`Filter ${label}`}
|
|
>
|
|
<Filter size={13} aria-hidden="true" />
|
|
{active && <span className="colfilter-count">{selected.length}</span>}
|
|
</button>
|
|
{open && pos && createPortal(
|
|
<div className="colfilter-pop" ref={popRef} role="group" aria-label={`Filter ${label}`} style={{ left: pos.left, top: pos.top }}>
|
|
<div className="colfilter-head">
|
|
<strong>{label}</strong>
|
|
{active && <button type="button" className="colfilter-clear" onClick={() => onChange([])}>Clear</button>}
|
|
</div>
|
|
{options.map((o) => (
|
|
<label key={o.value} className="colfilter-opt">
|
|
<input type="checkbox" checked={selected.includes(o.value)} onChange={() => toggleValue(o.value)} />
|
|
<span className="lbl">{o.label}</span>
|
|
<span className="cnt">{o.count}</span>
|
|
</label>
|
|
))}
|
|
</div>,
|
|
document.body,
|
|
)}
|
|
</span>
|
|
);
|
|
}
|