diff --git a/lib/color-util.test.ts b/lib/color-util.test.ts index f319921..fa7e8c9 100644 --- a/lib/color-util.test.ts +++ b/lib/color-util.test.ts @@ -1,4 +1,8 @@ -import { clampedBytesToRGBColor, clampedByteToHex } from "./color-util"; +import { + clampedBytesToRGBColor, + clampedByteToHex, + parseHexColor, +} from "./color-util"; describe("clampedBytesToRGBColor", () => { it("works", () => { @@ -23,3 +27,9 @@ describe("clampedByteToHex", () => { expect(clampedByteToHex(22)).toBe("16"); }); }); + +describe("parseHexColor", () => { + it("works", () => { + expect(parseHexColor("#ff001a")).toEqual([255, 0, 26]); + }); +}); diff --git a/lib/color-util.ts b/lib/color-util.ts index 8561bc3..2af8651 100644 --- a/lib/color-util.ts +++ b/lib/color-util.ts @@ -21,3 +21,14 @@ export function clampedByteToHex(value: number): string { export function clampedBytesToRGBColor(values: number[]): string { return "#" + values.map(clampedByteToHex).join(""); } + +/** + * Convert the given hex color string, e.g. `#abcdef`, to an + * Array of RGB numbers. + */ +export function parseHexColor(value: string): [number, number, number] { + const red = parseInt(value.substring(1, 3), 16); + const green = parseInt(value.substring(3, 5), 16); + const blue = parseInt(value.substring(5, 7), 16); + return [red, green, blue]; +} diff --git a/lib/pages/mandala-page/serialization.ts b/lib/pages/mandala-page/serialization.ts index c55ec2f..d59b9b3 100644 --- a/lib/pages/mandala-page/serialization.ts +++ b/lib/pages/mandala-page/serialization.ts @@ -15,7 +15,7 @@ import { getCirclesFromDesign, } from "./core"; import { fromBase64, toBase64 } from "../../base64"; -import { clampedBytesToRGBColor } from "../../color-util"; +import { clampedBytesToRGBColor, parseHexColor } from "../../color-util"; const LATEST_VERSION = "v2"; @@ -64,9 +64,7 @@ const SvgCompositionContextPacker: Packer< export const ColorPacker: Packer = { pack: (string) => { - const red = parseInt(string.substring(1, 3), 16); - const green = parseInt(string.substring(3, 5), 16); - const blue = parseInt(string.substring(5, 7), 16); + const [red, green, blue] = parseHexColor(string); return (red << 16) + (green << 8) + blue; }, unpack: (number) => {