This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
galata.ts
1950 lines (1573 loc) · 63 KB
/
galata.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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Bloomberg Finance LP.
// Distributed under the terms of the Modified BSD License.
import { Page, ElementHandle } from 'playwright';
import {
IDocumentManager
} from '@jupyterlab/docmanager';
import {
ISettingRegistry
} from '@jupyterlab/settingregistry';
import {
NotebookPanel
} from '@jupyterlab/notebook';
import * as nbformat from '@jupyterlab/nbformat';
import * as fs from 'fs';
import * as path from 'path';
import { default as axios, AxiosRequestConfig } from 'axios';
import pixelmatch from 'pixelmatch';
import * as jsBeautify from 'js-beautify';
import {
PNG
} from 'pngjs';
import {
INotebookRunCallback, IPluginNameToInterfaceMap, PLUGIN_ID_DOC_MANAGER, PLUGIN_ID_SETTINGS
} from './inpage/tokens';
import {
IGalataContext, CaptureCompareResult, ICapture, ITestLog, ICreateNewPageOptions
} from './tokens';
let _runCallbacksExposed: number = 0;
let _currentSuite: string;
let _currentTest: string;
function describeWrapper(name: number | string | Function | jest.FunctionLike, fn: jest.EmptyFunction) {
_currentSuite = name as string;
return describe(name, fn);
}
function wrappedTestFn(suiteName: string, testName: string, fn?: jest.ProvidesCallback): jest.ProvidesCallback {
const localTestName = testName;
return async (cb: jest.DoneCallback) => {
_currentTest = localTestName;
await fn(cb);
cb();
};
}
function testWrapper(name: string, fn?: jest.ProvidesCallback, timeout?: number) {
return test(name, wrappedTestFn(_currentSuite, name, fn), timeout);
}
export
namespace galata {
function _base64EncodeFile(filePath: string) {
const content = fs.readFileSync(filePath);
return content.toString('base64');
}
function _transformCaptureName(fileName: string): string {
if (context.capturePrefix !== '') {
fileName = `${context.capturePrefix}_${fileName}`;
}
return fileName.toLowerCase().replace(/[^a-z0-9]+/gi, "_");
}
async function _getElementClassList(element: ElementHandle): Promise<string[]> {
if (!element) {
return [];
}
const className = await element.getProperty("className");
if (className) {
const classNameList = await className.jsonValue();
if (typeof(classNameList) === 'string') {
return classNameList.split(" ");
}
}
return [];
}
export
const context: IGalataContext = global.__TEST_CONTEXT__;
export
type SidebarPosition = 'left' | 'right';
export
type SidebarTabId = 'filebrowser' | 'jp-running-sessions' | 'tab-manager' | 'jp-property-inspector' | 'table-of-contents' | 'extensionmanager.main-view' | 'jp-debugger-sidebar';
export
type NotebookToolbarItemId = 'save' | 'insert' | 'cut' | 'copy' | 'paste' | 'run' | 'interrupt' | 'restart' | 'restart-and-run' | 'cellType' | 'kernelName' | 'kernelStatus';
export
function xpContainsClass(className: string): string {
return `contains(concat(" ", normalize-space(@class), " "), " ${className} ")`;
}
export
function xpBuildActivityTabSelector(name: string): string {
return `//div[${xpContainsClass('jp-Activity')}]/ul/li[${xpContainsClass('lm-TabBar-tab')} and ./div[text()="${name}" and ${xpContainsClass('lm-TabBar-tabLabel')}]]`;
}
export
function xpBuildActivityPanelSelector(id: string): string {
return `//div[@id='${id}' and ${xpContainsClass('jp-Activity')} and ${xpContainsClass('lm-DockPanel-widget')}]`;
}
export
function xpBuildActiveActivityTabSelector(): string {
return `//div[${xpContainsClass('jp-Activity')}]/ul/li[${xpContainsClass('lm-TabBar-tab')} and ${xpContainsClass('lm-mod-current')} and ./div[${xpContainsClass('lm-TabBar-tabLabel')}]]`;
}
export
function getFilesInDirectory(dirPath: string, filePaths?: string[]): string[] {
const files = fs.readdirSync(dirPath);
filePaths = filePaths || [];
for (let file of files) {
if (file.startsWith('.')) {
continue;
}
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
filePaths = getFilesInDirectory(dirPath + "/" + file, filePaths);
} else {
filePaths.push(path.join(dirPath, "/", file));
}
}
return filePaths;
}
async function waitForFunction(fn: Function, timeout?: number): Promise<void> {
return new Promise((resolve, reject) => {
let checkTimer;
let timeoutTimer;
const check = async () => {
checkTimer = null;
if (await Promise.resolve(fn())) {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
resolve();
} else {
checkTimer = setTimeout(check, 200);
}
};
check();
if (timeout) {
timeoutTimer = setTimeout(() => {
timeoutTimer = null;
if (checkTimer) {
clearTimeout(checkTimer);
}
reject(new Error('Timed out waiting for condition to be fulfilled.'));
}, timeout);
}
});
}
async function waitForDuration(duration: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => { resolve(); }, duration);
});
}
export
async function waitFor(condition: Function | number, timeout?: number): Promise<void> {
const conditionType = typeof condition;
if (conditionType === 'function') {
return waitForFunction(condition as Function, timeout);
} else if (conditionType === 'number') {
return waitForDuration(condition as number);
}
}
function logTestCapture(capture: ICapture) {
if (!context.testCaptures[_currentSuite]) {
context.testCaptures[_currentSuite] = {};
}
const suiteCaptures = context.testCaptures[_currentSuite];
if (!suiteCaptures[_currentTest]) {
suiteCaptures[_currentTest] = [];
}
const testCaptures = suiteCaptures[_currentTest];
const numCaptures = testCaptures.length;
// if same name and type (html, image) then replace
for (let c = 0; c < numCaptures; ++c) {
const existingCapture = testCaptures[c];
if (existingCapture.name === capture.name && capture.type === existingCapture.type) {
testCaptures[c] = capture;
return;
}
}
testCaptures.push(capture);
}
export
function log(log: ITestLog) {
if (!context.testLogs[_currentSuite]) {
context.testLogs[_currentSuite] = {};
}
const suiteLogs = context.testLogs[_currentSuite];
if (!suiteLogs[_currentTest]) {
suiteLogs[_currentTest] = [];
}
const testLogs = suiteLogs[_currentTest];
testLogs.push(log);
}
export
function createNewPage(options?: ICreateNewPageOptions): Promise<Page> {
return context._createNewPage(options);
}
export
async function reloadPage(): Promise<void> {
await context._reloadPage();
}
export
namespace capture {
export
async function screenshot(fileName: string, element: ElementHandle<Element> | null = null): Promise<boolean> {
const fileNameSafe = _transformCaptureName(fileName);
const filePath = `screenshots/${fileNameSafe}.png`;
const options: any = {
path: `${context.testOutputDir}/${filePath}`
};
const logScreenshot = () => {
logTestCapture({type: 'image', name: fileName, fileName: fileNameSafe, result: 'uncompared'});
};
if (element) {
const rect = await context.page.evaluate(async (element) => {
const rect = element.getBoundingClientRect();
return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
}, element);
if (rect.width > 0 && rect.height > 0) {
await element.screenshot(options);
logScreenshot();
return true;
}
} else {
await context.page.screenshot(options);
logScreenshot();
return true;
}
return false;
}
export
async function compareScreenshot(fileName: string): Promise<CaptureCompareResult> {
const fileNameSafe = _transformCaptureName(fileName);
const filePath = `screenshots/${fileNameSafe}.png`;
const removeMatchedCapture = () => {
if (context.discardMatchedCaptures) {
fs.unlinkSync(`${context.testOutputDir}/${filePath}`);
}
};
if (context.skipVisualRegression) {
return 'same';
}
const referencePath = `screenshots/${fileNameSafe}.png`;
let result: CaptureCompareResult;
if (!fs.existsSync(`${context.testOutputDir}/${filePath}`)) {
result = 'missing-capture';
}
if (!fs.existsSync(`${context.referenceDir}/${referencePath}`)) {
result = 'missing-reference';
}
if (result) {
logTestCapture({
type: 'image',
name: fileName,
fileName: fileNameSafe,
result: result
});
return result;
}
const referenceImage = PNG.sync.read(fs.readFileSync(`${context.referenceDir}/${referencePath}`));
const testImage = PNG.sync.read(fs.readFileSync(`${context.testOutputDir}/${filePath}`));
const { width, height } = referenceImage;
if (testImage.width !== width || testImage.height !== height) {
result = 'different-size';
logTestCapture({
type: 'image',
name: fileName,
fileName: fileNameSafe,
result: result
});
return result;
}
const threshold = context.imageMatchThreshold;
const diffImage = new PNG({ width, height });
let diff = 0;
try {
diff = pixelmatch(
referenceImage.data, testImage.data, diffImage.data, width, height, { threshold: threshold });
} catch {
diff = Number.MAX_SAFE_INTEGER;
}
if (diff > 0) {
result = 'different';
const diffPath = `screenshots/diff/${fileNameSafe}.png`;
fs.writeFileSync(`${context.testOutputDir}/${diffPath}`, PNG.sync.write(diffImage));
} else {
result = 'same';
removeMatchedCapture();
}
logTestCapture({
type: 'image',
name: fileName,
fileName: fileNameSafe,
result: result
});
return result;
}
export
async function captureHTML(fileName: string, element: ElementHandle<Element> | null = null): Promise<string> {
const fileNameSafe = _transformCaptureName(fileName);
const filePath = `html/${fileNameSafe}.html`;
logTestCapture({type: 'html', name: fileName, fileName: fileNameSafe, result: 'uncompared'});
let result: string;
if (element) {
result = await element.evaluate(node => node.innerHTML);
} else {
result = await context.page.evaluate(() => document.body.innerHTML);
}
result = jsBeautify.html(result);
fs.writeFileSync(`${context.testOutputDir}/${filePath}`, result);
return result;
}
export
async function compareHTML(fileName: string): Promise<CaptureCompareResult> {
const fileNameSafe = _transformCaptureName(fileName);
const filePath = `html/${fileNameSafe}.html`;
const removeMatchedCapture = () => {
if (context.discardMatchedCaptures) {
fs.unlinkSync(`${context.testOutputDir}/${filePath}`);
}
};
if (context.skipHtmlRegression) {
return 'same';
}
const referencePath = `html/${fileNameSafe}.html`;
let result: CaptureCompareResult;
if (!fs.existsSync(`${context.testOutputDir}/${filePath}`)) {
result = 'missing-capture';
}
if (!fs.existsSync(`${context.referenceDir}/${referencePath}`)) {
result = 'missing-reference';
}
if (result) {
logTestCapture({
type: 'html',
name: fileName,
fileName: fileNameSafe,
result: result
});
return result;
}
const referenceContent = fs.readFileSync(`${context.referenceDir}/${referencePath}`);
const testContent = fs.readFileSync(`${context.testOutputDir}/${filePath}`);
if (testContent.compare(referenceContent) !== 0) {
result = 'different';
const diffPath = `${context.testOutputDir}/html/diff/${fileNameSafe}.html`;
fs.writeFileSync(diffPath, 'different');
} else {
result = 'same';
removeMatchedCapture();
}
logTestCapture({
type: 'html',
name: fileName,
fileName: fileNameSafe,
result: result
});
return result;
}
}
export
namespace kernel {
export
async function isAnyRunning(): Promise<boolean> {
return await context.page.evaluate(() => {
return window.jupyterlab.serviceManager.sessions.running().next() !== undefined;
});
}
export
async function shutdownAll(): Promise<void> {
await context.page.evaluate(async () => {
await window.jupyterlab.serviceManager.sessions.shutdownAll();
});
await waitFor(async () => {
return await isAnyRunning() === false;
});
}
}
export
namespace menu {
export
async function closeAll() {
const page = context.page;
const existingMenus = await page.$$('.lm-Menu');
const numOpenMenus = existingMenus.length;
// close menus
for (let i = 0; i < numOpenMenus; ++i) {
await page.keyboard.press('Escape');
await page.waitForTimeout(100);
await page.waitForFunction((menuCount: number) => {
return document.querySelectorAll('.lm-Menu').length === menuCount;
}, numOpenMenus - (i + 1));
}
}
export
async function getMenuBarItem(label: string): Promise<ElementHandle<Element> | null> {
return await context.page.$(`xpath=//li[./div[text()="${label}" and ${xpContainsClass('lm-MenuBar-itemLabel')}]]`);
}
export
async function getMenuItem(path: string): Promise<ElementHandle<Element> | null> {
const page = context.page;
const parts = path.split('>');
const numParts = parts.length;
let subMenu: ElementHandle<Element> = null;
for (let i = 0; i < numParts; ++i) {
const part = parts[i];
const menuItem = i === 0 ? await getMenuBarItem(part) : await getMenuItemInMenu(subMenu, part);
if (menuItem) {
if (i === numParts - 1) {
return menuItem;
} else {
if (i === 0) {
subMenu = await page.$('.lm-Menu.lm-MenuBar-menu');
} else {
const newMenus = await page.$$('.lm-Menu');
subMenu = newMenus.length > 0 ? newMenus[newMenus.length - 1] : null;
}
if (!subMenu) {
return null;
}
}
} else {
return null;
}
}
return null;
}
export
async function getMenuItemInMenu(parentMenu: ElementHandle<Element>, label: string): Promise<ElementHandle<Element> | null> {
const items = await parentMenu.$$(`xpath=./ul/li[./div[text()="${label}" and ${xpContainsClass('lm-Menu-itemLabel')}]]`);
if (items.length > 1) {
throw new Error(`More than one menu item matches label '${label}'`);
}
return items.length > 0 ? items[0] : null;
}
export
async function isAnyOpen(): Promise<boolean> {
return await context.page.$('.lm-Menu') !== null;
}
export
async function isOpen(path: string): Promise<boolean> {
return await getMenuItem(path) !== null;
}
export
async function open(path: string): Promise<ElementHandle<Element> | null> {
await closeAll();
const page = context.page;
const parts = path.split('>');
const numParts = parts.length;
let subMenu: ElementHandle<Element> = null;
for (let i = 0; i < numParts; ++i) {
const part = parts[i];
const menuItem = i === 0 ? await getMenuBarItem(part) : await getMenuItemInMenu(subMenu, part);
if (menuItem) {
if (i === 0) {
await menuItem.click();
subMenu = await page.waitForSelector('.lm-Menu.lm-MenuBar-menu', { state: 'visible' });
} else {
const existingMenus = await page.$$('.lm-Menu');
await menuItem.hover();
await page.waitForFunction(({menuCount, menuItem}) => {
return document.querySelectorAll('.lm-Menu').length === menuCount && menuItem.classList.contains('lm-mod-active');
}, {menuCount: existingMenus.length + 1, menuItem: menuItem});
await page.waitForTimeout(200);
// Fetch a new list of menus, and fetch the last one.
// We are assuming the last menu is the most recently opened.
const newMenus = await page.$$('.lm-Menu');
subMenu = newMenus[newMenus.length - 1];
}
}
}
return subMenu;
}
export
async function getOpenMenu(): Promise<ElementHandle<Element> | null> {
const openMenus = await context.page.$$('.lm-Widget.lm-Menu .lm-Menu-content');
if (openMenus.length > 0) {
return openMenus[openMenus.length - 1];
}
return null;
}
export
async function clickMenuItem(path: string) {
const parts = path.split('>');
const numParts = parts.length;
const label = parts[numParts - 1];
path = parts.slice(0, numParts - 1).join('>');
// open parent menu
const parentMenu = await open(path);
const menuItem = await getMenuItemInMenu(parentMenu, label);
if (menuItem) {
await menuItem.click();
}
}
}
export
namespace activity {
export
async function closeAll() {
const launcherSelector = xpBuildActivityTabSelector('Launcher');
await context.page.evaluate(async (launcherSelector) => {
const app = window.jupyterlab;
await app.commands.execute('application:close-all');
await window.galataip.waitForXPath(launcherSelector);
}, launcherSelector);
}
export
async function isTabActive(name: string): Promise<boolean> {
const tab = await getTab(name);
return tab && await tab.evaluate((tab) => tab.classList.contains('lm-mod-current'));
}
export
async function getTab(name?: string): Promise<ElementHandle<Element> | null> {
const page = context.page;
const tabSelector = name ? xpBuildActivityTabSelector(name) : xpBuildActiveActivityTabSelector();
return await page.$(`xpath=${tabSelector}`);
}
export
async function getPanel(name?: string): Promise<ElementHandle<Element> | null> {
const page = context.page;
const tab = await getTab(name);
if (tab) {
const id = await tab.evaluate((tab) => tab.getAttribute('data-id'));
return await page.$(`xpath=${xpBuildActivityPanelSelector(id)}`);
}
return null;
}
export
async function activateTab(name: string): Promise<boolean> {
const tab = await getTab(name);
if (tab) {
await tab.click();
await context.page.waitForFunction(({tab}) => {
return tab.classList.contains('jp-mod-current');
}, {tab});
return true;
}
return false;
}
}
export
namespace logconsole {
export
async function logCount(): Promise<number> {
return await context.page.evaluate(() => {
let count = 0;
const logPanels = document.querySelectorAll('.jp-LogConsolePanel .lm-StackedPanel-child');
logPanels.forEach((logPanel) => {
if (!logPanel.classList.contains('lm-mod-hidden')) {
count += logPanel.querySelectorAll('.jp-OutputArea-child').length;
}
});
return count;
});
}
}
export
namespace contents {
export
async function getContentMetadata(dirPath: string): Promise<any> {
const apiUrl = `${context.jlabBaseUrl}/api/contents`;
const data = JSON.stringify({
'type':'file'
});
const request: AxiosRequestConfig = {
url: `${apiUrl}/${dirPath}`,
method: 'GET',
data: data
};
if (context.jlabToken) {
request.headers = {'Authorization': `Token ${context.jlabToken}`};
}
let response: any;
try {
response = await axios(request);
} catch (error) {
}
const succeeded = response && response.status === 200;
if (succeeded) {
return response.data;
}
return null;
}
export
async function directoryExists(dirPath: string): Promise<boolean> {
const content = await getContentMetadata(dirPath);
return content && content.type === 'directory';
}
export
async function fileExists(filePath: string): Promise<boolean> {
const content = await getContentMetadata(filePath);
return content && (content.type === 'notebook' || content.type === 'file');
}
export
async function createDirectory(dirPath: string): Promise<boolean> {
const directories = dirPath.split('/');
let path = '';
for (let directory of directories) {
if (directory.trim() === '') {
continue;
}
if (path !== '') {
path += '/';
}
path += directory;
await _createDirectory(path);
}
return true;
}
export
async function moveDirectoryToServer(sourcePath: string, destinationPath?: string): Promise<boolean> {
const pos = sourcePath.lastIndexOf('/');
const sourceDirName = sourcePath.substring(pos + 1);
destinationPath = destinationPath === undefined ? sourceDirName : destinationPath;
const files = getFilesInDirectory(sourcePath);
for (let file of files) {
const relativePath = file.substring(sourcePath.length + 1);
await moveFileToServer(file, `${destinationPath}/${relativePath}`);
}
return true;
}
export
async function moveFileToServer(sourcePath: string, destinationPath?: string): Promise<boolean> {
const apiUrl = `${context.jlabBaseUrl}/api/contents`;
const fileName = destinationPath ? destinationPath : path.basename(sourcePath);
const pos = destinationPath ? destinationPath.lastIndexOf('/') : -1;
if (pos !== -1) {
const destDir = destinationPath.substring(0, pos);
if (!await directoryExists(destDir)) {
await createDirectory(destDir);
}
}
const data = JSON.stringify({
'content': _base64EncodeFile(sourcePath),
'format': 'base64',
'type':'file'
});
const request: AxiosRequestConfig = {
url: `${apiUrl}/${fileName}`,
method: 'PUT',
data: data,
maxContentLength: Infinity
};
if (context.jlabToken) {
request.headers = {'Authorization': `Token ${context.jlabToken}`};
}
let response: any;
try {
response = await axios(request);
} catch (error) {
console.error(error);
}
const succeeded = response && response.status === 201;
if (succeeded) {
return await fileExists(`${apiUrl}/${fileName}`);
}
return false;
}
export
async function deleteFile(filePath: string): Promise<boolean> {
await context.page.evaluate(async ({pluginId, filePath}) => {
const docManager = await window.galataip.getPlugin(pluginId) as IDocumentManager;
await docManager.deleteFile(filePath);
}, {pluginId: PLUGIN_ID_DOC_MANAGER as keyof IPluginNameToInterfaceMap, filePath: filePath});
return true;
}
export
async function deleteDirectory(dirPath: string): Promise<boolean> {
const dirContent = await getContentMetadata(dirPath);
if (!(dirContent && dirContent.type === 'directory')) {
return false;
}
let anyFailed = false;
// delete directory contents first
for (let item of dirContent.content) {
if (item.type === 'directory') {
if (!await deleteDirectory(item.path)) {
anyFailed = true;
}
} else {
if (!await deleteFile(item.path)) {
anyFailed = true;
}
}
}
if (!await deleteFile(dirPath)) {
anyFailed = true;
}
return !anyFailed;
}
export
async function renameFile(oldName: string, newName: string): Promise<boolean> {
return await context.page.evaluate(async ({pluginId, oldName, newName}) => {
const docManager = await window.galataip.getPlugin(pluginId) as IDocumentManager;
const result = await docManager.rename(oldName, newName);
return result != null;
}, {pluginId: PLUGIN_ID_DOC_MANAGER as keyof IPluginNameToInterfaceMap, oldName: oldName, newName: newName});
}
export
async function renameDirectory(oldName: string, newName: string): Promise<boolean> {
return await renameFile(oldName, newName);
}
export
async function waitForAPIResponse(trigger?: () => Promise<void> | void) {
const page = context.page;
return new Promise<void>(async (resolve, reject) => {
page.on('response', function callback(response) {
if (response.url().includes("api/contents")) {
page.removeListener('response', callback);
resolve();
}
});
if (trigger) {
await trigger();
}
});
}
async function _createDirectory(dirPath: string): Promise<boolean> {
const apiUrl = `${context.jlabBaseUrl}/api/contents`;
const data = JSON.stringify({
'format': 'json',
'type': 'directory'
});
const request: AxiosRequestConfig = {
url: `${apiUrl}/${dirPath}`,
method: 'PUT',
data: data
};
if (context.jlabToken) {
request.headers = {'Authorization': `Token ${context.jlabToken}`};
}
let response: any;
try {
response = await axios(request);
} catch (error) {
}
return response && response.status === 201;
}
}
export
namespace filebrowser {
export
function xpBuildFileSelector(fileName: string) {
return `//div[@id='filebrowser']//li[./span[${xpContainsClass('jp-DirListing-itemText')} and ./span[text()="${fileName}"]]]`;
}
export
function xpBuildDirectorySelector(dirName: string) {
return `//div[@id='filebrowser']//li[@data-isdir='true' and ./span[${xpContainsClass('jp-DirListing-itemText')} and ./span[text()="${dirName}"]]]`;
}
export
async function revealFileInBrowser(filePath: string): Promise<void> {
const pos = filePath.lastIndexOf('/');
const dirPath = filePath.substring(0, pos);
const fileName = filePath.substring(pos + 1);
await openDirectory(dirPath);
await waitFor(async () => {
return await isFileListedInBrowser(fileName);
});
}
export
async function isFileListedInBrowser(fileName: string): Promise<boolean> {
const item = await context.page.$(`xpath=${xpBuildFileSelector(fileName)}`);
return item !== null;
}
export
async function getCurrentDirectory(): Promise<string> {
return await context.page.evaluate(() => {
let directory = '';
const spans = document.querySelectorAll('.jp-FileBrowser .jp-FileBrowser-crumbs span');
const numSpans = spans.length;
if (numSpans > 1) {
directory = spans[numSpans - 2].getAttribute('title');
}
return directory;
});
}
export
async function openHomeDirectory(): Promise<boolean> {
const homeButton = await context.page.$('.jp-FileBrowser .jp-FileBrowser-crumbs span');
if (!homeButton) {
return false;
}
await homeButton.click();
await context.page.waitForFunction(() => {
const spans = document.querySelectorAll('.jp-FileBrowser .jp-FileBrowser-crumbs span');
return spans.length === 2 && spans[0].classList.contains('jp-BreadCrumbs-home');
});
// wait for DOM rerender
await waitFor(200);
return true;
}
export
async function openDirectory(dirPath: string): Promise<boolean> {
if (!await openHomeDirectory()) {
return false;
}
const directories = dirPath.split('/');
let path = '';
for (let directory of directories) {
if (directory.trim() === '') {
continue;
}
if (path !== '') {
path += '/';
}
path += directory;
if (!await _openDirectory(directory)) {
return false;
}
await waitFor(async () => {
return await getCurrentDirectory() === path;
});
}
return true;
}
export
async function refresh(): Promise<void> {
const page = context.page;
const item = await page.$(`xpath=//div[@id='filebrowser']//button[${xpContainsClass('jp-ToolbarButtonComponent')} and .//*[@data-icon='ui-components:refresh']]`);
if (item) {
// wait for network response or timeout
await Promise.race([
waitForDuration(2000),
contents.waitForAPIResponse(async () => {
await item.click();
})
]);
// wait for DOM rerender
await waitFor(200);
} else {
throw new Error('Could not find refresh toolbar item');
}
}