Debian Codegraph @

node/colorjs.io/src/Format.js

raw
1 import { isInstance, isNone } from "./util.js";
2 import Type from "./Type.js";
3
4 /** @import { ColorSpace, Coords } from "./types.js" */
5
6 // Type re-exports
7 /** @typedef {import("./types.js").Format} FormatInterface */
8
9 /**
10 * @internal
11 * Used to index {@link FormatInterface Format} objects and store an instance.
12 * Not meant for external use
13 */
14 export const instance = Symbol("instance");
15
16 /**
17 * Remove the first element of an array type
18 * @template {any[]} T
19 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
20 */
21
22 /**
23 * @class Format
24 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
25 * Class to hold a color serialization format
26 */
27 export default class Format {
28 // Class properties - declared here so that type inference works
29 type;
30 name;
31 spaceCoords;
32 /** @type {Type[][]} */
33 coords;
34 /** @type {string | undefined} */
35 id;
36 /** @type {boolean | undefined} */
37 alpha;
38
39 /**
40 * @param {FormatInterface} format
41 * @param {ColorSpace} space
42 */
43 constructor (format, space = format.space) {
44 format[instance] = this;
45 this.type = "function";
46 this.name = "color";
47
48 Object.assign(this, format);
49
50 this.space = space;
51
52 if (this.type === "custom") {
53 // Nothing else to do here
54 return;
55 }
56
57 this.spaceCoords = Object.values(space.coords);
58
59 if (!this.coords) {
60 // @ts-expect-error Strings are converted to the correct type later
61 this.coords = this.spaceCoords.map(coordMeta => {
62 let ret = ["<number>", "<percentage>"];
63
64 if (coordMeta.type === "angle") {
65 ret.push("<angle>");
66 }
67
68 return ret;
69 });
70 }
71
72 this.coords = this.coords.map(
73 /** @param {string | string[] | Type[]} types */ (types, i) => {
74 let coordMeta = this.spaceCoords[i];
75
76 if (typeof types === "string") {
77 types = types.trim().split(/\s*\|\s*/);
78 }
79
80 return types.map(type => Type.get(type, coordMeta));
81 },
82 );
83 }
84
85 /**
86 * @param {Coords} coords
87 * @param {number} precision
88 * @param {Type[]} types
89 */
90 serializeCoords (coords, precision, types) {
91 types = coords.map((_, i) =>
92 Type.get(types?.[i] ?? this.coords[i][0], this.spaceCoords[i]));
93 return coords.map((c, i) => types[i].serialize(c, precision));
94 }
95
96 /**
97 * Validates the coordinates of a color against a format's coord grammar and
98 * maps the coordinates to the range or refRange of the coordinates.
99 * @param {Coords} coords
100 * @param {[string, string, string]} types
101 */
102 coerceCoords (coords, types) {
103 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
104 let arg = coords[i];
105
106 if (isNone(arg) || isNaN(arg)) {
107 // Nothing to do here
108 return arg;
109 }
110
111 // Find grammar alternative that matches the provided type
112 // Non-strict equals is intentional because we are comparing w/ string objects
113 let providedType = types[i];
114 let type = this.coords[i].find(c => c.type == providedType);
115
116 // Check that each coord conforms to its grammar
117 if (!type) {
118 // Type does not exist in the grammar, throw
119 let coordName = coordMeta.name || id;
120 throw new TypeError(
121 `${providedType ?? /** @type {any} */ (arg)?.raw ?? arg} not allowed for ${coordName} in ${this.name}()`,
122 );
123 }
124
125 arg = type.resolve(arg);
126
127 if (type.range) {
128 // Adjust type to include range
129 types[i] = type.toString();
130 }
131
132 return arg;
133 });
134 }
135
136 /**
137 * @returns {boolean | Required<FormatInterface>["serialize"]}
138 */
139 canSerialize () {
140 return this.type === "function" || /** @type {any} */ (this).serialize;
141 }
142
143 /**
144 * @param {string} str
145 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
146 */
147 parse (str) {
148 return null;
149 }
150
151 /**
152 * @param {Format | FormatInterface} format
153 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
154 * @returns {Format}
155 */
156 static get (format, ...args) {
157 if (!format || isInstance(format, this)) {
158 return /** @type {Format} */ (format);
159 }
160
161 if (format[instance]) {
162 return format[instance];
163 }
164
165 return new Format(format, ...args);
166 }
167 }