feat: migrate Toast and Table with reviewed state focus and SSR contracts

This commit is contained in:
maoyingjie
2026-10-24 07:19:26 +08:00
parent 0cfe7b6195
commit ed41af5294
95 changed files with 9358 additions and 8 deletions
+289
View File
@@ -0,0 +1,289 @@
<script lang="ts">
import {
type VNodeChild,
computed,
normalizeStyle,
type StyleValue,
defineComponent,
h,
inject,
mergeProps,
onBeforeUnmount,
onMounted,
onUpdated,
provide,
ref,
useAttrs,
type PropType,
} from "vue";
import { toastVariants, type ToastVariants } from "@heroui-vue/styles";
import { toastContextKey, toastItemContextKey } from "./context";
import ToastIndicator from "./ToastIndicator.vue";
import ToastTitle from "./ToastTitle.vue";
import ToastDescription from "./ToastDescription.vue";
import ToastActionButton from "./ToastActionButton.vue";
import ToastContent from "./ToastContent.vue";
import ToastCloseButton from "./ToastCloseButton.vue";
import Spinner from "../spinner/Spinner.vue";
import type { ToastContentValue } from "./toast-queue";
function renderDefaultContent(content: ToastContentValue, close: () => void) {
const { title, description, isLoading, indicator, variant, actionProps } =
content;
const nodes: VNodeChild[] = [];
if (indicator === null) {
// explicit hide
} else if (isLoading) {
nodes.push(
h(
"div",
{ class: "hv-toast__indicator", "data-slot": "toast-indicator" },
[h(Spinner, { size: "sm" })],
),
);
} else if (indicator !== undefined) {
nodes.push(
h(
"div",
{ class: "hv-toast__indicator", "data-slot": "toast-indicator" },
[indicator as VNodeChild],
),
);
} else {
nodes.push(h(ToastIndicator, { variant: (variant as never) ?? "default" }));
}
const text: VNodeChild[] = [];
if (title !== undefined && title !== null && title !== "") {
text.push(h(ToastTitle, () => title));
}
if (description !== undefined && description !== null && description !== "") {
text.push(h(ToastDescription, () => description));
}
nodes.push(h(ToastContent, () => text));
if (actionProps) {
const ap = actionProps as Record<string, unknown> & {
label?: string;
onClick?: (e: MouseEvent) => void;
};
const { label, onClick: userOnClick, ...rest } = ap;
nodes.push(
h(
ToastActionButton,
mergeProps(
rest,
{ onClick: userOnClick },
{
onClick: (event: MouseEvent) => {
if (!event.defaultPrevented) close();
},
},
),
() => label ?? "OK",
),
);
}
nodes.push(h(ToastCloseButton, { onClick: close }));
return nodes;
}
export default defineComponent({
name: "Toast",
inheritAttrs: false,
props: {
toastKey: { type: String, required: true },
scaleFactor: { type: Number, default: undefined },
index: { type: Number, required: true },
content: {
type: Object as PropType<ToastContentValue>,
default: () => ({}),
},
placement: {
type: String as PropType<ToastVariants["placement"]>,
default: undefined,
},
variant: {
type: String as PropType<ToastVariants["variant"]>,
default: undefined,
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
const el = ref<HTMLElement | null>(null);
const isEntering = ref(true);
let enterFrame = 0;
let innerFrame = 0;
let observer: ResizeObserver | undefined;
function measure() {
const node = el.value;
if (!node || !ctx) return;
// Read natural content height even when a collapsed card borrows the
// front card's height. Restore before paint; only accepted height is state.
const previous = node.style.height;
node.style.height = "auto";
const height = node.offsetHeight;
node.style.height = previous;
if (height > 0) ctx.onToastHeightChange(props.toastKey, height);
}
onUpdated(() => {
measure();
if (observer && el.value) {
observer.disconnect();
observer.observe(el.value);
for (const child of el.value.children) observer.observe(child);
}
});
onMounted(() => {
measure();
if (typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(measure);
if (el.value) {
observer.observe(el.value);
for (const child of el.value.children) observer.observe(child);
}
}
enterFrame = requestAnimationFrame(() => {
innerFrame = requestAnimationFrame(() => {
isEntering.value = false;
});
});
});
onBeforeUnmount(() => {
observer?.disconnect();
cancelAnimationFrame(enterFrame);
cancelAnimationFrame(innerFrame);
ctx?.registerToast(props.toastKey, null);
ctx?.onToastHeightRemove(props.toastKey);
});
const isExiting = computed(
() => ctx?.exitingKeys.value.has(props.toastKey) ?? false,
);
const list = computed(() => ctx?.toasts.value ?? []);
const layoutToasts = computed(() => {
const exiting = ctx?.exitingKeys.value;
if (!exiting || exiting.size === 0) return list.value;
return list.value.filter(
(t) => !exiting.has(t.key) || t.key === props.toastKey,
);
});
const index = computed(() =>
layoutToasts.value.findIndex((t) => t.key === props.toastKey),
);
const fullIndex = computed(() =>
list.value.findIndex((t) => t.key === props.toastKey),
);
const isFrontmost = computed(() => index.value <= 0);
const isHidden = computed(
() =>
!isExiting.value && index.value >= (ctx?.maxVisibleToasts.value ?? 3),
);
const variant = computed(
() =>
props.variant ??
(props.content.variant as ToastVariants["variant"] | undefined) ??
"default",
);
const placement = computed(
() => props.placement ?? ctx?.placement.value ?? "bottom",
);
provide(toastItemContextKey, {
toastKey: computed(() => props.toastKey),
isExiting,
isFrontmost,
isHidden,
isExpanded: computed(() => ctx?.isExpanded.value ?? false),
index,
});
function setEl(node: unknown) {
el.value = (node as HTMLElement) ?? null;
ctx?.registerToast(props.toastKey, el.value);
if (el.value && ctx) {
measure();
}
}
const stackingStyle = computed(() => {
const gap = ctx?.gap.value ?? 12;
const scaleFactor = props.scaleFactor ?? ctx?.scaleFactor.value ?? 0.05;
const heights = ctx?.heightsByKey.value ?? {};
const frontHeight =
heights[layoutToasts.value[0]?.key ?? ""] ??
el.value?.offsetHeight ??
0;
let heightsBefore = 0;
for (let i = 0; i < index.value; i++) {
heightsBefore +=
heights[layoutToasts.value[i]?.key ?? ""] ?? frontHeight;
}
return {
"--offset-collapsed": `${index.value * gap}px`,
"--offset-expanded": `${heightsBefore + index.value * gap}px`,
"--scale-collapsed": `${1 - index.value * scaleFactor}`,
"--front-height": `${frontHeight}px`,
"--toast-height": heights[props.toastKey]
? `${heights[props.toastKey]}px`
: undefined,
zIndex: isExiting.value ? 0 : list.value.length - fullIndex.value,
} as Record<string, string | number | undefined>;
});
function render() {
return h(
"div",
{
...attrs,
ref: setEl,
class: [
toastVariants({
placement: placement.value as never,
variant: variant.value,
}).toast(),
attrs.class,
],
style: normalizeStyle([
stackingStyle.value,
attrs.style as StyleValue,
]),
"data-entering": isEntering.value || undefined,
"data-exiting": isExiting.value || undefined,
"data-expanded": (ctx?.isExpanded.value ?? false) || undefined,
"data-frontmost": isFrontmost.value || undefined,
"data-hidden": isHidden.value || undefined,
"data-index": index.value,
"data-placement": placement.value,
"data-slot": "toast",
role: "status",
tabindex:
isFrontmost.value ||
((ctx?.isExpanded.value ?? false) &&
!isHidden.value &&
!isExiting.value)
? 0
: -1,
inert:
isHidden.value ||
isExiting.value ||
(!isFrontmost.value && !ctx?.isExpanded.value)
? true
: undefined,
"aria-hidden": isHidden.value || isExiting.value ? "true" : undefined,
},
slots.default
? slots.default({
toast: props.content,
close: () => ctx?.close(props.toastKey),
})
: renderDefaultContent(props.content, () =>
ctx?.close(props.toastKey),
),
);
}
return render;
},
});
</script>
@@ -0,0 +1,36 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs, type PropType } from "vue";
import type { ButtonVariants } from "@heroui-vue/styles";
import Button from "../button/Button.vue";
import { toastContextKey } from "./context";
export default defineComponent({
name: "ToastActionButton",
inheritAttrs: false,
props: {
isDisabled: { type: Boolean, default: false },
variant: {
type: String as PropType<ButtonVariants["variant"]>,
default: "secondary",
},
size: { type: String as PropType<ButtonVariants["size"]>, default: "sm" },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
return () =>
h(
Button,
{
...attrs,
variant: props.variant as never,
size: props.size as never,
isDisabled: props.isDisabled,
class: [ctx?.slots.value.action(), attrs.class],
"data-slot": "toast-action-button",
},
slots,
);
},
});
</script>
@@ -0,0 +1,28 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import CloseButton from "../close-button/CloseButton.vue";
import { toastContextKey } from "./context";
export default defineComponent({
name: "ToastCloseButton",
inheritAttrs: false,
props: {
isDisabled: { type: Boolean, default: false },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
return () =>
h(
CloseButton,
{
...attrs,
isDisabled: props.isDisabled,
class: [ctx?.slots.value.close(), attrs.class],
"data-slot": "toast-close",
},
slots,
);
},
});
</script>
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { toastContextKey } from "./context";
export default defineComponent({
name: "ToastContent",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.content(), attrs.class],
"data-slot": "toast-content",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,25 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { toastContextKey } from "./context";
export default defineComponent({
name: "ToastDescription",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.description(), attrs.class],
"data-slot": "toast-description",
slot: "description",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,49 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs, type PropType } from "vue";
import type { ToastVariants } from "@heroui-vue/styles";
import { toastContextKey } from "./context";
import {
ToastDangerIcon,
ToastInfoIcon,
ToastSuccessIcon,
ToastWarningIcon,
} from "./icons";
export default defineComponent({
name: "ToastIndicator",
inheritAttrs: false,
props: {
variant: {
type: String as PropType<ToastVariants["variant"]>,
default: "default",
},
as: { type: String, default: "div" },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
function defaultIcon() {
switch (props.variant) {
case "success":
return h(ToastSuccessIcon, { "data-slot": "toast-default-icon" });
case "warning":
return h(ToastWarningIcon, { "data-slot": "toast-default-icon" });
case "danger":
return h(ToastDangerIcon, { "data-slot": "toast-default-icon" });
default:
return h(ToastInfoIcon, { "data-slot": "toast-default-icon" });
}
}
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.indicator(), attrs.class],
"data-slot": "toast-indicator",
},
slots.default?.() ?? [defaultIcon()],
);
},
});
</script>
@@ -0,0 +1,390 @@
<script lang="ts">
import {
Teleport,
computed,
normalizeStyle,
type StyleValue,
defineComponent,
h,
onBeforeUnmount,
onMounted,
nextTick,
provide,
ref,
shallowRef,
useAttrs,
watch,
type PropType,
} from "vue";
import { toastVariants, type ToastVariants } from "@heroui-vue/styles";
import {
DEFAULT_GAP,
DEFAULT_HOTKEY,
DEFAULT_MAX_VISIBLE_TOAST,
DEFAULT_SCALE_FACTOR,
DEFAULT_TOAST_WIDTH,
} from "./constants";
import {
ToastQueue,
createToastFunction,
type QueuedToast,
type ToastContentValue,
} from "./toast-queue";
import { toastContextKey } from "./context";
import { toastQueue } from "./toast";
import Toast from "./Toast.vue";
const MODIFIER_PROPS = ["altKey", "ctrlKey", "metaKey", "shiftKey"] as const;
export default defineComponent({
name: "ToastProvider",
inheritAttrs: false,
props: {
toastClass: { type: String, default: undefined },
gap: { type: Number, default: DEFAULT_GAP },
hotkey: {
type: Array as PropType<string[]>,
default: () => [...DEFAULT_HOTKEY],
},
isExpanded: { type: Boolean, default: false },
maxVisibleToasts: { type: Number, default: undefined },
placement: {
type: String as PropType<ToastVariants["placement"]>,
default: "bottom",
},
scaleFactor: { type: Number, default: DEFAULT_SCALE_FACTOR },
width: {
type: [Number, String] as PropType<number | string>,
default: DEFAULT_TOAST_WIDTH,
},
queue: {
type: Object as PropType<ToastQueue<ToastContentValue>>,
default: undefined,
},
/** Teleport target; omit to render in place (e.g. inside scoped demos). */
to: {
type: [String, Object] as PropType<string | HTMLElement>,
default: undefined,
},
},
setup(props, { slots, expose }) {
const attrs = useAttrs();
const toastNodes = new Map<string, HTMLElement>();
const hoverReason = Symbol("toast-hover"),
hiddenReason = Symbol("toast-hidden");
// Never render another server request's module singleton. Pass a queue
// created per request to SSR notifications explicitly.
const defaultQueue =
typeof window === "undefined"
? new ToastQueue<ToastContentValue>()
: toastQueue;
let previousFocus: HTMLElement | null = null;
// Single source of truth for the active queue; every action (render,
// close, pause, expose) must go through this ref so swaps stay coherent.
const activeQueue = shallowRef<ToastQueue<ToastContentValue>>(
props.queue ?? defaultQueue,
);
const toastList = shallowRef([...activeQueue.value.visibleToasts]);
const exitingKeys = shallowRef(activeQueue.value.getExitingKeys());
let unsubscribe = activeQueue.value.subscribe(() => {
toastList.value = [...activeQueue.value.visibleToasts];
});
let unsubscribeExiting = activeQueue.value.subscribeExiting(() => {
exitingKeys.value = activeQueue.value.getExitingKeys();
});
watch(
() => props.queue,
(next) => {
const prev = activeQueue.value;
unsubscribe();
unsubscribeExiting();
// Release this provider's pause reasons from the old queue.
prev.resumeTimers(hoverReason);
prev.resumeTimers(hiddenReason);
const q = next ?? defaultQueue;
activeQueue.value = q;
toastList.value = [...q.visibleToasts];
exitingKeys.value = q.getExitingKeys();
unsubscribe = q.subscribe(() => {
toastList.value = [...q.visibleToasts];
});
unsubscribeExiting = q.subscribeExiting(() => {
exitingKeys.value = q.getExitingKeys();
});
// Re-apply current pause state to the new queue.
if (typeof document !== "undefined" && document.hidden)
q.suspendTimers(hiddenReason);
if (isPointerOrFocusWithin.value) q.suspendTimers(hoverReason);
heightsByKey.value = {};
},
);
onBeforeUnmount(() => {
unsubscribe();
unsubscribeExiting();
activeQueue.value.resumeTimers(hoverReason);
activeQueue.value.resumeTimers(hiddenReason);
});
const heightsByKey = ref<Record<string, number>>({});
const regionEl = ref<HTMLElement | null>(null);
const isPointerOrFocusWithin = ref(false);
const pointerWithin = ref(false);
let heroToast: ReturnType<typeof createToastFunction> | undefined;
const slotsComputed = computed(() =>
toastVariants({ placement: props.placement }),
);
const isExpanded = computed(
() => props.isExpanded || isPointerOrFocusWithin.value,
);
const toasts = toastList;
const visibleLimit = computed(() =>
Math.max(
1,
props.maxVisibleToasts ??
activeQueue.value.maxVisibleToasts ??
DEFAULT_MAX_VISIBLE_TOAST,
),
);
provide(toastContextKey, {
slots: slotsComputed,
placement: computed(() => props.placement),
gap: computed(() => props.gap),
scaleFactor: computed(() => props.scaleFactor),
maxVisibleToasts: visibleLimit,
isExpanded,
heightsByKey: computed(() => heightsByKey.value),
exitingKeys,
toasts: computed(() => toastList.value),
queue: activeQueue,
onToastHeightChange(key, height) {
if (heightsByKey.value[key] === height) return;
heightsByKey.value = { ...heightsByKey.value, [key]: height };
},
onToastHeightRemove(key) {
if (!(key in heightsByKey.value)) return;
const next = { ...heightsByKey.value };
delete next[key];
heightsByKey.value = next;
},
registerToast(key, node) {
if (node) toastNodes.set(key, node);
else toastNodes.delete(key);
},
close: (key) => activeQueue.value.close(key),
});
watch(
[toastList, exitingKeys, visibleLimit],
() => {
if (typeof document === "undefined") return;
const focused = document.activeElement as HTMLElement | null;
const card = focused?.closest<HTMLElement>('[data-slot="toast"]');
if (!card || !regionEl.value?.contains(card)) return;
const key = [...toastNodes].find(([, node]) => node === card)?.[0];
const position = toastList.value.findIndex((t) => t.key === key);
if (
position >= 0 &&
position < visibleLimit.value &&
!exitingKeys.value.has(key!)
)
return;
void nextTick(() => {
const remaining = regionEl.value?.querySelector<HTMLElement>(
'[data-slot="toast"]:not([inert])',
);
if (remaining) remaining.focus();
else if (previousFocus?.isConnected) previousFocus.focus();
collapseIfOutside();
});
},
{ flush: "pre" },
);
function collapseIfOutside() {
if (
!pointerWithin.value &&
!(regionEl.value?.contains(document.activeElement) ?? false)
) {
isPointerOrFocusWithin.value = false;
if (!document.hidden) activeQueue.value.resumeTimers(hoverReason);
}
}
function onPointerEnter(event: PointerEvent) {
if (event.pointerType === "touch") return;
pointerWithin.value = true;
isPointerOrFocusWithin.value = true;
activeQueue.value.suspendTimers(hoverReason);
}
function onPointerLeave(event: PointerEvent) {
if (event.pointerType === "touch") return;
pointerWithin.value = false;
collapseIfOutside();
}
function onFocusIn(event: FocusEvent) {
if (
event.relatedTarget instanceof HTMLElement &&
!regionEl.value?.contains(event.relatedTarget)
)
previousFocus = event.relatedTarget;
isPointerOrFocusWithin.value = true;
activeQueue.value.suspendTimers(hoverReason);
}
function onFocusOut(event: FocusEvent) {
if (
event.relatedTarget instanceof Node &&
regionEl.value?.contains(event.relatedTarget)
) {
return;
}
void nextTick(collapseIfOutside);
}
function onGlobalPointerOver(event: PointerEvent) {
if (event.pointerType === "touch") return;
if (regionEl.value?.contains(event.target as Node)) return;
pointerWithin.value = false;
collapseIfOutside();
}
function onRegionKeyDown(event: KeyboardEvent) {
if (event.key !== "Escape") return;
if (regionEl.value?.contains(document.activeElement)) {
previousFocus?.isConnected
? previousFocus.focus()
: (document.activeElement as HTMLElement).blur();
}
pointerWithin.value = false;
isPointerOrFocusWithin.value = false;
}
function onDocumentKeyDown(event: KeyboardEvent) {
const hotkey = props.hotkey;
if (
event.defaultPrevented ||
!hotkey ||
hotkey.length === 0 ||
!toastList.value.some((t) => !exitingKeys.value.has(t.key))
)
return;
const hasExpectedModifiers = MODIFIER_PROPS.every(
(modifier) =>
(event as unknown as Record<string, boolean>)[modifier] ===
hotkey.includes(modifier),
);
const hasExpectedCodes = hotkey.every(
(key) =>
(MODIFIER_PROPS as readonly string[]).includes(key) ||
event.code === key,
);
if (!hasExpectedModifiers || !hasExpectedCodes) return;
event.preventDefault();
if (
document.activeElement instanceof HTMLElement &&
!regionEl.value?.contains(document.activeElement)
)
previousFocus = document.activeElement;
regionEl.value
?.querySelector<HTMLElement>('[data-slot="toast"]:not([inert])')
?.focus();
}
function onVisibility() {
if (document.hidden) activeQueue.value.suspendTimers(hiddenReason);
else activeQueue.value.resumeTimers(hiddenReason);
}
onMounted(() => {
document.addEventListener("visibilitychange", onVisibility);
onVisibility();
const node = regionEl.value;
if (!node) return;
node.addEventListener("pointerenter", onPointerEnter);
node.addEventListener("pointermove", onPointerEnter);
node.addEventListener("pointerleave", onPointerLeave);
node.addEventListener("focusin", onFocusIn);
node.addEventListener("focusout", onFocusOut);
node.addEventListener("keydown", onRegionKeyDown);
document.addEventListener("pointerover", onGlobalPointerOver, true);
document.addEventListener("keydown", onDocumentKeyDown);
});
onBeforeUnmount(() => {
activeQueue.value.resumeTimers(hiddenReason);
activeQueue.value.resumeTimers(hoverReason);
document.removeEventListener("visibilitychange", onVisibility);
const node = regionEl.value;
node?.removeEventListener("pointerenter", onPointerEnter);
node?.removeEventListener("pointermove", onPointerEnter);
node?.removeEventListener("pointerleave", onPointerLeave);
node?.removeEventListener("focusin", onFocusIn);
node?.removeEventListener("focusout", onFocusOut);
node?.removeEventListener("keydown", onRegionKeyDown);
document.removeEventListener("pointerover", onGlobalPointerOver, true);
document.removeEventListener("keydown", onDocumentKeyDown);
});
/** Imperative API matching the default `toast` helper. */
function api() {
// Bind to the *current* queue so a swapped provider keeps working.
heroToast = createToastFunction(activeQueue.value);
return heroToast;
}
expose({
queue: activeQueue,
toast: api,
});
function render() {
const list = toasts.value;
const region = renderRegion(list);
return props.to ? h(Teleport, { to: props.to }, [region]) : region;
}
function renderRegion(list: QueuedToast<ToastContentValue>[]) {
const widthStyle =
typeof props.width === "number"
? `${props.width}px`
: (props.width as string);
return h(
"div",
{
...attrs,
ref: (el: unknown) => {
regionEl.value = (el as HTMLElement) ?? null;
},
class: [slotsComputed.value.region(), attrs.class],
style: normalizeStyle([
{ "--toast-width": widthStyle, "--gap": `${props.gap}px` },
attrs.style as StyleValue,
]),
tabIndex: -1,
"data-slot": "toast-region",
role: attrs.role ?? "region",
"aria-label": attrs["aria-label"] ?? "Notifications",
},
list.map((toast, index) =>
h(
Toast,
{
key: toast.key,
toastKey: toast.key,
class: props.toastClass,
index,
content: toast.content,
},
slots.default
? () =>
slots.default?.({
toast: toast.content,
close: () => activeQueue.value.close(toast.key),
})
: undefined,
),
),
);
}
return render;
},
});
</script>
@@ -0,0 +1,25 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { toastContextKey } from "./context";
export default defineComponent({
name: "ToastTitle",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(toastContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.title(), attrs.class],
"data-slot": "toast-title",
slot: "title",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,20 @@
// Gap between toasts in pixels.
export const DEFAULT_GAP = 12;
// Visual cap on rendered toasts; older ones fade out but keep running.
export const DEFAULT_MAX_VISIBLE_TOAST = 3;
// How much each toast behind the front one scales down.
export const DEFAULT_SCALE_FACTOR = 0.05;
// Toast width in pixels.
export const DEFAULT_TOAST_WIDTH = 460;
// Auto-dismiss timeout in milliseconds.
export const DEFAULT_TOAST_TIMEOUT = 4000;
// How long a closing toast stays mounted for its exit animation, in milliseconds.
export const DEFAULT_EXIT_DURATION = 300;
// Modifiers match KeyboardEvent boolean props; other keys match event.code.
export const DEFAULT_HOTKEY: string[] = ["altKey", "KeyT"];
@@ -0,0 +1,40 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { toastVariants } from "@heroui-vue/styles";
import type { ToastQueue, ToastContentValue } from "./toast-queue";
export type ToastSlots = ReturnType<typeof toastVariants>;
export interface ToastContextValue {
slots: ComputedRef<ToastSlots>;
placement: ComputedRef<string>;
gap: ComputedRef<number>;
scaleFactor: ComputedRef<number>;
maxVisibleToasts: ComputedRef<number>;
isExpanded: ComputedRef<boolean>;
heightsByKey: ComputedRef<Record<string, number>>;
exitingKeys: ComputedRef<ReadonlySet<string>> | Ref<ReadonlySet<string>>;
/** Reactive snapshot of the queue's visible toasts. */
toasts:
| ComputedRef<ToastQueue<ToastContentValue>["visibleToasts"]>
| Ref<ToastQueue<ToastContentValue>["visibleToasts"]>;
queue: Ref<ToastQueue<ToastContentValue>>;
onToastHeightChange: (key: string, height: number) => void;
onToastHeightRemove: (key: string) => void;
registerToast: (key: string, node: HTMLElement | null) => void;
close: (key: string) => void;
}
export const toastContextKey: InjectionKey<ToastContextValue> =
Symbol("hv-toast");
export interface ToastItemContextValue {
toastKey: Ref<string>;
isExiting: ComputedRef<boolean>;
isFrontmost: ComputedRef<boolean>;
isHidden: ComputedRef<boolean>;
isExpanded: ComputedRef<boolean>;
index: ComputedRef<number>;
}
export const toastItemContextKey: InjectionKey<ToastItemContextValue> =
Symbol("hv-toast-item");
@@ -0,0 +1,50 @@
/** Baseline status icons from HeroUI icons.tsx (Apache-2.0). */
import { defineComponent, h } from "vue";
function icon(name: string, d: string) {
return defineComponent({
name,
inheritAttrs: false,
setup(_, { attrs }) {
return () =>
h(
"svg",
{
...attrs,
"aria-hidden": "true",
fill: "none",
height: "16",
role: "presentation",
viewBox: "0 0 16 16",
width: "16",
xmlns: "http://www.w3.org/2000/svg",
},
[
h("path", {
"clip-rule": "evenodd",
d,
fill: "currentColor",
"fill-rule": "evenodd",
}),
],
);
},
});
}
export const ToastInfoIcon = icon(
"ToastInfoIcon",
"M8 13.5a5.5 5.5 0 1 0 0-11a5.5 5.5 0 0 0 0 11M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m1-9.5a1 1 0 1 1-2 0a1 1 0 0 1 2 0m-.25 3a.75.75 0 0 0-1.5 0V11a.75.75 0 0 0 1.5 0z",
);
export const ToastWarningIcon = icon(
"ToastWarningIcon",
"M7.134 2.994L2.217 11.5a1 1 0 0 0 .866 1.5h9.834a1 1 0 0 0 .866-1.5L8.866 2.993a1 1 0 0 0-1.732 0m3.03-.75c-.962-1.665-3.366-1.665-4.329 0L.918 10.749c-.963 1.666.24 3.751 2.165 3.751h9.834c1.925 0 3.128-2.085 2.164-3.751zM8 5a.75.75 0 0 1 .75.75v2a.75.75 0 0 1-1.5 0v-2A.75.75 0 0 1 8 5m1 5.75a1 1 0 1 1-2 0a1 1 0 0 1 2 0",
);
export const ToastDangerIcon = icon(
"ToastDangerIcon",
"M8 13.5a5.5 5.5 0 1 0 0-11a5.5 5.5 0 0 0 0 11M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m1-4.5a1 1 0 1 1-2 0a1 1 0 0 1 2 0M8.75 5a.75.75 0 0 0-1.5 0v2.5a.75.75 0 0 0 1.5 0z",
);
export const ToastSuccessIcon = icon(
"ToastSuccessIcon",
"M13.5 8a5.5 5.5 0 1 1-11 0a5.5 5.5 0 0 1 11 0M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0m-3.9-1.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z",
);
@@ -0,0 +1,440 @@
/**
* Toast queue — HeroUI contract (add/update/close/clear, pause/resume,
* exit-aware unmount, promise). Self-contained timers; no second countdown.
*/
import type { VNodeChild } from "vue";
import type { ButtonProps } from "../../types";
import {
DEFAULT_EXIT_DURATION,
DEFAULT_TOAST_TIMEOUT,
DEFAULT_MAX_VISIBLE_TOAST,
} from "./constants";
export interface ToastQueueOptions {
/** How long a closing toast stays mounted for its exit animation (ms). @default 300 */
exitDuration?: number;
/** Visual cap on rendered toasts (older stay in the queue). @default 3 */
maxVisibleToasts?: number;
/** Wraps state updates (e.g. document.startViewTransition()). */
wrapUpdate?: (fn: () => void) => void;
}
export interface ToastContentValue {
/** null hides the indicator. */
indicator?: VNodeChild;
title?: VNodeChild;
description?: VNodeChild;
variant?: "default" | "accent" | "success" | "warning" | "danger";
actionProps?: Omit<ButtonProps, "onClick"> & {
label?: VNodeChild;
onClick?: (event: MouseEvent) => void;
};
/** Shows a spinner in place of the indicator. */
isLoading?: boolean;
}
export interface HeroUIToastOptions {
description?: VNodeChild;
indicator?: VNodeChild;
variant?: ToastContentValue["variant"];
actionProps?: Omit<ButtonProps, "onClick"> & {
label?: VNodeChild;
onClick?: (event: MouseEvent) => void;
};
isLoading?: boolean;
/** Auto-dismiss timeout in ms; 0 keeps the toast open. @default 4000 */
timeout?: number;
/** Called when dismissed; exit animation may still be playing. */
onClose?: () => void;
}
export interface ToastPromiseOptions<T = unknown> {
loading: VNodeChild;
success: ((data: T) => VNodeChild) | VNodeChild;
error: ((error: Error) => VNodeChild) | VNodeChild;
}
export interface QueuedToast<T> {
key: string;
content: T;
timeout: number;
onClose?: () => void;
timer?: ManagedTimer;
/** Set when the caller explicitly replaces content (blocks promise settle). */
replaced?: boolean;
}
function now(): number {
return typeof performance !== "undefined" &&
typeof performance.now === "function"
? performance.now()
: Date.now();
}
/** Pauseable countdown timer with remaining-time tracking. */
export class ManagedTimer {
timerId: ReturnType<typeof setTimeout> | null = null;
private startTime: number | null = null;
private remaining: number;
private readonly callback: () => void;
constructor(callback: () => void, delay: number) {
this.remaining = delay;
this.callback = callback;
}
reset(delay: number): void {
this.remaining = delay;
this.resume();
}
pause(): void {
if (this.timerId == null) return;
clearTimeout(this.timerId);
this.timerId = null;
this.remaining -= now() - (this.startTime ?? now());
}
resume(): void {
// Already running: a second resume must not spawn an orphan countdown.
if (this.timerId != null) return;
if (this.remaining <= 0) return;
this.startTime = now();
this.timerId = setTimeout(() => {
this.timerId = null;
this.remaining = 0;
this.callback();
}, this.remaining);
}
}
let keyCounter = 0;
function generateKey(): string {
keyCounter = (keyCounter + 1) % Number.MAX_SAFE_INTEGER;
return `hv-toast-${keyCounter}`;
}
export class ToastQueue<T extends object = ToastContentValue> {
readonly maxVisibleToasts?: number;
private readonly exitDuration: number;
private readonly wrapUpdate?: (fn: () => void) => void;
private toasts: QueuedToast<T>[] = [];
private exitTimers = new Map<string, ReturnType<typeof setTimeout>>();
private exitingSnapshot: ReadonlySet<string> = new Set();
private exitSubscriptions = new Set<() => void>();
private subscriptions = new Set<() => void>();
private suspensions = new Set<string | symbol>();
private isBatchingExits = false;
private destroyed = false;
constructor(options?: ToastQueueOptions) {
this.maxVisibleToasts =
options?.maxVisibleToasts ?? DEFAULT_MAX_VISIBLE_TOAST;
this.exitDuration = options?.exitDuration ?? DEFAULT_EXIT_DURATION;
this.wrapUpdate = options?.wrapUpdate;
}
private emit(): void {
const run = () => {
for (const fn of this.subscriptions) fn();
};
if (this.wrapUpdate) this.wrapUpdate(run);
else run();
}
private notifyExitSubscribers(): void {
for (const fn of this.exitSubscriptions) fn();
}
get visibleToasts(): QueuedToast<T>[] {
// Newest first, matching the source stack order.
return [...this.toasts].reverse();
}
getExitingKeys(): ReadonlySet<string> {
return this.exitingSnapshot;
}
subscribe(fn: () => void): () => void {
this.subscriptions.add(fn);
return () => this.subscriptions.delete(fn);
}
subscribeExiting(fn: () => void): () => void {
this.exitSubscriptions.add(fn);
return () => this.exitSubscriptions.delete(fn);
}
add(
content: T,
options?: { timeout?: number; onClose?: () => void },
): string {
if (this.destroyed) return "";
const key = generateKey();
const timeout = options?.timeout ?? DEFAULT_TOAST_TIMEOUT;
const toast: QueuedToast<T> = {
key,
content,
timeout,
onClose: options?.onClose,
};
if (timeout > 0 && typeof window !== "undefined") {
// Always allocate the timer so a later resume can start it.
toast.timer = new ManagedTimer(() => this.close(key), timeout);
if (this.suspensions.size === 0) toast.timer.resume();
}
this.toasts.push(toast);
this.emit();
return key;
}
update(
key: string,
content: T,
options?: { onClose?: () => void; timeout?: number },
): boolean {
if (this.destroyed || this.exitTimers.has(key)) return false;
const toast = this.toasts.find((t) => t.key === key);
if (!toast) return false;
toast.content = content;
toast.replaced = true;
if (options && "onClose" in options) toast.onClose = options.onClose;
if (options?.timeout !== undefined) {
toast.timer?.pause();
toast.timeout = options.timeout;
if (options.timeout > 0 && typeof window !== "undefined") {
toast.timer = new ManagedTimer(() => this.close(key), options.timeout);
if (this.suspensions.size === 0) toast.timer.resume();
} else {
toast.timer = undefined;
}
}
this.emit();
return true;
}
close(key: string): void {
if (this.destroyed) return;
const toast = this.toasts.find((t) => t.key === key);
if (this.exitTimers.has(key) || !toast) return;
toast.timer?.pause();
toast.timer = undefined;
const canAnimate =
this.exitDuration > 0 &&
typeof window !== "undefined" &&
!window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
if (!canAnimate) {
this.remove(key);
toast.onClose?.();
return;
}
const onClose = toast.onClose;
toast.onClose = undefined;
this.exitTimers.set(
key,
setTimeout(() => {
this.exitTimers.delete(key);
this.exitingSnapshot = new Set(this.exitTimers.keys());
this.remove(key);
if (!this.isBatchingExits) this.notifyExitSubscribers();
}, this.exitDuration),
);
if (!this.isBatchingExits) {
this.exitingSnapshot = new Set(this.exitTimers.keys());
this.notifyExitSubscribers();
}
onClose?.();
}
private remove(key: string): void {
this.toasts = this.toasts.filter((t) => t.key !== key);
this.emit();
}
clear(): void {
this.isBatchingExits = true;
try {
for (const t of [...this.toasts]) this.close(t.key);
} finally {
this.isBatchingExits = false;
this.exitingSnapshot = new Set(this.exitTimers.keys());
this.notifyExitSubscribers();
}
}
pauseAll(): void {
this.suspendTimers("external");
}
resumeAll(): void {
this.resumeTimers("external");
}
suspendTimers(source: string | symbol): void {
const wasEmpty = this.suspensions.size === 0;
this.suspensions.add(source);
if (wasEmpty) {
for (const t of this.toasts) t.timer?.pause();
}
}
resumeTimers(source: string | symbol): void {
this.suspensions.delete(source);
if (this.suspensions.size === 0) {
for (const t of this.toasts) t.timer?.resume();
}
}
destroy(): void {
this.destroyed = true;
for (const id of this.exitTimers.values()) clearTimeout(id);
this.exitTimers.clear();
this.exitingSnapshot = new Set();
this.exitSubscriptions.clear();
this.subscriptions.clear();
this.suspensions.clear();
for (const t of this.toasts) t.timer?.pause();
this.toasts = [];
}
}
export type ToastFn = {
(message: VNodeChild, options?: HeroUIToastOptions): string;
success: (
message: VNodeChild,
options?: Omit<HeroUIToastOptions, "variant">,
) => string;
danger: (
message: VNodeChild,
options?: Omit<HeroUIToastOptions, "variant">,
) => string;
info: (
message: VNodeChild,
options?: Omit<HeroUIToastOptions, "variant">,
) => string;
warning: (
message: VNodeChild,
options?: Omit<HeroUIToastOptions, "variant">,
) => string;
update: (
id: string,
message: VNodeChild,
options?: HeroUIToastOptions,
) => string;
promise: <T>(
promise: Promise<T> | (() => Promise<T>),
options: ToastPromiseOptions<T>,
) => string;
close: (key: string) => void;
pauseAll: () => void;
resumeAll: () => void;
clear: () => void;
};
export function createToastFunction(
queue: ToastQueue<ToastContentValue>,
): ToastFn {
const createContent = (
message: VNodeChild,
options?: HeroUIToastOptions,
): ToastContentValue => ({
title: message,
description: options?.description,
indicator: options?.indicator,
variant: options?.variant || "default",
actionProps: options?.actionProps,
isLoading: options?.isLoading,
});
const createAddOptions = (options?: HeroUIToastOptions) => ({
timeout: options?.timeout ?? DEFAULT_TOAST_TIMEOUT,
onClose: options?.onClose,
});
const createUpdateOptions = (options?: HeroUIToastOptions) => ({
...(options && "timeout" in options ? { timeout: options.timeout } : null),
...(options && "onClose" in options ? { onClose: options.onClose } : null),
});
const toastFn = ((message: VNodeChild, options?: HeroUIToastOptions) =>
queue.add(
createContent(message, options),
createAddOptions(options),
)) as ToastFn;
toastFn.success = (message, options) =>
toastFn(message, { ...options, variant: "success" });
toastFn.danger = (message, options) =>
toastFn(message, { ...options, variant: "danger" });
toastFn.info = (message, options) =>
toastFn(message, { ...options, variant: "accent" });
toastFn.warning = (message, options) =>
toastFn(message, { ...options, variant: "warning" });
toastFn.update = (id, message, options) => {
const content = createContent(message, options);
if (queue.update(id, content, createUpdateOptions(options))) return id;
return queue.add(content, createAddOptions(options));
};
toastFn.promise = (promise, options) => {
const promiseFn = typeof promise === "function" ? promise() : promise;
const loadingId = queue.add(
createContent(options.loading, { isLoading: true }),
{
timeout: 0,
},
);
const settle = (content: ToastContentValue) => {
// Only update the still-live, not-yet-replaced loading entry.
const current = queue.visibleToasts.find((t) => t.key === loadingId);
if (!current || current.replaced) return;
queue.update(loadingId, content, {
timeout: DEFAULT_TOAST_TIMEOUT,
});
};
promiseFn.then(
(data) => {
const message =
typeof options.success === "function"
? options.success(data)
: options.success;
settle(
createContent(message, {
isLoading: false,
variant: "success",
}),
);
},
(reason: unknown) => {
const error =
reason instanceof Error ? reason : new Error(String(reason));
const message =
typeof options.error === "function"
? options.error(error)
: options.error;
settle(
createContent(message, {
isLoading: false,
variant: "danger",
}),
);
},
);
return loadingId;
};
toastFn.close = (key) => queue.close(key);
toastFn.pauseAll = () => queue.pauseAll();
toastFn.resumeAll = () => queue.resumeAll();
toastFn.clear = () => queue.clear();
return toastFn;
}
@@ -0,0 +1,19 @@
import {
ToastQueue,
createToastFunction,
type ToastContentValue,
} from "./toast-queue";
// Client convenience must never accumulate notifications in a server module.
class ClientToastQueue extends ToastQueue<ToastContentValue> {
override add(
...args: Parameters<ToastQueue<ToastContentValue>["add"]>
): string {
return typeof window === "undefined" ? "" : super.add(...args);
}
}
/** Shared client queue. SSR uses an explicit request-local ToastQueue. */
export const toastQueue = new ClientToastQueue();
export const toast = createToastFunction(toastQueue);
if (import.meta.hot) import.meta.hot.dispose(() => toastQueue.destroy());