-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathpopup.tsx
More file actions
473 lines (456 loc) · 14.6 KB
/
popup.tsx
File metadata and controls
473 lines (456 loc) · 14.6 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
import { VNodeDirective } from 'vue';
import { createPopper } from '@popperjs/core';
import debounce from 'lodash/debounce';
import { on, off, once } from '../utils/dom';
import { renderTNodeJSX, renderContent } from '../utils/render-tnode';
import { getIEVersion } from '../utils/helper';
import setStyle from '../_common/js/utils/set-style';
import props from './props';
import { PopupVisibleChangeContext, TdPopupProps } from './type';
import Container from './container';
import { getClassPrefixMixins, getAttachConfigMixins } from '../config-provider/config-receiver';
import mixins from '../utils/mixins';
import { emitEvent } from '../utils/event';
import {
getPopperPlacement, attachListeners, triggers, defaultVisibleDelay,
} from './utils';
import { AttachNode } from '../common';
const classPrefixMixins = getClassPrefixMixins('popup');
const injectionKey = '__T_POPUP';
export default mixins(classPrefixMixins, getAttachConfigMixins('popup')).extend({
name: 'TPopup',
provide(this: any) {
return {
[injectionKey]: this,
};
},
inject: {
popup: {
from: injectionKey,
default: undefined,
},
},
props: {
...props,
expandAnimation: {
type: Boolean,
},
updateScrollTop: {
type: Function,
},
},
data() {
return {
/** popperjs instance */
popper: null as ReturnType<typeof createPopper>,
/** timeout id */
timeout: null,
hasDocumentEvent: false,
/** if a trusted action (opening or closing) is prevented, increase this flag */
visibleState: 0,
mouseInRange: false,
/** mark popup as clicked when mousedown, reset after mouseup */
contentClicked: false,
/** is popup leaving */
isLeaving: false,
};
},
computed: {
overlayClasses(): any {
return [
`${this.componentName}__content`,
{
[`${this.componentName}__content--text`]: this.content === 'string',
[`${this.componentName}__content--arrow`]: this.showArrow,
[this.commonStatusClassName.disabled]: this.disabled,
},
this.overlayInnerClassName,
];
},
hasTrigger(): Record<(typeof triggers)[number], boolean> {
return triggers.reduce(
(map, trigger) => ({
...map,
[trigger]: this.trigger.includes(trigger),
}),
{} as any,
);
},
normalizedDelay(): { open: number; close: number } {
const delay = [].concat(this.delay ?? defaultVisibleDelay);
return {
open: delay[0],
close: delay[1] ?? delay[0],
};
},
computeAttach(): AttachNode {
return this.attach || this.globalAttach();
},
},
watch: {
visible(visible) {
const { hasTrigger, $el: triggerEl } = this;
if (visible) {
this.preventClosing(true);
if (!this.hasDocumentEvent) {
on(document, 'mousedown', this.handleDocumentClick, true);
this.hasDocumentEvent = true;
}
// focus trigger esc 隐藏浮层
if (triggerEl && hasTrigger.focus) {
once(triggerEl, 'keydown', (ev: KeyboardEvent) => {
if (ev.code === 'Escape') {
this.handleClose({ trigger: 'keydown-esc' });
}
});
}
this.$nextTick(() => {
this.popupMounted();
this.updateOverlayInnerStyle();
});
} else {
this.preventClosing(false);
// destruction is delayed until after animation ends
off(document, 'mousedown', this.handleDocumentClick, true);
this.hasDocumentEvent = false;
this.mouseInRange = false;
}
},
overlayInnerStyle() {
this.updateOverlayInnerStyle();
this.updatePopper();
},
placement() {
this.popper?.destroy();
this.popper = null;
this.updatePopper();
},
// sync lock state recursively
contentClicked(clicked) {
if ((this as any).popup) {
(this as any).popup.contentClicked = clicked;
}
},
},
mounted() {
const trigger = attachListeners(this.$el);
const updateTrigger = () => {
trigger.clean();
const { hasTrigger } = this;
if (hasTrigger.hover) {
trigger.add('mouseenter', () => this.handleOpen({ trigger: 'trigger-element-hover' }));
trigger.add('mouseleave', () => this.handleClose({ trigger: 'trigger-element-hover' }));
} else if (hasTrigger.focus) {
trigger.add('focusin', () => this.handleOpen({ trigger: 'trigger-element-focus' }));
trigger.add('focusout', () => this.handleClose({ trigger: 'trigger-element-blur' }));
} else if (hasTrigger.click) {
trigger.add('click', (e: MouseEvent) => {
this.handleToggle({ e, trigger: 'trigger-element-click' });
// ie9-10 trigger propagation
if (getIEVersion() < 11) {
this.handleDocumentClick(e);
}
});
} else if (hasTrigger['context-menu']) {
trigger.add('contextmenu', (e: MouseEvent) => {
e.preventDefault();
// MouseEvent.button
// 2: Secondary button pressed, usually the right button
e.button === 2 && this.handleToggle({ trigger: 'context-menu' });
});
}
};
updateTrigger();
this.$watch('trigger', updateTrigger);
},
updated() {
(this.$refs.container as any)?.updateContent();
},
beforeDestroy() {
if (this.visible) {
(this as any).popup?.preventClosing(false);
}
this.destroyPopper();
off(document, 'mousedown', this.handleDocumentClick, true);
clearTimeout(this.timeout);
},
methods: {
updatePopper() {
const { $el: triggerEl } = this;
const popperEl = this.$refs.popper as HTMLElement;
if (!popperEl || !this.visible) return;
if (this.popper) {
this.popper.update();
return;
}
this.popper = createPopper(triggerEl, popperEl, {
modifiers:
getIEVersion() > 9
? []
: [
{
name: 'computeStyles',
options: {
// 默认为 true,即使用 transform 定位,开启 gpu 加速
// ie9 不支持 transform,需要添加 -ms- 前缀,@popperjs/core 没有添加这个样式,
// 在 ie9 下则去掉 gpu 优化加速,使用 top, right, bottom, left 定位
gpuAcceleration: false,
},
},
],
placement: getPopperPlacement(this.placement as TdPopupProps['placement']),
onFirstUpdate: () => {
this.$nextTick(this.updatePopper);
},
...this.popperOptions,
});
},
// popup弹出第一次初始化暴露事件
popupMounted() {
// 用于下拉组件定位事件
const overlayEl = this.$refs?.overlay as HTMLElement;
if (overlayEl) {
this.updateScrollTop?.(overlayEl);
}
},
getOverlayStyle() {
const { overlayStyle } = this;
const triggerEl = this.$el as HTMLElement;
const overlayEl = this.$refs?.overlay as HTMLElement;
if (typeof overlayStyle === 'function') {
return overlayStyle(triggerEl, overlayEl);
}
if (typeof overlayStyle === 'object') {
return overlayStyle;
}
},
updateOverlayInnerStyle() {
const { overlayInnerStyle } = this;
const triggerEl = this.$el as HTMLElement;
const overlayEl = this.$refs?.overlay as HTMLElement;
if (!triggerEl || !overlayEl) return;
if (typeof overlayInnerStyle === 'function') {
setStyle(overlayEl, overlayInnerStyle(triggerEl, overlayEl));
} else if (typeof overlayInnerStyle === 'object') {
setStyle(overlayEl, overlayInnerStyle);
}
},
/**
* destroy popper IF NEEDED
*/
destroyPopper() {
if (this.popper) {
this.popper.destroy();
this.popper = null;
}
if (this.destroyOnClose) {
(this.$refs.container as any)?.unmountContent();
}
},
handleToggle(context: PopupVisibleChangeContext) {
this.emitPopVisible(!this.visible, context);
},
handleOnScroll(e: WheelEvent) {
const { scrollTop, clientHeight, scrollHeight } = e.target as HTMLDivElement;
// 防止多次触发添加截流
const debounceOnScrollBottom = debounce((e) => emitEvent(this, 'scroll-to-bottom', { e }), 100);
// windows 下 scrollTop 会出现小数,这里取整
if (clientHeight + Math.floor(scrollTop) === scrollHeight) {
// touch bottom
debounceOnScrollBottom(e);
}
emitEvent(this, 'scroll', { e });
},
handleOpen(context: Pick<PopupVisibleChangeContext, 'trigger'>) {
clearTimeout(this.timeout);
this.timeout = setTimeout(
() => {
this.emitPopVisible(true, context);
},
this.hasTrigger.click ? 0 : this.normalizedDelay.open,
);
},
handleClose(context: Pick<PopupVisibleChangeContext, 'trigger'>) {
clearTimeout(this.timeout);
this.timeout = setTimeout(
() => {
this.emitPopVisible(false, context);
},
this.hasTrigger.click ? 0 : this.normalizedDelay.close,
);
},
handleDocumentClick(ev?: MouseEvent) {
// Make sure content's mousedown event fires first
setTimeout(() => {
if (this.contentClicked) {
// clear the flag after mousedown
setTimeout(() => {
this.contentClicked = false;
});
return;
}
const triggerEl = this.$el as HTMLElement;
// ignore document event when clicking trigger element
if (triggerEl.contains(ev.target as Node)) return;
// ignore document event if popper panel clicked
const popperEl = this.$refs.popper as HTMLDivElement;
if (popperEl?.contains(ev.target as Node)) return;
this.visibleState = 0;
this.emitPopVisible(false, { trigger: 'document', e: ev });
});
},
emitPopVisible(visible: boolean, context: PopupVisibleChangeContext) {
if (this.disabled || visible === !!this.visible) return;
if (!visible && this.visibleState > 1) return;
if (visible && this.mouseInRange) return;
this.$emit('visible-change', visible, context);
if (typeof this.onVisibleChange === 'function') {
this.onVisibleChange(visible, context);
}
},
onMouseEnter() {
if (this.destroyOnClose && this.isLeaving) {
// 如果 popup 在关闭的时候会被销毁,那在它消失的过程中,不响应鼠标进入事件,因为否则不会触发 mouseleave
return;
}
this.mouseInRange = true;
this.handleOpen({});
},
onMouseLeave(ev: MouseEvent) {
// 子元素存在打开的 popup 时,ui 可能重叠,而 dom 节点多是并列关系
// 需要做碰撞检测去阻止父级 popup 关闭
if (this.visibleState > 1) {
const rect = (this.$refs.popper as HTMLElement).getBoundingClientRect();
if (ev.x > rect.x && ev.x < rect.x + rect.width && ev.y > rect.y && ev.y < rect.y + rect.height) return;
}
this.mouseInRange = false;
this.handleClose({});
// parent can no longer monitor mouse leave
const parent = (this as any).popup;
if (parent?.mouseInRange) {
parent.onMouseLeave(ev);
}
},
onBeforeEnter() {
if (this.visible) {
this.updatePopper();
}
},
onAfterEnter() {
if (this.visible) {
this.updatePopper();
}
},
onLeave() {
this.isLeaving = true;
},
onAfterLeave() {
this.isLeaving = false;
this.destroyPopper();
},
preventClosing(preventing: boolean) {
const parent = (this as any).popup;
parent?.preventClosing(preventing);
if (preventing) {
this.visibleState += 1;
} else if (this.visibleState) {
this.visibleState -= 1;
if (!this.visibleState) {
this.emitPopVisible(false, {});
if (parent?.hasTrigger.hover && !parent?.mouseInRange) {
parent.emitPopVisible(false, {});
}
}
}
},
},
render(h) {
const {
visible, destroyOnClose, hasTrigger, handleOnScroll,
} = this;
const ref = renderContent(this, 'default', 'triggerElement');
const content = renderTNodeJSX(this, 'content');
const hidePopup = this.hideEmptyPopup && ['', undefined, null].includes(content);
const overlay = visible || !destroyOnClose
? h(
'div',
{
class: [this.componentName, this.overlayClassName],
ref: 'popper',
style: [
hidePopup && { visibility: 'hidden', pointerEvents: 'none' },
{ zIndex: this.zIndex },
this.getOverlayStyle(),
],
directives: destroyOnClose
? undefined
: [
{
name: 'show',
rawName: 'v-show',
value: visible && !hidePopup,
expression: 'visible',
} as VNodeDirective,
],
on: {
mousedown: () => {
this.contentClicked = true;
},
...(hasTrigger.hover && {
mouseenter: this.onMouseEnter,
mouseleave: this.onMouseLeave,
}),
},
},
[
h(
'div',
{
class: this.overlayClasses,
ref: 'overlay',
on: {
scroll(e: WheelEvent) {
handleOnScroll(e);
},
},
},
[content, this.showArrow && h('div', { class: `${this.componentName}__arrow` })],
),
],
)
: null;
return (
<Container
ref="container"
onContentMounted={() => {
if (visible) {
this.updatePopper();
this.updateOverlayInnerStyle();
}
}}
onResize={() => {
if (visible) {
this.updatePopper();
this.updateOverlayInnerStyle();
}
}}
parent={this}
visible={visible}
attach={() => ({ attach: this.computeAttach, current: this.$el })}
>
<transition
slot="content"
name={this.expandAnimation ? `${this.componentName}--animation-expand` : `${this.componentName}--animation`}
appear
onBeforeEnter={this.onBeforeEnter}
onAfterEnter={this.onAfterEnter}
onLeave={this.onLeave}
onAfterLeave={this.onAfterLeave}
>
{overlay}
</transition>
{ref}
</Container>
);
},
});