/
dialog.tsx
516 lines (487 loc) · 18.9 KB
/
dialog.tsx
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
import Vue from 'vue';
import isNumber from 'lodash/isNumber';
import throttle from 'lodash/throttle';
import {
CloseIcon as TdCloseIcon,
InfoCircleFilledIcon as TdInfoCircleFilledIcon,
CheckCircleFilledIcon as TdCheckCircleFilledIcon,
ErrorCircleFilledIcon as TdErrorCircleFilledIcon,
} from 'tdesign-icons-vue';
import TButton from '../button';
import ActionMixin from './actions';
import { DialogCloseContext, TdDialogProps } from './type';
import props from './props';
import { renderTNodeJSX, renderContent } from '../utils/render-tnode';
import mixins from '../utils/mixins';
import getConfigReceiverMixins, { DialogConfig, getGlobalIconMixins } from '../config-provider/config-receiver';
import TransferDom from '../utils/transfer-dom';
import { emitEvent } from '../utils/event';
import { ClassName, Styles } from '../common';
import { updateElement } from '../hooks/useDestroyOnClose';
import stack from './stack';
import { getScrollbarWidth } from '../_common/js/utils/getScrollbarWidth';
function getCSSValue(v: string | number) {
return isNaN(Number(v)) ? v : `${Number(v)}px`;
}
let mousePosition: { x: number; y: number } | null;
const getClickPosition = (e: MouseEvent) => {
mousePosition = {
x: e.clientX,
y: e.clientY,
};
setTimeout(() => {
mousePosition = null;
}, 100);
};
if (typeof window !== 'undefined' && window.document && window.document.documentElement) {
document.documentElement.addEventListener('click', getClickPosition, true);
}
let key = 1;
export default mixins(ActionMixin, getConfigReceiverMixins<Vue, DialogConfig>('dialog'), getGlobalIconMixins()).extend({
name: 'TDialog',
components: {
TButton,
},
data() {
return {
uid: 0,
scrollWidth: 0,
disX: 0,
disY: 0,
windowInnerWidth: 0,
windowInnerHeight: 0,
dialogW: 0,
dialogH: 0,
dLeft: 0,
dTop: 0,
styleEl: null,
timer: null,
animationEnd: false,
};
},
props: { ...props, instanceGlobal: Object },
computed: {
// 是否模态形式的对话框
isModal(): boolean {
return this.mode === 'modal';
},
// 是否非模态对话框
isModeLess(): boolean {
return this.mode === 'modeless';
},
// 是否普通对话框,没有脱离文档流的对话框
isNormal(): boolean {
return this.mode === 'normal';
},
isFullScreen(): boolean {
return this.mode === 'full-screen';
},
maskClass(): ClassName {
return [`${this.componentName}__mask`, !this.showOverlay && `${this.classPrefix}-is-hidden`];
},
dialogClass(): ClassName {
const dialogClass = [
`${this.componentName}`,
`${this.componentName}__modal-${this.theme}`,
this.isModeLess && this.draggable && `${this.componentName}--draggable`,
];
if (this.isFullScreen) {
dialogClass.push(`${this.componentName}__fullscreen`);
} else {
dialogClass.push(`${this.componentName}--default`);
}
return dialogClass;
},
positionClass(): ClassName {
if (this.isNormal) return [];
if (this.isFullScreen) return [`${this.componentName}__position_fullscreen`];
const dialogClass = [
`${this.componentName}__position`,
!!this.top && `${this.componentName}--top`,
`${this.placement && !this.top ? `${this.componentName}--${this.placement}` : ''}`,
];
return dialogClass;
},
wrapClass(): ClassName {
return [!this.isNormal && `${this.componentName}__wrap`];
},
ctxClass(): ClassName {
// dialog__ctx--fixed 绝对定位
// dialog__ctx--absolute 挂载在attach元素上 相对定位
// __ctx--modeless modeless 点击穿透
return [
`${this.componentName}__ctx`,
{
[`${this.classPrefix}-dialog__ctx--fixed`]: this.mode === 'modal' || this.isFullScreen,
[`${this.classPrefix}-dialog__ctx--absolute`]: this.isModal && this.showInAttachedElement,
[`${this.componentName}__ctx--modeless`]: this.isModeLess,
},
];
},
positionStyle(): Styles {
if (this.isFullScreen) return {}; // 全屏模式,top属性不生效
const topStyle = {} as Styles;
if (this.top !== undefined) {
// 判断是否时数字
if (isNumber(this.top) && this.top < 0) {
topStyle.paddingTop = `${this.top}px`;
} else {
topStyle.paddingTop = this.top;
}
}
return topStyle;
},
dialogStyle(): Styles {
return !this.isFullScreen ? { width: getCSSValue(this.width) } : {}; // width全屏模式不生效;
},
},
watch: {
visible: {
handler(value) {
if (value) {
this.animationEnd = false;
if ((this.isModal && !this.showInAttachedElement) || this.isFullScreen) {
if (this.preventScrollThrough) {
this.$nextTick(() => {
document.head.appendChild(this.styleEl);
});
}
this.$nextTick(() => {
const target = this.$refs.dialog as HTMLElement;
if (mousePosition && target) {
target.style.transformOrigin = `${mousePosition.x - target.offsetLeft}px ${
mousePosition.y - target.offsetTop
}px`;
}
});
}
// 清除鼠标焦点 避免entry事件多次触发(按钮弹出弹窗 不移除焦点 立即按Entry按键 会造成弹窗关闭再弹出)
(document.activeElement as HTMLElement).blur();
} else {
this.clearStyleFunc();
}
// 多个dialog同时存在时使用esc关闭异常 (#1209)
this.$nextTick(() => {
this.storeUid(value);
});
this.addKeyboardEvent(value);
if (this.isModeLess && this.draggable) {
this.$nextTick(() => {
this.initDragEvent(value);
});
}
// 父元素为 display: none 时,需要更新子元素,避免 Dialog 前套 Table 组件时,固定列等特性失效
if (value && !this.destroyOnClose && requestAnimationFrame) {
requestAnimationFrame(() => {
updateElement(this);
});
}
},
immediate: true,
},
},
mounted() {
const hasScrollBar = document.documentElement.scrollHeight > document.documentElement.clientHeight;
const scrollWidth = hasScrollBar ? getScrollbarWidth() : 0;
if (this.draggable) {
window.addEventListener('resize', throttle(this.resizeAdjustPosition, 1000));
}
// @ts-ignore 用于获取组件uid
this.uid = this._uid;
this.styleEl = document.createElement('style');
this.styleEl.dataset.id = `td_dialog_${+new Date()}_${(key += 1)}`;
this.styleEl.innerHTML = `
html body {
overflow-y: hidden;
width: calc(100% - ${scrollWidth}px);
}
`;
if (this.visible && this.isModal && this.preventScrollThrough && !this.showInAttachedElement) {
document.head.appendChild(this.styleEl);
}
},
beforeDestroy() {
this.addKeyboardEvent(false);
this.destroySelf();
this.destroySelfStyle();
},
directives: {
TransferDom,
},
methods: {
clearStyleFunc() {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.destroySelfStyle();
}, 150);
},
destroySelfStyle() {
this.styleEl.parentNode?.removeChild?.(this.styleEl);
},
destroySelf() {
this.$el.parentNode?.removeChild?.(this.$el);
},
// 多个dialog情况,若有些给了默认值true,出现ESC关闭不了弹窗问题解决
storeUid(flag: boolean) {
if (flag) {
stack.push(this.uid);
} else {
stack.pop(this.uid);
}
},
addKeyboardEvent(status: boolean) {
if (status) {
document.addEventListener('keydown', this.keyboardEvent);
this.confirmOnEnter && document.addEventListener('keydown', this.keyboardEnterEvent);
} else {
document.removeEventListener('keydown', this.keyboardEvent);
this.confirmOnEnter && document.removeEventListener('keydown', this.keyboardEnterEvent);
}
},
keyboardEvent(e: KeyboardEvent) {
if (e.code === 'Escape' && stack.top === this.uid) {
emitEvent<Parameters<TdDialogProps['onEscKeydown']>>(this, 'esc-keydown', { e });
// 根据 closeOnEscKeydown 判断按下ESC时是否触发close事件
if (this.closeOnEscKeydown ?? this.global.closeOnEscKeydown) {
this.emitCloseEvent({ e, trigger: 'esc' });
}
}
},
// 回车触发确认事件
keyboardEnterEvent(e: KeyboardEvent) {
const { code } = e;
if ((code === 'Enter' || code === 'NumpadEnter') && stack.top === this.uid) {
emitEvent<Parameters<TdDialogProps['onConfirm']>>(this, 'confirm', { e });
}
},
overlayAction(e: MouseEvent) {
if (e.target !== this.$refs.dialogPosition) {
return;
}
emitEvent<Parameters<TdDialogProps['onOverlayClick']>>(this, 'overlay-click', { e });
// 根据closeOnClickOverlay判断点击蒙层时是否触发close事件
if (this.showOverlay && (this.closeOnOverlayClick ?? this.global.closeOnOverlayClick)) {
this.emitCloseEvent({ e, trigger: 'overlay' });
}
},
closeBtnAction(e: MouseEvent) {
emitEvent<Parameters<TdDialogProps['onCloseBtnClick']>>(this, 'close-btn-click', { e });
this.emitCloseEvent({
trigger: 'close-btn',
e,
});
},
// used in mixins of ActionMixin
cancelBtnAction(e: MouseEvent) {
emitEvent<Parameters<TdDialogProps['onCancel']>>(this, 'cancel', { e });
this.emitCloseEvent({
trigger: 'cancel',
e,
});
},
// used in mixins of ActionMixin
confirmBtnAction(e: MouseEvent) {
emitEvent<Parameters<TdDialogProps['onConfirm']>>(this, 'confirm', { e });
},
// 打开弹窗动画结束时事件
afterEnter() {
emitEvent<Parameters<TdDialogProps['onOpened']>>(this, 'opened');
},
// 关闭弹窗动画结束时事件
afterLeave() {
if (this.isModeLess && this.draggable) {
const target = this.$refs.dialog as HTMLElement;
if (!target) return;
// 关闭弹窗 清空拖拽设置的相关css
target.style.position = 'relative';
target.style.left = 'unset';
target.style.top = 'unset';
}
emitEvent<Parameters<TdDialogProps['onClosed']>>(this, 'closed');
this.animationEnd = true;
},
emitCloseEvent(context: DialogCloseContext) {
emitEvent<Parameters<TdDialogProps['onClose']>>(this, 'close', context);
// 默认关闭弹窗
this.$emit('update:visible', false);
},
// Vue在引入阶段对事件的处理还做了哪些初始化操作。Vue在实例上用一个_events属性存贮管理事件的派发和更新,
// 暴露出$on, $once, $off, $emit方法给外部管理事件和派发执行事件
// 所以通过判断_events某个事件下监听函数数组是否超过一个,可以判断出组件是否监听了当前事件
hasEventOn(name: string) {
// _events 因没有被暴露在vue实例接口中,只能把这个规则注释掉
/* eslint-disable dot-notation */
const eventFuncs = this['_events']?.[name];
return !!eventFuncs?.length;
},
getIcon() {
const { InfoCircleFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon } = this.useGlobalIcon({
InfoCircleFilledIcon: TdInfoCircleFilledIcon,
CheckCircleFilledIcon: TdCheckCircleFilledIcon,
ErrorCircleFilledIcon: TdErrorCircleFilledIcon,
});
const icon = {
info: <InfoCircleFilledIcon class={`${this.classPrefix}-is-info`} />,
warning: <ErrorCircleFilledIcon class={`${this.classPrefix}-is-warning`} />,
danger: <ErrorCircleFilledIcon class={`${this.classPrefix}-is-error`} />,
success: <CheckCircleFilledIcon class={`${this.classPrefix}-is-success`} />,
};
return icon[this.theme];
},
mousedownHandler(targetEvent: MouseEvent) {
const target = this.$refs.dialog as HTMLElement;
// 算出鼠标相对元素的位置
this.disX = targetEvent.clientX - target.offsetLeft;
this.disY = targetEvent.clientY - target.offsetTop;
this.dialogW = target.offsetWidth;
this.dialogH = target.offsetHeight;
this.windowInnerWidth = window.innerWidth || document.documentElement.clientWidth;
this.windowInnerHeight = window.innerHeight || document.documentElement.clientHeight;
// 如果弹出框超出屏幕范围 不能进行拖拽
if (this.dialogW > this.windowInnerWidth || this.dialogH > this.windowInnerHeight) return;
// 元素按下时注册document鼠标监听事件
document.addEventListener('mousemove', this.mouseMoverHandler);
// 鼠标弹起来移除document鼠标监听事件
document.addEventListener('mouseup', this.mouseUpHandler);
// 拖拽结束移除鼠标监听事件,解决文字拖拽结束事件未解绑问题(window系统双击文本然后拖拽触发)
document.addEventListener('dragend', this.mouseUpHandler);
},
mouseMoverHandler(documentEvent: MouseEvent) {
const target = this.$refs.dialog as HTMLElement;
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = documentEvent.clientX - this.disX;
let top = documentEvent.clientY - this.disY;
// 移动当前元素
// 临界判断
// 拖拽上左边界限制
if (left < 0) left = 0;
if (top < 0) top = 0;
if (this.windowInnerWidth - target.offsetWidth - left < 0) left = this.windowInnerWidth - target.offsetWidth;
if (this.windowInnerHeight - target.offsetHeight - top < 0) top = this.windowInnerHeight - target.offsetHeight;
target.style.position = 'absolute';
target.style.left = `${left}px`;
target.style.top = `${top}px`;
},
mouseUpHandler() {
document.removeEventListener('mousemove', this.mouseMoverHandler);
document.removeEventListener('mouseup', this.mouseUpHandler);
document.removeEventListener('dragend', this.mouseUpHandler);
},
initDragEvent(status: boolean) {
const target = this.$refs.dialog as HTMLElement;
if (status) {
target.addEventListener('mousedown', this.mousedownHandler);
} else {
target.removeEventListener('mousedown', this.mousedownHandler);
}
},
/**
* 打开弹窗,浏览器动态调整大小的时候缩放
*/
resizeAdjustPosition() {
if (this.visible) {
const target = this.$refs.dialog as HTMLElement;
target.style.left = `${this.dLeft * (window.innerWidth / this.windowInnerWidth)}px`;
target.style.top = `${this.dTop * (window.innerHeight / this.windowInnerHeight)}px`;
}
},
onStopDown(e: MouseEvent) {
if (this.isModeLess && this.draggable) e.stopPropagation();
},
renderDialog() {
const { CloseIcon } = this.useGlobalIcon({
CloseIcon: TdCloseIcon,
});
// header 值为 true 显示空白头部
const defaultHeader = <h5 class="title"></h5>;
const defaultCloseBtn = <CloseIcon />;
const body = renderContent(this, 'default', 'body');
// this.getConfirmBtn is a function of ActionMixin
// this.getCancelBtn is a function of ActionMixin
const defaultFooter = (
<div>
{this.getCancelBtn({
cancelBtn: this.cancelBtn,
globalCancel: this.instanceGlobal?.cancel || this.global.cancel,
className: `${this.componentName}__cancel`,
})}
{this.getConfirmBtn({
theme: this.theme,
confirmBtn: this.confirmBtn,
confirmLoading: this.confirmLoading,
globalConfirm: this.instanceGlobal?.confirm || this.global.confirm,
globalConfirmBtnTheme: this.instanceGlobal?.confirmBtnTheme || this.global.confirmBtnTheme,
className: `${this.componentName}__confirm`,
})}
</div>
);
const headerClassName = this.isFullScreen
? [`${this.componentName}__header`, `${this.componentName}__header--fullscreen`]
: `${this.componentName}__header`;
const closeClassName = this.isFullScreen
? [`${this.componentName}__close`, `${this.componentName}__close--fullscreen`]
: `${this.componentName}__close`;
const bodyClassName = this.theme === 'default'
? [`${this.componentName}__body`]
: [`${this.componentName}__body`, `${this.componentName}__body__icon`];
const footerContent = renderTNodeJSX(this, 'footer', defaultFooter);
if (this.isFullScreen && footerContent) {
bodyClassName.push(`${this.componentName}__body--fullscreen`);
} else if (this.isFullScreen) {
bodyClassName.push(`${this.componentName}__body--fullscreen--without-footer`);
}
const footerClassName = this.isFullScreen
? [`${this.componentName}__footer`, `${this.componentName}__footer--fullscreen`]
: `${this.componentName}__footer`;
const footer = this.footer ? (
<div class={footerClassName} onmousedown={this.onStopDown}>
{footerContent}
</div>
) : null;
// 此处获取定位方式 top 优先级较高 存在时 默认使用top定位
return (
// 非模态形态下draggable为true才允许拖拽
<div class={this.wrapClass}>
<div class={this.positionClass} style={this.positionStyle} onClick={this.overlayAction} ref="dialogPosition">
<div key="dialog" ref="dialog" class={this.dialogClass} style={this.dialogStyle}>
<div class={headerClassName} onmousedown={this.onStopDown}>
<div class={`${this.componentName}__header-content`}>
{this.getIcon()}
{renderTNodeJSX(this, 'header', defaultHeader)}
</div>
{this.closeBtn ? (
<span class={closeClassName} onClick={this.closeBtnAction}>
{renderTNodeJSX(this, 'closeBtn', defaultCloseBtn)}
</span>
) : null}
</div>
<div class={bodyClassName} onmousedown={this.onStopDown}>
{body}
</div>
{footer}
</div>
</div>
</div>
);
},
},
render() {
const maskView = (this.isModal || this.isFullScreen) && <div key="mask" class={this.maskClass}></div>;
const dialogView = this.renderDialog();
const view = [maskView, dialogView];
const ctxStyle = { zIndex: this.zIndex };
if (this.destroyOnClose && !this.visible && this.animationEnd) return null;
return (
<transition
duration={300}
name={`${this.componentName}-zoom__vue`}
onAfterEnter={this.afterEnter}
onAfterLeave={this.afterLeave}
>
<div v-show={this.visible} class={this.ctxClass} style={ctxStyle} v-transfer-dom={this.attach}>
{view}
</div>
</transition>
);
},
});