This repository was archived by the owner on Apr 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
Expand file tree
/
Copy pathVersionControlBlameLayer.tsx
More file actions
401 lines (354 loc) · 13.4 KB
/
VersionControlBlameLayer.tsx
File metadata and controls
401 lines (354 loc) · 13.4 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
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
import { pathExists } from "fs-extra"
import { Buffer, BufferLayer, Commands, Configuration } from "oni-api"
import { warn } from "oni-core-logging"
import * as React from "react"
import { Transition } from "react-transition-group"
import { Position } from "vscode-languageserver-types"
import { LayerContextWithCursor } from "../../Editor/NeovimEditor/NeovimBufferLayersView"
import styled, { pixel, textOverflow, withProps } from "../../UI/components/common"
import { getTimeSince } from "../../Utility"
import { VersionControlProvider } from "./"
import { Blame as IBlame } from "./VersionControlProvider"
type TransitionStates = "entering" | "entered" | "exiting"
interface IBlamePosition {
top: number
left: number
hide: boolean
leftOffset: number
}
interface ICanFit {
canFit: boolean
message: string
position: IBlamePosition
}
interface ILineDetails {
nextSpacing: number
lastEmptyLine: number
}
export interface IProps extends LayerContextWithCursor {
getBlame: (lineOne: number, lineTwo: number) => Promise<IBlame>
priority: number
timeout: number
cursorScreenLine: number
cursorBufferLine: number
currentLine: string
mode: "auto" | "manual"
fontFamily: string
setupCommand: (callback: () => void) => void
}
export interface IState {
blame: IBlame
showBlame: boolean
currentLineContent: string
currentCursorBufferLine: number
error: Error
}
interface IContainerProps {
height: number
top: number
left: number
fontFamily: string
hide: boolean
priority: number
timeout: number
leftOffset: number
animationState: TransitionStates
}
const getOpacity = (state: TransitionStates) => {
const transitionStyles = {
entering: 0,
entered: 0.5,
exiting: 0,
}
return transitionStyles[state]
}
export const BlameContainer = withProps<IContainerProps>(styled.div).attrs({
style: ({ top, left, leftOffset }: IContainerProps) => ({
top: pixel(top),
left: pixel(left),
paddingLeft: pixel(leftOffset),
}),
})`
${p => p.hide && `visibility: hidden`};
width: auto;
box-sizing: border-box;
position: absolute;
font-style: italic;
font-family: ${p => p.fontFamily};
color: ${p => p.theme["menu.foreground"]};
opacity: ${p => getOpacity(p.animationState)};
transition: opacity ${p => p.timeout}ms ease-in-out;
height: ${p => pixel(p.height)};
line-height: ${p => pixel(p.height)};
right: 3em;
z-index: ${p => p.priority};
${textOverflow}
`
const BlameDetails = styled.span`
color: inherit;
width: 100%;
`
// CurrentLine - the string in the current line
// CursorLine - The 0 based position of the cursor in the file i.e. at line 30 this will be 29
// CursorBufferLine - The 1 based position of the cursor in the file i.e. at line 30 it will be 30
// CursorScreenLine - the position of the cursor within the visible lines so if line 30 is at the
// top of the viewport it will be 0
export class Blame extends React.PureComponent<IProps, IState> {
// Reset show blame to false when props change - do it here so it happens before rendering
// hide if the current line has changed or if the text of the line has changed
// aka input is in progress or if there is an empty line
public static getDerivedStateFromProps(nextProps: IProps, prevState: IState) {
const lineNumberChanged = nextProps.cursorBufferLine !== prevState.currentCursorBufferLine
const lineContentChanged = prevState.currentLineContent !== nextProps.currentLine
if (
(prevState.showBlame && (lineNumberChanged || lineContentChanged)) ||
!nextProps.currentLine
) {
return {
showBlame: false,
blame: prevState.blame,
currentLineContent: nextProps.currentLine,
currentCursorBufferLine: nextProps.cursorBufferLine,
}
}
return null
}
public state: IState = {
error: null,
blame: null,
showBlame: null,
currentLineContent: this.props.currentLine,
currentCursorBufferLine: this.props.cursorBufferLine,
}
private _timeout: any
private readonly DURATION = 300
private readonly LEFT_OFFSET = 4
public async componentDidMount() {
const { cursorBufferLine, mode } = this.props
await this.updateBlame(cursorBufferLine, cursorBufferLine)
if (mode === "auto") {
this.resetTimer()
}
this.props.setupCommand(() => {
const { showBlame } = this.state
this.setState({ showBlame: !showBlame })
})
}
public async componentDidUpdate(prevProps: IProps, prevState: IState) {
const { cursorBufferLine, currentLine, mode } = this.props
if (prevProps.cursorBufferLine !== cursorBufferLine && currentLine) {
await this.updateBlame(cursorBufferLine, cursorBufferLine)
if (mode === "auto") {
return this.resetTimer()
}
}
}
public componentWillUnmount() {
clearTimeout(this._timeout)
}
public componentDidCatch(error: Error) {
warn(`Oni VCS Blame layer failed because: ${error.message}`)
this.setState({ error })
}
public resetTimer = () => {
clearTimeout(this._timeout)
this._timeout = setTimeout(() => {
if (this.props.currentLine) {
this.setState({ showBlame: true })
}
}, this.props.timeout)
}
public getLastEmptyLine() {
const { cursorLine, visibleLines, topBufferLine } = this.props
const lineDetails: ILineDetails = {
lastEmptyLine: null,
nextSpacing: null,
}
for (
let currentBufferLine = cursorLine;
currentBufferLine >= topBufferLine;
currentBufferLine--
) {
const screenLine = currentBufferLine - topBufferLine
const line = visibleLines[screenLine]
if (!line.length) {
const nextLine = visibleLines[screenLine + 1]
lineDetails.lastEmptyLine = currentBufferLine
// search for index of first non-whitespace character which is equivalent
// to the whitespace count
lineDetails.nextSpacing = nextLine.search(/\S/)
break
}
}
return lineDetails
}
public calculatePosition(canFit: boolean) {
const { cursorLine, cursorScreenLine, visibleLines } = this.props
const currentLine = visibleLines[cursorScreenLine]
const character = currentLine && currentLine.length
if (canFit) {
return this.getPosition({ line: cursorLine, character }, canFit)
}
const { lastEmptyLine, nextSpacing } = this.getLastEmptyLine()
if (lastEmptyLine) {
return this.getPosition({ line: lastEmptyLine - 1, character: nextSpacing })
}
return this.getPosition()
}
// TODO: possibly add a caching strategy so a new call isn't made each time or
// get a blame for the entire file and store it
public updateBlame = async (lineOne: number, lineTwo: number) => {
const outOfBounds = this.isOutOfBounds(lineOne, lineTwo)
const blame = !outOfBounds ? await this.props.getBlame(lineOne, lineTwo) : null
this.setState({ blame })
}
public formatCommitDate(timestamp: string) {
return new Date(parseInt(timestamp, 10) * 1000)
}
public getPosition(positionToRender?: Position, canFit: boolean = false): IBlamePosition {
const emptyPosition: IBlamePosition = {
hide: true,
top: null,
left: null,
leftOffset: null,
}
if (!positionToRender) {
return emptyPosition
}
const position = this.props.bufferToPixel(positionToRender)
if (!position) {
return emptyPosition
}
return {
hide: false,
top: position.pixelY,
left: position.pixelX,
leftOffset: canFit ? this.LEFT_OFFSET * this.props.fontPixelWidth : 0,
}
}
public isOutOfBounds = (...lines: number[]) => {
return lines.some(
line => !line || line > this.props.bottomBufferLine || line < this.props.topBufferLine,
)
}
public getBlameText = (numberOfTruncations = 0) => {
const { blame } = this.state
if (!blame) {
return null
}
const { author, hash, committer_time } = blame
const formattedDate = this.formatCommitDate(committer_time)
const timeSince = `${getTimeSince(formattedDate)} ago`
const formattedHash = hash.slice(0, 4).toUpperCase()
const words = blame.summary.split(" ")
const message = words.slice(0, words.length - numberOfTruncations).join(" ")
const symbol = "…"
const summary = numberOfTruncations && words.length > 2 ? message.concat(symbol) : message
return words.length < 2
? `${author}, ${timeSince}`
: `${author}, ${timeSince}, ${summary} #${formattedHash}`
}
// Recursively calls get blame text if the message will not fit onto the screen up
// to a limit of 6 times each time removing one word from the blame message
// if after 6 attempts the message is still not small enougth then we render the popup
public canFit = (truncationAmount = 0): ICanFit => {
const { visibleLines, dimensions, cursorScreenLine } = this.props
const message = this.getBlameText(truncationAmount)
const currentLine = visibleLines[cursorScreenLine] || ""
const canFit = dimensions.width > currentLine.length + message.length + this.LEFT_OFFSET
if (!canFit && truncationAmount <= 6) {
return this.canFit(truncationAmount + 1)
}
const truncatedOrFullMessage = canFit ? message : this.getBlameText()
return {
canFit,
message: truncatedOrFullMessage,
position: this.calculatePosition(canFit),
}
}
public render() {
const { blame, showBlame, error } = this.state
if (!blame || !showBlame || error) {
return null
}
const { message, position } = this.canFit()
return (
<Transition in={blame && showBlame} timeout={this.DURATION}>
{(state: TransitionStates) => (
<BlameContainer
{...position}
data-id="vcs.blame"
timeout={this.DURATION}
animationState={state}
priority={this.props.priority}
height={this.props.fontPixelHeight}
fontFamily={this.props.fontFamily}
>
<BlameDetails>{message}</BlameDetails>
</BlameContainer>
)}
</Transition>
)
}
}
export default class VersionControlBlameLayer implements BufferLayer {
constructor(
private _buffer: Buffer,
private _vcsProvider: VersionControlProvider,
private _configuration: Configuration,
private _commands: Commands.Api,
) {}
public getBlame = async (lineOne: number, lineTwo: number) => {
const fileExists = await pathExists(this._buffer.filePath)
return (
fileExists &&
this._vcsProvider.getBlame({ file: this._buffer.filePath, lineOne, lineTwo })
)
}
get id() {
return "vcs.blame"
}
public setupCommand = (callback: () => void) => {
this._commands.registerCommand({
command: "experimental.vcs.blame.toggleBlame",
name: null,
detail: null,
enabled: this._isActive,
execute: callback,
})
}
public getConfigOpts() {
const fontFamily = this._configuration.getValue<string>("editor.fontFamily")
const timeout = this._configuration.getValue<number>("experimental.vcs.blame.timeout")
const mode = this._configuration.getValue<"auto" | "manual">("experimental.vcs.blame.mode")
const priorities = this._configuration.getValue<string[]>("layers.priority", [])
const index = priorities.indexOf(this.id)
const priority = index >= 0 ? priorities.length - index : 0
return { timeout, mode, fontFamily, priority }
}
public render(context: LayerContextWithCursor) {
const cursorBufferLine = context.cursorLine + 1
const cursorScreenLine = cursorBufferLine - context.topBufferLine
const config = this.getConfigOpts()
const activated = this._isActive()
return (
activated && (
<Blame
{...context}
mode={config.mode}
priority={config.priority}
timeout={config.timeout}
getBlame={this.getBlame}
fontFamily={config.fontFamily}
setupCommand={this.setupCommand}
cursorBufferLine={cursorBufferLine}
cursorScreenLine={cursorScreenLine}
currentLine={context.visibleLines[cursorScreenLine]}
/>
)
)
}
private _isActive() {
return this._vcsProvider && this._vcsProvider.isActivated
}
}