Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/dnd improvements #138

Open
wants to merge 15 commits into
base: next-15
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions css.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'react';

/**
* This is needed because React types are based on CSSType, which doesn't
* support CSS properties.
*
* See: https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
*/
declare module 'react' {
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
interface CSSProperties {
// Allow only namespaced CSS Custom Properties
[index: `--nc-${string}`]: string; // Interviewer
[index: `--tw-${string}`]: string; // Tailwind CSS
}
}
74 changes: 74 additions & 0 deletions lib/dnd/Draggable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { useCallback, useEffect, useRef } from 'react';
import useStore, { type DraggingItem } from './store';

export const useDraggable = <T extends HTMLElement>(dragItem: DraggingItem) => {
const ref = useRef<T | null>(null);
const setDraggingItem = useStore((state) => state.setDraggingItem);

const handleDragStart = useCallback(
(evt: DragEvent) => {
evt.stopPropagation();
console.log('drag start', dragItem.type);

// Now setup our dataTransfer object properly
// First we'll allow a move action — this is used for the cursor
evt.dataTransfer.effectAllowed = 'move';
// Setup some dummy drag-data to ensure dragging
evt.dataTransfer.setData('text/plain', 'some_dummy_data');
// Now we'll create a dummy image for our dragImage
const dragImage = document.createElement('div');
dragImage.setAttribute(
'style',
'position: absolute; left: 0px; top: 0px; width: 40px; height: 40px; background: red; z-index: -1',
);
document.body.appendChild(dragImage);
// And finally we assign the dragImage and center it on cursor
evt.dataTransfer.setDragImage(dragImage, 20, 20);

setDraggingItem(dragItem);
},
[setDraggingItem, dragItem],
);

const handleDragEnd = useCallback(() => {
setDraggingItem(null);
}, [setDraggingItem]);

useEffect(() => {
if (!ref.current) {
return;
}

const element = ref.current;

element.draggable = true;

element.addEventListener('dragstart', handleDragStart);
element.addEventListener('dragend', handleDragEnd);

return () => {
element.draggable = false;
element.removeEventListener('dragstart', handleDragStart);
element.removeEventListener('dragend', handleDragEnd);
};
}, [ref, handleDragEnd, handleDragStart]);

return {
ref,
};
};

export default function draggable(
WrappedComponent: React.ComponentType,
dragItem: DraggingItem,
) {
const Draggable = (props: Record<string, unknown>) => {
const { ref } = useDraggable<HTMLDivElement>(dragItem);

return <WrappedComponent {...props} ref={ref} />;
};

Draggable.displayName = `Draggable(${WrappedComponent.name})`;

return Draggable;
}
8 changes: 8 additions & 0 deletions lib/dnd/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Item Types
export const ItemTypes = [
'ROSTER_NODE',
'INTERVIEW_NODE',
'EXISTING_NODE',
] as const;

export type ItemType = (typeof ItemTypes)[number];
28 changes: 28 additions & 0 deletions lib/dnd/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { create } from 'zustand';
import { type ItemType } from './config';

export type DraggingItem = {
type: ItemType;
metaData?: Record<string, unknown>;
};

type DropZone = {
type: string;
};

type DndState = {
draggingItem: DraggingItem | null;
setDraggingItem: (item: DraggingItem | null) => void;
dropZones: DropZone[];
addDropZone: (zone: DropZone) => void;
};

const useStore = create<DndState>((set) => ({
draggingItem: null,
setDraggingItem: (item) => set({ draggingItem: item }),
dropZones: [],
addDropZone: (zone) =>
set((state) => ({ dropZones: [...state.dropZones, zone] })),
}));

export default useStore;
93 changes: 93 additions & 0 deletions lib/dnd/useDroppable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { useEffect, useRef, useState } from 'react';
import useStore, { DraggingItem } from './store';

type UseDroppableProps = {
disabled?: boolean;
onDrop?: (event: DragEvent) => void;
willAccept: (item: DraggingItem) => boolean;
};

export default function useDroppable(props: UseDroppableProps) {
const { disabled, onDrop, willAccept } = props;
const [isActive, setIsActive] = useState(false); // is the user currently dragging something
const [isValid, setIsValid] = useState(false); // is the user currently dragging something that can be dropped here
const [isOver, setIsOver] = useState(false); // is the user currently dragging something over this component

const draggingItem = useStore((state) => state.draggingItem);

const ref = useRef<HTMLDivElement>(null);

// Check if the item being dragged is valid
useEffect(() => {
if (!draggingItem) {
setIsActive(false);
setIsValid(false);

return;
}

setIsActive(true);

if (willAccept(draggingItem)) {
setIsValid(true);
} else {
setIsValid(false);
}
}, [draggingItem, willAccept]);

// Attach event listeners to the ref
useEffect(() => {
if (disabled) {
console.log('disabled');
return;
}

const handleDragEnter = (event: DragEvent) => {
event.preventDefault();
setIsOver(true);
};

const handleDragOver = (event: DragEvent) => {
event.preventDefault();
};

const handleDragLeave = (event: DragEvent) => {
event.preventDefault();
setIsOver(false);
};

const handleDrop = (event: DragEvent) => {
event.preventDefault();
setIsOver(false);

if (onDrop) {
onDrop(event);
}
};

const element = ref.current;

if (element) {
element.addEventListener('dragenter', handleDragEnter);
element.addEventListener('dragover', handleDragOver);
element.addEventListener('dragleave', handleDragLeave);
element.addEventListener('drop', handleDrop);
}

return () => {
if (element) {
element.removeEventListener('dragenter', handleDragEnter);
element.removeEventListener('dragover', handleDragOver);
element.removeEventListener('dragleave', handleDragLeave);
element.removeEventListener('drop', handleDrop);
}
};
}, [disabled]);

return {
ref,
isActive,
isValid,
isOver,
};
}
23 changes: 16 additions & 7 deletions lib/interviewer/components/Navigation.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { useSelector } from 'react-redux';
import ProgressBar from '~/lib/ui/components/ProgressBar';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '~/utils/shadcn';
import { useSelector } from 'react-redux';
import { getNavigationInfo } from '../selectors/session';

const NavigationButton = ({
Expand Down Expand Up @@ -58,21 +58,30 @@ const Navigation = ({
onClick={moveBackward}
disabled={disabled || !canMoveBackward}
>
<ChevronUp className="h-[2.4rem] w-[2.4rem]" strokeWidth="3px" />
<ChevronLeft
className="h-[2.4rem] w-[2.4rem] sm:rotate-90"
strokeWidth="3px"
/>
</NavigationButton>
<div className="m-6 flex grow">
<ProgressBar percentProgress={progress} />
<div className="m-6 flex flex-grow sm:hidden">
<ProgressBar percentProgress={progress} orientation="horizontal" />
</div>
<div className="m-6 hidden flex-grow sm:flex">
<ProgressBar percentProgress={progress} orientation="vertical" />
</div>
<NavigationButton
className={cn(
'bg-[var(--nc-light-background)]',
'hover:bg-[var(--nc-primary)]',
pulseNext && 'animate-pulse bg-success',
pulseNext && 'bg-success animate-pulse',
)}
onClick={moveForward}
disabled={disabled || !canMoveForward}
>
<ChevronDown className="h-[2.4rem] w-[2.4rem]" strokeWidth="3px" />
<ChevronRight
className="h-[2.4rem] w-[2.4rem] sm:rotate-90"
strokeWidth="3px"
/>
</NavigationButton>
</div>
);
Expand Down
30 changes: 0 additions & 30 deletions lib/interviewer/components/Node.js

This file was deleted.

33 changes: 33 additions & 0 deletions lib/interviewer/components/Node.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { type Codebook } from '@codaco/shared-consts';
import { useSelector } from 'react-redux';
import draggable from '~/lib/dnd/Draggable';
import { type DraggingItem } from '~/lib/dnd/store';
import UINode from '~/lib/ui/components/Node';
import { type NcNode } from '~/schemas/network-canvas';
import { getEntityAttributes } from '~/utils/general';
import { getNodeColor, labelLogic } from '../selectors/network';
import { getProtocolCodebook } from '../selectors/protocol';

type NodeProps = NcNode & {
type: string;
ref?: React.RefObject<HTMLDivElement>;
};

const Node = (props: NodeProps) => {
const { type, ref, ...rest } = props;

const color = useSelector(getNodeColor(type));
const codebook = useSelector(getProtocolCodebook) as Codebook;
const label = labelLogic(codebook.node![type]!, getEntityAttributes(props));

return (
<div ref={ref}>
<UINode color={color} {...rest} label={label} />
</div>
);
};

export const createDraggableNode = (item: DraggingItem) =>
draggable(Node, item);

export default Node;
30 changes: 19 additions & 11 deletions lib/interviewer/components/NodeBin.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,37 @@
import cx from 'classnames';
import PropTypes from 'prop-types';
import { createPortal } from 'react-dom';
import { compose, withProps } from 'recompose';
import useDroppable from '~/lib/dnd/useDroppable';

/**
* Renders a droppable NodeBin which accepts `EXISTING_NODE`.
*/
const NodeBin = ({ willAccept = false, isOver = false }) => {
const NodeBin = () => {
const removeNode = (node) => {
console.log('removeNode', node);

// const removeNode = (uid) => {
// dispatch(sessionActions.removeNode(uid));
// };
};

const { isOver, ref, isValid } = useDroppable({
willAccept: (item) => item.type === 'EXISTING_NODE',
onDrop: removeNode,
});

const classNames = cx(
'node-bin',
{ 'node-bin--active': willAccept },
{ 'node-bin--hover': willAccept && isOver },
{ 'node-bin--active': isValid },
{ 'node-bin--hover': isOver },
);

return createPortal(<div className={classNames} />, document.body);
return createPortal(<div className={classNames} ref={ref} />, document.body);
};

NodeBin.propTypes = {
isOver: PropTypes.bool,
willAccept: PropTypes.bool,
};

export default compose(
withProps((props) => ({
accepts: ({ meta }) => props.accepts(meta),
onDrop: ({ meta }) => props.dropHandler(meta),
})),
)(NodeBin);
export default NodeBin;
Loading
Loading