这几天写链路图,边写边想写这东西这么消耗体力,就想写个小工具出来能加快效率,但奈何比较懒,想着链路图应该很快能调好,可发现调了一个多小时,线还没开始,麻了!
思考了下,工具写起来应该比较简单,然后花了点时间写了这个PointsBuild,废话不多说,上代码::
import React, { useState, useRef } from 'react';
import Clipboard from 'clipboard';
/**
* 链路图点位工具
* @param {number} cartesianMaxY y轴最大值,默认为0,表示DOM定位方式
* @param {number} width 占位宽度
* @param {number} height 占位高度
* @param {url} background 占位背景
* @param {json} style 占位style
* @param {bool} notice 是否提示复制信息
* @param {string} formatter 数据输出格式,使用${x}${y}占位
* @param {bool} multi 多点连续输出,默认单点输出
*/
const listenerCatch = (obj, e, hander) => {
if (obj.addEventListener) {
obj.addEventListener(e, hander, false);
} else if (obj.attachEvent) {
e = 'on' + e;
obj.attachEvent(e, hander);
}
};
const cancelEvent = (e) => {
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation();
} else {
e.returnValue = false;
e.cancelBubble = true;
}
};
const PointsBuild = ({
cartesianMaxY = 0,
width = 100,
height = 100,
background = null,
style = {},
notice = true,
formatter = '',
multi = false,
}) => {
const [top, setTop] = useState(0);
const [left, setLeft] = useState(0);
const [mesWidth, setWidth] = useState(0);
const [pointer, points, ref] = [useRef({ x: 0, y: 0 }), useRef(''), useRef(null)];
const drag = (e) => {
!pointer.current.x && !pointer.current.y && listenerCatch(document, 'mousemove', mousemove);
pointer.current = { x: e.pageX, y: e.pageY };
};
const mousemove = (e) => {
cancelEvent(e);
let [x, y] = [e.pageX, e.pageY];
if (ref.current.offsetLeft <= 5 && ref.current.offsetTop <= 5) points.current = '';
setLeft((l) => l + x - pointer.current.x);
setTop((t) => t + y - pointer.current.y);
pointer.current = { x: x, y: y };
};
const copy = (e) => {
let text;
if (formatter) {
let [x, y] = cartesianMaxY ? [left + width / 2, cartesianMaxY - top - height / 2] : [le