Files
community-rule/tests/unit/previewSurfaceColor.test.ts

91 lines
2.6 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
isPreviewSurfaceColor,
mostCommonOpaqueColor,
randomPreviewSurfaceColor,
readableCardFill,
} from "../../lib/create/previewSurfaceColor";
function pixel(r: number, g: number, b: number, a = 255): number[] {
return [r, g, b, a];
}
describe("mostCommonOpaqueColor", () => {
it("returns the average of the largest quantized bucket", () => {
const data = new Uint8ClampedArray([
...pixel(200, 10, 10),
...pixel(201, 11, 9),
...pixel(202, 9, 11),
...pixel(10, 10, 220),
]);
expect(mostCommonOpaqueColor(data)).toBe("rgb(201, 10, 10)");
});
it("ignores transparent pixels", () => {
const data = new Uint8ClampedArray([
...pixel(255, 255, 255, 0),
...pixel(255, 255, 255, 0),
...pixel(20, 40, 60),
]);
expect(mostCommonOpaqueColor(data)).toBe("rgb(20, 40, 60)");
});
it("returns null when nothing is opaque", () => {
const data = new Uint8ClampedArray([...pixel(1, 2, 3, 0)]);
expect(mostCommonOpaqueColor(data)).toBeNull();
});
it("counts a translucent fill", () => {
const data = new Uint8ClampedArray([...pixel(255, 0, 0, 127)]);
expect(mostCommonOpaqueColor(data)).toBe("rgb(255, 0, 0)");
});
});
describe("readableCardFill", () => {
it("keeps a light logo color", () => {
expect(readableCardFill(201, 254, 249)).toBe("rgb(201, 254, 249)");
});
it("lifts a dark logo color into a pale tint of the same hue", () => {
const fill = readableCardFill(255, 0, 0);
const channels = fill
.split(/[^\d]+/)
.filter(Boolean)
.map(Number);
const lightness =
(Math.max(...channels) + Math.min(...channels)) / 2 / 255;
expect(lightness).toBeGreaterThanOrEqual(0.8);
expect(channels[0]).toBeGreaterThan(channels[2]);
});
});
describe("randomPreviewSurfaceColor", () => {
it("stays in a light range so black type can sit on it", () => {
let call = 0;
const sequence = [0, 0, 0];
expect(randomPreviewSurfaceColor(() => sequence[call++] ?? 0)).toBe(
"hsl(0, 50%, 76%)",
);
call = 0;
const high = [0.999, 0.999, 0.999];
expect(randomPreviewSurfaceColor(() => high[call++] ?? 0)).toBe(
"hsl(359, 84%, 87%)",
);
});
});
describe("isPreviewSurfaceColor", () => {
it("accepts the hsl strings this module writes", () => {
expect(isPreviewSurfaceColor("hsl(12, 50%, 80%)")).toBe(true);
expect(isPreviewSurfaceColor("hsl(359, 84%, 87%)")).toBe(true);
});
it("rejects other CSS colors", () => {
expect(isPreviewSurfaceColor("rgb(12, 80, 40)")).toBe(false);
expect(isPreviewSurfaceColor("red")).toBe(false);
});
});