import { describe, expect, it } from 'vitest' import { contrastRatio, parseTheme, rgbCss } from './theme' const rgb = (r: number, g: number, b: number, $type = 'site.standard.theme.color#rgb') => ({ $type, r, g, b, }) // The shape a real publication writes: the record's own `$type` on the theme // object, and the union tag on each color. const light = { $type: 'site.standard.theme.basic', background: rgb(253, 252, 249), foreground: rgb(38, 40, 43), accent: rgb(217, 72, 43), accentForeground: rgb(255, 255, 255), } describe('contrastRatio', () => { it('is 21 for black on white', () => { expect(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 })).toBeCloseTo(21, 5) }) it('is 1 for a color against itself', () => { expect(contrastRatio(light.background, light.background)).toBeCloseTo(1, 5) }) }) describe('rgbCss', () => { it('writes a CSS color', () => { expect(rgbCss({ r: 1, g: 2, b: 3 })).toBe('rgb(1 2 3)') }) }) describe('parseTheme', () => { it('reads the four required colors', () => { expect(parseTheme(light)).toEqual({ background: { r: 253, g: 252, b: 249 }, foreground: { r: 38, g: 40, b: 43 }, accent: { r: 217, g: 72, b: 43 }, accentForeground: { r: 255, g: 255, b: 255 }, }) }) it('accepts a loose color without the union tag', () => { expect( parseTheme({ background: { r: 255, g: 255, b: 255 }, foreground: { r: 0, g: 0, b: 0 }, accent: { r: 0, g: 0, b: 255 }, accentForeground: { r: 255, g: 255, b: 255 }, }), ).toBeDefined() }) it('rejects a missing color', () => { expect(parseTheme({ ...light, accent: undefined })).toBeUndefined() }) it('rejects out-of-range and non-integer components', () => { expect(parseTheme({ ...light, accent: rgb(256, 0, 0) })).toBeUndefined() expect(parseTheme({ ...light, accent: rgb(-1, 0, 0) })).toBeUndefined() expect(parseTheme({ ...light, accent: rgb(1.5, 0, 0) })).toBeUndefined() }) it('rejects a color tagged with another union member', () => { expect( parseTheme({ ...light, accent: rgb(0, 0, 0, 'site.standard.theme.color#rgba') }), ).toBeUndefined() }) it('rejects a theme whose text would be unreadable', () => { expect( parseTheme({ ...light, background: rgb(255, 255, 255), foreground: rgb(250, 250, 250), }), ).toBeUndefined() }) it('rejects anything that is not an object', () => { expect(parseTheme(undefined)).toBeUndefined() expect(parseTheme('nope')).toBeUndefined() expect(parseTheme(null)).toBeUndefined() }) })