dsh-gufa-code 1.3.78 → 1.3.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);
42
42
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
43
43
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
44
- - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明),单结果直接跳,多结果弹「跳转到定义」列表;
44
+ - **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
45
45
  - **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
46
46
  - 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
47
47
  - **从 Finder 粘贴/拖入文件**:系统剪贴板里复制的文件可直接 ⌘V 粘进资源管理器(写入选中的目录,重名自动加「副本」),也可从 Finder 直接拖进文件树;
package/client.js CHANGED
@@ -16,7 +16,7 @@ const GUFA_NS = 'gufa-code'
16
16
  const G = {}
17
17
  G.NS = GUFA_NS
18
18
  /** 客户端构建标记(排查页面是否加载了新代码时看标题栏) */
19
- G.BUILD = '1.3.78'
19
+ G.BUILD = '1.3.87'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -1685,6 +1685,8 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1685
1685
  border-bottom:1px solid var(--gufa-border);overflow:hidden;white-space:nowrap}
1686
1686
  .gufa-breadcrumb b{font-weight:500;color:var(--gufa-text)}
1687
1687
  .gufa-editor-host{flex:1 1 auto;position:relative;min-height:0;min-width:0;overflow:hidden}
1688
+ .gufa-def-link{text-decoration:underline;text-decoration-color:var(--gufa-accent);text-decoration-thickness:1px;text-underline-offset:2px;cursor:pointer}
1689
+ .monaco-editor.gufa-def-hover .view-lines{cursor:pointer}
1688
1690
  .gufa-editor-fallback{position:absolute;inset:0;overflow:auto;margin:0;padding:14px 18px;font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;tab-size:2}
1689
1691
  .gufa-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;height:100%;padding:28px;
1690
1692
  color:var(--gufa-text-dim);text-align:center}
@@ -2747,7 +2749,10 @@ G.FooterAction = function FooterAction(props) {
2747
2749
  if (gufaReadyMonaco() === null) gufaMonacoPromise = null
2748
2750
  }
2749
2751
 
2750
- /* ── model / URI ────────────────────────────────────────────────────── */
2752
+ /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
2753
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
2754
+
2755
+ /* ── model / URI ────────────────────────────────────────────────────── */
2751
2756
 
2752
2757
  /**
2753
2758
  * tab → Monaco model URI:file:///<root>/<path>(root 为项目绝对路径)。
@@ -3027,12 +3032,21 @@ G.FooterAction = function FooterAction(props) {
3027
3032
  if (host === null) return undefined
3028
3033
  let cancelled = false
3029
3034
  let editor = null
3035
+ let definitionCleanup = null
3030
3036
  const subscriptions = []
3031
3037
 
3032
3038
  setStatus('loading')
3033
3039
  setMonacoError('')
3034
3040
 
3035
3041
  const disposeEditor = () => {
3042
+ if (definitionCleanup !== null) {
3043
+ try {
3044
+ definitionCleanup()
3045
+ } catch {
3046
+ /* ignore */
3047
+ }
3048
+ definitionCleanup = null
3049
+ }
3036
3050
  for (const subscription of subscriptions.splice(0)) {
3037
3051
  try {
3038
3052
  subscription.dispose()
@@ -3095,11 +3109,207 @@ G.FooterAction = function FooterAction(props) {
3095
3109
  }
3096
3110
  })
3097
3111
 
3098
- /* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
3099
- 非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
3112
+ /* Cmd/Ctrl+点击跳转定义 + Cmd 悬停「可点击」提示:先走 Monaco 语言服务;
3113
+ 没有提供者(未打开的文件、非 TS/JS 语言等)时回退到 Host 的项目级定义搜索。 */
3100
3114
  try {
3101
- const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
3102
- if (domNode !== null && domNode !== undefined) {
3115
+ const editorDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
3116
+ if (editorDom !== null && editorDom !== undefined) {
3117
+ const isPrimaryEvent = (event) => {
3118
+ const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3119
+ return mac ? event.metaKey === true : event.ctrlKey === true
3120
+ }
3121
+ const decideDefinition = (result) => {
3122
+ const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3123
+ if (matches.length === 0) return { kind: 'none' }
3124
+ const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
3125
+ const top = matches[0]
3126
+ const topScore = Number(top.score) || 0
3127
+ if (currentPath !== null && top.path === currentPath) return { kind: 'open', match: top }
3128
+ const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
3129
+ if (!isStrong(top) && topScore < 50) return { kind: 'none' }
3130
+ if (topScore < 30) return { kind: 'none' }
3131
+ const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
3132
+ if (cluster.length === 1) return { kind: 'open', match: cluster[0] }
3133
+ const declCluster = cluster.filter((item) => isStrong(item))
3134
+ if (declCluster.length === 0) {
3135
+ const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
3136
+ return topScore >= 50 && topScore - secondScore >= 10 ? { kind: 'open', match: top } : { kind: 'none' }
3137
+ }
3138
+ const distinctFiles = new Set(declCluster.map((item) => item.path))
3139
+ if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
3140
+ return { kind: 'pick', matches: declCluster }
3141
+ }
3142
+ const queryDefinitions = (position, word, model, path, root) => G.api('code.definition', {
3143
+ root,
3144
+ path,
3145
+ line: position.lineNumber,
3146
+ column: position.column,
3147
+ word,
3148
+ content: model.getValue(),
3149
+ })
3150
+
3151
+ /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
3152
+ const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
3153
+ const clearHoverDecoration = () => {
3154
+ if (hover.decorationIds.length > 0) {
3155
+ try {
3156
+ hover.decorationIds = instance.deltaDecorations(hover.decorationIds, [])
3157
+ } catch {
3158
+ hover.decorationIds = []
3159
+ }
3160
+ }
3161
+ try {
3162
+ editorDom.classList.remove('gufa-def-hover')
3163
+ } catch {
3164
+ /* ignore */
3165
+ }
3166
+ }
3167
+ const showHoverDecoration = (position, wordInfo) => {
3168
+ if (wordInfo === null || wordInfo === undefined) return clearHoverDecoration()
3169
+ let range = null
3170
+ try {
3171
+ range = new monaco.Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn)
3172
+ } catch {
3173
+ return clearHoverDecoration()
3174
+ }
3175
+ try {
3176
+ hover.decorationIds = instance.deltaDecorations(hover.decorationIds, [
3177
+ { range, options: { inlineClassName: 'gufa-def-link', stickiness: 1 } },
3178
+ ])
3179
+ } catch {
3180
+ /* ignore */
3181
+ }
3182
+ try {
3183
+ editorDom.classList.add('gufa-def-hover')
3184
+ } catch {
3185
+ /* ignore */
3186
+ }
3187
+ }
3188
+ const evaluateHoverPosition = (position, wordInfo) => {
3189
+ if (!hover.meta) {
3190
+ clearHoverDecoration()
3191
+ return
3192
+ }
3193
+ const model = instance.getModel()
3194
+ const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
3195
+ const path = modelPathRef.current
3196
+ const root = modelsRootRef.current
3197
+ if (position === null || position === undefined || model === null || model === undefined
3198
+ || word.length < 2 || path === null || path === undefined || root === null || root === undefined || root === '') {
3199
+ clearHoverDecoration()
3200
+ return
3201
+ }
3202
+ hover.lastPosition = position
3203
+ hover.lastWordInfo = wordInfo
3204
+ const key = `${path}|${word}`
3205
+ hover.lastKey = key
3206
+ const cached = hover.cache.get(key)
3207
+ if (cached === 'none') {
3208
+ clearHoverDecoration()
3209
+ return
3210
+ }
3211
+ if (cached === 'yes') {
3212
+ showHoverDecoration(position, wordInfo)
3213
+ return
3214
+ }
3215
+ if (hover.timer !== 0) {
3216
+ window.clearTimeout(hover.timer)
3217
+ hover.timer = 0
3218
+ }
3219
+ const seq = ++hover.seq
3220
+ hover.timer = window.setTimeout(() => {
3221
+ hover.timer = 0
3222
+ if (!hover.meta || seq !== hover.seq) return
3223
+ void queryDefinitions(position, word, model, path, root).then((result) => {
3224
+ if (!hover.meta || seq !== hover.seq || hover.lastKey !== key) return
3225
+ const decision = decideDefinition(result)
3226
+ if (decision.kind === 'none') {
3227
+ if (hover.cache.size > 100) hover.cache.clear()
3228
+ hover.cache.set(key, 'none')
3229
+ clearHoverDecoration()
3230
+ return
3231
+ }
3232
+ if (hover.cache.size > 100) hover.cache.clear()
3233
+ hover.cache.set(key, 'yes')
3234
+ showHoverDecoration(position, wordInfo)
3235
+ }).catch(() => {
3236
+ /* ignore */
3237
+ })
3238
+ }, 130)
3239
+ }
3240
+ /* 用 Monaco 自己的 onMouseMove(带修饰键状态 + 精确 position),
3241
+ 不依赖 DOM mousedown/getTargetAtClientPoint 的坐标系与包含关系。 */
3242
+ const onMonacoMouseMove = (editorEvent) => {
3243
+ if (editorEvent === null || editorEvent === undefined) return
3244
+ const browser = editorEvent.event !== null && editorEvent.event !== undefined ? editorEvent.event.browserEvent : null
3245
+ const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3246
+ const pressed = browser !== null && browser !== undefined
3247
+ ? (mac ? browser.metaKey === true : browser.ctrlKey === true)
3248
+ : false
3249
+ if (!pressed) {
3250
+ if (hover.meta) {
3251
+ hover.meta = false
3252
+ hover.seq += 1
3253
+ if (hover.timer !== 0) {
3254
+ window.clearTimeout(hover.timer)
3255
+ hover.timer = 0
3256
+ }
3257
+ clearHoverDecoration()
3258
+ }
3259
+ return
3260
+ }
3261
+ hover.meta = true
3262
+ const target = editorEvent.target !== null && editorEvent.target !== undefined ? editorEvent.target : null
3263
+ const position = target !== null ? target.position : null
3264
+ if (position === null || position === undefined) {
3265
+ clearHoverDecoration()
3266
+ return
3267
+ }
3268
+ let wordInfo = null
3269
+ try {
3270
+ const model = instance.getModel()
3271
+ wordInfo = model !== null && model !== undefined ? model.getWordAtPosition(position) : null
3272
+ } catch {
3273
+ wordInfo = null
3274
+ }
3275
+ evaluateHoverPosition(position, wordInfo)
3276
+ }
3277
+ const onMetaDown = (event) => {
3278
+ if (event.key !== 'Meta' && event.key !== 'Control') return
3279
+ if (hover.meta) return
3280
+ hover.meta = true
3281
+ if (hover.lastPosition !== null && hover.lastWordInfo !== null) evaluateHoverPosition(hover.lastPosition, hover.lastWordInfo)
3282
+ }
3283
+ const onMetaUp = (event) => {
3284
+ if (event.key !== 'Meta' && event.key !== 'Control') return
3285
+ hover.meta = false
3286
+ hover.seq += 1
3287
+ if (hover.timer !== 0) {
3288
+ window.clearTimeout(hover.timer)
3289
+ hover.timer = 0
3290
+ }
3291
+ clearHoverDecoration()
3292
+ }
3293
+ const onDefWindowBlur = () => {
3294
+ hover.meta = false
3295
+ clearHoverDecoration()
3296
+ }
3297
+ const hoverSubscriptions = []
3298
+ try {
3299
+ if (typeof instance.onMouseMove === 'function') hoverSubscriptions.push(instance.onMouseMove(onMonacoMouseMove))
3300
+ if (typeof instance.onMouseLeave === 'function') hoverSubscriptions.push(instance.onMouseLeave(() => {
3301
+ hover.meta = false
3302
+ hover.lastPosition = null
3303
+ hover.lastWordInfo = null
3304
+ hover.seq += 1
3305
+ clearHoverDecoration()
3306
+ }))
3307
+ if (typeof instance.onDidChangeModelContent === 'function') hoverSubscriptions.push(instance.onDidChangeModelContent(() => clearHoverDecoration()))
3308
+ if (typeof instance.onDidScrollChange === 'function') hoverSubscriptions.push(instance.onDidScrollChange(() => clearHoverDecoration()))
3309
+ } catch {
3310
+ /* ignore */
3311
+ }
3312
+ for (const subscription of hoverSubscriptions) if (subscription !== null && subscription !== undefined) subscriptions.push(subscription)
3103
3313
  const onDefinitionClick = async (event) => {
3104
3314
  try {
3105
3315
  const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
@@ -3108,9 +3318,7 @@ G.FooterAction = function FooterAction(props) {
3108
3318
  return
3109
3319
  }
3110
3320
  if (event.button !== 0 || event.defaultPrevented === true) return
3111
- const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
3112
- const pressed = primary ? event.metaKey === true : event.ctrlKey === true
3113
- if (!pressed || event.altKey === true || event.shiftKey === true) return
3321
+ if (!isPrimaryEvent(event) || event.altKey === true || event.shiftKey === true) return
3114
3322
  if (event.target instanceof Element && event.target.closest('a') !== null) return
3115
3323
  let target = null
3116
3324
  try {
@@ -3131,7 +3339,7 @@ G.FooterAction = function FooterAction(props) {
3131
3339
  if (word.length < 2) return
3132
3340
  const path = modelPathRef.current
3133
3341
  const root = modelsRootRef.current
3134
- if (path === null || root === null || root === '') return
3342
+ if (path === null || path === undefined || root === null || root === undefined || root === '') return
3135
3343
  try {
3136
3344
  event.preventDefault()
3137
3345
  event.stopPropagation()
@@ -3160,28 +3368,44 @@ G.FooterAction = function FooterAction(props) {
3160
3368
  } catch {
3161
3369
  monacoHandled = false
3162
3370
  }
3371
+ clearHoverDecoration()
3163
3372
  if (monacoHandled) return
3164
3373
  try {
3165
- const result = await G.api('code.definition', {
3166
- root,
3167
- path,
3168
- line: position.lineNumber,
3169
- column: position.column,
3170
- word,
3171
- content: model.getValue(),
3172
- })
3173
- const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
3174
- if (matches.length === 0) return
3175
- if (matches.length === 1) {
3176
- G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
3374
+ const result = await queryDefinitions(position, word, model, path, root)
3375
+ const decision = decideDefinition(result)
3376
+ if (decision.kind === 'open') {
3377
+ G.bus.emit('editor:open-at', { path: decision.match.path, line: decision.match.line, column: decision.match.column })
3177
3378
  return
3178
3379
  }
3179
- G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
3380
+ if (decision.kind === 'pick') {
3381
+ G.bus.emit('definition:pick', {
3382
+ word: result !== null && result !== undefined && typeof result.word === 'string' ? result.word : word,
3383
+ matches: decision.matches,
3384
+ x: event.clientX,
3385
+ y: event.clientY,
3386
+ })
3387
+ }
3180
3388
  } catch {
3181
3389
  /* ignore */
3182
3390
  }
3183
3391
  }
3184
3392
  document.addEventListener('mousedown', onDefinitionClick, true)
3393
+ document.addEventListener('keydown', onMetaDown, true)
3394
+ document.addEventListener('keyup', onMetaUp, true)
3395
+ window.addEventListener('blur', onDefWindowBlur)
3396
+ definitionCleanup = () => {
3397
+ document.removeEventListener('mousedown', onDefinitionClick, true)
3398
+ document.removeEventListener('keydown', onMetaDown, true)
3399
+ document.removeEventListener('keyup', onMetaUp, true)
3400
+ window.removeEventListener('blur', onDefWindowBlur)
3401
+ if (hover.timer !== 0) {
3402
+ window.clearTimeout(hover.timer)
3403
+ hover.timer = 0
3404
+ }
3405
+ hover.seq += 1
3406
+ hover.meta = false
3407
+ clearHoverDecoration()
3408
+ }
3185
3409
  }
3186
3410
  } catch {
3187
3411
  /* ignore */
@@ -7,8 +7,8 @@
7
7
  <key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
8
8
  <key>CFBundleExecutable</key><string>gufa-float</string>
9
9
  <key>CFBundlePackageType</key><string>APPL</string>
10
- <key>CFBundleShortVersionString</key><string>1.3.78</string>
11
- <key>CFBundleVersion</key><string>1.3.78</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.87</string>
11
+ <key>CFBundleVersion</key><string>1.3.87</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -8,6 +8,13 @@
8
8
  - **不要用 localStorage / 全局状态判断摸鱼模式**(曾经因此让主窗口的「入口工作区」逻辑失效);
9
9
  - 摸鱼相关逻辑一律包在 `G.isFloatMode()` 里;古法编程的功能锁见 `docs/MODES.md`。
10
10
 
11
+ ## 0.5 Cmd/Ctrl+点击跳转定义(1.3.78 起)
12
+
13
+ - 编辑器 DOM 上挂 **document 级 mousedown 捕获**(不要挂 Monaco DOM 节点:标签切换/重建后容易挂到废弃节点)。
14
+ - 流程:`getTargetAtClientPoint` → `model.getWordAtPosition` → 先 `editor.action.revealDefinition`(Monaco 自带语言服务),160ms 内检测跳转/peek;没有则调 `code.definition` Host API 兜底。
15
+ - Host `code.definition` 注册在 `host/fs.js` 里,用带 mtime query 的动态 import 加载 `host/code.js`——Host 热重载只按 `MODULE_FILES`(host/*.js)的 mtime 触发,静态 import code.js 会一直吃老缓存。
16
+ - 兜底匹配会解析 import/require 来源(+220 分)、跳过压缩/生成的大文件(单行超长、>512KB)、按目录距离降权;**不要一有多结果就弹列表**:同文件/import/唯一候选直接跳,`function/class/method/type` 之外的弱匹配先要求分数 ≥50 且领先第二名 ≥10,否则静默;只有多个真正同名声明(不同文件、强类型)才弹 picker(最多 8 条)。
17
+
11
18
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
12
19
 
13
20
  **现象**:弹窗被右侧「古法 AI」聊天栏压住、只显示一半、关闭按钮点不到;或者反过来把官方设置/会话弹窗盖住。
package/host/code.js CHANGED
@@ -14,7 +14,7 @@ import { promisify } from 'node:util'
14
14
  import { ApiError, badRequest } from './context.js'
15
15
 
16
16
  const runCommand = promisify(execFile)
17
- const MAX_FILE_SIZE = 1024 * 1024
17
+ const MAX_FILE_SIZE = 512 * 1024
18
18
  const MAX_SCANNED = 3000
19
19
  const TIME_BUDGET = 7000
20
20
  const MAX_MATCHES = 30
@@ -96,15 +96,100 @@ function definitionPatterns(word) {
96
96
  ]
97
97
  }
98
98
 
99
+ function pathSegments(relPath) {
100
+ if (relPath === '') return []
101
+ const dir = relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : ''
102
+ return dir === '' ? [] : dir.split('/')
103
+ }
104
+
99
105
  function scoreMatch(match, current) {
100
106
  let score = match.weight
101
107
  if (match.path === current.path) score += 120
102
108
  if (extensionOf(match.path) === extensionOf(current.path)) score += 6
103
- if (match.path.startsWith(`${current.dir}/`)) score += 4
109
+ if (current.dir !== '' && match.path.startsWith(`${current.dir}/`)) score += 8
110
+ /* 目录距离:同目录 > 子目录 > 兄弟目录 > 远处目录(项目根是 home 时尤其重要) */
111
+ const currentSegments = pathSegments(current.path)
112
+ const matchSegments = pathSegments(match.path)
113
+ let common = 0
114
+ while (common < currentSegments.length && common < matchSegments.length && currentSegments[common] === matchSegments[common]) common += 1
115
+ const gap = currentSegments.length + matchSegments.length - common * 2
116
+ score += Math.max(0, 20 - gap * 4)
104
117
  if (match.kind === 'method' || match.kind === 'function' || match.kind === 'def' || match.kind === 'func' || match.kind === 'fn') score += 4
118
+ if (match.importBoost === true) score += 220
105
119
  return score
106
120
  }
107
121
 
122
+ /** 压缩/生成的单行超长文件:定义搜索里排除,避免点到包产物里的同名变量。 */
123
+ function isMinifiedText(text) {
124
+ const value = String(text)
125
+ if (value.length < 2000) return false
126
+ const lines = value.split('\n')
127
+ if (lines.length < 12) return true
128
+ let longLines = 0
129
+ const sample = Math.min(lines.length, 200)
130
+ for (let index = 0; index < sample; index += 1) {
131
+ if (lines[index].length > 1200) longLines += 1
132
+ }
133
+ if (longLines >= 1) return true
134
+ return value.length / lines.length > 240
135
+ }
136
+
137
+ /** 解析当前文件的 import/require,得到 标识符 → 模块 spec 的映射。 */
138
+ function parseImportMap(text) {
139
+ const map = new Map()
140
+ const source = String(text)
141
+ try {
142
+ let match
143
+ const es = /import\s+([^'"]+?)\s+from\s+['"]([^'"]+)['"]/g
144
+ while ((match = es.exec(source)) !== null) {
145
+ const clause = match[1]
146
+ const spec = match[2]
147
+ const named = /\{([^}]*)\}/.exec(clause)
148
+ if (named !== null) {
149
+ for (const part of named[1].split(',')) {
150
+ const raw = part.trim()
151
+ if (raw === '') continue
152
+ const alias = raw.split(/\s+as\s+/).pop().trim()
153
+ if (/^[A-Za-z_$][\w$]*$/.test(alias)) map.set(alias, spec)
154
+ }
155
+ }
156
+ const def = clause.replace(/\{[^}]*\}/g, '').replace(/,/g, ' ').trim().split(/\s+/)[0]
157
+ if (def !== undefined && /^[A-Za-z_$][\w$]*$/.test(def)) map.set(def, spec)
158
+ }
159
+ const cjs = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g
160
+ while ((match = cjs.exec(source)) !== null) map.set(match[1], match[2])
161
+ const cjsNamed = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/g
162
+ while ((match = cjsNamed.exec(source)) !== null) {
163
+ for (const part of match[1].split(',')) {
164
+ const name = part.trim().split(/\s*:\s*/).pop()
165
+ if (/^[A-Za-z_$][\w$]*$/.test(name)) map.set(name, match[2])
166
+ }
167
+ }
168
+ } catch {
169
+ /* ignore */
170
+ }
171
+ return map
172
+ }
173
+
174
+ /** 把相对 import 解析成候选文件路径(不含存在性检查)。 */
175
+ function importTargetPaths(currentPath, spec) {
176
+ if (!spec.startsWith('.')) return []
177
+ const baseDir = currentPath.includes('/') ? currentPath.slice(0, currentPath.lastIndexOf('/')) : ''
178
+ const raw = `${baseDir}${baseDir === '' ? '' : '/'}${spec}`
179
+ const parts = []
180
+ for (const part of raw.split('/')) {
181
+ if (part === '' || part === '.') continue
182
+ if (part === '..') parts.pop()
183
+ else parts.push(part)
184
+ }
185
+ const base = parts.join('/')
186
+ return [
187
+ base,
188
+ `${base}.js`, `${base}.ts`, `${base}.jsx`, `${base}.tsx`, `${base}.mjs`, `${base}.cjs`,
189
+ `${base}/index.js`, `${base}/index.ts`, `${base}/index.jsx`, `${base}/index.tsx`,
190
+ ]
191
+ }
192
+
108
193
  async function listCandidates(root, textBudgets) {
109
194
  /* Git 项目用 git ls-files(尊重 .gitignore、含未跟踪文件),否则 BFS 遍历。 */
110
195
  let isGit = false
@@ -201,8 +286,7 @@ function findDefinitionsInText(text, relPath, word, patterns, results, current)
201
286
  void current
202
287
  }
203
288
 
204
- export function register(router, env) {
205
- router.method('code.definition', async (body) => {
289
+ export async function definition(body, env) {
206
290
  const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
207
291
  const root = project.root
208
292
  const rawPath = typeof body.path === 'string' ? body.path : ''
@@ -233,6 +317,10 @@ export function register(router, env) {
233
317
  const patterns = definitionPatterns(word)
234
318
  const startedAt = Date.now()
235
319
  const current = { path: relPath, dir: relPath.includes('/') ? relPath.slice(0, relPath.lastIndexOf('/')) : '' }
320
+ /* import 解析:命中导入来源的文件给高权重,避免在 home 根目录这种大项目里点到同名变量 */
321
+ const importMap = parseImportMap(text)
322
+ const importedSpec = importMap.get(word)
323
+ const importTargets = new Set(importedSpec === undefined ? [] : importTargetPaths(relPath, importedSpec))
236
324
  const results = []
237
325
  /* 1) 当前文件(用编辑器传来的内容,能命中未保存的改动) */
238
326
  findDefinitionsInText(text, relPath, word, patterns, results, current)
@@ -254,6 +342,7 @@ export function register(router, env) {
254
342
  if (buffer.includes(0)) continue
255
343
  const candidateText = buffer.toString('utf8')
256
344
  if (!candidateText.includes(word)) continue
345
+ if (isMinifiedText(candidateText)) continue
257
346
  findDefinitionsInText(candidateText, candidate, word, patterns, results, current)
258
347
  }
259
348
  /* 去重 + 打分 + 排序 */
@@ -263,13 +352,14 @@ export function register(router, env) {
263
352
  const key = `${item.path}:${item.line}:${item.column}`
264
353
  if (seen.has(key)) continue
265
354
  seen.add(key)
355
+ const candidate = { ...item, importBoost: importTargets.has(item.path) }
266
356
  matches.push({
267
357
  path: item.path,
268
358
  line: item.line,
269
359
  column: item.column,
270
360
  kind: item.kind,
271
361
  preview: item.preview,
272
- score: scoreMatch(item, current),
362
+ score: scoreMatch(candidate, current),
273
363
  })
274
364
  }
275
365
  matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path) || a.line - b.line)
@@ -279,5 +369,8 @@ export function register(router, env) {
279
369
  current: { path: relPath, line, column },
280
370
  truncated: matches.length > MAX_MATCHES,
281
371
  }
282
- })
372
+ }
373
+
374
+ export function register(router, env) {
375
+ router.method('code.definition', (body) => definition(body, env))
283
376
  }
package/host/fs.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * 所有路径都必须是「已打开项目根」内的相对路径,防止越权访问任意磁盘。
4
4
  */
5
5
  import { createHash, randomUUID } from 'node:crypto'
6
+ import { statSync } from 'node:fs'
6
7
  import { createReadStream } from 'node:fs'
7
8
  import { access, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
8
9
  import { execFile } from 'node:child_process'
@@ -11,7 +12,6 @@ import { constants } from 'node:fs'
11
12
  import { tmpdir } from 'node:os'
12
13
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
13
14
  import { ApiError, badRequest } from './context.js'
14
- import { register as registerCodeNavigation } from './code.js'
15
15
 
16
16
  const TEXT_LIMIT = 4 * 1024 * 1024
17
17
  const runCommand = promisify(execFile)
@@ -244,9 +244,18 @@ async function listProjectCandidates(root, project, maxScanned) {
244
244
  }
245
245
 
246
246
  export function register(router, env) {
247
- /* 代码导航(Cmd+点击跳定义)注册在 fs 模块里:host 热重载按 host/*.js 的 mtime 触发,
248
- 如果单开一个模块,需要重启 Host 才能挂上;挂在 fs 上改代码即可热生效。 */
249
- registerCodeNavigation(router, env)
247
+ /* 代码导航(Cmd+点击跳定义):实现放在 code.js,但 Host 热重载只按 host/*.js 的 mtime
248
+ 触发,因此这里用带 mtime 的 query 动态 import,code.js 改动后下一次请求就能热生效。 */
249
+ router.method('code.definition', async (body) => {
250
+ let stamp = '0'
251
+ try {
252
+ stamp = String(statSync(new URL('./code.js', import.meta.url)).mtimeMs)
253
+ } catch {
254
+ stamp = '0'
255
+ }
256
+ const module = await import(new URL(`./code.js?gufa-code-def=${stamp}`, import.meta.url).href)
257
+ return module.definition(body, env)
258
+ })
250
259
 
251
260
  router.method('fs.list', async (body) => {
252
261
  const root = await projectOf(env, body)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.78",
3
+ "version": "1.3.87",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -1677,6 +1677,8 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1677
1677
  border-bottom:1px solid var(--gufa-border);overflow:hidden;white-space:nowrap}
1678
1678
  .gufa-breadcrumb b{font-weight:500;color:var(--gufa-text)}
1679
1679
  .gufa-editor-host{flex:1 1 auto;position:relative;min-height:0;min-width:0;overflow:hidden}
1680
+ .gufa-def-link{text-decoration:underline;text-decoration-color:var(--gufa-accent);text-decoration-thickness:1px;text-underline-offset:2px;cursor:pointer}
1681
+ .monaco-editor.gufa-def-hover .view-lines{cursor:pointer}
1680
1682
  .gufa-editor-fallback{position:absolute;inset:0;overflow:auto;margin:0;padding:14px 18px;font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;tab-size:2}
1681
1683
  .gufa-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;height:100%;padding:28px;
1682
1684
  color:var(--gufa-text-dim);text-align:center}
@@ -399,7 +399,10 @@
399
399
  if (gufaReadyMonaco() === null) gufaMonacoPromise = null
400
400
  }
401
401
 
402
- /* ── model / URI ────────────────────────────────────────────────────── */
402
+ /** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
403
+ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
404
+
405
+ /* ── model / URI ────────────────────────────────────────────────────── */
403
406
 
404
407
  /**
405
408
  * tab → Monaco model URI:file:///<root>/<path>(root 为项目绝对路径)。
@@ -679,12 +682,21 @@
679
682
  if (host === null) return undefined
680
683
  let cancelled = false
681
684
  let editor = null
685
+ let definitionCleanup = null
682
686
  const subscriptions = []
683
687
 
684
688
  setStatus('loading')
685
689
  setMonacoError('')
686
690
 
687
691
  const disposeEditor = () => {
692
+ if (definitionCleanup !== null) {
693
+ try {
694
+ definitionCleanup()
695
+ } catch {
696
+ /* ignore */
697
+ }
698
+ definitionCleanup = null
699
+ }
688
700
  for (const subscription of subscriptions.splice(0)) {
689
701
  try {
690
702
  subscription.dispose()
@@ -747,11 +759,207 @@
747
759
  }
748
760
  })
749
761
 
750
- /* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
751
- 非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
762
+ /* Cmd/Ctrl+点击跳转定义 + Cmd 悬停「可点击」提示:先走 Monaco 语言服务;
763
+ 没有提供者(未打开的文件、非 TS/JS 语言等)时回退到 Host 的项目级定义搜索。 */
752
764
  try {
753
- const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
754
- if (domNode !== null && domNode !== undefined) {
765
+ const editorDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
766
+ if (editorDom !== null && editorDom !== undefined) {
767
+ const isPrimaryEvent = (event) => {
768
+ const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
769
+ return mac ? event.metaKey === true : event.ctrlKey === true
770
+ }
771
+ const decideDefinition = (result) => {
772
+ const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
773
+ if (matches.length === 0) return { kind: 'none' }
774
+ const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
775
+ const top = matches[0]
776
+ const topScore = Number(top.score) || 0
777
+ if (currentPath !== null && top.path === currentPath) return { kind: 'open', match: top }
778
+ const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
779
+ if (!isStrong(top) && topScore < 50) return { kind: 'none' }
780
+ if (topScore < 30) return { kind: 'none' }
781
+ const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
782
+ if (cluster.length === 1) return { kind: 'open', match: cluster[0] }
783
+ const declCluster = cluster.filter((item) => isStrong(item))
784
+ if (declCluster.length === 0) {
785
+ const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
786
+ return topScore >= 50 && topScore - secondScore >= 10 ? { kind: 'open', match: top } : { kind: 'none' }
787
+ }
788
+ const distinctFiles = new Set(declCluster.map((item) => item.path))
789
+ if (distinctFiles.size === 1) return { kind: 'open', match: declCluster[0] }
790
+ return { kind: 'pick', matches: declCluster }
791
+ }
792
+ const queryDefinitions = (position, word, model, path, root) => G.api('code.definition', {
793
+ root,
794
+ path,
795
+ line: position.lineNumber,
796
+ column: position.column,
797
+ word,
798
+ content: model.getValue(),
799
+ })
800
+
801
+ /* ── Cmd 悬停:可跳转时下划线 + 手型光标 ─────────────── */
802
+ const hover = { meta: false, timer: 0, seq: 0, cache: new Map(), decorationIds: [], lastClient: null, lastPosition: null, lastWordInfo: null, lastKey: '' }
803
+ const clearHoverDecoration = () => {
804
+ if (hover.decorationIds.length > 0) {
805
+ try {
806
+ hover.decorationIds = instance.deltaDecorations(hover.decorationIds, [])
807
+ } catch {
808
+ hover.decorationIds = []
809
+ }
810
+ }
811
+ try {
812
+ editorDom.classList.remove('gufa-def-hover')
813
+ } catch {
814
+ /* ignore */
815
+ }
816
+ }
817
+ const showHoverDecoration = (position, wordInfo) => {
818
+ if (wordInfo === null || wordInfo === undefined) return clearHoverDecoration()
819
+ let range = null
820
+ try {
821
+ range = new monaco.Range(position.lineNumber, wordInfo.startColumn, position.lineNumber, wordInfo.endColumn)
822
+ } catch {
823
+ return clearHoverDecoration()
824
+ }
825
+ try {
826
+ hover.decorationIds = instance.deltaDecorations(hover.decorationIds, [
827
+ { range, options: { inlineClassName: 'gufa-def-link', stickiness: 1 } },
828
+ ])
829
+ } catch {
830
+ /* ignore */
831
+ }
832
+ try {
833
+ editorDom.classList.add('gufa-def-hover')
834
+ } catch {
835
+ /* ignore */
836
+ }
837
+ }
838
+ const evaluateHoverPosition = (position, wordInfo) => {
839
+ if (!hover.meta) {
840
+ clearHoverDecoration()
841
+ return
842
+ }
843
+ const model = instance.getModel()
844
+ const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
845
+ const path = modelPathRef.current
846
+ const root = modelsRootRef.current
847
+ if (position === null || position === undefined || model === null || model === undefined
848
+ || word.length < 2 || path === null || path === undefined || root === null || root === undefined || root === '') {
849
+ clearHoverDecoration()
850
+ return
851
+ }
852
+ hover.lastPosition = position
853
+ hover.lastWordInfo = wordInfo
854
+ const key = `${path}|${word}`
855
+ hover.lastKey = key
856
+ const cached = hover.cache.get(key)
857
+ if (cached === 'none') {
858
+ clearHoverDecoration()
859
+ return
860
+ }
861
+ if (cached === 'yes') {
862
+ showHoverDecoration(position, wordInfo)
863
+ return
864
+ }
865
+ if (hover.timer !== 0) {
866
+ window.clearTimeout(hover.timer)
867
+ hover.timer = 0
868
+ }
869
+ const seq = ++hover.seq
870
+ hover.timer = window.setTimeout(() => {
871
+ hover.timer = 0
872
+ if (!hover.meta || seq !== hover.seq) return
873
+ void queryDefinitions(position, word, model, path, root).then((result) => {
874
+ if (!hover.meta || seq !== hover.seq || hover.lastKey !== key) return
875
+ const decision = decideDefinition(result)
876
+ if (decision.kind === 'none') {
877
+ if (hover.cache.size > 100) hover.cache.clear()
878
+ hover.cache.set(key, 'none')
879
+ clearHoverDecoration()
880
+ return
881
+ }
882
+ if (hover.cache.size > 100) hover.cache.clear()
883
+ hover.cache.set(key, 'yes')
884
+ showHoverDecoration(position, wordInfo)
885
+ }).catch(() => {
886
+ /* ignore */
887
+ })
888
+ }, 130)
889
+ }
890
+ /* 用 Monaco 自己的 onMouseMove(带修饰键状态 + 精确 position),
891
+ 不依赖 DOM mousedown/getTargetAtClientPoint 的坐标系与包含关系。 */
892
+ const onMonacoMouseMove = (editorEvent) => {
893
+ if (editorEvent === null || editorEvent === undefined) return
894
+ const browser = editorEvent.event !== null && editorEvent.event !== undefined ? editorEvent.event.browserEvent : null
895
+ const mac = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
896
+ const pressed = browser !== null && browser !== undefined
897
+ ? (mac ? browser.metaKey === true : browser.ctrlKey === true)
898
+ : false
899
+ if (!pressed) {
900
+ if (hover.meta) {
901
+ hover.meta = false
902
+ hover.seq += 1
903
+ if (hover.timer !== 0) {
904
+ window.clearTimeout(hover.timer)
905
+ hover.timer = 0
906
+ }
907
+ clearHoverDecoration()
908
+ }
909
+ return
910
+ }
911
+ hover.meta = true
912
+ const target = editorEvent.target !== null && editorEvent.target !== undefined ? editorEvent.target : null
913
+ const position = target !== null ? target.position : null
914
+ if (position === null || position === undefined) {
915
+ clearHoverDecoration()
916
+ return
917
+ }
918
+ let wordInfo = null
919
+ try {
920
+ const model = instance.getModel()
921
+ wordInfo = model !== null && model !== undefined ? model.getWordAtPosition(position) : null
922
+ } catch {
923
+ wordInfo = null
924
+ }
925
+ evaluateHoverPosition(position, wordInfo)
926
+ }
927
+ const onMetaDown = (event) => {
928
+ if (event.key !== 'Meta' && event.key !== 'Control') return
929
+ if (hover.meta) return
930
+ hover.meta = true
931
+ if (hover.lastPosition !== null && hover.lastWordInfo !== null) evaluateHoverPosition(hover.lastPosition, hover.lastWordInfo)
932
+ }
933
+ const onMetaUp = (event) => {
934
+ if (event.key !== 'Meta' && event.key !== 'Control') return
935
+ hover.meta = false
936
+ hover.seq += 1
937
+ if (hover.timer !== 0) {
938
+ window.clearTimeout(hover.timer)
939
+ hover.timer = 0
940
+ }
941
+ clearHoverDecoration()
942
+ }
943
+ const onDefWindowBlur = () => {
944
+ hover.meta = false
945
+ clearHoverDecoration()
946
+ }
947
+ const hoverSubscriptions = []
948
+ try {
949
+ if (typeof instance.onMouseMove === 'function') hoverSubscriptions.push(instance.onMouseMove(onMonacoMouseMove))
950
+ if (typeof instance.onMouseLeave === 'function') hoverSubscriptions.push(instance.onMouseLeave(() => {
951
+ hover.meta = false
952
+ hover.lastPosition = null
953
+ hover.lastWordInfo = null
954
+ hover.seq += 1
955
+ clearHoverDecoration()
956
+ }))
957
+ if (typeof instance.onDidChangeModelContent === 'function') hoverSubscriptions.push(instance.onDidChangeModelContent(() => clearHoverDecoration()))
958
+ if (typeof instance.onDidScrollChange === 'function') hoverSubscriptions.push(instance.onDidScrollChange(() => clearHoverDecoration()))
959
+ } catch {
960
+ /* ignore */
961
+ }
962
+ for (const subscription of hoverSubscriptions) if (subscription !== null && subscription !== undefined) subscriptions.push(subscription)
755
963
  const onDefinitionClick = async (event) => {
756
964
  try {
757
965
  const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
@@ -760,9 +968,7 @@
760
968
  return
761
969
  }
762
970
  if (event.button !== 0 || event.defaultPrevented === true) return
763
- const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
764
- const pressed = primary ? event.metaKey === true : event.ctrlKey === true
765
- if (!pressed || event.altKey === true || event.shiftKey === true) return
971
+ if (!isPrimaryEvent(event) || event.altKey === true || event.shiftKey === true) return
766
972
  if (event.target instanceof Element && event.target.closest('a') !== null) return
767
973
  let target = null
768
974
  try {
@@ -783,7 +989,7 @@
783
989
  if (word.length < 2) return
784
990
  const path = modelPathRef.current
785
991
  const root = modelsRootRef.current
786
- if (path === null || root === null || root === '') return
992
+ if (path === null || path === undefined || root === null || root === undefined || root === '') return
787
993
  try {
788
994
  event.preventDefault()
789
995
  event.stopPropagation()
@@ -812,28 +1018,44 @@
812
1018
  } catch {
813
1019
  monacoHandled = false
814
1020
  }
1021
+ clearHoverDecoration()
815
1022
  if (monacoHandled) return
816
1023
  try {
817
- const result = await G.api('code.definition', {
818
- root,
819
- path,
820
- line: position.lineNumber,
821
- column: position.column,
822
- word,
823
- content: model.getValue(),
824
- })
825
- const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
826
- if (matches.length === 0) return
827
- if (matches.length === 1) {
828
- G.bus.emit('editor:open-at', { path: matches[0].path, line: matches[0].line, column: matches[0].column })
1024
+ const result = await queryDefinitions(position, word, model, path, root)
1025
+ const decision = decideDefinition(result)
1026
+ if (decision.kind === 'open') {
1027
+ G.bus.emit('editor:open-at', { path: decision.match.path, line: decision.match.line, column: decision.match.column })
829
1028
  return
830
1029
  }
831
- G.bus.emit('definition:pick', { word: result.word ?? word, matches, x: event.clientX, y: event.clientY })
1030
+ if (decision.kind === 'pick') {
1031
+ G.bus.emit('definition:pick', {
1032
+ word: result !== null && result !== undefined && typeof result.word === 'string' ? result.word : word,
1033
+ matches: decision.matches,
1034
+ x: event.clientX,
1035
+ y: event.clientY,
1036
+ })
1037
+ }
832
1038
  } catch {
833
1039
  /* ignore */
834
1040
  }
835
1041
  }
836
1042
  document.addEventListener('mousedown', onDefinitionClick, true)
1043
+ document.addEventListener('keydown', onMetaDown, true)
1044
+ document.addEventListener('keyup', onMetaUp, true)
1045
+ window.addEventListener('blur', onDefWindowBlur)
1046
+ definitionCleanup = () => {
1047
+ document.removeEventListener('mousedown', onDefinitionClick, true)
1048
+ document.removeEventListener('keydown', onMetaDown, true)
1049
+ document.removeEventListener('keyup', onMetaUp, true)
1050
+ window.removeEventListener('blur', onDefWindowBlur)
1051
+ if (hover.timer !== 0) {
1052
+ window.clearTimeout(hover.timer)
1053
+ hover.timer = 0
1054
+ }
1055
+ hover.seq += 1
1056
+ hover.meta = false
1057
+ clearHoverDecoration()
1058
+ }
837
1059
  }
838
1060
  } catch {
839
1061
  /* ignore */