-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathBaseNode.tsx
More file actions
576 lines (533 loc) · 17.4 KB
/
BaseNode.tsx
File metadata and controls
576 lines (533 loc) · 17.4 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import { createElement as h, Component } from 'preact/compat'
import { reaction, IReactionDisposer } from 'mobx'
import { map, isFunction, isNil } from 'lodash-es'
import Anchor from '../Anchor'
import { BaseText } from '../text'
import LogicFlow from '../../LogicFlow'
import { GraphModel, BaseNodeModel, Model } from '../../model'
import { ElementState, EventType, TextMode } from '../../constant'
import {
StepDrag,
snapToGrid,
isIe,
isMultipleSelect,
cancelRaf,
createRaf,
IDragParams,
// RotateMatrix,
} from '../../util'
import RotateControlPoint from '../Rotate'
import ResizeControlGroup from '../Control'
type IProps = {
model: BaseNodeModel
graphModel: GraphModel
}
type IState = {
isDragging?: boolean
}
export abstract class BaseNode<P extends IProps = IProps> extends Component<
P,
IState
> {
static isObserved: boolean = false
static extendsKey?: string
t: any
moveOffset?: LogicFlow.OffsetData
stepDrag: StepDrag
mouseUpDrag?: boolean
startTime?: number
modelDisposer: IReactionDisposer
longPressTimer?: number
mouseDownPosition?: LogicFlow.Position
constructor(props: IProps) {
super()
const {
graphModel: { gridSize, eventCenter },
model,
} = props
// 不在构造函数中判断,因为editConfig可能会被动态改变
this.stepDrag = new StepDrag({
onDragStart: this.onDragStart,
onDragging: this.onDragging,
onDragEnd: this.onDragEnd,
step: gridSize,
eventType: 'NODE',
isStopPropagation: false,
eventCenter,
model,
})
// https://github.com/didi/LogicFlow/issues/1370
// 当使用撤销功能:LogicFlow.undo()时,会重新初始化所有model数据,即LogicFlow.undo()时会新构建一个model对象
// 但是this.stepDrag并不会重新创建
// 导致this.stepDrag持有的model并没有重新赋值,因为之前的做法是构造函数中传入一个model对象
// 使用mobx的reaction监听能力,如果this.props.model发生变化,则进行this.stepDrag.setModel()操作
this.modelDisposer = reaction(
() => this.props,
(newProps) => {
if (newProps && newProps.model) {
this.stepDrag.setModel(newProps.model)
}
},
)
}
componentWillUnmount() {
if (this.modelDisposer) {
this.modelDisposer()
}
// 以下是 mobx-preact 中 componentWillUnmount 的回调逻辑,但是不知道出于什么考虑,mobx-preact 没有混入这一段逻辑
// @ts-ignore
if (this.render.$mobx) {
// @ts-ignore
this.render.$mobx.dispose()
}
}
componentDidMount() {}
componentDidUpdate() {}
abstract getShape(): h.JSX.Element | null
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getAnchorShape(_anchorData?: Model.AnchorConfig): h.JSX.Element | null {
return null
}
getAnchors() {
const { model, graphModel } = this.props
const { isSelected, isHitable, isDragging, isShowAnchor } = model
if (isHitable && (isSelected || isShowAnchor) && !isDragging) {
return map(model.anchors, (anchor, index) => {
const edgeStyle = model.getAnchorLineStyle(anchor)
const style = model.getAnchorStyle(anchor)
return (
<Anchor
anchorData={anchor}
node={this}
style={style}
edgeStyle={edgeStyle}
anchorIndex={index}
nodeModel={model}
graphModel={graphModel}
setHoverOff={this.setHoverOff}
/>
)
})
}
return []
}
getRotateControl() {
const { model, graphModel } = this.props
const {
editConfigModel: { isSilentMode, allowRotate },
} = graphModel
const { isSelected, isHitable, rotatable, isHovered } = model
// 合并全局 allResize 和节点自身的 resizable 配置,以节点配置高于全局配置
const canRotate = allowRotate && rotatable // 全局开关 > 节点配置
const style = model.getRotateControlStyle()
if (!isSilentMode && isHitable && (isSelected || isHovered) && canRotate) {
return (
<RotateControlPoint
graphModel={graphModel}
nodeModel={model}
eventCenter={graphModel.eventCenter}
style={style}
/>
)
}
}
getResizeControl(): h.JSX.Element | null {
const { model, graphModel } = this.props
const {
editConfigModel: { isSilentMode, allowResize },
} = graphModel
const { isSelected, isHitable, resizable, isHovered } = model
// 合并全局 allResize 和节点自身的 resizable 配置,以节点配置高于全局配置
const canResize = allowResize && resizable // 全局开关 > 节点配置
const style = model.getResizeControlStyle()
if (!isSilentMode && isHitable && (isSelected || isHovered) && canResize) {
return (
<ResizeControlGroup
style={style}
model={model}
graphModel={graphModel}
/>
)
}
return null
}
getText(): h.JSX.Element | null {
const { model, graphModel } = this.props
const { editConfigModel } = graphModel
// 当 节点文本模式非 TEXT 时,不显示文本
if (editConfigModel.nodeTextMode !== TextMode.TEXT) return null
// 文本被编辑的时候,显示编辑框,不显示文本。
if (model.state === ElementState.TEXT_EDIT) return null
if (model.text) {
let draggable = false
if (editConfigModel.nodeTextDraggable && model.text.draggable) {
draggable = true
}
return (
<BaseText
editable={
editConfigModel.nodeTextEdit && (model.text.editable ?? true)
}
model={model}
graphModel={graphModel}
draggable={draggable}
/>
)
}
return null
}
getStateClassName() {
const {
model: { state, isDragging, isSelected },
} = this.props
let className = 'lf-node'
switch (state) {
case ElementState.ALLOW_CONNECT:
className += ' lf-node-allow'
break
case ElementState.NOT_ALLOW_CONNECT:
className += ' lf-node-not-allow'
break
default:
className += ' lf-node-default'
break
}
if (isDragging) {
className += ' lf-dragging'
}
if (isSelected) {
className += ' lf-node-selected'
}
return className
}
onDragStart = ({ event }: Partial<IDragParams>) => {
const { model, graphModel } = this.props
if (event) {
const {
canvasOverlayPosition: { x, y },
} = graphModel.getPointByClient({
x: event.clientX,
y: event.clientY,
})
this.moveOffset = {
dx: model.x - x,
dy: model.y - y,
}
}
}
onDragging = ({ event }: IDragParams) => {
const { model, graphModel } = this.props
const {
editConfigModel: { stopMoveGraph, autoExpand, snapGrid },
transformModel,
selectNodes,
width,
height,
gridSize,
} = graphModel
const { clientX, clientY } = event!
const { x: mouseDownX, y: mouseDownY } = this.mouseDownPosition!
if (clientX - mouseDownX > gridSize || clientY - mouseDownY > gridSize) {
model.isDragging = true
}
let {
canvasOverlayPosition: { x, y },
} = graphModel.getPointByClient({
x: clientX,
y: clientY,
})
const [x1, y1] = transformModel.CanvasPointToHtmlPoint([x, y])
// 1. 考虑画布被缩放
// 2. 考虑鼠标位置不再节点中心
x = x + (this.moveOffset?.dx ?? 0)
y = y + (this.moveOffset?.dy ?? 0)
// 校准坐标
x = snapToGrid(x, gridSize, snapGrid)
y = snapToGrid(y, gridSize, snapGrid)
if (!width || !height) {
graphModel.moveNode2Coordinate(model.id, x, y)
return
}
const isOutCanvas = x1 < 0 || y1 < 0 || x1 > width || y1 > height
if (autoExpand && !stopMoveGraph && isOutCanvas) {
// 鼠标超出画布后的拖动,不处理,而是让上一次setInterval持续滚动画布
return
}
// 取节点左上角和右下角,计算节点移动是否超出范围
const [leftTopX, leftTopY] = transformModel.CanvasPointToHtmlPoint([
x - model.width / 2,
y - model.height / 2,
])
const [rightBottomX, rightBottomY] = transformModel.CanvasPointToHtmlPoint([
x + model.width / 2,
y + model.height / 2,
])
const size: number = Math.max(gridSize, 20)
let nearBoundary: LogicFlow.PointTuple | [] = []
if (leftTopX < 0) {
nearBoundary = [size, 0]
} else if (rightBottomX > graphModel.width) {
nearBoundary = [-size, 0]
} else if (leftTopY < 0) {
nearBoundary = [0, size]
} else if (rightBottomY > graphModel.height) {
nearBoundary = [0, -size]
}
if (this.t) {
cancelRaf(this.t)
}
let moveNodes = selectNodes.map((node) => node.id)
// 未被选中的节点也可以拖动
if (moveNodes.indexOf(model.id) === -1) {
moveNodes = [model.id]
}
if (nearBoundary.length > 0 && !stopMoveGraph && autoExpand) {
this.t = createRaf(() => {
const [translateX, translateY] = nearBoundary
transformModel.translate(translateX ?? 0, translateY ?? 0)
const deltaX = -(translateX ?? 0) / transformModel.SCALE_X
const deltaY = -(translateY ?? 0) / transformModel.SCALE_X
graphModel.moveNodes(moveNodes, deltaX, deltaY)
})
} else {
graphModel.moveNodes(moveNodes, x - model.x, y - model.y)
}
}
onDragEnd = () => {
if (this.t) {
cancelRaf(this.t)
}
const { model } = this.props
model.isDragging = false
}
onMouseOut = (ev: MouseEvent) => {
if (isIe()) {
this.setHoverOff(ev)
}
}
handleMouseUp = () => {
const { model } = this.props
this.mouseUpDrag = model.isDragging
if (this.longPressTimer) {
clearTimeout(this.longPressTimer)
this.longPressTimer = undefined
}
}
handleClick = (e: MouseEvent) => {
// 节点拖拽进画布之后,不触发click事件相关emit
// 点拖拽进画布没有触发mousedown事件,没有startTime,用这个值做区分
const isDragging = this.mouseUpDrag === false
const curTime = new Date().getTime()
if (!this.startTime) return
const timeInterval = curTime - this.startTime
const { model, graphModel } = this.props
// 这里会有一种极端情况:当网格大小是1或者关闭网格吸附时,用触摸板点击节点会触发拖拽事件导致节点无法选中
// 当触摸板点击节点时,为了防止误触发拖拽导致节点无法选中,允许在非拖拽状态且时间间隔小于100ms时触发点击事件
if (!isDragging && timeInterval > 300) return
if (!isDragging) {
this.onDragEnd()
this.handleMouseUp()
}
// 节点数据,多为事件对象数据抛出
const nodeData = model.getData()
const position = graphModel.getPointByClient({
x: e.clientX,
y: e.clientY,
})
// TODO: 这里加入了 isSelected 与 isMultiple,主要是为 group 插件做的加强,有种被插件夺舍的感觉
const eventOptions = {
data: nodeData,
e,
position,
isSelected: false,
isMultiple: false,
}
const isRightClick = e.button === 2
// 这里 IE 11不能正确显示
const isDoubleClick = e.detail === 2
// 判断是否有右击,如果有右击则取消点击事件触发
if (isRightClick) return
const { editConfigModel } = graphModel
// 在multipleSelect tool禁用的情况下,允许取消选中节点
const isMultiple = isMultipleSelect(e, editConfigModel)
eventOptions.isMultiple = isMultiple
if (model.isSelected && !isDoubleClick && isMultiple) {
eventOptions.isSelected = false
model.setSelected(false)
} else {
graphModel.selectNodeById(model.id, isMultiple)
eventOptions.isSelected = true
// 静默模式下点击节点不变更节点层级
if (!editConfigModel.isSilentMode) {
this.toFront()
}
}
// 不是双击的,默认都是单击
if (isDoubleClick) {
if (editConfigModel.nodeTextEdit) {
if (model.text.editable && editConfigModel.textMode === TextMode.TEXT) {
model.setSelected(false)
graphModel.setElementStateById(model.id, ElementState.TEXT_EDIT)
}
}
graphModel.eventCenter.emit(EventType.NODE_DBCLICK, eventOptions)
} else {
graphModel.eventCenter.emit(EventType.ELEMENT_CLICK, eventOptions)
graphModel.eventCenter.emit(EventType.NODE_CLICK, eventOptions)
// 复制粘贴后会出现点击节点时,节点会失去焦点的问题,这里手动让节点获焦以解决这个问题
const el = e.currentTarget as HTMLElement
const rAF =
!isNil(window) && isFunction(window.requestAnimationFrame)
? window.requestAnimationFrame.bind(window)
: (fn: () => void) => setTimeout(fn, 0)
rAF(() => {
el.focus()
})
}
}
handleContextMenu = (ev: MouseEvent) => {
ev.preventDefault()
const { model, graphModel } = this.props
const { editConfigModel } = graphModel
// 节点数据,多为事件对象数据抛出
const nodeData = model.getData()
const position = graphModel.getPointByClient({
x: ev.clientX,
y: ev.clientY,
})
graphModel.setElementStateById(
model.id,
ElementState.SHOW_MENU,
position.domOverlayPosition,
)
if (!model.isSelected) {
graphModel.selectNodeById(model.id)
}
graphModel.eventCenter.emit(EventType.NODE_CONTEXTMENU, {
data: nodeData,
e: ev,
position,
})
// 静默模式下点击节点不变更节点层级
if (!editConfigModel.isSilentMode) {
this.toFront()
}
}
handleMouseDown = (ev: PointerEvent) => {
const { model, graphModel } = this.props
this.mouseDownPosition = { x: ev.clientX, y: ev.clientY }
this.startTime = new Date().getTime()
const { editConfigModel, gridSize, transformModel } = graphModel
if (editConfigModel.adjustNodePosition && model.draggable) {
this.stepDrag.setStep(gridSize * transformModel.SCALE_X)
this.stepDrag.handleMouseDown(ev)
}
if (this.longPressTimer) {
clearTimeout(this.longPressTimer)
}
if (ev.pointerType === 'touch') {
this.longPressTimer = window.setTimeout(() => {
if (!this.props.model.isDragging) {
this.handleContextMenu(ev)
}
}, 500)
}
}
handleFocus = () => {
const { model, graphModel } = this.props
graphModel.eventCenter.emit(EventType.NODE_FOCUS, {
data: model.getData(),
})
}
handleBlur = () => {
// 当节点通过自定义锚点实现节点删除时,这里props会变成undefined,需兼容一下
if (!this.props) return
const { model, graphModel } = this.props
graphModel.eventCenter.emit(EventType.NODE_BLUR, {
data: model.getData(),
})
}
// 因为自定义节点的时候,可能会基于hover状态自定义不同的样式。
setHoverOn = (ev: MouseEvent) => {
const { model, graphModel } = this.props
if (model.isHovered) return
const nodeData = model.getData()
model.setHovered(true)
graphModel.eventCenter.emit(EventType.NODE_MOUSEENTER, {
data: nodeData,
e: ev,
})
}
setHoverOff = (ev: MouseEvent) => {
const { model, graphModel } = this.props
const nodeData = model.getData()
// 文本focus时,关联的元素也需要高亮,所以元素失焦时还要判断下是否有文本处于focus状态
if (!model.isHovered) return
model.setHovered(false)
graphModel.eventCenter.emit(EventType.NODE_MOUSELEAVE, {
data: nodeData,
e: ev,
})
}
/**
* @overridable 支持重写, 节点置顶,可以被某些不需要置顶的节点重写,如group节点。
*/
toFront() {
const { model, graphModel } = this.props
if (model.autoToFront) {
graphModel.toFront(model.id)
}
}
render() {
const { model, graphModel } = this.props
const {
editConfigModel: { hideAnchors, allowRotate, allowResize },
} = graphModel
const { isHitable, transform } = model
const { className = '', ...restAttributes } = model.getOuterGAttributes()
const nodeShapeInner = (
<g className="lf-node-content">
<g transform={transform}>
{this.getShape()}
{this.getText()}
{allowResize && this.getResizeControl()}
{allowRotate && this.getRotateControl()}
</g>
{!hideAnchors && this.getAnchors()}
</g>
)
let nodeShape: h.JSX.Element
if (!isHitable) {
nodeShape = (
<g
className={`${this.getStateClassName()} ${className}`}
{...restAttributes}
>
{nodeShapeInner}
</g>
)
} else {
nodeShape = (
<g
className={`${this.getStateClassName()} ${className}`}
onPointerDown={this.handleMouseDown}
onPointerUp={this.handleMouseUp}
onClick={this.handleClick}
//因为移动端点击操作完成会按顺序触发enter、leave、click事件,所以会造成节点的闪烁,所以在这里没有统一状态为Pointer
onMouseEnter={this.setHoverOn}
onMouseOver={this.setHoverOn}
onMouseLeave={this.setHoverOff}
onMouseOut={this.onMouseOut}
onContextMenu={this.handleContextMenu}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
{...restAttributes}
>
{nodeShapeInner}
</g>
)
}
return nodeShape
}
}
export default BaseNode