fix: codeframe marker should have min width of 1

This commit is contained in:
Evan You 2019-12-19 15:42:53 -05:00
parent d6da48a33f
commit 02c6d5c4e3
2 changed files with 5 additions and 7 deletions

View File

@ -36,7 +36,6 @@ import { generateCodeFrame as _genCodeFrame } from '@vue/shared'
const generateCodeFrame = _genCodeFrame as ( const generateCodeFrame = _genCodeFrame as (
source: string, source: string,
start?: number, start?: number,
end?: number, end?: number
lineOffset?: number
) => string ) => string
export { generateCodeFrame } export { generateCodeFrame }

View File

@ -3,8 +3,7 @@ const range: number = 2
export function generateCodeFrame( export function generateCodeFrame(
source: string, source: string,
start = 0, start = 0,
end = source.length, end = source.length
lineOffset = 0
): string { ): string {
const lines = source.split(/\r?\n/) const lines = source.split(/\r?\n/)
let count = 0 let count = 0
@ -14,20 +13,20 @@ export function generateCodeFrame(
if (count >= start) { if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) { for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) continue if (j < 0 || j >= lines.length) continue
const line = j + 1 + lineOffset const line = j + 1
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`) res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`)
const lineLength = lines[j].length const lineLength = lines[j].length
if (j === i) { if (j === i) {
// push underline // push underline
const pad = start - (count - lineLength) + 1 const pad = start - (count - lineLength) + 1
const length = Math.max( const length = Math.max(
0, 1,
end > count ? lineLength - pad : end - start end > count ? lineLength - pad : end - start
) )
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)) res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length))
} else if (j > i) { } else if (j > i) {
if (end > count) { if (end > count) {
const length = Math.min(end - count, lineLength) const length = Math.max(Math.min(end - count, lineLength), 1)
res.push(` | ` + '^'.repeat(length)) res.push(` | ` + '^'.repeat(length))
} }
count += lineLength + 1 count += lineLength + 1