zhangxiao
2024-08-26 57b66478e7e335379435b31c20da4619bd1411f5
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<template>
    <div
        ref="myself"
        class="the-draggable-item"
        :style="itemStyle"
        draggable="true"
        @dragstart="ondragstart"
        @drag="ondrag"
        @dragend="ondragend"
        @mousedown="mousedown"
        @mouseup="mouseup"
        @dragenter="ondragenter"
        @dragove="ondragove"
    >
        <div v-show="props.active" :class="[props.active && 'active']">
            <div
                v-for="item in handleList"
                :key="item.name"
                class="handle"
                :style="item.style"
                @mousedown.stop.prevent="handleDown($event, item.name)"
            ></div>
        </div>
        <slot></slot>
    </div>
</template>
<script lang="ts" setup name="TheDraggableItem">
import { MatchedLine, Position, SetMatchedLine } from "../the-draggable-container/type";
 
//吸附阈值
const adsorbValue = 10;
 
const props = withDefaults(
    defineProps<{
        id: string;
        w: number; //宽度
        h: number; //高度
        x: number; //x坐标
        y: number; //y坐标
        minW?: number; //最小宽度
        minH?: number; //最小高度
        active?: boolean; //是否激活
    }>(),
    {
        minH: 10,
        minW: 10,
        active: false
    }
);
 
const allList = ref(inject<Position[]>("list"));
 
const setMatchedLine = inject<SetMatchedLine>("setMatchedLine");
 
const myself = ref<HTMLElement | null>(null);
 
let parentClientRect = <DOMRect | null>null;
let mouseEl = <MouseEvent | null>null;
let scrollRect = <Element | null>null;
let parentDom = <HTMLElement | null>null;
 
const emits = defineEmits<{
    (e: "update:active", data: boolean): void;
    (e: "update:x", data: number): void;
    (e: "update:y", data: number): void;
    (e: "update:w", data: number): void;
    (e: "update:h", data: number): void;
}>();
 
const itemStyle = computed<Record<string, any>>(() => {
    const width = isNaN(Number(props.w)) ? props.w : props.w + "px";
    const height = isNaN(Number(props.h)) ? props.h : props.h + "px";
    const x = isNaN(Number(props.x)) ? props.x : props.x + "px";
    const y = isNaN(Number(props.y)) ? props.y : props.y + "px";
    return {
        position: "absolute",
        // overflow: "hidden",
        width,
        height,
        transform: `translate3d(${x}, ${y}, 0px)`
    };
});
 
const handleList = computed(() => {
    return [
        {
            name: "tl",
            style: {
                top: "0",
                left: "0",
                cursor: "nwse-resize",
                transform: "translate(-50%, -50%)"
            }
        },
        {
            name: "tm",
            style: {
                top: "0",
                left: "50%",
                cursor: "ns-resize",
                transform: "translate(-50%, -50%)"
            }
        },
        {
            name: "tr",
            style: {
                top: "0",
                right: "0",
                cursor: "nesw-resize",
                transform: "translate(50%, -50%)"
            }
        },
        {
            name: "ml",
            style: {
                top: "50%",
                left: "0",
                cursor: "ew-resize",
                transform: "translate(-50%, -50%)"
            }
        },
        {
            name: "mr",
            style: {
                top: "50%",
                right: "0",
                cursor: "ew-resize",
                transform: "translate(50%, -50%)"
            }
        },
        {
            name: "bl",
            style: {
                bottom: "0",
                left: "0",
                cursor: "nesw-resize",
                transform: "translate(-50%, 50%)"
            }
        },
        {
            name: "bm",
            style: {
                bottom: "0",
                left: "50%",
                cursor: "ns-resize",
                transform: "translate(-50%, 50%)"
            }
        },
        {
            name: "br",
            style: {
                bottom: "0",
                right: "0",
                cursor: "nwse-resize",
                transform: "translate(50%, 50%)"
            }
        }
    ];
});
 
//控制柄位置
let handleAction = "";
 
const selfAnchorPoint = computed(() => {
    return {
        x: [props.x, props.x + props.w / 2, props.x + props.w],
        y: [props.y, props.y + props.h / 2, props.y + props.h]
    };
});
 
watch(
    () => props,
    () => {
        if (!allList.value) return;
        const index = allList.value.findIndex((item: any) => item._id === props.id);
        if (index !== -1) {
            allList.value[index].w = props.w;
            allList.value[index].h = props.h;
            allList.value[index].x = props.x;
            allList.value[index].y = props.y;
            allList.value[index].active = props.active;
        } else {
            allList.value.push({
                _id: props.id,
                w: props.w,
                h: props.h,
                x: props.x,
                y: props.y,
                active: props.active
            });
        }
    },
    {
        immediate: true,
        deep: true
    }
);
 
function ondragstart(event: DragEvent) {
    var img = new Image();
    img.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E";
    event?.dataTransfer?.setDragImage(img, 0, 0);
}
 
async function ondrag(event: DragEvent) {
    if (!parentClientRect || !mouseEl || !event.clientX || !event.clientY) {
        return;
    }
    const scrollTop = scrollRect?.scrollTop || 0;
    const scrollLeft = scrollRect?.scrollLeft || 0;
    let leftNew = Math.ceil(event.clientX - parentClientRect.left - mouseEl.offsetX) + scrollLeft;
    let topNew = Math.ceil(event.clientY - parentClientRect.top - mouseEl.offsetY) + scrollTop;
    //如果超出父元素边界,则禁止拖动
    if (leftNew >= 0 && leftNew + Number(props.w) <= parentClientRect.width) {
        emits("update:x", leftNew);
    }
    if (topNew >= 0 && topNew + Number(props.h) <= parentClientRect.height) {
        emits("update:y", topNew);
    }
    nextTick(() => {
        checkSnap();
    });
}
 
//检查辅助线和吸附
function checkSnap() {
    if (!setMatchedLine) {
        return;
    }
    const list = allList.value?.filter((item: any) => item._id !== props.id);
    const matchedLine: MatchedLine = {
        row: [],
        col: []
    };
    if (!list) {
        return;
    }
    const anchorPointList = list.map((item) => {
        const anchorPoint = {
            x: [item.x, item.x + item.w / 2, item.x + item.w],
            y: [item.y, item.y + item.h / 2, item.y + item.h]
        };
        return anchorPoint;
    });
    //x表示竖向线条,有3条线
    selfAnchorPoint.value.x.forEach((v1) => {
        //用于存储匹配的x坐标
        let matchX: Record<number, number[]> = {};
        //遍历其他元素所有的锚点
        anchorPointList.forEach((v2, i2) => {
            v2.x.forEach((v3) => {
                const abs = v1 - v3;
                if (Math.abs(abs) <= adsorbValue) {
                    emits("update:x", props.x - abs);
                    //如果有匹配的x坐标,则存储
                    if (!matchX[v3]) {
                        matchX[v3] = [...anchorPointList[i2].y, ...selfAnchorPoint.value.y];
                    } else {
                        matchX[v3].push(...anchorPointList[i2].y, ...selfAnchorPoint.value.y);
                    }
                }
            });
        });
        //如果有匹配的x坐标,则计算最小值和最大值,存储到matchedLine中
        Object.keys(matchX).forEach((key) => {
            const min = Math.min(...matchX[Number(key)]);
            const max = Math.max(...matchX[Number(key)]);
            matchedLine.col.push({
                top: min,
                left: Number(key),
                height: max - min
            });
        });
    });
    //y表示横向线条,有3条线
    selfAnchorPoint.value.y.forEach((v1) => {
        let matchY: Record<number, number[]> = {};
        anchorPointList.forEach((v2, i2) => {
            v2.y.forEach((v3) => {
                const abs = v1 - v3;
                if (Math.abs(abs) <= adsorbValue) {
                    emits("update:y", props.y - abs);
                    if (!matchY[v3]) {
                        matchY[v3] = [...anchorPointList[i2].x, ...selfAnchorPoint.value.x];
                    } else {
                        matchY[v3].push(...anchorPointList[i2].x, ...selfAnchorPoint.value.x);
                    }
                }
            });
        });
        Object.keys(matchY).forEach((key) => {
            const min = Math.min(...matchY[Number(key)]);
            const max = Math.max(...matchY[Number(key)]);
            matchedLine.row.push({
                top: Number(key),
                left: min,
                width: max - min
            });
        });
    });
    setMatchedLine(matchedLine);
}
 
function ondragend(event: DragEvent) {
    event.stopPropagation();
    mouseEl = null;
    if (setMatchedLine) {
        setMatchedLine(null);
    }
}
 
function ondragenter(event: DragEvent) {
    event.preventDefault();
}
 
function ondragove(event: DragEvent) {
    event.preventDefault();
}
 
function mousedown(event: MouseEvent) {
    event.stopPropagation();
    emits("update:active", true);
    if (allList.value?.length) {
        for (let item of allList.value) {
            if (item._id !== props.id) {
                item.active = false;
            }
        }
    }
    mouseEl = event;
}
 
//开始控制柄操作
function handleDown(event: MouseEvent, direction: string) {
    handleAction = direction;
    mouseEl = event;
    event.stopPropagation();
    parentDom?.addEventListener("mousemove", handleMove, true);
    parentDom?.addEventListener("mouseup", handleUp, true);
}
//结束控制柄操作
function handleUp(event: MouseEvent) {
    handleAction = "";
    event.stopPropagation();
    parentDom?.removeEventListener("mousemove", handleMove, true);
    parentDom?.removeEventListener("mouseup", handleUp, true);
    if (setMatchedLine) {
        // setMatchedLine(null);
    }
}
//控制柄移动
function handleMove(event: MouseEvent) {
    event.stopPropagation();
    if (!mouseEl) {
        console.warn("鼠标移动事件未触发");
        return;
    }
    const { clientX, clientY } = event;
    const { clientX: mouseClientX, clientY: mouseClientY } = mouseEl;
    const x = clientX - mouseClientX;
    const y = clientY - mouseClientY;
    if (handleAction === "tl") {
        //左上角
        emits("update:x", props.x + x);
        emits("update:y", props.y + y);
        emits("update:w", props.w - x);
        emits("update:h", props.h - y);
    } else if (handleAction === "tm") {
        //上中
        emits("update:y", props.y + y);
        emits("update:h", props.h - y);
    } else if (handleAction === "tr") {
        //右上角
        emits("update:y", props.y + y);
        emits("update:w", props.w + x);
        emits("update:h", props.h - y);
    } else if (handleAction === "mr") {
        //右中
        emits("update:w", props.w + x);
    } else if (handleAction === "br") {
        //右下角
        emits("update:w", props.w + x);
        emits("update:h", props.h + y);
    } else if (handleAction === "bm") {
        //下中
        emits("update:h", props.h + y);
    } else if (handleAction === "bl") {
        //左下角
        emits("update:x", props.x + x);
        emits("update:w", props.w - x);
        emits("update:h", props.h + y);
    } else if (handleAction === "ml") {
        //左中
        emits("update:x", props.x + x);
        emits("update:w", props.w - x);
    }
    mouseEl = event;
    nextTick(() => {
        // checkSnap();
    });
}
 
function mouseup(event: MouseEvent) {
    console.log("触发mouseup");
    event.stopPropagation();
    // emits("update:active", false);
    mouseEl = null;
}
 
onMounted(() => {
    nextTick(() => {
        parentDom = document.getElementById("the-draggable-container");
        parentClientRect = parentDom?.getBoundingClientRect() || null;
        scrollRect = document.getElementsByClassName("layout-content")[0];
        if (parentDom) {
            parentDom.ondragover = function (e) {
                // 禁止默认行为,才能看到拖动元素的光标样式与effectAllowed的值对应
                e.preventDefault();
            };
        }
    });
});
 
onBeforeUnmount(() => {
    // window.removeEventListener("scroll", handleScroll, true);
});
</script>
<style lang="scss" scoped>
.the-draggable-item {
    position: relative;
    user-select: none;
    cursor: default;
    .active {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border: 1px dashed #f2f3f5;
        .handle {
            position: absolute;
            background-color: #fff;
            border: 1px solid #333;
            box-shadow: 0 0 2px #bbb;
            z-index: 1;
            width: 8px;
            height: 8px;
            display: "block";
        }
    }
}
</style>