/
codeframe.js
285 lines (246 loc) Β· 8.73 KB
/
codeframe.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// @flow
import type {DiagnosticCodeHighlight} from '@parcel/diagnostic';
import chalk from 'chalk';
import emphasize from 'emphasize';
import stringWidth from 'string-width';
import sliceAnsi from 'slice-ansi';
type CodeFramePadding = {|
before: number,
after: number,
|};
type CodeFrameOptionsInput = $Shape<CodeFrameOptions>;
type CodeFrameOptions = {|
useColor: boolean,
syntaxHighlighting: boolean,
maxLines: number,
padding: CodeFramePadding,
terminalWidth: number,
language?: string,
|};
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
const TAB_REPLACE_REGEX = /\t/g;
const TAB_REPLACEMENT = ' ';
const DEFAULT_TERMINAL_WIDTH = 80;
const highlightSyntax = (txt: string, lang?: string): string => {
if (lang) {
try {
return emphasize.highlight(lang, txt).value;
} catch (e) {
// fallback for unknown languages...
}
}
return emphasize.highlightAuto(txt).value;
};
export default function codeFrame(
code: string,
highlights: Array<DiagnosticCodeHighlight>,
inputOpts: CodeFrameOptionsInput = {},
): string {
if (highlights.length < 1) return '';
let opts: CodeFrameOptions = {
useColor: !!inputOpts.useColor,
syntaxHighlighting: !!inputOpts.syntaxHighlighting,
language: inputOpts.language,
maxLines: inputOpts.maxLines ?? 12,
terminalWidth: inputOpts.terminalWidth || DEFAULT_TERMINAL_WIDTH,
padding: inputOpts.padding || {
before: 1,
after: 2,
},
};
// Highlights messages and prefixes when colors are enabled
const highlighter = (s: string, bold?: boolean) => {
if (opts.useColor) {
let redString = chalk.red(s);
return bold ? chalk.bold(redString) : redString;
}
return s;
};
// Prefix lines with the line number
const lineNumberPrefixer = (params: {|
lineNumber?: string,
lineNumberLength: number,
isHighlighted: boolean,
|}) => {
let {lineNumber, lineNumberLength, isHighlighted} = params;
return `${isHighlighted ? highlighter('>') : ' '} ${
lineNumber
? lineNumber.padStart(lineNumberLength, ' ')
: ' '.repeat(lineNumberLength)
} | `;
};
// Make columns/lines start at 1
highlights = highlights.map(h => {
return {
start: {
column: h.start.column - 1,
line: h.start.line - 1,
},
end: {
column: h.end.column - 1,
line: h.end.line - 1,
},
message: h.message,
};
});
// Find first and last highlight
let firstHighlight =
highlights.length > 1
? highlights.sort((a, b) => a.start.line - b.start.line)[0]
: highlights[0];
let lastHighlight =
highlights.length > 1
? highlights.sort((a, b) => b.end.line - a.end.line)[0]
: highlights[0];
// Calculate first and last line index of codeframe
let startLine = firstHighlight.start.line - opts.padding.before;
startLine = startLine < 0 ? 0 : startLine;
let endLineIndex = lastHighlight.end.line + opts.padding.after;
endLineIndex =
endLineIndex - startLine > opts.maxLines
? startLine + opts.maxLines - 1
: endLineIndex;
let lineNumberLength = (endLineIndex + 1).toString(10).length;
// Split input into lines and highlight syntax
let lines = code.split(NEWLINE);
let syntaxHighlightedLines = (
opts.syntaxHighlighting ? highlightSyntax(code, opts.language) : code
)
.replace(TAB_REPLACE_REGEX, TAB_REPLACEMENT)
.split(NEWLINE);
// Loop over all lines and create codeframe
let resultLines = [];
for (
let currentLineIndex = startLine;
currentLineIndex < syntaxHighlightedLines.length;
currentLineIndex++
) {
if (currentLineIndex > endLineIndex) break;
if (currentLineIndex > syntaxHighlightedLines.length - 1) break;
// Find highlights that need to get rendered on the current line
let lineHighlights = highlights
.filter(
highlight =>
highlight.start.line <= currentLineIndex &&
highlight.end.line >= currentLineIndex,
)
.sort(
(a, b) =>
(a.start.line < currentLineIndex ? 0 : a.start.column) -
(b.start.line < currentLineIndex ? 0 : b.start.column),
);
// Check if this line has a full line highlight
let isWholeLine =
lineHighlights.length &&
!!lineHighlights.find(
h => h.start.line < currentLineIndex && h.end.line > currentLineIndex,
);
let lineLengthLimit =
opts.terminalWidth > lineNumberLength + 7
? opts.terminalWidth - (lineNumberLength + 5)
: 10;
// Split the line into line parts that will fit the provided terminal width
let colOffset = 0;
let lineEndCol = lineLengthLimit;
let syntaxHighlightedLine = syntaxHighlightedLines[currentLineIndex];
if (stringWidth(syntaxHighlightedLine) > lineLengthLimit) {
if (lineHighlights.length > 0) {
if (lineHighlights[0].start.line === currentLineIndex) {
colOffset = lineHighlights[0].start.column - 5;
} else if (lineHighlights[0].end.line === currentLineIndex) {
colOffset = lineHighlights[0].end.column - 5;
}
}
colOffset = colOffset > 0 ? colOffset : 0;
lineEndCol = colOffset + lineLengthLimit;
syntaxHighlightedLine = sliceAnsi(
syntaxHighlightedLine,
colOffset,
lineEndCol,
);
}
// Write the syntax highlighted line part
resultLines.push(
lineNumberPrefixer({
lineNumber: (currentLineIndex + 1).toString(10),
lineNumberLength,
isHighlighted: lineHighlights.length > 0,
}) + syntaxHighlightedLine,
);
let lineWidth = stringWidth(syntaxHighlightedLine);
let highlightLine = '';
if (isWholeLine) {
highlightLine = highlighter('^'.repeat(lineWidth));
} else if (lineHighlights.length > 0) {
let lastCol = 0;
let highlight = null;
let highlightHasEnded = false;
for (
let highlightIndex = 0;
highlightIndex < lineHighlights.length;
highlightIndex++
) {
// Set highlight to current highlight
highlight = lineHighlights[highlightIndex];
highlightHasEnded = false;
// Calculate the startColumn and get the real width by doing a substring of the original
// line and replacing tabs with our tab replacement to support tab handling
let startCol = 0;
if (
highlight.start.line === currentLineIndex &&
highlight.start.column > colOffset
) {
startCol = lines[currentLineIndex]
.substring(colOffset, highlight.start.column)
.replace(TAB_REPLACE_REGEX, TAB_REPLACEMENT).length;
}
// Calculate the endColumn and get the real width by doing a substring of the original
// line and replacing tabs with our tab replacement to support tab handling
let endCol = lineWidth - 1;
if (highlight.end.line === currentLineIndex) {
endCol = lines[currentLineIndex]
.substring(colOffset, highlight.end.column)
.replace(TAB_REPLACE_REGEX, TAB_REPLACEMENT).length;
// If the endCol is too big for this line part, trim it so we can handle it in the next one
if (endCol > lineWidth) {
endCol = lineWidth - 1;
}
highlightHasEnded = true;
}
// If endcol is smaller than lastCol it overlaps with another highlight and is no longer visible, we can skip those
if (endCol >= lastCol) {
let characters = endCol - startCol + 1;
if (startCol > lastCol) {
// startCol is before lastCol, so add spaces as padding before the highlight indicators
highlightLine += ' '.repeat(startCol - lastCol);
} else if (lastCol > startCol) {
// If last column is larger than the start, there's overlap in highlights
// This line adjusts the characters count to ensure we don't add too many characters
characters += startCol - lastCol;
}
// Append the highlight indicators
highlightLine += highlighter('^'.repeat(characters));
// Set the lastCol equal to character count between start of line part and highlight end-column
lastCol = endCol + 1;
}
// There's no point in processing more highlights if we reached the end of the line
if (endCol >= lineEndCol - 1) {
break;
}
}
// Append the highlight message if the current highlights ends on this line part
if (highlight && highlight.message && highlightHasEnded) {
highlightLine += ' ' + highlighter(highlight.message, true);
}
}
if (highlightLine) {
resultLines.push(
lineNumberPrefixer({
lineNumberLength,
isHighlighted: true,
}) + highlightLine,
);
}
}
return resultLines.join('\n');
}