king
2020-11-03 37a134bd23ec4b227a0e010b08a1a89c2bbaaa0d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, { useState } from 'react'
import { useDrop } from 'react-dnd'
import { is, fromJS } from 'immutable'
import update from 'immutability-helper'
import { message, Empty } from 'antd'
 
import Utils from '@/utils/utils.js'
import Card from './card'
import './index.scss'
 
const Container = ({config, editId, handleList, editCard, deleteCard, doubleClickCard }) => {
  const [cards, setCards] = useState(config.components)
  const moveCard = (id, atIndex) => {
    const { card, index } = findCard(id)
    const _cards = update(cards, { $splice: [[index, 1], [atIndex, 0, card]] })
    handleList({...config, components: _cards})
  }
 
  if (!is(fromJS(cards), fromJS(config.components))) {
    setCards(config.components)
  }
  
  const findCard = id => {
    const card = cards.filter(c => `${c.uuid}` === id)[0]
    return {
      card,
      index: cards.indexOf(card),
    }
  }
 
  const updateConfig = (element) => {
    handleList({...config, components: cards.map(item => item.uuid === element.uuid ? element : item)})
  }
 
  const [, drop] = useDrop({
    accept: 'mob',
    drop(item) {
      if (item.hasOwnProperty('originalIndex')) {
        return
      }
 
      if (cards.length > 0 && cards[0].type === 'login') {
        message.warning('登录页不可添加其他元素!')
        return
      }
 
      let newcard = {
        uuid: Utils.getuuid(),
        type: item.componentType,
        subtype: item.subtype,
      }
 
      let targetId = ''
 
      if (item.dropTargetId) {
        targetId = item.dropTargetId
        delete item.dropTargetId
      } else if (cards.length > 0) {
        targetId = cards[cards.length - 1].uuid
      }
 
      const { index: overIndex } = findCard(`${targetId}`) // cards为空时 overIndex 为 -1
      const _cards = update(cards, { $splice: [[overIndex + 1, 0, newcard]] })
 
      handleList({...config, components: _cards})
    }
  })
 
  return (
    <div ref={drop} className="mob-shell-inner">
      {cards.map(card => (
        <Card
          id={card.uuid}
          key={card.uuid}
          card={card}
          editId={editId}
          moveCard={moveCard}
          editCard={editCard}
          delCard={deleteCard}
          findCard={findCard}
          updateConfig={updateConfig}
          doubleClickCard={doubleClickCard}
        />
      ))}
      {cards.length === 0 ?
        <Empty description="请添加组件" /> : null
      }
    </div>
  )
}
export default Container