Files
heroui-vue/packages/vue/src/components/toast/ToastIndicator.vue
T

91 lines
2.4 KiB
Vue

<script lang="ts">
import {
computed,
defineComponent,
h,
inject,
isVNode,
ref,
useAttrs,
watch,
type PropType,
type VNodeChild,
} from "vue";
import type { ToastVariants } from "@heroui-vue/styles";
import { toastContextKey } from "./context";
import {
ToastDangerIcon,
ToastInfoIcon,
ToastSuccessIcon,
ToastWarningIcon,
} from "./icons";
/** Identity of the indicator payload: element type, or "default" for the built-in icon. */
function childrenKind(children: VNodeChild): unknown {
if (children == null || children === false) return "default";
if (Array.isArray(children)) {
const first = children.find(
(c) => isVNode(c) || (typeof c === "string" && c.trim() !== ""),
);
return first === undefined ? "default" : childrenKind(first as VNodeChild);
}
if (isVNode(children)) return children.type;
return "default";
}
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);
// Swap marker: animate content that replaces earlier content (promise
// settle) without animating the first paint.
const hasSwapped = ref(false);
let previousKind: unknown;
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 () => {
const custom = slots.default?.();
const kind = custom ? childrenKind(custom) : childrenKind(null);
if (previousKind === undefined) {
previousKind = kind;
} else if (previousKind !== kind) {
previousKind = kind;
hasSwapped.value = true;
}
return h(
props.as,
{
...attrs,
class: [ctx?.slots.value.indicator(), attrs.class],
"data-slot": "toast-indicator",
"data-swapped": hasSwapped.value || undefined,
},
custom ?? [defaultIcon()],
);
};
},
});
</script>