click.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * adb method: click — 按坐标或变量位置点击
  3. */
  4. async function run(action, ctx) {
  5. const { device, variableContext, api, extractVarName, resolveValue } = ctx
  6. const inVars = action.inVars || []
  7. let position = inVars.length > 0 ? variableContext[extractVarName(inVars[0])] : null
  8. if (!position && action.target) position = resolveValue(action.target, variableContext)
  9. if (!position) return { success: false, error: 'click 操作缺少位置参数' }
  10. if (typeof position === 'string') {
  11. if (position === '') return { success: false, error: 'click 操作缺少位置参数(位置变量为空)' }
  12. try {
  13. position = JSON.parse(position)
  14. } catch (e) {
  15. const parts = position.split(',')
  16. if (parts.length === 2) {
  17. const x = parseFloat(parts[0].trim())
  18. const y = parseFloat(parts[1].trim())
  19. if (!isNaN(x) && !isNaN(y)) position = { x: Math.round(x), y: Math.round(y) }
  20. else return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` }
  21. } else return { success: false, error: `click 操作的位置格式错误,无法解析字符串: ${position}` }
  22. }
  23. }
  24. if (Array.isArray(position) && position.length >= 2) position = { x: position[0], y: position[1] }
  25. if (position?.topLeft && position?.bottomRight) {
  26. position = {
  27. x: Math.round((position.topLeft.x + position.bottomRight.x) / 2),
  28. y: Math.round((position.topLeft.y + position.bottomRight.y) / 2),
  29. }
  30. }
  31. if (!position || typeof position !== 'object' || position.x === undefined || position.y === undefined)
  32. return { success: false, error: 'click 操作的位置格式错误,需要 {x, y} 对象' }
  33. if (!api?.sendTap) return { success: false, error: '点击 API 不可用' }
  34. const tapResult = await api.sendTap(device, position.x, position.y)
  35. if (!tapResult.success) return { success: false, error: `点击失败: ${tapResult.error != null ? tapResult.error : 'unknown'}` }
  36. return { success: true }
  37. }
  38. module.exports = { run }