import {computed, designComponent, iMouseEvent, onBeforeUnmount, onMounted, reactive, useStyles} from "@peryl/react-compose"; import {disabledUserSelect} from "@peryl/utils/disabledUserSelect"; import {enableUserSelect} from "@peryl/utils/enableUserSelect"; import {Scroll} from "./index"; import {delay} from "@peryl/utils/delay"; import Tooltip from "../Tooltip"; import {ClientZoom} from "../ClientZoom"; export const HorizontalScrollbar = designComponent({ props: { tooltip: { type: String }, }, setup({ props }) { const dragState = { left: 0, clientX: 0, }; const scroll = Scroll.use.inject(); const state = reactive({ scrollLeft: 0, }); const width = computed(() => { return scroll.state.contentWidth > scroll.state.hostWidth ? (scroll.state.hostWidth * scroll.state.hostWidth) / scroll.state.contentWidth : 0; }); const left = computed(() => { return (scroll.state.hostWidth - width.value) * state.scrollLeft / (scroll.state.contentWidth - scroll.state.hostWidth); }); const styles = useStyles(() => ({ height: `${scroll.targetScrollbarSize.value}px`, width: `${width.value}px`, left: `${left.value}px`, backgroundColor: scroll.props.scrollbarColor, })); const handler = { onScroll: (e: Event) => { state.scrollLeft = (e.target as HTMLElement).scrollLeft; }, onMousedown: (e: iMouseEvent) => { const { clientX } = ClientZoom.getClientPosition(e); scroll.freezeState.isDragging = true; dragState.left = left.value; dragState.clientX = clientX; document.addEventListener('mousemove', handler.onMousemove); document.addEventListener('mouseup', handler.onMouseup); disabledUserSelect(); }, onMousemove: (e: MouseEvent) => { const { clientX } = ClientZoom.getClientPosition(e); let deltaX = clientX - dragState.clientX; const left = dragState.left + deltaX; let scrollLeft = left * (scroll.state.contentWidth - scroll.state.hostWidth) / (scroll.state.hostWidth - width.value); scrollLeft = Math.max(0, Math.min(scrollLeft, scroll.state.contentWidth - scroll.state.hostWidth)); if (!scroll.props.scrollAfterDragEnd) { scroll.refs.wrapper!.scrollLeft = scrollLeft; } else { state.scrollLeft = scrollLeft; } }, onMouseup: (e: MouseEvent) => { scroll.freezeState.isDragging = false; document.removeEventListener('mousemove', handler.onMousemove); document.removeEventListener('mouseup', handler.onMouseup); enableUserSelect(); if (scroll.props.scrollAfterDragEnd) { const { clientX } = ClientZoom.getClientPosition(e); let deltaX = clientX - dragState.clientX; const left = dragState.left + deltaX; scroll.refs.wrapper!.scrollLeft = left * (scroll.state.contentWidth - scroll.state.hostWidth) / (scroll.state.hostWidth - width.value); } }, }; onMounted(() => {delay(23).then(() => {state.scrollLeft = scroll.refs.wrapper?.scrollLeft || 0;});}); onBeforeUnmount(scroll.hooks.onScroll.use(e => {handler.onScroll(e);})); return { render: () => { let content =
; if (!!props.tooltip) {content = ({content});} return (
{content}
); } }; }, });