export function getColorValue()

in src/languageFacts/colors.ts [366:433]


export function getColorValue(node: nodes.Node): Color | null {
	if (node.type === nodes.NodeType.HexColorValue) {
		const text = node.getText();
		return colorFromHex(text);
	} else if (node.type === nodes.NodeType.Function) {
		const functionNode = <nodes.Function>node;
		const name = functionNode.getName();
		let colorValues = functionNode.getArguments().getChildren();
		if (colorValues.length === 1) {
			const functionArg = colorValues[0].getChildren();
			if (functionArg.length === 1 && functionArg[0].type === nodes.NodeType.Expression) {
				colorValues = functionArg[0].getChildren();
				if (colorValues.length === 3) {
					const lastValue = colorValues[2];
					if (lastValue instanceof nodes.BinaryExpression) {
						const left = lastValue.getLeft(), right = lastValue.getRight(), operator = lastValue.getOperator();
						if (left && right && operator && operator.matches('/')) {
							colorValues = [ colorValues[0], colorValues[1], left, right ];
						}
					}
				}
			}	
		}
		if (!name || colorValues.length < 3 || colorValues.length > 4) {
			return null;
		}
		try {
			const alpha = colorValues.length === 4 ? getNumericValue(colorValues[3], 1) : 1;
			if (name === 'rgb' || name === 'rgba') {
				return {
					red: getNumericValue(colorValues[0], 255.0),
					green: getNumericValue(colorValues[1], 255.0),
					blue: getNumericValue(colorValues[2], 255.0),
					alpha
				};
			} else if (name === 'hsl' || name === 'hsla') {
				const h = getAngle(colorValues[0]);
				const s = getNumericValue(colorValues[1], 100.0);
				const l = getNumericValue(colorValues[2], 100.0);
				return colorFromHSL(h, s, l, alpha);
			}
		} catch (e) {
			// parse error on numeric value
			return null;
		}
	} else if (node.type === nodes.NodeType.Identifier) {
		if (node.parent && node.parent.type !== nodes.NodeType.Term) {
			return null;
		}
		const term = node.parent;
		if (term && term.parent && term.parent.type === nodes.NodeType.BinaryExpression) {
			const expression = term.parent;
			if (expression.parent && expression.parent.type === nodes.NodeType.ListEntry && (<nodes.ListEntry>expression.parent).key === expression) {
				return null;
			}
		}

		const candidateColor = node.getText().toLowerCase();
		if (candidateColor === 'none') {
			return null;
		}
		const colorHex = colors[candidateColor];
		if (colorHex) {
			return colorFromHex(colorHex);
		}
	}
	return null;
}