-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathBackgroundProvider.js
More file actions
257 lines (230 loc) · 8.21 KB
/
Copy pathBackgroundProvider.js
File metadata and controls
257 lines (230 loc) · 8.21 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { Fragment, h } from 'preact';
import styles from './BackgroundReceiver.module.css';
import { values } from '../customizer/values.js';
import { useContext, useEffect, useState } from 'preact/hooks';
import { CustomizerContext } from '../customizer/CustomizerProvider.js';
import { detectThemeFromHex } from '../customizer/utils.js';
import { useSignalEffect } from '@preact/signals';
import { memo } from 'preact/compat';
/**
* @import { BackgroundVariant, BrowserTheme, ThemeVariant } from "../../types/new-tab"
*/
/**
* @param {BackgroundVariant} background
* @param {BrowserTheme} browserTheme
* @param {'light' | 'dark'} system
* @return {{bg: 'light' | 'dark', browser: 'light' | 'dark'}}
*/
export function inferSchemeFrom(background, browserTheme, system) {
const browser = themeFromBrowser(browserTheme, system);
switch (background.kind) {
case 'default':
return { bg: browser, browser };
case 'color': {
const color = values.colors[background.value];
return { bg: color.colorScheme, browser };
}
case 'gradient': {
const gradient = values.gradients[background.value];
return { bg: gradient.colorScheme, browser };
}
case 'userImage':
return { bg: background.value.colorScheme, browser };
case 'hex':
return { bg: detectThemeFromHex(background.value), browser };
}
}
/**
* @param {BrowserTheme} browserTheme
* @param {'light' | 'dark'} system
* @return {'light' | 'dark'}
*/
export function themeFromBrowser(browserTheme, system) {
if (browserTheme === 'system') {
return system;
}
return browserTheme;
}
/**
* @param {object} props
* @param {import("@preact/signals").Signal<'light' | 'dark'>} props.browser
* @param {import("@preact/signals").Signal<ThemeVariant>} props.variant
*/
export function BackgroundConsumer({ browser, variant }) {
const { data } = useContext(CustomizerContext);
const background = data.value.background;
useSignalEffect(() => {
const background = data.value.background;
// reflect some values onto the <body> tag
document.body.dataset.backgroundKind = background.kind;
let nextBodyBackground = '';
if (background.kind === 'gradient') {
const gradient = values.gradients[background.value];
nextBodyBackground = gradient.fallback;
}
if (background.kind === 'color') {
const color = values.colors[background.value];
nextBodyBackground = color.hex;
}
if (background.kind === 'hex') {
nextBodyBackground = background.value;
}
if (background.kind === 'userImage') {
const isDark = background.value.colorScheme === 'dark';
nextBodyBackground = isDark ? 'var(--default-dark-background-color)' : 'var(--default-light-background-color)';
}
if (background.kind === 'default') {
nextBodyBackground =
browser.value === 'dark' ? 'var(--default-dark-background-color)' : 'var(--default-light-background-color)';
}
document.body.style.setProperty('background-color', nextBodyBackground);
// let animations occur, after properties above have been flushed to the DOM
if (!document.body.dataset.animateBackground) {
requestAnimationFrame(() => {
document.body.dataset.animateBackground = 'true';
});
}
});
// Sync theme attributes to <body>
useSignalEffect(() => {
document.body.dataset.theme = browser.value;
});
useSignalEffect(() => {
document.body.dataset.themeVariant = variant.value;
});
switch (background.kind) {
case 'color':
case 'default':
case 'hex': {
return null;
}
case 'userImage': {
const img = background.value;
return <ImageCrossFade src={img.src} />;
}
case 'gradient': {
const gradient = values.gradients[background.value];
return (
<Fragment>
<ImageCrossFade src={gradient.path} />
<div
className={styles.root}
style={{
backgroundImage: `url(gradients/grain.png)`,
backgroundRepeat: 'repeat',
opacity: 0.5,
mixBlendMode: 'soft-light',
}}
/>
</Fragment>
);
}
default: {
console.warn('Unreachable!');
return null;
}
}
}
/**
* @typedef {'idle'
* | 'loadingFirst'
* | 'loading'
* | 'fading'
* | 'settled'
* } ImgState
*/
/**
* @type {Record<ImgState, ImgState>}
*/
const states = {
idle: 'idle',
loadingFirst: 'loadingFirst',
loading: 'loading',
fading: 'fading',
settled: 'settled',
};
/**
* @param {object} props
* @param {string} props.src
*/
function ImageCrossFade_({ src }) {
const [state, setState] = useState({
/** @type {ImgState} */
value: states.idle,
current: src,
next: src,
});
useEffect(() => {
/** @type {HTMLImageElement|undefined} */
let img = new Image();
let cancelled = false;
// Mark the component as being in a 'loading' state, without
// explicit changes to any DOM
setState((prev) => {
// prettier-ignore
const nextState = prev.value === states.idle
? states.loadingFirst
: states.loading;
return { ...prev, value: nextState };
});
/** @type {(()=>void)|undefined} */
let handler = () => {
if (cancelled) return;
setState((prev) => {
// when coming from a 'loading' states, we can fade
if (prev.value === states.loading) {
return { ...prev, value: states.fading, next: src };
}
return prev;
});
};
// trigger the load in memory, not on screen
img.addEventListener('load', handler);
img.src = src;
return () => {
cancelled = true;
if (img && handler) {
img.removeEventListener('load', handler);
img = undefined;
handler = undefined;
}
};
}, [src]);
switch (state.value) {
case states.settled:
case states.loadingFirst:
return <img class={styles.root} data-state={state.value} src={state.current} alt="" />;
case states.loading:
case states.fading:
return (
<Fragment>
<img class={styles.root} data-state={state.value} src={state.current} alt="" />
<img
class={styles.root}
data-state={state.value}
src={state.next}
onLoad={(e) => {
const elem = /** @type {HTMLImageElement} */ (e.target);
// HACK: This is what I needed to force, to get 100% predictability. 🤷
elem.style.opacity = '0';
const anim = elem.animate([{ opacity: '0' }, { opacity: '1' }], {
duration: 250,
iterations: 1,
fill: 'both',
});
// when the fade completes, we want to reset the stable `src`.
// This allows the image underneath to be updated but also allows us to un-mount the fader on top.
anim.onfinish = () => {
setState((prev) => {
return { ...prev, value: states.settled, current: prev.next, next: prev.next };
});
};
}}
/>
</Fragment>
);
default:
return null;
}
}
const ImageCrossFade = memo(ImageCrossFade_);