useDnD.js 5.7 KB

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