首页
/ Novu 仓库 figma-use 技能:Figma Plugin API 全表面索引与 use_figma 脚本编写指南

Novu 仓库 figma-use 技能:Figma Plugin API 全表面索引与 use_figma 脚本编写指南

2026-09-05 16:02:42作者:翟萌耘Ralph

本文基于 Novu 仓库中 figma-use 技能自带的参考文档 plugin-api-standalone.index.md,系统讲解 Figma Plugin API 的完整表面:figma.* 主入口、VariablesAPI 变量系统、节点类型与 Mixin 组合模型、Paint/Effect/排版/几何等核心数据类型,以及 use_figma 工具在此之上扩展的 node.query()node.set()node.screenshot() 等高效 API。读完后你能够独立完成:查阅索引定位任意 Plugin API 符号、编写可运行的 Figma 插件脚本(含自动布局、变量绑定、字体加载),并掌握索引中标注的每一处"必须/禁止"类陷阱。

一、这份索引在 figma-use 技能中的定位

SKILL.md 定义了仓库中 figma-use 技能的工作方式:通过 use_figma 工具在 Figma 文件上下文中执行 JavaScript。技能文档明确要求——"在开始之前,先加载 plugin-api-standalone.index.md 理解能力边界;当你需要编写 Plugin API 代码时,用这份索引去 grep 完整类型定义文件 plugin-api-standalone.d.ts"。

两个文件的分工是清晰的:

文件 作用 使用方式
plugin-api-standalone.index.md 全 API 表面的符号索引,按主题分组列出接口、方法与关键陷阱 全文加载,快速定位"有没有这个能力"
plugin-api-standalone.d.ts 完整类型定义文件(当前仓库中为 11,428 行,文件头注明它源自官方 @figma/plugin-typings,自动生成、不要直接修改) 文件太大,不要整份加载,按符号名 grep 精确段落

索引文件给出了标准的定位手法(对应 All Symbols 一节的建议):

grep -n "^interface Foo\|^type Foo\|^declare type Foo" plugin-api-standalone.d.ts

也就是说,这份索引的价值在于把上万行类型定义压缩成一张"符号地图":每个符号名、它的接口名、以及它在 .d.ts 中的行号区间,让你在写脚本前就能确认 API 的确切签名和返回类型。

二、figma.* 主入口(PluginAPI)

figma.* 是脚本能触达 Figma 文档的唯一入口。索引将其划分为六个功能区,以下完整继承索引中的成员表,并结合 .d.ts 补充了实现细节。

2.1 身份与状态(Identity & State)

成员 类型 说明
apiVersion '1.0.0' 只读 API 版本
editorType 'figma' | 'figjam' | 'dev' | 'slides' | 'buzz' 当前编辑器类型;use_figma 默认工作在 figma 设计模式
mode 'default' | 'textreview' | 'inspect' | 'codegen' | 'linkpreview' | 'auth' 运行上下文
fileKey string | undefined 当前文件 key
root DocumentNode 文档根节点
currentPage PageNode 只读。同步赋值 figma.currentPage = page 不生效并会抛出 "Setting figma.currentPage is not supported",必须改用 await figma.setCurrentPageAsync(page)
currentUser User | null 当前用户
mixed unique symbol 选中集存在混合值时的哨兵值
skipInvisibleInstanceChildren boolean 是否跳过不可见的实例子节点

.d.tsPluginAPI 接口定义在第 24 行(plugin-api-standalone.d.ts#L24),文件末尾(L11413)还有一个用于扩展声明合并的重复 interface PluginAPI——这正是 use_figma 扩展 API(见第七节)的挂载点。

2.2 导航与查找(Navigation & Lookup)

方法 返回 备注
setCurrentPageAsync(page) Promise<void> 唯一可用的页面切换方式;切换同时会加载该页内容(页面是增量加载的)
getNodeByIdAsync(id) Promise<BaseNode | null> 异步按 ID 取节点
getNodeById(id) BaseNode | null 同步版本
getStyleByIdAsync(id) Promise<BaseStyle | null> 异步按 ID 取样式
getStyleById(id) BaseStyle | null 同步版本

setCurrentPageAsync.d.ts 中位于 L472,其文档注释明确写道:当 manifest 声明 "documentAccess": "dynamic-page"currentPage 为只读属性,必须用该异步方法更新。SKILL.md 进一步强调:每次 use_figma 调用的 figma.currentPage 都会重置到第一个页面,跨多次调用的工作流必须在每个脚本开头重新切页。

2.3 节点创建(Create Nodes)

索引列出了全部创建方法:

方法 返回
createFrame() FrameNode
createAutoLayout(direction?) FrameNode
createComponent() / createComponentFromNode(node) ComponentNode
createRectangle() / createEllipse() / createLine() / createPolygon() / createStar() 对应形状节点
createVector() VectorNode
createText() TextNode
createSection() / createPage() / createSlice() 页面结构节点
createBooleanOperation() BooleanOperationNode
createTable(rows?, cols?) TableNode
createImage(data: Uint8Array) Image
createNodeFromSvg(svg) FrameNode
createNodeFromJSXAsync(jsx) Promise<SceneNode>
importComponentByKeyAsync(key) Promise<ComponentNode>
importComponentSetByKeyAsync(key) Promise<ComponentSetNode>
importStyleByKeyAsync(key) Promise<BaseStyle>

其中 createAutoLayout.d.ts 中定义于 L1093SKILL.md 把它列为"高效 API"之首:任何需要自动布局的容器都优先用它,因为创建出来的 Frame 已开启自动布局且两个轴都 HUG 内容,等价于手动依次设置 layoutModeprimaryAxisSizingModecounterAxisSizingModelayoutSizingHorizontal/Vertical

// 冗长写法,容易搞错顺序
const frame = figma.createFrame()
frame.layoutMode = 'VERTICAL'
frame.primaryAxisSizingMode = 'AUTO'
frame.counterAxisSizingMode = 'AUTO'
frame.layoutSizingHorizontal = 'HUG'
frame.layoutSizingVertical = 'HUG'

// 推荐写法:一次调用,布局就绪
const frame = figma.createAutoLayout('VERTICAL')
// 也支持传 props 对象
figma.createAutoLayout({ name: 'Card', itemSpacing: 12 })               // HORIZONTAL + props
figma.createAutoLayout('VERTICAL', { name: 'Column', itemSpacing: 8 })  // VERTICAL + props

2.4 本地样式、字体与生命周期

样式(Local Styles)createPaintStyle() / createTextStyle() / createEffectStyle() / createGridStyle() 分别创建四种本地样式;对应的 getLocal*Styles()getLocal*StylesAsync() 用于列举。

字体(Fonts)

方法 说明
loadFontAsync(fontName) 在任何文本编辑前必须调用.d.tsL1625)注明加载结果有缓存,重复加载同一字体不会重新读盘
listAvailableFontsAsync() Promise<Font[]>,用于发现可用字体与确切 style 名(如 "Semi Bold" 而非猜测的 "SemiBold"
hasMissingFont boolean,文档是否存在缺失字体

插件生命周期(Lifecycle)

方法 说明
closePlugin(message?) 自动调用;use_figma 中应改用 return 把结果传回
closePluginWithFailure(message?) 出错时自动调用,不要手动调
commitUndo() / triggerUndo() 写入/回滚撤销历史快照
saveVersionHistoryAsync(title, desc?) Promise<VersionHistoryResult>
notify(message, options?) use_figma 中会抛出 "not implemented",禁用;输出走 return
openExternal(url) 在浏览器打开 URL

2.5 子 API(Sub-APIs)

figma 上挂着一组子 API,索引给出了各自的接口名与 .d.ts 行号(行号以索引编制版本为准,当前文件中实际位置略有偏移,以下给出已核实的实际行号):

属性 接口 已核实的 .d.ts 定义位置
figma.variables VariablesAPI L2042
figma.clientStorage ClientStorageAPI L2557
figma.ui UIAPI L2630
figma.util UtilAPI L2717
figma.viewport ViewportAPI L3112
figma.constants ConstantsAPI 索引标注 L2809
figma.parameters ParametersAPI 索引标注 L3292
figma.teamLibrary TeamLibraryAPI 索引标注 L2372
figma.annotations AnnotationsAPI 索引标注 L2187
figma.codegen CodegenAPI 索引标注 L2871
figma.textreview? / figma.payments? / figma.buzz / figma.timer? 对应接口 部分为 FigJam/Slides 或实验性能力

各子 API 的核心表面(索引 "Key Sub-API Surfaces" 一节):

  • ClientStorageAPIgetAsync(key)setAsync(key, value)keysAsync()deleteAsync(key) —— 插件私有键值存储;
  • ViewportAPIcenter: Vectorzoom: numberscrollAndZoomIntoView(nodes)bounds: Rect
  • UtilAPIsolidPaint(hex, opacity?)rgba(r,g,b,a?)rgb(r,g,b)colorToHex(color)loadImageAsync(url)clone(val) —— 注意 figma.util.solidPaint 接受 hex 字符串,而手写 SolidPaint 对象时 color 必须是 0–1 的 {r,g,b}
  • TeamLibraryAPIgetAvailableLibraryVariableCollectionsAsync()importVariableByKeyAsync(key)
  • ImagehashgetBytesAsync()getSizeAsync()

三、VariablesAPI:变量系统的完整模型

Figma 变量(设计 Token 的载体)由 VariableVariableCollectionVariableAlias 三类对象构成,VariablesAPIL2042)提供全部读写能力。

3.1 方法与返回

getVariableByIdAsync(id)                 Promise<Variable | null>    ← 推荐;同步版已废弃
getVariableCollectionByIdAsync(id)       Promise<VariableCollection | null>  ← 推荐;同步版已废弃
getLocalVariablesAsync(type?)            Promise<Variable[]>         ← 推荐;可按 VariableResolvedDataType 过滤
getLocalVariableCollectionsAsync()       Promise<VariableCollection[]>       ← 推荐
createVariable(name, collection, type)   Variable
createVariableCollection(name)           VariableCollection
createVariableAlias(variable)           VariableAlias
importVariableByKeyAsync(key)            Promise<Variable>
setBoundVariableForPaint(paint, field, variable)   → 返回【新的】paint,必须重新赋值
setBoundVariableForEffect(effect, field, variable) → 返回【新的】effect,必须重新赋值
setBoundVariableForLayoutGrid(grid, field, variable)

setBoundVariableForPaint.d.ts 中定义于 L2157。"返回新对象"意味着这是纯函数式 API——索引将其列为 CRITICAL 级注意事项:

// 错误:忽略了返回值,绑定不生效
figma.variables.setBoundVariableForPaint(paint, 'color', variable)

// 正确:捕获返回的新 paint 并重新赋值给 fills
const newPaints = node.fills.map((p) =>
  p.type === 'SOLID' ? figma.variables.setBoundVariableForPaint(p, 'color', variable) : p
)
node.fills = newPaints

SKILL.md 的规则 10 与之对应:"setBoundVariableForPaint returns a NEW paint — must capture and reassign"。

3.2 对象模型

Variable.d.ts 中实际位于 L10230):nameresolvedTypecodeSyntaxscopeshiddenFromPublishingvaluesByModevariableCollectionId,方法有:

  • setVariableCodeSyntax(platform, value),platform 取 'WEB' | 'ANDROID' | 'iOS'(即 CodeSyntaxPlatform);
  • setValueForMode(collectionId, modeId, value)
  • remove()

VariableCollection(实际位于 L10444):namemodesvariableIdsdefaultModeIdhiddenFromPublishing;方法有 addMode(name) → 返回 modeIdremoveMode(modeId)renameMode(modeId, name)

与变量绑定相关的类型族(索引 "Variables & Bindings" 一节)值得单独记住:

类型 说明
VariableValue boolean | string | number | RGB | RGBA | VariableAlias
VariableResolvedDataType 'BOOLEAN' | 'COLOR' | 'FLOAT' | 'STRING'L10197,已核实)
VariableDataType 额外包含 'VARIABLE_ALIAS' | 'EXPRESSION'
VariableScope 变量可作用到的范围(如 FRAME_FILLTEXT_FILLGAP
VariableBindablePaintField 'color'
VariableBindableEffectField 'color' | 'radius' | 'spread' | 'offsetX' | 'offsetY'
VariableBindableNodeField / VariableBindableTextField 节点/文本上可绑定变量的字段

SKILL.md 规则 16 强调:创建变量时必须显式设置 variable.scopes,默认的 ALL_SCOPES 会污染每一个属性选择器。完整的 scope 清单与发现已有变量的模式见 variable-patterns.md

3.3 发现现有变量集合的惯用脚本

SKILL.md "Discover Conventions Before Creating" 一节给出的检查脚本,正是 VariablesAPI 的典型用法:

const collections = await figma.variables.getLocalVariableCollectionsAsync();
const results = collections.map((c) => ({
  name: c.name,
  id: c.id,
  varCount: c.variableIds.length,
  modes: c.modes.map((m) => m.name),
}));
return results;

四、节点类型系统与 Mixin 组合

4.1 具体场景节点

节点 索引标注行号 关键特征
DocumentNode L8960 根节点;children: PageNode[]
PageNode L9119(实际 L9145 children、本地样式、backgrounds
FrameNode L9311(实际 L9337extends DefaultFrameMixin,已核实) 自动布局、裁剪、子节点
GroupNode L9321 仅子节点,无自动布局
ComponentNode L9678 类似 Frame 且可发布
ComponentSetNode L9653 变体集合容器
InstanceNode L9719 类似 Frame;mainComponentdetach()
RectangleNode / EllipseNode / LineNode / PolygonNode / StarNode / VectorNode L9378–L9476 DefaultShapeMixin;Ellipse 另有 arcData
TextNode L9493(实际 L9519 富文本、字体、segments
TextPathNode L9564 沿路径排布的文字
BooleanOperationNode L9792 booleanOperation 属性
SliceNode L9368 仅用于导出
SectionNode L10754 分组 + 填充
TableNode L9862 子节点为 TableCellNode

按编辑器划分的专属节点(与 SKILL.md 第 4 节的"Editor Mode"允许/禁止清单互相印证):

  • FigJam 专属StickyNodeConnectorNodeShapeWithTextNodeStampNodeCodeBlockNodeEmbedNodeLinkUnfurlNodeMediaNode
  • Slides 专属SlideNodeSlideRowNodeSlideGridNode

联合类型(均已核实实际行号):

// [L10953](https://gitcode.com/GitHub_Trending/no/novu/blob/7a36cd2640b04df115b8443e684667709e60cb08/.agents/skills/figma-use/references/plugin-api-standalone.d.ts?utm_source=gitcode_repo_files#L10953)
type SceneNode = FrameNode | GroupNode | SliceNode | RectangleNode | LineNode
  | EllipseNode | PolygonNode | StarNode | VectorNode | TextNode | ComponentSetNode
  | ComponentNode | InstanceNode | BooleanOperationNode | SectionNode | ...

// [L10949](https://gitcode.com/GitHub_Trending/no/novu/blob/7a36cd2640b04df115b8443e684667709e60cb08/.agents/skills/figma-use/references/plugin-api-standalone.d.ts?utm_source=gitcode_repo_files#L10949)
type BaseNode = DocumentNode | PageNode | SceneNode

4.2 Mixin 组合模型

Figma 的节点类型不是经典继承树,而是 Mixin 接口组合——这是理解"某节点上有哪些属性"的关键。索引 "Mixin Interfaces" 一节给出了完整清单:

Mixin 提供能力
BaseNodeMixin idnametypeparentremove()、plugin data
SceneNodeMixin visiblelockedopacity、变量绑定
ChildrenMixin childrenappendChild()insertChild()findAll()findOne()findAllWithCriteria()
LayoutMixin xywidthheightrotationresize()rescale()
AutoLayoutMixin layoutMode、主轴/交叉轴对齐、padding、itemSpacinglayoutSizingHorizontal/Vertical
AutoLayoutChildrenMixin layoutAlignlayoutGrow、sizing —— 必须在 appendChild() 之后设置
GridLayoutMixin / GridChildrenMixin CSS Grid 轨道、gap、模板;网格子节点定位
GeometryMixin fillsstrokesstrokeWeightstrokeAlign
MinimalFillsMixin / MinimalStrokesMixin 仅提供 fills / strokesstrokeWeight
BlendMixin opacityblendModeisMaskeffects
CornerMixin / RectangleCornerMixin cornerRadiuscornerSmoothing;逐角圆角
ExportMixin exportSettingsexportAsync()
ReactionMixin reactions(原型交互)
PublishableMixin descriptionkeygetPublishStatusAsync()
VariantMixin / ComponentPropertiesMixin variantPropertiescomponentPropertiesaddComponentProperty()
PluginDataMixin getSharedPluginData() / setSharedPluginData() 受支持getPluginData() / setPluginData()use_figma不受支持
FramePrototypingMixin overflowDirectionnumberOfFixedChildren
ExplicitVariableModesMixin setExplicitVariableModeForCollection()

组合关系上(索引 "DefaultFrameMixin / DefaultShapeMixin" 两行):

  • BaseFrameMixin = ChildrenMixin + LayoutMixin + AutoLayoutMixin + GeometryMixin + …
  • DefaultFrameMixin = BaseFrameMixin + FramePrototypingMixin + ReactionMixin(FrameNodeextends DefaultFrameMixin,从 .d.ts L9337 可直接验证);
  • DefaultShapeMixin = BlendMixin + GeometryMixin + LayoutMixin + ExportMixin + ReactionMixin。

PluginDataMixin 的取舍对脚本实践有直接影响:.d.ts L5499 处定义了 getSharedPluginData(namespace, key)getSharedPluginDataKeys(namespace)SKILL.md 规则 3a 说明 use_figma 只支持 shared 版本,替代方案是把节点 ID 通过 return 传回、在后续调用中以字符串字面量传入。

五、Paint、Effect 与排版类型

5.1 Paint 与 Fill

类型 关键属性
SolidPaint(实际 L4328 type: 'SOLID'color: RGBopacityvisibleblendMode
GradientPaintL4383 type: 'GRADIENT_LINEAR'|'RADIAL'|'ANGULAR'|'DIAMOND'gradientStops: ColorStop[]
ImagePaint type: 'IMAGE'imageHashscaleMode
VideoPaint / PatternPaint type: 'VIDEO' / type: 'PATTERN'
PaintL4507 以上五者的联合
ColorStop { position: number, color: RGBA }
ImageFilters exposure、contrast、saturation 等

索引用 CRITICAL 标注了两条铁律,也是 SKILL.md 规则 6 与 7 的内容:

  1. 颜色是 0–1 范围,不是 0–255{r: 1, g: 0, b: 0} 才是红色;
  2. fills/strokes 是只读数组 —— 必须 clone、modify、reassign,原地修改不生效。
// 正确的改色姿势:新数组 + 新 paint 对象,整体重新赋值
node.fills = [{ type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.8 }, opacity: 1 }]
// 注意:SOLID 的 color 对象只有 {r, g, b},透明度放在 paint 层的 opacity 字段

5.2 Effect 与 Typography

Effect 族DropShadowEffect.d.ts 实际 L3992)、InnerShadowEffectBlurEffect(Normal/Progressive)、NoiseEffect(Mono/Duo/Multitone)、TextureEffectGlassEffect,联合类型 Effect

排版类型

类型 说明
FontNameL3723 { family: string, style: string }
TextNode characterstextAlignHorizontalfontSizefontNamegetStyledTextSegments()
StyledTextSegment 按文本范围设置属性
LetterSpacing { value, unit: 'PIXELS'|'PERCENT' } —— 不是裸数字
LineHeight { value, unit } | { unit: 'AUTO' } —— 同样必须带 unit
TextCase 'ORIGINAL'|'UPPER'|'LOWER'|'TITLE'|'SMALL_CAPS'
TextDecoration 'NONE'|'UNDERLINE'|'STRIKETHROUGH'
OpenTypeFeature 连字、数字样式等

排版操作的硬前置条件是字体加载(SKILL.md 规则 8,比常见认知更严格):只要文档中存在含未加载字体的文本节点,任何触碰它的操作都要先预加载字体——不只是 characters 赋值,还包括 appendChildinsertChildsetBoundVariablesetValueForMode 甚至 findAll 的回调。标准模式:先 await figma.listAvailableFontsAsync() 确认可用字体与确切 style 名,再对每个用到的字体 await figma.loadFontAsync({ family, style })。完整的 WRONG/CORRECT 对照见 gotchas.md

六、Primitives、Prototyping、Events 与 Export

Primitives & Geometry(索引 "Primitives & Geometry" 一节):

类型 形状
Vector { x, y }
Rect { x, y, width, height }
RGB / RGBA { r, g, b } / { r, g, b, a } —— 0–1 范围
Transform [[a,b,tx],[c,d,ty]] 2×3 仿射矩阵
ArcData { startingAngle, endingAngle, innerRadius }
Constraints / ConstraintType { horizontal, vertical };取值 'MIN'|'CENTER'|'MAX'|'STRETCH'|'SCALE'
VectorPath / VectorNetwork { windingRule, data };vertices + segments + regions
Guide { axis, offset }

PrototypingReaction = trigger + action 对;Trigger(谁触发)、Action(发生什么)、TransitionSimpleTransition \| DirectionalTransition)、EasingNavigation'NAVIGATE'\|'SWAP'\|'OVERLAY'\|'SCROLL_TO'\|'CHANGE_TO')、OverflowDirection'NONE'\|'HORIZONTAL'\|'VERTICAL'\|'BOTH')、OverlayPositionType

Events & ChangesArgFreeEventType.d.ts L11,含 'selectionchange''currentpagechange''close' 与 timer 系列)、RunEventDropEventDocumentChangeEventNodeChangeEventNodeChangeProperty(所有可监听的属性名)、StyleChangeEventDocumentChangeCreateChange | DeleteChange | PropertyChange)、TextReviewEvent

ExportExportSettingsImage(PNG/JPG/WEBP/BMP)、ExportSettingsSVGExportSettingsPDFExportSettingsREST,约束类型 ExportSettingsConstraints{ type: 'SCALE'\|'WIDTH'\|'HEIGHT', value },配合 ExportMixinexportSettings / exportAsync() 使用。

七、use_figma 扩展 API:query / set / screenshot

索引最后 "Additional APIs (available via use_figma)" 一节列出了不是官方 Plugin API、而是 use_figma 运行时注入的增强能力。这些 API 依赖文件末尾的 PluginAPI 声明合并扩展点,能大幅压缩脚本样板代码。

7.1 节点方法

方法 / 属性 返回 / 类型 说明
node.query(selector) QueryResult 在子树内做 CSS 风格选择器搜索
node.matches(selector) boolean 测试节点是否匹配选择器
node.set(props) this 一次批量设置多个属性,可链式调用
await node.screenshot(opts?) Promise<void> 将节点截图内联返回到工具响应中
node.placeholder boolean 显示/隐藏"AI 进行中"的微光遮罩

7.2 figma.io 命名空间

方法 返回 说明
figma.io.write(path, data) void 把图片/数据写入,随后在工具响应中返回

7.3 配套类型

  • QueryResult:可迭代,提供 .first().last().each().map().filter().values().set().query()
  • ScreenshotOptions{ scale?: number, contentsOnly?: boolean }

SKILL.md 第 5 节给了 query 选择器语法的完整说明与对比示例:

// 冗长的遍历写法
const texts = frame.findAll((n) => n.type === 'TEXT' && n.name === 'Title')

// query 一行搞定
const texts = frame.query('TEXT[name=Title]')

选择器支持:类型名(FRAMETEXT 等,大小写不敏感)、属性精确/子串/前后缀匹配([name*=art])、点路径与通配下标([fills.0.type=SOLID][fills.*.type=SOLID])、实例匹配([mainComponent=nodeId])、组合符(>、空格、+~)、伪类(:first-child:nth-child(2):not():is())、节点 ID(#nodeId)、逗号联合与通配 *。作用域是该节点的子树;想搜整页用 figma.currentPage.query('...')(没有全局 figma.query())。

典型批量修改:

// 把所有以 Card 开头的 FRAME 内的 TEXT 统一改色
figma.currentPage.query('FRAME[name^=Card] TEXT').set({
  fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.8 } }],
})

// 提取所有 FRAME 的名称与坐标
return figma.currentPage.query('FRAME').values(['name', 'x', 'y'])

node.set(props) 有两个内部约定(来自 SKILL.md):layoutMode 无论 key 顺序如何都先于其他属性应用,避免 resize() 行为随 layoutMode 设置顺序漂移;width/height 会自动路由到 node.resize()

node.screenshot() 默认 0.5x 缩放且自动把最大边限制在 1024px 内;{ scale: N } 可绕过上限,contentsOnly: false 可包含兄弟节点的重叠内容。图片标题自带节点元数据(如 "Card (300x150 at 0,60).png"),便于在同一次调用里"写后验证"。placeholder 用于多步构建时的进度反馈,SKILL.md 要求完成后必须置回 false,不留残留遮罩。

八、把索引落到脚本上:关键约束清单

索引文件通篇以"MUST / do not"标注了十余处易错点。结合 SKILL.md 的 Critical Rules 与 validation-and-recovery.md 的恢复流程,可以归纳为以下可核查清单:

  1. 输出走 return:返回值被自动 JSON 序列化;不调 figma.closePlugin(),不包 async IIFE,不用 console.log()figma.notify()use_figma 中会抛 "not implemented"。
  2. 原子性use_figma 脚本失败即整体不执行,文件保持原状。出错时先停、读错误、用 get_metadata/get_screenshot 确认状态,修好再重试,而不是盲目重跑。
  3. 切页只用 await figma.setCurrentPageAsync(page);且每次调用后 figma.currentPage 重置到第一页,跨调用工作流每次都要重新切页。
  4. 字体先行loadFontAsync 覆盖文档中既有文本用到的所有字体,不只是要编辑的那个节点。
  5. 只读数组语义:fills/strokes 克隆后整体重新赋值;setBoundVariableForPaint/Effect 的返回值必须接住。
  6. 顺序敏感layoutSizingHorizontal/Vertical = 'FILL' 必须在 parent.appendChild(child) 之后设置,否则抛错;resize() 会重置 sizing mode 为 FIXED,先 resize 再设 sizing。
  7. 位置与规模:新建页级节点避开 (0,0)(扫描 figma.currentPage.children 找空位);每次 use_figma 至多 10 个逻辑操作,增量构建、逐步验证。
  8. 必须 return 所有创建/变更过的节点 ID(如 return { createdNodeIds: [...], mutatedNodeIds: [...] }),后续调用以字符串字面量引用它们。
  9. 所有 Promise 都要 await——未 await 的 loadFontAsync/setCurrentPageAsync 等会造成静默失败与竞态。
  10. 创建变量显式设置 scopes,不要依赖 ALL_SCOPES 默认值。

常见的"错误信息 → 根因 → 修复"映射(摘自 SKILL.md 第 7 节)也值得随索引一起备查:"not implemented" → 误用了 figma.notify()"node must be an auto-layout frame..." → FILL/HUG 提前于 appendChild;"Setting figma.currentPage is not supported" → 用了同步切页;颜色越界 → 用了 0–255 值域;"The node with id X does not exist" → 父实例被 detachInstance() 隐式脱离导致 ID 变化,应改从稳定的非实例父节点重新遍历。

九、索引的完整符号表与使用路径

索引 "All Symbols (flat)" 一节是一张扁平符号总表,覆盖:15 个 API 接口(PluginAPIVariablesAPIUIAPIUtilAPIViewportAPIClientStorageAPIConstantsAPICodegenAPIPaymentsAPITextReviewAPIParametersAPITimerAPIBuzzAPIDevResourcesAPIAnnotationsAPITeamLibraryAPI)、全部具体节点(含 FigJam/Slides 专属与 WidgetNodeHighlightNodeWashiTapeNode 等扩展节点)、约 40 个 Mixin、变量族、Paint/Effect/Style 族、排版族、几何族、原型交互族、事件族、导出族及 UserImageVersionHistoryResultFindAllCriteria 等辅助类型。

实际使用路径建议(与 SKILL.md 第 10 节的参考文档表一致):

  1. 先查索引:本文件定位"这个能力存在吗、接口叫什么、签名是什么";
  2. 再 grep 类型定义:对 plugin-api-standalone.d.ts 执行 grep -n "^interface FrameNode" 之类的精确搜索,只读命中的片段,不整份加载;
  3. 需要可运行代码时,转 common-patterns.md(脚本脚手架)、plugin-api-patterns.md(fills/strokes/自动布局/效果)、component-patterns.md(组件与变体)、variable-patterns.md(集合、模式、作用域、别名与绑定)、text-style-patterns.mdeffect-style-patterns.md(样式创建与应用);
  4. 写之前过一遍 gotchas.md 的 WRONG/CORRECT 对照与本文第八节的清单;
  5. 多步写入与出错后validation-and-recovery.mdget_metadata/get_screenshot 双通道验证流程走。

需要说明的前提:该索引中的 L# 行号以其编制时的 .d.ts 版本(11,292 行)为准,而当前仓库中的 plugin-api-standalone.d.ts 已增长到 11,428 行(文件头声明其源自官方 @figma/plugin-typings 自动生成),因此个别行号会有偏移;本文正文中已核实的行号以实际文件为准,未核实的仍以索引标注值列出。这不影响索引的主用途——按符号名 grep 永远有效。

登录后查看全文
热门项目推荐
相关项目推荐