-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathFileNavigation.js
More file actions
804 lines (709 loc) · 32.4 KB
/
FileNavigation.js
File metadata and controls
804 lines (709 loc) · 32.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
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
/*
* Project Name : Visual Python
* Description : GUI-based Python code generator
* File Name : FileNavigation.js
* Author : Black Logic
* Note : File navigation
* License : GNU GPLv3 with Visual Python special exception
* Date : 2021. 11. 18
* Change Date :
*/
//============================================================================
// [CLASS] FileNavigation
//============================================================================
define([
'!!text-loader!vp_base/html/component/fileNavigation.html', // LAB: text! to text-loader
'vp_base/css/component/fileNavigation.css', // LAB: css! to css-loader
'vp_base/js/com/component/LoadingSpinner',
'vp_base/js/com/com_Const',
'vp_base/js/com/com_String',
'vp_base/js/com/com_util',
'vp_base/js/com/component/Component'
], function(fileNaviHtml, fileNaviCss, LoadingSpinner, com_Const, com_String, com_util, Component) {
// Temporary constant data
const NAVIGATION_DIRECTION_TYPE = {
TOP: 0,
TO: 1,
PREV: 2,
INIT: 3
}
/**
* FileNavigation
* ------------------------------------------------------
* How to use:
* // create file navigation
* let fileNavigation = new FileNavigation({
* type: 'open',
* extensions: ['vp'],
* finish: function(filesPath, status, error) {
* // Do something after selecting file
* }});
* // open file navigation
* fileNavigation.open();
*/
class FileNavigation extends Component {
/**
* Constructor
* @param {Object} state { type, extensions, finish ... }
*/
constructor(state) {
super($(vpConfig.parentSelector), state);
/**
* state.type open / save
* state.extensions extensions list
* state.finish callback function after selection
* - example form : function (filesPath, status, error) { }
* - filesPath : list => list of Object [ { file: '', path: '' } ]
* - status : boolean => true for success / false for error
* - error : if there's error, return its content
* ---------------------------------------------------------------
* state.fileName (optional on save type) pre-defined fileName
* state.multiSelect (optional)
* state.showAll (optional)
*/
vpLog.display(VP_LOG_TYPE.DEVELOP, 'FileNavigation created', state);
}
_init() {
super._init();
/** Write codes executed before rendering */
// state types
this.state = {
direction: '',
type: '', // open / save
filePath: '',
fileName: '',
extensions: [], // extensions list ex) png, jpg, gif
multiSelect: false, // multi selection
showAll: false, // show other extension files also
finish: null, // callback after selection
...this.state
};
this.pathStackPointer = -1;
this.pathStack = [];
this.currentFileList = [];
this.pathState = {
parentPath: '',
currentPath: '',
baseFolder: '', // root folder name
relativeDir: '', // root folder name
baseDir: '', // sliced current dir
notebookFolder: '', // base folder of jupyter notebook path
notebookPath: '' // jupyter notebook path
}
}
_bindEvent() {
var that = this;
// Close file navigation
$(this.wrapSelector('.fileNavigationPage-closedBtn')).on('click', function() {
that.close();
});
// Click root
$(this.wrapSelector('#fnpRootFolder')).on('click', function() {
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.TOP,
destDir: '/'
};
that.getFileList(dirObj);
});
// Click sidebar
$(this.wrapSelector('.fnp-sidebar-menu')).click(function(event) {
$('.fnp-sidebar-menu').removeClass('selected');
$(this).addClass('selected');
var pathType = $(this).attr('data-path');
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.TO,
destDir: '/'
}
switch (pathType) {
case 'desktop':
dirObj.destDir = "_vp_get_desktop_path()";
dirObj.useFunction = true;
break;
case 'documents':
dirObj.destDir = "_vp_get_documents_path()";
dirObj.useFunction = true;
break;
case 'downloads':
dirObj.destDir = "_vp_get_downloads_path()";
dirObj.useFunction = true;
break;
case 'userid':
dirObj.destDir = "_vp_get_userprofile_path()";
dirObj.useFunction = true;
break;
case 'drive':
dirObj.destDir = "/content/drive/MyDrive";
break;
case '/':
default:
dirObj.direction = NAVIGATION_DIRECTION_TYPE.TOP;
break;
}
that.getFileList(dirObj);
});
// Click next(>) directory
$(this.wrapSelector('.fileNavigationPage-btn-next')).click(() => {
if (that.pathStackPointer + 1 == that.pathStack.length) {
com_util.renderAlertModal('No next directory');
return;
}
// initialize sidebar-menu selection
$('.fnp-sidebar-menu').removeClass('selected');
// get next path stack
that.pathStackPointer++;
var nextData = that.pathStack[that.pathStackPointer];
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.PREV,
destDir: nextData
}
that.getFileList(dirObj);
});
// Click prev(<) directory
$(this.wrapSelector('.fileNavigationPage-btn-prev')).click(() => {
if (that.pathStackPointer <= 0) {
com_util.renderAlertModal('No previous directory');
return;
}
// initialize sidebar-menu selection
$('.fnp-sidebar-menu').removeClass('selected');
// get prev path stack
that.pathStackPointer--;
var popedData = that.pathStack[that.pathStackPointer];
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.PREV,
destDir: popedData
}
that.getFileList(dirObj);
});
}
template() {
/** Implement generating template */
let fileNaviBody = $(fileNaviHtml.replaceAll('${vp_base}', com_Const.BASE_PATH));
$(fileNaviBody).find('.fnp-sidebar-menu').hide();
if (vpConfig.extensionType === 'notebook') {
$(fileNaviBody).find('.fnp-sidebar-menu.notebook').show();
} else if (vpConfig.extensionType === 'colab') {
$(fileNaviBody).find('.fnp-sidebar-menu.colab').show();
} else if (vpConfig.extensionType === 'lab') {
$(fileNaviBody).find('.fnp-sidebar-menu.lab').show();
}
return fileNaviBody;
}
/**
* Render file item
* @param {*} fileState { name, type, path, size, atime, mtime }
* - name : file name
* - type : file type (dir / file)
* - path : file absolute path
* - size : size (format: 0.0{B,KB,MB,...})
* - atime : created time (format: YYYY-MM-DD HH:mm)
* - mtime : modified time (format: YYYY-MM-DD HH:mm)
*/
renderFileItem(fileState) {
let {
name, type, path, size, atime, mtime
} = fileState;
let that = this;
let directoryLi = $('<li class="fileNavigationPage-li"></li>');
let directoryI = $(`<i class="fileNavigationPage-dir-text
item_icon
${type=='dir'?'folder':'file'}_icon
icon-fixed-width"
data-type="${type}"
data-path="${path}"
data-size="${size}"
data-atime="${atime}"
data-mtime="${mtime}">
${name}
</i>`);
directoryI.click(function() {
if (type == 'dir') {
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.TO,
destDir: path
}
// initialize sidebar-menu selection
$('.fnp-sidebar-menu').removeClass('selected');
that.getFileList(dirObj);
} else {
let dirPath = that.getRelativePath(that.pathState.baseDir, that.pathState.currentPath);
let extension = name.substring(name.lastIndexOf('.') + 1);
let allowExtensionList = that.state.extensions;
// if it is not allowed extension
if (!allowExtensionList.includes(extension)) {
// TODO: alert
//vpCommon.renderAlertModal('Not supported file type');
return;
}
that.handleSelectFile(dirPath, name);
}
});
directoryLi.append(directoryI);
return directoryLi;
}
/**
* render file list based on currentFileList
*/
renderFileList() {
let that = this;
let fileList = this.currentFileList;
// clear body
$(this.wrapSelector('.fileNavigationPage-body')).html('');
// render file items
let dirArr = [];
let fileArr = [];
// render upper folder
if (that.pathState.parentPath != '') {
let upperFolderTag = that.renderFileItem({
name: '..',
type: 'dir',
path: that.pathState.parentPath,
size: '',
atime: '',
mtime: ''
});
dirArr.push(upperFolderTag);
}
fileList && fileList.forEach((file, idx) => {
if (idx == 0) return;
let fileTag = that.renderFileItem(file);
if (file.type == 'dir') {
dirArr.push(fileTag);
} else {
fileArr.push(fileTag);
}
});
var fileNavigationPageUl = $(`<ul class='fileNavigationPage-ul'></ul>`);
// render folder first
dirArr.forEach(dirTag => {
fileNavigationPageUl.append(dirTag);
});
fileArr.forEach(fileTag => {
fileNavigationPageUl.append(fileTag);
});
$(this.wrapSelector('.fileNavigationPage-body')).append(fileNavigationPageUl);
}
renderNowLocation() {
let that = this;
let currentRelativePathStr = this.pathState.relativeDir;
let currentDirStr = this.pathState.currentPath;
var notebookPathStr = this.pathState.notebookPath;
var notebookPathStrLength = notebookPathStr.length;
var baseFolder = this.pathState.baseFolder;
var notebookFolder = this.pathState.notebookFolder;
/** render current path */
var currentRelativePathStrArray = currentRelativePathStr.split('/');
if (baseFolder === notebookFolder && vpKernel.getNotebookPath().indexOf('/') === -1) {
var index = currentRelativePathStrArray.indexOf(baseFolder)
if (index >= 0) {
currentRelativePathStrArray.splice(index,1);
}
}
var currentRelativePathDomElement = $(`<div><div>`);
var basePathDomElement = $(`<span class='vp-filenavigation-nowLocation' value='/'> / </span>`);
currentRelativePathDomElement.append(basePathDomElement);
basePathDomElement.click(function() {
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.TO,
destDir: notebookPathStr
}
// initialize sidebar-menu selection
$('.fnp-sidebar-menu').removeClass('selected');
// render current file/dir list in fileNavigation body
that.getFileList(dirObj, this);
});
var nestedLength = 0;
// if it's outside of notebookPath, ignore notebookPath
var prevLength = notebookPathStrLength;
var useSidebar = false;
if (currentRelativePathStr.includes('..')) {
var upperList = currentRelativePathStr.match(/(\.\.\/)/g);
if (upperList && upperList.length > 0) {
// in case, currentRelativePathStr = ../../somePathHere
prevLength -= upperList.length * 3; // 3 = length of '../' upper path string
useSidebar = true;
} else {
// in case, currentRelativePathStr = ..
prevLength = 0;
useSidebar = true;
}
}
let slashStr = '/';
currentRelativePathStrArray.forEach((pathToken,index) => {
if (index === 0) {
slashStr = '';
} else {
slashStr = '/';
}
var spanElement = $(`<span class='vp-filenavigation-nowLocation' value='${pathToken}'>
${slashStr} ${pathToken}
</span>`);
var pathLength = prevLength + pathToken.length + 1 + nestedLength;
spanElement.click(function() {
var currentRelativePathStr = `${currentDirStr.substring(0, pathLength)}`;
var dirObj = {
direction: NAVIGATION_DIRECTION_TYPE.TO,
destDir: currentRelativePathStr
}
// initialize sidebar-menu selection
$('.fnp-sidebar-menu').removeClass('selected');
// render current file/dir list in fileNavigation body
that.getFileList(dirObj, this);
});
currentRelativePathDomElement.append(spanElement);
nestedLength += pathToken.length + 1;
});
$('.fileNavigationPage-directory-nowLocation').empty();
$('.fileNavigationPage-directory-nowLocation').append(currentRelativePathDomElement);
}
renderSaveBox() {
let page = new com_String();
page.appendFormatLine('<input id="{0}" type="text" class="vp-input" placeholder="{1}" value="{2}"/>'
, 'vp_fileNavigationInput', 'New File Name', this.state.fileName);
page.appendFormatLine('<select id="{0}" class="vp-select">', 'vp_fileNavigationExt');
this.state.extensions.forEach(ext => {
page.appendFormatLine('<option value="{0}">{1}</option>', ext, ext);
});
page.appendLine('</select>');
page.appendFormatLine('<button class="{0} vp-button" data-menu="{1}">{2}</button>', 'vp-filenavi-btn', 'select', 'Select');
$('.fileNavigationPage-button').html(page.toString());
let that = this;
// bind filename change event
$(this.wrapSelector('#vp_fileNavigationInput')).on('change', function() {
let fileName = $(this).val();
let filePath = that.getRelativePath(that.pathState.baseDir, that.pathState.currentPath);
that.handleSelectFile(filePath, fileName);
});
// bind save cancel event
$(this.wrapSelector('.vp-filenavi-btn')).on('click', function() {
let menu = $(this).data('menu');
if (menu == 'select') {
// select file
let { fileName, filePath } = that.state;
let selectedExt = $(that.wrapSelector('#vp_fileNavigationExt')).val();
let fileExtIdx = fileName.lastIndexOf('.');
// if no extension, add it
if (selectedExt != '' && (fileExtIdx < 0 || fileName.substring(fileExtIdx + 1) != selectedExt)) {
fileName += '.' + selectedExt;
}
// no path, set it
if (filePath == '') {
filePath = './' + fileName;
}
fileExtIdx = filePath.lastIndexOf('.');
if (selectedExt != '' && (fileExtIdx < 0 || filePath.substring(fileExtIdx + 1) != selectedExt)) {
filePath += '.' + selectedExt;
}
// Manage result using finish function
let filesPath = [{ file: fileName, path: filePath }]; //FIXME: fix it if multiple selection implemented
let status = true;
let error = null;
vpLog.display(VP_LOG_TYPE.DEVELOP, 'fileNavigation finished saving', filesPath, status, error);
that.state.finish(filesPath, status, error);
// cancel file navigation
that.close();
}
});
}
loadFileList() {
this.renderNowLocation();
this.renderFileList();
}
render() {
super.render();
let that = this;
/** Implement after rendering */
// if save mode
if (this.state.type == 'save') {
// render saving box
this.renderSaveBox();
}
// get current path
this.getCurrentDirectory().then(function(currentPath) {
that.pathState.currentPath = currentPath;
that.makePaths(currentPath);
// get file list of current path
that.getFileList({ direction: NAVIGATION_DIRECTION_TYPE.INIT, destDir: currentPath});
})
}
open() {
$(this.wrapSelector()).show();
}
close() {
$(this.wrapSelector()).remove();
}
//============================================================================
// File & Path control
//============================================================================
handleSelectFile(relativeDirPath, filePathStr) {
var fileNavigationState = this.pathState;
var baseFolder = fileNavigationState.baseFolder;
var currentDirStr = fileNavigationState.currentPath;
var slashstr = `/`;
if (relativeDirPath === '') {
slashstr = '';
}
var pathInput = '';
var fileInput = `${filePathStr}`;
// if baseFolder doesn't exist in current path
if (currentDirStr.indexOf(baseFolder) === -1) {
pathInput = `${relativeDirPath}${slashstr}${filePathStr}`;
} else {
// if baseFolder exists in current path
pathInput = `./${relativeDirPath}${slashstr}${filePathStr}`;
}
//============================================================================
// Set selection result
//============================================================================
if (this.state.type == 'save') {
// add as saving file
this.setSelectedFile(fileInput, pathInput);
} else {
// Manage result using finish function
let filesPath = [{ file: fileInput, path: pathInput }]; //FIXME: fix it if multiple selection implemented
let status = true;
let error = null;
vpLog.display(VP_LOG_TYPE.DEVELOP, 'fileNavigation finished', filesPath, status, error);
this.state.finish(filesPath, status, error);
// remove and close file navigation
this.close();
}
}
getCurrentDirectory() {
return vpKernel.getCurrentDirectory();
}
/**
* Get File/Dir list
* @param {Object} dirObj { direction, destDir, useFunction }
* - direction : TO, PREV, TOP, INIT
* - destDir : path to search
* - useFunction : boolean (true if use given path (Desktop, Downloads, User, ...))
* @returns Promise(result)
*/
getFileList(dirObj) {
let that = this;
let { direction, destDir, useFunction } = dirObj;
if (direction === NAVIGATION_DIRECTION_TYPE.TO
|| direction === NAVIGATION_DIRECTION_TYPE.PREV) {
;
}
else if (direction === NAVIGATION_DIRECTION_TYPE.TOP) {
destDir = '..';
} else {
destDir = '.';
}
// loading
let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.fileNavigationPage-directory-container')));
// get file list using kernel
return vpKernel.getFileList(destDir, useFunction).then(function(result) {
/** Caution : if change code "$1" to '$1' as single quote, json parsing error occurs */
var jsonVars = result.replace(/'([^']+)': /g, `"$1": `); // object front
jsonVars = jsonVars.replace(/: '([^']+)'([,}])/g, `: "$1"$2`); // object back
jsonVars = jsonVars.replace(/\\/g, `/`);
var varList = JSON.parse(jsonVars);
/** remove file/dir which starts with . */
var filtered_varList = varList.filter(data => {
if (data.name && data.name[0] == '.') {
return false;
} else {
return true;
}
}).sort((a,b) => {
/** sort ascending */
return a - b;
});
/**
* Filter file/dir which included in this.state.extensions
*/
if (Array.isArray(that.state.extensions) && that.state.extensions.length > 0 && that.state.extensions.toString() !== '') {
filtered_varList = filtered_varList.filter((data, index) => {
if (index == 0) {
return true;
}
if (data.type && data.type == 'dir') {
// if file, just show
return true;
} else if (data.name) {
var extension = data.name.substring(data.name.lastIndexOf('.') + 1);
if (that.state.extensions.includes(extension)) {
return true;
} else {
return false;
}
} else {
return false;
}
});
}
vpLog.display(VP_LOG_TYPE.DEVELOP, 'FileNavigation - getFileList: ', filtered_varList);
var { currentDirStr, currentRelativePathStr } = that.splitPathStrAndSetStack(dirObj, filtered_varList);
if (filtered_varList[0].current === filtered_varList[0].parent) {
// no parent
that.pathState.parentPath = '';
} else {
that.pathState.parentPath = filtered_varList[0].parent; // parent path
}
that.pathState.relativeDir = currentRelativePathStr;
that.pathState.currentPath = currentDirStr;
that.currentFileList = filtered_varList;
that.loadFileList();
}).catch(function(resultObj) {
vpLog.display(VP_LOG_TYPE.ERROR, 'FileNavigation error', resultObj);
let { msg, result } = resultObj;
// show error using alert
if (msg.content.evalue) {
let resultStr = msg.content.evalue;
//t.match(/\[Errno [0-9]+?\] (.*)/)[1]
// get error message from traceback
let alertMsg = resultStr.match(/\[Errno [0-9]+?\] (.*)/)[1];
com_util.renderAlertModal(alertMsg);
}
}).finally(function() {
loadingSpinner.remove();
});
}
/**
* Get current path and set pathStates
* @param {String} currentDirStr
*/
makePaths(currentDirStr) {
var slicedCurrentDirStr = currentDirStr.slice(1, currentDirStr.length -1);
slicedCurrentDirStr = slicedCurrentDirStr.replace(/\\/g, `/`);
// slicedCurrentDirStr = slicedCurrentDirStr.replaceAll("//","/"); // replace with codes below
var cursor = 0;
while (slicedCurrentDirStr[cursor] !== undefined ) {
if(slicedCurrentDirStr[cursor] === "/" && slicedCurrentDirStr[cursor + 1] === "/") {
slicedCurrentDirStr = slicedCurrentDirStr.slice(0,cursor) + slicedCurrentDirStr.slice(cursor + 1,slicedCurrentDirStr.length);
}
cursor++;
}
var splitedDirStrArr = slicedCurrentDirStr.split('/');
/**
* ex) if current path is 'C:/Users/VP/Desktop/Test'
* BaseFolderStr = 'Test'
* BaseDirStr = 'C:/Users/VP/Desktop/Test'
* RelativePathStr = 'Test'
* RelativePathStr changes when moving through paths
*/
var rootFolderName = splitedDirStrArr[splitedDirStrArr.length - 1];
var notebookPath = vpKernel.getNotebookPath();
this.pathState.baseFolder = rootFolderName;
this.pathState.relativeDir = rootFolderName;
this.pathState.baseDir = slicedCurrentDirStr;
var baseDirStr = slicedCurrentDirStr;
/**
* Generate notebookFolder, notebookPathStr using Jupyter.notebook.notebook_path
* ex) if current path is 'C:/Users/VP/Desktop/Test'
* Jupyter.notebook.notebook_path = 'Desktop/Test'
* notebookFolder = 'Desktop'
* notebookPathStr = 'Desktop/Test'
* Very root folder is 'VP'
*/
if (notebookPath.indexOf("/") !== -1) {
var index = 0;
while ( notebookPath[index] !== "/" ) {
if ( notebookPath[index] === undefined ) {
break;
}
index++;
}
var notebookFolder = notebookPath.substring(0, index);
var index2 = baseDirStr.indexOf(notebookFolder);
while (baseDirStr[index2] !== "/") {
if ( baseDirStr[index2] === undefined ) {
break;
}
index2++;
}
var notebookFullPathStr = baseDirStr.substring(0, index2);
var index3 = notebookFullPathStr.indexOf(notebookFolder);
var notebookPathStr = baseDirStr.substring(0, index3 - 1);
this.pathState.notebookFolder = notebookFolder;
this.pathState.notebookPath = notebookPathStr;
} else {
this.pathState.notebookFolder = rootFolderName;
this.pathState.notebookPath = slicedCurrentDirStr;
}
}
splitPathStrAndSetStack(dirObj, resultInfoArr){
var currentDirStr = resultInfoArr[0].current.split('//').join('/');
var splitedDirStrArr = currentDirStr.split('/');
var rootFolderName = splitedDirStrArr[splitedDirStrArr.length - 1];
var firstIndex = currentDirStr.indexOf( this.pathState.notebookFolder );
var currentRelativePathStr = '';
if ( firstIndex === -1 ) {
var notebookDir = this.pathState.notebookPath; //TEST:
// FIXME: if current path is upper than Jupyter Home, send no permission?
// currentRelativePathStr = currentDirStr.substring(this.getNotebookDir().length + 1, currentDirStr.length);
// currentRelativePathStr = this.getRelativePath(notebookDir, currentDirStr);
var baseDir = this.pathState.baseDir;
currentRelativePathStr = this.getRelativePath(baseDir, currentDirStr);
} else {
currentRelativePathStr = currentDirStr.substring(firstIndex, currentDirStr.length);
}
if ( dirObj.direction === NAVIGATION_DIRECTION_TYPE.TOP
|| dirObj.direction === NAVIGATION_DIRECTION_TYPE.TO ) {
this.pushPath(currentDirStr);
}
return {
currentDirStr,
currentRelativePathStr,
rootFolderName
}
}
/**
* Get relative path based on start path
* - referred python os.path.relpath()
* @param {string} start start path (base path)
* @param {string} path current path
* @returns current relative path
*/
getRelativePath(start, path) {
const sep = '/';
const curdir = '.';
const pardir = '..';
var startSplit = start.split(sep);
var pathSplit = path.split(sep);
// TODO: check drive: startSplit[0] == pathSplit[0]
var startList = startSplit.slice(1);
var pathList = pathSplit.slice(1);
var stopIdx = 0;
while (stopIdx < startList.length) {
var e1 = startList[stopIdx];
var e2 = pathList[stopIdx];
if (e1 != e2) {
break;
}
stopIdx++;
}
var parList = Array(startList.length - stopIdx).fill(pardir);
var relList = parList.concat(pathList.slice(stopIdx));
if (!relList || relList.length == 0) {
return ''; // curdir
}
return relList.join(sep);
}
pushPath = function(path) {
this.pathStack.push(path);
return true;
}
popPath = function() {
if (this.pathStack.length <= 0) {
return undefined;
}
return this.pathStack.pop();
}
//============================================================================
// Set states
//============================================================================
setExtensions(arr) {
this.state.extensions = arr;
}
setSelectedFile(fileName, filePath) {
this.state.fileName = fileName;
this.state.filePath = filePath;
$(this.wrapSelector('#vp_fileNavigationInput')).val(fileName);
}
}
return FileNavigation;
});