theme-toggles icon indicating copy to clipboard operation
theme-toggles copied to clipboard

dyamic ID babel plugin breaks hex colours

Open G1itcher opened this issue 1 year ago • 1 comments

your babel/svgr plugin for dynamic IDs overwrites hex colour values. I don't have time to do a full PR so here's the fix:

const t = require("@babel/core").types;
const template = require("@babel/core").template;

const getValueWithProps = (value, { prefix, suffix }) =>
  `${prefix ? "${props.idPrefix || ''}" : ""}${value}${
    suffix ? "${props.idSuffix || ''}" : ""
  }`;

const isHexValue = (possibleHexValue) => {
  return (
    possibleHexValue[0] === "#" &&
    !isNaN(parseInt(possibleHexValue.slice(1), 16))
  );
};

const getAttributeValue = (value, opts) => {
  let id = "";
  let prefix = "";
  let suffix = "";
  if (value && !isHexValue(value) && value.charAt(0) === "#") {
    id = value.slice(1);
    prefix = "#";
  } else if (value && value.match(/^url\(#/)) {
    id = value.slice(5, -1);
    prefix = "url(#";
    suffix = ")";
  }
  if (id) {
    return t.jsxExpressionContainer(
      template.ast(`\`${prefix}${getValueWithProps(id, opts)}${suffix}\``)
        .expression,
    );
  }
};

const getIdValue = (value, opts) =>
  t.jsxExpressionContainer(
    template.ast(`\`${getValueWithProps(value, opts)}\``).expression,
  );

const plugin = (api, opts) => ({
  visitor: {
    JSXAttribute(path) {
      if (!opts.prefix && !opts.suffix) return;

      const valuePath = path.get("value");
      const namePath = path.get("name");

      const value = valuePath?.container?.value?.value;
      const name = namePath?.container?.name?.name;

      if (name === "id") {
        valuePath.replaceWith(getIdValue(value, opts));
      } else {
        const attr = getAttributeValue(value, opts);
        if (attr) {
          valuePath.replaceWith(attr);
        }
      }
    },
  },
});

module.exports = plugin;

G1itcher avatar Jul 14 '23 11:07 G1itcher

Thanks, this shouldn't be an issue with my current use of the plugin but it would be great to get it in when I have the chance. I don't think this solution is 100% perfect since it could in theory pick up id's which are of a hex format whilst not being colors. Although it's much better than what I have currently

AlfieJones avatar Aug 29 '23 23:08 AlfieJones