-
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathFile.js
More file actions
502 lines (444 loc) · 20.7 KB
/
File.js
File metadata and controls
502 lines (444 loc) · 20.7 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
/*
* Project Name : Visual Python
* Description : GUI-based Python code generator
* File Name : File.js
* Author : Black Logic
* Note : Apps > File
* License : GNU GPLv3 with Visual Python special exception
* Date : 2021. 11. 18
* Change Date :
*/
//============================================================================
// [CLASS] File
//============================================================================
define([
__VP_TEXT_LOADER__('vp_base/html/m_apps/file.html'), // INTEGRATION: unified version of text loader
__VP_CSS_LOADER__('vp_base/css/m_apps/file'), // INTEGRATION: unified version of css loader
'vp_base/js/com/com_String',
'vp_base/js/com/com_util',
'vp_base/js/com/com_Const',
'vp_base/js/com/component/PopupComponent',
'vp_base/js/com/com_generatorV2',
'vp_base/data/m_library/pandasLibrary',
'vp_base/js/com/component/FileNavigation',
'vp_base/js/com/component/SuggestInput'
], function(fileHtml, fileCss, com_String, com_util, com_Const, PopupComponent
, pdGen, pandasLibrary, FileNavigation, SuggestInput) {
/**
* File
*/
class File extends PopupComponent {
_init() {
super._init();
/** Write codes executed before rendering */
this.config.dataview = false;
this.config.sizeLevel = 1;
this.config.checkModules = ['pd'];
this.fileExtensions = {
'csv': 'csv',
'excel': 'xlsx',
'json': 'json',
'pickle': '',
'sas': '', // xport or sas7bdat
'spss': ''
}
this.package = {
input: [
{ name: 'vp_fileioType' },
{ name: 'vp_pageDom'}
]
}
// INTEGRATED: integrate data source from raw.github
// if (vpConfig.extensionType === 'notebook') {
// this.dataPath = window.location.origin + com_Const.DATA_PATH + "sample_csv/";
// } else if (vpConfig.extensionType === 'colab' || vpConfig.extensionType === 'lab') {
// // this.dataPath = com_Const.DATA_PATH + "sample_csv/";
// this.dataPath = 'https://raw.githubusercontent.com/visualpython/visualpython/main/data/sample_csv/';
// }
if (vpConfig.extensionType === 'lite') {
this.dataPath = '/drive/data/';
} else {
this.dataPath = 'https://raw.githubusercontent.com/visualpython/visualpython/main/visualpython/data/sample_csv/';
}
this.state = {
fileExtension: 'csv',
selectedFile: '',
selectedPath: '',
vp_fileioType: 'Read',
vp_pageDom: '',
userOption: '',
...this.state
}
this.fileResultState = {
pathInputId : this.wrapSelector('#vp_fileRead #i0'),
fileInputId : this.wrapSelector('#vp_fileRead #fileName')
};
this.fileState = {
'Read': {
fileTypeId: {
'csv': 'pd_readCsv',
'excel': 'pd_readExcel',
'json': 'pd_readJson',
'pickle': 'pd_readPickle',
'sas': 'pd_readSas',
'spss': 'pd_readSpss'
},
selectedType: 'csv',
package: null,
fileResultState: {
pathInputId : this.wrapSelector('#vp_fileRead #i0'),
fileInputId : this.wrapSelector('#vp_fileRead #fileName')
}
},
'Write': {
fileTypeId: {
'csv': 'pd_toCsv',
'excel': 'pd_toExcel',
'json': 'pd_toJson',
'pickle': 'pd_toPickle'
},
selectedType: 'csv',
package: null,
fileResultState: {
pathInputId : this.wrapSelector('#vp_fileWrite #i1'),
fileInputId : this.wrapSelector('#vp_fileWrite #fileName')
}
},
// 'Sample': {
// library: 'pandas',
// code: "${vp_sampleReturn} = pd.read_csv('" + this.dataPath + "${vp_sampleFile}'${v})",
// input: [
// {
// name:'vp_sampleFile',
// label: 'Sample Data',
// component: 'option_select',
// options: [
// 'iris.csv', 'titanic.csv', 'fish.csv', 'campusRecruitment.csv',
// 'houseData_500.csv', 'economic_index.csv', 'tips.csv'
// ],
// options_label: [
// 'iris', 'titanic', 'fish', 'campusRecruitment',
// 'houseData_500', 'economic index', 'tips'
// ]
// }
// ],
// output: [
// {
// name:'vp_sampleReturn',
// type:'var',
// label:'Allocate to',
// required: true
// }
// ]
// }
"Sample": {
"library": "pandas",
"code": "${vp_sampleReturn} = pd.read_csv('" + this.dataPath + "${vp_sampleFile}')",
"options": [
{
"name": "vp_sampleFile",
"label": "Sample Data",
"required": true,
"component": [
"option_select"
],
"options": [
"iris.csv",
"titanic.csv",
"fish.csv",
"campusRecruitment.csv",
"houseData_500.csv",
"economic_index.csv",
"tips.csv"
],
"options_label": [
"iris",
"titanic",
"fish",
"campusRecruitment",
"houseData_500",
"economic index",
"tips"
]
},
{
"name": "vp_sampleReturn",
"label": "Allocate to",
"component": [
"data_select"
],
"output": true,
"required": true,
"value": 'vp_df'
}
]
}
}
}
_bindEvent() {
super._bindEvent();
/** Implement binding events */
var that = this;
$(this.wrapSelector('#vp_fileioType')).on('change', function() {
var pageType = $(this).val();
that.state['vp_fileioType'] = pageType;
$(that.wrapSelector('.vp-fileio-box')).hide();
$(that.wrapSelector('#vp_file' + pageType)).show();
//set fileExtensions
that.fileResultState = {
...that.fileState[pageType].fileResultState
};
});
}
_bindEventByType(pageType) {
var that = this;
var prefix = '#vp_file' + pageType + ' ';
// select file type
$(this.wrapSelector(prefix + '#fileType')).change(function() {
var value = $(this).val();
that.fileState[pageType].selectedType = value;
// reload
that.renderPage(pageType);
that._bindEventByType(pageType);
if (value === 'spss') {
// show install button
that.showInstallButton();
// show install note below File type selection
$(`<tr><td colspan="2">
<label class="vp-orange-text vp-italic">NOTE: </label>
<label class="vp-gray-text vp-italic">pyreadstat package is required to read spss file.</label>
</td></tr>`).insertAfter($(that.wrapSelector('#fileType')).closest('tr'));
} else {
that.hideInstallButton();
}
});
// open file navigation
$(this.wrapSelector(prefix + '#vp_openFileNavigationBtn')).click(function() {
let type = 'save';
if (pageType == 'Read') {
type = 'open';
}
let extensionList = [];
if (that.state.fileExtension !== '') {
extensionList = [ that.state.fileExtension ];
}
let fileNavi = new FileNavigation({
type: type,
extensions: extensionList,
finish: function(filesPath, status, error) {
let {file, path} = filesPath[0];
that.state.selectedFile = file;
that.state.selectedPath = path;
// set text
$(that.fileResultState.fileInputId).val(file);
$(that.fileResultState.pathInputId).val(path);
}
});
fileNavi.open();
});
}
saveState() {
var pageType = $(this.wrapSelector('#vp_fileioType')).val();
// save input state
$(this.wrapSelector('#vp_file' + pageType + ' input')).each(function () {
this.defaultValue = this.value;
});
// save checkbox state
$(this.wrapSelector('#vp_file' + pageType + ' input[type="checkbox"]')).each(function () {
if (this.checked) {
this.setAttribute("checked", true);
} else {
this.removeAttribute("checked");
}
});
// save select state
$(this.wrapSelector('#vp_file' + pageType + ' select > option')).each(function () {
if (this.selected) {
this.setAttribute("selected", true);
} else {
this.removeAttribute("selected");
}
});
var pageDom = $(this.wrapSelector('#vp_file' + pageType)).html();
this.state['vp_pageDom'] = pageDom;
}
loadStateAfterRender() {
var pageType = this.state['vp_fileioType'];
var pageDom = this.state['vp_pageDom'];
// load pageDom
$(this.wrapSelector('#vp_file' + pageType)).html(pageDom);
// set page type
$(this.wrapSelector('#vp_fileioType')).val(pageType);
// show loaded page
$(this.wrapSelector('.vp-fileio-box')).hide();
$(this.wrapSelector('#vp_file' + pageType)).show();
//set fileResultState
this.fileResultState = {
...this.fileState[pageType].fileResultState
};
// bind event by page type
this._bindEventByType(pageType);
}
templateForBody() {
/** Implement generating template */
let page = $(fileHtml);
// Removed dataselector for Allocation input
// let allocateSelector = new DataSelector({
// pageThis: this, id: 'vp_sampleReturn', placeholder: 'Variable name', value: 'vp_df'
// });
// $(page).find('#vp_sampleReturn').replaceWith(allocateSelector.toTagString());
return page;
}
renderPage(pageType) {
var that = this;
var prefix = '#vp_file' + pageType + ' ';
// clear
$(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).html('');
$(this.wrapSelector(prefix + '#vp_optionBox table tbody')).html('');
var fileTypeObj = this.fileState[pageType]['fileTypeId'];
var selectedType = this.fileState[pageType]['selectedType'];
let fileId = fileTypeObj[selectedType];
let pdLib = pandasLibrary.PANDAS_FUNCTION;
let thisPkg = JSON.parse(JSON.stringify(pdLib[fileId]));
this.fileState[pageType].package = thisPkg;
this.state.fileExtension = that.fileExtensions[selectedType];
this.fileResultState = {
...this.fileState[pageType].fileResultState
};
if (selectedType == 'pickle') {
// hide additional option box
$(this.wrapSelector(prefix + '#vp_optionBox')).closest('.vp-accordian-container').hide();
} else {
$(this.wrapSelector(prefix + '#vp_optionBox')).closest('.vp-accordian-container').show();
}
if (pageType == 'Write') {
if (selectedType == 'json') {
this.fileResultState.pathInputId = this.wrapSelector(prefix + '#path_or_buf');
}
if (selectedType == 'pickle') {
this.fileResultState.pathInputId = this.wrapSelector(prefix + '#path');
}
}
// render interface
// pdGen.vp_showInterfaceOnPage(this.wrapSelector('#vp_file' + pageType), thisPkg);
// pdGen.vp_showInterfaceOnPage(this.wrapSelector('#vp_file' + pageType), thisPkg);
pdGen.vp_showInterfaceOnPage(this, thisPkg, this.state, parent=('#vp_file' + pageType));
// prepend file type selector
$(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).prepend(
$('<tr>').append($(`<td><label for="fileType" class="vp-bold vp-orange-text">File Type</label></td>`))
.append($('<td><select id="fileType" class="vp-select"></select></td>'))
);
var fileTypeList = Object.keys(fileTypeObj);
fileTypeList.forEach(type => {
$(this.wrapSelector(prefix + '#fileType')).append(
$(`<option value="${type}">${type}</option>`)
);
});
// prepend user option
let hasAllocateTo = $(this.wrapSelector(prefix + '#o0')).length > 0;
if (hasAllocateTo) {
$(this.wrapSelector(prefix + '#o0')).closest('tr').after(
$('<tr>').append($(`<td><label for="userOption">User Option</label></td>`))
.append($('<td><input id="userOption" type="text" class="vp-input vp-state" placeholder="key=value, ..."/></td>'))
)
} else {
$(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).append(
$('<tr>').append($(`<td><label for="userOption">User Option</label></td>`))
.append($('<td><input id="userOption" type="text" class="vp-input vp-state" placeholder="key=value, ..."/></td>'))
)
}
$(this.wrapSelector(prefix + '#fileType')).val(selectedType);
// add file navigation button
if (pageType == 'Write') {
if (selectedType == 'json') {
$(prefix + '#path_or_buf').parent().html(
com_util.formatString('<input type="text" class="vp-input vp-state" id="path_or_buf" index="0" placeholder="" value="" title=""><div id="vp_openFileNavigationBtn" class="{0}"></div>'
, 'vp-file-browser-button')
);
} else if (selectedType == 'pickle') {
$(prefix + '#path').parent().html(
com_util.formatString('<input type="text" class="vp-input vp-state" id="path" index="0" placeholder="" value="" title="" required="true"><div id="vp_openFileNavigationBtn" class="{0}"></div>'
, 'vp-file-browser-button')
);
} else {
$(this.fileState[pageType]['fileResultState']['pathInputId']).parent().html(
com_util.formatString('<input type="text" class="vp-input vp-state" id="{0}" index="0" placeholder="" value="" title="" required="true"><div id="vp_openFileNavigationBtn" class="{1}"></div>'
, 'i1'
, 'vp-file-browser-button')
);
}
} else {
$(this.fileState[pageType]['fileResultState']['pathInputId']).parent().html(
com_util.formatString('<input type="text" class="vp-input vp-state" id="{0}" index="0" placeholder="" value="" title="" required="true"><div id="vp_openFileNavigationBtn" class="{1}"></div>'
, 'i0'
, 'vp-file-browser-button')
);
}
// encoding suggest input
$(this.wrapSelector('#encoding')).replaceWith(function() {
// encoding list : utf8 cp949 ascii
var encodingList = ['utf8', 'cp949', 'ascii'];
var suggestInput = new SuggestInput();
suggestInput.setComponentID('encoding');
suggestInput.addClass('vp-input vp-state');
suggestInput.setSuggestList(function() { return encodingList; });
suggestInput.setPlaceholder('encoding option');
return suggestInput.toTagString();
});
}
render() {
super.render();
this.renderPage('Read');
this.renderPage('Write');
// initialize fileResultState
this.fileResultState = {
...this.fileState['Read'].fileResultState
};
if (this.state.vp_pageDom && this.state.vp_pageDom != '') {
this.loadStateAfterRender();
}
this._bindEventByType('Read');
this._bindEventByType('Write');
}
generateInstallCode() {
return [ '!pip install pyreadstat' ];
}
generateCode() {
var pageType = $(this.wrapSelector('#vp_fileioType')).val();
var sbCode = new com_String;
this.saveState();
var prefix = '#vp_file' + pageType + ' ';
var userOption = new com_String();
var userOptValue = $(this.wrapSelector(prefix + '#userOption')).val();
if (userOptValue != '') {
userOption.appendFormat(', {0}', userOptValue);
}
if (pageType == 'Sample') {
// sample csv code
// var result = pdGen.vp_codeGenerator(this.uuid + ' #vp_fileSample', { ...this.fileState[pageType] }, userOption.toString());
var result = pdGen.vp_codeGenerator(this, { ...this.fileState[pageType] }, this.state, userOption.toString(), parent='#vp_fileSample');
sbCode.append(result);
} else if (pageType == 'Read') {
var thisPkg = JSON.parse(JSON.stringify(this.fileState[pageType].package));
thisPkg.options.push({
name: 'fileType',
type: 'var'
});
// var result = pdGen.vp_codeGenerator(this.uuid + ' #vp_fileRead', thisPkg, userOption.toString());
var result = pdGen.vp_codeGenerator(this, thisPkg, this.state, userOption.toString(), parent='#vp_fileRead');
sbCode.append(result);
} else if (pageType == 'Write') {
var thisPkg = JSON.parse(JSON.stringify(this.fileState[pageType].package));
thisPkg.options.push({
name: 'fileType',
type: 'var'
});
// var result = pdGen.vp_codeGenerator(this.uuid + ' #vp_fileWrite', thisPkg, userOption.toString());
var result = pdGen.vp_codeGenerator(this, thisPkg, this.state, userOption.toString(), parent='#vp_fileWrite');
sbCode.append(result);
}
return sbCode.toString();
}
}
return File;
});