Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dyamic ID babel plugin breaks hex colours #23

Open
G1itcher opened this issue Jul 14, 2023 · 1 comment
Open

dyamic ID babel plugin breaks hex colours #23

G1itcher opened this issue Jul 14, 2023 · 1 comment

Comments

@G1itcher
Copy link

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;
@AlfieJones
Copy link
Owner

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

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

No branches or pull requests

2 participants