Skip to content

Conversation

@n1kk
Copy link

@n1kk n1kk commented Nov 7, 2019

Hi,

I've added new method to the plugin api: addFunction through which users can define custom css functions, since we all have sometime unique requirements and it's easier and better to write a js function that has access to raw config than figuring out a way to hack it in css or hooking up sass/less to the project. So if you want to have a way to get some color from your config in a certain format you can just quickly add the exact method you need:

// css color functions plugin
function ({addFunction, theme})
{
	const hex2rgb = (hex) => {
		const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return match ? `${parseInt(match[1], 16)}, ${parseInt(match[2], 16)}, ${parseInt(match[3], 16)}` : "";
	};
	// get value from color section of config
	addFunction('color', (color) => {
		color = color.replace(/^\s*['"]|['"]\s*$/g, "");
		const col = theme("colors." + color);
		return col;
	});
	// get value from color section of config in rgb format
	addFunction('colorRgb', (color) => {
		color = color.replace(/^\s*['"]|['"]\s*$/g, "");
		let col = theme("colors." + color);
		return `rgb(${hex2rgb(col)})`
	});
	// get value from color section of config in rgba format
	addFunction('colorRgba', (color, alpha) => {
		color = color.replace(/^\s*['"]|['"]\s*$/g, "");
		let col = theme("colors." + color);
		return `rgba(${hex2rgb(col)}, ${alpha})`
	});
}

Functions are being added after tailwinds own ones so it is possible to override theme function. Didn't do it for any specific reason, so the order can be changed if you want to enforce theme method to be immutable.

I've also changed theme function to behave like it's counterpart in css and return default value if the requested item is object and has default field. I think it's more consistent this way and if you still need the raw config value there's config function.

Waiting for some feedback :)

@hacknug
Copy link
Contributor

hacknug commented Nov 11, 2019

Definitely something interesting. Would love to hear/read everyone else's thoughts on this 👀

@adamwathan
Copy link
Member

Hey thanks for this! Unfortunately for now I don't want to take on ownership of a feature like this that feels a bit outside of Tailwind's usual scope. Instead I would recommend just using postcss-functions directly and importing your Tailwind theme into your own custom JS in order to reference it.

@adamwathan adamwathan closed this Dec 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants