-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathmerge.ts
453 lines (409 loc) · 11 KB
/
merge.ts
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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import * as alertify from 'alertify.js';
import type * as nbformat from '@jupyterlab/nbformat';
import { JSONExt, JSONObject } from '@lumino/coreutils';
import { Panel, Widget } from '@lumino/widgets';
import { RenderMimeRegistry } from '@jupyterlab/rendermime';
import { Sanitizer } from '@jupyterlab/apputils';
import { createEditorFactory } from 'nbdime/lib/common/editor';
import { NotebookMergeModel } from 'nbdime/lib/merge/model';
import type { IMergeDecision } from 'nbdime/lib/merge/decisions';
import { NotebookMergeWidget } from 'nbdime/lib/merge/widget';
import { stringify } from 'nbdime/lib/patch';
import { requestMerge, requestApi } from 'nbdime/lib/request';
import {
getBaseUrl,
getConfigOption,
closeTool,
toggleSpinner,
toggleShowUnchanged,
markUnchangedRanges,
} from './common';
import { rendererFactories } from './rendermime';
import { extractMergedNotebook } from './save';
let mergeWidget: NotebookMergeWidget | null = null;
/**
* Show the merge as represented by the base notebook and a
* list of merge decisions
*/
function showMerge(data: {
base: nbformat.INotebookContent;
merge_decisions: IMergeDecision[];
}): Promise<void> {
let rendermime = new RenderMimeRegistry({
initialFactories: rendererFactories,
sanitizer: new Sanitizer(),
});
const collapseIdentical = getConfigOption('collapseIdentical', 2);
const showBase = getConfigOption('showBase', true);
if (!showBase) {
document.querySelector('#nbdime-header-base')!.textContent = 'Merged';
}
let nbmModel = new NotebookMergeModel(data.base, data.merge_decisions);
let nbmWidget = new NotebookMergeWidget({
model: nbmModel,
rendermime,
editorFactory: createEditorFactory(),
collapseIdentical,
showBase,
});
let root = document.getElementById('nbdime-root');
if (!root) {
throw new Error('Missing root element "nbidme-root"');
}
root.innerHTML = '';
// Hide unchanged cells by default:
toggleShowUnchanged(!getConfigOption('hideUnchanged', true));
let panel = new Panel();
panel.id = 'main';
Widget.attach(panel, root);
panel.addWidget(nbmWidget);
let work = nbmWidget.init();
work.then(() => {
window.onresize = () => {
panel.update();
};
});
mergeWidget = nbmWidget;
return work;
}
/**
* Calls `requestMerge` with our response handlers
*/
export function getMerge(base: string, local: string, remote: string) {
let baseUrl = getBaseUrl();
requestMerge(
base,
local,
remote,
baseUrl,
onMergeRequestCompleted,
onMergeRequestFailed,
);
}
/**
* Merge form submission callback. Sends a request for a merge to the server
* based on the content of the form.
*
* Also pushes state to history for navigation history wo/reload
*/
function onMerge(e: Event) {
e.preventDefault();
let b = (document.getElementById('merge-base') as HTMLInputElement).value;
let c = (document.getElementById('merge-local') as HTMLInputElement).value;
let r = (document.getElementById('merge-remote') as HTMLInputElement).value;
compare(b, c, r, true);
return false;
}
function compare(
b: string,
c: string,
r: string,
pushHistory: boolean | 'replace',
) {
// All values present, do merge
toggleSpinner(true);
getMerge(b, c, r);
if (pushHistory) {
let uri = window.location.pathname;
uri +=
'?base=' +
encodeURIComponent(b) +
'&local=' +
encodeURIComponent(c) +
'&remote=' +
encodeURIComponent(r);
editHistory(
pushHistory,
{ base: b, local: c, remote: r },
'Merge: "' + c + '" - "' + b + '" - "' + r + '"',
uri,
);
}
}
function editHistory(
pushHistory: boolean | 'replace',
statedata: any,
title: string,
url?: string,
): void {
if (pushHistory === true) {
history.pushState(statedata, title, url);
} else if (pushHistory === 'replace') {
history.replaceState(statedata, title, url);
}
}
/**
* Called when a 'back' is requested
*/
function onPopState(e: PopStateEvent) {
if (e.state) {
let eb = document.getElementById('merge-base') as HTMLInputElement;
let el = document.getElementById('merge-local') as HTMLInputElement;
let er = document.getElementById('merge-remote') as HTMLInputElement;
eb.value = e.state.base;
el.value = e.state.local;
er.value = e.state.remote;
compare(e.state.base, e.state.local, e.state.remote, false);
}
}
/**
* Callback for a successfull merge request
*/
function onMergeRequestCompleted(data: any) {
let layoutWork = showMerge(data);
layoutWork.then(() => {
toggleSpinner(false);
markUnchangedRanges();
});
}
/**
* Callback for a failed merge request
*/
function onMergeRequestFailed(response: string) {
console.log('Merge request failed.');
let root = document.getElementById('nbdime-root');
if (!root) {
throw new Error('Missing root element "nbidme-root"');
}
const pre = document.createElement('pre');
pre.innerText = response;
root.innerHTML = '';
root.appendChild(pre);
mergeWidget = null;
toggleSpinner(false);
}
/**
* Extract the merged notebook from the model, as well as any remaining
* conflicts, and send them to the server for storage / further processing.
*/
export function saveMerged() {
if (!mergeWidget) {
return;
}
let nb = extractMergedNotebook(mergeWidget);
let conflicts: IMergeDecision[] = [];
for (let md of mergeWidget.model.conflicts) {
conflicts.push(md.serialize());
}
submitMerge(nb, conflicts);
}
function downloadNotebook(
notebook: nbformat.INotebookContent,
filename: string,
) {
let element = document.createElement('a');
const nbCopy = JSONExt.deepCopy(notebook) as JSONObject;
element.setAttribute(
'href',
'data:text/plain;charset=utf-8,' + encodeURIComponent(stringify(nbCopy)),
);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
try {
element.click();
} finally {
document.body.removeChild(element);
}
}
function getMergeFilename() {
// If present use 'outputfilename'
let filename = getConfigOption('outputfilename');
// Otherwise use base name as suggestion
if (!filename) {
filename = getConfigOption('base');
}
// Fallback:
if (!filename) {
filename = 'merged.ipynb';
}
return filename;
}
/**
*
*/
export function downloadMerged() {
if (!mergeWidget) {
return;
}
function download() {
let filename = getMergeFilename();
let nb = extractMergedNotebook(mergeWidget!);
downloadNotebook(nb, filename);
}
let conflicted = mergeWidget.model.conflicts.length > 0;
if (conflicted) {
alertify.confirm(
'There are conflicts remaining. ' +
'Do you still want to download the merge output?',
() => {
download();
},
);
} else {
download();
}
}
/**
* Submit a merged notebook
*/
function submitMerge(
mergedNotebook: nbformat.INotebookContent,
conflicts: IMergeDecision[],
) {
requestApi(
getBaseUrl(),
'/api/store',
{
merged: mergedNotebook,
conflicts: conflicts,
},
onSubmissionCompleted,
onSubmissionFailed,
);
}
/**
* Callback for a successful store of the submitted merged notebook
*/
function onSubmissionCompleted() {
alertify.success('Merged notebook saved successfully');
mergeWidget!.model.unsavedChanges = false;
}
/**
* Callback for a failed store of the submitted merged notebook
*/
function onSubmissionFailed(response: string) {
alertify.error(
'Was not able to save the notebook! See console and/or server log for details.',
);
}
/**
* Called when the merge tool is closing, but it can be prevented.
*/
export function closeMerge(ev: Event, unloading = false): string | void | null {
if (!mergeWidget) {
return closeTool(1);
}
let savable = getConfigOption('savable');
for (let md of mergeWidget.model.conflicts) {
if (md.conflict) {
if (mergeWidget.model.unsavedChanges && savable) {
let prompt =
'There are remaining conflicts, and you have unsaved changes. Do you want to close anyway?';
if (unloading) {
ev.returnValue = true;
return prompt;
}
alertify.confirm(
prompt,
() => {
window.onbeforeunload = null!;
closeTool(1);
},
() => {
ev.preventDefault();
},
);
return null;
} else {
let prompt =
'There are remaining conflicts. Do you want to close anyway?';
if (unloading) {
ev.returnValue = true;
return prompt;
}
alertify.confirm(
prompt,
() => {
window.onbeforeunload = null!;
closeTool(1);
},
() => {
ev.preventDefault();
},
);
return null;
}
}
}
if (mergeWidget.model.unsavedChanges && savable) {
let prompt = 'There are unsaved changes. Do you want to close anyway?';
if (unloading) {
ev.returnValue = true;
return prompt;
}
alertify.confirm(
prompt,
() => {
window.onbeforeunload = null!;
closeTool(0);
},
() => {
ev.preventDefault();
},
);
return null;
}
closeTool(0);
return null;
}
/**
* Called when merge tool is closing, and it shouldn't be prevented.
*
* Will only try to set the correct exit code for the tool.
*/
export function forceCloseMerge(): void {
if (!mergeWidget) {
return closeTool(1);
}
for (let md of mergeWidget.model.conflicts) {
if (md.conflict) {
closeTool(1);
}
}
closeTool(0);
}
/**
* Wire up callbacks.
*/
function attachToForm() {
let frm = document.getElementById('nbdime-merge-form') as HTMLFormElement;
if (frm) {
frm.onsubmit = onMerge;
// It only makes sense to listen to pop state events when the form is
// availalbe (i.e. when we are not a diff/mergetool):
window.onpopstate = onPopState;
}
}
/** */
export function initializeMerge() {
attachToForm();
// If arguments supplied in config, run merge directly:
let base = getConfigOption('base');
let local = getConfigOption('local'); // Only available for merge
let remote = getConfigOption('remote');
if (base && local && remote) {
compare(base, local, remote, 'replace');
}
let savable = getConfigOption('savable');
let saveBtn = document.getElementById('nbdime-save') as HTMLButtonElement;
if (savable) {
saveBtn.onclick = saveMerged;
saveBtn.style.display = 'initial';
}
let downloadBtn = document.getElementById(
'nbdime-download',
) as HTMLButtonElement;
downloadBtn.onclick = downloadMerged;
downloadBtn.style.display = 'initial';
let hideUnchangedChk = document.getElementById(
'nbdime-hide-unchanged',
) as HTMLInputElement;
hideUnchangedChk.checked = getConfigOption('hideUnchanged', true);
hideUnchangedChk.onchange = () => {
toggleShowUnchanged(!hideUnchangedChk.checked, mergeWidget);
};
}