How to get font with mix font style in Figma Plugin. Error Cannot unwrap symbol

221 Views Asked by At

I'm trying to get font from a selected element and when an element with mix font styles is selected it gives me an error.

figma_app.min.js.br:5 Error: in postMessage: Cannot unwrap symbol at (PLUGIN_477_SOURCE:26)

The frame selection code is:

figma.on("selectionchange", () => {
  const selectedNodes = figma.currentPage.selection;

  if (selectedNodes && selectedNodes.length > 0) {
    const fontsInSelection = getFontsFromSelection(selectedNodes);
    figma.ui.postMessage({ type: "fontList", fonts: fontsInSelection });
  } else {
    figma.ui.postMessage({ type: "noElementSelected" });
  }
});

and I'm trying to get font with this code:

function getFontsFromSelection(selection: ReadonlyArray<SceneNode>) {
  const fontsMap = new Map();

  function processNode(node: SceneNode) {
    if (node.type === "TEXT") {
      const font = node.fontName as FontName;
      const fontFamily = font ? font.family : "";
      const fontStyle = font ? font.style : "";
      const fontWeight = node.fontWeight || "";

      if (!fontsMap.has(fontFamily)) {
        fontsMap.set(fontFamily, new Set());
      }

      const stylesSet = fontsMap.get(fontFamily);
      stylesSet.add({ style: fontStyle, weight: fontWeight });
    } else if (node.type === "GROUP" || node.type === "FRAME") {
      for (const childNode of (node as GroupNode | FrameNode).children) {
        processNode(childNode);
      }
    }
  }

  for (const node of selection) {
    processNode(node);
  }

  const fonts = [];

  for (const [fontFamily, fontStyles] of fontsMap) {
    fonts.push({ family: fontFamily, styles: Array.from(fontStyles) });
  }

  return fonts;
}
1

There are 1 best solutions below

0
On

You can get fontName of each character like this:

for (let i = 0; i < textNode.characters.length; i++) {
    const char = textNode.characters[i];
    const fontName = textNode.getRangeFontName(i, i + 1) as FontName;
}