-
Notifications
You must be signed in to change notification settings - Fork 638
/
main.js
276 lines (251 loc) · 9 KB
/
main.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
var _ = require('lodash');
var $ = require('jquery');
jQuery = $; // this is for old backward compatability of bootrap modules
var ko = require('knockout');
var dndPageScroll = require('dnd-page-scroll');
require('./bootstrap');
require('./jquery-ui');
require('./knockout-bindings');
const winston = require('winston');
ungit.logger = winston.createLogger({
level: ungit.config.logLevel || 'error',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.colorize(),
winston.format.printf((info) => {
const splat = info[Symbol.for('splat')];
if (splat) {
const splatStr = splat.map((arg) => JSON.stringify(arg)).join('\n');
return `${info.timestamp} - ${info.level}: ${info.message} ${splatStr}`;
}
return `${info.timestamp} - ${info.level}: ${info.message}`;
})
),
transports: [new winston.transports.Console()],
});
var components = require('ungit-components');
var Server = require('./server');
var programEvents = require('ungit-program-events');
var navigation = require('ungit-navigation');
var storage = require('ungit-storage');
var adBlocker = require('just-detect-adblock');
var { encodePath } = require('ungit-address-parser');
// Request animation frame polyfill and init tooltips
(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
$(document).tooltip({
selector: '[data-toggle="tooltip"]',
});
})();
ko.bindingHandlers.autocomplete = {
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) => {
const setAutoCompleteOptions = (sources) => {
$(element)
.autocomplete({
classes: {
'ui-autocomplete': 'dropdown-menu',
},
source: sources,
minLength: 0,
messages: {
noResults: '',
results: () => {},
},
})
.data('ui-autocomplete')._renderItem = (ul, item) => {
return $('<li></li>').append($('<a>').text(item.label)).appendTo(ul);
};
};
const handleKeyEvent = (event) => {
const value = $(element).val();
const lastChar = value.slice(-1);
if (lastChar == ungit.config.fileSeparator) {
// When file separator is entered, list what is in given path, and rest auto complete options
server
.getPromise('/fs/listDirectories', { term: value })
.then((directoryList) => {
const currentDir = directoryList.shift();
$(element).val(
currentDir.endsWith(ungit.config.fileSeparator)
? currentDir
: currentDir + ungit.config.fileSeparator
);
setAutoCompleteOptions(directoryList);
$(element).autocomplete('search', value);
})
.catch((err) => {
if (
!err.errorSummary.startsWith('ENOENT: no such file or directory') &&
err.errorCode !== 'read-dir-failed'
) {
throw err;
}
});
} else if (event.keyCode === 13) {
// enter key is struck, navigate to the path
event.preventDefault();
navigation.browseTo(`repository?path=${encodePath(value)}`);
} else if (value === '' && storage.getItem('repositories')) {
// if path is emptied out, show save path options
const folderNames = JSON.parse(storage.getItem('repositories')).map((value) => {
return {
value: value,
label: value.substring(value.lastIndexOf(ungit.config.fileSeparator) + 1),
};
});
setAutoCompleteOptions(folderNames);
$(element).autocomplete('search', '');
}
return true;
};
ko.utils.registerEventHandler(element, 'keyup', _.debounce(handleKeyEvent, 100));
},
};
// Used to catch when a user was tabbed away and re-visits the page.
// If fs.watch worked better on Windows (i.e. on subdirectories) we wouldn't need this
(function detectReActivity() {
var lastMoved = Date.now();
document.addEventListener('mousemove', function () {
// If the user didn't move for 3 sec and then moved again, it's likely it's a tab-back
if (Date.now() - lastMoved > 3000) {
console.log('Fire change event due to re-activity');
programEvents.dispatch({ event: 'working-tree-changed' });
}
lastMoved = Date.now();
});
})();
function WindowTitle() {
this.path = 'ungit';
this.crash = false;
}
WindowTitle.prototype.update = function () {
var title = this.path
.replace(/\\/g, '/')
.split('/')
.filter(function (x) {
return x;
})
.reverse()
.join(' < ');
if (this.crash) title = ':( ungit crash ' + title;
document.title = title;
};
var windowTitle = new WindowTitle();
windowTitle.update();
var AppContainerViewModel = function () {
this.content = ko.observable();
};
exports.AppContainerViewModel = AppContainerViewModel;
AppContainerViewModel.prototype.templateChooser = function (data) {
if (!data) return '';
return data.template;
};
var app, appContainer, server;
let eventArgMap = {};
const throttledEventTrigger = _.throttle(
async () => {
if (ungit.__eventProcessingProm) {
ungit.logger.debug('programEvent process rescheduled');
return throttledEventTrigger();
}
const eventsToProcess = Object.values(eventArgMap);
eventArgMap = {};
try {
ungit.logger.debug('programEvent process triggered');
ungit.__eventProcessingProm = Promise.all(
eventsToProcess.map(async (event) => {
return app.onProgramEvent(event);
})
);
await ungit.__eventProcessingProm;
ungit.__eventProcessedTime = Date.now();
} catch (e) {
ungit.logger.error('failed to process onProgramEvent', e, e.stacktrace);
} finally {
ungit.__eventProcessingProm = undefined;
ungit.logger.debug('programEvent process finished');
}
},
500,
{ leading: false, trailing: true }
);
exports.start = function () {
server = new Server();
appContainer = new AppContainerViewModel();
app = components.create('app', { appContainer: appContainer, server: server });
programEvents.add(async (event) => {
ungit.logger.info(`received event: ${event.event}`);
if (event.event == 'disconnected' || event.event == 'git-crash-error') {
console.error(`ungit crash: ${event.event}`, event.error, event.stacktrace);
const err =
event.event == 'disconnected' && (await adBlocker.detectAnyAdblocker())
? 'adblocker'
: event.event;
appContainer.content(components.create('crash', err));
windowTitle.crash = true;
windowTitle.update();
} else if (event.event == 'connected') {
appContainer.content(app);
windowTitle.crash = false;
windowTitle.update();
}
eventArgMap[JSON.stringify(event)] = event;
throttledEventTrigger();
});
if (ungit.config.authentication) {
var authenticationScreen = components.create('login', { server: server });
appContainer.content(authenticationScreen);
authenticationScreen.loggedIn.add(function () {
server.initSocket();
});
} else {
server.initSocket();
}
Raven.TraceKit.report.subscribe(function (event, err) {
programEvents.dispatch({ event: 'raven-crash', error: err || event.event });
});
var prevTimestamp = 0;
var updateAnimationFrame = function (timestamp) {
var delta = timestamp - prevTimestamp;
prevTimestamp = timestamp;
if (app.updateAnimationFrame) app.updateAnimationFrame(delta);
window.requestAnimationFrame(updateAnimationFrame);
};
window.requestAnimationFrame(updateAnimationFrame);
ko.applyBindings(appContainer);
// routing
navigation.crossroads.addRoute('/', function () {
app.content(components.create('home', { app: app }));
windowTitle.path = 'ungit';
windowTitle.update();
});
navigation.crossroads.addRoute('/repository{?query}', function (query) {
programEvents.dispatch({ event: 'navigated-to-path', path: query.path });
app.content(components.create('path', { server: server, path: query.path }));
windowTitle.path = query.path;
windowTitle.update();
});
navigation.init();
};
$(document).ready(function () {
dndPageScroll.default(); // Automatic page scrolling on drag-n-drop: http://www.planbox.com/blog/news/updates/html5-drag-and-drop-scrolling-the-page.html
});