diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.test.ts b/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.test.ts index 273611e94ee40a..e26a1e43509c81 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.test.ts +++ b/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.test.ts @@ -200,6 +200,25 @@ describe('sortLayer', () => { ]); }); + // Hidden map layers on map load may not add mbLayers to mbStyle. + test('Should sort with missing mblayers to expected order', () => { + // Notice there are no bravo mbLayers in initial style. + const initialMbStyle = { + version: 0, + layers: [ + { id: `${CHARLIE_LAYER_ID}_fill`, type: 'fill' } as MbLayer, + { id: `${ALPHA_LAYER_ID}_circle`, type: 'circle' } as MbLayer, + ], + }; + const mbMap = new MockMbMap(initialMbStyle); + syncLayerOrder((mbMap as unknown) as MbMap, spatialFilterLayer, mapLayers); + const sortedMbStyle = mbMap.getStyle(); + const sortedMbLayerIds = sortedMbStyle.layers!.map((mbLayer) => { + return mbLayer.id; + }); + expect(sortedMbLayerIds).toEqual(['charlie_fill', 'alpha_circle']); + }); + test('Should not call move layers when layers are in expected order', () => { const initialMbStyle = { version: 0, diff --git a/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.ts b/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.ts index 4752eeba2376aa..0c970fe6635576 100644 --- a/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.ts +++ b/x-pack/plugins/maps/public/connected_components/map/mb/sort_layers.ts @@ -128,7 +128,8 @@ export function syncLayerOrder(mbMap: MbMap, spatialFiltersLayer: ILayer, layerL if (!isLayerInOrder(mbMap, mapLayer, LAYER_CLASS.LABEL, beneathMbLayerId)) { moveMapLayer(mbMap, mbLayers, mapLayer, LAYER_CLASS.LABEL, beneathMbLayerId); } - beneathMbLayerId = getBottomMbLayerId(mbLayers, mapLayer, LAYER_CLASS.LABEL); + const bottomMbLayerId = getBottomMbLayerId(mbLayers, mapLayer, LAYER_CLASS.LABEL); + if (bottomMbLayerId) beneathMbLayerId = bottomMbLayerId; }); // Sort map layers @@ -137,6 +138,7 @@ export function syncLayerOrder(mbMap: MbMap, spatialFiltersLayer: ILayer, layerL if (!isLayerInOrder(mbMap, mapLayer, layerClass, beneathMbLayerId)) { moveMapLayer(mbMap, mbLayers, mapLayer, layerClass, beneathMbLayerId); } - beneathMbLayerId = getBottomMbLayerId(mbLayers, mapLayer, layerClass); + const bottomMbLayerId = getBottomMbLayerId(mbLayers, mapLayer, layerClass); + if (bottomMbLayerId) beneathMbLayerId = bottomMbLayerId; }); }