react-dnd#DragSourceMonitor TypeScript Examples

The following examples show how to use react-dnd#DragSourceMonitor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From hive with MIT License 6 votes vote down vote up
widgetSource = {
    beginDrag(props: Props) {
        return {
            model: props.model,
            id: props.model.uuid,
            originalIndex: props.dashboardView.currentPage.findWidgetIndex(props.model.uuid),
        };
    },

    endDrag(props: Props, monitor: DragSourceMonitor) {
        const { id: droppedId, originalIndex } = monitor.getItem();
        const didDrop = monitor.didDrop();

        if (!didDrop) {
            props.dashboardView.currentPage.moveWidget(droppedId, originalIndex);
        }
    },
}
Example #2
Source File: DragItem.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
DragItem: React.FC<DragItemProps> = (props) => {
  const { label, value, onMoved, index, disabled, ...rest } = props;
  const prefixCls = `${usePrefixCls(PREFIX)}`;
  const ref = useRef<HTMLDivElement>(null);
  const [{ handlerId }, drop] = useDrop({
    accept: 'drag-item',
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId(),
      };
    },
    hover(item: { index: number; type: string; id: string }, monitor: DropTargetMonitor) {

      const dragIndex = item.index;
      const hoverIndex = index;

      if (dragIndex === hoverIndex) {
        return;
      }
      const hoverBoundingRect = ref.current?.getBoundingClientRect() || { bottom: 0, top: 0 };
      const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
      const clientOffset = monitor.getClientOffset();

      const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;

      // Dragging upwards or downwards
      if ((dragIndex < hoverIndex && hoverClientY < hoverMiddleY) || (dragIndex > hoverIndex && hoverClientY > hoverMiddleY)) {
        return
      };

      onMoved?.(dragIndex as number, hoverIndex);
      // eslint-disable-next-line no-param-reassign
      item.index = hoverIndex;
    },
  });
  const [, drag] = useDrag({
    item: { type: 'drag-item', id: value, index },
    collect: (monitor: DragSourceMonitor) => ({
      isDragging: monitor.isDragging(),
    }),
    canDrag: !disabled,
  });

  drag(drop(ref));
  return (
    <div
      className={classNames(`${prefixCls}--item`, `${prefixCls}--item--drag`, {
        [`${prefixCls}--item--disabled`]: disabled,
      })}
      ref={ref}
      data-handler-id={handlerId}
    >
      <DragOutlined
        className={classNames(`${prefixCls}--item--drag--icon`, {
          [`${prefixCls}--item--drag--icon--disabled`]: disabled,
        })}
        color="#ADB2C2"
        size="14px"
      />
      <Item label={label} value={value} disabled={disabled} {...rest} />
    </div>
  );
}
Example #3
Source File: WorkoutCard.tsx    From calendar-hack with MIT License 6 votes vote down vote up
WorkoutCard: React.FC<WorkoutCardProps> = ({ dayDetails, date, units, swap }) => {

    const [{ isDragging }, drag, preview] = useDrag({
        item: { date: date, type: ItemTypes.DAY, dayDetails: dayDetails, units: units },
        collect: (monitor) => ({
            isDragging: monitor.isDragging(),
            canDrag: dayDetails !== undefined,
        }),
        end: (item: { date: Date } | undefined, monitor: DragSourceMonitor) => {
            const dropResult = monitor.getDropResult()
            if (item && dropResult) {
            }
        },
    })

    return (
        <Card>
            <Dateline dayDetails={dayDetails} units={units} date={date} />
            <DragSource isDragging={isDragging} dayDetails={dayDetails} ref={preview}>
                <Preview generator={generateDayPreview} />
                <Content>
                    <div ref={drag}>
                        <DragHandle viewBox="0 0 32 36" />
                    </div>
                    <p>{renderDesc(dayDetails, dayDetails.sourceUnits, units)}</p>
                </Content>
            </DragSource>
        </Card >
    );
}
Example #4
Source File: DayOfWeekHeader.tsx    From calendar-hack with MIT License 5 votes vote down vote up
DayOfWeekHeader: React.FC<Props> = ({ dow, swapDow, selectDow, hoverDow }) => {

    const [{ isOver, canDrop, droppedItem }, drop] = useDrop({
        accept: ItemTypes.DOW,
        canDrop: () => true,
        drop: () => { swapDow(dow, droppedItem.dow); return; },
        collect: (monitor) => {
            if (monitor.isOver()) {
                hoverDow(dow);
            }
            return {
                isOver: monitor.isOver(),
                canDrop: monitor.canDrop(),
                droppedItem: monitor.getItem()
            }
        },
    })

    const [{ isDragging }, drag, preview] = useDrag({
        item: { type: ItemTypes.DOW, dow: dow },
        collect: (monitor) => {
            if (monitor.isDragging()) {
                selectDow(dow);
            }
            return {
                isDragging: monitor.isDragging(),
            };
        },
        begin: (monitor: DragSourceMonitor) => {
            selectDow(dow);
        },
        end: (item: { dow: dayOfWeek } | undefined, monitor: DragSourceMonitor) => {
            const dropResult = monitor.getDropResult()
            if (item && dropResult) {
                selectDow(undefined);
                hoverDow(undefined);
            }
        },
    })

    return (
        <div style={{
            position: 'relative',
            width: '100%',
            height: '100%',
        }}>
            <DragSource isDragging={isDragging} dow={dow}>
                <DropTarget isOver={isOver} canDrop={canDrop} ref={drop}>
                    <Preview generator={generateDowPreview} />
                    <div ref={preview}>
                        <Root ref={drag}>
                            <DragHandle viewBox="0 0 32 36" />
                            <div>{dow}</div>
                        </Root>
                    </div>
                </DropTarget>
            </DragSource>
        </div>
    )
}
Example #5
Source File: useDraggable.ts    From ui-schema with MIT License 4 votes vote down vote up
useDraggable = <C extends HTMLElement = HTMLElement, S extends ItemSpec = ItemSpec>(
    {
        item,
        allowedTypes,
        scope: localScope,
        refRoot,
    }: {
        item: S
        allowedTypes: string[] | List<string> | undefined
        scope?: string
        refRoot: React.MutableRefObject<C | null>
    }
): {
    isOver: boolean
    canDrop: boolean
    drop: ConnectDropTarget
    isDragging: boolean
    drag: ConnectDragSource
    preview: ConnectDragPreview
    setDisableDrag: React.Dispatch<React.SetStateAction<boolean>>
    canDrag: boolean
} => {
    const [disableDrag, setDisableDrag] = React.useState<boolean>(false)
    const {onMove, scope} = useKitDnd<C>()

    const [{isOver, canDrop}, drop] = useDrop<S, S, { handlerId: (Identifier | null), isOver: boolean, canDrop: boolean }>(() => ({
        accept: localScope ? localScope : (scope ? '_' + scope : '_') as string,
        options: {},
        collect: (monitor: DropTargetMonitor<C>) => ({
            isOver: monitor.isOver({shallow: true}),
            canDrop: monitor.canDrop(),
            handlerId: monitor.getHandlerId(),
        }),
        canDrop: (fromItem: S, monitor: DropTargetMonitor<C>) => {
            if (!monitor.isOver({shallow: true})) {
                return false
            }
            return (
                !fromItem.dataKeys.push(fromItem.index).equals(item.dataKeys.push(item.index)) &&
                fromItem.id !== item.id
            ) && (
                !allowedTypes ||
                allowedTypes.indexOf(fromItem.type) !== -1
            )
        },
        hover(fromItem: S, monitor: DropTargetMonitor<C>) {
            if (monitor.canDrop()) {
                onMove({
                    targetElement: refRoot.current as C,
                    toItem: item as unknown as S,
                    fromItem: fromItem as unknown as S,
                    monitor,
                })
            }
        },
    }), [item, localScope, scope, allowedTypes, refRoot])

    const [{canDrag, isDragging}, drag, preview] = useDrag<S, S, { isDragging: boolean, canDrag: boolean }>(() => ({
        type: localScope ? localScope : (scope ? '_' + scope : '_') as string,
        item: {...item},
        collect: (monitor: DragSourceMonitor<S>) => ({
            isDragging: monitor.isDragging(),
            canDrag: monitor.canDrag(),
        }),
        canDrag: () => {
            return !disableDrag
        },
        isDragging: (monitor: DragSourceMonitor<S>) => {
            const {index, dataKeys} = item
            const tmpItem = monitor.getItem() as S
            if (!tmpItem) return false
            let itemDataKeys = tmpItem.dataKeys as List<number>
            if (!List.isList(itemDataKeys)) {
                itemDataKeys = List(itemDataKeys) as List<number>
            }
            return tmpItem.dataKeys.push(tmpItem.index).equals(dataKeys.push(index)) &&
                itemDataKeys.equals(!List.isList(dataKeys) ? List(dataKeys) : dataKeys)
        },
    }), [
        item, localScope, scope, disableDrag,
    ])

    return {
        isOver, canDrop, drop,
        isDragging, drag, preview,
        setDisableDrag,
        // todo: somehow `canDrag` isn't `false` when it is internally `false`
        canDrag: canDrag && !disableDrag,
    }
}