import {CSSProperties, designComponent, getComponentCls, iHTMLDivElement, isReact, mergeAttrs, onBeforeUnmount, onMounted, PropType, reactive, useClasses, useModel, useRefs} from "@peryl/react-compose"; import './stack-card.scss'; import {findReactElement} from "../../utils/findReactElement"; import StackCardItem from "../StackCardItem"; import {createEffects} from "@peryl/utils/createEffects"; import {delay} from "@peryl/utils/delay"; import {addWindowListener} from "@peryl/utils/addWindowListener"; export const StackCard = designComponent({ name: 'stack-card', props: { modelValue: { type: [String, Number] }, // 双向绑定值,当前显示哪一个子节点 prevBufferCount: { type: Number }, // 左/上侧显示元素个数 nextBufferCount: { type: Number }, // 右/下侧显示元素个数, 这个包含当前显示的元素,所以这个nextBufferCount不能小于1 stackItemWidth: { type: Number, default: 24 }, // 每一张折叠卡片横向偏移距离 stackItemHeight: { type: Number, default: 12 }, // 每一张折叠卡片纵向向偏移距离 scaleRate: { type: Number, default: 0.1 }, // 每一张折叠卡片缩放比例 demandRender: { type: Boolean }, // 按需渲染内容,当卡片没有展示的时候不渲染内容 flick: { type: Boolean }, // 轻拂模式,拖拽的时候不会触发卡片滚动,松开的时候才会触发切换,如果卡片内容有复杂的内容比如表单因为transform变化显示异常的情况下可以启用这个属性 vertical: { type: Boolean }, // 设置为true之后,开启纵向切换 verticalOffset: { type: Boolean }, // 横向切换下有效,开启纵向偏移 verticalAlign: { type: String as PropType<'top' | 'center' | 'bottom'>, default: 'center' }, // 横向切换下有效,纵向对齐方式 }, emits: { onUpdateModelValue: (val?: string | number) => true, }, slots: ['default'], setup({ props, slots, event: { emit } }) { const { effects } = createEffects(); const { refs, onRef } = useRefs({ el: iHTMLDivElement, container: iHTMLDivElement }); const model = useModel(() => props.modelValue, emit.onUpdateModelValue, { onChange: async () => {await utils.resetData();} }); const classes = useClasses(() => [ getComponentCls('stack-card'), `stack-card-direction-${props.vertical ? 'vertical' : 'horizontal'}`, { 'stack-card-touching': draggier.draggierState.touching, } ]); const draggier = (() => { /** * 拖拽响应式状态 * @author 韦胜健 * @date 2024/2/1 14:34 * @param lot 缩写,left or top * @param touching, 当前是否处于拖拽状态 */ const draggierState = reactive({ lot: 0, touching: false, }); const touchstart = (e: TouchEvent | MouseEvent) => { e.preventDefault(); e.stopPropagation(); let staticState = { /*拖拽开始时的left or top*/ startLot: draggierState.lot, /*拖拽开始时触点的x轴以及y轴位置*/ ...'touches' in e ? { startX: e.touches[0].clientX, startY: e.touches[0].clientY, } : { startX: e.clientX, startY: e.clientY, }, moveX: 0, moveY: 0 }; const { effects: draggierEffects } = createEffects(); const touchmove = (e: TouchEvent | MouseEvent) => { Object.assign( staticState, 'touches' in e ? { moveX: e.touches[0].clientX, moveY: e.touches[0].clientY } : { moveX: e.clientX, moveY: e.clientY } ); let { durX, durY } = { durX: staticState.moveX - staticState.startX, durY: staticState.moveY - staticState.startY }; if (!draggierState.touching) { /*横向切换状态下,横向移动距离超过10个像素*/ /*或者纵向切换状态下,纵向移动距离超过10个像素*/ if ((!props.vertical && Math.abs(durX) > 10) || (props.vertical && Math.abs(durY) > 10)) { draggierState.touching = true; draggierEffects.push(() => { draggierState.touching = false; if (!props.flick) { if (!!renderData) { /** * 设置滚动位置为最近的子节点 * @author 韦胜健 * @date 2024/1/4 21:12 */ const { closestItem, itemsList, itemValList } = renderData; draggierState.lot = itemsList.find( (i) => i.index === closestItem.index )!.startLot; const newVal = itemValList[closestItem.index]; if (newVal != model.value) { model.value = newVal; // delay(300).then(() => refreshItemArrowProvider.refresh()); } } } else { let activeIndex = model.value == null ? -1 : renderData.itemValList.indexOf(model.value); if (activeIndex == -1) { activeIndex = 0; } let index = ((): 1 | -1 => { if (!props.vertical) { return staticState.moveX > staticState.startX ? -1 : 1; } else { return staticState.moveY > staticState.startY ? -1 : 1; } })() + activeIndex; if (index < 0) { index = renderData.itemValList.length - 1; } if (index > renderData.itemValList.length - 1) { index = 0; } draggierState.lot = renderData.itemsList.find((i) => i.index === index)!.startLot; const newVal = renderData.itemValList[index]; if (newVal != model.value) { model.value = newVal; // delay(300).then(() => refreshItemArrowProvider.refresh()); } } }); } } if (!draggierState.touching) { return; } if (!props.flick) { /*实时设置滚动位置*/ durX = Math.ceil(durX / 3); durY = Math.ceil(durY / 10); draggierState.lot = !props.vertical ? -durX + staticState.startLot : -durY + staticState.startLot; } }; draggierEffects.push(addWindowListener('mousemove', touchmove)); draggierEffects.push(addWindowListener('mouseup', draggierEffects.clear)); draggierEffects.push(addWindowListener('touchmove', touchmove)); draggierEffects.push(addWindowListener('touchend', draggierEffects.clear)); }; return { draggierState, touchstart }; })(); const utils = { /** * 重新计算当前渲染信息数据 * @author 韦胜健 * @date 2024/1/4 21:13 */ resetData: async () => { await delay(); const activeIndex = model.value == null ? -1 : renderData.itemValList.indexOf(model.value); if (activeIndex === -1) {return;} const newItem = renderData.itemsList.find(i => i.index === activeIndex); if (!!newItem) { draggier.draggierState.lot = renderData.itemsList.find(i => i.index === activeIndex)!.startLot; } }, }; onMounted(() => { refs.el!.addEventListener('touchstart', draggier.touchstart); refs.el!.addEventListener('mousedown', draggier.touchstart); utils.resetData(); }); onBeforeUnmount(effects.clear); let renderData = { /*子节点信息,listLeft为子节点相对于o位置的偏移量*/ itemsList: [] as iStackItemDataMeta[], /*子节点的val数组*/ itemValList: [] as (string | number)[], /*子节点转换为循环列表的信息,distance为循环列表中元素距离选中元素的偏移量*/ listData: [] as (iStackItemDataMeta & { distance: number })[], /*最靠近选中元素的节点数据*/ closestItem: {} as iStackItemDataMeta, }; return () => { const content = slots.default() as any; /*从内容解析出来StackCardItem的数量及其props*/ const items: any[] = !content ? [] : findReactElement(content, (i: any) => i.type?.name === StackCardItem.name) || []; const itemValList = items.map((i, index) => i.props?.val == null ? index : i.props?.val); const total = items.length; let prevBufferCount = props.prevBufferCount == null ? Math.ceil(total / 2) : props.prevBufferCount; let nextBufferCount = props.nextBufferCount == null ? Math.ceil(total / 2) : props.nextBufferCount; const elStyles = {} as CSSProperties; if (!props.vertical) { elStyles.paddingLeft = `${(prevBufferCount) * props.stackItemWidth}px`; elStyles.paddingRight = `${(nextBufferCount - 1) * props.stackItemWidth}px`; if (!!props.verticalOffset) { elStyles.paddingBottom = `${Math.max(prevBufferCount, nextBufferCount - 1) * props.stackItemHeight}px`; } } else { elStyles.paddingTop = `${(prevBufferCount) * props.stackItemHeight}px`; elStyles.paddingBottom = `${(nextBufferCount - 1) * props.stackItemHeight}px`; /*if (!!props.verticalOffset) { elStyles.paddingBottom = `${Math.max(leftBufferCount, rightBufferCount - 1) * props.stackItemHeight}px`; }*/ } let itemStyles: CSSProperties[] = []; const stackItemSize = !props.vertical ? props.stackItemWidth : props.stackItemHeight; /*实际中拖拽的left距离,与item的startLeft匹配,item的startLeft实际上是item的中心距离*/ let pointLot = draggier.draggierState.lot; /*拖拽的left距离向右偏移半个stackItemWidth得到offsetPointLeft, 通过offsetPointLeft在item的startLeft到endLeft之间的位置找到closetItem*/ let offsetPointLot = Math.floor(stackItemSize / 2 + pointLot); /*计算每个item的startLeft以及endLeft*/ const itemsList: iStackItemDataMeta[] = itemValList.map((_, index) => ({ index, startLot: index * stackItemSize, endLot: (index + 1) * stackItemSize, })); /*总长度*/ const maxEndLot = itemsList[itemsList.length - 1]?.endLot; /*修正left,超出maxListLeft或者小于0时,循环计算left使其落在0到maxListLeft的范围*/ if (!!itemsList.length && !!maxEndLot) { while (offsetPointLot > maxEndLot) { offsetPointLot -= maxEndLot; pointLot -= maxEndLot; } while (offsetPointLot < 0) { offsetPointLot += maxEndLot; pointLot += maxEndLot; } } /*找到最靠近的位置*/ const closestItem = itemsList.reduce((prev, item) => { if (item.startLot <= offsetPointLot && item.endLot >= offsetPointLot) { return { distance: Math.abs(item.startLot - pointLot), item }; } else { return prev; } }, { distance: Infinity, item: null } as { distance: number, item: iStackItemDataMeta | null }).item!; /*循环列表前半部分*/ const prevItemsList = itemsList.slice(0, closestItem.index); /*循环列表后半部分*/ const nextItemsList = itemsList.slice(closestItem.index); /*根据左侧右侧预留的空位填补前后列表*/ while (prevItemsList.length - nextItemsList.length > 1) {nextItemsList.push(prevItemsList.shift()!);} while (nextItemsList.length - prevItemsList.length > 1) {prevItemsList.unshift(nextItemsList.pop()!);} while (prevItemsList.length > prevBufferCount) { const shiftItem = prevItemsList.shift()!; if (nextItemsList.length < nextBufferCount) { nextItemsList.push(shiftItem); } } while (nextItemsList.length > nextBufferCount) { const popItem = nextItemsList.pop()!; if (prevItemsList.length < prevBufferCount) { prevItemsList.unshift(popItem); } } /*此时后半部分的第一个元素就是选中的元素,索引就是前半部分列表的最后一个位置+1*/ const activeIndex = prevItemsList.length; /*根据最靠近left的节点来计算当前的少量偏移*/ const offsetLot = closestItem.startLot - pointLot; /*计算循环列表中每个节点距离选中节点的偏移距离*/ const list = [...prevItemsList, ...nextItemsList].map((item, index) => ({ ...item, distance: (index - activeIndex) * stackItemSize, zIndex: 0, })); /*先排序,然后根据顺序设置zIndex,最靠近left的节点zIndex最大*/ list.sort((a, b) => Math.abs(a.distance) - Math.abs(b.distance)).forEach((i, index) => { i.zIndex = total - index; }); const isPrevOfClosetItem = (index: number) => { index = index + 1; if (index >= total) {index = 0;} return index === closestItem.index; }; const isNextOfClosetItem = (index: number) => { index = index - 1; if (index < 0) {index = total - 1;} return index === closestItem.index; }; /*计算子节点样式*/ itemStyles = itemsList.map((_, index): CSSProperties => { const item = list.find(i => i.index === index); if (!item) { const isPrevHidden = isPrevOfClosetItem(_.index); const isNextHidden = !isPrevHidden && isNextOfClosetItem(_.index); if (isPrevHidden) { /*下一个就是closetItem,但是当前item隐藏,提前缩放以及进行位置偏移*/ return { opacity: 0, zIndex: total + 2, pointerEvents: 'none', transformOrigin: !props.vertical ? 'left' + (' ' + props.verticalAlign) : 'top', transform: !props.vertical ? `translate3d(${Math.ceil(-stackItemSize * 0.5)}px,0,0) scale(${1 - props.scaleRate / 2})` : `translate3d(0,${Math.ceil(-stackItemSize * 0.5)}px,0) scale(${1 - props.scaleRate / 2})` }; } else if (isNextHidden) { /*上一个就是closetItem,但是当前item隐藏,提前缩放以及进行位置偏移*/ return { opacity: 0, zIndex: total + 2, pointerEvents: 'none', transformOrigin: !props.vertical ? 'right' + (' ' + props.verticalAlign) : 'bottom', transform: !props.vertical ? `translate3d(${Math.ceil(stackItemSize * 0.5)}px,0,0) scale(${1 - props.scaleRate / 2})` : `translate3d(0,${Math.ceil(stackItemSize * 0.5)}px,0) scale(${1 - props.scaleRate / 2})` }; } else { /*不在前部分列表后部分列表的元素,可能是因为预留位置不足,这里不做显示*/ return { opacity: 0, transition: 'none' }; } } /*元素的偏移距离*/ const lot = item.distance + offsetLot; /*根据偏移距离实时计算缩放大小,越靠近left,越接近1*/ const scale = Math.max(0, 1 - Number((Math.abs(lot) / stackItemSize * props.scaleRate).toFixed(2))); if (!props.vertical) { return { transform: `translate3d(${lot}px,${props.verticalOffset ? `${lot / props.stackItemWidth * props.stackItemHeight}px` : 0},0) scale(${scale})`, transformOrigin: `${lot > 0 ? 'right' : 'left'} ${props.verticalAlign}`, zIndex: item.zIndex, // opacity: total - item.zIndex === 0 ? 1 : 0.75, }; } else { return { transform: `translate3d(0,${lot}px,0) scale(${scale})`, transformOrigin: `${lot > 0 ? 'bottom' : 'top'}`, zIndex: item.zIndex, // opacity: total - item.zIndex === 0 ? 1 : 0.75, }; } }); renderData = { itemsList, closestItem, listData: list, itemValList, }; return (