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
@@ -170,7 +170,7 @@ function focus(e: FocusEvent) {
:data-pressed="(!pending && !disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="button"
:data-slot="$attrs['data-slot'] ?? 'button'"
@pointerenter="hovered = !pending && !disabled"
@pointerleave="
hovered = false;
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { tableContextKey } from "./context";
export default defineComponent({
name: "TableBody",
inheritAttrs: false,
props: { as: { type: String, default: "tbody" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.body(), attrs.class],
"data-slot": "table-body",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,66 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
useAttrs,
ref,
onMounted,
onUpdated,
} from "vue";
import { tableContextKey, tableRowContextKey } from "./context";
export default defineComponent({
name: "TableCell",
inheritAttrs: false,
props: {
as: { type: String, default: "td" },
colspan: { type: [Number, String], default: undefined },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
const row = inject(tableRowContextKey, null);
const element = ref<HTMLTableCellElement | null>(null);
const index = ref(row?.nextCellIndex() ?? -1);
const sync = () => {
index.value = element.value?.cellIndex ?? -1;
};
onMounted(sync);
onUpdated(sync);
const column = computed(
() =>
ctx?.columnDefinitions?.value[index.value] ??
[...(ctx?.columns?.value.values() ?? [])].sort((a, b) =>
a.node.compareDocumentPosition(b.node) & 2 ? 1 : -1,
)[index.value],
);
const isTreeColumn = computed(
() =>
column.value?.id !== undefined &&
column.value.id === ctx?.treeColumn.value,
);
return () =>
h(
column.value?.isRowHeader && props.as === "td" ? "th" : props.as,
{
...attrs,
ref: element,
scope: column.value?.isRowHeader ? "row" : undefined,
tabindex: attrs.tabindex ?? -1,
class: [ctx?.slots.value.cell(), attrs.class],
"data-slot": "table-cell",
colspan: props.colspan,
},
slots.default?.({
isExpanded: row?.isExpanded.value ?? false,
hasChildItems: row?.hasChildItems ?? false,
isDisabled: row?.isDisabled.value ?? false,
isTreeColumn: isTreeColumn.value,
isSelected: row?.isSelected.value ?? false,
}),
);
},
});
</script>
@@ -0,0 +1,27 @@
<script lang="ts">
import { defineComponent, h, Fragment, useAttrs, type PropType } from "vue";
/**
* Declarative items renderer for rows. Use the default scoped slot with
* each item, matching the upstream Table.Collection API.
*/
export default defineComponent({
name: "TableCollection",
inheritAttrs: false,
props: {
items: { type: Array as PropType<unknown[]>, default: () => [] },
as: { type: String, default: undefined },
},
setup(props, { slots }) {
const attrs = useAttrs();
return () => {
const children = (props.items ?? []).map((item, index) =>
slots.default?.({ item, index }),
);
return props.as
? h(props.as, { ...attrs, "data-slot": "table-collection" }, children)
: h(Fragment, children);
};
},
});
</script>
@@ -0,0 +1,123 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
mergeProps,
provide,
useAttrs,
ref,
watch,
onBeforeUnmount,
} from "vue";
import {
tableContextKey,
tableColumnContextKey,
tableColumnWidthKey,
type TableSortDirection,
} from "./context";
export default defineComponent({
name: "TableColumn",
inheritAttrs: false,
props: {
as: { type: String, default: "th" },
allowsSorting: { type: Boolean, default: false },
isRowHeader: { type: Boolean, default: false },
id: { type: String, default: undefined },
width: { type: [String, Number], default: undefined },
maxWidth: { type: Number, default: undefined },
minWidth: { type: Number, default: undefined },
defaultWidth: { type: [String, Number], default: undefined },
},
emits: { "update:width": (_width: number) => true },
setup(props, { slots, emit }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
const token = Symbol();
const element = ref<HTMLElement | null>(null);
watch(
[element, () => props.id, () => props.isRowHeader],
([node, id, isRowHeader]) => {
if (!ctx?.columns) return;
const next = new Map(ctx.columns.value);
if (node) next.set(token, { node, id, isRowHeader });
else next.delete(token);
ctx.columns.value = next;
},
{ flush: "sync" },
);
onBeforeUnmount(() => {
if (ctx?.columns) {
const next = new Map(ctx.columns.value);
next.delete(token);
ctx.columns.value = next;
}
});
const internalWidth = ref(props.defaultWidth);
const width = computed(() =>
props.width !== undefined ? props.width : internalWidth.value,
);
const setWidth = (next: number) => {
if (props.width === undefined) internalWidth.value = next;
emit("update:width", next);
};
provide(tableColumnWidthKey, {
minWidth: computed(() => props.minWidth),
maxWidth: computed(() => props.maxWidth),
width,
setWidth,
});
const cssWidth = (value: string | number | undefined) =>
typeof value === "number" ? `${value}px` : value;
const sortDirection = computed<TableSortDirection | undefined>(() => {
if (!props.allowsSorting || !props.id) return undefined;
const d = ctx?.sortDescriptor.value;
if (!d || d.column !== props.id) return undefined;
return d.direction === "none" ? undefined : d.direction;
});
provide(tableColumnContextKey, {
key: computed(() => props.id),
allowsSorting: computed(() => props.allowsSorting),
sortDirection: computed(() => sortDirection.value ?? "none"),
});
return () => {
// Vue DOM merge: user onClick first, then the sort proposal.
return h(
props.as,
mergeProps(attrs as Record<string, unknown>, {
ref: element,
class: [ctx?.slots.value.column(), attrs.class],
style: {
width: cssWidth(width.value),
minWidth: cssWidth(
typeof width.value === "number"
? Math.max(props.minWidth ?? 0, width.value)
: props.minWidth,
),
maxWidth: cssWidth(props.maxWidth),
},
"data-column-id": props.id,
"data-row-header": props.isRowHeader || undefined,
"data-slot": "table-column",
"data-allows-sorting": props.allowsSorting || undefined,
"aria-sort": props.allowsSorting
? (sortDirection.value ?? "none")
: undefined,
// Row-header flag is metadata for the row cells; the header
// th keeps column scope.
scope: "col",
onClick: (event: MouseEvent) => {
if (event.defaultPrevented) return;
if (props.allowsSorting && props.id && ctx) {
ctx.sort(props.id);
}
},
}),
slots.default?.(),
);
};
},
});
</script>
@@ -0,0 +1,159 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
mergeProps,
onBeforeUnmount,
ref,
} from "vue";
import { tableColumnWidthKey, tableContextKey } from "./context";
export default defineComponent({
name: "TableColumnResizer",
inheritAttrs: false,
props: {
as: { type: String, default: "div" },
minWidth: { type: Number, default: 48 },
maxWidth: { type: Number, default: 640 },
step: { type: Number, default: 8 },
},
setup(props, { attrs }) {
const ctx = inject(tableContextKey, null);
const widthCtx = inject(tableColumnWidthKey, null);
const el = ref<HTMLElement | null>(null);
const min = computed(() => widthCtx?.minWidth.value ?? props.minWidth);
const max = computed(() =>
Math.max(min.value, widthCtx?.maxWidth.value ?? props.maxWidth),
);
const width = ref<number>();
const isResizing = ref(false);
let gesture:
| {
node: HTMLElement;
id: number;
x: number;
width: number;
direction: number;
}
| undefined;
const column = () => el.value?.closest("th") as HTMLElement | null;
const direction = () => {
const node = el.value;
return node &&
(node.closest("[dir]")?.getAttribute("dir") === "rtl" ||
getComputedStyle(node).direction === "rtl")
? -1
: 1;
};
function apply(value: number) {
width.value = Math.max(min.value, Math.min(max.value, value));
if (widthCtx) widthCtx.setWidth(width.value);
else {
const node = column();
if (node) node.style.width = `${width.value}px`;
}
}
function finish(cancel: boolean) {
const previous = gesture;
if (!previous) return;
gesture = undefined;
isResizing.value = false;
if (cancel) apply(previous.width);
try {
previous.node.releasePointerCapture(previous.id);
} catch {
/* capture already lost */
}
}
function down(event: PointerEvent) {
if (event.defaultPrevented || event.button !== 0 || gesture || !el.value)
return;
event.preventDefault();
event.stopPropagation();
isResizing.value = true;
gesture = {
node: el.value,
id: event.pointerId,
x: event.clientX,
width: column()?.getBoundingClientRect().width ?? 0,
direction: direction(),
};
try {
gesture.node.setPointerCapture(event.pointerId);
} catch {
/* synthetic / interrupted pointer */
}
}
function move(event: PointerEvent) {
if (event.defaultPrevented || !gesture || event.pointerId !== gesture.id)
return;
apply(gesture.width + (event.clientX - gesture.x) * gesture.direction);
}
function up(event: PointerEvent) {
if (gesture?.id === event.pointerId) finish(false);
}
function cancel(event: PointerEvent) {
if (gesture?.id === event.pointerId) finish(true);
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.key === "Escape" && gesture) {
event.preventDefault();
finish(true);
return;
}
const current = column()?.getBoundingClientRect().width ?? 0;
let next: number;
if (event.key === "Home") next = min.value;
else if (event.key === "End") next = max.value;
else if (event.key === "ArrowLeft" || event.key === "ArrowRight")
next =
current +
(event.key === "ArrowRight" ? 1 : -1) *
direction() *
props.step *
(event.shiftKey ? 4 : 1);
else return;
event.preventDefault();
event.stopPropagation();
apply(next);
}
function setEl(node: unknown) {
const next = node as HTMLElement | null;
if (el.value === next) return;
finish(true);
el.value = next;
}
onBeforeUnmount(() => finish(true));
return () =>
h(
props.as,
mergeProps(attrs, {
ref: setEl,
class: ctx?.slots.value.columnResizer(),
"data-slot": "table-column-resizer",
"data-resizing": isResizing.value || undefined,
role: "separator",
"aria-label": attrs["aria-label"] ?? "调整列宽",
"aria-orientation": "vertical",
"aria-valuemin": min.value,
"aria-valuemax": max.value,
"aria-valuenow":
typeof widthCtx?.width.value === "number"
? widthCtx.width.value
: width.value,
tabindex: attrs.tabindex ?? 0,
onPointerdown: down,
onPointermove: move,
onPointerup: up,
onPointercancel: cancel,
onLostpointercapture: cancel,
onKeydown: keydown,
onClick: (event: MouseEvent) => event.stopPropagation(),
}),
);
},
});
</script>
@@ -0,0 +1,226 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
provide,
ref,
shallowRef,
mergeProps,
onBeforeUnmount,
type PropType,
} from "vue";
import { useTableNavigation } from "./navigation";
import { useCollectionSelection } from "../collection/selection";
import type { TableKey } from "./context";
import { tableContextKey, type TableSortDirection } from "./context";
export default defineComponent({
name: "TableContent",
inheritAttrs: false,
props: {
as: { type: String, default: "table" },
sortDescriptor: {
type: Object as PropType<{
column: string;
direction: TableSortDirection;
} | null>,
default: undefined,
},
defaultSortDescriptor: {
type: Object as PropType<{
column: string;
direction: TableSortDirection;
} | null>,
default: null,
},
selectionMode: {
type: String as PropType<"none" | "single" | "multiple">,
default: "none",
},
selectedKeys: {
type: Array as PropType<TableKey[]>,
default: undefined,
},
defaultSelectedKeys: {
type: Array as PropType<TableKey[]>,
default: () => [],
},
disabledKeys: {
type: Array as PropType<TableKey[]>,
default: () => [],
},
rowKeys: { type: Array as PropType<TableKey[]>, default: undefined },
/** Expanded row ids for tree tables. */
expandedKeys: {
type: Array as PropType<TableKey[]>,
default: undefined,
},
defaultExpandedKeys: {
type: Array as PropType<TableKey[]>,
default: () => [],
},
/** Column id used as the tree column. */
treeColumn: { type: String, default: undefined },
},
emits: {
focusRow: (_key: TableKey, _index: number) => true,
"update:selectedKeys": (keys: TableKey[]) => Array.isArray(keys),
selectionChange: (keys: TableKey[]) => Array.isArray(keys),
"update:sortDescriptor": (
d: {
column: string;
direction: TableSortDirection;
} | null,
) => true,
sortChange: (d: {
column: string;
direction: "ascending" | "descending";
}) => true,
"update:expandedKeys": (keys: TableKey[]) => Array.isArray(keys),
expandedChange: (keys: TableKey[]) => Array.isArray(keys),
},
setup(props, { attrs, slots, emit }) {
const parentCtx = inject(tableContextKey, null);
const internalSort = ref<{
column: string;
direction: TableSortDirection;
} | null>(props.defaultSortDescriptor);
const internalExpanded = ref<TableKey[]>([
...(props.defaultExpandedKeys ?? []),
]);
const selection = useCollectionSelection({
mode: () => props.selectionMode,
controlled: () => props.selectedKeys !== undefined,
value: () => props.selectedKeys,
defaultValue: props.defaultSelectedKeys,
disabledKeys: () => [
...props.disabledKeys,
...navigation.disabledKeys.value,
],
onChange(keys) {
emit("update:selectedKeys", keys);
emit("selectionChange", keys);
},
});
const selectedKeys = selection.keys;
const sortDescriptor = computed(() =>
props.sortDescriptor !== undefined
? props.sortDescriptor
: internalSort.value,
);
const expandedKeys = computed(() =>
props.expandedKeys !== undefined
? props.expandedKeys
: internalExpanded.value,
);
const element = ref<HTMLElement | null>(null);
let anchor: TableKey | undefined;
function select(key: TableKey, extend = false) {
if (selection.disabled(key)) return;
if (extend && props.selectionMode === "multiple") {
anchor ??= navigation.entry.value ?? key;
const ordered = navigation.keys.value;
const start = ordered.indexOf(anchor ?? key),
end = ordered.indexOf(key);
if (start >= 0 && end >= 0)
selection.request(
ordered
.slice(Math.min(start, end), Math.max(start, end) + 1)
.filter((k) => !selection.disabled(k)),
);
} else {
anchor = key;
selection.toggle(key);
}
}
const navigation = useTableNavigation({
element,
keys: () => props.rowKeys,
disabled: selection.disabled,
select,
selectAll: () => selection.selectAll(navigation.keys.value),
requestFocus: (key, index) => emit("focusRow", key, index),
});
onBeforeUnmount(navigation.cancel);
function toggleSelect(key: TableKey, event?: MouseEvent | KeyboardEvent) {
select(key, event?.shiftKey ?? false);
}
function sort(column: string) {
const current = sortDescriptor.value;
let direction: TableSortDirection = "ascending";
if (current?.column === column) {
direction =
current.direction === "ascending" ? "descending" : "ascending";
}
const next = { column, direction };
if (props.sortDescriptor === undefined) internalSort.value = next;
emit("update:sortDescriptor", next);
emit(
"sortChange",
next as { column: string; direction: "ascending" | "descending" },
);
}
function toggleExpand(key: TableKey) {
const current = expandedKeys.value;
const next = current.includes(key)
? current.filter((k) => k !== key)
: [...current, key];
if (props.expandedKeys === undefined) internalExpanded.value = next;
emit("update:expandedKeys", next);
emit("expandedChange", next);
}
provide(tableContextKey, {
...(parentCtx ?? {
slots: computed(() => ({}) as never),
variant: computed(() => "primary"),
}),
navigation,
columns: shallowRef(new Map()),
columnDefinitions: shallowRef([]),
selectionMode: computed(() => props.selectionMode),
selectedKeys,
disabledKeys: computed(() => props.disabledKeys),
sortDescriptor,
expandedKeys,
treeColumn: computed(() => props.treeColumn),
toggleSelect,
toggleExpand,
isRowSelected: (key) =>
props.selectionMode !== "none" && selectedKeys.value.includes(key),
isRowDisabled: (key) => props.disabledKeys.includes(key),
isRowExpanded: (key) => expandedKeys.value.includes(key),
sort,
});
return () =>
h(
props.as,
mergeProps(attrs, {
ref: element,
class: parentCtx?.slots.value.content(),
"data-slot": "table-content",
role:
attrs.role ??
(props.treeColumn !== undefined ? "treegrid" : "grid"),
"aria-multiselectable":
props.selectionMode === "multiple" ? true : undefined,
tabindex:
attrs.tabindex ??
(navigation.entry.value === undefined ||
!navigation.hasEntryMounted.value
? 0
: undefined),
onKeydown: navigation.onKeydown,
onFocusin: navigation.onFocusin,
}),
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { tableContextKey } from "./context";
export default defineComponent({
name: "TableFooter",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.footer(), attrs.class],
"data-slot": "table-footer",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,76 @@
<script lang="ts">
import {
defineComponent,
h,
inject,
useAttrs,
Fragment,
type VNode,
} from "vue";
import { tableContextKey } from "./context";
/** thead with a single header row wrapping the columns. */
export default defineComponent({
name: "TableHeader",
inheritAttrs: false,
props: {
as: { type: String, default: "thead" },
rowAs: { type: String, default: "tr" },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
function definitions(
nodes: VNode[],
): { id?: string; isRowHeader: boolean }[] {
return nodes.flatMap((node) => {
if (node.type === Fragment)
return definitions(node.children as VNode[]);
if (
typeof node.type === "object" &&
"name" in node.type &&
node.type.name === "TableColumn"
)
return [
{
id: node.props?.id,
isRowHeader:
node.props?.isRowHeader === "" ||
node.props?.isRowHeader === true ||
node.props?.["is-row-header"] === "" ||
node.props?.["is-row-header"] === true,
},
];
return [];
});
}
return () => {
const children = slots.default?.() ?? [];
const columns = definitions(children);
if (
ctx?.columnDefinitions &&
JSON.stringify(ctx.columnDefinitions.value) !== JSON.stringify(columns)
)
ctx.columnDefinitions.value = columns;
return h(
props.as,
{
...attrs,
class: [ctx?.slots.value.header(), attrs.class],
"data-slot": "table-header",
},
[
h(
props.rowAs,
{
"data-slot": "table-header-row",
class: ctx?.slots.value.row(),
},
children,
),
],
);
};
},
});
</script>
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { tableContextKey } from "./context";
export default defineComponent({
name: "TableLoadMoreContent",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.loadMoreContent(), attrs.class],
"data-slot": "table-load-more-content",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,112 @@
<script lang="ts">
import {
defineComponent,
h,
inject,
onBeforeUnmount,
onMounted,
ref,
watch,
type PropType,
} from "vue";
import { tableContextKey } from "./context";
/** A sentinel owned by the nearest table scroll viewport. */
export default defineComponent({
name: "TableLoadMoreItem",
inheritAttrs: false,
props: {
colspan: { type: Number, default: 100 },
as: { type: String, default: "tr" },
isLoading: { type: Boolean, default: false },
hasMore: { type: Boolean, default: true },
scrollOffset: { type: Number, default: 0 },
scrollRoot: { type: Object as PropType<HTMLElement>, default: undefined },
},
emits: { loadMore: () => true },
setup(props, { attrs, slots, emit }) {
const ctx = inject(tableContextKey, null);
const el = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | undefined;
let mounted = false,
visible = false,
requested = false;
function request() {
if (
!mounted ||
!visible ||
requested ||
props.isLoading ||
!props.hasMore
)
return;
requested = true;
emit("loadMore");
}
function observe() {
observer?.disconnect();
const node = el.value;
if (!mounted || !node || typeof IntersectionObserver === "undefined")
return;
const current = new IntersectionObserver(
(entries) => {
if (observer !== current || !mounted) return;
visible = entries.some((entry) => entry.isIntersecting);
if (!visible) requested = false;
request();
},
{
root:
props.scrollRoot ??
node.closest('[data-slot="table-scroll-container"]'),
rootMargin: `${props.scrollOffset}px`,
},
);
observer = current;
current.observe(node);
}
function bind(node: unknown) {
if (el.value === node) return;
el.value = node as HTMLElement | null;
visible = false;
requested = false;
observe();
}
watch(
() => props.isLoading,
(next, previous) => {
if (previous && !next) {
requested = false;
request();
}
},
);
watch([() => props.scrollRoot, () => props.scrollOffset], observe);
watch(() => props.hasMore, request);
onMounted(() => {
mounted = true;
observe();
});
onBeforeUnmount(() => {
mounted = false;
observer?.disconnect();
observer = undefined;
});
return () =>
h(
props.as,
{
...attrs,
ref: bind,
class: [ctx?.slots.value.loadMore(), attrs.class],
"data-slot": "table-load-more",
"aria-busy": props.isLoading || undefined,
"data-loading": props.isLoading || undefined,
},
props.as === "tr"
? [h("td", { colspan: props.colspan }, slots.default?.())]
: slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { tableContextKey } from "./context";
export default defineComponent({
name: "TableResizableContainer",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.resizableContainer(), attrs.class],
"data-slot": "table-resizable-container",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,58 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
} from "vue";
import { tableVariants, type TableVariants } from "@heroui-vue/styles";
import { tableContextKey, type TableSortDirection } from "./context";
export default defineComponent({
name: "TableRoot",
inheritAttrs: false,
props: {
variant: {
type: String as PropType<TableVariants["variant"]>,
default: "primary",
},
as: { type: String, default: "div" },
},
setup(props, { attrs, slots }) {
const slotsComputed = computed(() =>
tableVariants({ variant: props.variant }),
);
const noop = () => {};
provide(tableContextKey, {
slots: slotsComputed,
variant: computed(() => props.variant),
selectionMode: computed(() => "none" as const),
selectedKeys: computed(() => [] as string[]),
disabledKeys: computed(() => [] as string[]),
sortDescriptor: computed(
() => null as { column: string; direction: TableSortDirection } | null,
),
expandedKeys: computed(() => [] as string[]),
treeColumn: computed(() => undefined),
toggleSelect: noop,
toggleExpand: noop,
isRowSelected: () => false,
isRowDisabled: () => false,
isRowExpanded: () => false,
sort: noop,
});
return () =>
h(
props.as,
{
...attrs,
class: [slotsComputed.value.base(), attrs.class],
"data-slot": "table",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,136 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
mergeProps,
provide,
useAttrs,
ref,
watch,
onBeforeUnmount,
onUpdated,
type PropType,
} from "vue";
import { tableContextKey, tableRowContextKey, type TableKey } from "./context";
export default defineComponent({
name: "TableRow",
inheritAttrs: false,
props: {
level: { type: Number, default: undefined },
rowKey: { type: [String, Number] as PropType<TableKey>, required: true },
isDisabled: { type: Boolean, default: false },
hasChildItems: { type: Boolean, default: false },
as: { type: String, default: "tr" },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
const element = ref<HTMLElement | null>(null);
watch(
[() => props.rowKey, element],
([key, node], previous) => {
if (previous) ctx?.navigation?.register(previous[0], null);
if (!node?.closest("thead"))
ctx?.navigation?.register(key, node, () => props.isDisabled);
},
{ flush: "sync" },
);
onBeforeUnmount(() => ctx?.navigation?.register(props.rowKey, null));
onUpdated(() => ctx?.navigation?.refresh());
const isSelected = computed(
() => ctx?.isRowSelected(props.rowKey) ?? false,
);
const isDisabled = computed(
() => props.isDisabled || (ctx?.isRowDisabled(props.rowKey) ?? false),
);
const isExpanded = computed(
() => ctx?.isRowExpanded(props.rowKey) ?? false,
);
let cellIndex = 0;
provide(tableRowContextKey, {
nextCellIndex: () => cellIndex++,
get key() {
return props.rowKey;
},
isSelected,
isDisabled,
isExpanded,
get hasChildItems() {
return props.hasChildItems;
},
});
return () => {
// Vue DOM merge: user onClick is first in the array, so
// stopImmediatePropagation / preventDefault gate the internal handler.
return h(
props.as,
mergeProps(attrs as Record<string, unknown>, {
ref: element,
"aria-disabled": isDisabled.value || undefined,
class: [ctx?.slots.value.row(), attrs.class],
"data-slot": "table-row",
"data-selected": isSelected.value || undefined,
"data-disabled": isDisabled.value || undefined,
"data-expanded": isExpanded.value || undefined,
"aria-expanded": props.hasChildItems ? isExpanded.value : undefined,
"aria-level": props.level,
"aria-selected":
ctx && ctx.selectionMode.value !== "none"
? isSelected.value
: undefined,
// Selectable rows get a default keyboard entry when the caller
// does not set tabindex explicitly.
tabindex:
attrs.tabindex !== undefined
? attrs.tabindex
: ctx?.navigation
? isDisabled.value
? -1
: ctx.navigation.tabIndex(props.rowKey)
: undefined,
onClick: (event: MouseEvent) => {
if (event.defaultPrevented) return;
if (isDisabled.value) return;
const target = event.target as HTMLElement | null;
if (
target?.closest(
"button, a, input, select, textarea, [role='button'], [role='link']",
)
) {
return;
}
ctx?.toggleSelect(props.rowKey, event);
},
onKeydown: (event: KeyboardEvent) => {
if (event.defaultPrevented || isDisabled.value) return;
if (event.key !== " " && event.key !== "Spacebar") return;
const target = event.target as HTMLElement | null;
if (
target?.closest(
"input, select, textarea, button, a, [role='button'], [role='link'], [contenteditable='true']",
)
) {
return;
}
event.preventDefault();
ctx?.toggleSelect(props.rowKey, event);
},
}),
slots.default?.({
isSelected: isSelected.value,
isExpanded: isExpanded.value,
hasChildItems: props.hasChildItems,
toggleExpanded: () => {
if (!isDisabled.value && props.hasChildItems)
ctx?.toggleExpand(props.rowKey);
},
isDisabled: isDisabled.value,
}),
);
};
},
});
</script>
@@ -0,0 +1,24 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { tableContextKey } from "./context";
export default defineComponent({
name: "TableScrollContainer",
inheritAttrs: false,
props: { as: { type: String, default: "div" } },
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
return () =>
h(
props.as,
{
...attrs,
class: [ctx?.slots.value.scrollContainer(), attrs.class],
"data-slot": "table-scroll-container",
},
slots.default?.(),
);
},
});
</script>
@@ -0,0 +1,133 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
mergeProps,
useAttrs,
type PropType,
} from "vue";
import {
tableColumnContextKey,
tableContextKey,
type TableSortDirection,
} from "./context";
/**
* Sortable column label + indicator, rendered inside a sortable Table.Column.
* The column (th) owns the click target; this is a visual span.
*/
export default defineComponent({
name: "TableSortableColumnHeader",
inheritAttrs: false,
props: {
/** Column id; alias kept for click-to-sort on the trigger button. */
columnKey: { type: String, default: undefined },
/** Current sort direction from the column's sort state. */
sortDirection: {
type: String as PropType<TableSortDirection | undefined>,
default: undefined,
},
showIndicator: { type: Boolean, default: true },
indicator: {
type: [Object, String] as PropType<unknown>,
default: undefined,
},
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "span" },
},
setup(props, { slots }) {
const attrs = useAttrs();
const ctx = inject(tableContextKey, null);
const column = inject(tableColumnContextKey, null);
// Explicit prop wins; otherwise read the current descriptor for this column.
const effectiveDirection = computed(() => {
if (props.sortDirection !== undefined) return props.sortDirection;
const d = ctx?.sortDescriptor.value;
return d &&
d.column === (props.columnKey ?? column?.key.value) &&
d.direction !== "none"
? d.direction
: undefined;
});
const shouldRenderIndicator = computed(
() => props.showIndicator && Boolean(effectiveDirection.value),
);
function renderIndicator() {
if (!shouldRenderIndicator.value) return null;
const base = {
class: ctx?.slots.value.sortableColumnIndicator(),
"data-direction": effectiveDirection.value,
"data-slot": "table-sortable-column-indicator",
};
if (props.indicator === undefined) {
// Default chevron (baseline IconChevronUp), flips via data-direction.
return h(
"svg",
{
...base,
"aria-hidden": "true",
fill: "none",
height: "12",
viewBox: "0 0 12 12",
width: "12",
xmlns: "http://www.w3.org/2000/svg",
},
[
h("path", {
d: "M2.5 7.5L6 4l3.5 3.5",
stroke: "currentColor",
"stroke-linecap": "round",
"stroke-linejoin": "round",
"stroke-width": "1.5",
}),
],
);
}
return props.indicator;
}
return () => {
// Strip onClick from the wrapper; it runs from the trigger button.
const { onClick: _userOnClick, ...rest } = attrs as Record<
string,
unknown
>;
return h(
props.as,
{
...rest,
class: [ctx?.slots.value.sortableColumnHeader(), attrs.class],
"data-direction": effectiveDirection.value,
"data-slot": "table-sortable-column-header",
},
[
h(
"button",
mergeProps(
{ onClick: attrs.onClick as unknown },
{
type: "button",
disabled: props.isDisabled,
class: "hv-table__sortable-column-trigger",
onClick: (event: MouseEvent) => {
if (event.defaultPrevented) return;
if (props.isDisabled) {
event.stopPropagation();
return;
}
if (!column?.allowsSorting.value && props.columnKey && ctx)
ctx.sort(props.columnKey);
},
},
),
[slots.default?.(), renderIndicator()],
),
],
);
};
},
});
</script>
@@ -0,0 +1,66 @@
import type { CollectionKey } from "../collection/keys";
import type { useTableNavigation } from "./navigation";
export type TableKey = CollectionKey;
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { tableVariants } from "@heroui-vue/styles";
export type TableSlots = ReturnType<typeof tableVariants>;
export type TableSortDirection = "ascending" | "descending" | "none";
export interface TableContextValue {
columnDefinitions?: Ref<{ id?: string; isRowHeader: boolean }[]>;
columns?: Ref<
Map<symbol, { node: HTMLElement; id?: string; isRowHeader: boolean }>
>;
navigation?: ReturnType<typeof useTableNavigation>;
slots: ComputedRef<TableSlots>;
variant: ComputedRef<string>;
selectionMode: ComputedRef<"none" | "single" | "multiple">;
selectedKeys: ComputedRef<readonly TableKey[]>;
disabledKeys: ComputedRef<readonly TableKey[]>;
sortDescriptor: ComputedRef<{
column: string;
direction: TableSortDirection;
} | null>;
expandedKeys: ComputedRef<readonly TableKey[]>;
treeColumn: ComputedRef<string | undefined>;
toggleSelect: (key: TableKey, event?: MouseEvent | KeyboardEvent) => void;
toggleExpand: (key: TableKey) => void;
isRowSelected: (key: TableKey) => boolean;
isRowDisabled: (key: TableKey) => boolean;
isRowExpanded: (key: TableKey) => boolean;
sort: (column: string) => void;
}
export const tableContextKey: InjectionKey<TableContextValue> =
Symbol("hv-table");
export interface TableRowContextValue {
nextCellIndex: () => number;
key: TableKey;
isSelected: ComputedRef<boolean>;
isDisabled: ComputedRef<boolean>;
isExpanded: ComputedRef<boolean>;
hasChildItems: boolean;
}
export const tableRowContextKey: InjectionKey<TableRowContextValue> =
Symbol("hv-table-row");
export interface TableColumnContextValue {
key: ComputedRef<string | undefined>;
allowsSorting: ComputedRef<boolean>;
sortDirection: ComputedRef<TableSortDirection>;
}
export const tableColumnContextKey: InjectionKey<TableColumnContextValue> =
Symbol("hv-table-column");
export interface TableColumnWidthContext {
minWidth: ComputedRef<number | undefined>;
maxWidth: ComputedRef<number | undefined>;
width: ComputedRef<string | number | undefined>;
setWidth: (width: number) => void;
}
export const tableColumnWidthKey: InjectionKey<TableColumnWidthContext> =
Symbol("hv-table-column-width");
@@ -0,0 +1,169 @@
import { computed, nextTick, shallowRef, type Ref } from "vue";
import type { CollectionKey } from "../collection/keys";
/** Table-local DOM ownership. Logical keys may include unmounted virtual rows. */
export function useTableNavigation(options: {
element: Ref<HTMLElement | null>;
keys: () => readonly CollectionKey[] | undefined;
disabled: (key: CollectionKey) => boolean;
select: (key: CollectionKey, extend: boolean) => void;
selectAll: () => void;
requestFocus: (key: CollectionKey, index: number) => void;
}) {
const nodes = shallowRef(new Map<CollectionKey, HTMLElement>());
const disabledRows = shallowRef(new Map<CollectionKey, () => boolean>());
const disabledKeys = computed(() =>
[...disabledRows.value]
.filter(([, disabled]) => disabled())
.map(([key]) => key),
);
const active = shallowRef<CollectionKey | undefined>();
let column = 0;
let request = 0;
const mountedKeys = shallowRef<CollectionKey[]>([]);
function refresh() {
const ordered = [...nodes.value.entries()]
.sort((a, b) => (a[1].compareDocumentPosition(b[1]) & 2 ? 1 : -1))
.map(([key]) => key);
if (
ordered.length !== mountedKeys.value.length ||
ordered.some((key, index) => key !== mountedKeys.value[index])
)
mountedKeys.value = ordered;
}
const keys = computed(() => options.keys() ?? mountedKeys.value);
const entry = computed(() =>
active.value !== undefined &&
keys.value.includes(active.value) &&
!options.disabled(active.value)
? active.value
: keys.value.find((key) => !options.disabled(key)),
);
function register(
key: CollectionKey,
node: HTMLElement | null,
disabled?: () => boolean,
) {
if (nodes.value.get(key) === node || (!node && !nodes.value.has(key)))
return;
const next = new Map(nodes.value);
if (node) next.set(key, node);
else next.delete(key);
nodes.value = next;
const states = new Map(disabledRows.value);
if (node && disabled) states.set(key, disabled);
else states.delete(key);
disabledRows.value = states;
refresh();
}
async function focus(key: CollectionKey, cell = false) {
const token = ++request;
active.value = key;
if (!nodes.value.has(key)) {
options.requestFocus(key, keys.value.indexOf(key));
await nextTick();
}
if (token !== request) return;
const row = nodes.value.get(key);
const cells = row
? ([...row.children].filter((el) => el.matches("td,th")) as HTMLElement[])
: [];
(cell ? (cells[Math.min(column, cells.length - 1)] ?? row) : row)?.focus();
}
function rowOf(target: EventTarget | null) {
if (!(target instanceof Element)) return;
const row = target.closest('[data-slot="table-row"]');
return [...nodes.value].find(([, node]) => node === row);
}
function onFocusin(event: FocusEvent) {
const record = rowOf(event.target);
if (record) active.value = record[0];
}
function onKeydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
const table = options.element.value;
const target = event.target as HTMLElement;
if (!table || target.closest("table") !== table) return;
if (
target.closest(
'button,a,input,select,textarea,[contenteditable="true"],[role="button"],[role="separator"]',
)
)
return;
const record = rowOf(target);
const enabled = keys.value.filter((key) => !options.disabled(key));
const key = record?.[0] ?? entry.value;
if (key === undefined) return;
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "a") {
event.preventDefault();
options.selectAll();
return;
}
const cell = target.closest("td,th") as HTMLElement | null;
if (record && cell) column = [...record[1].children].indexOf(cell);
let next = key;
let toCell = !!cell;
const position = enabled.indexOf(key);
switch (event.key) {
case "ArrowDown":
next = enabled[Math.min(position + 1, enabled.length - 1)] ?? key;
break;
case "ArrowUp":
next = enabled[Math.max(0, position - 1)] ?? key;
break;
case "Home":
if (event.ctrlKey || event.metaKey) next = enabled[0] ?? key;
else {
column = 0;
toCell = true;
}
break;
case "End":
if (event.ctrlKey || event.metaKey) next = enabled.at(-1) ?? key;
else {
column = Math.max(0, (record?.[1].children.length ?? 1) - 1);
toCell = true;
}
break;
case "ArrowLeft":
case "ArrowRight": {
const rtl =
table.closest("[dir]")?.getAttribute("dir") === "rtl" ||
getComputedStyle(table).direction === "rtl";
const step = (event.key === "ArrowRight" ? 1 : -1) * (rtl ? -1 : 1);
column = Math.max(
0,
Math.min(
(record?.[1].children.length ?? 1) - 1,
(cell ? column : -step) + step,
),
);
toCell = true;
break;
}
default:
return;
}
event.preventDefault();
if (event.shiftKey) options.select(next, true);
void focus(next, toCell);
}
return {
keys,
hasEntryMounted: computed(
() => entry.value !== undefined && nodes.value.has(entry.value),
),
refresh,
disabledKeys,
entry,
register,
onKeydown,
onFocusin,
focus,
tabIndex: (key: CollectionKey) =>
entry.value === key && !options.disabled(key) ? 0 : -1,
cancel: () => {
request++;
},
};
}
+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());