Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

1.3 KB
Raw Blame
import { decode } from "html-entities";

// JSX uses XML numeric references and requires lowercase x for hexadecimal references.
export function decodeJsxText(text) {
  return text.replace(
    /&(?:#(\d+)|#x([\da-fA-F]+)|([a-zA-Z][a-zA-Z0-9]*));/g,
    (entity, decimal, hexadecimal, named) => {
      if (named) return decode(entity, { level: "html4", scope: "strict" });
      const codePoint = Number.parseInt(
        decimal ?? hexadecimal,
        decimal ? 10 : 16,
      );
      return codePoint <= 0x10ffff ? String.fromCodePoint(codePoint) : entity;
    },
  );
}

// Translation rules expect decoded JSX text.
// Oxlint exposes the source spelling.
export function withDecodedJsxText(plugin) {
  const rule = plugin.rules["no-literal-string"];
  return {
    ...plugin,
    rules: {
      ...plugin.rules,
      "no-literal-string": {
        ...rule,
        create(context) {
          const visitors = rule.create(context);
          return {
            ...visitors,
            JSXText(node) {
              const value = decodeJsxText(node.value);
              return visitors.JSXText(
                value === node.value
                  ? node
                  : Object.create(node, { value: { value } }),
              );
            },
          };
        },
      },
    },
  };
}