Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(LayerManager): check click outside event on the same layer where the mousedown event happened #549

Merged
merged 1 commit into from
Mar 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions src/components/utils/LayerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export interface LayerConfig extends LayerExtendableProps {

class LayerManager {
private stack: LayerConfig[] = [];
private mouseDownTarget: HTMLElement | null = null;
private mouseDownLayerTarget?: {layer: LayerConfig; target: HTMLElement};

add(config: LayerConfig) {
this.stack.push(config);
Expand Down Expand Up @@ -70,23 +70,41 @@ class LayerManager {
};

private handleDocumentClick = (event: MouseEvent) => {
const topLayer = this.getTopLayer();
let layer: LayerConfig;
let mouseDownTarget: HTMLElement | null = null;
if (this.mouseDownLayerTarget) {
layer = this.mouseDownLayerTarget.layer;
mouseDownTarget = this.mouseDownLayerTarget.target;
this.mouseDownLayerTarget = undefined;
if (!this.stack.includes(layer)) {
return;
}
} else {
layer = this.getTopLayer();
}

if (!topLayer.disableOutsideClick && this.isOutsideClick(topLayer, event)) {
topLayer.onOutsideClick?.(event);
topLayer.onClose?.(event, 'outsideClick');
if (!layer.disableOutsideClick && this.isOutsideClick(layer, event, mouseDownTarget)) {
layer.onOutsideClick?.(event);
layer.onClose?.(event, 'outsideClick');
}
};

private handleDocumentMouseDown = (event: MouseEvent) => {
this.mouseDownTarget = event.target as HTMLElement;
const layer = this.getTopLayer();
if (layer) {
this.mouseDownLayerTarget = {layer, target: event.target as HTMLElement};
}
};

private getTopLayer() {
return this.stack[this.stack.length - 1];
}

private isOutsideClick(layer: LayerConfig, event: MouseEvent) {
private isOutsideClick(
layer: LayerConfig,
event: MouseEvent,
mouseDownTarget: HTMLElement | null = null,
) {
const contentElements = layer.contentRefs || [];
const {target} = event;
const composedPath = typeof event.composedPath === 'function' ? event.composedPath() : [];
Expand All @@ -95,7 +113,7 @@ class LayerManager {
const isClickOnContentElements = contentElements.some(
(el) =>
el?.current?.contains?.(target as Element) ||
el?.current?.contains?.(this.mouseDownTarget) ||
el?.current?.contains?.(mouseDownTarget) ||
composedPath.includes(el?.current as EventTarget),
);

Expand Down