facebook / stylex

StyleX is the styling system for ambitious user interfaces.
https://stylexjs.com
MIT License
8.21k stars 304 forks source link

How to capture var values for third-party library styling? #571

Open pnegahdar opened 1 month ago

pnegahdar commented 1 month ago

I use highlightjs in a project and I want to use a different themes depending on a what a var is set to. Binding it to a theme makes sense to me -- i.e I could do it other ways but this seems like the right coupling.

I was wondering if you all head a way of grabbing a var value?

I ended up writing this garbage to set the theme, which gets the job done (though it isn't reactive, but I guess I could add a mutation observer), but is there a better way? useVarValue() would be nice.

    const themeVar = theme.editorTheme.slice(4, -1); // gets the inner --varname
    // hack to get themes in here. I need to find a better way in the future.
    useEffect(() => {
        if (!selfElem.current) return
        const value = getComputedStyle(selfElem.current).getPropertyValue(themeVar)
        setThemeValue(value)
    }, [themeVar, setThemeValue])
zaydek commented 3 weeks ago

FWIW I wrote basically the same code today:

  const [color, setColor] = useState<Color | null>(null);

  const once = useRef(false);
  useEffect(() => {
    if (!once.current) {
      once.current = true;
      return;
    }
    if (color !== null) {
      document.body.style.setProperty(unvar(vars.colorTrim), colorMap[color]);
    }
  }, [color]);
// unvar removes the var() function from a string.
export function unvar(str: string): string {
  return str.replace(/var\(([^)]+)\)/g, "$1");
}
nmn commented 3 weeks ago

There is a pull request to allow defining stylex variables with literal names. Would that solve your problem?

https://github.com/facebook/stylex/pull/584