refactor: move codeframe to @vue/shared
This commit is contained in:
37
packages/shared/src/codeframe.ts
Normal file
37
packages/shared/src/codeframe.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
const range: number = 2
|
||||
|
||||
export function generateCodeFrame(
|
||||
source: string,
|
||||
start: number = 0,
|
||||
end: number = source.length
|
||||
): string {
|
||||
const lines = source.split(/\r?\n/)
|
||||
let count = 0
|
||||
const res = []
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
count += lines[i].length + 1
|
||||
if (count >= start) {
|
||||
for (let j = i - range; j <= i + range || end > count; j++) {
|
||||
if (j < 0 || j >= lines.length) continue
|
||||
res.push(
|
||||
`${j + 1}${' '.repeat(3 - String(j + 1).length)}| ${lines[j]}`
|
||||
)
|
||||
const lineLength = lines[j].length
|
||||
if (j === i) {
|
||||
// push underline
|
||||
const pad = start - (count - lineLength) + 1
|
||||
const length = end > count ? lineLength - pad : end - start
|
||||
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
|
||||
} else if (j > i) {
|
||||
if (end > count) {
|
||||
const length = Math.min(end - count, lineLength)
|
||||
res.push(` | ` + '^'.repeat(length))
|
||||
}
|
||||
count += lineLength + 1
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return res.join('\n')
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { makeMap } from './makeMap'
|
||||
export { makeMap }
|
||||
export * from './patchFlags'
|
||||
export { isGloballyWhitelisted } from './globalsWhitelist'
|
||||
export { generateCodeFrame } from './codeframe'
|
||||
|
||||
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
|
||||
? Object.freeze({})
|
||||
|
||||
Reference in New Issue
Block a user