import {classnames, computed, designComponent, getComponentCls, useClasses, useCollect, useModel, watch} from "@peryl/react-compose"; import './tabs.scss'; import {TabCommonProps, TabData} from "./tabs.utils"; import {TabsInner} from "./TabsInner"; import {TabsHeaderHorizontal} from "./header/horizontal/TabsHeaderHorizontal"; import {TabsHeaderVertical} from "./header/vertical/TabsHeaderVertical"; import Tab from "../Tab"; import Icon from "../Icon"; import {StyleProps, useStyle} from "../../uses/useStyle"; export const TabGroup = designComponent({ name: 'tab-group', props: { ...StyleProps, modelValue: { type: [String, Number] }, // 双向绑定值,控制当前显示的tab closeable: { type: Boolean }, // 是否显示关闭按钮,会派发onClose事件 fitHeight: { type: Boolean }, // 适配高度 ...TabCommonProps, }, emits: { onUpdateModelValue: (val?: string | number) => true, }, slots: ['default', 'operator'], setup({ props, event: { emit }, slots }) { const { styleComputed } = useStyle(); const model = useModel(() => props.modelValue, emit.onUpdateModelValue); const items = TabCollector.parent(); const tabs = computed(() => items.map((item, index) => { const { val } = item.props; return { item, index, val: val == null ? index : val, active: (() => { if (val != null) { return model.value == val; } if (model.value != null) { return model.value == index; } return index == 0; })(), }; })); watch(() => tabs.value.map(i => i.val).join('_'), () => { const activeItem = tabs.value.find(i => i.active); if (!activeItem) { model.value = tabs.value[0]?.val; } }); const classes = useClasses(() => [ getComponentCls('tab-group'), `tabs-head-position-${props.headPosition}`, `tabs-head-type-${props.headType}`, `tab-group-size-${styleComputed.value.size}`, { 'tabs-fit-height': props.fitHeight }, ]); const handler = { onClickTabHeader: ({ item, index, active }: TabData) => { const { props: { val } } = item; if (active) {return;} model.value = val == null ? index : val; } }; return { render: () => { const head = (() => { const Header = props.headPosition === 'top' || props.headPosition === 'bottom' ? TabsHeaderHorizontal : TabsHeaderVertical; return (
{tabs.value.map((tab, index) => (
handler.onClickTabHeader(tab)} data-active={tab.active ? 1 : 0}> {tab.item.scopeSlots.head({ active: false }, tab.item.props.title)} {props.closeable && { e.stopPropagation(); tab.item.event.emit.onClose(); }}/>}
))} {slots.operator.isExist() && (
{slots.operator()}
)}
); })(); const body = (
{[...tabs.value].sort((a, b) => String(a.val).localeCompare(String(b.val))).map((tab, index) => ( tab.item.slots.default()}/> ))}
); return (
{slots.default()}
{props.headPosition === 'top' || props.headPosition === 'left' ? <> {head} {body} : <> {body} {head} }
); } }; }, }); export const TabCollector = useCollect(() => ({ parent: TabGroup, child: Tab, })); export default TabGroup;