From 8dfa466f0c42e374b5cb45648736b76caf86f72e Mon Sep 17 00:00:00 2001 From: Lee Chase Date: Mon, 10 Jun 2024 16:25:48 +0100 Subject: [PATCH] feat: Show light and dark theme applied using system preferences (#4022) * Show light and dark theme applied using system preferences Modern browsers and systems allow the user to configure a preference for light and dark modes. This should be obeyed where the user has not configured a theme for the current application. * chore: format --------- Co-authored-by: Alison Joseph --- src/pages/elements/themes/code.mdx | 89 ++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/src/pages/elements/themes/code.mdx b/src/pages/elements/themes/code.mdx index 146e9127577..97f3af3d721 100644 --- a/src/pages/elements/themes/code.mdx +++ b/src/pages/elements/themes/code.mdx @@ -101,6 +101,95 @@ Themes can also be extended with your own custom tokens: ); ``` +#### System preferences + +Modern browsers and systems have adopted the idea of dark and light themes +applied at a system level. Where no user preference has been specified their +system level theme should be matched. + +For example applying `g10` or `g100` automaticcally based on system preferences. + +```scss +@use '@carbon/themes/scss/themes' as *; +@use '@carbon/themes'; + +/* system preference theme by default */ +:root { + @include themes.theme($g10); +} + +@media (prefers-color-scheme: dark) { + :root { + @include themes.theme($g100); + } +} + +/* user has configured a theme preference for the current page/app */ +[data-carbon-theme='white'] { + @include themes.theme($white); +} + +[data-carbon-theme='g10'] { + @include themes.theme($g10); +} + +[data-carbon-theme='g90'] { + @include themes.theme($g90); +} + +[data-carbon-theme='g100'] { + @include themes.theme($g100); +} +``` + +Some designs include a sections in the opposite theme. + +```scss +@mixin theme-scheme($default, $compliment) { + /* apply default theme */ + @include theme($default, true); + + /* apply to the compliment theme */ + [data-carbon-theme--compliment] { + @include theme($compliment, true); + } + + /* apply the default theme */ + /* to switch back from within a compliment */ + [data-carbon-theme] { + @include theme($default, true); + } +} + +/* system preference theme by default */ +:root { + @include theme-scheme(themes.$g10, themes.$g100); +} + +@media (prefers-color-scheme: dark) { + :root { + @include theme-scheme(themes.$g100, themes.$g10); + } +} + +/* user has configured a theme preference for the current page/app */ +[data-carbon-theme='white'] { + @include theme-scheme(themes.$white, themes.$g90); +} + +[data-carbon-theme='g10'] { + @include theme-scheme(themes.$g10, themes.$g100); +} + +[data-carbon-theme='g90'] { + @include theme-scheme(themes.$g90, themes.$white); +} + +[data-carbon-theme='g100'] { + @include theme-scheme(themes.$g100, themes.$g10); +} +``` + ### JavaScript If you're looking to use these themes in JavaScript, we export a variety of