dsh-gufa-code 1.3.69 → 1.3.82
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 +1 -0
- package/client.js +188 -2
- package/desktop/float/bin/gufa-float-macos-arm64 +0 -0
- package/desktop/float/bin/gufa-float-macos-universal +0 -0
- package/desktop/float/bin/gufa-float-macos-x64 +0 -0
- package/desktop/float//345/217/244/346/263/225/347/274/226/347/250/213/346/202/254/346/265/256/345/261/202.app/Contents/Info.plist +2 -2
- package/desktop/float//345/217/244/346/263/225/347/274/226/347/250/213/346/202/254/346/265/256/345/261/202.app/Contents/MacOS/gufa-float +0 -0
- package/host/code.js +376 -0
- package/host/fs.js +14 -0
- package/package.json +1 -1
- package/scripts/selftest-host.mjs +21 -1
- package/src/client/00-core.js +2 -0
- package/src/client/20-editor.js +123 -1
- package/src/client/90-app.js +62 -0
package/README.md
CHANGED
|
@@ -41,6 +41,7 @@ dsh plugin add dsh-gufa-code
|
|
|
41
41
|
- Monaco 编辑器(离线随包分发,无需联网下载);
|
|
42
42
|
- 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
|
|
43
43
|
- 保存走磁盘版本冲突检测 + 原子写;未保存标记;
|
|
44
|
+
- **⌘/Ctrl + 点击跳转定义 / 方法实现**:优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;
|
|
44
45
|
- **全局搜索 / 替换**(左栏放大镜 / `⌘⇧F`):整个项目的文本搜索,支持区分大小写、正则、包含/排除文件(glob);结果按文件分组、高亮匹配,点击跳转行列;替换栏支持保留大小写(AB)、全部替换(需确认)、按文件替换(悬停文件头铅笔)、按单行匹配替换与忽略(悬停结果行);替换前会自动保存未落盘的编辑器内容;Git 项目用 `git ls-files` 枚举文件(尊重 `.gitignore`、含未跟踪文件),非 Git 项目遍历目录并自动跳过 `node_modules` 等依赖/缓存目录;摸鱼悬浮窗里同样可用;
|
|
45
46
|
- 资源管理器右键:新建 / 重命名 / 删除 / 复制 / 粘贴 / 打开所在文件夹 / 两文件对比;
|
|
46
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.
|
|
19
|
+
G.BUILD = '1.3.82'
|
|
20
20
|
G.PANEL_ID = 'gufa-code'
|
|
21
21
|
/** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
|
|
22
22
|
G.pendingEntryWorkspace = null
|
|
@@ -126,6 +126,7 @@ const DICT_ZH = {
|
|
|
126
126
|
'shortcuts.newTerminal': '新建终端',
|
|
127
127
|
'shortcuts.help': '打开 / 关闭本快捷键列表',
|
|
128
128
|
'shortcuts.editorTitle': '编辑器(Monaco / VS Code 同款键位)',
|
|
129
|
+
'editor.gotoDefinition': '跳转到定义',
|
|
129
130
|
'editorKeys.comment': '切换行注释',
|
|
130
131
|
'editorKeys.blockComment': '切换块注释',
|
|
131
132
|
'editorKeys.nextOccurrence': '选中下一个相同内容(多光标)',
|
|
@@ -382,6 +383,7 @@ const DICT_EN = {
|
|
|
382
383
|
'shortcuts.newTerminal': 'New terminal',
|
|
383
384
|
'shortcuts.help': 'Show / hide this shortcut list',
|
|
384
385
|
'shortcuts.editorTitle': 'Editor (Monaco / VS Code keybindings)',
|
|
386
|
+
'editor.gotoDefinition': 'Go to definition',
|
|
385
387
|
'editorKeys.comment': 'Toggle line comment',
|
|
386
388
|
'editorKeys.blockComment': 'Toggle block comment',
|
|
387
389
|
'editorKeys.nextOccurrence': 'Add next occurrence to multi-cursor',
|
|
@@ -2745,7 +2747,10 @@ G.FooterAction = function FooterAction(props) {
|
|
|
2745
2747
|
if (gufaReadyMonaco() === null) gufaMonacoPromise = null
|
|
2746
2748
|
}
|
|
2747
2749
|
|
|
2748
|
-
|
|
2750
|
+
/** 这些声明类型算「定义级」,多个同名时值得让用户选;普通 const/赋值等弱匹配不轻易弹列表。 */
|
|
2751
|
+
const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'def', 'func', 'fn', 'type', 'export'])
|
|
2752
|
+
|
|
2753
|
+
/* ── model / URI ────────────────────────────────────────────────────── */
|
|
2749
2754
|
|
|
2750
2755
|
/**
|
|
2751
2756
|
* tab → Monaco model URI:file:///<root>/<path>(root 为项目绝对路径)。
|
|
@@ -3092,6 +3097,125 @@ G.FooterAction = function FooterAction(props) {
|
|
|
3092
3097
|
/* ignore */
|
|
3093
3098
|
}
|
|
3094
3099
|
})
|
|
3100
|
+
|
|
3101
|
+
/* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
|
|
3102
|
+
非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
|
|
3103
|
+
try {
|
|
3104
|
+
const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
|
|
3105
|
+
if (domNode !== null && domNode !== undefined) {
|
|
3106
|
+
const onDefinitionClick = async (event) => {
|
|
3107
|
+
try {
|
|
3108
|
+
const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
|
|
3109
|
+
if (currentDom === null || currentDom === undefined || !(event.target instanceof Node) || !currentDom.contains(event.target)) return
|
|
3110
|
+
} catch {
|
|
3111
|
+
return
|
|
3112
|
+
}
|
|
3113
|
+
if (event.button !== 0 || event.defaultPrevented === true) return
|
|
3114
|
+
const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
|
|
3115
|
+
const pressed = primary ? event.metaKey === true : event.ctrlKey === true
|
|
3116
|
+
if (!pressed || event.altKey === true || event.shiftKey === true) return
|
|
3117
|
+
if (event.target instanceof Element && event.target.closest('a') !== null) return
|
|
3118
|
+
let target = null
|
|
3119
|
+
try {
|
|
3120
|
+
target = typeof instance.getTargetAtClientPoint === 'function' ? instance.getTargetAtClientPoint(event.clientX, event.clientY) : null
|
|
3121
|
+
} catch {
|
|
3122
|
+
target = null
|
|
3123
|
+
}
|
|
3124
|
+
const position = target !== null && target !== undefined ? target.position : null
|
|
3125
|
+
const model = instance.getModel()
|
|
3126
|
+
if (position === null || position === undefined || model === null || model === undefined) return
|
|
3127
|
+
let wordInfo = null
|
|
3128
|
+
try {
|
|
3129
|
+
wordInfo = typeof model.getWordAtPosition === 'function' ? model.getWordAtPosition(position) : null
|
|
3130
|
+
} catch {
|
|
3131
|
+
wordInfo = null
|
|
3132
|
+
}
|
|
3133
|
+
const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
|
|
3134
|
+
if (word.length < 2) return
|
|
3135
|
+
const path = modelPathRef.current
|
|
3136
|
+
const root = modelsRootRef.current
|
|
3137
|
+
if (path === null || root === null || root === '') return
|
|
3138
|
+
try {
|
|
3139
|
+
event.preventDefault()
|
|
3140
|
+
event.stopPropagation()
|
|
3141
|
+
} catch {
|
|
3142
|
+
/* ignore */
|
|
3143
|
+
}
|
|
3144
|
+
const beforePath = modelPathRef.current
|
|
3145
|
+
const beforePosition = instance.getPosition()
|
|
3146
|
+
try {
|
|
3147
|
+
const action = typeof instance.getAction === 'function' ? instance.getAction('editor.action.revealDefinition') : null
|
|
3148
|
+
if (action !== null && action !== undefined) {
|
|
3149
|
+
const supported = typeof action.isSupported === 'function' ? action.isSupported() : true
|
|
3150
|
+
if (supported !== false) await action.run()
|
|
3151
|
+
}
|
|
3152
|
+
} catch {
|
|
3153
|
+
/* ignore */
|
|
3154
|
+
}
|
|
3155
|
+
await new Promise((resolve) => { window.setTimeout(resolve, 160) })
|
|
3156
|
+
let monacoHandled = false
|
|
3157
|
+
try {
|
|
3158
|
+
const afterPosition = instance.getPosition()
|
|
3159
|
+
monacoHandled = modelPathRef.current !== beforePath
|
|
3160
|
+
|| (beforePosition !== null && beforePosition !== undefined && afterPosition !== null && afterPosition !== undefined
|
|
3161
|
+
&& (afterPosition.lineNumber !== beforePosition.lineNumber || afterPosition.column !== beforePosition.column))
|
|
3162
|
+
|| document.querySelector('.monaco-editor .peekview-widget, .monaco-editor .reference-zone-widget') !== null
|
|
3163
|
+
} catch {
|
|
3164
|
+
monacoHandled = false
|
|
3165
|
+
}
|
|
3166
|
+
if (monacoHandled) return
|
|
3167
|
+
try {
|
|
3168
|
+
const result = await G.api('code.definition', {
|
|
3169
|
+
root,
|
|
3170
|
+
path,
|
|
3171
|
+
line: position.lineNumber,
|
|
3172
|
+
column: position.column,
|
|
3173
|
+
word,
|
|
3174
|
+
content: model.getValue(),
|
|
3175
|
+
})
|
|
3176
|
+
const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
|
|
3177
|
+
if (matches.length === 0) return
|
|
3178
|
+
const openMatch = (item) => G.bus.emit('editor:open-at', { path: item.path, line: item.line, column: item.column })
|
|
3179
|
+
const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
|
|
3180
|
+
const top = matches[0]
|
|
3181
|
+
const topScore = Number(top.score) || 0
|
|
3182
|
+
/* 当前文件里的声明:直接跳,不打扰 */
|
|
3183
|
+
if (currentPath !== null && top.path === currentPath) {
|
|
3184
|
+
openMatch(top)
|
|
3185
|
+
return
|
|
3186
|
+
}
|
|
3187
|
+
const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
|
|
3188
|
+
/* 弱匹配(const/赋值等)只有在很近/很确定时才跳,避免点属性名时跳到别的仓库同名变量 */
|
|
3189
|
+
if (!isStrong(top) && topScore < 50) return
|
|
3190
|
+
if (topScore < 30) return
|
|
3191
|
+
const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
|
|
3192
|
+
if (cluster.length === 1) {
|
|
3193
|
+
openMatch(cluster[0])
|
|
3194
|
+
return
|
|
3195
|
+
}
|
|
3196
|
+
const declCluster = cluster.filter((item) => isStrong(item))
|
|
3197
|
+
if (declCluster.length === 0) {
|
|
3198
|
+
const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
|
|
3199
|
+
if (topScore >= 50 && topScore - secondScore >= 10) {
|
|
3200
|
+
openMatch(top)
|
|
3201
|
+
}
|
|
3202
|
+
return
|
|
3203
|
+
}
|
|
3204
|
+
const distinctFiles = new Set(declCluster.map((item) => item.path))
|
|
3205
|
+
if (distinctFiles.size === 1) {
|
|
3206
|
+
openMatch(declCluster[0])
|
|
3207
|
+
return
|
|
3208
|
+
}
|
|
3209
|
+
G.bus.emit('definition:pick', { word: result.word ?? word, matches: declCluster, x: event.clientX, y: event.clientY })
|
|
3210
|
+
} catch {
|
|
3211
|
+
/* ignore */
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
document.addEventListener('mousedown', onDefinitionClick, true)
|
|
3215
|
+
}
|
|
3216
|
+
} catch {
|
|
3217
|
+
/* ignore */
|
|
3218
|
+
}
|
|
3095
3219
|
} catch {
|
|
3096
3220
|
/* ignore */
|
|
3097
3221
|
}
|
|
@@ -10796,6 +10920,7 @@ G.GufaApp = function GufaApp(props) {
|
|
|
10796
10920
|
const gitInFlightRef = useRef(false)
|
|
10797
10921
|
const [modal, setModal] = useState(null)
|
|
10798
10922
|
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
|
10923
|
+
const [definitionPicker, setDefinitionPicker] = useState(null)
|
|
10799
10924
|
const [trashUndo, setTrashUndo] = useState([])
|
|
10800
10925
|
const [branchMenu, setBranchMenu] = useState(null)
|
|
10801
10926
|
const [workspaceDialog, setWorkspaceDialog] = useState(null)
|
|
@@ -11039,6 +11164,28 @@ G.GufaApp = function GufaApp(props) {
|
|
|
11039
11164
|
}, 120)
|
|
11040
11165
|
}, [openFile])
|
|
11041
11166
|
|
|
11167
|
+
/* Cmd/Ctrl+点击定义:编辑器 → App 跳转 / 多结果选择(兜底搜索在 host/code.js) */
|
|
11168
|
+
useEffect(() => {
|
|
11169
|
+
if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
|
|
11170
|
+
const offOpen = G.bus.on('editor:open-at', (detail) => {
|
|
11171
|
+
if (detail === null || detail === undefined || typeof detail.path !== 'string') return
|
|
11172
|
+
void openFileAt(detail.path, detail.line, detail.column)
|
|
11173
|
+
})
|
|
11174
|
+
const offPick = G.bus.on('definition:pick', (detail) => {
|
|
11175
|
+
if (detail === null || detail === undefined || !Array.isArray(detail.matches) || detail.matches.length === 0) return
|
|
11176
|
+
setDefinitionPicker({
|
|
11177
|
+
word: typeof detail.word === 'string' ? detail.word : '',
|
|
11178
|
+
matches: detail.matches,
|
|
11179
|
+
x: Number.isFinite(Number(detail.x)) ? Number(detail.x) : 240,
|
|
11180
|
+
y: Number.isFinite(Number(detail.y)) ? Number(detail.y) : 200,
|
|
11181
|
+
})
|
|
11182
|
+
})
|
|
11183
|
+
return () => {
|
|
11184
|
+
offOpen?.()
|
|
11185
|
+
offPick?.()
|
|
11186
|
+
}
|
|
11187
|
+
}, [openFileAt])
|
|
11188
|
+
|
|
11042
11189
|
/* 原子恢复标签集合:按快照顺序、去重、最后激活指定文件(避免 openFile 并发产生重复标签) */
|
|
11043
11190
|
const applyTabs = useCallback(async (paths, active) => {
|
|
11044
11191
|
if (project === null || !Array.isArray(paths)) return
|
|
@@ -13130,6 +13277,45 @@ G.GufaApp = function GufaApp(props) {
|
|
|
13130
13277
|
),
|
|
13131
13278
|
),
|
|
13132
13279
|
typeof G.UsageDock === 'function' ? h(G.UsageDock, { active: true }) : null,
|
|
13280
|
+
G.portal(definitionPicker === null
|
|
13281
|
+
? null
|
|
13282
|
+
: h(
|
|
13283
|
+
'div',
|
|
13284
|
+
{ style: { position: 'fixed', inset: 0, zIndex: 2147483120 }, onMouseDown: () => setDefinitionPicker(null) },
|
|
13285
|
+
h(
|
|
13286
|
+
'div',
|
|
13287
|
+
{
|
|
13288
|
+
className: 'gufa-menu',
|
|
13289
|
+
style: {
|
|
13290
|
+
position: 'fixed',
|
|
13291
|
+
left: `${Math.max(8, Math.min(definitionPicker.x, (typeof window !== 'undefined' ? window.innerWidth : 1200) - 380))}px`,
|
|
13292
|
+
top: `${Math.max(8, Math.min(definitionPicker.y, (typeof window !== 'undefined' ? window.innerHeight : 800) - 60))}px`,
|
|
13293
|
+
minWidth: '340px',
|
|
13294
|
+
maxWidth: '520px',
|
|
13295
|
+
maxHeight: '420px',
|
|
13296
|
+
overflowY: 'auto',
|
|
13297
|
+
},
|
|
13298
|
+
onMouseDown: (event) => event.stopPropagation(),
|
|
13299
|
+
},
|
|
13300
|
+
h(
|
|
13301
|
+
'div',
|
|
13302
|
+
{ style: { padding: '4px 9px 6px', fontSize: '11px', color: 'var(--gufa-text-dim)' } },
|
|
13303
|
+
`${t('editor.gotoDefinition')}:${definitionPicker.word}`,
|
|
13304
|
+
),
|
|
13305
|
+
...definitionPicker.matches.slice(0, 15).map((item, index) =>
|
|
13306
|
+
h(G.MenuItem, {
|
|
13307
|
+
key: `${item.path}:${item.line}:${item.column}:${index}`,
|
|
13308
|
+
icon: 'code',
|
|
13309
|
+
label: `${G.basename(item.path)} · ${G.dirname(item.path) === '' ? '.' : G.dirname(item.path)} :${item.line}`,
|
|
13310
|
+
onClick: () => {
|
|
13311
|
+
setDefinitionPicker(null)
|
|
13312
|
+
void openFileAt(item.path, item.line, item.column)
|
|
13313
|
+
},
|
|
13314
|
+
}),
|
|
13315
|
+
),
|
|
13316
|
+
),
|
|
13317
|
+
),
|
|
13318
|
+
),
|
|
13133
13319
|
G.portal(workspaceDialog === null
|
|
13134
13320
|
? null
|
|
13135
13321
|
: h(
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -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.
|
|
11
|
-
<key>CFBundleVersion</key><string>1.3.
|
|
10
|
+
<key>CFBundleShortVersionString</key><string>1.3.82</string>
|
|
11
|
+
<key>CFBundleVersion</key><string>1.3.82</string>
|
|
12
12
|
<key>LSUIElement</key><true/>
|
|
13
13
|
<key>NSHighResolutionCapable</key><true/>
|
|
14
14
|
<key>NSPrincipalClass</key><string>NSApplication</string>
|
|
Binary file
|
package/host/code.js
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 代码导航:Cmd/Ctrl+点击「跳转到定义 / 方法实现」的 Host 侧兜底实现。
|
|
3
|
+
*
|
|
4
|
+
* Monaco 自带的语言服务只覆盖已加载到 Monaco 的 model(以及 TS/JS 打开过的文件),
|
|
5
|
+
* 对未打开的文件、Python/Go/Rust 等没有内置语言服务的语言就找不到定义。这里做一个
|
|
6
|
+
* 项目级的轻量定义搜索:只匹配声明形态(function/class/const/def/func/fn/method/type…),
|
|
7
|
+
* 优先当前文件,其次同类语言文件,返回带行列号的结果供客户端跳转或列表选择。
|
|
8
|
+
*/
|
|
9
|
+
import { execFile } from 'node:child_process'
|
|
10
|
+
import { readFile, readdir, stat } from 'node:fs/promises'
|
|
11
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
12
|
+
import { promisify } from 'node:util'
|
|
13
|
+
|
|
14
|
+
import { ApiError, badRequest } from './context.js'
|
|
15
|
+
|
|
16
|
+
const runCommand = promisify(execFile)
|
|
17
|
+
const MAX_FILE_SIZE = 512 * 1024
|
|
18
|
+
const MAX_SCANNED = 3000
|
|
19
|
+
const TIME_BUDGET = 7000
|
|
20
|
+
const MAX_MATCHES = 30
|
|
21
|
+
const EXCLUDED = new Set([
|
|
22
|
+
'node_modules', '.git', 'dist', 'build', 'out', '.next', 'vendor', 'target', '.venv', 'venv',
|
|
23
|
+
'__pycache__', '.idea', '.cache', '.turbo', '.svelte-kit', '.nuxt', '.output', 'coverage',
|
|
24
|
+
'.gradle', 'DerivedData', 'Pods', '.tox', '.mypy_cache', '.pytest_cache', '.ruff_cache',
|
|
25
|
+
'.electron-cache', '.npm-cache', '.pip-cache', '.yarn', '.pnpm-store', '.pnpm',
|
|
26
|
+
])
|
|
27
|
+
const EXCLUDED_PREFIXES = ['.venv', '.npm-cache', '.pip-cache', '.electron-cache', '.pnpm', '.yarn', '.cache']
|
|
28
|
+
const SKIP_EXT = new Set([
|
|
29
|
+
'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'bmp', 'tiff', 'pdf', 'zip', 'gz', 'tgz', 'tar', '7z', 'rar', 'dmg', 'iso',
|
|
30
|
+
'mp4', 'mp3', 'wav', 'mov', 'avi', 'mkv', 'flac', 'jar', 'class', 'o', 'a', 'so', 'dylib', 'dll', 'exe', 'bin', 'dat',
|
|
31
|
+
'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'pyc', 'node',
|
|
32
|
+
])
|
|
33
|
+
|
|
34
|
+
function escapeRegExp(text) {
|
|
35
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extensionOf(rel) {
|
|
39
|
+
const name = String(rel).split('/').pop() ?? ''
|
|
40
|
+
const dot = name.lastIndexOf('.')
|
|
41
|
+
return dot <= 0 ? '' : name.slice(dot + 1).toLowerCase()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isExcludedDir(name) {
|
|
45
|
+
if (EXCLUDED.has(name)) return true
|
|
46
|
+
for (const prefix of EXCLUDED_PREFIXES) if (String(name).startsWith(prefix)) return true
|
|
47
|
+
return false
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function lineColumnAt(text, index) {
|
|
51
|
+
let line = 1
|
|
52
|
+
let lastNewline = -1
|
|
53
|
+
for (let i = 0; i < index && i < text.length; i += 1) {
|
|
54
|
+
if (text.charCodeAt(i) === 10) {
|
|
55
|
+
line += 1
|
|
56
|
+
lastNewline = i
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return { line, column: index - lastNewline }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function extractWord(lineText, column) {
|
|
63
|
+
const text = String(lineText ?? '')
|
|
64
|
+
const position = Math.max(0, Math.min(text.length - 1, column - 1))
|
|
65
|
+
const isWord = (char) => /[A-Za-z0-9_$]/.test(char)
|
|
66
|
+
if (!isWord(text[position] ?? '')) {
|
|
67
|
+
/* 在附近找最近的标识符字符(Cmd 点击可能落在词边上) */
|
|
68
|
+
let left = position
|
|
69
|
+
while (left >= 0 && !isWord(text[left])) left -= 1
|
|
70
|
+
if (left < 0) return ''
|
|
71
|
+
let right = position
|
|
72
|
+
while (right < text.length && isWord(text[right])) right += 1
|
|
73
|
+
return text.slice(left, right)
|
|
74
|
+
}
|
|
75
|
+
let start = position
|
|
76
|
+
while (start > 0 && isWord(text[start - 1])) start -= 1
|
|
77
|
+
let end = position
|
|
78
|
+
while (end < text.length && isWord(text[end])) end += 1
|
|
79
|
+
return text.slice(start, end)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 定义形态:返回 [{kind, weight, regex}],regex 需含一个捕获组交出定义词位置。 */
|
|
83
|
+
function definitionPatterns(word) {
|
|
84
|
+
const escaped = escapeRegExp(word)
|
|
85
|
+
return [
|
|
86
|
+
{ kind: 'function', weight: 22, regex: new RegExp(`\\bfunction\\s+(${escaped})\\b`) },
|
|
87
|
+
{ kind: 'class', weight: 22, regex: new RegExp(`\\bclass\\s+(${escaped})\\b`) },
|
|
88
|
+
{ kind: 'def', weight: 22, regex: new RegExp(`\\bdef\\s+(${escaped})\\b`) },
|
|
89
|
+
{ kind: 'func', weight: 22, regex: new RegExp(`\\bfunc\\s+(?:\\([^)]*\\)\\s*)?(${escaped})\\s*\\(`) },
|
|
90
|
+
{ kind: 'fn', weight: 22, regex: new RegExp(`\\bfn\\s+(${escaped})\\s*\\(`) },
|
|
91
|
+
{ kind: 'type', weight: 20, regex: new RegExp(`\\b(?:interface|type|enum|struct|trait|module|namespace|protocol)\\s+(${escaped})\\b`) },
|
|
92
|
+
{ kind: 'const', weight: 16, regex: new RegExp(`\\b(?:const|let|var|val)\\s+(${escaped})\\b`) },
|
|
93
|
+
{ kind: 'assign', weight: 14, regex: new RegExp(`\\b(${escaped})\\s*=\\s*(?:async\\s+)?(?:function|\\()`) },
|
|
94
|
+
{ kind: 'method', weight: 18, regex: new RegExp(`^\\s*(?:(?:public|private|protected|static|final|abstract|async|synchronized|override|virtual|export|default|get|set)\\s+)*[\\w<>\\[\\],\\s.?:*&]+\\s+(${escaped})\\s*\\(`) },
|
|
95
|
+
{ kind: 'export', weight: 18, regex: new RegExp(`\\bexport\\s+(?:default\\s+)?(?:const|let|var|function|class|async)\\s+(${escaped})\\b`) },
|
|
96
|
+
]
|
|
97
|
+
}
|
|
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
|
+
|
|
105
|
+
function scoreMatch(match, current) {
|
|
106
|
+
let score = match.weight
|
|
107
|
+
if (match.path === current.path) score += 120
|
|
108
|
+
if (extensionOf(match.path) === extensionOf(current.path)) score += 6
|
|
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)
|
|
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
|
|
119
|
+
return score
|
|
120
|
+
}
|
|
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
|
+
|
|
193
|
+
async function listCandidates(root, textBudgets) {
|
|
194
|
+
/* Git 项目用 git ls-files(尊重 .gitignore、含未跟踪文件),否则 BFS 遍历。 */
|
|
195
|
+
let isGit = false
|
|
196
|
+
try {
|
|
197
|
+
const dotGit = await stat(join(root, '.git'))
|
|
198
|
+
isGit = dotGit.isDirectory() || dotGit.isFile()
|
|
199
|
+
} catch {
|
|
200
|
+
isGit = false
|
|
201
|
+
}
|
|
202
|
+
const files = []
|
|
203
|
+
if (isGit) {
|
|
204
|
+
try {
|
|
205
|
+
const { stdout } = await runCommand('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
|
|
206
|
+
cwd: root,
|
|
207
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
208
|
+
timeout: 12000,
|
|
209
|
+
})
|
|
210
|
+
for (const rel of stdout.split('\0')) {
|
|
211
|
+
if (rel === '' || isExcludedDir(rel.split('/').pop() ?? '')) continue
|
|
212
|
+
if (SKIP_EXT.has(extensionOf(rel))) continue
|
|
213
|
+
files.push(rel)
|
|
214
|
+
if (files.length >= MAX_SCANNED) break
|
|
215
|
+
}
|
|
216
|
+
files.sort((a, b) => a.localeCompare(b))
|
|
217
|
+
return files
|
|
218
|
+
} catch {
|
|
219
|
+
/* 回退目录遍历 */
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const queue = ['']
|
|
223
|
+
let head = 0
|
|
224
|
+
while (head < queue.length && files.length < MAX_SCANNED) {
|
|
225
|
+
const dirRel = queue[head]
|
|
226
|
+
head += 1
|
|
227
|
+
let entries
|
|
228
|
+
try {
|
|
229
|
+
entries = await readdir(join(root, dirRel), { withFileTypes: true })
|
|
230
|
+
} catch {
|
|
231
|
+
continue
|
|
232
|
+
}
|
|
233
|
+
entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
|
|
234
|
+
for (const entry of entries) {
|
|
235
|
+
if (entry.isDirectory()) {
|
|
236
|
+
if (!isExcludedDir(entry.name)) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
|
|
237
|
+
continue
|
|
238
|
+
}
|
|
239
|
+
if (!entry.isFile()) continue
|
|
240
|
+
const rel = dirRel === '' ? entry.name : `${dirRel}/${entry.name}`
|
|
241
|
+
if (SKIP_EXT.has(extensionOf(rel))) continue
|
|
242
|
+
files.push(rel)
|
|
243
|
+
if (files.length >= MAX_SCANNED) break
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
void textBudgets
|
|
247
|
+
return files
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** 项目内相对路径解析(只读场景:拒绝绝对路径与 .. 逃逸)。 */
|
|
251
|
+
async function resolveInsideProject(root, raw) {
|
|
252
|
+
if (typeof raw !== 'string') throw badRequest('path must be a string')
|
|
253
|
+
if (isAbsolute(raw)) throw new ApiError('path-invalid', '不允许绝对路径', 400)
|
|
254
|
+
const absolute = resolve(root, raw === '' ? '.' : raw)
|
|
255
|
+
const rel = relative(root, absolute)
|
|
256
|
+
if (rel !== '' && (rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel))) {
|
|
257
|
+
throw new ApiError('path-outside', '路径超出项目范围', 403)
|
|
258
|
+
}
|
|
259
|
+
return absolute
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 在一段文本里找 word 的所有声明位置。 */
|
|
263
|
+
function findDefinitionsInText(text, relPath, word, patterns, results, current) {
|
|
264
|
+
if (results.length >= MAX_MATCHES) return
|
|
265
|
+
const lines = String(text).split(/\r?\n/)
|
|
266
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
267
|
+
const line = lines[index]
|
|
268
|
+
if (!line.includes(word)) continue
|
|
269
|
+
for (const pattern of patterns) {
|
|
270
|
+
const match = pattern.regex.exec(line)
|
|
271
|
+
if (match === null) continue
|
|
272
|
+
const column = (match.index ?? 0) + match[0].indexOf(match[1]) + 1
|
|
273
|
+
results.push({
|
|
274
|
+
path: relPath,
|
|
275
|
+
line: index + 1,
|
|
276
|
+
column: Math.max(1, column),
|
|
277
|
+
kind: pattern.kind,
|
|
278
|
+
weight: pattern.weight,
|
|
279
|
+
preview: line.trim().slice(0, 160),
|
|
280
|
+
score: 0,
|
|
281
|
+
})
|
|
282
|
+
break
|
|
283
|
+
}
|
|
284
|
+
if (results.length >= MAX_MATCHES) return
|
|
285
|
+
}
|
|
286
|
+
void current
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export async function definition(body, env) {
|
|
290
|
+
const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
|
|
291
|
+
const root = project.root
|
|
292
|
+
const rawPath = typeof body.path === 'string' ? body.path : ''
|
|
293
|
+
if (rawPath === '') throw badRequest('path is required')
|
|
294
|
+
const line = Number(body.line)
|
|
295
|
+
const column = Number(body.column)
|
|
296
|
+
if (!Number.isInteger(line) || line < 1 || !Number.isInteger(column) || column < 1) throw badRequest('line/column is invalid')
|
|
297
|
+
const absolute = await resolveInsideProject(root, rawPath)
|
|
298
|
+
const relPath = relative(root, absolute).split(sep).join('/')
|
|
299
|
+
let text = ''
|
|
300
|
+
if (typeof body.content === 'string' && Buffer.byteLength(body.content, 'utf8') <= 4 * 1024 * 1024) {
|
|
301
|
+
text = body.content
|
|
302
|
+
} else {
|
|
303
|
+
try {
|
|
304
|
+
const info = await stat(absolute)
|
|
305
|
+
if (info.size <= 4 * 1024 * 1024) text = await readFile(absolute, 'utf8')
|
|
306
|
+
} catch {
|
|
307
|
+
text = ''
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const lines = text.split(/\r?\n/)
|
|
311
|
+
const lineText = lines[line - 1] ?? ''
|
|
312
|
+
let word = typeof body.word === 'string' ? body.word.trim() : ''
|
|
313
|
+
if (word === '') word = extractWord(lineText, column)
|
|
314
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(word) || word.length < 2 || word.length > 80) {
|
|
315
|
+
return { word, matches: [], current: { path: relPath, line, column } }
|
|
316
|
+
}
|
|
317
|
+
const patterns = definitionPatterns(word)
|
|
318
|
+
const startedAt = Date.now()
|
|
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))
|
|
324
|
+
const results = []
|
|
325
|
+
/* 1) 当前文件(用编辑器传来的内容,能命中未保存的改动) */
|
|
326
|
+
findDefinitionsInText(text, relPath, word, patterns, results, current)
|
|
327
|
+
/* 2) 项目其它文件 */
|
|
328
|
+
const candidates = await listCandidates(root, null)
|
|
329
|
+
for (const candidate of candidates) {
|
|
330
|
+
if (candidate === relPath) continue
|
|
331
|
+
if (results.length >= MAX_MATCHES) break
|
|
332
|
+
if (Date.now() - startedAt > TIME_BUDGET) break
|
|
333
|
+
const candidateAbs = join(root, candidate)
|
|
334
|
+
const info = await stat(candidateAbs).catch(() => undefined)
|
|
335
|
+
if (info === undefined || !info.isFile() || info.size > MAX_FILE_SIZE) continue
|
|
336
|
+
let buffer
|
|
337
|
+
try {
|
|
338
|
+
buffer = await readFile(candidateAbs)
|
|
339
|
+
} catch {
|
|
340
|
+
continue
|
|
341
|
+
}
|
|
342
|
+
if (buffer.includes(0)) continue
|
|
343
|
+
const candidateText = buffer.toString('utf8')
|
|
344
|
+
if (!candidateText.includes(word)) continue
|
|
345
|
+
if (isMinifiedText(candidateText)) continue
|
|
346
|
+
findDefinitionsInText(candidateText, candidate, word, patterns, results, current)
|
|
347
|
+
}
|
|
348
|
+
/* 去重 + 打分 + 排序 */
|
|
349
|
+
const seen = new Set()
|
|
350
|
+
const matches = []
|
|
351
|
+
for (const item of results) {
|
|
352
|
+
const key = `${item.path}:${item.line}:${item.column}`
|
|
353
|
+
if (seen.has(key)) continue
|
|
354
|
+
seen.add(key)
|
|
355
|
+
const candidate = { ...item, importBoost: importTargets.has(item.path) }
|
|
356
|
+
matches.push({
|
|
357
|
+
path: item.path,
|
|
358
|
+
line: item.line,
|
|
359
|
+
column: item.column,
|
|
360
|
+
kind: item.kind,
|
|
361
|
+
preview: item.preview,
|
|
362
|
+
score: scoreMatch(candidate, current),
|
|
363
|
+
})
|
|
364
|
+
}
|
|
365
|
+
matches.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path) || a.line - b.line)
|
|
366
|
+
return {
|
|
367
|
+
word,
|
|
368
|
+
matches: matches.slice(0, MAX_MATCHES),
|
|
369
|
+
current: { path: relPath, line, column },
|
|
370
|
+
truncated: matches.length > MAX_MATCHES,
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export function register(router, env) {
|
|
375
|
+
router.method('code.definition', (body) => definition(body, env))
|
|
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'
|
|
@@ -243,6 +244,19 @@ async function listProjectCandidates(root, project, maxScanned) {
|
|
|
243
244
|
}
|
|
244
245
|
|
|
245
246
|
export function register(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
|
+
})
|
|
259
|
+
|
|
246
260
|
router.method('fs.list', async (body) => {
|
|
247
261
|
const root = await projectOf(env, body)
|
|
248
262
|
const absolute = await resolveProjectPath(root, typeof body.path === 'string' ? body.path : '')
|
package/package.json
CHANGED
|
@@ -12,6 +12,7 @@ import { join } from 'node:path'
|
|
|
12
12
|
import * as assets from '../host/assets.js'
|
|
13
13
|
import * as floatPlatform from '../host/float-platform.js'
|
|
14
14
|
import * as chat from '../host/chat.js'
|
|
15
|
+
import * as code from '../host/code.js'
|
|
15
16
|
import * as fs from '../host/fs.js'
|
|
16
17
|
import * as git from '../host/git.js'
|
|
17
18
|
import * as project from '../host/project.js'
|
|
@@ -67,7 +68,7 @@ const sandbox = mkdtempSync(join(tmpdir(), 'gufa-selftest-'))
|
|
|
67
68
|
const projectDir = join(sandbox, 'demo-project')
|
|
68
69
|
const router = makeRouter()
|
|
69
70
|
const env = { ctx: { get: () => undefined }, projects: new ProjectRegistry() }
|
|
70
|
-
for (const module of [assets, project, fs, git, ssh, terminal, chat]) module.register(router, env)
|
|
71
|
+
for (const module of [assets, project, fs, git, ssh, terminal, chat, code]) module.register(router, env)
|
|
71
72
|
|
|
72
73
|
try {
|
|
73
74
|
console.log('project.create / project.open')
|
|
@@ -217,6 +218,25 @@ try {
|
|
|
217
218
|
const diff = await call(router, 'git.diff', { root, path: 'src/main.ts' })
|
|
218
219
|
check('diff contains change', diff.patch.includes('43'))
|
|
219
220
|
|
|
221
|
+
console.log('code.definition')
|
|
222
|
+
await call(router, 'fs.create', { root, path: 'nav', kind: 'dir' })
|
|
223
|
+
await call(router, 'fs.create', { root, path: 'nav/defs.js', kind: 'file' })
|
|
224
|
+
await call(router, 'fs.write', { root, path: 'nav/defs.js', content: 'export function helperFn(){ return 1 }\n\nexport class WidgetBox {\n render(){ return 2 }\n}\n' })
|
|
225
|
+
await call(router, 'fs.create', { root, path: 'nav/use.js', kind: 'file' })
|
|
226
|
+
const useContent = 'const value = helperFn()\nconst widget = new WidgetBox()\nwidget.render()\n'
|
|
227
|
+
await call(router, 'fs.write', { root, path: 'nav/use.js', content: useContent })
|
|
228
|
+
const defsResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 15, word: 'helperFn', content: useContent })
|
|
229
|
+
check('definition finds cross-file function', defsResult.matches.some((item) => item.path === 'nav/defs.js' && item.line === 1), JSON.stringify(defsResult.matches.slice(0, 2)))
|
|
230
|
+
const classResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 2, column: 20, word: 'WidgetBox', content: useContent })
|
|
231
|
+
check('definition finds class', classResult.matches.some((item) => item.path === 'nav/defs.js' && item.kind === 'class'), JSON.stringify(classResult.matches.slice(0, 2)))
|
|
232
|
+
const methodResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 3, column: 9, word: 'render', content: useContent })
|
|
233
|
+
check('definition finds method', methodResult.matches.some((item) => item.path === 'nav/defs.js' && item.kind === 'method'), JSON.stringify(methodResult.matches.slice(0, 2)))
|
|
234
|
+
const derivedResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 16, content: useContent })
|
|
235
|
+
check('definition derives word from line/column', derivedResult.word === 'helperFn' && derivedResult.matches.length > 0, JSON.stringify(derivedResult.word))
|
|
236
|
+
const emptyResult = await call(router, 'code.definition', { root, path: 'nav/use.js', line: 1, column: 7, content: useContent, word: 'x' })
|
|
237
|
+
check('definition ignores too-short word', emptyResult.word === 'x' && emptyResult.matches.length === 0)
|
|
238
|
+
await call(router, 'fs.delete', { root, path: 'nav' }).catch(() => {})
|
|
239
|
+
|
|
220
240
|
console.log('workspaces')
|
|
221
241
|
const fakeSessions = new Map([
|
|
222
242
|
['s1', { id: 's1', updatedAt: 20 }],
|
package/src/client/00-core.js
CHANGED
|
@@ -118,6 +118,7 @@ const DICT_ZH = {
|
|
|
118
118
|
'shortcuts.newTerminal': '新建终端',
|
|
119
119
|
'shortcuts.help': '打开 / 关闭本快捷键列表',
|
|
120
120
|
'shortcuts.editorTitle': '编辑器(Monaco / VS Code 同款键位)',
|
|
121
|
+
'editor.gotoDefinition': '跳转到定义',
|
|
121
122
|
'editorKeys.comment': '切换行注释',
|
|
122
123
|
'editorKeys.blockComment': '切换块注释',
|
|
123
124
|
'editorKeys.nextOccurrence': '选中下一个相同内容(多光标)',
|
|
@@ -374,6 +375,7 @@ const DICT_EN = {
|
|
|
374
375
|
'shortcuts.newTerminal': 'New terminal',
|
|
375
376
|
'shortcuts.help': 'Show / hide this shortcut list',
|
|
376
377
|
'shortcuts.editorTitle': 'Editor (Monaco / VS Code keybindings)',
|
|
378
|
+
'editor.gotoDefinition': 'Go to definition',
|
|
377
379
|
'editorKeys.comment': 'Toggle line comment',
|
|
378
380
|
'editorKeys.blockComment': 'Toggle block comment',
|
|
379
381
|
'editorKeys.nextOccurrence': 'Add next occurrence to multi-cursor',
|
package/src/client/20-editor.js
CHANGED
|
@@ -399,7 +399,10 @@
|
|
|
399
399
|
if (gufaReadyMonaco() === null) gufaMonacoPromise = null
|
|
400
400
|
}
|
|
401
401
|
|
|
402
|
-
|
|
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 为项目绝对路径)。
|
|
@@ -746,6 +749,125 @@
|
|
|
746
749
|
/* ignore */
|
|
747
750
|
}
|
|
748
751
|
})
|
|
752
|
+
|
|
753
|
+
/* Cmd/Ctrl+点击跳转定义:先走 Monaco 语言服务;没有提供者(未打开的文件、
|
|
754
|
+
非 TS/JS 语言等)时回退到 Host 的项目级定义搜索,单结果直接跳,多结果弹选择。 */
|
|
755
|
+
try {
|
|
756
|
+
const domNode = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
|
|
757
|
+
if (domNode !== null && domNode !== undefined) {
|
|
758
|
+
const onDefinitionClick = async (event) => {
|
|
759
|
+
try {
|
|
760
|
+
const currentDom = typeof instance.getDomNode === 'function' ? instance.getDomNode() : null
|
|
761
|
+
if (currentDom === null || currentDom === undefined || !(event.target instanceof Node) || !currentDom.contains(event.target)) return
|
|
762
|
+
} catch {
|
|
763
|
+
return
|
|
764
|
+
}
|
|
765
|
+
if (event.button !== 0 || event.defaultPrevented === true) return
|
|
766
|
+
const primary = typeof G.isMacPlatform === 'function' ? G.isMacPlatform() : true
|
|
767
|
+
const pressed = primary ? event.metaKey === true : event.ctrlKey === true
|
|
768
|
+
if (!pressed || event.altKey === true || event.shiftKey === true) return
|
|
769
|
+
if (event.target instanceof Element && event.target.closest('a') !== null) return
|
|
770
|
+
let target = null
|
|
771
|
+
try {
|
|
772
|
+
target = typeof instance.getTargetAtClientPoint === 'function' ? instance.getTargetAtClientPoint(event.clientX, event.clientY) : null
|
|
773
|
+
} catch {
|
|
774
|
+
target = null
|
|
775
|
+
}
|
|
776
|
+
const position = target !== null && target !== undefined ? target.position : null
|
|
777
|
+
const model = instance.getModel()
|
|
778
|
+
if (position === null || position === undefined || model === null || model === undefined) return
|
|
779
|
+
let wordInfo = null
|
|
780
|
+
try {
|
|
781
|
+
wordInfo = typeof model.getWordAtPosition === 'function' ? model.getWordAtPosition(position) : null
|
|
782
|
+
} catch {
|
|
783
|
+
wordInfo = null
|
|
784
|
+
}
|
|
785
|
+
const word = wordInfo !== null && wordInfo !== undefined && typeof wordInfo.word === 'string' ? wordInfo.word : ''
|
|
786
|
+
if (word.length < 2) return
|
|
787
|
+
const path = modelPathRef.current
|
|
788
|
+
const root = modelsRootRef.current
|
|
789
|
+
if (path === null || root === null || root === '') return
|
|
790
|
+
try {
|
|
791
|
+
event.preventDefault()
|
|
792
|
+
event.stopPropagation()
|
|
793
|
+
} catch {
|
|
794
|
+
/* ignore */
|
|
795
|
+
}
|
|
796
|
+
const beforePath = modelPathRef.current
|
|
797
|
+
const beforePosition = instance.getPosition()
|
|
798
|
+
try {
|
|
799
|
+
const action = typeof instance.getAction === 'function' ? instance.getAction('editor.action.revealDefinition') : null
|
|
800
|
+
if (action !== null && action !== undefined) {
|
|
801
|
+
const supported = typeof action.isSupported === 'function' ? action.isSupported() : true
|
|
802
|
+
if (supported !== false) await action.run()
|
|
803
|
+
}
|
|
804
|
+
} catch {
|
|
805
|
+
/* ignore */
|
|
806
|
+
}
|
|
807
|
+
await new Promise((resolve) => { window.setTimeout(resolve, 160) })
|
|
808
|
+
let monacoHandled = false
|
|
809
|
+
try {
|
|
810
|
+
const afterPosition = instance.getPosition()
|
|
811
|
+
monacoHandled = modelPathRef.current !== beforePath
|
|
812
|
+
|| (beforePosition !== null && beforePosition !== undefined && afterPosition !== null && afterPosition !== undefined
|
|
813
|
+
&& (afterPosition.lineNumber !== beforePosition.lineNumber || afterPosition.column !== beforePosition.column))
|
|
814
|
+
|| document.querySelector('.monaco-editor .peekview-widget, .monaco-editor .reference-zone-widget') !== null
|
|
815
|
+
} catch {
|
|
816
|
+
monacoHandled = false
|
|
817
|
+
}
|
|
818
|
+
if (monacoHandled) return
|
|
819
|
+
try {
|
|
820
|
+
const result = await G.api('code.definition', {
|
|
821
|
+
root,
|
|
822
|
+
path,
|
|
823
|
+
line: position.lineNumber,
|
|
824
|
+
column: position.column,
|
|
825
|
+
word,
|
|
826
|
+
content: model.getValue(),
|
|
827
|
+
})
|
|
828
|
+
const matches = result !== null && result !== undefined && Array.isArray(result.matches) ? result.matches : []
|
|
829
|
+
if (matches.length === 0) return
|
|
830
|
+
const openMatch = (item) => G.bus.emit('editor:open-at', { path: item.path, line: item.line, column: item.column })
|
|
831
|
+
const currentPath = result.current !== null && result.current !== undefined && typeof result.current.path === 'string' ? result.current.path : null
|
|
832
|
+
const top = matches[0]
|
|
833
|
+
const topScore = Number(top.score) || 0
|
|
834
|
+
/* 当前文件里的声明:直接跳,不打扰 */
|
|
835
|
+
if (currentPath !== null && top.path === currentPath) {
|
|
836
|
+
openMatch(top)
|
|
837
|
+
return
|
|
838
|
+
}
|
|
839
|
+
const isStrong = (item) => GUFA_DEFINITION_STRONG_KINDS.has(item.kind)
|
|
840
|
+
/* 弱匹配(const/赋值等)只有在很近/很确定时才跳,避免点属性名时跳到别的仓库同名变量 */
|
|
841
|
+
if (!isStrong(top) && topScore < 50) return
|
|
842
|
+
if (topScore < 30) return
|
|
843
|
+
const cluster = matches.filter((item) => (Number(item.score) || 0) >= topScore - 8).slice(0, 8)
|
|
844
|
+
if (cluster.length === 1) {
|
|
845
|
+
openMatch(cluster[0])
|
|
846
|
+
return
|
|
847
|
+
}
|
|
848
|
+
const declCluster = cluster.filter((item) => isStrong(item))
|
|
849
|
+
if (declCluster.length === 0) {
|
|
850
|
+
const secondScore = matches.length > 1 ? Number(matches[1].score) || 0 : 0
|
|
851
|
+
if (topScore >= 50 && topScore - secondScore >= 10) {
|
|
852
|
+
openMatch(top)
|
|
853
|
+
}
|
|
854
|
+
return
|
|
855
|
+
}
|
|
856
|
+
const distinctFiles = new Set(declCluster.map((item) => item.path))
|
|
857
|
+
if (distinctFiles.size === 1) {
|
|
858
|
+
openMatch(declCluster[0])
|
|
859
|
+
return
|
|
860
|
+
}
|
|
861
|
+
G.bus.emit('definition:pick', { word: result.word ?? word, matches: declCluster, x: event.clientX, y: event.clientY })
|
|
862
|
+
} catch {
|
|
863
|
+
/* ignore */
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
document.addEventListener('mousedown', onDefinitionClick, true)
|
|
867
|
+
}
|
|
868
|
+
} catch {
|
|
869
|
+
/* ignore */
|
|
870
|
+
}
|
|
749
871
|
} catch {
|
|
750
872
|
/* ignore */
|
|
751
873
|
}
|
package/src/client/90-app.js
CHANGED
|
@@ -267,6 +267,7 @@ G.GufaApp = function GufaApp(props) {
|
|
|
267
267
|
const gitInFlightRef = useRef(false)
|
|
268
268
|
const [modal, setModal] = useState(null)
|
|
269
269
|
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
|
270
|
+
const [definitionPicker, setDefinitionPicker] = useState(null)
|
|
270
271
|
const [trashUndo, setTrashUndo] = useState([])
|
|
271
272
|
const [branchMenu, setBranchMenu] = useState(null)
|
|
272
273
|
const [workspaceDialog, setWorkspaceDialog] = useState(null)
|
|
@@ -510,6 +511,28 @@ G.GufaApp = function GufaApp(props) {
|
|
|
510
511
|
}, 120)
|
|
511
512
|
}, [openFile])
|
|
512
513
|
|
|
514
|
+
/* Cmd/Ctrl+点击定义:编辑器 → App 跳转 / 多结果选择(兜底搜索在 host/code.js) */
|
|
515
|
+
useEffect(() => {
|
|
516
|
+
if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
|
|
517
|
+
const offOpen = G.bus.on('editor:open-at', (detail) => {
|
|
518
|
+
if (detail === null || detail === undefined || typeof detail.path !== 'string') return
|
|
519
|
+
void openFileAt(detail.path, detail.line, detail.column)
|
|
520
|
+
})
|
|
521
|
+
const offPick = G.bus.on('definition:pick', (detail) => {
|
|
522
|
+
if (detail === null || detail === undefined || !Array.isArray(detail.matches) || detail.matches.length === 0) return
|
|
523
|
+
setDefinitionPicker({
|
|
524
|
+
word: typeof detail.word === 'string' ? detail.word : '',
|
|
525
|
+
matches: detail.matches,
|
|
526
|
+
x: Number.isFinite(Number(detail.x)) ? Number(detail.x) : 240,
|
|
527
|
+
y: Number.isFinite(Number(detail.y)) ? Number(detail.y) : 200,
|
|
528
|
+
})
|
|
529
|
+
})
|
|
530
|
+
return () => {
|
|
531
|
+
offOpen?.()
|
|
532
|
+
offPick?.()
|
|
533
|
+
}
|
|
534
|
+
}, [openFileAt])
|
|
535
|
+
|
|
513
536
|
/* 原子恢复标签集合:按快照顺序、去重、最后激活指定文件(避免 openFile 并发产生重复标签) */
|
|
514
537
|
const applyTabs = useCallback(async (paths, active) => {
|
|
515
538
|
if (project === null || !Array.isArray(paths)) return
|
|
@@ -2601,6 +2624,45 @@ G.GufaApp = function GufaApp(props) {
|
|
|
2601
2624
|
),
|
|
2602
2625
|
),
|
|
2603
2626
|
typeof G.UsageDock === 'function' ? h(G.UsageDock, { active: true }) : null,
|
|
2627
|
+
G.portal(definitionPicker === null
|
|
2628
|
+
? null
|
|
2629
|
+
: h(
|
|
2630
|
+
'div',
|
|
2631
|
+
{ style: { position: 'fixed', inset: 0, zIndex: 2147483120 }, onMouseDown: () => setDefinitionPicker(null) },
|
|
2632
|
+
h(
|
|
2633
|
+
'div',
|
|
2634
|
+
{
|
|
2635
|
+
className: 'gufa-menu',
|
|
2636
|
+
style: {
|
|
2637
|
+
position: 'fixed',
|
|
2638
|
+
left: `${Math.max(8, Math.min(definitionPicker.x, (typeof window !== 'undefined' ? window.innerWidth : 1200) - 380))}px`,
|
|
2639
|
+
top: `${Math.max(8, Math.min(definitionPicker.y, (typeof window !== 'undefined' ? window.innerHeight : 800) - 60))}px`,
|
|
2640
|
+
minWidth: '340px',
|
|
2641
|
+
maxWidth: '520px',
|
|
2642
|
+
maxHeight: '420px',
|
|
2643
|
+
overflowY: 'auto',
|
|
2644
|
+
},
|
|
2645
|
+
onMouseDown: (event) => event.stopPropagation(),
|
|
2646
|
+
},
|
|
2647
|
+
h(
|
|
2648
|
+
'div',
|
|
2649
|
+
{ style: { padding: '4px 9px 6px', fontSize: '11px', color: 'var(--gufa-text-dim)' } },
|
|
2650
|
+
`${t('editor.gotoDefinition')}:${definitionPicker.word}`,
|
|
2651
|
+
),
|
|
2652
|
+
...definitionPicker.matches.slice(0, 15).map((item, index) =>
|
|
2653
|
+
h(G.MenuItem, {
|
|
2654
|
+
key: `${item.path}:${item.line}:${item.column}:${index}`,
|
|
2655
|
+
icon: 'code',
|
|
2656
|
+
label: `${G.basename(item.path)} · ${G.dirname(item.path) === '' ? '.' : G.dirname(item.path)} :${item.line}`,
|
|
2657
|
+
onClick: () => {
|
|
2658
|
+
setDefinitionPicker(null)
|
|
2659
|
+
void openFileAt(item.path, item.line, item.column)
|
|
2660
|
+
},
|
|
2661
|
+
}),
|
|
2662
|
+
),
|
|
2663
|
+
),
|
|
2664
|
+
),
|
|
2665
|
+
),
|
|
2604
2666
|
G.portal(workspaceDialog === null
|
|
2605
2667
|
? null
|
|
2606
2668
|
: h(
|