Skip to content

Commit

Permalink
fix(LayerManager): check click outside event on the same layer where …
Browse files Browse the repository at this point in the history
…the mousedown event happened (#549)
  • Loading branch information
ValeraS authored and amje committed Mar 1, 2023
1 parent 6f502a0 commit 2df5362
Showing 1 changed file with 26 additions and 8 deletions.
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

0 comments on commit 2df5362

Please sign in to comment.