From f98f66c52935816975563c541af30c09a4794858 Mon Sep 17 00:00:00 2001 From: Andreas Hocevar Date: Wed, 19 Feb 2020 11:52:12 +0100 Subject: [PATCH] Make Select interaction work when there are multiple instances --- src/ol/interaction/Select.js | 48 +++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/src/ol/interaction/Select.js b/src/ol/interaction/Select.js index d838bf83c8..52bb569164 100644 --- a/src/ol/interaction/Select.js +++ b/src/ol/interaction/Select.js @@ -133,6 +133,12 @@ class SelectEvent extends Event { } +/** + * Original feature styles to reset to when features are no longer selected. + * @type {Object.|import("../style/Style.js").StyleFunction>} + */ +const originalFeatureStyles = {}; + /** * @classdesc @@ -209,14 +215,6 @@ class Select extends Interaction { */ this.style_ = options.style !== undefined ? options.style : getDefaultStyleFunction(); - /** - * An association between selected feature (key) - * and original style (value) - * @private - * @type {Object.|import("../style/Style.js").StyleFunction>} - */ - this.featureStyleAssociation_ = {}; - /** * @private * @type {import("../Collection.js").default} @@ -319,11 +317,11 @@ class Select extends Interaction { setMap(map) { const currentMap = this.getMap(); if (currentMap && this.style_) { - this.features_.forEach(this.removeSelectedStyle_.bind(this)); + this.features_.forEach(this.restorePreviousStyle_.bind(this)); } super.setMap(map); if (map && this.style_) { - this.features_.forEach(this.giveSelectedStyle_.bind(this)); + this.features_.forEach(this.applySelectedStyle_.bind(this)); } } @@ -334,7 +332,7 @@ class Select extends Interaction { addFeature_(evt) { const feature = evt.element; if (this.style_) { - this.giveSelectedStyle_(feature); + this.applySelectedStyle_(feature); } } @@ -345,17 +343,26 @@ class Select extends Interaction { removeFeature_(evt) { const feature = evt.element; if (this.style_) { - this.removeSelectedStyle_(feature); + this.restorePreviousStyle_(feature); } } + /** + * @return {import("../style/Style.js").default|Array.|import("../style/Style.js").StyleFunction|null} Select style. + */ + getStyle() { + return this.style_; + } + /** * @param {import("../Feature.js").default} feature Feature * @private */ - giveSelectedStyle_(feature) { + applySelectedStyle_(feature) { const key = getUid(feature); - this.featureStyleAssociation_[key] = feature.getStyle(); + if (!(key in originalFeatureStyles)) { + originalFeatureStyles[key] = feature.getStyle(); + } feature.setStyle(this.style_); } @@ -363,10 +370,17 @@ class Select extends Interaction { * @param {import("../Feature.js").default} feature Feature * @private */ - removeSelectedStyle_(feature) { + restorePreviousStyle_(feature) { const key = getUid(feature); - feature.setStyle(this.featureStyleAssociation_[key]); - delete this.featureStyleAssociation_[key]; + const selectInteractions = /** @type {Array