Something went wrong. Try again.
Monorepo for Tangled forked from tangled.org/core
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465<script module lang="ts"> import { tv, type VariantProps } from "tailwind-variants"; import { popoverAnchorName, popoverOrigin, type PopoverOrigin } from "#lib/components/ui/popover.svelte.ts";
export const tooltip = tv({ slots: { wrapper: "inline-flex", // overflow-visible undoes the UA stylesheet's `overflow: auto` on [popover], which // would otherwise clip the arrow off at the bubble's padding box bubble: "tooltip-bubble fixed inset-auto z-50 m-none h-fit w-max max-w-64 popover-transition overflow-visible rounded-sm bg-background-emphasis px-xs pt-1.5 pb-2xs typography-paragraph-small text-foreground-inverted shadow-regular" }, variants: { side: { top: {}, right: {}, bottom: {}, left: {} } }, defaultVariants: { side: "top" } });
export type TooltipVariants = VariantProps<typeof tooltip>;
// hovering a second trigger while one tooltip is up should swap them, not stack them. // `popover="hint"` would do this natively but is not widely supported yet, so keep a // module-level singleton the way Dropdown keeps its groups. type ActiveTooltip = { hide: (instant: boolean) => void; bubble: () => HTMLElement | undefined; group: () => boolean; }; let active: ActiveTooltip | undefined;
const SKIP_DELAY = 300; const GROUP_GRACE = 120; const GROUP_TRAVEL = 14; let lastHiddenAt = 0;
const instantly = (node: HTMLElement, action: () => void) => { node.dataset.instant = ""; action(); void getComputedStyle(node).opacity; delete node.dataset.instant; };</script>
<script lang="ts"> import type { Snippet } from "svelte"; import { onMount } from "svelte"; import { popoverExit } from "#lib/popoverExit.ts"; import { CROSSFADE_DURATION, CROSSFADE_EASING, RAIL_DURATION, RAIL_EASING } from "#lib/motion/spring.ts";
interface Props { content: string | Snippet; side?: TooltipVariants["side"]; /** ms to wait before opening on hover. Keyboard focus always opens immediately. */ delay?: number; /** Skip the tooltip entirely — handy when the label is only useful in some states. */ disabled?: boolean; /** Two-way: set it to drive the tooltip yourself, e.g. a transient "Copied!". */ open?: boolean; arrow?: boolean; id?: string; class?: string; bubbleClass?: string; origin?: PopoverOrigin; group?: boolean; children: Snippet; }
let { content, side = "top", delay = 300, disabled = false, open = $bindable(false), arrow = true, id, class: className, bubbleClass, origin, group = false, children }: Props = $props();
const classes = $derived(tooltip({ side })); const fallbackId = $props.id(); const bubbleId = $derived(id ?? fallbackId); // anchor-name has to be a custom ident and unique per instance, so it cannot live in the // stylesheet — derive it from the same id the bubble is labelled with const anchorName = $derived(popoverAnchorName("tooltip", bubbleId));
let wrapperEl = $state<HTMLElement>(); let bubbleEl = $state<HTMLElement>(); let bodyEl = $state<HTMLElement>(); let glides: Animation[] = []; let timer: ReturnType<typeof setTimeout> | undefined;
// The arrow cannot be driven off `side`: position-try flips the bubble to the opposite // edge without touching any attribute, so a preference of "top" can render below the // trigger and the arrow would point away from it. Both the edge the bubble actually // landed on and the arrow's offset along that edge are therefore measured from geometry. // undefined until the first measurement, so `side` stays the honest answer until then let measuredSide = $state<TooltipVariants["side"] | undefined>(); const resolvedSide = $derived(measuredSide ?? side); let arrowOffset = $state(0);
const ARROW_INSET = 8;
const measureArrow = () => { if (!arrow || !bubbleEl || !wrapperEl || bubbleEl.dataset.gliding !== undefined) return; const box = bubbleEl.getBoundingClientRect(); const trigger = wrapperEl.getBoundingClientRect(); if (box.width === 0) return; const style = getComputedStyle(bubbleEl); const width = Number.parseFloat(style.width); const height = Number.parseFloat(style.height); const [originX, originY] = style.transformOrigin.split(" ").map(Number.parseFloat); const [shiftX = 0, shiftY = 0] = style.translate === "none" ? [] : style.translate.split(" ").map(Number.parseFloat); const left = box.left - shiftX - originX * (1 - box.width / width); const top = box.top - shiftY - originY * (1 - box.height / height); const bubble = { left, top, width, height };
const vertical = side === "top" || side === "bottom"; measuredSide = vertical ? bubble.top >= trigger.bottom - 1 ? "bottom" : "top" : bubble.left >= trigger.right - 1 ? "right" : "left";
const along = vertical ? trigger.left + trigger.width / 2 - bubble.left : trigger.top + trigger.height / 2 - bubble.top; const extent = vertical ? bubble.width : bubble.height; arrowOffset = Math.min(Math.max(along, ARROW_INSET), Math.max(extent - ARROW_INSET, ARROW_INSET)) - extent / 2; };
const cancel = () => { clearTimeout(timer); timer = undefined; };
const stopGlides = () => { for (const animation of glides) animation.cancel(); glides = []; };
const glide = (from: DOMRect) => { const bubble = bubbleEl; const body = bodyEl; if (!bubble || !body) return; measureArrow(); const to = bubble.getBoundingClientRect(); body.style.width = `${body.getBoundingClientRect().width}px`; bubble.style.width = `${from.width}px`; bubble.style.height = `${from.height}px`; const start = bubble.getBoundingClientRect(); bubble.style.removeProperty("width"); bubble.style.removeProperty("height");
const vertical = side === "top" || side === "bottom"; const travel = vertical ? Math.sign(to.left + to.width / 2 - (from.left + from.width / 2)) : Math.sign(to.top + to.height / 2 - (from.top + from.height / 2)); bubble.dataset.gliding = ""; glides = [ bubble.animate( { width: [`${from.width}px`, `${to.width}px`], height: [`${from.height}px`, `${to.height}px`], translate: [`${from.left - start.left}px ${from.top - start.top}px`, "0px 0px"] }, { duration: RAIL_DURATION, easing: RAIL_EASING } ), body.animate( { opacity: [0, 1], translate: [ vertical ? `${travel * GROUP_TRAVEL}px 0px` : `0px ${travel * GROUP_TRAVEL}px`, "0px 0px" ] }, { duration: CROSSFADE_DURATION, easing: CROSSFADE_EASING } ) ]; const settle = () => { delete bubble.dataset.gliding; body.style.removeProperty("width"); }; glides[0].finished.then(settle, settle); };
const show = () => { cancel(); if (disabled || !bubbleEl || active === handle) return; const previous = active; const from = group && previous?.group() ? previous.bubble()?.getBoundingClientRect() : undefined; active = handle; previous?.hide(from !== undefined); if (!from) { bubbleEl.showPopover(); return; } const bubble = bubbleEl; instantly(bubble, () => bubble.showPopover()); if (!matchMedia("(prefers-reduced-motion: reduce)").matches) glide(from); };
const hide = (instant = false) => { cancel(); stopGlides(); if (active === handle) active = undefined; const bubble = bubbleEl; if (!bubble) return; if (instant) instantly(bubble, () => bubble.hidePopover()); else bubble.hidePopover(); };
const handle: ActiveTooltip = { hide, bubble: () => bubbleEl, group: () => group };
const leave = () => { if (!group) return hide(); cancel(); timer = setTimeout(hide, GROUP_GRACE); };
const scheduleShow = () => { cancel(); if (disabled || open) return; const instant = delay === 0 || Date.now() - lastHiddenAt < SKIP_DELAY; if (instant) { show(); return; } timer = setTimeout(show, delay); };
const onPointerEnter = (event: PointerEvent) => { // touch has no hover: the tap would open the tooltip and swallow the visual feedback // of whatever was actually tapped if (event.pointerType === "touch") return; scheduleShow(); };
const onClick = () => hide();
const onFocusIn = () => { // no delay on focus: aria-describedby only resolves while the bubble is rendered, so // it has to be up by the time a keyboard user lands on the trigger if (!disabled) show(); };
const onToggle = (event: Event) => { const { newState } = event as ToggleEvent; open = newState === "open"; if (open) return; lastHiddenAt = Date.now(); if (active === handle) active = undefined; };
$effect(() => { if (!bubbleEl) return; if (open) bubbleEl.showPopover(); else bubbleEl.hidePopover(); });
$effect(() => { if (disabled) hide(); });
$effect(() => { if (!open) return; measureArrow();
const onKeydown = (event: KeyboardEvent) => { if (event.key === "Escape") hide(); }; document.addEventListener("keydown", onKeydown); document.addEventListener("scroll", measureArrow, { capture: true, passive: true }); window.addEventListener("resize", measureArrow); return () => { document.removeEventListener("keydown", onKeydown); document.removeEventListener("scroll", measureArrow, { capture: true }); window.removeEventListener("resize", measureArrow); }; });
onMount(() => { const wrapper = wrapperEl; if (!wrapper) return;
wrapper.addEventListener("pointerenter", onPointerEnter); wrapper.addEventListener("pointerleave", leave); wrapper.addEventListener("focusin", onFocusIn); wrapper.addEventListener("focusout", leave); wrapper.addEventListener("click", onClick);
// point aria-describedby at whatever interactive element is inside rather than at the // wrapper span, which AT ignores const target = wrapper.querySelector<HTMLElement>( 'button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])' ) ?? wrapper; const previous = target.getAttribute("aria-describedby"); target.setAttribute("aria-describedby", previous ? `${previous} ${bubbleId}` : bubbleId);
return () => { wrapper.removeEventListener("pointerenter", onPointerEnter); wrapper.removeEventListener("pointerleave", leave); wrapper.removeEventListener("focusin", onFocusIn); wrapper.removeEventListener("focusout", leave); wrapper.removeEventListener("click", onClick); if (previous) target.setAttribute("aria-describedby", previous); else target.removeAttribute("aria-describedby"); cancel(); stopGlides(); if (active === handle) active = undefined; }; });</script>
<span bind:this={wrapperEl} class={classes.wrapper({ class: className })} style="anchor-name: {anchorName}"> {@render children()}</span>
<div bind:this={bubbleEl} id={bubbleId} role="tooltip" popover="manual" data-side={side} data-resolved-side={resolvedSide} style="position-anchor: {anchorName}" class={classes.bubble({ class: bubbleClass })} ontoggle={onToggle} {@attach popoverExit()} {@attach popoverOrigin( () => wrapperEl, () => origin )}> <span bind:this={bodyEl} class="block"> {#if typeof content === "string"} {content} {:else} {@render content()} {/if} </span> {#if arrow} <span class="tooltip-arrow" aria-hidden="true" style:--tooltip-arrow="{arrowOffset}px" ></span> {/if}</div>
<style> /* anchor positioning went Baseline in early 2026; without it the popover falls back to the UA's centred position, same trade-off Dropdown already takes */ @supports (position-area: bottom) and (position-try: flip-block) { .tooltip-bubble { position: absolute; /* the gap between trigger and bubble — margin, because position-area owns inset */ margin: 0.25rem; position-try: flip-block, flip-inline; }
.tooltip-bubble[data-side="top"] { position-area: block-start; }
.tooltip-bubble[data-side="bottom"] { position-area: block-end; }
.tooltip-bubble[data-side="left"] { position-area: inline-start; }
.tooltip-bubble[data-side="right"] { position-area: inline-end; } }
.tooltip-bubble:global([data-instant]) { transition: none; }
.tooltip-bubble:global([data-gliding]):is([data-side="top"], [data-side="bottom"]) { overflow-x: clip; }
.tooltip-bubble:global([data-gliding]):is([data-side="left"], [data-side="right"]) { overflow-y: clip; }
/* the arrow exactly fills the 0.25rem gap, so its tip meets the trigger's edge. */ .tooltip-arrow { position: absolute; background-color: inherit; }
.tooltip-bubble[data-resolved-side="top"] > .tooltip-arrow { top: 100%; left: calc(50% + var(--tooltip-arrow)); width: 0.5rem; height: 0.25rem; translate: -50% 0; clip-path: polygon(50% 100%, 0 0, 100% 0); }
.tooltip-bubble[data-resolved-side="bottom"] > .tooltip-arrow { bottom: 100%; left: calc(50% + var(--tooltip-arrow)); width: 0.5rem; height: 0.25rem; translate: -50% 0; clip-path: polygon(50% 0, 0 100%, 100% 100%); }
.tooltip-bubble[data-resolved-side="left"] > .tooltip-arrow { left: 100%; top: calc(50% + var(--tooltip-arrow)); width: 0.25rem; height: 0.5rem; translate: 0 -50%; clip-path: polygon(100% 50%, 0 0, 0 100%); }
.tooltip-bubble[data-resolved-side="right"] > .tooltip-arrow { right: 100%; top: calc(50% + var(--tooltip-arrow)); width: 0.25rem; height: 0.5rem; translate: 0 -50%; clip-path: polygon(0 50%, 100% 0, 100% 100%); }</style>