useDnD.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // import { useVueFlow,Position,MarkerType } from '@vue-flow/core';
  2. import { useVueFlow, Position, MarkerType } from "@vue-flow/core"
  3. import { ref, watch } from "vue"
  4. import { ElMessage, ElButton, ElDialog, ElSelect } from "element-plus"
  5. import { request, getImage } from "@/utils/request"
  6. import emitter from "@/utils/emitter"
  7. import { useProjectStore } from "@/store/project"
  8. import { nextTick } from "vue"
  9. import tempic from "@/assets/img/temp.png"
  10. const projectStore = useProjectStore()
  11. let nid = 0
  12. // 用于计数
  13. let nodecount = 0
  14. let treeobj = ref([])
  15. let datas = {}
  16. // 用于存储组件的临时数据
  17. let com = {}
  18. /**
  19. * @returns {string} - A unique id.
  20. */
  21. function getId() {
  22. const timestamp = Date.now() // 获取当前时间的毫秒数
  23. return `${nid}${nodecount++}_${timestamp}`
  24. }
  25. function imagefun() {
  26. console.log(nid)
  27. return (datas = {
  28. comId: com.comId,
  29. label: com.name,
  30. image: getImage(com.image) || tempic,
  31. idCode: com.idCode,
  32. pcId: "",
  33. idCodeser: ""
  34. })
  35. }
  36. /**
  37. * In a real world scenario you'd want to avoid creating refs in a global scope like this as they might not be cleaned up properly.
  38. * @type {{draggedType: Ref<string|null>, isDragOver: Ref<boolean>, isDragging: Ref<boolean>}}
  39. */
  40. const state = {
  41. /**
  42. * The type of the node being dragged.
  43. */
  44. draggedType: ref(null),
  45. isDragOver: ref(false),
  46. isDragging: ref(false)
  47. }
  48. // 组件创建
  49. const createComponent = async (pid, comId) => {
  50. const params = {
  51. transCode: "ES0004",
  52. pid: pid || "",
  53. comId: comId || "" // 组件ID
  54. }
  55. try {
  56. const res = await request(params)
  57. return {
  58. pcId: res.pcId,
  59. ser: res.ser,
  60. idCode: res.idCode
  61. }
  62. } catch (err) {
  63. ElMessage.error(err.returnMsg)
  64. }
  65. }
  66. // 用来存储每种组件名称出现次数的对象
  67. const nameCount = {}
  68. export default function useDragAndDrop() {
  69. const { draggedType, isDragOver, isDragging } = state
  70. const {
  71. addNodes,
  72. addEdges,
  73. findNode,
  74. screenToFlowCoordinate,
  75. onNodesInitialized,
  76. updateNode,
  77. updateNodeInternals
  78. } = useVueFlow()
  79. watch(isDragging, (dragging) => {
  80. document.body.style.userSelect = dragging ? "none" : ""
  81. })
  82. function onDragStart(event, type, data) {
  83. if (event.dataTransfer) {
  84. com = data //传递组件数据
  85. nid = data.comId //传递组件ID
  86. event.dataTransfer.setData("application/vueflow", type)
  87. event.dataTransfer.effectAllowed = "move"
  88. }
  89. draggedType.value = type
  90. //draggedType.value = 'smoothstep'
  91. isDragging.value = true
  92. document.addEventListener("drop", onDragEnd)
  93. }
  94. /**
  95. * Handles the drag over event.
  96. *
  97. * @param {DragEvent} event
  98. */
  99. function onDragOver(event) {
  100. event.preventDefault()
  101. if (draggedType.value) {
  102. isDragOver.value = true
  103. if (event.dataTransfer) {
  104. event.dataTransfer.dropEffect = "move"
  105. }
  106. }
  107. }
  108. function handleNodeDrop(e) { }
  109. function onDragLeave(e) {
  110. isDragOver.value = false
  111. }
  112. function onDragEnd() {
  113. isDragging.value = false
  114. isDragOver.value = false
  115. draggedType.value = null
  116. nid = ""
  117. document.removeEventListener("drop", onDragEnd)
  118. }
  119. /**
  120. * Handles the drop event.
  121. *
  122. * @param {DragEvent} event
  123. */
  124. async function onDrop(event) {
  125. const GRID_SIZE = 5; // 网格大小,调整为需要的对齐单位(如 10 或 50)
  126. const position = screenToFlowCoordinate({
  127. x: event.clientX,
  128. y: event.clientY
  129. });
  130. // 对齐到网格
  131. const alignedX = Math.round(position.x / GRID_SIZE) * GRID_SIZE;
  132. const alignedY = Math.round(position.y / GRID_SIZE) * GRID_SIZE;
  133. const pid = projectStore.pid;
  134. const nodeId = getId();
  135. const image1 = imagefun();
  136. const componentName = image1.idCode;
  137. if (!nameCount[componentName]) {
  138. nameCount[componentName] = 0;
  139. }
  140. const newName = `${componentName}${nameCount[componentName]}`;
  141. // 创建初始节点(使用对齐后的位置)
  142. const newNode = {
  143. id: nodeId,
  144. type: draggedType.value,
  145. position: { x: alignedX, y: alignedY },
  146. data: {
  147. ...image1,
  148. uid: newName
  149. }
  150. };
  151. // 1. 先添加节点到画布
  152. addNodes([newNode]);
  153. // 2. 调整位置(确保对齐效果保留,居中调整后仍对齐到网格)
  154. const { off } = onNodesInitialized(() => {
  155. updateNode(nodeId, (node) => {
  156. const adjustedX = Math.round((node.position.x - node.dimensions.width / 2) / GRID_SIZE) * GRID_SIZE;
  157. const adjustedY = Math.round((node.position.y - node.dimensions.height / 2) / GRID_SIZE) * GRID_SIZE;
  158. return {
  159. ...node,
  160. position: {
  161. x: adjustedX,
  162. y: adjustedY
  163. },
  164. dimensions: { height: 58, width: 60 }
  165. };
  166. });
  167. off(); // 移除监听,避免重复执行
  168. });
  169. // 3. 异步获取 pcId 和 idCodeser,并更新节点
  170. try {
  171. const { pcId, ser, idCode } = await createComponent(pid, nid);
  172. updateNode(nodeId, (node) => ({
  173. ...node,
  174. data: {
  175. ...node.data,
  176. pcId,
  177. idCodeser: `${idCode}${ser}`,
  178. }
  179. }));
  180. updateNodeInternals(nodeId);
  181. } catch (err) {
  182. console.error("添加组件失败:", err.message);
  183. ElMessage.error("添加组件失败");
  184. // 如果失败,可以考虑移除节点:
  185. // removeNodes([nodeId]);
  186. }
  187. }
  188. return {
  189. treeobj,
  190. draggedType,
  191. isDragOver,
  192. isDragging,
  193. onDragStart,
  194. onDragLeave,
  195. onDragOver,
  196. onDrop,
  197. handleNodeDrop
  198. }
  199. }