You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by di...@apache.org on 2024/11/21 13:08:23 UTC

(superset) branch geido/fix/color-consistency-race-conditions updated (50e82129b8 -> 3f7df9f37a)

This is an automated email from the ASF dual-hosted git repository.

diegopucci pushed a change to branch geido/fix/color-consistency-race-conditions
in repository https://gitbox.apache.org/repos/asf/superset.git


    omit 50e82129b8 chore(Dashboard): Clean up color consistency functions
     new 3f7df9f37a chore(Dashboard): Clean up color consistency functions

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (50e82129b8)
            \
             N -- N -- N   refs/heads/geido/fix/color-consistency-race-conditions (3f7df9f37a)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 superset-frontend/src/dashboard/actions/dashboardState.js | 4 +++-
 superset/examples/birth_names.py                          | 7 ++-----
 2 files changed, 5 insertions(+), 6 deletions(-)


(superset) 01/01: chore(Dashboard): Clean up color consistency functions

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diegopucci pushed a commit to branch geido/fix/color-consistency-race-conditions
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 3f7df9f37a4674dec62d1cb7d4536ca7631e76d5
Author: Diego Pucci <di...@gmail.com>
AuthorDate: Wed Nov 20 16:38:41 2024 +0200

    chore(Dashboard): Clean up color consistency functions
---
 .../cypress/e2e/dashboard/editmode.test.ts         |  94 +++++-----
 .../src/utils/colorControls.ts                     |   2 +
 .../test/utils/colorControls.test.ts               |  10 ++
 .../src/color/CategoricalColorNamespace.ts         |   2 +-
 .../test/color/CategoricalColorNameSpace.test.ts   |  16 +-
 .../test/color/CategoricalColorScale.test.ts       |   2 +-
 .../src/dashboard/actions/dashboardState.js        | 192 ++++++++++++++-------
 .../dashboard/components/PropertiesModal/index.tsx |   9 +-
 .../dashboard/components/gridComponents/Chart.jsx  |  14 +-
 .../src/dashboard/reducers/dashboardState.js       |  26 ++-
 .../components/ExploreChartHeader/index.jsx        |   4 +-
 .../controls/ColorSchemeControl/index.tsx          |  25 ++-
 superset-frontend/src/utils/colorScheme.ts         |   3 +-
 superset/examples/birth_names.py                   |  23 ++-
 14 files changed, 281 insertions(+), 141 deletions(-)

diff --git a/superset-frontend/cypress-base/cypress/e2e/dashboard/editmode.test.ts b/superset-frontend/cypress-base/cypress/e2e/dashboard/editmode.test.ts
index d9806f0937..0f7005bf85 100644
--- a/superset-frontend/cypress-base/cypress/e2e/dashboard/editmode.test.ts
+++ b/superset-frontend/cypress-base/cypress/e2e/dashboard/editmode.test.ts
@@ -165,27 +165,23 @@ function selectColorScheme(
     .first()
     .then($input => {
       cy.wrap($input).click({ force: true });
-      cy.wrap($input).type(color.slice(0, 3), { force: true });
+      cy.wrap($input).type(color.slice(0, 5), { force: true });
     });
   cy.getBySel(color).click({ force: true });
 }
 
-function setExploreAdmin(username: string) {
+function saveAndGo(dashboard = 'Tabbed Dashboard') {
   interceptExploreUpdate();
-  cy.get(`input[aria-label="Owners"]`)
-    .first()
-    .then($input => {
-      cy.get('body').then($body => {
-        if ($body.find('.ant-tag-close-icon').length) {
-          cy.get('.ant-tag-close-icon').click({ force: true, multiple: true });
-        }
-        cy.wrap($input).click({ force: true });
-        cy.wrap($input).type(username.slice(0, 5), { force: true });
-        cy.wrap($input).type('{enter}');
-      });
-    });
-  cy.getBySel('properties-modal-save-button').click();
-  cy.wait('@chartUpdate');
+  cy.getBySel('query-save-button').click();
+  cy.getBySel('save-modal-body').then($modal => {
+    cy.wrap($modal)
+      .find("div[aria-label='Select a dashboard'] .ant-select-selection-item")
+      .should('have.text', dashboard);
+    cy.getBySel('save-overwrite-radio').should('not.be.disabled');
+    cy.getBySel('save-overwrite-radio').click();
+    cy.get('#btn_modal_save_goto_dash').click();
+    cy.wait('@chartUpdate');
+  });
 }
 
 function applyChanges() {
@@ -228,7 +224,7 @@ function writeMetadata(metadata: string) {
   });
 }
 
-function openExplore(chartName: string) {
+function openExploreWithDashboardContext(chartName: string) {
   interceptExploreJson();
   interceptGet();
 
@@ -245,11 +241,24 @@ function openExplore(chartName: string) {
   cy.get('.chart-container').should('exist');
 }
 
+function saveExploreColorScheme(
+  chart = 'Top 10 California Names Timeseries',
+  colorScheme = 'supersetColors',
+) {
+  interceptExploreUpdate();
+  openExploreWithDashboardContext(chart);
+  openTab(0, 1, 'control-tabs');
+  selectColorScheme(colorScheme, 'control-item');
+  cy.getBySel('query-save-button').click();
+  cy.getBySel('save-overwrite-radio').click();
+  cy.getBySel('btn-modal-save').click();
+  cy.wait('@chartUpdate');
+}
+
 describe('Dashboard edit', () => {
   describe('Color consistency', () => {
     beforeEach(() => {
       resetDashboardColors();
-      resetDashboardColors('supported_charts_dash');
     });
 
     it('should not allow to change color scheme of a chart when dashboard has one', () => {
@@ -266,7 +275,7 @@ describe('Dashboard edit', () => {
         viz: 'line',
       });
 
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -296,7 +305,7 @@ describe('Dashboard edit', () => {
       });
 
       openTab(0, 0);
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -331,7 +340,7 @@ describe('Dashboard edit', () => {
         .first()
         .should('have.css', 'fill', 'rgb(255, 0, 0)');
 
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -350,6 +359,16 @@ describe('Dashboard edit', () => {
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
         .eq(1)
         .should('have.css', 'fill', 'rgb(50, 0, 167)');
+
+      // label Daniel
+      cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
+        .eq(2)
+        .should('have.css', 'fill', 'rgb(0, 76, 218)');
+
+      // label David
+      cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
+        .eq(3)
+        .should('have.css', 'fill', 'rgb(0, 116, 241)');
     });
 
     it('should allow to change color scheme of a chart when dashboard has no scheme and show the change', () => {
@@ -369,7 +388,7 @@ describe('Dashboard edit', () => {
         .first()
         .should('have.css', 'fill', 'rgb(31, 168, 201)');
 
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -384,11 +403,7 @@ describe('Dashboard edit', () => {
         .first()
         .should('have.css', 'fill', 'rgb(50, 0, 167)');
 
-      openExploreProperties();
-      setExploreAdmin('admin user');
-      cy.getBySel('query-save-button').click();
-      cy.getBySel('save-overwrite-radio').click();
-      cy.get('#btn_modal_save_goto_dash').click();
+      saveAndGo();
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -396,12 +411,7 @@ describe('Dashboard edit', () => {
         .should('have.css', 'fill', 'rgb(50, 0, 167)');
 
       // reset original scheme
-      openExplore('Top 10 California Names Timeseries');
-      openTab(0, 1, 'control-tabs');
-      selectColorScheme('supersetColors', 'control-item');
-      cy.getBySel('query-save-button').click();
-      cy.getBySel('save-overwrite-radio').click();
-      cy.get('#btn_modal_save_goto_dash').click();
+      saveExploreColorScheme();
     });
 
     it('should allow to change color scheme of a chart when dashboard has no scheme but custom label colors and show the change', () => {
@@ -427,7 +437,7 @@ describe('Dashboard edit', () => {
         .first()
         .should('have.css', 'fill', 'rgb(255, 0, 0)');
 
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -447,11 +457,7 @@ describe('Dashboard edit', () => {
         .eq(1)
         .should('have.css', 'fill', 'rgb(50, 0, 167)');
 
-      openExploreProperties();
-      setExploreAdmin('admin user');
-      cy.getBySel('query-save-button').click();
-      cy.getBySel('save-overwrite-radio').click();
-      cy.get('#btn_modal_save_goto_dash').click();
+      saveAndGo();
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -464,12 +470,7 @@ describe('Dashboard edit', () => {
         .should('have.css', 'fill', 'rgb(50, 0, 167)');
 
       // reset original scheme
-      openExplore('Top 10 California Names Timeseries');
-      openTab(0, 1, 'control-tabs');
-      selectColorScheme('supersetColors', 'control-item');
-      cy.getBySel('query-save-button').click();
-      cy.getBySel('save-overwrite-radio').click();
-      cy.get('#btn_modal_save_goto_dash').click();
+      saveExploreColorScheme();
     });
 
     it('should not change colors on refreshes with no color scheme set', () => {
@@ -897,7 +898,7 @@ describe('Dashboard edit', () => {
         .first()
         .should('have.css', 'fill', 'rgb(255, 0, 0)');
 
-      openExplore('Top 10 California Names Timeseries');
+      openExploreWithDashboardContext('Top 10 California Names Timeseries');
 
       // label Anthony
       cy.get('[data-test="chart-container"] .line .nv-legend-symbol')
@@ -1064,6 +1065,7 @@ describe('Dashboard edit', () => {
     beforeEach(() => {
       cy.createSampleDashboards([0]);
       openProperties();
+      selectColorScheme('supersetColors');
     });
 
     it('should accept a valid color scheme', () => {
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/utils/colorControls.ts b/superset-frontend/packages/superset-ui-chart-controls/src/utils/colorControls.ts
index 5ee5e6363d..b9400d9d41 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/utils/colorControls.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/utils/colorControls.ts
@@ -25,6 +25,8 @@ export const getColorControlsProps = (state: Record<string, any>) => {
       !!dashboardId && !!state?.form_data?.dashboard_color_scheme,
     hasCustomLabelsColor:
       Object.keys(state?.form_data?.label_colors || {}).length > 0,
+    colorNamespace: state?.form_data?.color_namespace,
+    mapLabelsColors: state?.form_data?.map_label_colors || {},
     sharedLabelsColors: state?.form_data?.shared_label_colors || [],
   };
 };
diff --git a/superset-frontend/packages/superset-ui-chart-controls/test/utils/colorControls.test.ts b/superset-frontend/packages/superset-ui-chart-controls/test/utils/colorControls.test.ts
index c96b45659c..deadc3eede 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/test/utils/colorControls.test.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/test/utils/colorControls.test.ts
@@ -27,6 +27,8 @@ describe('getColorControlsProps', () => {
       dashboardId: undefined,
       hasDashboardColorScheme: false,
       hasCustomLabelsColor: false,
+      colorNamespace: undefined,
+      mapLabelsColors: {},
       sharedLabelsColors: [],
     });
   });
@@ -46,6 +48,8 @@ describe('getColorControlsProps', () => {
       dashboardId: 123,
       hasDashboardColorScheme: true,
       hasCustomLabelsColor: false,
+      colorNamespace: undefined,
+      mapLabelsColors: {},
       sharedLabelsColors: [],
     });
   });
@@ -64,6 +68,8 @@ describe('getColorControlsProps', () => {
       dashboardId: 123,
       hasDashboardColorScheme: false,
       hasCustomLabelsColor: true,
+      colorNamespace: undefined,
+      mapLabelsColors: {},
       sharedLabelsColors: [],
     });
   });
@@ -81,6 +87,8 @@ describe('getColorControlsProps', () => {
       hasDashboardColorScheme: false,
       hasCustomLabelsColor: false,
       sharedLabelsColors: ['#FF5733', '#33FF57'],
+      colorNamespace: undefined,
+      mapLabelsColors: {},
     });
   });
 
@@ -96,6 +104,8 @@ describe('getColorControlsProps', () => {
       dashboardId: 789,
       hasDashboardColorScheme: false,
       hasCustomLabelsColor: false,
+      colorNamespace: undefined,
+      mapLabelsColors: {},
       sharedLabelsColors: [],
     });
   });
diff --git a/superset-frontend/packages/superset-ui-core/src/color/CategoricalColorNamespace.ts b/superset-frontend/packages/superset-ui-core/src/color/CategoricalColorNamespace.ts
index 28535c7d95..9389ad549f 100644
--- a/superset-frontend/packages/superset-ui-core/src/color/CategoricalColorNamespace.ts
+++ b/superset-frontend/packages/superset-ui-core/src/color/CategoricalColorNamespace.ts
@@ -72,7 +72,7 @@ export default class CategoricalColorNamespace {
     this.forcedItems = {};
   }
 
-  resetIndividualColors(labels: string[] = []) {
+  resetColorsForLabels(labels: string[] = []) {
     const updatedForcedItems = cloneDeep(this.forcedItems);
     labels.forEach(label => {
       if (updatedForcedItems.hasOwnProperty(label)) {
diff --git a/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorNameSpace.test.ts b/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorNameSpace.test.ts
index 83e11d67bd..014be25486 100644
--- a/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorNameSpace.test.ts
+++ b/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorNameSpace.test.ts
@@ -161,12 +161,12 @@ describe('CategoricalColorNamespace', () => {
       expect(color).toBe(color2);
     });
   });
-  describe('statis resetIndividualColors(labels)', () => {
+  describe('statis resetColorsForLabels(labels)', () => {
     it('removes specified labels from forcedItems', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
       namespace.setColor('label2', 'blue');
-      namespace.resetIndividualColors(['label1']);
+      namespace.resetColorsForLabels(['label1']);
 
       expect(namespace.forcedItems).toMatchObject({ label2: 'blue' });
     });
@@ -174,7 +174,7 @@ describe('CategoricalColorNamespace', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
       namespace.setColor('label2', 'blue');
-      namespace.resetIndividualColors();
+      namespace.resetColorsForLabels();
 
       expect(namespace.forcedItems).toMatchObject({
         label1: 'red',
@@ -184,7 +184,7 @@ describe('CategoricalColorNamespace', () => {
     it('does nothing if the label is not in forcedItems', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
-      namespace.resetIndividualColors(['label2']); // label2 doesn't exist
+      namespace.resetColorsForLabels(['label2']); // label2 doesn't exist
 
       expect(namespace.forcedItems).toMatchObject({ label1: 'red' });
     });
@@ -192,7 +192,7 @@ describe('CategoricalColorNamespace', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
       namespace.setColor('label2', 'blue');
-      namespace.resetIndividualColors(['label1', 'label2']);
+      namespace.resetColorsForLabels(['label1', 'label2']);
 
       expect(namespace.forcedItems).toMatchObject({});
     });
@@ -201,21 +201,21 @@ describe('CategoricalColorNamespace', () => {
       namespace.setColor('label1', 'red');
 
       const originalForcedItems = namespace.forcedItems;
-      namespace.resetIndividualColors(['label1']);
+      namespace.resetColorsForLabels(['label1']);
 
       expect(originalForcedItems).not.toBe(namespace.forcedItems);
     });
     it('removes the label if it exists in updatedForcedItems', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
-      namespace.resetIndividualColors(['label1']);
+      namespace.resetColorsForLabels(['label1']);
 
       expect(namespace.forcedItems).toEqual({});
     });
     it('does nothing for a label not in updatedForcedItems', () => {
       const namespace = getNamespace('test-reset-individual');
       namespace.setColor('label1', 'red');
-      namespace.resetIndividualColors(['label2']); // label2 doesn't exist
+      namespace.resetColorsForLabels(['label2']); // label2 doesn't exist
 
       expect(namespace.forcedItems).toEqual({ label1: 'red' });
     });
diff --git a/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorScale.test.ts b/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorScale.test.ts
index 4ebc99413c..9ba4bcc5b0 100644
--- a/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorScale.test.ts
+++ b/superset-frontend/packages/superset-ui-core/test/color/CategoricalColorScale.test.ts
@@ -33,7 +33,7 @@ describe('CategoricalColorScale', () => {
     expect(CategoricalColorScale !== undefined).toBe(true);
   });
 
-  describe('new CategoricalColorScale(colors, forcedColors, colorScheme, originalScheme)', () => {
+  describe('new CategoricalColorScale(colors, forcedColors)', () => {
     it('can create new scale when forcedColors is not given', () => {
       const scale = new CategoricalColorScale(['blue', 'red', 'green']);
       expect(scale).toBeInstanceOf(CategoricalColorScale);
diff --git a/superset-frontend/src/dashboard/actions/dashboardState.js b/superset-frontend/src/dashboard/actions/dashboardState.js
index 4f3660ac01..bf1eb0f7e0 100644
--- a/superset-frontend/src/dashboard/actions/dashboardState.js
+++ b/superset-frontend/src/dashboard/actions/dashboardState.js
@@ -226,34 +226,40 @@ export function saveDashboardFinished() {
   return { type: SAVE_DASHBOARD_FINISHED };
 }
 
-export const SET_DASHBOARD_LABELS_COLORS_SYNCABLE =
-  'SET_DASHBOARD_LABELS_COLORS_SYNCABLE';
-export const SET_DASHBOARD_LABELS_COLORS_SYNCED =
-  'SET_DASHBOARD_LABELS_COLORS_SYNCED';
+export const SET_DASHBOARD_LABELS_COLORMAP_SYNCABLE =
+  'SET_DASHBOARD_LABELS_COLORMAP_SYNCABLE';
+export const SET_DASHBOARD_LABELS_COLORMAP_SYNCED =
+  'SET_DASHBOARD_LABELS_COLORMAP_SYNCED';
+export const SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCABLE =
+  'SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCABLE';
+export const SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCED =
+  'SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCED';
 
-export function setDashboardLabelsColorsSync() {
-  return { type: SET_DASHBOARD_LABELS_COLORS_SYNCABLE };
+export function setDashboardLabelsColorMapSync() {
+  return { type: SET_DASHBOARD_LABELS_COLORMAP_SYNCABLE };
 }
 
-export function setDashboardLabelsColorsSynced() {
-  return { type: SET_DASHBOARD_LABELS_COLORS_SYNCED };
+export function setDashboardLabelsColorMapSynced() {
+  return { type: SET_DASHBOARD_LABELS_COLORMAP_SYNCED };
 }
 
-export const setDashboardMetadata =
-  (updatedMetadata, persist = false) =>
-  async dispatch => {
-    dispatch(
-      dashboardInfoChanged({
-        metadata: {
-          ...updatedMetadata,
-        },
-      }),
-    );
+export function setDashboardSharedLabelsColorsSync() {
+  return { type: SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCABLE };
+}
 
-    if (persist) {
-      dispatch(setDashboardLabelsColorsSync());
-    }
-  };
+export function setDashboardSharedLabelsColorsSynced() {
+  return { type: SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCED };
+}
+
+export const setDashboardMetadata = updatedMetadata => async dispatch => {
+  dispatch(
+    dashboardInfoChanged({
+      metadata: {
+        ...updatedMetadata,
+      },
+    }),
+  );
+};
 
 export function saveDashboardRequest(data, id, saveType) {
   return (dispatch, getState) => {
@@ -727,12 +733,13 @@ const storeDashboardMetadata = async (id, metadata) =>
 export const persistDashboardLabelsColor = () => async (dispatch, getState) => {
   const {
     dashboardInfo: { id, metadata },
-    dashboardState: { labelsColorsMustSync },
+    dashboardState: { labelsColorMapMustSync, sharedLabelsColorsMustSync },
   } = getState();
 
-  if (labelsColorsMustSync) {
+  if (labelsColorMapMustSync || sharedLabelsColorsMustSync) {
     storeDashboardMetadata(id, metadata);
-    dispatch(setDashboardLabelsColorsSynced());
+    dispatch(setDashboardLabelsColorMapSynced());
+    dispatch(setDashboardSharedLabelsColorsSynced());
   }
 };
 
@@ -755,10 +762,13 @@ export const applyDashboardLabelsColorOnLoad = metadata => async dispatch => {
     const sharedLabels = metadata.shared_label_colors || [];
     if (!Array.isArray(sharedLabels) && Object.keys(sharedLabels).length > 0) {
       hasChanged = true;
-      updatedMetadata.shared_label_colors = getSharedLabels(sharedLabelsColor);
+      updatedMetadata.shared_label_colors = getSharedLabels(
+        Object.keys(sharedLabelsColor),
+      );
     }
     // backward compatibility of map_label_colors
-    const isMapLabelColorsMissing = !metadata.map_label_colors;
+    const hasMapLabelColors =
+      Object.keys(metadata.map_label_colors || {}).length > 0;
 
     let updatedScheme = metadata.color_scheme;
     const categoricalSchemes = getCategoricalSchemeRegistry();
@@ -790,7 +800,7 @@ export const applyDashboardLabelsColorOnLoad = metadata => async dispatch => {
 
     // if color scheme is invalid or map is missing, apply a fresh color map
     // if valid, apply the stored map to keep consistency across refreshes
-    const shouldGoFresh = isMapLabelColorsMissing || hasInvalidColorScheme;
+    const shouldGoFresh = !hasMapLabelColors || hasInvalidColorScheme;
     applyColors(updatedMetadata, shouldGoFresh);
 
     if (shouldGoFresh) {
@@ -802,13 +812,83 @@ export const applyDashboardLabelsColorOnLoad = metadata => async dispatch => {
     }
 
     if (hasChanged) {
-      dispatch(setDashboardMetadata(updatedMetadata, true));
+      dispatch(setDashboardMetadata(updatedMetadata));
+      dispatch(setDashboardLabelsColorMapSync());
     }
   } catch (e) {
     console.error('Failed to update dashboard color on load:', e);
   }
 };
 
+/**
+ *
+ * Ensure that the stored color map matches fresh map.
+ *
+ * @returns void
+ */
+export const ensureSyncedLabelsColorMap = () => (dispatch, getState) => {
+  const {
+    dashboardInfo: { metadata },
+    dashboardState: { labelsColorMapMustSync },
+  } = getState();
+  const updatedMetadata = { ...metadata };
+  const customLabelsColor = metadata.label_colors || {};
+  const isMapSynced = isLabelsColorMapSynced(metadata);
+  const mustSync = !isMapSynced;
+
+  if (mustSync) {
+    const freshestColorMapEntries = getLabelsColorMapEntries(customLabelsColor);
+    updatedMetadata.map_label_colors = freshestColorMapEntries;
+    dispatch(setDashboardMetadata(updatedMetadata));
+  }
+
+  if (mustSync && !labelsColorMapMustSync) {
+    // prepare to persist the just applied labels color map
+    dispatch(setDashboardLabelsColorMapSync());
+  }
+  if (!mustSync && labelsColorMapMustSync) {
+    dispatch(setDashboardLabelsColorMapSynced());
+  }
+};
+
+/**
+ *
+ * Ensure that the stored shared labels colors match current.
+ *
+ * @returns void
+ */
+export const ensureSyncedSharedLabelsColors = () => (dispatch, getState) => {
+  // using a timeout to let the rendered charts finish processing labels
+  setTimeout(() => {
+    const {
+      dashboardInfo: { metadata },
+      dashboardState: { sharedLabelsColorsMustSync },
+    } = getState();
+    const updatedMetadata = { ...metadata };
+    const sharedLabelsColors = metadata.shared_label_colors || [];
+    const freshLabelsColors = getSharedLabels(sharedLabelsColors);
+    const isSharedLabelsColorsSynced = isEqual(
+      sharedLabelsColors,
+      freshLabelsColors,
+    );
+
+    const mustSync = !isSharedLabelsColorsSynced;
+
+    if (mustSync) {
+      updatedMetadata.shared_label_colors = freshLabelsColors;
+      dispatch(setDashboardMetadata(updatedMetadata));
+    }
+
+    if (mustSync && !sharedLabelsColorsMustSync) {
+      // prepare to persist the shared labels colors
+      dispatch(setDashboardSharedLabelsColorsSync());
+    }
+    if (!mustSync && sharedLabelsColorsMustSync) {
+      dispatch(setDashboardSharedLabelsColorsSynced());
+    }
+  }, 500);
+};
+
 /**
  *
  * Updates the color map with new labels and colors as they appear.
@@ -817,7 +897,7 @@ export const applyDashboardLabelsColorOnLoad = metadata => async dispatch => {
  * @returns void
  */
 export const updateDashboardLabelsColor =
-  renderedChartIds => async (dispatch, getState) => {
+  renderedChartIds => (dispatch, getState) => {
     try {
       const {
         dashboardInfo: { metadata },
@@ -827,38 +907,44 @@ export const updateDashboardLabelsColor =
       const labelsColorMapInstance = getLabelsColorMap();
       const fullLabelsColors = metadata.map_label_colors || {};
       const sharedLabelsColors = metadata.shared_label_colors || [];
-      const customLabelsColor = metadata.label_colors || {};
+      const customLabelsColors = metadata.label_colors || {};
       const updatedMetadata = { ...metadata };
 
       // for dashboards with no color scheme, the charts should always use their individual schemes
       // this logic looks for unique labels (not shared across multiple charts) of each rendered chart
       // it applies a new color to those unique labels when the applied scheme is not up to date
-      // while leaving shared label colors intact for color consistency
+      // while leaving shared label colors and custom label colors intact for color consistency
       const shouldReset = [];
-      if (!colorScheme && renderedChartIds.length > 0) {
+      if (renderedChartIds.length > 0) {
         const sharedLabelsSet = new Set(sharedLabelsColors);
         renderedChartIds.forEach(id => {
           const chart = charts[id];
           const formData = chart.form_data || chart.latestQueryFormData;
+          // ensure charts have their original color scheme always available
+          labelsColorMapInstance.setOwnColorScheme(
+            formData.slice_id,
+            formData.color_scheme,
+          );
+
+          // if dashboard has a scheme, charts should ignore individual schemes
+          // thus following logic is inapplicable if a dashboard color scheme exists
+          if (colorScheme) return;
+
           const chartColorScheme = formData.color_scheme;
           const currentChartConfig = labelsColorMapInstance.chartsLabelsMap.get(
             formData.slice_id,
           );
           const currentChartLabels = currentChartConfig?.labels || [];
           const uniqueChartLabels = currentChartLabels.filter(
-            l => !sharedLabelsSet.has(l),
-          );
-
-          // ensure charts have their original color scheme available
-          labelsColorMapInstance.setOwnColorScheme(
-            formData.slice_id,
-            formData.color_scheme,
+            l =>
+              !sharedLabelsSet.has(l) && !customLabelsColors.hasOwnProperty(l),
           );
 
           // Map unique labels to colors
           const uniqueChartLabelsColor = new Set(
             uniqueChartLabels.map(l => fullLabelsColors[l]).filter(Boolean),
           );
+
           const expectedColorsForChartScheme = new Set(
             getColorSchemeDomain(chartColorScheme),
           );
@@ -879,28 +965,10 @@ export const updateDashboardLabelsColor =
       const shouldMerge = !shouldGoFresh;
       // re-apply the color map first to get fresh maps accordingly
       applyColors(updatedMetadata, shouldGoFresh, shouldMerge);
-
-      // using a timeout to let the rendered charts finish processing labels
-      // to work on the freshest state of the color maps
-      setTimeout(() => {
-        // new data may appear in the map (data changes)
-        // or new slices may appear while changing tabs
-        const isMapSynced = isLabelsColorMapSynced(updatedMetadata);
-        const freshLabelsColors = getSharedLabels(sharedLabelsColors);
-        const isSharedLabelsColorsSynced = isEqual(
-          metadata.shared_label_colors,
-          freshLabelsColors,
-        );
-
-        if (!isMapSynced || !isSharedLabelsColorsSynced) {
-          // prepare to persist the just applied labels color map
-          updatedMetadata.shared_label_colors = freshLabelsColors;
-          updatedMetadata.map_label_colors =
-            getLabelsColorMapEntries(customLabelsColor);
-
-          dispatch(setDashboardMetadata(updatedMetadata, true));
-        }
-      }, [0]);
+      // new data may have appeared in the map (data changes)
+      // or new slices may have appeared while changing tabs
+      dispatch(ensureSyncedLabelsColorMap());
+      dispatch(ensureSyncedSharedLabelsColors());
     } catch (e) {
       console.error('Failed to update colors for new charts and labels:', e);
     }
diff --git a/superset-frontend/src/dashboard/components/PropertiesModal/index.tsx b/superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
index b0e24f29dc..998e8540dc 100644
--- a/superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
+++ b/superset-frontend/src/dashboard/components/PropertiesModal/index.tsx
@@ -17,7 +17,7 @@
  * under the License.
  */
 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { isEqual, omit } from 'lodash';
+import { omit } from 'lodash';
 import { Input } from 'src/components/Input';
 import { FormItem } from 'src/components/Form';
 import jsonStringify from 'json-stringify-pretty-compact';
@@ -56,6 +56,7 @@ import {
   setColorScheme,
   setDashboardMetadata,
 } from 'src/dashboard/actions/dashboardState';
+import { areObjectsEqual } from 'src/reduxUtils';
 
 const StyledFormItem = styled(FormItem)`
   margin-bottom: 0;
@@ -341,9 +342,9 @@ const PropertiesModal = ({
     const updatedColorScheme = metadata?.color_scheme || colorScheme;
     const shouldGoFresh =
       updatedColorScheme !== originalDashboardMetadata.current.color_scheme;
-    const shouldResetCustomLabels = !isEqual(
-      originalDashboardMetadata.current.label_colors,
-      metadata?.label_colors,
+    const shouldResetCustomLabels = !areObjectsEqual(
+      originalDashboardMetadata.current.label_colors || {},
+      metadata?.label_colors || {},
     );
     const currentCustomLabels = Object.keys(metadata?.label_colors || {});
     const prevCustomLabels = Object.keys(
diff --git a/superset-frontend/src/dashboard/components/gridComponents/Chart.jsx b/superset-frontend/src/dashboard/components/gridComponents/Chart.jsx
index a421b5b3ca..d125ccb626 100644
--- a/superset-frontend/src/dashboard/components/gridComponents/Chart.jsx
+++ b/superset-frontend/src/dashboard/components/gridComponents/Chart.jsx
@@ -197,15 +197,19 @@ class Chart extends Component {
         }
       }
     } else if (
-      // chart should re-render if color scheme or label color was changed
+      // chart should re-render if color scheme or label colors were changed
       nextProps.formData?.color_scheme !== this.props.formData?.color_scheme ||
       !areObjectsEqual(
-        nextProps.formData?.label_colors,
-        this.props.formData?.label_colors,
+        nextProps.formData?.label_colors || {},
+        this.props.formData?.label_colors || {},
       ) ||
       !areObjectsEqual(
-        nextProps.formData?.map_label_colors,
-        this.props.formData?.map_label_colors,
+        nextProps.formData?.map_label_colors || {},
+        this.props.formData?.map_label_colors || {},
+      ) ||
+      !isEqual(
+        nextProps.formData?.shared_label_colors || [],
+        this.props.formData?.shared_label_colors || [],
       )
     ) {
       return true;
diff --git a/superset-frontend/src/dashboard/reducers/dashboardState.js b/superset-frontend/src/dashboard/reducers/dashboardState.js
index 42efec0b0d..771a563016 100644
--- a/superset-frontend/src/dashboard/reducers/dashboardState.js
+++ b/superset-frontend/src/dashboard/reducers/dashboardState.js
@@ -46,8 +46,10 @@ import {
   SET_OVERRIDE_CONFIRM,
   SAVE_DASHBOARD_STARTED,
   SAVE_DASHBOARD_FINISHED,
-  SET_DASHBOARD_LABELS_COLORS_SYNCABLE,
-  SET_DASHBOARD_LABELS_COLORS_SYNCED,
+  SET_DASHBOARD_LABELS_COLORMAP_SYNCABLE,
+  SET_DASHBOARD_LABELS_COLORMAP_SYNCED,
+  SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCABLE,
+  SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCED,
 } from '../actions/dashboardState';
 import { HYDRATE_DASHBOARD } from '../actions/hydrate';
 
@@ -103,16 +105,28 @@ export default function dashboardStateReducer(state = {}, action) {
         updatedColorScheme: true,
       };
     },
-    [SET_DASHBOARD_LABELS_COLORS_SYNCABLE]() {
+    [SET_DASHBOARD_LABELS_COLORMAP_SYNCABLE]() {
       return {
         ...state,
-        labelsColorsMustSync: true,
+        labelsColorMapMustSync: true,
       };
     },
-    [SET_DASHBOARD_LABELS_COLORS_SYNCED]() {
+    [SET_DASHBOARD_LABELS_COLORMAP_SYNCED]() {
       return {
         ...state,
-        labelsColorsMustSync: false,
+        labelsColorMapMustSync: false,
+      };
+    },
+    [SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCABLE]() {
+      return {
+        ...state,
+        sharedLabelsColorsMustSync: true,
+      };
+    },
+    [SET_DASHBOARD_SHARED_LABELS_COLORS_SYNCED]() {
+      return {
+        ...state,
+        sharedLabelsColorsMustSync: false,
       };
     },
     [TOGGLE_EXPAND_SLICE]() {
diff --git a/superset-frontend/src/explore/components/ExploreChartHeader/index.jsx b/superset-frontend/src/explore/components/ExploreChartHeader/index.jsx
index f3ac418bac..c7df2af40f 100644
--- a/superset-frontend/src/explore/components/ExploreChartHeader/index.jsx
+++ b/superset-frontend/src/explore/components/ExploreChartHeader/index.jsx
@@ -108,8 +108,8 @@ export const ExploreChartHeader = ({
 
         // setting the chart to use the dashboard custom label colors if any
         const dashboardMetadata = JSON.parse(result.json_metadata);
-        // if the dashboard does not have a color scheme, only apply shared colors
-        applyColors(dashboardMetadata, false, false, !dashboardColorScheme);
+        // ensure consistency with the dashboard
+        applyColors(dashboardMetadata);
       } catch (error) {
         logging.info(t('Unable to retrieve dashboard colors'));
       }
diff --git a/superset-frontend/src/explore/components/controls/ColorSchemeControl/index.tsx b/superset-frontend/src/explore/components/controls/ColorSchemeControl/index.tsx
index f6b80ed68b..fd9dc85f0f 100644
--- a/superset-frontend/src/explore/components/controls/ColorSchemeControl/index.tsx
+++ b/superset-frontend/src/explore/components/controls/ColorSchemeControl/index.tsx
@@ -27,6 +27,7 @@ import {
   t,
   useTheme,
   getLabelsColorMap,
+  CategoricalColorNamespace,
 } from '@superset-ui/core';
 import AntdSelect from 'antd/lib/select';
 import { isFunction, sortBy } from 'lodash';
@@ -36,6 +37,7 @@ import Icons from 'src/components/Icons';
 import { SelectOptionsType } from 'src/components/Select/types';
 import { StyledSelect } from 'src/components/Select/styles';
 import { handleFilterOptionHelper } from 'src/components/Select/utils';
+import { getColorNamespace } from 'src/utils/colorScheme';
 import ColorSchemeLabel from './ColorSchemeLabel';
 
 const { Option, OptGroup } = AntdSelect;
@@ -50,7 +52,9 @@ export interface ColorSchemeControlProps {
   hasCustomLabelsColor: boolean;
   hasDashboardColorScheme?: boolean;
   hasSharedLabelsColor?: boolean;
-  sharedLabelsColors: string[];
+  sharedLabelsColors?: string[];
+  mapLabelsColors?: Record<string, any>;
+  colorNamespace?: string;
   chartId?: number;
   dashboardId?: number;
   label: string;
@@ -125,8 +129,10 @@ const Label = ({
 const ColorSchemeControl = ({
   hasCustomLabelsColor = false,
   hasDashboardColorScheme = false,
+  mapLabelsColors = {},
   sharedLabelsColors = [],
   dashboardId,
+  colorNamespace,
   chartId,
   label = t('Color scheme'),
   onChange = () => {},
@@ -265,7 +271,22 @@ const ColorSchemeControl = ({
   // We can't pass on change directly because it receives a second
   // parameter and it would be interpreted as the error parameter
   const handleOnChange = (value: string) => {
-    if (chartId) colorMapInstance.setOwnColorScheme(chartId, value);
+    if (chartId) {
+      colorMapInstance.setOwnColorScheme(chartId, value);
+      if (dashboardId) {
+        const colorNameSpace = getColorNamespace(colorNamespace);
+        const categoricalNamespace =
+          CategoricalColorNamespace.getNamespace(colorNameSpace);
+
+        const sharedLabelsSet = new Set(sharedLabelsColors);
+        // reset colors except shared and custom labels to keep dashboard consistency
+        const resettableLabels = Object.keys(mapLabelsColors).filter(
+          l => !sharedLabelsSet.has(l),
+        );
+        categoricalNamespace.resetColorsForLabels(resettableLabels);
+      }
+    }
+
     onChange(value);
   };
 
diff --git a/superset-frontend/src/utils/colorScheme.ts b/superset-frontend/src/utils/colorScheme.ts
index 00e4a7c859..420d1fdf4d 100644
--- a/superset-frontend/src/utils/colorScheme.ts
+++ b/superset-frontend/src/utils/colorScheme.ts
@@ -166,7 +166,6 @@ export const applyColors = (
   // Catch new labels in the color map as they appear
   merge = false,
   // Apply only label colors that are shared across multiple charts.
-  // Used in Explore from a dashboard context without color scheme.
   shared = false,
 ) => {
   const colorNameSpace = getColorNamespace(metadata?.color_namespace);
@@ -192,7 +191,7 @@ export const applyColors = (
     // should only reset colors for charts that have changed scheme
     // while keeping colors of existing shared label colors intact
     // this is used also to reset custom label colors when added or removed
-    categoricalNamespace.resetIndividualColors(fresh);
+    categoricalNamespace.resetColorsForLabels(fresh);
   }
 
   if (fresh || merge) {
diff --git a/superset/examples/birth_names.py b/superset/examples/birth_names.py
index 81e31e7416..b69cf0f4a4 100644
--- a/superset/examples/birth_names.py
+++ b/superset/examples/birth_names.py
@@ -21,7 +21,7 @@ import pandas as pd
 from sqlalchemy import DateTime, inspect, String
 from sqlalchemy.sql import column
 
-from superset import app, db
+from superset import app, db, security_manager
 from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
 from superset.models.core import Database
 from superset.models.dashboard import Dashboard
@@ -152,6 +152,7 @@ def _add_table_metrics(datasource: SqlaTable) -> None:
 
 
 def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
+    owner = security_manager.get_user_by_id(1)
     metrics = [
         {
             "expressionType": "SIMPLE",
@@ -193,7 +194,6 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
     slice_kwargs = {
         "datasource_id": tbl.id,
         "datasource_type": DatasourceType.TABLE,
-        "owners": [],
     }
 
     print("Creating some slices")
@@ -210,6 +210,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 compare_suffix="over 5Y",
                 metric=metric,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -218,6 +219,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
             params=get_slice_json(
                 defaults, viz_type="pie", groupby=["gender"], metric=metric
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -232,6 +234,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 show_legend=True,
                 metrics=metrics,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -268,6 +271,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 ],
                 groupby=["state"],
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -281,6 +285,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 timeseries_limit_metric=metric,
                 metrics=[metric],
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -297,6 +302,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 adhoc_filters=[gen_filter("gender", "girl")],
                 metric=metric,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -310,6 +316,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 timeseries_limit_metric=metric,
                 metrics=[metric],
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -326,6 +333,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 adhoc_filters=[gen_filter("gender", "boy")],
                 metric=metric,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -343,6 +351,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 x_axis_forma="smart_date",
                 metrics=metrics,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -360,6 +369,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 x_axis_forma="smart_date",
                 metrics=metrics,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -381,6 +391,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                     }
                 ],
             ),
+            owners=[],
         ),
     ]
     misc_slices = [
@@ -405,12 +416,14 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 yAxisIndex=0,
                 yAxisIndexB=1,
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
             slice_name="Num Births Trend",
             viz_type="line",
             params=get_slice_json(defaults, viz_type="line", metrics=metrics),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -433,6 +446,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                     }
                 ],
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -452,6 +466,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 viz_type="big_number_total",
                 granularity_sqla="ds",
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -484,6 +499,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 },
                 limit="10",
             ),
+            owners=[owner] if owner else [],
         ),
         Slice(
             **slice_kwargs,
@@ -504,6 +520,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                     "label": "SUM(num_california)",
                 },
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -517,6 +534,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 adhoc_filters=[gen_filter("gender", "girl")],
                 subheader="total female participants",
             ),
+            owners=[],
         ),
         Slice(
             **slice_kwargs,
@@ -529,6 +547,7 @@ def create_slices(tbl: SqlaTable) -> tuple[list[Slice], list[Slice]]:
                 groupbyColumns=["state"],
                 metrics=metrics,
             ),
+            owners=[],
         ),
     ]
     for slc in slices: