| 1 |
import { isNone, clamp } from "./util.js"; |
| 2 |
import hooks from "./hooks.js"; |
| 3 |
import ColorSpace from "./ColorSpace.js"; |
| 4 |
import defaults from "./defaults.js"; |
| 5 |
|
| 6 |
/** @import { ColorConstructor } from "./types.js" */ |
| 7 |
|
| 8 |
// Type re-exports |
| 9 |
/** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */ |
| 10 |
/** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */ |
| 11 |
/** @typedef {import("./types.js").ParseOptions} ParseOptions */ |
| 12 |
|
| 13 |
/** |
| 14 |
* Convert a CSS Color string to a color object |
| 15 |
* @param {string} str |
| 16 |
* @param {ParseOptions} [options] |
| 17 |
* @returns {ColorConstructor} |
| 18 |
*/ |
| 19 |
export default function parse (str, options) { |
| 20 |
let env = { |
| 21 |
str: String(str)?.trim(), |
| 22 |
options, |
| 23 |
}; |
| 24 |
|
| 25 |
hooks.run("parse-start", env); |
| 26 |
|
| 27 |
if (env.color) { |
| 28 |
return env.color; |
| 29 |
} |
| 30 |
|
| 31 |
env.parsed = parseFunction(env.str); |
| 32 |
let ret; |
| 33 |
let meta = env.options ? (env.options.parseMeta ?? env.options.meta) : null; |
| 34 |
|
| 35 |
if (env.parsed) { |
| 36 |
// Is a functional syntax |
| 37 |
let name = env.parsed.name; |
| 38 |
let format; |
| 39 |
let space; |
| 40 |
let coords = env.parsed.args; |
| 41 |
let types = coords.map((c, i) => env.parsed.argMeta[i]?.type); |
| 42 |
|
| 43 |
if (name === "color") { |
| 44 |
// color() function |
| 45 |
let id = coords.shift(); |
| 46 |
types.shift(); |
| 47 |
// Check against both <dashed-ident> and <ident> versions |
| 48 |
let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`; |
| 49 |
let ids = [id, alternateId]; |
| 50 |
format = ColorSpace.findFormat({ name, id: ids, type: "function" }); |
| 51 |
|
| 52 |
if (!format) { |
| 53 |
// Not found |
| 54 |
let didYouMean; |
| 55 |
|
| 56 |
let registryId = id in ColorSpace.registry ? id : alternateId; |
| 57 |
if (registryId in ColorSpace.registry) { |
| 58 |
// Used color space id instead of color() id, these are often different |
| 59 |
let cssId = ColorSpace.registry[registryId].formats?.color?.id; |
| 60 |
|
| 61 |
if (cssId) { |
| 62 |
let altColor = str.replace("color(" + id, "color(" + cssId); |
| 63 |
didYouMean = `Did you mean ${altColor}?`; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
throw new TypeError( |
| 68 |
`Cannot parse ${env.str}. ` + (didYouMean ?? "Missing a plugin?"), |
| 69 |
); |
| 70 |
} |
| 71 |
|
| 72 |
space = format.space; |
| 73 |
|
| 74 |
if (format.id.startsWith("--") && !id.startsWith("--")) { |
| 75 |
defaults.warn( |
| 76 |
`${space.name} is a non-standard space and not currently supported in the CSS spec. ` + |
| 77 |
`Use prefixed color(${format.id}) instead of color(${id}).`, |
| 78 |
); |
| 79 |
} |
| 80 |
if (id.startsWith("--") && !format.id.startsWith("--")) { |
| 81 |
defaults.warn( |
| 82 |
`${space.name} is a standard space and supported in the CSS spec. ` + |
| 83 |
`Use color(${format.id}) instead of prefixed color(${id}).`, |
| 84 |
); |
| 85 |
} |
| 86 |
} |
| 87 |
else { |
| 88 |
format = ColorSpace.findFormat({ name, type: "function" }); |
| 89 |
space = format.space; |
| 90 |
} |
| 91 |
|
| 92 |
if (meta) { |
| 93 |
Object.assign(meta, { |
| 94 |
format, |
| 95 |
formatId: format.name, |
| 96 |
types, |
| 97 |
commas: env.parsed.commas, |
| 98 |
}); |
| 99 |
} |
| 100 |
|
| 101 |
let alpha = 1; |
| 102 |
|
| 103 |
if (env.parsed.lastAlpha) { |
| 104 |
alpha = env.parsed.args.pop(); |
| 105 |
|
| 106 |
if (meta) { |
| 107 |
meta.alphaType = types.pop(); |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
let coordCount = format.coords.length; |
| 112 |
|
| 113 |
if (coords.length !== coordCount) { |
| 114 |
throw new TypeError( |
| 115 |
`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`, |
| 116 |
); |
| 117 |
} |
| 118 |
|
| 119 |
coords = format.coerceCoords(coords, types); |
| 120 |
|
| 121 |
ret = { spaceId: space.id, coords, alpha }; |
| 122 |
} |
| 123 |
else { |
| 124 |
// Custom, colorspace-specific format |
| 125 |
spaceloop: for (let space of ColorSpace.all) { |
| 126 |
for (let formatId in space.formats) { |
| 127 |
let format = space.formats[formatId]; |
| 128 |
|
| 129 |
if (format.type !== "custom") { |
| 130 |
continue; |
| 131 |
} |
| 132 |
|
| 133 |
if (format.test && !format.test(env.str)) { |
| 134 |
continue; |
| 135 |
} |
| 136 |
|
| 137 |
// Convert to Format object |
| 138 |
let formatObject = space.getFormat(format); |
| 139 |
|
| 140 |
let color = formatObject.parse(env.str); |
| 141 |
|
| 142 |
if (color) { |
| 143 |
if (meta) { |
| 144 |
Object.assign(meta, { format: formatObject, formatId }); |
| 145 |
} |
| 146 |
|
| 147 |
ret = color; |
| 148 |
break spaceloop; |
| 149 |
} |
| 150 |
} |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
if (!ret) { |
| 155 |
// If we're here, we couldn't parse |
| 156 |
throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`); |
| 157 |
} |
| 158 |
|
| 159 |
// Clamp alpha to [0, 1] |
| 160 |
ret.alpha = isNone(ret.alpha) |
| 161 |
? ret.alpha |
| 162 |
: ret.alpha === undefined |
| 163 |
? 1 |
| 164 |
: clamp(0, ret.alpha, 1); |
| 165 |
|
| 166 |
return ret; |
| 167 |
} |
| 168 |
|
| 169 |
/** |
| 170 |
* Units and multiplication factors for the internally stored numbers |
| 171 |
*/ |
| 172 |
export const units = { |
| 173 |
"%": 0.01, |
| 174 |
deg: 1, |
| 175 |
grad: 0.9, |
| 176 |
rad: 180 / Math.PI, |
| 177 |
turn: 360, |
| 178 |
}; |
| 179 |
|
| 180 |
export const regex = { |
| 181 |
// Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call |
| 182 |
function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i, |
| 183 |
number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i, |
| 184 |
unitValue: RegExp(`(${Object.keys(units).join("|")})$`), |
| 185 |
|
| 186 |
// NOTE The -+ are not just for prefix, but also for idents, and e+N notation! |
| 187 |
singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g, |
| 188 |
}; |
| 189 |
|
| 190 |
/** |
| 191 |
* Parse a single function argument |
| 192 |
* @param {string} rawArg |
| 193 |
* @returns {{value: number, meta: ArgumentMeta}} |
| 194 |
*/ |
| 195 |
export function parseArgument (rawArg) { |
| 196 |
/** @type {Partial<ArgumentMeta>} */ |
| 197 |
let meta = {}; |
| 198 |
let unit = rawArg.match(regex.unitValue)?.[0]; |
| 199 |
/** @type {string | number} */ |
| 200 |
let value = (meta.raw = rawArg); |
| 201 |
|
| 202 |
if (unit) { |
| 203 |
// It’s a dimension token |
| 204 |
meta.type = unit === "%" ? "<percentage>" : "<angle>"; |
| 205 |
meta.unit = unit; |
| 206 |
meta.unitless = Number(value.slice(0, -unit.length)); // unitless number |
| 207 |
|
| 208 |
value = meta.unitless * units[unit]; |
| 209 |
} |
| 210 |
else if (regex.number.test(value)) { |
| 211 |
// It's a number |
| 212 |
// Convert numerical args to numbers |
| 213 |
value = Number(value); |
| 214 |
meta.type = "<number>"; |
| 215 |
} |
| 216 |
else if (value === "none") { |
| 217 |
value = null; |
| 218 |
} |
| 219 |
else if (value === "NaN" || value === "calc(NaN)") { |
| 220 |
value = NaN; |
| 221 |
meta.type = "<number>"; |
| 222 |
} |
| 223 |
else { |
| 224 |
meta.type = "<ident>"; |
| 225 |
} |
| 226 |
|
| 227 |
return { value: /** @type {number} */ (value), meta: /** @type {ArgumentMeta} */ (meta) }; |
| 228 |
} |
| 229 |
|
| 230 |
/** |
| 231 |
* Parse a CSS function, regardless of its name and arguments |
| 232 |
* @param {string} str String to parse |
| 233 |
* @return {ParseFunctionReturn | void} |
| 234 |
*/ |
| 235 |
export function parseFunction (str) { |
| 236 |
if (!str) { |
| 237 |
return; |
| 238 |
} |
| 239 |
|
| 240 |
str = str.trim(); |
| 241 |
|
| 242 |
let parts = str.match(regex.function); |
| 243 |
|
| 244 |
if (parts) { |
| 245 |
// It is a function, parse args |
| 246 |
let args = []; |
| 247 |
let argMeta = []; |
| 248 |
let lastAlpha = false; |
| 249 |
let name = parts[1].toLowerCase(); |
| 250 |
|
| 251 |
let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => { |
| 252 |
let { value, meta } = parseArgument(rawArg); |
| 253 |
|
| 254 |
if ( |
| 255 |
// If there's a slash here, it's modern syntax |
| 256 |
$0.startsWith("/") || |
| 257 |
// If there's still elements to process after there's already 3 in `args` (and the we're not dealing with "color()"), it's likely to be a legacy color like "hsl(0, 0%, 0%, 0.5)" |
| 258 |
(name !== "color" && args.length === 3) |
| 259 |
) { |
| 260 |
// It's alpha |
| 261 |
lastAlpha = true; |
| 262 |
} |
| 263 |
|
| 264 |
args.push(value); |
| 265 |
argMeta.push(meta); |
| 266 |
return ""; |
| 267 |
}); |
| 268 |
|
| 269 |
return { |
| 270 |
name, |
| 271 |
args, |
| 272 |
argMeta, |
| 273 |
lastAlpha, |
| 274 |
commas: separators.includes(","), |
| 275 |
rawName: parts[1], |
| 276 |
rawArgs: parts[2], |
| 277 |
}; |
| 278 |
} |
| 279 |
} |