-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathvpFuncJS.js
More file actions
423 lines (376 loc) · 15 KB
/
vpFuncJS.js
File metadata and controls
423 lines (376 loc) · 15 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
define([
'jquery'
, 'nbextensions/visualpython/src/common/vpCommon'
, 'nbextensions/visualpython/src/common/constant'
, 'nbextensions/visualpython/src/common/metaDataHandler'
, 'nbextensions/visualpython/src/common/StringBuilder'
, 'nbextensions/visualpython/src/common/component/vpAccordionBox'
, 'nbextensions/visualpython/src/common/component/vpLineNumberTextArea'
, 'nbextensions/visualpython/src/common/component/vpTableLayoutVerticalSimple'
, 'nbextensions/visualpython/src/common/component/vpTableLayoutHorizontalSimple'
, 'nbextensions/visualpython/src/common/component/vpMultiButtonModal'
, 'nbextensions/visualpython/src/common/component/vpMultiButtonModal_new'
], function($, vpCommon, vpConst, md, sb, vpAccordionBox, vpLineNumberTextArea, vpTableLayoutVerticalSimple, vpTableLayoutHorizontalSimple, vpMultiButtonModal
, vpMultiButtonModal_new) {
"use strict";
/**
* @class VpFuncJS
* @constructor
* @param {funcOptProp} props 기본 속성
* @param {String} uuid 고유 id
*/
var VpFuncJS = function(props, uuid) {
this.setOptionProp(props);
this.uuid = uuid;
this.generatedCode = "";
};
/**
@param {funcOptProp} props 기본 속성
*/
VpFuncJS.prototype.setOptionProp = function(props) {
this.funcName = props.funcName;
this.funcID = props.funcID;
}
/**
* Task Index 셋팅
* @param {number} idx task sequential index
*/
VpFuncJS.prototype.setTaskIndex = function(idx) {
this.taskIdx = idx;
}
/**
* Task Index 확인
* @returns {number} task sequential index
*/
VpFuncJS.prototype.getTaskIndex = function() {
return this.taskIdx;
}
/**
* 유효성 검사
* @param {*} args
* @returns {boolean} 유효성 체크
*/
VpFuncJS.prototype.optionValidation = function(args) {
console.log("[vpFuncJS.optionValidation] Not developed yet. Need override on child.");
return false;
}
/**
* Python 코드 실행 후 반환 값 전달해 콜백함수 호출
* @param {String} command 실행할 코드
* @param {function} callback 실행 완료 후 호출될 callback
* @param {boolean} isSilent 커널에 실행위한 신호 전달 여부 기본 false
* @param {boolean} isStoreHistory 커널에 히스토리 채우도록 신호 기본 !isSilent
* @param {boolean} isStopOnError 실행큐에 예외 발생시 중지 여부 기본 true
*/
VpFuncJS.prototype.kernelExecute = function(command, callback, isSilent = false, isStoreHistory = !isSilent, isStopOnError = true) {
Jupyter.notebook.kernel.execute(
command,
{
iopub: {
output: function(msg) {
var result = String(msg.content["text"]);
if (!result || result == 'undefined') {
if (msg.content.data) {
result = String(msg.content.data["text/plain"]);
}
}
callback(result);
}
}
},
{ silent: isSilent, store_history: isStoreHistory, stop_on_error: isStopOnError }
);
}
/**
* 셀에 소스 추가하고 실행.
* @param {String} command 실행할 코드
* @param {boolean} exec 실행여부
* @param {String} type 셀 타입
*/
VpFuncJS.prototype.cellExecute = function(command, exec, type = "code") {
// TODO: Validate 거칠것
this.generatedCode = command;
var targetCell = Jupyter.notebook.insert_cell_below(type);
// 코드타입인 경우 시그니쳐 추가.
if (type == "code") {
// command = vpCommon.formatString("{0}\n{1}", vpConst.PREFIX_CODE_SIGNATURE, command);
command = vpCommon.formatString("{0}", command);
}
targetCell.set_text(command);
Jupyter.notebook.select_next();
// this.metaSave(); 각 함수에서 호출하도록 변경.
if (exec) {
switch (type) {
case "markdown":
targetCell.render();
break;
case "code":
default:
targetCell.execute();
}
/**
* 추가 + 이진용 주임
* 2020 10 22 한글('코드가 실행되었습니다') -> 영어로 변경('Your code has been executed)
*/
vpCommon.renderSuccessMessage("Your code has been executed");
}
/** 추가 + 김민주 주임
* 2020 11 24 주피터 셀 실행(run)/추가(add) 후 선택된 셀로 이동
*/
Jupyter.notebook.scroll_to_cell(Jupyter.notebook.get_selected_index());
}
/**
* 선택자 범위 uuid 안으로 감싸기
* @param {String} selector 제한할 대상 선택자. 복수 매개 시 uuid 아래로 순서대로 제한됨
* @returns 감싸진 선택자
*/
VpFuncJS.prototype.wrapSelector = function(selector) {
var args = Array.prototype.slice.call(arguments);
args.unshift("." + this.uuid);
return vpCommon.wrapSelector.apply(this, args);
}
/**
* append css on option
* @param {String} url style sheet url
*/
VpFuncJS.prototype.loadCss = function(url) {
try {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = requirejs.toUrl(url);
document.getElementsByClassName(this.uuid)[0].appendChild(link);
} catch (err) {
console.log("[vp] Error occurred during load style sheet. Skip this time.");
console.warn(err.message);
}
}
/**
* 미리 생성된 코드 실행
*/
VpFuncJS.prototype.executeGenerated = function() {
if (this.generatedCode !== "")
this.cellExecute(this.generatedCode, true);
}
/** 추가 + 이진용 주임
* 파일 네비게이션에 이 코드를 사용
* @param {String} command 실행할 코드
* @param {function} callback 실행 완료 후 호출될 callback
* @param {boolean} isSilent 커널에 실행위한 신호 전달 여부 기본 false
* @param {boolean} isStoreHistory 커널에 히스토리 채우도록 신호 기본 !isSilent
* @param {boolean} isStopOnError 실행큐에 예외 발생시 중지 여부 기본 true
*/
VpFuncJS.prototype.kernelExecuteV2 = function(command, callback, isSilent = false, isStoreHistory = !isSilent, isStopOnError = true) {
Jupyter.notebook.kernel.execute(
command,
{
iopub: {
output: function(msg) {
var result = msg.content.data['text/plain']; // <- 이 부분을 개선한 kernelExecute 버전2 코드
callback(result);
}
}
},
{ silent: isSilent, store_history: isStoreHistory, stop_on_error: isStopOnError }
);
}
/**
* 메타데이터 핸들러 초기화
*/
VpFuncJS.prototype.initMetaHandler = function() {
if (this.mdHandler === undefined)
this.mdHandler = new md.MdHandler(this.funcID);
return this.mdHandler;
}
/**
* 메타데이터 생성
*/
VpFuncJS.prototype.metaGenerate = function() {
if (this.package === undefined) return;
var inputIdList = this.package.input.map(x => x.name);
// inputIdList = inputIdList.concat(this.package.output.map(x => x.name));
// inputIdList = inputIdList.concat(this.package.variable.map(x => x.name));
// FIXME: minju : not existing object mapping error fixed
if (this.package.output) inputIdList = inputIdList.concat(this.package.output.map(x => x.name));
if (this.package.variable) inputIdList = inputIdList.concat(this.package.variable.map(x => x.name));
// generate metadata
this.initMetaHandler();
this.metadata = this.mdHandler.generateMetadata(this, inputIdList);
}
/**
* 메타데이터 세이브
*/
VpFuncJS.prototype.metaSave = function() {
// generate metadata
this.metaGenerate();
// save metadata
if (this.package === undefined) return;
// 20210104 minju: 셀에 Metadata 저장하지 않기
// this.mdHandler.saveMetadata();
}
/**
* 메타데이터 로드
* @param {funcJS} option
* @param {JSON} meta
*/
VpFuncJS.prototype.loadMeta = function(funcJS, meta) {
this.initMetaHandler();
this.mdHandler.metadata = meta;
this.mdHandler.loadDirectMdAsTag(funcJS, meta);
// 로드 후 작업이 바인딩 되어있으면 처리
if (this.loadMetaExpend !== undefined && typeof this.loadMetaExpend == "function") {
this.loadMetaExpend(funcJS, meta);
}
}
/**
* Get Value of Metadata by option id
* @param {string} id
*/
VpFuncJS.prototype.getMetadata = function(id) {
if (this.metadata == undefined)
return "";
if (this.metadata.options) {
var len = this.metadata.options.length;
for (var i = 0; i < len; i++) {
var obj = this.metadata.options[i];
if (obj.id == id)
return obj.value;
}
}
return "";
}
/**
* 페이지 내용 삽입.
* @param {String} content 페이지 내용
* @param {number} pageIndex 페이지 인덱스
*/
VpFuncJS.prototype.setPage = function(content, pageIndex = 0) {
$(vpCommon.wrapSelector(vpCommon.formatString(".{0}.{1}:eq({2})", this.uuid, vpConst.API_OPTION_PAGE, pageIndex))).append(content);
}
/**
* prefix, postfix 입력 컨트롤 생성
* @param {String} caption 아코디언 박스 캡션
* @param {String} areaID textarea id
* @param {String} content textarea content
* @returns {String} tag string
*/
VpFuncJS.prototype.createManualCode = function(caption, areaID, content) {
var accBoxManualCode = new vpAccordionBox.vpAccordionBox(caption);
var lineNumberTextArea = new vpLineNumberTextArea.vpLineNumberTextArea(areaID, content);
accBoxManualCode.addClass(vpConst.ACCORDION_GRAY_COLOR);
accBoxManualCode.appendContent(lineNumberTextArea.toTagString());
return accBoxManualCode.toTagString();
}
/**
* prefix 입력 컨트롤 생성
* @param {String} content textarea content
* @returns {String} tag string
*/
VpFuncJS.prototype.createPrefixCode = function(content = "") {
return this.createManualCode(vpConst.API_OPTION_PREFIX_CAPTION, vpConst.API_OPTION_PREFIX_CODE_ID, content);
}
/**
* prefix 컨트롤 값 설정
* @param {String} content textarea content
*/
VpFuncJS.prototype.setPrefixCode = function(content) {
$(this.wrapSelector(vpCommon.formatString("#{0}", vpConst.API_OPTION_PREFIX_CODE_ID))).val(content);
}
/**
* prefix 컨트롤 값 조회
* @returns {String} textarea content
*/
VpFuncJS.prototype.getPrefixCode = function() {
return $(this.wrapSelector(vpCommon.formatString("#{0}", vpConst.API_OPTION_PREFIX_CODE_ID))).val();
}
/**
* postfix 입력 컨트롤 생성
* @param {String} content textarea content
* @returns {String} tag string
*/
VpFuncJS.prototype.createPostfixCode = function(content = "") {
return this.createManualCode(vpConst.API_OPTION_POSTFIX_CAPTION, vpConst.API_OPTION_POSTFIX_CODE_ID, content);
}
/**
* postfix 컨트롤 값 설정
* @param {String} content textarea content
*/
VpFuncJS.prototype.setPostfixCode = function(content) {
$(this.wrapSelector(vpCommon.formatString("#{0}", vpConst.API_OPTION_POSTFIX_CODE_ID))).val(content);
}
/**
* postfix 컨트롤 값 조회
* @returns {String} textarea content
*/
VpFuncJS.prototype.getPostfixCode = function() {
return $(this.wrapSelector(vpCommon.formatString("#{0}", vpConst.API_OPTION_POSTFIX_CODE_ID))).val();
}
/**
* 옵션 컨테이너 생성
* @param {String} caption 아코디언 박스 캡션
* @returns {vpAccordionBox} 아코디언 박스
*/
VpFuncJS.prototype.createOptionContainer = function(caption) {
var accBox = new vpAccordionBox.vpAccordionBox(caption);
return accBox;
}
/**
* 세로형 간단 테이블 레이아웃 생성
* @param {String} thWidth 테이블 헤더(좌측 셀) 넓이
*/
VpFuncJS.prototype.createVERSimpleLayout = function(thWidth) {
var tblLayout = new vpTableLayoutVerticalSimple.vpTableLayoutVerticalSimple();
tblLayout.setTHWidth(thWidth);
return tblLayout;
}
/**
* 가로형 간단 테이블 레이아웃 생성
* @param {Array} thWidth 테이블 셀별 넓이
*/
VpFuncJS.prototype.createHORIZSimpleLayout = function(thWidth) {
var tblLayout = new vpTableLayoutHorizontalSimple.vpTableLayoutHorizontalSimple();
// tblLayout.setTHWidth(thWidth);
return tblLayout;
}
/**
* 옵션별 이벤트 바인딩. (컨테이너 callback 에서 호출 함)
*/
VpFuncJS.prototype.bindOptionEvent = function() {
// var that = this;
// $(document).on(vpCommon.formatString("click.{0}", that.uuid), function(evt) {
// console.log("Test log from vp func. " + that.uuid);
// });
// $(document).on(vpCommon.formatString("dblclick.{0}", that.uuid), function(evt) {
// console.log("Test log from vp func dblclick. " + that.uuid);
// });
}
/**
* 옵션별 이벤트 언바인딩. (컨테이너에서 로드옵션 파기될때 호출 함).
*/
VpFuncJS.prototype.unbindOptionEvent = function() {
$(document).unbind(vpCommon.formatString(".{0}", this.uuid));
}
/**
* 모달 오픈
* @param {String} message 모달 메시지
* @param {Array} buttons 버튼 캡션
* @param {function} callback 선택 콜백 함수
*/
VpFuncJS.prototype.openMultiBtnModal = function(message = "", buttons = new Array(), callback) {
var mbmModal = new vpMultiButtonModal.vpMultiButtonModal();
mbmModal.setMessage(message);
mbmModal.setButtons(buttons);
mbmModal.openModal(callback);
}
/**
* 모달 오픈
* @param {String} message 모달 메시지
* @param {Array<string>} buttons 버튼 캡션
* @param {Array<function>} callback 선택 콜백 함수
*/
VpFuncJS.prototype.openMultiBtnModal_new = function(message = "", submessage, buttons = new Array(), callbackList) {
var mbmModal = new vpMultiButtonModal_new.vpMultiButtonModal(message, submessage, buttons);
mbmModal.openModal(callbackList);
}
return {'VpFuncJS': VpFuncJS};
});