Skip to content

Commit

Permalink
feat(hook): ✨ 添加光标位置保存与恢复功能 (#152)
Browse files Browse the repository at this point in the history
- 新增响应式变量 `lastCursorPosition` 用于保存和恢复输入框的光标位置
- 在输入框失去焦点时保存当前光标位置
- 在输入框获得焦点时恢复上次保存的光标位置
- 更新光标位置的逻辑以确保用户体验流畅
  • Loading branch information
CHIMOOO authored Jan 7, 2025
1 parent cb08e62 commit 53b5935
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion src/hooks/useMsgInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,15 @@ export const useMsgInput = (messageInputDom: Ref) => {
topicKeyword
)

// 在文件顶部添加新的响应式变量
const lastCursorPosition = ref<{
range: Range | null
selection: Selection | null
}>({
range: null,
selection: null
})

watchEffect(() => {
chatKey.value = chat.value.sendKey
if (!ait.value && personList.value.length > 0) {
Expand Down Expand Up @@ -368,6 +377,12 @@ export const useMsgInput = (messageInputDom: Ref) => {
return
}

// 保存最后的光标位置
lastCursorPosition.value = {
range: range.cloneRange(),
selection
}

/** 获取当前节点 */
const curNode = range.endContainer
/** 判断当前节点是否是文本节点 */
Expand Down Expand Up @@ -439,7 +454,15 @@ export const useMsgInput = (messageInputDom: Ref) => {
}
// 先确保输入框获得焦点
messageInputDom.value?.focus()
// 先获取并保存当前的编辑器范围

// 恢复上次保存的光标位置
if (lastCursorPosition.value.range && lastCursorPosition.value.selection) {
const selection = window.getSelection()
selection?.removeAllRanges()
selection?.addRange(lastCursorPosition.value.range)
}

// 获取当前光标位置
const { range: currentRange, selection: currentSelection } = getEditorRange()!
editorRange.value = { range: currentRange, selection: currentSelection }

Expand Down Expand Up @@ -467,6 +490,15 @@ export const useMsgInput = (messageInputDom: Ref) => {
insertNode(MsgEnum.AIT, item.name, {} as HTMLElement)
triggerInputEvent(messageInputDom.value)
ait.value = false

// 更新最后的光标位置
const newRange = getEditorRange()
if (newRange) {
lastCursorPosition.value = {
range: newRange.range.cloneRange(),
selection: newRange.selection
}
}
}

/** 处理点击 / 提及框事件 */
Expand Down Expand Up @@ -588,6 +620,17 @@ export const useMsgInput = (messageInputDom: Ref) => {
})
}
})

// 添加失焦事件监听
messageInputDom.value?.addEventListener('blur', () => {
const { range, selection } = getEditorRange()!
if (range && selection) {
lastCursorPosition.value = {
range: range.cloneRange(),
selection
}
}
})
})

return {
Expand Down

0 comments on commit 53b5935

Please sign in to comment.