Re: [css-houdini-drafts] [css-custom-functions] user-defined custom CSS functions (#1007)

I think it would be great if there was a way for authors to wire up custom functions JavaScript knows about to CSS using a custom `<dashed-ident>` as the function name. 

Suppose you have a function like this somewhere in JS:

```js
function pickRandom(array = []) {
  return array[Math.floor(Math.random() * array.length]
}
```

You would need some way to register this with CSS to be used with a certain name:

```js
CSS.registerCustomFunction({
  name: '--pick-random',
  syntax: '<any>#', // space separated tokens
  definition: pickRandom,
  events: ['load']
})
```

And then be able to use it anywhere in a CSS value as `--pick-random()`:

```css
:root {
  background-color: --pick-random(red green blue);
}
```

Being able to expose existing JavaScript functions to CSS (including all of the colour conversion and animation libs out there) would bring a lot of value because so many of the most useful functions might exist already and be immediately usable from new places. Another exciting possibility is allowing people to integrate some of the styling integrations currently only possible CSS-in-JS to be used from regular CSS stylesheets as well.

I think this would be true whether or not there was a way to declaratively define them from CSS syntax (which I also think is fun). As a side note, I am not proposing anything about defining them from CSS but an at-rule seems to make sense for something like that. Just for fun, here's a codepen I made recently exploring defining JS functions in CSS syntax to be used from CSS as custom functions: https://codepen.io/tomhodgins/pen/oNbBYZw

I'd love to see anything like this, even browsers parsing and hanging onto `--custom()` functions so we can try to support them client-side. I've noticed browsers today _will_ hang onto `--custom-functions()` in two situations:

```css
a {
  --works-inside-in-a-custom-property: --custom();
}
```
Inside the value of a custom property basically everything that's valid CSS parsed and kept, so any `--custom()` function usage is safe to use in-browsers here.

```css
a {
  width: var(--works-in-any-property-value-that-includes-var-too) --custom();
}
```
It also seems like browsers parse and hang onto custom functions inside property values that include `var()` as well, so as long as `var()` is somewhere in the property value it seems like you can `--something-like-this()` in browsers today (it won't show up in the property value, but can be found in that CSS rule's `cssText`)

I'm all for anything like any of the above! 😎

-- 
GitHub Notification of comment by tomhodgins
Please view or discuss this issue at https://github.com/w3c/css-houdini-drafts/issues/1007#issuecomment-678853542 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Monday, 24 August 2020 01:04:14 UTC