Files
heroui-vue/packages/vue/src/components/chip/Chip.vue
T
2026-10-21 18:35:24 +08:00

125 lines
3.0 KiB
Vue

<script lang="ts">
import {
Comment,
Fragment,
Text,
computed,
defineComponent,
h,
isVNode,
provide,
useAttrs,
type PropType,
type VNode,
type VNodeChild,
} from "vue";
import { chipVariants, type ChipVariants } from "@heroui-vue/styles";
import { chipContextKey } from "./context";
import ChipLabel from "./ChipLabel.vue";
function flattenChildren(
nodes: VNodeChild[],
out: VNodeChild[] = [],
): VNodeChild[] {
for (const child of nodes) {
if (Array.isArray(child)) {
flattenChildren(child, out);
continue;
}
if (
isVNode(child) &&
child.type === Fragment &&
Array.isArray(child.children)
) {
flattenChildren(child.children as VNodeChild[], out);
continue;
}
out.push(child);
}
return out;
}
function isIgnorable(node: VNodeChild): boolean {
if (node == null || node === false || node === true) return true;
if (typeof node === "string") return node.trim() === "";
if (typeof node === "number") return false;
if (!isVNode(node)) return true;
if (node.type === Comment) return true;
if (node.type === Text && String(node.children ?? "").trim() === "")
return true;
return false;
}
/** True when the slot is only plain text/number content (auto-wrapped in ChipLabel). */
function isPlainTextSlot(nodes: VNodeChild[]): boolean {
const meaningful = flattenChildren(nodes).filter(
(node) => !isIgnorable(node),
);
if (meaningful.length === 0) return false;
return meaningful.every((node) => {
if (typeof node === "number" || typeof node === "string") return true;
return isVNode(node) && node.type === Text;
});
}
export default defineComponent({
name: "Chip",
inheritAttrs: false,
props: {
color: {
type: String as PropType<ChipVariants["color"]>,
default: "default",
},
size: {
type: String as PropType<ChipVariants["size"]>,
default: "md",
},
variant: {
type: String as PropType<ChipVariants["variant"]>,
default: "secondary",
},
},
setup(props, { attrs, slots }) {
const variantSlots = computed(() =>
chipVariants({
color: props.color,
size: props.size,
variant: props.variant,
}),
);
provide(chipContextKey, { slots: variantSlots });
/**
* Re-read the default slot on every render so text ↔ composed content
* switches and parent slot-swap updates stay in sync. Slot-function
* identity is not a reactive dependency.
*/
function render() {
const children = (slots.default?.() ?? []) as VNodeChild[];
const content: VNodeChild[] = isPlainTextSlot(children)
? [
h(
ChipLabel,
{ key: "chip-auto-label" },
{ default: () => children },
),
]
: children;
return h(
"span",
{
...attrs,
class: [variantSlots.value.base(), attrs.class],
"data-slot": "chip",
},
content,
);
}
return render;
},
});
</script>