|
| 1 | +import React, { FunctionComponent } from 'react'; |
| 2 | +import { |
| 3 | + DropTarget, |
| 4 | + DropTargetCollector, |
| 5 | + DropTargetConnector, |
| 6 | + DropTargetMonitor, |
| 7 | + DropTargetSpec, |
| 8 | +} from 'react-dnd'; |
| 9 | + |
| 10 | +import { MAKE_TEMPLATE_DROP_KEY } from '../Content/SandboxCard'; |
| 11 | + |
| 12 | +import { Item } from './Item'; |
| 13 | + |
| 14 | +import TemplateIcon from '-!svg-react-loader!@codesandbox/common/lib/icons/template.svg'; |
| 15 | + |
| 16 | +type ComponentProps = { |
| 17 | + currentPath: string; |
| 18 | + teamId?: string; |
| 19 | +}; |
| 20 | +type Props = ComponentProps & CollectedProps; |
| 21 | +const TemplateItemComponent: FunctionComponent<Props> = ({ |
| 22 | + canDrop, |
| 23 | + connectDropTarget, |
| 24 | + currentPath, |
| 25 | + isOver, |
| 26 | + teamId, |
| 27 | +}) => { |
| 28 | + const path = teamId |
| 29 | + ? `/dashboard/teams/${teamId}/templates` |
| 30 | + : `/dashboard/templates`; |
| 31 | + |
| 32 | + return connectDropTarget( |
| 33 | + <div> |
| 34 | + <Item |
| 35 | + active={currentPath === path} |
| 36 | + Icon={TemplateIcon} |
| 37 | + name={teamId ? 'Team Templates' : 'My Templates'} |
| 38 | + path={path} |
| 39 | + style={ |
| 40 | + isOver && canDrop ? { backgroundColor: 'rgba(0, 0, 0, 0.3)' } : {} |
| 41 | + } |
| 42 | + /> |
| 43 | + </div> |
| 44 | + ); |
| 45 | +}; |
| 46 | + |
| 47 | +const entryTarget: DropTargetSpec<ComponentProps> = { |
| 48 | + canDrop: (_props, { getItem }) => getItem() !== null, |
| 49 | + drop: ({ teamId }, { isOver }) => { |
| 50 | + // Check if only child is selected: |
| 51 | + if (!isOver({ shallow: true })) { |
| 52 | + return {}; |
| 53 | + } |
| 54 | + |
| 55 | + // Used in SandboxCard |
| 56 | + return { |
| 57 | + [MAKE_TEMPLATE_DROP_KEY]: true, |
| 58 | + teamId, |
| 59 | + }; |
| 60 | + }, |
| 61 | +}; |
| 62 | + |
| 63 | +const collectTarget: DropTargetCollector<CollectedProps> = ( |
| 64 | + connect, |
| 65 | + monitor |
| 66 | +) => ({ |
| 67 | + canDrop: monitor.canDrop(), |
| 68 | + // Call this function inside render() |
| 69 | + // to let React DnD handle the drag events: |
| 70 | + connectDropTarget: connect.dropTarget(), |
| 71 | + // You can ask the monitor about the current drag state: |
| 72 | + isOver: monitor.isOver({ shallow: true }), |
| 73 | +}); |
| 74 | + |
| 75 | +type CollectedProps = { |
| 76 | + canDrop: ReturnType<DropTargetMonitor['canDrop']>; |
| 77 | + connectDropTarget: ReturnType<DropTargetConnector['dropTarget']>; |
| 78 | + isOver: ReturnType<DropTargetMonitor['isOver']>; |
| 79 | +}; |
| 80 | +export const TemplateItem = DropTarget<ComponentProps, CollectedProps>( |
| 81 | + ['SANDBOX'], |
| 82 | + entryTarget, |
| 83 | + collectTarget |
| 84 | +)(TemplateItemComponent); |
0 commit comments