stylex icon indicating copy to clipboard operation
stylex copied to clipboard

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

Open pnegahdar opened this issue 1 year ago • 2 comments

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])

pnegahdar avatar May 15 '24 04:05 pnegahdar

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");
}

zaydek avatar Jun 06 '24 09:06 zaydek

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

nmn avatar Jun 07 '24 21:06 nmn