perf(hooks): replace the ref object with a plain object (#15061)

Co-authored-by: 唐铃 <ling.tang01@geely.com>
This commit is contained in:
Polaris-tl 2024-07-28 18:22:44 +08:00 committed by GitHub
parent 2fce7b469b
commit ce0220612e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,19 +1,18 @@
import { ref } from 'vue'
import type { ShallowRef } from 'vue' import type { ShallowRef } from 'vue'
// Keep input cursor in the correct position when we use formatter. interface SelectionInfo {
export function useCursor(
input: ShallowRef<HTMLInputElement | undefined>
): [() => void, () => void] {
const selectionRef = ref<{
selectionStart?: number selectionStart?: number
selectionEnd?: number selectionEnd?: number
value?: string value?: string
beforeTxt?: string beforeTxt?: string
afterTxt?: string afterTxt?: string
}>() }
// Keep input cursor in the correct position when we use formatter.
export function useCursor(
input: ShallowRef<HTMLInputElement | undefined>
): [() => void, () => void] {
let selectionInfo: SelectionInfo
function recordCursor() { function recordCursor() {
if (input.value == undefined) return if (input.value == undefined) return
@ -24,7 +23,7 @@ export function useCursor(
const beforeTxt = value.slice(0, Math.max(0, selectionStart)) const beforeTxt = value.slice(0, Math.max(0, selectionStart))
const afterTxt = value.slice(Math.max(0, selectionEnd)) const afterTxt = value.slice(Math.max(0, selectionEnd))
selectionRef.value = { selectionInfo = {
selectionStart, selectionStart,
selectionEnd, selectionEnd,
value, value,
@ -33,10 +32,10 @@ export function useCursor(
} }
} }
function setCursor() { function setCursor() {
if (input.value == undefined || selectionRef.value == undefined) return if (input.value == undefined || selectionInfo == undefined) return
const { value } = input.value const { value } = input.value
const { beforeTxt, afterTxt, selectionStart } = selectionRef.value const { beforeTxt, afterTxt, selectionStart } = selectionInfo
if ( if (
beforeTxt == undefined || beforeTxt == undefined ||