From a9c18b4359c5aa242cadb59d0b5ffa301f71f53a Mon Sep 17 00:00:00 2001 From: Nick Taylor Date: Tue, 23 Jun 2020 09:05:24 -0400 Subject: [PATCH] Theme switcher in Storybook persists theme between stories and sessions now (#8855) --- app/javascript/.storybook/preview.js | 61 +++++++++++++++++----------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/app/javascript/.storybook/preview.js b/app/javascript/.storybook/preview.js index 74d9380fc..d9f157c70 100644 --- a/app/javascript/.storybook/preview.js +++ b/app/javascript/.storybook/preview.js @@ -8,7 +8,7 @@ import '../../assets/javascripts/lib/xss'; import '../../assets/javascripts/utilities/timeAgo'; import './storybook.scss'; -function addStylesheet(theme) { +function addStylesheet(theme = '') { if (theme === '') { return; // default theme } @@ -18,37 +18,52 @@ function addStylesheet(theme) { link.type = 'text/css'; link.rel = 'stylesheet'; - link.href = `themes/${event.target.value}.css`; + link.href = `themes/${theme}.css`; link.id = 'dev-theme'; head.appendChild(link); } -const themeSwitcher = (event) => { - const currentTheme = document.getElementById('dev-theme'); +function themeSwitcher(event) { + const themeNode = document.getElementById('dev-theme'); + const theme = event.target.value; - if (currentTheme) { - currentTheme.parentElement.removeChild(currentTheme); + if (themeNode) { + themeNode.parentElement.removeChild(themeNode); } - addStylesheet(event.target.value); -}; + localStorage.setItem('storybook-crayons-theme', theme); -const themeSwitcherDecorator = (storyFn) => ( -
- - {storyFn()} -
-); + addStylesheet(theme); +} + +const THEMES = Object.freeze(['default', 'night', 'minimal', 'pink', 'hacker']); + +const themeSwitcherDecorator = (storyFn) => { + const lastThemeUsed = localStorage.getItem('storybook-crayons-theme') || ''; + + addStylesheet(lastThemeUsed); + + return ( +
+ + {storyFn()} +
+ ); +}; addDecorator(themeSwitcherDecorator); addDecorator(withA11y);