-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
utils.test.ts
639 lines (554 loc) · 19.4 KB
/
utils.test.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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { CustomThemeConfig } from "@streamlit/lib/src/proto"
import { LocalStore } from "@streamlit/lib/src/util/storageUtils"
import {
baseTheme,
createAutoTheme,
darkTheme,
lightTheme,
} from "@streamlit/lib/src/theme/index"
import { ThemeConfig } from "@streamlit/lib/src/theme/types"
import { fonts } from "@streamlit/lib/src/theme/primitives/typography"
import {
AUTO_THEME_NAME,
bgColorToBaseString,
CUSTOM_THEME_NAME,
computeSpacingStyle,
createEmotionTheme,
createTheme,
fontEnumToString,
fontToEnum,
getDefaultTheme,
getSystemTheme,
isColor,
isPresetTheme,
toThemeInput,
getCachedTheme,
removeCachedTheme,
setCachedTheme,
hasLightBackgroundColor,
} from "./utils"
const matchMediaFillers = {
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}
const windowLocationSearch = (search: string): any => ({
location: {
search,
},
})
const windowMatchMedia = (theme: "light" | "dark"): any => ({
matchMedia: (query: any) => ({
matches: query === `(prefers-color-scheme: ${theme})`,
media: query,
...matchMediaFillers,
}),
})
const mockWindow = (...overrides: object[]): jest.SpyInstance => {
const localStorage = window.localStorage
const windowSpy = jest.spyOn(window, "window", "get")
windowSpy.mockImplementation(() => ({
localStorage,
...windowLocationSearch(""),
...windowMatchMedia("light"),
...Object.assign({}, ...overrides),
}))
return windowSpy
}
describe("Styling utils", () => {
describe("computeSpacingStyle", () => {
test("pulls correct theme values", async () => {
expect(computeSpacingStyle("sm md lg none", lightTheme.emotion)).toEqual(
"0.5rem 0.75rem 1rem 0"
)
expect(computeSpacingStyle("xs 0 px lg", lightTheme.emotion)).toEqual(
"0.375rem 0 1px 1rem"
)
})
})
})
describe("isPresetTheme", () => {
it("returns true for the light, dark, and auto themes", () => {
const presetThemes = [lightTheme, darkTheme, createAutoTheme()]
presetThemes.forEach((themeConfig: ThemeConfig) => {
expect(isPresetTheme(themeConfig)).toBe(true)
})
})
it("returns false for custom themes", () => {
const customTheme = createTheme(
CUSTOM_THEME_NAME,
new CustomThemeConfig({
primaryColor: "red",
secondaryBackgroundColor: "blue",
font: CustomThemeConfig.FontFamily.SERIF,
})
)
expect(isPresetTheme(customTheme)).toBe(false)
})
})
describe("Cached theme helpers", () => {
// NOTE: localStorage is weird, and calling .spyOn(window.localStorage, "setItem")
// doesn't work. Accessing .__proto__ here isn't too bad of a crime since
// it's test code.
const breakLocalStorage = (): void => {
jest
// eslint-disable-next-line no-proto
.spyOn(window.localStorage.__proto__, "setItem")
.mockImplementation(() => {
throw new Error("boom")
})
}
afterEach(() => {
jest.restoreAllMocks()
window.localStorage.clear()
})
describe("getCachedTheme", () => {
it("returns null if localStorage is not available", () => {
breakLocalStorage()
// eslint-disable-next-line no-proto
const getItemSpy = jest.spyOn(window.localStorage.__proto__, "getItem")
expect(getCachedTheme()).toBe(null)
expect(getItemSpy).not.toHaveBeenCalled()
})
it("returns null if no theme is set in localStorage", () => {
expect(getCachedTheme()).toBe(null)
})
it("does not find cached themes with older versions, so returns null", () => {
// Save a cachedTheme in LocalStorage with the key of a previous version.
window.localStorage.setItem(
LocalStore.CACHED_THEME_BASE_KEY,
JSON.stringify({ name: darkTheme.name })
)
expect(getCachedTheme()).toBe(null)
})
it("returns preset cached theme if localStorage is available and one is set", () => {
window.localStorage.setItem(
LocalStore.ACTIVE_THEME,
JSON.stringify({ name: darkTheme.name })
)
expect(getCachedTheme()).toEqual(darkTheme)
})
it("returns a custom cached theme if localStorage is available and one is set", () => {
const themeInput: Partial<CustomThemeConfig> = {
primaryColor: "red",
backgroundColor: "orange",
secondaryBackgroundColor: "yellow",
textColor: "green",
font: CustomThemeConfig.FontFamily.SERIF,
}
const customTheme = createTheme(CUSTOM_THEME_NAME, themeInput)
window.localStorage.setItem(
LocalStore.ACTIVE_THEME,
JSON.stringify({ name: CUSTOM_THEME_NAME, themeInput })
)
expect(getCachedTheme()).toEqual(customTheme)
})
})
describe("removeCachedTheme", () => {
it("does nothing if localStorage is not available", () => {
breakLocalStorage()
const removeItemSpy = jest.spyOn(
// eslint-disable-next-line no-proto
window.localStorage.__proto__,
"removeItem"
)
removeCachedTheme()
expect(removeItemSpy).not.toHaveBeenCalled()
})
it("removes theme if localStorage", () => {
const removeItemSpy = jest.spyOn(
// eslint-disable-next-line no-proto
window.localStorage.__proto__,
"removeItem"
)
removeCachedTheme()
expect(removeItemSpy).toHaveBeenCalled()
})
})
describe("setCachedTheme", () => {
const themeInput: Partial<CustomThemeConfig> = {
primaryColor: "red",
backgroundColor: "orange",
secondaryBackgroundColor: "yellow",
textColor: "green",
font: CustomThemeConfig.FontFamily.SERIF,
}
const customTheme = createTheme(CUSTOM_THEME_NAME, themeInput)
it("does nothing if localStorage is not available", () => {
breakLocalStorage()
// eslint-disable-next-line no-proto
const setItemSpy = jest.spyOn(window.localStorage.__proto__, "setItem")
setCachedTheme(darkTheme)
// This looks a bit funny and is the way it is because the way we know
// that localStorage is broken is that setItem throws an error at us.
expect(setItemSpy).toHaveBeenCalledTimes(1)
expect(setItemSpy).toHaveBeenCalledWith("testData", "testData")
})
it("sets a preset theme with just its name if localStorage is available", () => {
setCachedTheme(darkTheme)
const cachedTheme = JSON.parse(
window.localStorage.getItem(LocalStore.ACTIVE_THEME) as string
)
expect(cachedTheme).toEqual({ name: darkTheme.name })
})
it("deletes cached themes with older versions", () => {
window.localStorage.setItem("stActiveTheme", "I should get deleted :|")
window.localStorage.setItem(
LocalStore.CACHED_THEME_BASE_KEY,
"I should get deleted too :|"
)
setCachedTheme(customTheme)
expect(window.localStorage.getItem("stActiveTheme")).toBe(null)
expect(
window.localStorage.getItem(LocalStore.CACHED_THEME_BASE_KEY)
).toBe(null)
})
it("sets a custom theme with its name and themeInput if localStorage is available", () => {
setCachedTheme(customTheme)
const cachedTheme = JSON.parse(
window.localStorage.getItem(LocalStore.ACTIVE_THEME) as string
)
expect(cachedTheme).toEqual({
name: customTheme.name,
themeInput,
})
})
})
})
describe("createTheme", () => {
it("returns a theme", () => {
const customThemeConfig = new CustomThemeConfig({
primaryColor: "red",
secondaryBackgroundColor: "blue",
font: CustomThemeConfig.FontFamily.SERIF,
})
const customTheme = createTheme(CUSTOM_THEME_NAME, customThemeConfig)
expect(customTheme.name).toBe(CUSTOM_THEME_NAME)
expect(customTheme.emotion.colors.primary).toBe("red")
expect(customTheme.emotion.colors.secondaryBg).toBe("blue")
expect(customTheme.emotion.genericFonts.bodyFont).toBe(
lightTheme.emotion.fonts.serif
)
// If it is not provided, use the default
expect(customTheme.emotion.colors.bgColor).toBe(
lightTheme.emotion.colors.bgColor
)
})
it("returns a theme based on a different theme", () => {
const customThemeConfig = new CustomThemeConfig({
primaryColor: "red",
secondaryBackgroundColor: "blue",
font: CustomThemeConfig.FontFamily.SERIF,
})
const customTheme = createTheme(
CUSTOM_THEME_NAME,
customThemeConfig,
darkTheme,
// inSidebar
true
)
expect(customTheme.name).toBe(CUSTOM_THEME_NAME)
expect(customTheme.emotion.colors.primary).toBe("red")
expect(customTheme.emotion.colors.secondaryBg).toBe("blue")
expect(customTheme.emotion.genericFonts.bodyFont).toBe(
darkTheme.emotion.fonts.serif
)
// If it is not provided, use the default
expect(customTheme.emotion.colors.bgColor).toBe(
darkTheme.emotion.colors.bgColor
)
expect(customTheme.emotion.inSidebar).toBe(true)
expect(darkTheme.emotion.inSidebar).toBe(false)
})
it("handles hex values without #", () => {
const customThemeConfig = new CustomThemeConfig({
primaryColor: "eee",
secondaryBackgroundColor: "fc9231",
font: CustomThemeConfig.FontFamily.SERIF,
})
const customTheme = createTheme(
CUSTOM_THEME_NAME,
customThemeConfig,
darkTheme
)
expect(customTheme.name).toBe(CUSTOM_THEME_NAME)
expect(customTheme.emotion.colors.primary).toBe("#eee")
expect(customTheme.emotion.colors.secondaryBg).toBe("#fc9231")
expect(customTheme.emotion.genericFonts.bodyFont).toBe(
customTheme.emotion.fonts.serif
)
// If it is not provided, use the default
expect(customTheme.emotion.colors.bgColor).toBe(
darkTheme.emotion.colors.bgColor
)
})
it("sets unspecified theme options using the given BaseTheme", () => {
const customTheme = createTheme(
CUSTOM_THEME_NAME,
new CustomThemeConfig({
base: CustomThemeConfig.BaseTheme.DARK,
primaryColor: "blue",
})
)
expect(customTheme.emotion.colors.bgColor).toBe(
darkTheme.emotion.colors.bgColor
)
expect(customTheme.emotion.colors.primary).toBe("blue")
// Auxiliary colors should be those of the Dark theme.
expect(customTheme.emotion.colors.warning).toBe(
darkTheme.emotion.colors.warning
)
})
it("sets auxiliary colors based on backgroundColor over the BaseTheme", () => {
const customTheme = createTheme(
CUSTOM_THEME_NAME,
new CustomThemeConfig({
backgroundColor: "black",
base: CustomThemeConfig.BaseTheme.LIGHT,
})
)
expect(customTheme.emotion.colors.bgColor).toBe("black")
// Auxiliary colors should be picked to be ones that work well with the
// black background even though the user set the base theme to light.
expect(customTheme.emotion.colors.warning).toBe(
darkTheme.emotion.colors.warning
)
// Theme options should be inherited from the light theme as defined by the
// user.
expect(customTheme.emotion.colors.secondaryBg).toBe(
lightTheme.emotion.colors.secondaryBg
)
})
})
describe("getSystemTheme", () => {
let windowSpy: jest.SpyInstance
afterEach(() => {
windowSpy.mockRestore()
window.localStorage.clear()
})
it("returns lightTheme when matchMedia does *not* match dark", () => {
windowSpy = mockWindow()
expect(getSystemTheme().name).toBe("Light")
})
it("returns darkTheme when matchMedia does match dark", () => {
windowSpy = mockWindow(windowMatchMedia("dark"))
expect(getSystemTheme().name).toBe("Dark")
})
})
describe("getDefaultTheme", () => {
let windowSpy: jest.SpyInstance
afterEach(() => {
windowSpy.mockRestore()
window.localStorage.clear()
})
it("sets default to the auto theme when there is no cached theme", () => {
windowSpy = mockWindow()
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe(AUTO_THEME_NAME)
// Also verify that the theme is our lightTheme.
expect(defaultTheme.emotion.colors).toEqual(lightTheme.emotion.colors)
})
it("sets the auto theme correctly when the OS preference is dark", () => {
mockWindow(windowSpy, windowMatchMedia("dark"))
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe(AUTO_THEME_NAME)
expect(defaultTheme.emotion.colors).toEqual(darkTheme.emotion.colors)
})
it("sets the default to the user preference when one is set", () => {
windowSpy = mockWindow()
setCachedTheme(darkTheme)
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe("Dark")
expect(defaultTheme.emotion.colors).toEqual(darkTheme.emotion.colors)
})
it("sets default to the light theme when an embed query parameter is set", () => {
windowSpy = mockWindow(
windowLocationSearch("?embed=true&embed_options=light_theme")
)
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe("Light")
// Also verify that the theme is our lightTheme.
expect(defaultTheme.emotion.colors).toEqual(lightTheme.emotion.colors)
})
it("sets default to the dark theme when an embed query parameter is set", () => {
windowSpy = mockWindow(
windowLocationSearch("?embed=true&embed_options=dark_theme")
)
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe("Dark")
// Also verify that the theme is our darkTheme.
expect(defaultTheme.emotion.colors).toEqual(darkTheme.emotion.colors)
})
it("respects embed query parameter is set over system theme", () => {
windowSpy = mockWindow(
windowMatchMedia("dark"),
windowLocationSearch("?embed=true&embed_options=light_theme")
)
const defaultTheme = getDefaultTheme()
expect(defaultTheme.name).toBe("Light")
// Also verify that the theme is our lightTheme.
expect(defaultTheme.emotion.colors).toEqual(lightTheme.emotion.colors)
})
})
describe("isColor", () => {
// https://www.w3schools.com/cssref/css_colors_legal.asp
it("works with valid colors", () => {
expect(isColor("#fff")).toBe(true)
expect(isColor("#ffffff")).toBe(true)
expect(isColor("#ffffff0")).toBe(true)
expect(isColor("#000")).toBe(true)
expect(isColor("#000000")).toBe(true)
expect(isColor("#fafafa")).toBe(true)
expect(isColor("red")).toBe(true)
expect(isColor("coral")).toBe(true)
expect(isColor("transparent")).toBe(true)
expect(isColor("rgb(0,0,0)")).toBe(true)
expect(isColor("rgb(-1, 0, -255)")).toBe(true)
expect(isColor("rgba(0,0,0,.5)")).toBe(true)
expect(isColor("hsl(120,50%,40%)")).toBe(true)
expect(isColor("hsl(120,50%,40%, .4)")).toBe(true)
expect(isColor("currentColor")).toBe(true)
})
it("works with invalid colors", () => {
expect(isColor("fff")).toBe(false)
expect(isColor("cookies are delicious")).toBe(false)
expect(isColor("")).toBe(false)
expect(isColor("hsl(120,50,40)")).toBe(false)
})
})
describe("createEmotionTheme", () => {
it("sets to light when matchMedia does not match dark", () => {
const themeInput: Partial<CustomThemeConfig> = {
font: CustomThemeConfig.FontFamily.MONOSPACE,
primaryColor: "red",
backgroundColor: "pink",
secondaryBackgroundColor: "blue",
textColor: "orange",
}
const theme = createEmotionTheme(themeInput)
expect(theme.colors.primary).toBe("red")
expect(theme.colors.bgColor).toBe("pink")
expect(theme.colors.secondaryBg).toBe("blue")
expect(theme.colors.bodyText).toBe("orange")
expect(theme.genericFonts.bodyFont).toBe(theme.fonts.monospace)
expect(theme.genericFonts.headingFont).toBe(theme.fonts.monospace)
expect(theme.genericFonts.codeFont).toBe(theme.fonts.monospace)
})
it("defaults to base if missing value", () => {
const themeInput: Partial<CustomThemeConfig> = {
primaryColor: "red",
}
const theme = createEmotionTheme(themeInput)
expect(theme.colors.primary).toBe("red")
expect(theme.colors.bgColor).toBe(baseTheme.emotion.colors.bgColor)
expect(theme.colors.secondaryBg).toBe(baseTheme.emotion.colors.secondaryBg)
expect(theme.colors.bodyText).toBe(baseTheme.emotion.colors.bodyText)
expect(theme.genericFonts.bodyFont).toBe(
baseTheme.emotion.genericFonts.bodyFont
)
expect(theme.genericFonts.headingFont).toBe(
baseTheme.emotion.genericFonts.headingFont
)
expect(theme.genericFonts.codeFont).toBe(
baseTheme.emotion.genericFonts.codeFont
)
})
})
describe("toThemeInput", () => {
it("converts from emotion theme to what a custom component expects", () => {
const { colors } = lightTheme.emotion
expect(toThemeInput(lightTheme.emotion)).toEqual({
primaryColor: colors.primary,
backgroundColor: colors.bgColor,
secondaryBackgroundColor: colors.secondaryBg,
textColor: colors.bodyText,
font: CustomThemeConfig.FontFamily.SANS_SERIF,
})
})
})
describe("converting font <> enum", () => {
it("fontEnumToString converts to enum", () => {
expect(fontEnumToString(CustomThemeConfig.FontFamily.SANS_SERIF)).toBe(
fonts.sansSerif
)
expect(fontEnumToString(CustomThemeConfig.FontFamily.SERIF)).toBe(
fonts.serif
)
expect(fontEnumToString(CustomThemeConfig.FontFamily.MONOSPACE)).toBe(
fonts.monospace
)
})
it("fontToEnum converts to string", () => {
expect(fontToEnum(fonts.monospace)).toBe(
CustomThemeConfig.FontFamily.MONOSPACE
)
expect(fontToEnum(fonts.sansSerif)).toBe(
CustomThemeConfig.FontFamily.SANS_SERIF
)
expect(fontToEnum(fonts.serif)).toBe(CustomThemeConfig.FontFamily.SERIF)
})
})
describe("bgColorToBaseString", () => {
it("returns 'light' if passed undefined", () => {
expect(bgColorToBaseString(undefined)).toBe("light")
})
it("returns 'light' for a light background color", () => {
expect(bgColorToBaseString("#FFFFFF")).toBe("light")
})
it("returns 'dark' for a dark background color", () => {
expect(bgColorToBaseString("#000000")).toBe("dark")
})
})
describe("hasLightBackgroundColor", () => {
const testCases = [
{
description: "works for default light theme",
theme: lightTheme,
expectedResult: true,
},
{
description: "works for default dark theme",
theme: darkTheme,
expectedResult: false,
},
{
description: "works for custom light theme",
theme: createTheme(
CUSTOM_THEME_NAME,
new CustomThemeConfig({ backgroundColor: "yellow" })
),
expectedResult: true,
},
{
description: "works for custom dark theme",
theme: createTheme(
CUSTOM_THEME_NAME,
new CustomThemeConfig({ backgroundColor: "navy" })
),
expectedResult: false,
},
]
testCases.forEach(({ description, theme, expectedResult }) => {
it(`${description}`, () => {
expect(hasLightBackgroundColor(theme.emotion)).toBe(expectedResult)
})
})
})