import {computed, CSSProperties, designComponent, getComponentCls, iHTMLDivElement, iMouseEvent, isReact, iTouchEvent, onBeforeUnmount, PropType, reactive, StyleProperties, useClasses, useModel, useRefs, useStyles,} from '@peryl/react-compose'; import './carousel.scss'; import CarouselItem, {iCarouselItemMeta} from '../CarouselItem'; import {createCounter} from '@peryl/utils/createCounter'; import {Icon} from '../Icon'; import {useWatchAutoClear} from '../../utils/watchEffectAutoClear'; import {findReactElement} from '../../utils/findReactElement'; import {addElementListener} from '@peryl/utils/addElementListener'; import {createEffects} from "@peryl/utils/createEffects"; import {unit} from "@peryl/utils/unit"; import {doNothing} from "@peryl/utils/doNothing"; import {delay} from "@peryl/utils/delay"; import {Tooltip} from "../Tooltip"; import {buildCycleIndexList} from "../../utils/buildCycleIndexList"; import {ComponentUtils} from "../../utils/ComponentUtils"; import {addWindowListener} from "@peryl/utils/addWindowListener"; export const Carousel = designComponent({ name: 'carousel', provideRefer: true, props: { modelValue: { type: [String, Number] }, // 双向绑定值 vertical: { type: Boolean }, // 纵向轮播 card: { type: Boolean }, // 卡片形式切换 noIndicator: { type: Boolean }, // 禁用指示器 indicatorStyle: { type: String as PropType<'line' | 'dot' | 'text'>, default: 'line' }, // 指示器类型 switchButton: { type: Boolean, default: true }, // 显示切换按钮 largeSwitchButton: { type: Boolean }, // 使用大型的切换按钮 autoPlay: { type: [Boolean, Number] as PropType, default: true }, // 自动播放 height: { type: [String, Number] }, // 固定高度 disableSwiper: { type: Boolean }, // 禁用拂动切换 indicatorTrigger: { type: String as PropType<'click' | 'hover'>, default: 'click' }, // 指示器的触发类型,click点击,hover鼠标悬浮 alignItems: { type: String as PropType, default: 'center' }, // 每个子元素的对其方式 fullHeight: { type: Boolean }, // 适配容器高度,开启这个特性会限制每个子元素的高度为容器高度 prevSwitchButtonTip: { type: String }, // 上一页按钮提示文本 nextSwitchButtonTip: { type: String }, // 下一页按钮提示文本 }, emits: { onUpdateModelValue: (val?: string | number) => true }, scopeSlots: { indicator: (scope: { total: number; activeIndex: number; prevIndex: number; nextIndex: number; }) => {} }, slots: ['default', 'cover'], setup({ props, event: { emit }, slots, scopeSlots }) { const { refs, onRef } = useRefs({ el: iHTMLDivElement }); const id = nextCarouselId(); const model = useModel(() => props.modelValue, emit.onUpdateModelValue, { onChange: async (newVal, oldVal) => { methods.show(newVal, oldVal, false); } }); const direction = computed(() => /*方向,是横向还是纵向*/ props.vertical ? ('vertical' as const) : ('horizontal' as const) ); const classes = useClasses(() => [ getComponentCls('carousel'), `carousel-${direction.value}`, { 'carousel-card': props.card, 'carousel-disable-swiper': props.disableSwiper, 'carousel-touching': !!touchHandler.touchState.touching, 'carousel-full-height': !!props.fullHeight, 'carousel-fixed-height': !!props.height, 'carousel-large-switch-button': !!props.largeSwitchButton } ]); const styles = useStyles((style) => { if (!!props.height) { style.height = unit(props.height); } }); const state = reactive({ /*临时绑定值,不直接使用modelValue,这个值与baseLeft,baseLeftCount对应,同时变化*/ tempValue: model.value, }); const utils = { /** * 获取container item的style * @author 韦胜健 * @date 2023/4/27 23:13 */ getItemStyles(itemMeta: iCarouselItemMeta) { const style = {} as StyleProperties; let base = -itemMeta.props.index; // 令item偏移到第一个item的位置 if (itemMeta.props.distance < 0) { base--; } else if (itemMeta.props.distance > 0) { base++; } const isMoving = Math.abs(itemMeta.props.distance) <= 1; /*实际偏移位置*/ style.transform = props.vertical ? `translate3d(0,calc(${base * 100}% + ${!isMoving ? 0 : (touchHandler.touchState.touching?.moveTop || 0)}px),0)` : `translate3d(calc(${base * 100}% + ${!isMoving ? 0 : (touchHandler.touchState.touching?.moveLeft || 0)}px),0,0)`; /*既不是prev,也不是next以及active的item不显示,但是占用空间,以实现自动撑开高度的效果*/ if (Math.abs(itemMeta.props.distance) > 1) { style.opacity = '0'; style.transition = 'none'; style.pointerEvents = 'none'; } if (touchHandler.touchState.touching) { style.transition = 'none'; } if (itemMeta.props.distance != 0) { /*如果一个元素从循环列表的一端跑到另一端,则禁用过度动画*/ if (!!tempState.prev && !!tempState.curr) { /*上一次在循环列表的左边还是右边*/ const prevPos: 'left' | 'right' | null = ((() => { if (itemMeta.props.index === tempState.prev!.current) {return null;} const prevCurrIndex = tempState.prev!.cycleIndexList.indexOf(tempState.prev!.current); const prevItemIndex = tempState.prev!.cycleIndexList.indexOf(itemMeta.props.index); return prevCurrIndex > prevItemIndex ? 'left' : 'right'; })()); /*这一次在循环列表的左边还是右边*/ const nextPos: 'left' | 'right' | null = ((() => { if (itemMeta.props.index === tempState.curr!.current) {return null;} const nextCurrIndex = tempState.curr!.cycleIndexList.indexOf(tempState.curr!.current); const nextItemIndex = tempState.curr!.cycleIndexList.indexOf(itemMeta.props.index); return nextCurrIndex > nextItemIndex ? 'left' : 'right'; })()); /*两次渲染的左右位置不同的话,则禁用过度动画*/ if (!!prevPos && !!nextPos && prevPos !== nextPos) { style.transition = 'none'; } } } style.zIndex = itemProps.length - Math.abs(itemMeta.props.distance); return style; } }; const touchHandler = (() => { let touchState = reactive({ /*拖拽开始时x定位*/ startX: null as null | number, /*拖拽开始时y定位*/ startY: null as null | number, /*拖拽的状态,拖拽开始时偏移大于5个px开始计算*/ touching: null as null | { /*拖拽开始时container的left偏移量*/ startLeft: number; /*拖拽 过程中container的left偏移量*/ moveLeft: number; /*拖拽开始时container的top偏移量*/ startTop: number; /*拖拽 过程中container的top偏移量*/ moveTop: number; } }); /** * 拖拽开始 * @author 韦胜健 * @date 2023/4/27 23:17 */ const touchstart = (e: TouchEvent | MouseEvent) => { e.preventDefault(); e.stopPropagation(); const { effects: draggierEffects } = createEffects(); if (props.vertical) { touchHandler.touchState.startY = 'touches' in e ? e.touches[0].clientY : e.clientY; } else { touchHandler.touchState.startX = 'touches' in e ? e.touches[0].clientX : e.clientX; } /** * 拖拽移动 * @author 韦胜健 * @date 2023/4/27 23:17 */ const touchmove = (e: TouchEvent | MouseEvent) => { if (props.disableSwiper) { return; } if (props.vertical) { const durY = ('touches' in e ? e.touches[0].clientY : e.clientY) - touchHandler.touchState.startY!; if (!touchState.touching) { if (Math.abs(durY) > 5) { touchState.touching = { startLeft: 0, moveLeft: 0, startTop: 0, moveTop: 0, }; draggierEffects.push(touchend); } } if (touchState.touching) { touchState.touching.moveTop = touchState.touching.startTop + durY; } } else { const durX = ('touches' in e ? e.touches[0].clientX : e.clientX) - touchHandler.touchState.startX!; if (!touchState.touching) { if (Math.abs(durX) > 5) { touchState.touching = { startLeft: 0, moveLeft: 0, startTop: 0, moveTop: 0, }; draggierEffects.push(touchend); } } if (touchState.touching) { touchState.touching.moveLeft = touchState.touching.startLeft + durX; } } }; /** * 拖拽结束 * @author 韦胜健 * @date 2023/4/27 23:17 */ const touchend = async (e: iTouchEvent | iMouseEvent) => { if (!touchState.touching) { return; } let dur = props.vertical ? touchState.touching.moveTop - touchState.touching.startTop! : touchState.touching.moveLeft - touchState.touching.startLeft!; const info = await ComponentUtils.getElInfo(`#${id}`); const duration = props.vertical ? info.height / 4 : info.width / 4; let activeIndex = itemProps!.findIndex((i) => i == state.tempValue); if (activeIndex === -1) { activeIndex = 0; } if (itemProps.length <= 1) { /** * 轮播节点少于等于1个,不做切换 * @author 韦胜健 * @date 2024/1/4 10:57 */ dur = 0; } else { /** * 当轮播节点数量少于或者等于2时, * 如果是第一个节点后移,不做切换 * 如果是最后一个节点前移,不做切换 * @author 韦胜健 * @date 2024/1/4 10:56 */ if (itemProps.length <= 2) { if (dur < 0 && activeIndex === itemProps.length - 1) { dur = 0; } else if (dur > 0 && activeIndex === 0) { dur = 0; } } } if (dur > duration) { /*上一张*/ activeIndex--; } else if (dur < -duration) { /*下一张*/ activeIndex++; } if (activeIndex < 0) { activeIndex = itemProps!.length - 1; } if (activeIndex >= itemProps!.length) { activeIndex = 0; } state.tempValue = itemProps![activeIndex]; model.value = state.tempValue; reset(); }; draggierEffects.push(addWindowListener('mousemove', touchmove)); draggierEffects.push(addWindowListener('touchmove', touchmove)); draggierEffects.push(addWindowListener('mouseup', draggierEffects.clear)); draggierEffects.push(addWindowListener('touchend', draggierEffects.clear)); }; const reset = () => { /*重置拖拽状态*/ touchState.startX = null; touchState.startY = null; touchState.touching = null; }; return { touchstart, touchState, reset }; })(); let itemProps = [] as any[]; const play = (() => { let timer: any = null; const start = () => { if (!!timer) { return; } timer = setInterval( () => { methods.next(); }, typeof props.autoPlay === 'boolean' ? 3000 : props.autoPlay ); }; const stop = () => { if (!!timer) { clearInterval(timer); timer = null; } }; return { start, stop }; })(); const methods = { /** * 切换到上一张 * @author 韦胜健 * @date 2023/4/28 16:21 */ prev: async (): Promise => { /*当前只有一个元素,不做处理*/ if (itemProps.length < 2) {return;} if (!itemProps) { return; } let activeIndex = itemProps.findIndex((i) => i === state.tempValue); if (activeIndex === -1) { activeIndex = 0; } /*当前只有两个元素,并且已经是第一个元素了,点击prev的时候转为next*/ if (activeIndex === 0 && itemProps.length === 2) { return methods.next(); } let prevIndex = activeIndex == 0 ? itemProps.length - 1 : activeIndex - 1; state.tempValue = itemProps[prevIndex]; model.value = state.tempValue; if (props.autoPlay) { methods.stop(); methods.start(); } }, /** * 切换到下一张 * @author 韦胜健 * @date 2023/4/28 16:21 */ next: async () => { /*当前只有一个元素,不做处理*/ if (itemProps.length < 2) {return;} if (!itemProps) { return; } let activeIndex = itemProps.findIndex((i) => i === state.tempValue); if (activeIndex === -1) { activeIndex = 0; } /*当前只有两个元素,并且已经是最后一个元素了,点击next的时候转为prev*/ if (activeIndex === itemProps.length - 1 && itemProps.length === 2) { return methods.prev(); } let nextIndex = activeIndex == itemProps.length - 1 ? 0 : activeIndex + 1; state.tempValue = itemProps[nextIndex]; model.value = state.tempValue; if (props.autoPlay) { methods.stop(); methods.start(); } }, ...play, show: async (newVal: any, oldVal: any, autoEmit = true) => { if (autoEmit && newVal === oldVal) { return; } /*更新tempValue*/ state.tempValue = newVal; if (autoEmit) { model.value = state.tempValue; } if (!!props.autoPlay) { methods.stop(); methods.start(); } }, }; const handler = { onDoubleClickSwitchButton: (e: iMouseEvent) => { e.stopPropagation(); } }; useWatchAutoClear( /*拖拽过程中禁用自动播放*/ () => props.autoPlay && !touchHandler.touchState.touching, (autoPlay) => { if (!!autoPlay) { methods.start(); } return () => { methods.stop(); }; } ); const { effects: listenerEffects } = createEffects(); useWatchAutoClear(() => props.disableSwiper, disableSwiper => { listenerEffects.clear(); if (disableSwiper) { touchHandler.reset(); return doNothing; } delay().then(() => { listenerEffects.push(addElementListener(refs.el!, 'touchstart', touchHandler.touchstart, { passive: false })); listenerEffects.push(addElementListener(refs.el!, 'mousedown', touchHandler.touchstart, { passive: false })); }); return listenerEffects.clear; }); onBeforeUnmount(() => { play.stop(); listenerEffects.clear(); }); let tempState = { /*上一次渲染的循环列表数据*/ prev: null as null | { current: number, cycleIndexList: number[], }, /*下一次渲染的循环列表数据*/ curr: null as null | { current: number, cycleIndexList: number[], } }; return { refer: { utils, methods, refs, }, render: () => { const content = slots.default() as any; const items: any[] = !content ? [] : findReactElement(content, (i: any) => i.type?.name === CarouselItem.name) || []; itemProps = items.map((i, index) => i.props?.val == null ? index : i.props?.val); const total = items.length; const activeIndex = !state.tempValue ? 0 : itemProps.findIndex((i) => i === state.tempValue); const { index2distance, cycleIndexList, currentIndexInCycle } = buildCycleIndexList({ length: itemProps.length, current: activeIndex }); const prevIndex = cycleIndexList[currentIndexInCycle] - 1; const nextIndex = cycleIndexList[currentIndexInCycle] + 1; if (!tempState.curr || tempState.curr.current !== activeIndex) { tempState.prev = tempState.curr; tempState.curr = { current: activeIndex, cycleIndexList: cycleIndexList, }; } return (
{items.map((Item: any, index: number) => { const ItemComp = isReact ? Item.type : Item; return ( ); })}
{!props.noIndicator && scopeSlots.indicator( { total, activeIndex, prevIndex, nextIndex }, (() => { return (
{(() => { if (props.indicatorStyle === 'text') { return `${activeIndex + 1} / ${total}`; } else { return itemProps.map((_, index) => (
methods.show(itemProps[index], model.value) } : { onMouseEnter: () => methods.show(itemProps[index], model.value) }} className={`carousel-indicator-item ${ index === activeIndex ? 'carousel-indicator-item-active' : index === prevIndex ? 'carousel-indicator-item-prev' : index === nextIndex ? 'carousel-indicator-item-next' : '' }`} /> )); } })()}
); })() )} {props.switchButton && (
{(() => { const prevButton = (
); return !!props.prevSwitchButtonTip ? {prevButton} : prevButton; })()} {(() => { const nextButton = (
); return !!props.nextSwitchButtonTip ? {nextButton} : nextButton; })()}
)} {slots.cover.isExist() && (
{slots.cover()}
)}
); } }; } }); const nextCarouselId = createCounter('carousel'); export default Carousel;