Remove focus listeners with unbinding tooltip (#9232)

Co-authored-by: Adauji <5890802@ez.edeka.net>
Co-authored-by: Florian Bischof <design.falke@gmail.com>
This commit is contained in:
Mihai Adauji
2025-03-01 12:03:39 +02:00
committed by GitHub
parent ecdb13df2e
commit 7d6bb49a43
2 changed files with 60 additions and 13 deletions

View File

@ -580,4 +580,36 @@ describe('Tooltip', () => {
layer2.openTooltip();
expect(spy2.called).to.be.true;
});
it('removes focus listeners after unbinding tooltip from Layer', () => {
const marker = new Marker([51.515, -0.09]).addTo(map);
marker
.bindTooltip('Tooltip that will be unbinded')
.openTooltip();
expect(marker.getElement()._leaflet_focus_handler).to.be.not.undefined;
marker.unbindTooltip();
expect(() => UIEventSimulator.fire('focus', marker.getElement())).to.not.throw();
expect(marker.getElement()._leaflet_focus_handler).to.be.undefined;
});
it('removes focus listeners after unbinding tooltip from FeatureGroup', () => {
const marker = new Marker([51.515, -0.09]);
const layergroup = new FeatureGroup([marker]).addTo(map);
layergroup
.bindTooltip('Tooltip that will be unbinded in two seconds')
.openTooltip();
expect(marker.getElement()._leaflet_focus_handler).to.be.not.undefined;
layergroup.unbindTooltip();
expect(() => UIEventSimulator.fire('focus', marker.getElement())).to.not.throw();
expect(marker.getElement()._leaflet_focus_handler).to.be.undefined;
});
});

View File

@ -312,9 +312,9 @@ Layer.include({
events.mouseout = this.closeTooltip;
events.click = this._openTooltip;
if (this._map) {
this._addFocusListeners();
this._addFocusListeners(remove);
} else {
events.add = this._addFocusListeners;
events.add = () => this._addFocusListeners(remove);
}
} else {
events.add = this._openTooltip;
@ -385,22 +385,37 @@ Layer.include({
return this._tooltip;
},
_addFocusListeners() {
_addFocusListeners(remove) {
if (this.getElement) {
this._addFocusListenersOnLayer(this);
this._addFocusListenersOnLayer(this, remove);
} else if (this.eachLayer) {
this.eachLayer(this._addFocusListenersOnLayer, this);
this.eachLayer(layer => this._addFocusListenersOnLayer(layer, remove), this);
}
},
_addFocusListenersOnLayer(layer) {
_addFocusListenersOnLayer(layer, remove) {
const el = typeof layer.getElement === 'function' && layer.getElement();
if (el) {
DomEvent.on(el, 'focus', function () {
const onOff = remove ? 'off' : 'on';
if (!remove) {
// Remove focus listener, if already existing
el._leaflet_focus_handler && DomEvent.off(el, 'focus', el._leaflet_focus_handler, this);
// eslint-disable-next-line camelcase
el._leaflet_focus_handler = () => {
if (this._tooltip) {
this._tooltip._source = layer;
this.openTooltip();
}, this);
DomEvent.on(el, 'blur', this.closeTooltip, this);
}
};
}
el._leaflet_focus_handler && DomEvent[onOff](el, 'focus', el._leaflet_focus_handler, this);
DomEvent[onOff](el, 'blur', this.closeTooltip, this);
if (remove) {
delete el._leaflet_focus_handler;
}
}
},