figmaParser.ts 7.16 KB
import type { FigmaNodeDSL, FigmaFill, DSLResult } from './types'

/**
 * 从 Figma URL 中解析 fileKey 和 nodeId
 * 支持格式:
 *   - https://www.figma.com/design/:fileKey/:name?node-id=xxx
 *   - https://www.figma.com/file/:fileKey/:name?node-id=xxx
 */
export function parseFigmaUrl(url: string): { fileKey: string; nodeId: string | null } {
  const fileKeyMatch = url.match(/figma\.com\/(?:design|file)\/([^/?#]+)/)
  if (!fileKeyMatch) {
    throw new Error('无效的 Figma URL,无法提取 fileKey,请确认链接格式正确')
  }
  const fileKey = fileKeyMatch[1]

  const nodeIdMatch = url.match(/node-id=([^&#]+)/)
  let nodeId: string | null = null
  if (nodeIdMatch) {
    // Figma URL 中的 node-id 使用连字符,API 中使用冒号
    nodeId = decodeURIComponent(nodeIdMatch[1]).replace(/-/g, ':')
  }

  return { fileKey, nodeId }
}

/**
 * 调用 Figma REST API 拉取文件 JSON
 */
export async function fetchFigmaFile(
  fileKey: string,
  token: string,
  nodeId?: string | null
): Promise<any> {
  const baseUrl = 'https://api.figma.com/v1'
  console.log('nodeId', nodeId) 
  const url = nodeId
    ? `${baseUrl}/files/${fileKey}/nodes?ids=${encodeURIComponent(nodeId)}`
    : `${baseUrl}/files/${fileKey}`
    console.log('url', url) 

  const res = await fetch(url, {
    headers: { 'X-Figma-Token': token },
  })

  if (!res.ok) {
    const errText = await res.text()
    throw new Error(`Figma API 请求失败 (HTTP ${res.status}):${errText}`)
  }

  const data = await res.json()

  // 若按节点维度拉取,仅保留目标节点子树,使下游逻辑保持兼容(仍然有 document 根节点)
  if (nodeId) {
    const nodeEntry = data.nodes?.[nodeId]
    if (!nodeEntry || !nodeEntry.document) {
      throw new Error(`Figma API 返回中未找到节点(nodeId: ${nodeId})`)
    }

    return {
      name: data.name,
      document: nodeEntry.document,
    }
  }

  return data
}

/**
 * 解析用于导出的截图节点 ID(与 DSL 目标节点一致)。
 * 未指定 URL 中的 node-id 时,取首页第一个子节点(整帧/画板级预览)。
 */
export async function resolveScreenshotNodeId(
  fileKey: string,
  token: string,
  nodeId: string | null,
): Promise<string> {
  if (nodeId) return nodeId
  const figmaData = await fetchFigmaFile(fileKey, token, null)
  const node = findTargetNode(figmaData, null)
  if (!node?.id) {
    throw new Error('无法解析截图节点:文件中未找到可用节点')
  }
  return node.id
}

export type FigmaImageFormat = 'png' | 'jpg' | 'svg' | 'pdf'

/**
 * GET /v1/images/:fileKey?ids=:nodeId → 节点渲染图 URL(PNG 等)
 * 大图异步导出时 images[id] 可能短暂为 null,会做有限次重试。
 */
export async function fetchFigmaNodeImageUrl(
  fileKey: string,
  token: string,
  renderNodeId: string,
  options?: { format?: FigmaImageFormat; scale?: number },
): Promise<string> {
  const format = options?.format ?? 'png'
  const scale = options?.scale ?? 2
  const baseUrl = 'https://api.figma.com/v1'
  const query = new URLSearchParams({
    ids: renderNodeId,
    format,
    scale: String(scale),
  })
  const url = `${baseUrl}/images/${fileKey}?${query.toString()}`

  const maxAttempts = 5
  const delayMs = 1200

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const res = await fetch(url, {
      headers: { 'X-Figma-Token': token },
    })

    if (!res.ok) {
      const errText = await res.text()
      throw new Error(`Figma Images API 请求失败 (HTTP ${res.status}):${errText}`)
    }

    const data = (await res.json()) as {
      err?: string | null
      images?: Record<string, string | null>
    }

    if (data.err) {
      throw new Error(`Figma Images API:${data.err}`)
    }

    const imageUrl = data.images?.[renderNodeId]
    if (imageUrl) return imageUrl

    if (attempt < maxAttempts) {
      await new Promise(r => setTimeout(r, delayMs))
    }
  }

  throw new Error('Figma 截图尚未就绪或导出失败,请稍后重试')
}

/**
 * 将 Figma 原始节点转换为精简的 DSL 节点
 * 去除噪声字段,保留布局/尺寸/颜色/文本/圆角等关键属性
 */
function toDSLNode(node: any): FigmaNodeDSL {
  const dsl: FigmaNodeDSL = {
    id: node.id,
    name: node.name,
    type: node.type,
  }

  if (node.visible === false) dsl.visible = false

  // 尺寸和位置
  if (node.absoluteBoundingBox) {
    dsl.width = Math.round(node.absoluteBoundingBox.width)
    dsl.height = Math.round(node.absoluteBoundingBox.height)
    dsl.x = Math.round(node.absoluteBoundingBox.x)
    dsl.y = Math.round(node.absoluteBoundingBox.y)
  }

  // 文本节点
  if (node.type === 'TEXT') {
    dsl.text = node.characters ?? ''
    if (node.style) {
      dsl.textStyle = {
        fontFamily: node.style.fontFamily,
        fontSize: node.style.fontSize,
        fontWeight: node.style.fontWeight,
        lineHeightPx: node.style.lineHeightPx,
        textAlignHorizontal: node.style.textAlignHorizontal,
        letterSpacing: node.style.letterSpacing,
      }
    }
  }

  // 填充和描边
  if (node.fills?.length) dsl.fills = node.fills as FigmaFill[]
  if (node.strokes?.length) dsl.strokes = node.strokes as FigmaFill[]

  // 圆角
  if (node.rectangleCornerRadii) {
    dsl.cornerRadius = node.rectangleCornerRadii as number[]
  } else if (node.cornerRadius !== undefined) {
    dsl.cornerRadius = node.cornerRadius as number
  }

  // Auto Layout
  if (node.layoutMode && node.layoutMode !== 'NONE') {
    dsl.layoutMode = node.layoutMode
    dsl.primaryAxisAlignItems = node.primaryAxisAlignItems
    dsl.counterAxisAlignItems = node.counterAxisAlignItems
    if (node.itemSpacing) dsl.itemSpacing = node.itemSpacing

    const top = node.paddingTop
    const right = node.paddingRight
    const bottom = node.paddingBottom
    const left = node.paddingLeft
    if (top || right || bottom || left) {
      dsl.padding = { top, right, bottom, left }
    }
  }

  // 递归处理子节点
  if (node.children?.length) {
    dsl.children = node.children.map(toDSLNode)
  }

  return dsl
}

/**
 * 深度优先搜索指定 nodeId 的节点
 * 未指定 nodeId 时取首页第一个子节点
 */
function findTargetNode(figmaData: any, nodeId: string | null): any {
  const document = figmaData.document

  if (!nodeId) {
    const firstPage = document?.children?.[0]
    return firstPage?.children?.[0] ?? firstPage ?? document
  }

  function dfs(node: any): any {
    if (!node) return null
    if (node.id === nodeId) return node
    if (node.children) {
      for (const child of node.children) {
        const found = dfs(child)
        if (found) return found
      }
    }
    return null
  }

  return dfs(document)
}

/**
 * 构建完整 DSL 对象(包含 meta 信息)
 */
export function buildDSL(figmaData: any, fileKey: string, nodeId: string | null): DSLResult {
  const targetNode = findTargetNode(figmaData, nodeId)
  if (!targetNode) {
    throw new Error(`未找到目标节点(nodeId: ${nodeId ?? '自动取首个节点'}),请检查节点 ID 是否正确`)
  }

  return {
    meta: {
      figmaFileKey: fileKey,
      figmaNodeId: nodeId,
      name: figmaData.name ?? targetNode.name,
      generatedAt: new Date().toISOString(),
    },
    root: toDSLNode(targetNode),
  }
}