Skip to content

Commit fcb5436

Browse files
committed
Allow serialize() to use formats from other color spaces, closes #246
1 parent ed823c0 commit fcb5436

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

src/Format.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export default class Format {
8888
}
8989

9090
static get (format, ...args) {
91-
if (format instanceof Format) {
91+
if (!format || format instanceof Format) {
9292
return format;
9393
}
9494

src/serialize.js

+8
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as util from "./util.js";
22
import ColorSpace from "./space.js";
33
import defaults from "./defaults.js";
44
import getColor from "./getColor.js";
5+
import to from "./to.js";
56
import checkInGamut from "./inGamut.js";
67
import toGamut from "./toGamut.js";
78
import clone from "./clone.js";
@@ -29,9 +30,16 @@ export default function serialize (color, options = {}) {
2930

3031
let formatId = format;
3132
format = color.space.getFormat(format)
33+
?? ColorSpace.findFormat(format)
3234
?? color.space.getFormat("default")
3335
?? ColorSpace.DEFAULT_FORMAT;
3436

37+
if (format.space && format.space !== color.space) {
38+
// Format specified belongs to a different color space,
39+
// need to convert to it first
40+
color = to(color, format.space);
41+
}
42+
3543
// The assignment to coords and inGamut needs to stay in the order they are now
3644
// The order of the assignment was changed as a workaround for a bug in Next.js
3745
// See this issue for details: https://github.com/color-js/color.js/issues/260

test/serialize.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,12 @@ const tests = {
8484
{
8585
name: "Hex on non-sRGB color",
8686
args: ["hsl", [0, 100, 50], 1, {format: "hex"}],
87-
expect: "#ff0000",
87+
expect: "#f00",
88+
},
89+
{
90+
name: "Cannot serialize as keyword",
91+
args: ["srgb", [1, 0.5, 0], 1, {format: "keyword"}],
92+
throws: true,
8893
},
8994
],
9095
},

0 commit comments

Comments
 (0)