~james/core

core/web/src/lib/avatarGradient.test.ts -rw-r--r-- 1.7 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
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
import { describe, expect, it } from "vitest";
import { gradientCss, gradientFor, hashString } from "#lib/avatarGradient.ts";

const dids = [
	"did:plc:7ztawo7fm3lhsiggwoqa36y3",
	"did:plc:mpyoufk5zobjcq2ogucxy2o7",
	"did:web:example.com",
	"did:web:spindle.next-dev.tangled.org"
];

describe("gradientFor", () => {
	it("gives the same gradient for the same did", () => {
		for (const did of dids) expect(gradientFor(did)).toEqual(gradientFor(did));
	});

	it("gives did:plc and did:web alike a different gradient each", () => {
		expect(new Set(dids.map((did) => gradientCss(did))).size).toBe(dids.length);
	});

	it("hashes a known string to a known value", () => {
		expect(hashString("")).toBe(2166136261);
		expect(hashString("a")).toBe(3826002220);
	});

	it.each(dids)("keeps the stops of %s ordered in 3 to 5 steps from 0 to 100", (did) => {
		const { stops } = gradientFor(did);
		expect(stops.length).toBeGreaterThanOrEqual(3);
		expect(stops.length).toBeLessThanOrEqual(5);
		expect(stops[0].offset).toBe(0);
		expect(stops.at(-1)?.offset).toBe(100);
		expect(stops.map((s) => s.offset)).toEqual(
			[...stops.map((s) => s.offset)].sort((a, b) => a - b)
		);
	});
});

describe("gradientCss", () => {
	it.each(dids)("is a radial glow over a linear gradient for %s", (did) => {
		expect(gradientCss(did)).toMatch(
			/^radial-gradient\(\d+(\.\d+)?% \d+(\.\d+)?% at [\d.]+% [\d.]+%, #[0-9a-f]{8}, #[0-9a-f]{6}00\), linear-gradient\(\d+deg, (#[0-9a-f]{6} -?[\d.]+%(, )?)+\)$/
		);
	});

	it("stretches the stops so they span the corners like the svg", () => {
		const css = gradientCss(dids[0]);
		const stops = [...css.matchAll(/#[0-9a-f]{6} (-?[\d.]+)%/g)].map((m) => Number(m[1]));
		expect(stops[0]).toBeLessThan(0);
		expect(stops.at(-1)).toBeGreaterThan(100);
	});
});