examples icon indicating copy to clipboard operation
examples copied to clipboard

Color Mode Switcher Shows wrong icon in `auto` mode. Root cause contributes to occasional flickering.

Open nenadvicentic opened this issue 1 year ago • 0 comments

Currently, color mode switcher displays Light or Dark icon, when no color mode has been stored in the localStorage.

The culprit is following code: https://github.com/twbs/examples/blob/6786420f365d35b5d79095865233a619e0235ec4/color-modes/js/color-modes.js#L13-L20:

The function getPreferredTheme converts non-stored item (null) to light or dark value on the output, Thus, wrong active color mode button is matched.

Further, handling of actual theme set in IU is splitted between the above function and following function: https://github.com/twbs/examples/blob/6786420f365d35b5d79095865233a619e0235ec4/color-modes/js/color-modes.js#L22-L28

The function setTheme has special case for input parameter auto. Therefore cases where there is no value stored in localStorage and when value auto has been stored are handled in a slightly different way.

Further, value auto makes sense only for the color-swicher component, as a part of element ID in [data-bs-theme-value="auto"]. In CSS only values light and dark are valid.

Further yet, the event handler: https://github.com/twbs/examples/blob/6786420f365d35b5d79095865233a619e0235ec4/color-modes/js/color-modes.js#L60-L65

Currently works correctly, only if there are only light and dark color modes stored in localStorage, and there are no custom color modes added by user.

Fix could be following:

  1. Threat localStorage.getItem('theme') === null and localStorage.getItem('theme') === 'auto' in the same manner. Or even better, do not store any value in auto mode in localStorage.
  2. Use auto suffix only for color-switcher UI handling, as a fallback value for localStorage.getItem('theme') === null.

nenadvicentic avatar Jan 02 '25 14:01 nenadvicentic