To ensure all fonts are loaded before accessing text node properties using the Figma REST API, you can follow these steps:
1. Fetch the text nodes: Use the "GET file nodes" endpoint to retrieve the nodes in a Figma file, including the text nodes.
javascript
const response = await axios.get(`https://api.figma.com/v1/files/FILE_KEY/nodes?ids=NODE_ID`, config);
const textNode = response.data.nodes[NODE_ID];
2. Check if the text node has any missing fonts: Use the `hasMissingFont` property to determine if the required fonts are loaded.
javascript
if (textNode.hasMissingFont) {
// Load the required fonts first
await loadMissingFonts(textNode);
}
3. Load the missing fonts: Use the `figma.loadFontAsync()` function to load the required fonts. You can do this by iterating through the unique font names used in the text node.
javascript
async function loadMissingFonts(textNode) {
const fontNames = new Set();
const len = textNode.characters.length;
// Collect the unique font names used in the text node
for (let i = 0; i < len; i++) {
const fontName = textNode.getRangeFontName(i, i + 1);
fontNames.add(JSON.stringify(fontName));
}
// Load each unique font
const fontPromises = Array.from(fontNames).map(async (fontNameStr) => {
const fontName = JSON.parse(fontNameStr);
await figma.loadFontAsync(fontName);
});
await Promise.all(fontPromises);
}
4. Access the text node properties: Now that the required fonts are loaded, you can safely access the text node properties.
javascript
console.log(textNode.fontSize);
console.log(textNode.fontName);
By following these steps, you can ensure that all the necessary fonts are loaded before attempting to access the text node properties. This will help you avoid the "Cannot write to node with unloaded font" error.
Remember to handle any errors that may occur during the font loading process, as the `figma.loadFontAsync()` function returns a Promise that can reject if the font fails to load.
Citations:[1] https://forum.figma.com/t/function-for-setting-text-and-loading-fonts/6290
[2] https://forum.figma.com/t/get-figma-fonts/4079
[3] https://www.figma.com/plugin-docs/api/TextSublayer/
[4] https://www.figma.com/plugin-docs/api/figma/
[5] https://www.figma.com/plugin-docs/api/api-errors/