Assign new String

Hi, I’m about to playing around with plugin development in Figma. I tried to change the value of a textNode on click. The values are stored in a simple array.

So I have an array and a random calc to replace the textNode with other values if button is hit again:

var names = ["John", "Elias", "Mark", "Robert", "Niels", "Andrea"];
var randomItem = names[Math.floor(Math.random() * names.length)];

here’s the html side:

<button id="runPlugin">Change Text</button>
<script>
  document.getElementById("runPlugin").onclick = () => {
    const text = document.pluginMessage.selection();
    parent.postMessage({ type: { request: "runPlugin" } }, "*");
  };
</script>

on the .ts side I’m having a bit trouble. I made sth similar in js which is working but this… :exploding_head:I know I’m doing sth really wrong in the 2nd if section…

figma.ui.onmessage = async (event) => {
  if (event.type === "request:runPlugin") {
    let selection = figma.currentPage.selection[0];
    if (selection) {
      selection = event.randomItem;
    }
    return;
  }

Any idea? Thanks!

You have problems in both ui.html and code.js.

The working code should look like this:
ui.html

<button id='runPlugin'>Change Text</button>
<script>
	document.getElementById('runPlugin').onclick = () => {
		parent.postMessage({ pluginMessage: {type: 'runPlugin'} }, '*');
	}
</script>

code.js

let names = ['John', 'Elias', 'Mark', 'Robert', 'Niels', 'Andrea'],
	selection = figma.currentPage.selection[0];

figma.showUI(__html__);
figma.ui.onmessage = async (event) => {
	let randomItem = names[Math.floor(Math.random() * names.length)];

	if (event.type === 'runPlugin' && selection.type === 'TEXT') {
		await figma.loadFontAsync(selection.fontName);
		selection.characters = randomItem;
	}
}

Please see the developer documentation:

1 Like

First of all: Thank you for your help :pray:
When I tried to implement / change it, It gave me an error in fontName. But it worked partially.

However, even if I reuse the above code, I can’t run the plugin anymore.
I get the error:

let selection: TextNode
Argument of type 'FontName | unique symbol' is not assignable to parameter of type 'FontName'.
  Type 'typeof figma.mixed' is not assignable to type 'FontName'.ts(2345)

I googled for a solution but I can’t find any.

I also tried a for loop to change multiple textNodes e.g
for (const node of figma.currentPage.selection)
Did not work.

Any clue why this is? I also got the latest typings…

Because a TextNode can contain multiple fonts, you need to know all the fonts. The getRangeAllFontNames function will help you with this.

You can see an example of loading multiple fonts here: TextNode · Figma Developers