-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
withBackground.ts
59 lines (48 loc) · 1.71 KB
/
withBackground.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { StoryFn as StoryFunction, StoryContext, useMemo, useEffect } from '@storybook/addons';
import { PARAM_KEY as BACKGROUNDS_PARAM_KEY } from '../constants';
import { clearStyles, addBackgroundStyle, getBackgroundColorByName } from '../helpers';
export const withBackground = (StoryFn: StoryFunction, context: StoryContext) => {
const { globals, parameters } = context;
const globalsBackgroundColor = globals[BACKGROUNDS_PARAM_KEY]?.value;
const backgroundsConfig = parameters[BACKGROUNDS_PARAM_KEY];
const selectedBackgroundColor = useMemo(() => {
if (backgroundsConfig.disable) {
return 'transparent';
}
return getBackgroundColorByName(
globalsBackgroundColor,
backgroundsConfig.values,
backgroundsConfig.default
);
}, [backgroundsConfig, globalsBackgroundColor]);
const isActive = useMemo(
() => selectedBackgroundColor && selectedBackgroundColor !== 'transparent',
[selectedBackgroundColor]
);
const selector =
context.viewMode === 'docs' ? `#anchor--${context.id} .docs-story` : '.sb-show-main';
const backgroundStyles = useMemo(() => {
return `
${selector} {
background: ${selectedBackgroundColor} !important;
transition: background-color 0.3s;
}
`;
}, [selectedBackgroundColor, selector]);
useEffect(() => {
const selectorId =
context.viewMode === 'docs'
? `addon-backgrounds-docs-${context.id}`
: `addon-backgrounds-color`;
if (!isActive) {
clearStyles(selectorId);
return;
}
addBackgroundStyle(
selectorId,
backgroundStyles,
context.viewMode === 'docs' ? context.id : null
);
}, [isActive, backgroundStyles, context]);
return StoryFn();
};