52 lines
1.2 KiB
JavaScript
52 lines
1.2 KiB
JavaScript
import { ref, nextTick } from 'vue'
|
|
|
|
const LINE_HEIGHT = 22.4
|
|
const PADDING = 16
|
|
|
|
export function countLines(text) {
|
|
return text ? text.split('\n').length : 1
|
|
}
|
|
|
|
export function useLineNumberEditor(getText, options = {}) {
|
|
const { onBeforeUpdate } = options
|
|
|
|
const containerRef = ref(null)
|
|
const editorRef = ref(null)
|
|
const lineCount = ref(1)
|
|
|
|
const adjustEditorHeight = () => {
|
|
const editor = editorRef.value
|
|
if (!editor) return
|
|
|
|
editor.style.height = 'auto'
|
|
const scrollHeight = editor.scrollHeight
|
|
const minHeight = PADDING + LINE_HEIGHT + PADDING
|
|
editor.style.height = `${Math.max(scrollHeight, minHeight)}px`
|
|
}
|
|
|
|
const updateLineCount = () => {
|
|
if (onBeforeUpdate) onBeforeUpdate()
|
|
lineCount.value = countLines(getText())
|
|
nextTick(adjustEditorHeight)
|
|
}
|
|
|
|
const resetEditorScroll = () => {
|
|
if (containerRef.value) containerRef.value.scrollTop = 0
|
|
if (editorRef.value) editorRef.value.scrollTop = 0
|
|
}
|
|
|
|
const initEditor = () => {
|
|
nextTick(updateLineCount)
|
|
}
|
|
|
|
return {
|
|
containerRef,
|
|
editorRef,
|
|
lineCount,
|
|
updateLineCount,
|
|
adjustEditorHeight,
|
|
resetEditorScroll,
|
|
initEditor,
|
|
}
|
|
}
|