Advertisement
loginblogin

Untitled

Apr 9th, 2025 (edited)
541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function replaceTextPreservingFullStyle(textNode: TextNode, newText: string) {
  2.   if (textNode.characters.length === 0) return;
  3.  
  4.   const fontName = textNode.getRangeFontName(0, 1) as FontName;
  5.   const fontSize = textNode.getRangeFontSize(0, 1) as number;
  6.   const styleId = textNode.getRangeTextStyleId(0, 1);
  7.   const fills = textNode.getRangeFills(0, 1);
  8.  
  9.   await figma.loadFontAsync(fontName);
  10.  
  11.   // Сохраняем цвет, только если он переопределён вручную
  12.   const customFill = fills !== figma.mixed ? (fills as Paint[]) : null;
  13.  
  14.   // Заменяем текст
  15.   textNode.characters = newText;
  16.  
  17.   // Применяем стиль, если был
  18.   if (styleId && styleId !== figma.mixed && styleId !== "") {
  19.     await textNode.setRangeTextStyleIdAsync(0, newText.length, styleId as string);
  20.   } else {
  21.     // Иначе применяем вручную всё
  22.     textNode.setRangeFontName(0, newText.length, fontName);
  23.     textNode.setRangeFontSize(0, newText.length, fontSize);
  24.   }
  25.  
  26.   // Если цвет был переопределён вручную — применим его обратно
  27.   if (customFill) {
  28.     textNode.setRangeFills(0, newText.length, customFill);
  29.   }
  30. }
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement