-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathindex.tsx
572 lines (537 loc) · 17 KB
/
index.tsx
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
import * as React from 'react';
import * as PropTypes from 'prop-types';
import cn from 'classnames';
import {
computeLineInformation,
LineInformation,
DiffInformation,
DiffType,
DiffMethod,
} from './compute-lines';
import computeStyles, { ReactDiffViewerStylesOverride, ReactDiffViewerStyles } from './styles';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const m = require('memoize-one');
const memoize = m.default || m;
export enum LineNumberPrefix {
LEFT = 'L',
RIGHT = 'R',
}
export interface ReactDiffViewerProps {
// Old value to compare.
oldValue: string;
// New value to compare.
newValue: string;
// Enable/Disable split view.
splitView?: boolean;
// Enable/Disable word diff.
disableWordDiff?: boolean;
// JsDiff text diff method from https://github.com/kpdecker/jsdiff/tree/v4.0.1#api
compareMethod?: DiffMethod;
// Number of unmodified lines surrounding each line diff.
extraLinesSurroundingDiff?: number;
// Show/hide line number.
hideLineNumbers?: boolean;
// Show only diff between the two values.
showDiffOnly?: boolean;
// Render prop to format final string before displaying them in the UI.
renderContent?: (
source: string,
lineNumber: number,
type: DiffType,
prefix: LineNumberPrefix
) => JSX.Element;
// Render prop to format code fold message.
codeFoldMessageRenderer?: (
totalFoldedLines: number,
leftStartLineNumber: number,
rightStartLineNumber: number,
) => JSX.Element;
// Event handler for line number click.
onLineNumberClick?: (
lineId: string,
event: React.MouseEvent<HTMLTableCellElement>,
) => void;
// Array of line ids to highlight lines.
highlightLines?: string[];
// Style overrides.
styles?: ReactDiffViewerStylesOverride;
// Use dark theme.
useDarkTheme?: boolean;
// Title for left column
leftTitle?: string | JSX.Element;
// Title for left column
rightTitle?: string | JSX.Element;
}
export interface ReactDiffViewerState {
// Array holding the expanded code folding.
expandedBlocks?: number[];
}
class DiffViewer extends React.Component<ReactDiffViewerProps, ReactDiffViewerState> {
private styles: ReactDiffViewerStyles;
public static defaultProps: ReactDiffViewerProps = {
oldValue: '',
newValue: '',
splitView: true,
highlightLines: [],
disableWordDiff: false,
compareMethod: DiffMethod.CHARS,
styles: {},
hideLineNumbers: false,
extraLinesSurroundingDiff: 3,
showDiffOnly: true,
useDarkTheme: false,
};
public static propTypes = {
oldValue: PropTypes.string.isRequired,
newValue: PropTypes.string.isRequired,
splitView: PropTypes.bool,
disableWordDiff: PropTypes.bool,
compareMethod: PropTypes.oneOf(Object.values(DiffMethod)),
renderContent: PropTypes.func,
onLineNumberClick: PropTypes.func,
extraLinesSurroundingDiff: PropTypes.number,
styles: PropTypes.object,
hideLineNumbers: PropTypes.bool,
showDiffOnly: PropTypes.bool,
highlightLines: PropTypes.arrayOf(PropTypes.string),
leftTitle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
rightTitle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
};
public constructor(props: ReactDiffViewerProps) {
super(props);
this.state = {
expandedBlocks: [],
};
}
/**
* Resets code block expand to the initial stage. Will be exposed to the parent component via
* refs.
*/
public resetCodeBlocks = (): boolean => {
if (this.state.expandedBlocks.length > 0) {
this.setState({
expandedBlocks: [],
});
return true;
}
return false;
}
/**
* Pushes the target expanded code block to the state. During the re-render,
* this value is used to expand/fold unmodified code.
*/
private onBlockExpand = (id: number): void => {
const prevState = this.state.expandedBlocks.slice();
prevState.push(id);
this.setState({
expandedBlocks: prevState,
});
};
/**
* Computes final styles for the diff viewer. It combines the default styles with the user
* supplied overrides. The computed styles are cached with performance in mind.
*
* @param styles User supplied style overrides.
*/
private computeStyles: (
styles: ReactDiffViewerStylesOverride,
useDarkTheme: boolean,
) => ReactDiffViewerStyles = memoize(computeStyles);
/**
* Returns a function with clicked line number in the closure. Returns an no-op function when no
* onLineNumberClick handler is supplied.
*
* @param id Line id of a line.
*/
private onLineNumberClickProxy = (id: string): any => {
if (this.props.onLineNumberClick) {
return (e: any): void => this.props.onLineNumberClick(id, e);
}
return (): void => { };
};
/**
* Maps over the word diff and constructs the required React elements to show word diff.
*
* @param diffArray Word diff information derived from line information.
* @param renderer Optional renderer to format diff words. Useful for syntax highlighting.
* @param prefix LineNumberPrefix L|R
* @param lineNumber the line number displayed in the gutter.
*/
private renderWordDiff = (
diffArray: DiffInformation[],
prefix: LineNumberPrefix,
lineNumber: number,
renderer?: (
chunk: string,
lineNumber: number,
type: DiffType,
prefix: LineNumberPrefix
) => JSX.Element,
): JSX.Element[] => {
return diffArray.map(
(wordDiff, i): JSX.Element => {
return (
<span
key={i}
className={cn(this.styles.wordDiff, {
[this.styles.wordAdded]: wordDiff.type === DiffType.ADDED,
[this.styles.wordRemoved]: wordDiff.type === DiffType.REMOVED,
})}
>
{renderer ? renderer(
wordDiff.value as string,
lineNumber,
wordDiff.type,
prefix,
) : wordDiff.value}
</span>
);
},
);
};
/**
* Maps over the line diff and constructs the required react elements to show line diff. It calls
* renderWordDiff when encountering word diff. This takes care of both inline and split view line
* renders.
*
* @param lineNumber Line number of the current line.
* @param type Type of diff of the current line.
* @param prefix Unique id to prefix with the line numbers.
* @param value Content of the line. It can be a string or a word diff array.
* @param additionalLineNumber Additional line number to be shown. Useful for rendering inline
* diff view. Right line number will be passed as additionalLineNumber.
* @param additionalPrefix Similar to prefix but for additional line number.
*/
private renderLine = (
lineNumber: number,
type: DiffType,
prefix: LineNumberPrefix,
value: string | DiffInformation[],
additionalLineNumber?: number,
additionalPrefix?: LineNumberPrefix,
): JSX.Element => {
const lineNumberTemplate = `${prefix}-${lineNumber}`;
const additionalLineNumberTemplate = `${additionalPrefix}-${additionalLineNumber}`;
const highlightLine = this.props.highlightLines.includes(lineNumberTemplate)
|| this.props.highlightLines.includes(additionalLineNumberTemplate);
const added = type === DiffType.ADDED;
const removed = type === DiffType.REMOVED;
let content;
const passedLineNumber = lineNumber !== null ? lineNumber : additionalLineNumber;
if (Array.isArray(value)) {
content = this.renderWordDiff(value, prefix, passedLineNumber, this.props.renderContent);
} else if (this.props.renderContent) {
content = this.props.renderContent(value, passedLineNumber, type, prefix);
} else {
content = value;
}
return (
<React.Fragment>
{!this.props.hideLineNumbers && (
<td
onClick={
lineNumber && this.onLineNumberClickProxy(lineNumberTemplate)
}
className={cn(this.styles.gutter, {
[this.styles.emptyGutter]: !lineNumber,
[this.styles.diffAdded]: added,
[this.styles.diffRemoved]: removed,
[this.styles.highlightedGutter]: highlightLine,
})}
>
<pre className={this.styles.lineNumber}>{lineNumber}</pre>
</td>
)}
{!this.props.splitView && !this.props.hideLineNumbers && (
<td
onClick={
additionalLineNumber
&& this.onLineNumberClickProxy(additionalLineNumberTemplate)
}
className={cn(this.styles.gutter, {
[this.styles.emptyGutter]: !additionalLineNumber,
[this.styles.diffAdded]: added,
[this.styles.diffRemoved]: removed,
[this.styles.highlightedGutter]: highlightLine,
})}
>
<pre className={this.styles.lineNumber}>{additionalLineNumber}</pre>
</td>
)}
<td
className={cn(this.styles.marker, {
[this.styles.emptyLine]: !content,
[this.styles.diffAdded]: added,
[this.styles.diffRemoved]: removed,
[this.styles.highlightedLine]: highlightLine,
})}
>
<pre>
{added && '+'}
{removed && '-'}
</pre>
</td>
<td
className={cn(this.styles.content, {
[this.styles.emptyLine]: !content,
[this.styles.diffAdded]: added,
[this.styles.diffRemoved]: removed,
[this.styles.highlightedLine]: highlightLine,
})}
>
<pre className={this.styles.contentText}>{content}</pre>
</td>
</React.Fragment>
);
};
/**
* Generates lines for split view.
*
* @param obj Line diff information.
* @param obj.left Life diff information for the left pane of the split view.
* @param obj.right Life diff information for the right pane of the split view.
* @param index React key for the lines.
*/
private renderSplitView = (
{ left, right }: LineInformation,
index: number,
): JSX.Element => {
return (
<tr key={index} className={this.styles.line}>
{this.renderLine(
left.lineNumber,
left.type,
LineNumberPrefix.LEFT,
left.value,
)}
{this.renderLine(
right.lineNumber,
right.type,
LineNumberPrefix.RIGHT,
right.value,
)}
</tr>
);
};
/**
* Generates lines for inline view.
*
* @param obj Line diff information.
* @param obj.left Life diff information for the added section of the inline view.
* @param obj.right Life diff information for the removed section of the inline view.
* @param index React key for the lines.
*/
public renderInlineView = (
{ left, right }: LineInformation,
index: number,
): JSX.Element => {
let content;
if (left.type === DiffType.REMOVED && right.type === DiffType.ADDED) {
return (
<React.Fragment key={index}>
<tr className={this.styles.line}>
{this.renderLine(
left.lineNumber,
left.type,
LineNumberPrefix.LEFT,
left.value,
null,
)}
</tr>
<tr className={this.styles.line}>
{this.renderLine(
null,
right.type,
LineNumberPrefix.RIGHT,
right.value,
right.lineNumber,
)}
</tr>
</React.Fragment>
);
}
if (left.type === DiffType.REMOVED) {
content = this.renderLine(
left.lineNumber,
left.type,
LineNumberPrefix.LEFT,
left.value,
null,
);
}
if (left.type === DiffType.DEFAULT) {
content = this.renderLine(
left.lineNumber,
left.type,
LineNumberPrefix.LEFT,
left.value,
right.lineNumber,
LineNumberPrefix.RIGHT,
);
}
if (right.type === DiffType.ADDED) {
content = this.renderLine(
null,
right.type,
LineNumberPrefix.RIGHT,
right.value,
right.lineNumber,
);
}
return <tr key={index} className={this.styles.line}>{content}</tr>;
};
/**
* Returns a function with clicked block number in the closure.
*
* @param id Cold fold block id.
*/
private onBlockClickProxy = (id: number): any => (): void => this.onBlockExpand(id);
/**
* Generates cold fold block. It also uses the custom message renderer when available to show
* cold fold messages.
*
* @param num Number of skipped lines between two blocks.
* @param blockNumber Code fold block id.
* @param leftBlockLineNumber First left line number after the current code fold block.
* @param rightBlockLineNumber First right line number after the current code fold block.
*/
private renderSkippedLineIndicator = (
num: number,
blockNumber: number,
leftBlockLineNumber: number,
rightBlockLineNumber: number,
): JSX.Element => {
const { splitView } = this.props;
const message = this.props.codeFoldMessageRenderer
? this.props
.codeFoldMessageRenderer(num, leftBlockLineNumber, rightBlockLineNumber)
: <pre className={this.styles.codeFoldContent}>Expand {num} lines ...</pre>;
const content = (
<td>
<a onClick={this.onBlockClickProxy(blockNumber)} tabIndex={0}>
{message}
</a>
</td>
);
return (
<tr key={`${leftBlockLineNumber}-${rightBlockLineNumber}`} className={this.styles.codeFold}>
{!this.props.hideLineNumbers && (
<td className={this.styles.codeFoldGutter} />
)}
<td className={cn({ [this.styles.codeFoldGutter]: !splitView })} />
{splitView ? content : <td />}
{!splitView ? content : <td />}
<td />
<td />
</tr>
);
};
/**
* Generates the entire diff view.
*/
private renderDiff = (): JSX.Element[] => {
const { oldValue, newValue, splitView, disableWordDiff, compareMethod } = this.props;
const { lineInformation, diffLines } = computeLineInformation(
oldValue,
newValue,
disableWordDiff,
compareMethod,
);
const extraLines = this.props.extraLinesSurroundingDiff < 0
? 0
: this.props.extraLinesSurroundingDiff;
let skippedLines: number[] = [];
return lineInformation.map(
(line: LineInformation, i: number): JSX.Element => {
const diffBlockStart = diffLines[0];
const currentPosition = diffBlockStart - i;
if (this.props.showDiffOnly) {
if (currentPosition === -extraLines) {
skippedLines = [];
diffLines.shift();
}
if (
line.left.type === DiffType.DEFAULT
&& (currentPosition > extraLines
|| typeof diffBlockStart === 'undefined')
&& !this.state.expandedBlocks.includes(diffBlockStart)
) {
skippedLines.push(i + 1);
if (i === lineInformation.length - 1 && skippedLines.length > 1) {
return this.renderSkippedLineIndicator(
skippedLines.length,
diffBlockStart,
line.left.lineNumber,
line.right.lineNumber,
);
}
return null;
}
}
const diffNodes = splitView
? this.renderSplitView(line, i)
: this.renderInlineView(line, i);
if (currentPosition === extraLines && skippedLines.length > 0) {
const { length } = skippedLines;
skippedLines = [];
return (
<React.Fragment key={i}>
{this.renderSkippedLineIndicator(
length,
diffBlockStart,
line.left.lineNumber,
line.right.lineNumber,
)}
{diffNodes}
</React.Fragment>
);
}
return diffNodes;
},
);
}
public render = (): JSX.Element => {
const {
oldValue,
newValue,
useDarkTheme,
leftTitle,
rightTitle,
splitView,
} = this.props;
if (typeof oldValue !== 'string' || typeof newValue !== 'string') {
throw Error('"oldValue" and "newValue" should be strings');
}
this.styles = this.computeStyles(this.props.styles, useDarkTheme);
const nodes = this.renderDiff();
const title = (leftTitle || rightTitle)
&& <tr>
<td colSpan={splitView ? 3 : 5} className={this.styles.titleBlock}>
<pre className={this.styles.contentText}>
{leftTitle}
</pre>
</td>
{splitView
&& <td colSpan={3} className={this.styles.titleBlock}>
<pre className={this.styles.contentText}>{rightTitle}</pre>
</td>
}
</tr>;
return (
<table className={cn(this.styles.diffContainer, { [this.styles.splitView]: splitView })}>
<tbody>
{title}
{nodes}
</tbody>
</table>
);
};
}
export default DiffViewer;
export { ReactDiffViewerStylesOverride, DiffMethod };