-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSourceCodeViewer.js
More file actions
247 lines (219 loc) · 7.99 KB
/
SourceCodeViewer.js
File metadata and controls
247 lines (219 loc) · 7.99 KB
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
import React from 'react';
import PropTypes from 'prop-types';
import { Prism as SyntaxHighlighter, createElement } from 'react-syntax-highlighter';
import { lruMemoize } from 'reselect';
import { vs } from 'react-syntax-highlighter/dist/esm/styles/prism';
import 'prismjs/themes/prism.css';
import ReviewCommentForm, { newCommentFormInitialValues } from '../../forms/ReviewCommentForm';
import { getPrismModeFromExtension } from '../../helpers/syntaxHighlighting.js';
import { getFileExtensionLC, canUseDOM, EMPTY_OBJ } from '../../../helpers/common.js';
import SourceCodeComment from './SourceCodeComment.js';
import './SourceCodeViewer.css';
const groupCommentsByLine = lruMemoize(comments => {
const res = {};
// group by
(comments || []).forEach(comment => {
res[comment.line] = res[comment.line] || [];
res[comment.line].push(comment);
});
// make sure each group is in ascending order (by time of creation)
const comparator = (a, b) => a.createdAt - b.createdAt;
Object.keys(res).forEach(line => {
res[line].sort(comparator);
});
return res;
});
/**
* Compute index of visible lines (+-2 lines around existing comments).
* @param {Object} comments - The comments object (keys are line numbers)
* @returns {Object} - The object where keys are line numbers to be visible, values are true.
* Disabled lines are not present (so their value is undefined).
*/
const getVisibleLines = lruMemoize(comments => {
const lines = {};
Object.keys(comments).forEach(line => {
const lineNum = parseInt(line);
for (let i = lineNum - 2; i <= lineNum + 2; ++i) {
lines[i] = true;
}
});
return lines;
});
class SourceCodeViewer extends React.Component {
state = { activeLine: null, newComment: null, editComment: null, editInitialValues: null };
lineClickHandler = ev => {
// opens new comment form if no other form is currently open
const target = ev.target.closest('*[data-line]');
const lineNumber = target && parseInt(target.dataset.line);
if (lineNumber && !isNaN(lineNumber) && !this.state.activeLine) {
ev.stopPropagation();
window.getSelection()?.removeAllRanges();
this.setState({ activeLine: lineNumber, newComment: lineNumber });
}
};
startEditing = ({ id, line, text, issue }) => {
this.setState({
editComment: id,
activeLine: line,
newComment: null,
editInitialValues: { text, issue, suppressNotification: false },
});
};
closeForms = () => this.setState({ activeLine: null, newComment: null, editComment: null, editInitialValues: null });
createNewComment = ({ text, issue, suppressNotification = false }) => {
const { name, addComment } = this.props;
text = text.trim();
return addComment({
text,
issue,
suppressNotification,
file: name,
line: this.state.newComment,
}).then(this.closeForms);
};
editComment = ({ text, issue, suppressNotification = false }) => {
const { updateComment } = this.props;
text = text.trim();
if (!text || !this.state.editComment) {
this.closeForms();
return Promise.resolve();
}
return updateComment({
id: this.state.editComment,
text,
issue,
suppressNotification,
}).then(this.closeForms);
};
linesRenderer = ({ rows, stylesheet, useInlineStyles }) => {
const {
id,
name,
authorView = false,
updateComment = null,
removeComment = null,
restrictCommentAuthor = null,
onlyComments = false,
} = this.props;
const comments = groupCommentsByLine(this.props.comments || []);
const visibleLines = onlyComments ? getVisibleLines(comments) : null;
let lastLineVisible = true; // used to properly display gaps (first hidden line after visible lines renders it)
return rows.map((node, i) => {
const lineNumber = i + 1;
// handle line hiding in onlyComments mode
if (visibleLines && !visibleLines[lineNumber]) {
if (lastLineVisible) {
lastLineVisible = false;
return (
<div key={`empty${lineNumber}`} className="p-2 text-center text-muted bg-light">
...
</div>
);
}
return null;
}
lastLineVisible = true;
return (
<React.Fragment key={`cfrag${lineNumber}`}>
{createElement({
node,
stylesheet,
useInlineStyles,
key: `cseg${lineNumber}`,
})}
<span className="scvAddButton" data-line={lineNumber} onClick={this.lineClickHandler}></span>
{(comments[lineNumber] || (this.state.newComment && this.state.newComment === lineNumber)) && (
<div className="sourceCodeViewerComments">
{(comments[lineNumber] || []).map(comment =>
this.state.editComment === comment.id ? (
<ReviewCommentForm
key={comment.id}
form={`review-comment-${comment.id}`}
initialValues={this.state.editInitialValues}
createdAt={comment.createdAt}
authorId={comment.author}
onCancel={this.closeForms}
onSubmit={this.editComment}
showSuppressor={this.props.reviewClosed}
fileName={name}
lineNumber={lineNumber}
/>
) : (
<SourceCodeComment
key={comment.id}
comment={comment}
authorView={authorView}
restrictCommentAuthor={restrictCommentAuthor}
startEditing={updateComment ? this.startEditing : null}
removeComment={removeComment}
/>
)
)}
{this.state.newComment && this.state.newComment === lineNumber && (
<ReviewCommentForm
form={`review-comment-new-${id}`}
initialValues={newCommentFormInitialValues}
onCancel={this.closeForms}
onSubmit={this.createNewComment}
showSuppressor={this.props.reviewClosed}
fileName={name}
lineNumber={lineNumber}
/>
)}
</div>
)}
</React.Fragment>
);
});
};
linePropsGenerator = lineNumber => ({
'data-line': lineNumber,
'data-line-active': this.state.activeLine && this.state.activeLine === lineNumber ? '1' : undefined,
onDoubleClick: this.props.addComment && !this.props.onlyComments ? this.lineClickHandler : undefined,
});
render() {
const { name, content = '', addComment, highlightOverrides = EMPTY_OBJ } = this.props;
const extension = getFileExtensionLC(name);
const language =
highlightOverrides[extension] !== undefined
? highlightOverrides[extension]
: getPrismModeFromExtension(extension);
return canUseDOM ? (
<SyntaxHighlighter
language={language}
style={vs}
className={
addComment && !this.props.onlyComments && !this.state.activeLine
? 'sourceCodeViewer addComment'
: 'sourceCodeViewer'
}
showLineNumbers={true}
showInlineLineNumbers={true}
wrapLines={true}
wrapLongLines={false}
useInlineStyles={false}
lineProps={this.linePropsGenerator}
renderer={this.linesRenderer}>
{content}
</SyntaxHighlighter>
) : (
<></>
);
}
}
SourceCodeViewer.propTypes = {
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
content: PropTypes.string,
solutionId: PropTypes.string.isRequired,
comments: PropTypes.array,
addComment: PropTypes.func,
updateComment: PropTypes.func,
removeComment: PropTypes.func,
authorView: PropTypes.bool,
restrictCommentAuthor: PropTypes.string,
reviewClosed: PropTypes.bool,
onlyComments: PropTypes.bool,
highlightOverrides: PropTypes.object,
};
export default SourceCodeViewer;