`);
+ var basePathDomElement = $(`
/ `);
+ 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 = $(`
+ ${slashStr} ${pathToken}
+ `);
+
+ 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('
'
+ , 'vp_fileNavigationInput', 'New File Name', this.state.fileName);
+ page.appendFormatLine('
', 'vp_fileNavigationExt');
+ page.appendLine('All files(*.*) ');
+ if (this.state.extensions && this.state.extensions.length > 0) {
+ let selectedExt = this.selectedExt;
+ this.state.extensions.forEach(ext => {
+ page.appendFormatLine('*.{2} ', ext, (selectedExt === ext?'selected':''), ext);
+ });
+ }
+ page.appendLine(' ');
+ page.appendFormatLine('
{2} ', '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 file extension change event
+ $(this.wrapSelector('#vp_fileNavigationExt')).on('change', function() {
+ let ext = $(this).val();
+ that.selectedExt = ext;
+
+ that.renderFileList();
+ });
+ // 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();
+ if (selectedExt == undefined || selectedExt == null) {
+ selectedExt = '';
+ }
+ 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
+ //============================================================================
+ this.setSelectedFile(fileInput, pathInput);
+ // 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;
+ });
+
+ 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 && 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;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/HelpViewer.js b/visualpython/js/com/component/HelpViewer.js
new file mode 100644
index 00000000..84ccfe44
--- /dev/null
+++ b/visualpython/js/com/component/HelpViewer.js
@@ -0,0 +1,221 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : HelpViewer.js
+ * Author : Black Logic
+ * Note : Component > HelpViewer
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 07. 13
+ * Change Date :
+ */
+//============================================================================
+// [CLASS] HelpViewer
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/helpViewer.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/popupComponent'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/Component',
+ 'vp_base/js/com/component/LoadingSpinner'
+], function(hvHtml, ppCss, com_util, com_Const, com_String, Component, LoadingSpinner) {
+
+ /**
+ * HelpViewer
+ */
+ class HelpViewer extends Component {
+ constructor() {
+ super($(vpConfig.parentSelector), {}, {});
+ }
+
+ _init() {
+ this.position = {
+ right: 10, top: 120
+ };
+ this.size = {
+ width: 500,
+ height: 500
+ };
+ }
+
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ $(that.wrapSelector('.vp-popup-maximize')).on('click', function() {
+ // save position
+ that.position = $(that.wrapSelector()).position();
+ // save size
+ that.size = {
+ width: $(that.wrapSelector()).width(),
+ height: $(that.wrapSelector()).height()
+ }
+ // maximize popup
+ $(that.wrapSelector()).css({
+ width: '100%',
+ height: '100%',
+ top: 0,
+ left: 0
+ });
+ // show / hide buttons
+ $(this).hide();
+ $(that.wrapSelector('.vp-popup-return')).show();
+ });
+
+ // Return operation
+ $(this.wrapSelector('.vp-popup-return')).on('click', function(evt) {
+ // return size
+ $(that.wrapSelector()).css({
+ width: that.size.width + 'px',
+ height: that.size.height + 'px',
+ top: that.position.top,
+ left: that.position.left
+ });
+ // show / hide buttons
+ $(this).hide();
+ $(that.wrapSelector('.vp-popup-maximize')).show();
+ });
+
+ $(that.wrapSelector('.vp-popup-close')).on('click', function() {
+ that.remove();
+ });
+
+ $(that.wrapSelector('.vp-popup-button')).on('click', function() {
+ var btnType = $(this).data('type');
+ switch(btnType) {
+ case 'cancel':
+ that.remove();
+ break;
+ }
+ });
+
+ // Focus recognization
+ $(this.wrapSelector()).on('click', function() {
+ that.focus();
+ });
+ }
+
+ _bindDraggable() {
+ var that = this;
+ let containment = 'body';
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ containment = '#main';
+ }
+ $(this.wrapSelector()).draggable({
+ handle: '.vp-popup-title',
+ containment: containment,
+ start: function(evt, ui) {
+ // check focused
+ $(that.eventTarget).trigger({
+ type: 'focus_option_page',
+ component: that
+ });
+ }
+ });
+ }
+
+ _bindResizable() {
+ let that = this;
+ $(this.wrapSelector()).resizable({
+ handles: 'all',
+ start: function(evt, ui) {
+ // show / hide buttons
+ $(that.wrapSelector('.vp-popup-return')).hide();
+ $(that.wrapSelector('.vp-popup-maximize')).show();
+ }
+ });
+ }
+
+ template() {
+ this.$pageDom = $(hvHtml);
+
+ return this.$pageDom;
+ }
+
+ render() {
+ super.render();
+
+ // set detailed size
+ $(this.wrapSelector()).css({
+ width: this.size.width + 'px',
+ height: this.size.height + 'px'
+ });
+
+ // position
+ $(this.wrapSelector()).css({ top: this.position.top, right: this.position.right });
+
+ this._bindDraggable();
+ this._bindResizable();
+ }
+
+ wrapSelector(selector='') {
+ var sbSelector = new com_String();
+ var cnt = arguments.length;
+ if (cnt < 2) {
+ // if there's no more arguments
+ sbSelector.appendFormat(".vp-popup-frame.{0} {1}", this.uuid, selector);
+ } else {
+ // if there's more arguments
+ sbSelector.appendFormat(".vp-popup-frame.{0}", this.uuid);
+ for (var idx = 0; idx < cnt; idx++) {
+ sbSelector.appendFormat(" {0}", arguments[idx]);
+ }
+ }
+ return sbSelector.toString();
+ }
+
+ open(content, useHelp=true, importCode='') {
+ this.show();
+
+ let that = this;
+
+ let code = content;
+ if (useHelp === true) {
+ if (importCode !== '') {
+ code = importCode + '\n' + `print(help(${content}))`;
+ } else {
+ code = `print(help(${content}))`;
+ }
+ }
+
+ let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.vp-popup-body')));
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result } = resultObj;
+
+ $(that.wrapSelector('#helpContent')).text(result);
+
+ }).catch(function(err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+
+ this.focus();
+ }
+
+ generateCode() {
+ return '';
+ }
+
+ show() {
+ $(this.wrapSelector()).show();
+ }
+
+ remove() {
+ $(this.wrapSelector()).remove();
+ }
+
+ focus() {
+ $('.vp-popup-frame').removeClass('vp-focused');
+ $('.vp-popup-frame').css({ 'z-index': 1200 });
+ $(this.wrapSelector()).addClass('vp-focused');
+ $(this.wrapSelector()).css({ 'z-index': 1205 }); // move forward
+ }
+
+ }
+
+ return HelpViewer;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/InfoModal.js b/visualpython/js/com/component/InfoModal.js
new file mode 100644
index 00000000..e8901263
--- /dev/null
+++ b/visualpython/js/com/component/InfoModal.js
@@ -0,0 +1,56 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : InfoModal.js
+ * Author : Black Logic
+ * Note : InfoModal
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] InfoModal
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/infoModal.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/infoModal'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/component/Component'
+], function(msgHtml, msgCss, com_Const, Component) {
+
+ /**
+ * InfoModal
+ */
+ class InfoModal extends Component {
+ constructor(title) {
+ super($('body'), { title: title });
+ }
+
+ _bindEvent() {
+ let that = this;
+ // click ok button
+ $(this.wrapSelector('.vp-infoModal-yes')).click( function() {
+ that.remove();
+ });
+ }
+
+ template() {
+ return msgHtml.replaceAll('${vp_base}', com_Const.BASE_PATH);
+ }
+
+ render() {
+ super.render();
+
+ // set title
+ $(this.wrapSelector('.vp-infoModal-titleStr')).text(this.state.title);
+ }
+
+ remove() {
+ $(this.wrapSelector()).remove();
+ }
+
+ }
+
+ return InfoModal;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/InnerFuncViewer.js b/visualpython/js/com/component/InnerFuncViewer.js
new file mode 100644
index 00000000..e9f14649
--- /dev/null
+++ b/visualpython/js/com/component/InnerFuncViewer.js
@@ -0,0 +1,211 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : InnerFuncViewer.js
+ * Author : Black Logic
+ * Note : Component > InnerFuncViewer
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 06. 14
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] InnerFuncViewer
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/innerFuncViewer.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/innerFuncViewer'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation'
+], function(ifHtml, ifCss, com_util, com_Const, com_String, PopupComponent, FileNavigation) {
+
+ /**
+ * InnerFuncViewer
+ */
+ class InnerFuncViewer extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.name = 'Inner Function Viewer';
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.sizeLevel = 3;
+
+ this.state = {
+ vp_userCode: '',
+ ...this.state
+ }
+
+ this.codemirrorList = {};
+ this.importedList = [];
+ this.title_no = 0;
+
+ // double click setter
+ this.clicked = 0;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // search item
+ $(this.wrapSelector('.vp-if-search')).on('change', function(evt) {
+ var value = $(this).val();
+ if (value != '') {
+ $(that.wrapSelector('.vp-if-item')).hide();
+ $(that.wrapSelector('.vp-if-item')).filter(function() {
+ return $(this).data('title').search(value) >= 0;
+ }).show();
+ } else {
+ $(that.wrapSelector('.vp-if-item')).show();
+ }
+ });
+ }
+
+ bindSnippetItem() {
+ let that = this;
+ // item header click (toggle item)
+ $(this.wrapSelector('.vp-if-item-header')).off('click');
+ $(this.wrapSelector('.vp-if-item-header')).on('click', function(evt) {
+ // select item
+ // remove selection
+ $(that.wrapSelector('.vp-if-item-header')).removeClass('selected');
+ // select item
+ $(this).addClass('selected');
+
+ // toggle item
+ var parent = $(this).parent();
+ var indicator = $(parent).find('.vp-if-indicator');
+ var hasOpen = $(indicator).hasClass('open');
+
+ if (!hasOpen) {
+ // show code
+ $(indicator).addClass('open');
+ $(parent).find('.vp-if-item-code').show();
+ } else {
+ // hide code
+ $(indicator).removeClass('open');
+ $(parent).find('.vp-if-item-code').hide();
+ }
+ evt.stopPropagation();
+ });
+
+ // item menu click
+ $(this.wrapSelector('.vp-if-item-menu-item')).off('click');
+ $(this.wrapSelector('.vp-if-item-menu-item')).on('click', function(evt) {
+ var menu = $(this).data('menu');
+ var item = $(this).closest('.vp-if-item');
+ var title = $(item).data('title');
+ if (menu == 'run') {
+ // get codemirror
+ let cmCode = that.codemirrorList[title];
+ cmCode.save();
+ var code = cmCode.getValue();
+ // create block and run it
+ $('#vp_wrapper').trigger({
+ type: 'create_option_page',
+ blockType: 'block',
+ menuId: 'lgExe_code',
+ menuState: { taskState: { code: code } },
+ afterAction: 'run'
+ });
+ }
+ evt.stopPropagation();
+ });
+ }
+
+ bindCodeMirror(title, selector) {
+ let cmCode = this.initCodemirror({
+ key: title,
+ selector: selector,
+ type: 'readonly',
+ events: [{
+ key: 'change',
+ callback: function(evt, chgObj) {
+ if (chgObj.removed.join('') != '' || chgObj.text.join('') != '') {
+ // enable save button
+ $(selector).parent().find('.vp-if-save').removeClass('vp-disable');
+ }
+ }
+ }]
+ });
+ this.codemirrorList[title] = cmCode;
+ }
+
+ templateForBody() {
+ return ifHtml;
+ }
+
+ render() {
+ super.render();
+
+ // load udf list
+ this.loadUserCommandList();
+ }
+
+ renderSnippetItem(title, code, description) {
+ var item = new com_String();
+ item.appendFormatLine('
', 'vp-if-item', title, title);
+ item.appendFormatLine('
', 'vp-if-item-header', description);
+ item.appendFormatLine('
', 'vp-if-indicator');
+ item.appendFormatLine('
', 'vp-if-item-title', title);
+ item.appendFormatLine('
', 'vp-if-item-menu');
+ // LAB: img to url
+ // item.appendFormatLine('
'
+ item.appendFormatLine('
'
+ , 'vp-if-item-menu-item', 'run', 'Run');
+ // item.appendFormatLine('
', com_Const.IMAGE_PATH + 'snippets/run.svg');
+ item.appendLine('
');
+ item.appendLine('
'); // end of vp-if-item-menu
+ item.appendLine('
'); // end of vp-if-item-header
+ item.appendFormatLine('
', 'vp-if-item-code');
+ item.appendFormatLine('', code);
+ item.appendLine('
'); // end of vp-if-item-code
+ item.appendLine('
'); // end of vp-if-item
+ return item.toString();
+ }
+
+ generateCode() {
+ return '';
+ }
+
+ loadUserCommandList() {
+ var that = this;
+
+ let funcDict = vpConfig.getModuleCode();
+ funcDict = Object.fromEntries(Object.entries(funcDict).filter(([key]) => funcDict[key].type == 'function'));
+
+ // clear table except head
+ $(this.wrapSelector('.vp-if-table')).html('');
+
+ // load code list
+ var innerFuncCode = new com_String();
+ Object.keys(funcDict).forEach(key => {
+ let obj = funcDict[key];
+ if (obj.code != null && obj.code != undefined) {
+ var item = that.renderSnippetItem(key, obj.code, obj.description);
+ innerFuncCode.append(item);
+ }
+ });
+ $(that.wrapSelector('.vp-if-table')).html(innerFuncCode.toString());
+
+ // bind snippet item
+ that.bindSnippetItem();
+
+ // load codemirror
+ var codeList = $(that.wrapSelector('.vp-if-item-code textarea'));
+ codeList.each((idx, tag) => {
+ var title = $(tag).closest('.vp-if-item').data('title');
+ that.bindCodeMirror(title, tag);
+ });
+ }
+
+ }
+
+ return InnerFuncViewer;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/InstanceEditor.js b/visualpython/js/com/component/InstanceEditor.js
new file mode 100644
index 00000000..c3a030c0
--- /dev/null
+++ b/visualpython/js/com/component/InstanceEditor.js
@@ -0,0 +1,562 @@
+define([
+ __VP_CSS_LOADER__('vp_base/css/component/instanceEditor'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/data/m_library/instanceLibrary',
+ 'vp_base/js/com/component/LibraryComponent'
+], function(insCss, com_Const, com_String, com_util, SuggestInput, instanceLibrary, LibraryComponent) {
+
+
+ // temporary const
+ const VP_INS_BOX = 'vp-ins-box';
+ const VP_INS_SELECT_CONTAINER = 'vp-ins-select-container';
+ const VP_INS_SELECT_TITLE = 'vp-ins-select-title';
+ const VP_INS_SEARCH = 'vp-ins-search';
+ const VP_INS_TYPE = 'vp-ins-type';
+ const VP_INS_SELECT_BOX = 'vp-ins-select-box';
+ const VP_INS_SELECT_LIST = 'vp-ins-select-list';
+ const VP_INS_SELECT_ITEM = 'vp-ins-select-item';
+
+ const VP_INS_PARAMETER_BOX = 'vp-ins-parameter-box';
+ const VP_INS_PARAMETER = 'vp-ins-parameter';
+
+ const VP_CREATE_VAR_BOX = 'vp-create-var-box';
+ const VP_CREATE_VAR = 'vp-create-var';
+ const VP_CREATE_VAR_BTN = 'vp-create-var-btn';
+
+ // function/method types
+ var _METHOD_TYPES = ['function', 'method', 'type', 'builtin_function_or_method', 'PlotAccessor'];
+
+ /**
+ * @class InstanceEditor
+ * @param {object} pageThis
+ * @param {string} targetId
+ * @param {boolean} popup
+ * @constructor
+ */
+ class InstanceEditor {
+ constructor(pageThis, targetId, containerId = 'vp_wrapper', config = {}) {
+ this.pageThis = pageThis;
+ this.targetId = targetId;
+ this.uuid = 'u' + com_util.getUUID();
+ this.containerId = containerId;
+ this.config = {
+ popup: false,
+ showAlert: false, // show alert by modal or not
+ targetType: 'instance', // instance / outside
+ ...config
+ }
+
+ this.state = {
+ code: '',
+ type: '',
+ list: [],
+ };
+
+ this.isFirstPage = false;
+ this.dataTypeInfo = [
+ { label: 'DataFrame', type: 'DataFrame', assign: ' = pd.DataFrame()' },
+ { label: 'Series', type: 'Series', assign: ' = pd.Series()' },
+ { label: 'Dict', type: 'dict', assign: ' = {}' },
+ { label: 'List', type: 'list', assign: ' = []' },
+ { label: 'Integer', type: 'int', assign: ' = 0' },
+ { label: 'Others', type: '' }
+ ];
+ this.dataTypeList = ['DataFrame', 'Series', 'dict', 'list', 'int'];
+
+ this.bindEvent();
+ this.init();
+
+ }
+ getVarType() {
+ return this.state.type;
+ }
+ getVarList() {
+ return this.state.list;
+ }
+ init() {
+ this.reload();
+ }
+ wrapSelector(selector = '') {
+ return com_util.formatString('.{0} {1}', this.uuid, selector);
+ }
+ renderFirstPage() {
+ var tag = new com_String();
+ tag.appendFormatLine('
', VP_INS_BOX, this.uuid); // vp-select-base
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'datatype');
+ tag.appendFormatLine('
Data Type
', VP_INS_SELECT_TITLE);
+ tag.appendFormatLine('
', VP_INS_TYPE, 'datatype');
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'datatype');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'datatype');
+ this.dataTypeInfo.forEach((obj, idx) => {
+ tag.appendFormatLine('{4} ',
+ VP_INS_SELECT_ITEM + (idx == 0 ? ' selected' : ''), obj.label, obj.type, obj.assign, obj.label);
+ });
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'variable');
+ tag.appendFormatLine('
Variable
', VP_INS_SELECT_TITLE);
+ tag.appendFormatLine('
', VP_INS_TYPE, 'variable');
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'variable');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'variable');
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+
+
+ // create variable input
+ tag.appendFormatLine('
', VP_CREATE_VAR_BOX);
+ tag.appendFormatLine('
', VP_CREATE_VAR);
+ // tag.appendFormatLine('
', VP_CREATE_VAR_BTN, com_Const.IMAGE_PATH + 'plus.svg');
+ tag.appendFormatLine('
', VP_CREATE_VAR_BTN);
+ tag.appendLine('
');
+
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendLine('
'); // VP_INS_BOX END
+
+
+
+ // TODO: if this.popup == true
+ $(this.pageThis.wrapSelector('#' + this.containerId)).html(tag.toString());
+
+ return tag.toString();
+ }
+ renderVarList(varType, varList) {
+ var varListTag = new com_String();
+ varList != undefined && varList.forEach(obj => {
+ if ((varType == '' && !this.dataTypeList.includes(obj.type))
+ || obj.type == varType) {
+ varListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, obj.name, obj.type, obj.type, obj.name);
+ }
+ });
+ $(this.wrapSelector('.' + VP_INS_SELECT_LIST + '.variable')).html(varListTag.toString());
+ }
+ renderPage(replace = true) {
+ var tag = new com_String();
+ tag.appendFormatLine('
', VP_INS_BOX, this.uuid); // vp-select-base
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'attr');
+ tag.appendFormatLine('
Attribute
', VP_INS_SELECT_TITLE);
+
+ tag.appendFormatLine('
', 'position: relative;');
+ tag.appendFormatLine(' ', VP_INS_SEARCH, 'attr');
+ tag.appendFormatLine(' ', VP_INS_TYPE, 'attr');
+ tag.appendLine('
');
+
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'attr');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'attr');
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'method');
+ tag.appendFormatLine('
Method
', VP_INS_SELECT_TITLE);
+
+ tag.appendFormatLine('
', 'position: relative;');
+ tag.appendFormatLine(' ', VP_INS_SEARCH, 'method');
+ tag.appendFormatLine(' ', VP_INS_TYPE, 'method');
+ tag.appendLine('
');
+
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'method');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'method');
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendFormatLine('
', VP_INS_PARAMETER_BOX);
+ tag.appendFormatLine(' ',
+ VP_INS_PARAMETER, 'input parameter');
+ tag.appendFormatLine('Option ', 'vp-ins-opt-button');
+ tag.appendLine('
'); // VP_INS_PARAMETER
+
+ tag.appendLine('
'); // VP_INS_BOX END
+
+
+
+ // TODO: if this.popup == true
+ $(this.pageThis.wrapSelector('#' + this.containerId)).html(tag.toString());
+
+ return tag.toString();
+ }
+ bindEvent() {
+ var that = this;
+
+ // select datatype
+ $(document).on('click', this.wrapSelector('.' + VP_INS_SELECT_LIST + '.datatype .' + VP_INS_SELECT_ITEM), function (event) {
+ var varType = $(this).attr('data-var-type');
+ $(that.wrapSelector('.' + VP_INS_SELECT_LIST + '.datatype .' + VP_INS_SELECT_ITEM)).removeClass('selected');
+ $(this).addClass('selected');
+
+ // if others selected, cannot create variable
+ if (varType == '') {
+ $(that.wrapSelector('.' + VP_CREATE_VAR_BOX)).hide();
+ } else {
+ $(that.wrapSelector('.' + VP_CREATE_VAR_BOX)).show();
+ }
+
+ that.reload();
+ });
+
+ // select variable
+ $(document).on('click', this.wrapSelector('.' + VP_INS_SELECT_LIST + '.variable .' + VP_INS_SELECT_ITEM), function (event) {
+ var varName = $(this).attr('data-var-name');
+ var varType = $(this).attr('data-var-type');
+
+ // console.log('clicked', varName, varType, that.state);
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_selected",
+ varName: varName,
+ varType: varType,
+ isMethod: false
+ });
+ });
+
+ // create variable
+ $(document).on('click', this.wrapSelector('.' + VP_CREATE_VAR_BTN), function (event) {
+ var varName = $(that.wrapSelector('.' + VP_CREATE_VAR)).val();
+ var selectedType = $(that.wrapSelector('.' + VP_INS_SELECT_LIST + '.datatype .' + VP_INS_SELECT_ITEM + '.selected'));
+ var varType = selectedType.attr('data-var-type');
+ var assignCode = selectedType.attr('data-var-assign');
+
+ if (varName == '') {
+ ; // no variable name entered
+ } else {
+ var code = com_util.formatString('{0}{1}\n{2}', varName, assignCode, 'type(' + varName + ').__name__');
+ vpKernel.execute(code).then(function (resultObj) {
+ let { result } = resultObj;
+ if (result.includes(varType)) {
+ com_util.renderSuccessMessage('Variable Created!');
+ that.reload();
+ }
+ $(that.wrapSelector('.' + VP_CREATE_VAR)).val('');
+ });
+ }
+ });
+
+ // select attribute
+ $(document).on('click', this.wrapSelector('.' + VP_INS_SELECT_LIST + '.attr .' + VP_INS_SELECT_ITEM), function (event) {
+ var varName = $(this).attr('data-var-name');
+ var varType = $(this).attr('data-var-type');
+
+ // console.log('clicked', varName, varType, that.state);
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_selected",
+ varName: varName,
+ varType: varType,
+ isMethod: false
+ });
+ });
+
+ // select method
+ $(document).on('click', this.wrapSelector('.' + VP_INS_SELECT_LIST + '.method .' + VP_INS_SELECT_ITEM), function (event) {
+ var varName = $(this).attr('data-var-name');
+ var varType = $(this).attr('data-var-type');
+ // console.log('clicked', varName, varType, that.state);
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_selected",
+ varName: varName,
+ varType: varType,
+ isMethod: true
+ });
+ });
+
+ // parameter input
+ $(document).on('change', this.wrapSelector('.' + VP_INS_PARAMETER), function (event) {
+ var parameter = $(this).val();
+ var variable = $(that.pageThis.wrapSelector('#' + that.targetId)).val();
+ var splitList = variable.split('.');
+ if (splitList && splitList.length > 0) {
+ var lastSplit = splitList[splitList.length - 1];
+ var matchList = lastSplit.match(/\(.*?\)$/gi);
+ if (matchList && matchList.length > 0) {
+ var lastBracket = matchList[matchList.length - 1];
+ splitList[splitList.length - 1] = lastSplit.replace(lastBracket, com_util.formatString('({0})', parameter));
+ var newCode = splitList.join('.');
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_replaced",
+ originCode: variable,
+ newCode: newCode
+ });
+ }
+ }
+ });
+
+ // open option popup
+ $(document).on('click', this.wrapSelector('.vp-ins-opt-button:not(.disabled)'), function(event) {
+ if (that.optionPopup) {
+ that.optionPopup.open();
+ }
+ });
+ }
+ reload(callback = undefined) {
+ var that = this;
+ var variable = $(this.pageThis.wrapSelector('#' + this.targetId)).val();
+ if (variable == null) {
+ this.isFirstPage = false;
+ this.renderPage();
+ return;
+ }
+ this.state.code = variable;
+ var prevVarType = that.state.type;
+
+ if (variable == '') {
+ if (!this.isFirstPage) {
+ // if it's outside mode
+ if (this.config.targetType === 'outside') {
+ this.isFirstPage = false;
+ this.renderPage();
+ return;
+ } else {
+ this.renderFirstPage();
+ this.isFirstPage = true;
+ }
+ }
+ } else {
+ this.isFirstPage = false;
+ this.renderPage();
+ }
+ var splitList = [];
+ if (variable != '') {
+ splitList = variable.split('.');
+ }
+ var hasOption = false;
+ // get parameter
+ if (splitList && splitList.length > 0) {
+ var lastSplit = splitList[splitList.length - 1];
+ // get target code
+ var methodMatch = lastSplit.match(/[a-zA-Z_]+/i);
+ if (methodMatch) {
+ var methodName = methodMatch[0];
+ var targetCode = splitList.slice(0, splitList.length - 1).join('.');
+ if ((prevVarType in instanceLibrary.INSTANCE_MATCHING_LIBRARY) && (methodName in instanceLibrary.INSTANCE_MATCHING_LIBRARY[prevVarType])) {
+ // get target library
+ var targetLib = instanceLibrary.INSTANCE_MATCHING_LIBRARY[prevVarType][methodName];
+ var targetId = targetLib.target;
+ var popupState = {
+ config: {
+ name: methodName, category: 'Instance',
+ id: targetLib.id,
+ saveOnly: true,
+ noOutput: true
+ }
+ }
+ // add targetid as state if exists
+ if (targetId) {
+ popupState[targetId] = targetCode;
+ that.state[targetId] = targetCode;
+ }
+ if (that.optionPopup) {
+ that.optionPopup.remove();
+ that.optionPopup = null;
+ }
+ that.optionPopup = new LibraryComponent(popupState,
+ {
+ pageThis: that,
+ targetSelector: that.pageThis.wrapSelector('#' + that.targetId),
+
+ finish: function(code) {
+ // set parameter
+ let lastSplit = code?.split('.')?.pop();
+ // if bracket is at the end of code
+ let matchList = lastSplit.match(/\(.*?\)$/gi);
+ if (matchList != null && matchList.length > 0) {
+ let lastBracket = matchList[matchList.length - 1];
+ // remove first/last brackets
+ let parameter = lastBracket.substr(1, lastBracket.length - 2);
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).val(parameter);
+ }
+
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_replaced",
+ originCode: that.state.code,
+ newCode: code
+ });
+ }
+ }
+ );
+ hasOption = true;
+ } else {
+ that.optionPopup = null;
+ }
+ }
+
+
+ if (hasOption) {
+ if ($(that.wrapSelector('.vp-ins-opt-button')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-ins-opt-button')).removeClass('disabled');
+ }
+ } else {
+ if (!$(that.wrapSelector('.vp-ins-opt-button')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-ins-opt-button')).addClass('disabled');
+ }
+ }
+ } else {
+ if (!$(that.wrapSelector('.vp-ins-opt-button')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-ins-opt-button')).addClass('disabled');
+ }
+ }
+
+ var code = com_util.formatString('_vp_print(_vp_load_instance("{0}"))', variable);
+ vpKernel.execute(code).then(function (resultObj) {
+ let { result } = resultObj;
+ var varObj = {
+ type: 'None',
+ list: []
+ };
+ try {
+ varObj = JSON.parse(result);
+ } catch {
+ ; // command error
+ }
+
+ var varType = varObj.type;
+ var varList = varObj.list;
+ if (varType == 'module') {
+ // get module name
+ varType = varObj.name;
+ }
+
+ that.state.type = varType;
+ that.state.list = varList;
+
+ // set variable type
+ // $(that.wrapSelector('#vp_instanceType')).text(varType);
+ // set dir list
+ if (that.isFirstPage) {
+ varType = $(that.wrapSelector('.' + VP_INS_SELECT_LIST + '.datatype .' + VP_INS_SELECT_ITEM + '.selected')).attr('data-var-type');
+ that.renderVarList(varType, varList);
+ } else {
+ var attrListTag = new com_String();
+ var methodListTag = new com_String();
+ var attrList = [];
+ var methodList = [];
+ varList != undefined && varList.forEach(obj => {
+ if (obj.type.includes('Indexer')) {
+ methodListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, obj.name + '[]', obj.type, obj.type, obj.name);
+ methodList.push({
+ label: obj.name + '[]' + ' (' + obj.type + ')',
+ value: obj.name + '[]',
+ type: obj.type
+ });
+ }
+
+ // Method/Function... -> Method
+ else if (_METHOD_TYPES.includes(obj.type)) {
+ methodListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, obj.name + '()', obj.type, obj.type, obj.name);
+ methodList.push({
+ label: obj.name + '()' + ' (' + obj.type + ')',
+ value: obj.name + '()',
+ type: obj.type
+ });
+ } else {
+ attrListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, obj.name, obj.type, obj.type, obj.name);
+ attrList.push({
+ label: obj.name + ' (' + obj.type + ')',
+ value: obj.name,
+ type: obj.type
+ });
+ }
+ });
+ $(that.wrapSelector('.' + VP_INS_SELECT_LIST + '.attr')).html(attrListTag.toString());
+ $(that.wrapSelector('.' + VP_INS_SELECT_LIST + '.method')).html(methodListTag.toString());
+
+ // attribute search suggest
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input attr');
+ suggestInput.addClass(VP_INS_SEARCH);
+ suggestInput.setPlaceholder("Search Attribute");
+ suggestInput.setSuggestList(function () { return attrList; });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.' + VP_INS_TYPE + '.attr')).val(item.type);
+
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_selected",
+ varName: value,
+ varType: item.type,
+ isMethod: false
+ });
+ });
+ $(that.wrapSelector('.' + VP_INS_SEARCH + '.attr')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // method search suggest
+ suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input method');
+ suggestInput.addClass(VP_INS_SEARCH);
+ suggestInput.setPlaceholder("Search Method");
+ suggestInput.setSuggestList(function () { return methodList; });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.' + VP_INS_TYPE + '.method')).val(item.type);
+
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "instance_editor_selected",
+ varName: value,
+ varType: item.type,
+ isMethod: true
+ });
+ });
+ $(that.wrapSelector('.' + VP_INS_SEARCH + '.method')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // get parameter
+ if (splitList && splitList.length > 0) {
+ var lastSplit = splitList[splitList.length - 1];
+
+ // if bracket is at the end of code
+ var matchList = lastSplit.match(/\(.*?\)$/gi);
+ if (matchList != null && matchList.length > 0) {
+ var lastBracket = matchList[matchList.length - 1];
+ // remove first/last brackets
+ var parameter = lastBracket.substr(1, lastBracket.length - 2);
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).val(parameter);
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).val('');
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).prop('disabled', true);
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_INS_PARAMETER)).prop('disabled', true);
+ }
+ }
+
+ // callback
+ if (callback) {
+ callback(varObj);
+ }
+ }).catch(function(resultObj) {
+ let { result } = resultObj;
+ // show alert if this is visible
+ if (that.pageThis.isHidden() == false && that.config.showAlert == true) {
+ com_util.renderAlertModal(result.ename + ': ' + result.evalue);
+ }
+ // callback
+ if (callback) {
+ callback({});
+ }
+ });
+
+ }
+ show() {
+ $(this.wrapSelector()).show();
+ this.reload();
+ }
+ hide() {
+ $(this.wrapSelector()).hide();
+ }
+ }
+
+ return InstanceEditor;
+})
\ No newline at end of file
diff --git a/visualpython/js/com/component/LibraryComponent.js b/visualpython/js/com/component/LibraryComponent.js
new file mode 100644
index 00000000..e02c31f2
--- /dev/null
+++ b/visualpython/js/com/component/LibraryComponent.js
@@ -0,0 +1,206 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : LibraryComponent.js
+ * Author : Black Logic
+ * Note : Library Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] LibraryComponent
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_library/libraryComponent.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_library/libraryComponent'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_library/pandasLibrary'
+], function(libHtml, libCss, PopupComponent, com_Const, com_generatorV2, pandasLibrary) {
+
+ /**
+ * LibraryComponent
+ */
+ class LibraryComponent extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+ this.config.helpview = true;
+
+ this.packageId = this.id;
+ // deep copy package info
+ this.package = null;
+ try {
+ let findPackage = pandasLibrary.PANDAS_FUNCTION[this.packageId];
+ if (findPackage) {
+ this.package = JSON.parse(JSON.stringify(findPackage)); // deep copy of package
+ } else {
+ throw 'Cannot find package';
+ }
+ } catch(err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Cannot find package id from library: ' + this.packageId);
+ return;
+ }
+ this.config.checkModules = ['pd'];
+
+ // set docs link
+ if (this.package.docs === undefined) {
+ let docsLink = 'https://pandas.pydata.org/docs/reference/api/pandas.';
+ let docsMatchObj = this.package.code.match(/\= (.+)\.(.+)\(/);
+ if (docsMatchObj) {
+ let targetType = docsMatchObj[1]; // ${i0} or pd
+ let method = docsMatchObj[2];
+ if (targetType === 'pd') {
+ docsLink += method + '.html';
+ } else {
+ docsLink += 'DataFrame.' + method + '.html';
+ }
+ this.config.docs = docsLink;
+ } else {
+ this.config.docs = 'https://pandas.pydata.org/docs/reference/index.html';
+ }
+ } else {
+ this.config.docs = this.package.docs;
+ }
+
+ // set helpview content
+ let helpMatchObj = this.package.code.match(/\= (.+)\.(.+)\(/);
+ if (helpMatchObj) {
+ let helpContent = '';
+ let targetType = helpMatchObj[1]; // ${i0} or pd
+ let method = helpMatchObj[2];
+ if (targetType === 'pd') {
+ helpContent += '_vp_pd.' + method;
+ } else {
+ helpContent += '_vp_pd.' + 'DataFrame.' + method;
+ }
+ this.config.helpInfo.content = helpContent;
+ } else {
+ this.config.helpview = false;
+ }
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'loading state', this.state);
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // save change of vp-state component
+ $(this.wrapSelector('.vp-state')).on('change', function() {
+ let id = $(this)[0].id;
+ let val = $(this).val();
+ that.state[id] = val;
+ });
+ }
+
+ loadState() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, this.state);
+
+ let that = this;
+ Object.keys(this.state).forEach(key => {
+ if (key !== 'config') {
+ let tag = $(that.wrapSelector('#' + key));
+ let tagName = $(tag).prop('tagName');
+ let savedValue = that.state[key];
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(savedValue);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', savedValue);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(savedValue);
+ break;
+ }
+ }
+ });
+ }
+
+ saveState() {
+ let that = this;
+ $(this.wrapSelector('.vp-state')).each((idx, tag) => {
+ let id = tag.id;
+ let tagName = $(tag).prop('tagName');
+ let newValue = '';
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ newValue = $(tag).val();
+ break;
+ }
+ if (inputType == 'checkbox') {
+ newValue = $(tag).prop('checked');
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ newValue = $(tag).val();
+ break;
+ }
+
+ that.state[id] = newValue;
+ });
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'savedState', that.state);
+ }
+
+ templateForBody() {
+ return libHtml.replaceAll('${vp_base}', com_Const.BASE_PATH);
+ }
+
+ render() {
+ super.render();
+
+ // show interface
+ // com_generator.vp_showInterfaceOnPage(this.wrapSelector(), this.package);
+ if (this.config.noOutput && this.config.noOutput === true) {
+ // no allocateTo
+ this.package.options = this.package.options.filter(x => x.output != true);
+ }
+ com_generatorV2.vp_showInterfaceOnPage(this, this.package, this.state);
+
+ // hide required page if no options
+ if ($.trim($(this.wrapSelector('#vp_inputOutputBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-require-box')).hide();
+ }
+
+ // hide optional page if no options
+ if ($.trim($(this.wrapSelector('#vp_optionBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-option-box')).hide();
+ }
+ }
+
+ open() {
+ super.open();
+ // hide optional page if no options
+ if ($.trim($(this.wrapSelector('#vp_optionBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-option-box')).hide();
+ }
+ }
+
+ generateCode() {
+ // return com_generator.vp_codeGenerator(this.uuid, this.package);
+ let code = com_generatorV2.vp_codeGenerator(this, this.package, this.state);
+ return code;
+ }
+
+ }
+
+ return LibraryComponent;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/LoadingSpinner.js b/visualpython/js/com/component/LoadingSpinner.js
new file mode 100644
index 00000000..77626542
--- /dev/null
+++ b/visualpython/js/com/component/LoadingSpinner.js
@@ -0,0 +1,46 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : LoadingSpinner.js
+ * Author : Black Logic
+ * Note : LoadingSpinner
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 08. 26
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] LoadingSpinner
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/component/loadingSpinner'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/component/Component'
+], function(msgCss, Component) {
+
+ /**
+ * LoadingSpinner
+ * Usage:
+ * let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.container')));
+ * loadingSpinner.remove();
+ */
+ class LoadingSpinner extends Component {
+ constructor(targetTag) {
+ super($(targetTag));
+ }
+
+ template() {
+ return '
';
+ }
+
+ render() {
+ super.render();
+ }
+
+ remove() {
+ $(this.wrapSelector()).remove();
+ }
+
+ }
+
+ return LoadingSpinner;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/Modal.js b/visualpython/js/com/component/Modal.js
new file mode 100644
index 00000000..99fd5049
--- /dev/null
+++ b/visualpython/js/com/component/Modal.js
@@ -0,0 +1,159 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Modal.js
+ * Author : Black Logic
+ * Note : Modal
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Modal
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/component/modal'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/Component',
+ 'vp_base/js/com/com_util'
+], function(modalCss, com_String, Component, com_util) {
+
+ /**
+ * Modal
+ */
+ class Modal extends Component {
+ /**
+ *
+ * @param {Object} state {title, message, buttons, defaultButtonIdx, finish}
+ * - title : string / modal title
+ * - message : string / modal message
+ * - buttons : list / at least 1 button needed
+ * [optional]
+ * - defaultButtonIdx : int (default: 1)
+ * - finish : callback function when modal button clicked (result:button idx 0~n)
+ * - buttonClass : list / same length as buttons, define classes for buttons
+ */
+ constructor(state) {
+ super($('body'), state);
+ }
+ _init() {
+ super._init();
+ this.state = {
+ title: '',
+ message: '',
+ buttons: [],
+ defaultButtonIdx: 1,
+ finish: function(modalIdx) {
+ /* Implementation needed */
+ },
+ buttonClass: [],
+ ...this.state
+ }
+ /** Write codes executed before rendering */
+ if (this.state.buttons.length == 0) {
+ this.state.buttons.push("OK");
+ }
+ }
+
+ _bindEvent() {
+ /** Implement binding events */
+ let that = this;
+ // button click event
+ $(this.wrapSelector('.vp-modal-button')).on('click', function () {
+ if (typeof that.state.finish == "function") {
+ let modalIdx = parseInt($(this).data('idx'));
+ that.state.finish(modalIdx);
+ }
+ that.close();
+ });
+
+ // esc key to close, enter key to select
+ $(document).bind(com_util.formatString('keydown.{0}', this.uuid), function (event) {
+ that.handleEscToExit(event);
+ that.handleEnterToClickButton(event);
+ });
+ }
+
+ template() {
+ /** Implement generating template */
+ let { title, message, buttons, defaultButtonIdx, buttonClass } = this.state;
+ var sbTagString = new com_String();
+ sbTagString.appendLine("
");
+ sbTagString.appendLine("
");
+ return sbTagString.toString();
+ }
+
+ render() {
+ /** Implement after rendering */
+
+ }
+
+ //============================================================================
+ // Settings
+ //============================================================================
+ /**
+ * Open modal tag
+ * @param {function} callBackList
+ */
+ open() {
+ // render on open
+ super.render();
+ /** focus on default button */
+ $(this.wrapSelector('.vp-modal-button[data-idx="' + this.state.defaultButtonIdx + '"]')).focus();
+ // show
+ $(this.wrapSelector()).show();
+ }
+ close() {
+ $(document).unbind(com_util.formatString(".{0}", this.uuid));
+ $(document).unbind(com_util.formatString("keydown.{0}", this.uuid));
+ $(this.wrapSelector()).remove();
+ }
+ /**
+ * close using esc
+ * @param {Event} event
+ */
+ handleEscToExit(event) {
+ var keyCode = event.keyCode ? event.keyCode : event.which;
+ // esc
+ if (keyCode == 27) {
+ this.close();
+ }
+ }
+ /**
+ * select using enter
+ * @param {Event} event
+ */
+ handleEnterToClickButton(event) {
+ var keyCode = event.keyCode ? event.keyCode : event.which;
+ // enter
+ if (keyCode == 13) {
+ $(this.wrapSelector('.vp-modal-button[data-idx="' + this.state.defaultButtonIdx + '"]')).click();
+ this.close();
+ }
+ }
+
+ }
+
+ return Modal;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/ModelEditor.js b/visualpython/js/com/component/ModelEditor.js
new file mode 100644
index 00000000..c2fab057
--- /dev/null
+++ b/visualpython/js/com/component/ModelEditor.js
@@ -0,0 +1,1300 @@
+define([
+ __VP_CSS_LOADER__('vp_base/css/component/instanceEditor'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/Component',
+ 'vp_base/js/com/component/SuggestInput'
+], function(insCss, com_String, com_util, com_generator, Component, SuggestInput) {
+
+ // temporary const
+ const VP_INS_BOX = 'vp-ins-box';
+ const VP_INS_SELECT_CONTAINER = 'vp-ins-select-container';
+ const VP_INS_SELECT_TITLE = 'vp-ins-select-title';
+ const VP_INS_SEARCH = 'vp-ins-search';
+ const VP_INS_TYPE = 'vp-ins-type';
+ const VP_INS_SELECT_BOX = 'vp-ins-select-box';
+ const VP_INS_SELECT_LIST = 'vp-ins-select-list';
+ const VP_INS_SELECT_ITEM = 'vp-ins-select-item';
+
+ const VP_INS_PARAMETER_BOX = 'vp-ins-parameter-box';
+ const VP_INS_PARAMETER = 'vp-ins-parameter';
+
+ class ModelEditor extends Component {
+ constructor(pageThis, targetId, containerId) {
+ super(null, { pageThis: pageThis, targetId: targetId, containerId: containerId });
+ }
+
+ _init() {
+ super._init();
+
+ this.pageThis = this.state.pageThis;
+ this.targetId = this.state.targetId;
+ this.containerId = this.state.containerId;
+
+ let modelEditorType = '';
+ let modelEditorName = '';
+ if (this.pageThis.state['modelEditorType'] == undefined) {
+ modelEditorType = '';
+ }
+ if (this.pageThis.state['modelEditorName'] == undefined) {
+ modelEditorName = '';
+ }
+
+ this.state = {
+ modelEditorType: modelEditorType,
+ modelEditorName: modelEditorName,
+ action: {},
+ info: {},
+ config: {},
+ ...this.state
+ }
+
+ this.loaded = false;
+ }
+
+ render() {
+ ;
+ }
+
+ getModelCategory(modelType) {
+ let mlDict = vpConfig.getMLDataDict();
+ let keys = Object.keys(mlDict);
+ let modelCategory = '';
+ for (let i = 0; i < keys.length; i++) {
+ let key = keys[i];
+ if (mlDict[key].includes(modelType)) {
+ modelCategory = key;
+ break;
+ }
+ }
+ return modelCategory;
+ }
+
+ getAction(modelType) {
+ let category = this.getModelCategory(modelType);
+ let defaultActions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Perform modeling from features, or distance matrix.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict the closest target data X belongs to.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'predict_proba': {
+ name: 'predict_proba',
+ label: 'Predict probability',
+ code: '${pred_prob_allocate} = ${model}.predict_proba(${pred_prob_featureData})',
+ description: 'Predict class probabilities for X.',
+ options: [
+ { name: 'pred_prob_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_prob_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Apply dimensionality reduction to X.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ };
+ let actions = {};
+ switch (category) {
+ case 'Data Preparation':
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit Encoder/Scaler to X.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit Encoder/Scaler to X, then transform X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform labels to normalized encoding.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ if (modelType != 'ColumnTransformer') {
+ actions = {
+ ...actions,
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Transform binary labels back to multi-class labels.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'LabelEncoder') {
+ actions = {
+ ...actions,
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit Encoder/Scaler to X.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit Encoder/Scaler to X, then transform X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform labels to normalized encoding.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ if (modelType === 'SMOTE') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Check inputs and statistics of the sampler.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ },
+ 'fit_resample': {
+ name: 'fit_resample',
+ label: 'Fit and resample',
+ code: '${fit_res_allocateX}, ${fit_res_allocatey} = ${model}.fit_resample(${fit_res_featureData}, ${fit_res_targetData})',
+ description: 'Resample the dataset.',
+ options: [
+ { name: 'fit_res_allocateX', label: 'Allocate feature', component: ['input'], placeholder: 'New variable', value: 'X_res' },
+ { name: 'fit_res_allocatey', label: 'Allocate target', component: ['input'], placeholder: 'New variable', value: 'y_res' },
+ { name: 'fit_res_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_res_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Regression':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict']
+ }
+ break;
+ case 'Classification':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict'],
+ 'predict_proba': defaultActions['predict_proba'],
+ }
+ if (['LogisticRegression', 'SVC', 'GradientBoostingClassifier'].includes(modelType)) {
+ actions = {
+ ...actions,
+ 'decision_function': {
+ name: 'decision_function',
+ label: 'Decision function',
+ code: '${dec_allocate} = ${model}.decision_function(${dec_featureData})',
+ description: 'Compute the decision function of X.',
+ options: [
+ { name: 'dec_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'dec_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Auto ML':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict'],
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Fit and predict.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'predict_proba': defaultActions['predict_proba']
+ }
+ break;
+ case 'Clustering':
+ if (modelType == 'AgglomerativeClustering'
+ || modelType == 'DBSCAN') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Perform clustering from features, or distance matrix.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' }
+ ]
+ },
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Compute clusters from a data or distance matrix and predict labels.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ }
+ }
+ break;
+ }
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Compute clustering.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict the closest target data X belongs to.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Compute cluster centers and predict cluster index for each sample.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ }
+ }
+ if (modelType == 'KMeans') {
+ actions = {
+ ...actions,
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Compute clustering and transform X to cluster-distance space.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform X to a cluster-distance space.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Dimension Reduction':
+ if (modelType == 'TSNE') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit X into an embedded space.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit X into an embedded space and return that transformed output.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ }
+ if (modelType == 'LinearDiscriminantAnalysis') { // LDA
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Fit the Linear Discriminant Analysis model.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData}, ${fit_trans_targetData})',
+ description: 'Fit to data, then transform it.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict class labels for samples in X.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Project data to maximize class separation.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ }
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit X into an embedded space.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit the model with X and apply the dimensionality reduction on X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Transform data back to its original space.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Apply dimensionality reduction to X.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ case 'ETC':
+ if (modelType === 'GridSearchCV') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}${fit_targetData})',
+ description: 'Run fit with all sets of parameters.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train', usePair: true, pairKey: 'y' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Call predict on the estimator with the best found parameters.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Call inverse_transform on the estimator with the best found params.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Call transform on the estimator with the best found parameters.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ break;
+ }
+ return actions;
+ }
+
+ getInfo(modelType) {
+ let category = this.getModelCategory(modelType);
+ let infos = {};
+ let defaultInfos = {
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData}, ${score_targetData})',
+ description: '',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'score_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'get_params': {
+ name: 'get_params',
+ label: 'Get parameters',
+ code: '${param_allocate} = ${model}.get_params(${deep})',
+ description: 'Get parameters for this estimator.',
+ options: [
+ { name: 'deep', component: ['bool_select'], default: 'True', usePair: true },
+ { name: 'param_allocate', label: 'Allocate to', component: ['input'], value: 'params' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ 'feature_importances': {
+ name: 'feature_importances',
+ label: 'Feature importances',
+ code: "${fi_allocate} = vp_create_feature_importances(${model}, ${fi_featureData}${sort})",
+ description: 'Allocate feature_importances_',
+ options: [
+ { name: 'fi_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fi_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'df_i' },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true }
+ ]
+ },
+ 'plot_feature_importances': {
+ name: 'plot_feature_importances',
+ label: 'Plot feature importances',
+ code: "vp_plot_feature_importances(${model}, ${fi_featureData}${sort}${top_count})",
+ description: 'Draw feature_importances_',
+ options: [
+ { name: 'fi_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true },
+ ]
+ }
+ }
+ switch (category) {
+ case 'Data Preparation':
+ if (modelType == 'OneHotEncoder') {
+ infos = {
+ 'categories_': { // TODO:
+ name: 'categories_',
+ label: 'Categories',
+ code: '${categories_allocate} = ${model}.categories_',
+ description: 'The categories of each feature determined during fitting',
+ options: [
+ { name: 'categories_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'categories' }
+ ]
+ },
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'LabelEncoder') {
+ infos = {
+ 'classes_': {
+ name: 'classes_',
+ label: 'Classes',
+ code: '${classes_allocate} = ${model}.classes_',
+ description: 'Holds the label for each class.',
+ options: [
+ { name: 'classes_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'classes' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'KBinsDiscretizer') {
+ infos = {
+ 'bin_edges': { // TODO:
+ name: 'bin_edges',
+ label: 'Bin edges',
+ code: '${bin_edges_allocate} = ${model}.bin_edges_',
+ description: 'The edges of each bin. Contain arrays of varying shapes',
+ options: [
+ { name: 'bin_edges_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'bin_edges' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'ColumnTransformer') {
+ infos = {
+ 'transformers_': {
+ name: 'transformers_',
+ label: 'Transformers_',
+ code: '${transformers_allocate} = ${model}.transformers_',
+ description: 'The collection of fitted transformers as tuples of (name, fitted_transformer, column).',
+ options: [
+ { name: 'transformers_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'classes' }
+ ]
+ },
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ if (modelType === 'SMOTE') {
+ infos = {
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names for transformation.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ infos = {
+ ...infos,
+ 'get_params': defaultInfos['get_params']
+ }
+ break;
+ case 'Regression':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the coefficient of determination of the prediction.'
+ },
+ 'cross_val_score': {
+ name: 'cross_val_score',
+ label: 'Cross validation score',
+ import: 'from sklearn.model_selection import cross_val_score',
+ code: '${cvs_allocate} = cross_val_score(${model}, ${cvs_featureData}, ${cvs_targetData}${scoring}${cv})',
+ description: 'Evaluate a score by cross-validation.',
+ options: [
+ { name: 'cvs_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'cvs_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'scoring', component: ['option_select'], usePair: true, type: 'text',
+ options: [
+ '',
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'cv', label: 'Cross Validation', component: ['input_number'], placeholder: '1 ~ 10', default: 5, usePair: true },
+ { name: 'cvs_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ 'Coefficient': {
+ name: 'coef_',
+ label: 'Coefficient',
+ code: '${coef_allocate} = ${model}.coef_',
+ description: 'Weights assigned to the features.',
+ options: [
+ { name: 'coef_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'coef' }
+ ]
+ },
+ 'Intercept': {
+ name: 'intercept_',
+ label: 'Intercept',
+ code: '${intercept_allocate} = ${model}.intercept_',
+ description: 'Constants in decision function.',
+ options: [
+ { name: 'intercept_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'intercepts' }
+ ]
+ }
+ }
+ let svcList = [
+ 'DecisionTreeRegressor',
+ 'RandomForestRegressor',
+ 'GradientBoostingRegressor',
+ 'XGBRegressor', 'LGBMRegressor', 'CatBoostRegressor'
+ ];
+ if (svcList.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'feature_importances': defaultInfos['feature_importances'],
+ 'plot_feature_importances': defaultInfos['plot_feature_importances']
+ }
+ }
+ break;
+ case 'Classification':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'cross_val_score': {
+ name: 'cross_val_score',
+ label: 'Cross validation score',
+ import: 'from sklearn.model_selection import cross_val_score',
+ code: '${cvs_allocate} = cross_val_score(${model}, ${cvs_featureData}, ${cvs_targetData}${scoring}${cv})',
+ description: 'Evaluate a score by cross-validation.',
+ options: [
+ { name: 'cvs_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'cvs_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'scoring', component: ['option_select'], usePair: true, type: 'text',
+ options: [
+ '',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'cv', label: 'Cross Validation', component: ['input_number'], placeholder: '1 ~ 10', default: 5, usePair: true },
+ { name: 'cvs_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'roc_curve': {
+ name: 'roc_curve',
+ label: 'ROC Curve',
+ import: 'from sklearn import metrics',
+ code: "fpr, tpr, thresholds = metrics.roc_curve(${roc_targetData}, ${model}.predict_proba(${roc_featureData})[:, 1])\
+ \nplt.plot(fpr, tpr, label='ROC Curve')\
+ \nplt.xlabel('Sensitivity')\
+ \nplt.ylabel('Specificity')\
+ \nplt.show()",
+ description: '',
+ options: [
+ { name: 'roc_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'roc_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_test' }
+ ]
+ },
+ 'auc': {
+ name: 'auc',
+ label: 'AUC',
+ import: 'from sklearn import metrics',
+ code: 'metrics.roc_auc_score(${auc_targetData}, ${model}.predict_proba(${auc_featureData})[:, 1])',
+ description: '',
+ options: [
+ { name: 'auc_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'auc_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_test' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ }
+
+ // feature importances
+ let clfList = [
+ 'DecisionTreeClassifier',
+ 'RandomForestClassifier',
+ 'GradientBoostingClassifier',
+ 'XGBClassifier',
+ 'LGBMClassifier',
+ 'CatBoostClassifier',
+ ]
+ if (clfList.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'feature_importances': defaultInfos['feature_importances'],
+ 'plot_feature_importances': defaultInfos['plot_feature_importances']
+ }
+ }
+
+ // use decision_function on ROC, AUC
+ let decisionFunctionTypes = [
+ 'LogisticRegression', 'SVC', 'GradientBoostingClassifier'
+ ];
+ if (decisionFunctionTypes.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'roc_curve': {
+ ...infos['roc_curve'],
+ code: "fpr, tpr, thresholds = metrics.roc_curve(${roc_targetData}, ${model}.decision_function(${roc_featureData}))\
+ \nplt.plot(fpr, tpr, label='ROC Curve')\
+ \nplt.xlabel('Sensitivity')\
+ \nplt.ylabel('Specificity')\
+ \nplt.show()"
+ },
+ 'auc': {
+ ...infos['auc'],
+ code: 'metrics.roc_auc_score(${auc_targetData}, ${model}.decision_function(${auc_featureData}))',
+ }
+ }
+ }
+ break;
+ case 'Auto ML':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'get_params': {
+ ...defaultInfos['get_params']
+ }
+ }
+ break;
+ case 'Clustering':
+ infos = {
+ 'get_params': {
+ ...defaultInfos['get_params']
+ }
+ }
+
+ if (modelType == 'KMeans') {
+ infos = {
+ ...infos,
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'cluster_centers_': {
+ name: 'cluster_centers',
+ label: 'Cluster centers',
+ code: '${centers_allocate} = ${model}.cluster_centers_',
+ description: 'Coordinates of cluster centers.',
+ options: [
+ { name: 'centers_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'cluster_centers' }
+ ]
+ }
+ }
+ }
+
+ if (modelType == 'AgglomerativeClustering') {
+ infos = {
+ ...infos,
+ 'Dendrogram': { // FIXME:
+ name: 'dendrogram',
+ label: 'Dendrogram',
+ code: "# import\nfrom scipy.cluster.hierarchy import dendrogram, ward\n\nlinkage_array = ward(${dendro_data})\ndendrogram(linkage_array, p=3, truncate_mode='level', no_labels=True)\nplt.show()",
+ description: 'Draw a dendrogram',
+ options: [
+ { name: 'dendro_data', label: 'Data', component: ['data_select'], var_type: ['DataFrame'] }
+ ]
+ }
+ }
+ }
+
+ if (modelType == 'GaussianMixture') {
+ infos = {
+ ...infos,
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Compute the per-sample average log-likelihood of the given data X.'
+ }
+ }
+ }
+ break;
+ case 'Dimension Reduction':
+ if (modelType == 'LDA') {
+ infos = {
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData}, ${score_targetData})',
+ description: 'Return the average log-likelihood of all samples.',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'score_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ }
+ }
+ break;
+ }
+ if (modelType == 'PCA') {
+ infos = {
+ 'explained_variance_ratio_': {
+ name: 'explained_variance_ratio_',
+ label: 'Explained variance ratio',
+ code: '${ratio_allocate} = ${model}.explained_variance_ratio_',
+ description: 'Percentage of variance explained by each of the selected components.',
+ options: [
+ { name: 'ratio_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'ratio' }
+ ]
+ }
+ }
+ }
+ infos = {
+ ...infos,
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData})',
+ description: 'Return the average log-likelihood of all samples.',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ }
+ }
+ break;
+ case 'ETC':
+ if (modelType === 'GridSearchCV') {
+ infos = {
+ 'best_estimator_': {
+ name: 'best_estimator_',
+ label: 'Best estimator',
+ code: '${best_estimator_allocate} = ${model}.best_estimator_',
+ description: 'Estimator that was chosen by the search.',
+ options: [
+ { name: 'best_estimator_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_estimator' }
+ ]
+ },
+ 'best_score_': {
+ name: 'best_score_',
+ label: 'Best score',
+ code: '${best_score_allocate} = ${model}.best_score_',
+ description: 'Mean cross-validated score of the best_estimator.',
+ options: [
+ { name: 'best_score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_score' }
+ ]
+ },
+ 'best_params_': {
+ name: 'best_params_',
+ label: 'Best params',
+ code: '${best_params_allocate} = ${model}.best_params_',
+ description: 'Parameter setting that gave the best results on the hold out data.',
+ options: [
+ { name: 'best_params_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_params' }
+ ]
+ }
+ }
+ }
+ break;
+ }
+ return infos;
+ }
+
+ renderPage() {
+ var tag = new com_String();
+ tag.appendFormatLine('
', VP_INS_BOX, this.uuid); // vp-select-base
+
+ // Model Editor State (Saved state)
+ tag.appendFormatLine('
', 'modelEditorType', this.state.modelEditorType);
+ tag.appendFormatLine('
', 'modelEditorName', this.state.modelEditorName);
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'action');
+ tag.appendFormatLine('
Action
', VP_INS_SELECT_TITLE);
+
+ tag.appendFormatLine('
', 'position: relative;');
+ tag.appendFormatLine(' ', VP_INS_SEARCH, 'attr');
+ tag.appendFormatLine(' ', VP_INS_TYPE, 'action');
+ tag.appendFormatLine(' ', 'fa fa-search', 'vp-ins-search-icon');
+ tag.appendLine('
');
+
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'action');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'action');
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendFormatLine('
', VP_INS_SELECT_CONTAINER, 'info');
+ tag.appendFormatLine('
Information
', VP_INS_SELECT_TITLE);
+
+ tag.appendFormatLine('
', 'position: relative;');
+ tag.appendFormatLine(' ', VP_INS_SEARCH, 'method');
+ tag.appendFormatLine(' ', VP_INS_TYPE, 'info');
+ tag.appendFormatLine(' ', 'fa fa-search', 'vp-ins-search-icon');
+ tag.appendLine('
');
+
+ tag.appendFormatLine('
', VP_INS_SELECT_BOX, 'info');
+ tag.appendFormatLine('
', VP_INS_SELECT_LIST, 'info');
+ tag.appendLine(' ');
+ tag.appendLine('
'); // VP_INS_SELECT_BOX
+ tag.appendLine('
'); // VP_INS_SELECT_CONTAINER
+
+ tag.appendFormatLine('
Options
', VP_INS_SELECT_TITLE);
+ tag.appendFormatLine('
', VP_INS_PARAMETER_BOX);
+ tag.appendLine('
'); // VP_INS_BOX END
+
+ $(this.pageThis.wrapSelector('#' + this.containerId)).html(tag.toString());
+
+ return tag.toString();
+ }
+
+ reload() {
+ this.renderPage();
+
+ let targetTag = $(this.pageThis.wrapSelector('#' + this.targetId));
+ let model = $(targetTag).val();
+ let modelType = $(targetTag).find('option:selected').data('type');
+
+ let actions = this.getAction(modelType);
+ let infos = this.getInfo(modelType);
+ this.state.action = { ...actions };
+ this.state.info = { ...infos };
+
+ var actListTag = new com_String();
+ var infoListTag = new com_String();
+
+ Object.keys(actions).forEach(actKey => {
+ let titleText = actions[actKey].description;
+ if (actions[actKey].name != actions[actKey].label) {
+ titleText = actions[actKey].name + ': ' + titleText;
+ }
+ actListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, actKey, 'action', titleText, actions[actKey].label);
+ });
+ Object.keys(infos).forEach(infoKey => {
+ let titleText = infos[infoKey].description;
+ if (infos[infoKey].name != infos[infoKey].label) {
+ titleText = infos[infoKey].name + ': ' + titleText;
+ }
+ infoListTag.appendFormatLine('
{4} ',
+ VP_INS_SELECT_ITEM, infoKey, 'info', titleText, infos[infoKey].label);
+ });
+
+ $(this.wrapSelector('.' + VP_INS_SELECT_LIST + '.action')).html(actListTag.toString());
+ $(this.wrapSelector('.' + VP_INS_SELECT_LIST + '.info')).html(infoListTag.toString());
+
+ let that = this;
+ // action search suggest
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input action');
+ suggestInput.addClass(VP_INS_SEARCH);
+ suggestInput.setPlaceholder("Search Action");
+ suggestInput.setSuggestList(function () { return Object.keys(actions); });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.' + VP_INS_TYPE + '.action')).val(item.type);
+
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "model_editor_selected",
+ varName: value,
+ varOptions: actions[value],
+ isMethod: false
+ });
+ });
+ $(that.wrapSelector('.' + VP_INS_SEARCH + '.action')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // info search suggest
+ suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input info');
+ suggestInput.addClass(VP_INS_SEARCH);
+ suggestInput.setPlaceholder("Search info");
+ suggestInput.setSuggestList(function () { return Object.keys(infos); });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.' + VP_INS_TYPE + '.info')).val(item.type);
+
+ $(that.pageThis.wrapSelector('#' + that.targetId)).trigger({
+ type: "model_editor_selected",
+ varName: value,
+ varOptions: infos[value],
+ isMethod: true
+ });
+ });
+ $(that.wrapSelector('.' + VP_INS_SEARCH + '.info')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // bind event
+ this._bindEvent();
+
+ // load once on initializing page
+ if (this.loaded == false) {
+ let { modelEditorType, modelEditorName } = this.pageThis.state;
+ if (modelEditorType != '' && modelEditorName != '') {
+ // render option page for saved state
+ that.renderOptionPage(modelEditorType, modelEditorName);
+ }
+ // set loaded true
+ this.loaded = true;
+ }
+ }
+
+ renderOptionPage(type, name) {
+ if (this.state[type] != undefined && this.state[type][name] != undefined) {
+ let config = this.state[type][name];
+ let optBox = new com_String();
+ // render tag
+ config && config.options && config.options.forEach(opt => {
+ let label = opt.name;
+ if (opt.label != undefined) {
+ label = opt.label;
+ }
+ // fix label
+ label = com_util.optionToLabel(label);
+ optBox.appendFormatLine('
{2} '
+ , opt.name, opt.name, label);
+ let content = com_generator.renderContent(this, opt.component[0], opt, this.pageThis.state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // replace option box
+ $(this.wrapSelector('.' + VP_INS_PARAMETER_BOX)).html(optBox.toString());
+
+ this.state.config = config;
+
+ // add selection
+ $(this.wrapSelector('.' + VP_INS_SELECT_ITEM)).removeClass('selected');
+ let typeClass = '.' + VP_INS_SELECT_LIST + '.' + type;
+ let nameClass = '.' + VP_INS_SELECT_ITEM + '[data-var-name="' + name + '"]';
+ $(this.wrapSelector(typeClass + ' ' + nameClass)).addClass('selected');
+ // set state
+ $(this.wrapSelector('#modelEditorType')).val(type);
+ $(this.wrapSelector('#modelEditorName')).val(name);
+ this.pageThis.state.modelEditorType = type;
+ this.pageThis.state.modelEditorName = name;
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+
+ $(this.wrapSelector('.' + VP_INS_SELECT_ITEM)).on('click', function() {
+ let name = $(this).data('var-name');
+ let type = $(this).data('var-type');
+
+ that.renderOptionPage(type, name);
+ });
+ }
+
+ /**
+ * Show Model Editor
+ * @param {*} showType all / action / info
+ */
+ show() {
+ $(this.wrapSelector()).show();
+
+ this.reload();
+ }
+
+ hide() {
+ $(this.wrapSelector()).hide();
+ }
+
+ getCode(replaceDict={}) {
+ let code = new com_String();
+ if (this.config.import != undefined) {
+ code.appendLine(this.config.import);
+ code.appendLine();
+ }
+ let modelCode = com_generator.vp_codeGenerator(this.pageThis, this.config, this.pageThis.state);
+ Object.keys(replaceDict).forEach(key => {
+ modelCode = modelCode.replace(key, replaceDict[key]);
+ });
+ code.append(modelCode);
+
+ let allocateIdx = modelCode.indexOf(' = ');
+ if (allocateIdx >= 0) {
+ let allocateCode = modelCode.substr(0, allocateIdx);
+ code.appendLine();
+ code.append(allocateCode);
+ }
+
+ return code.toString();
+ }
+ }
+
+ return ModelEditor;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/MultiSelector.js b/visualpython/js/com/component/MultiSelector.js
new file mode 100644
index 00000000..d9d3d9fa
--- /dev/null
+++ b/visualpython/js/com/component/MultiSelector.js
@@ -0,0 +1,739 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : MultiSelector.js
+ * Author : Black Logic
+ * Note : Multi Selector
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 10. 05
+ * Change Date :
+ */
+define([
+ __VP_CSS_LOADER__('vp_base/css/component/multiSelector'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/Component',
+ 'vp_base/js/com/component/SuggestInput'
+], function(multiCss, com_Const, com_String, com_util, Component, SuggestInput) {
+
+ //========================================================================
+ // Define variable
+ //========================================================================
+ /** select */
+ const APP_PREFIX = 'vp-cs'
+ const APP_SELECT_CONTAINER = APP_PREFIX + '-select-container';
+ const APP_SELECT_LEFT = APP_PREFIX + '-select-left';
+ const APP_SELECT_BTN_BOX = APP_PREFIX + '-select-btn-box';
+ const APP_SELECT_RIGHT = APP_PREFIX + '-select-right';
+
+ const APP_SELECT_BOX = APP_PREFIX + '-select-box';
+ const APP_SELECT_ITEM = APP_PREFIX + '-select-item';
+
+ /** select left */
+ const APP_SELECT_SEARCH = APP_PREFIX + '-select-search';
+ const APP_DROPPABLE = APP_PREFIX + '-droppable';
+ const APP_DRAGGABLE = APP_PREFIX + '-draggable';
+
+ /** select btns */
+ const APP_SELECT_ADD_ALL_BTN = APP_PREFIX + '-select-add-all-btn';
+ const APP_SELECT_ADD_BTN = APP_PREFIX + '-select-add-btn';
+ const APP_SELECT_DEL_BTN = APP_PREFIX + '-select-del-btn';
+ const APP_SELECT_DEL_ALL_BTN = APP_PREFIX + '-select-del-all-btn';
+
+
+ //========================================================================
+ // [CLASS] MultiSelector
+ //========================================================================
+ /**
+ * MultiSelector
+ * Usage
+ * this._columnSelector = new MultiSelector(this.wrapSelector('#multi-selector-id'),
+ { mode: 'columns', parent: [data], selectedList: this.state.indexing, allowAdd: true }
+ );
+ */
+ class MultiSelector extends Component {
+
+ /**
+ *
+ * @param {string} frameSelector query for parent component
+ * @param {Object} config parent:[], selectedList=[], includeList=[], excludeList=[], allowAdd=true/false
+ */
+ constructor(frameSelector, config) {
+ super(frameSelector, config, {});
+ }
+
+ _init() {
+ this.frameSelector = this.$target;
+
+ // configuration
+ this.config = this.state;
+
+ var {
+ mode, type, parent,
+ dataList=[], selectedList=[], includeList=[], excludeList=[],
+ allowAdd=false, showDescription=true,
+ change=null
+ } = this.config;
+ this.mode = mode; // variable / columns / index / ndarray0 / ndarray1 / methods / data(given data)
+ this.parent = parent;
+ this.varType = type; // for mode:variable, variable type list to search
+ this.selectedList = selectedList;
+ this.includeList = includeList;
+ this.excludeList = excludeList;
+ this.allowAdd = allowAdd; // allow adding new item
+ this.showDescription = showDescription; // show description on the top of the box
+
+ this.change = change; // function (type=('add'|'remove'), list=[])
+
+ this.dataList = dataList; // [ { value, code, type }, ... ]
+ this.pointer = { start: -1, end: -1 };
+
+ this.loadDataList();
+ }
+
+ render() {
+ ;
+ }
+
+ loadDataList() {
+ var that = this;
+
+ if (this.mode !== 'variable' && this.mode !== 'data') {
+ if (this.parent == null || this.parent === '' || (Array.isArray(this.parent) && this.parent.length == 0)) {
+ this._executeCallback([]);
+ return;
+ }
+ }
+ switch (this.mode) {
+ case 'columns':
+ this._getColumnList(this.parent, function(dataList) {
+ that._executeCallback(dataList);
+ });
+ break;
+ case 'variable':
+ this._getVariableList(this.varType, function(dataList) {
+ that._executeCallback(dataList);
+ });
+ break;
+ case 'index':
+ this._getRowList(this.parent, function(dataList) {
+ that._executeCallback(dataList);
+ });
+ break;
+ case 'ndarray0':
+ this._getNdarray(this.parent, 0, function(dataList) {
+ that._executeCallback(dataList);
+ });
+ break;
+ case 'ndarray1':
+ this._getNdarray(this.parent, 1, function(dataList) {
+ that._executeCallback(dataList);
+ });
+ break;
+ case 'data':
+ that._executeCallback(this.dataList);
+ break;
+ }
+ }
+
+ _executeCallback(dataList) {
+ if (this.includeList && this.includeList.length > 0) {
+ dataList = dataList.filter(data => this.includeList.includes(data.code));
+ }
+ if (this.excludeList && this.excludeList.length > 0) {
+ dataList = dataList.filter(data => !this.excludeList.includes(data.code));
+ }
+ this.dataList = dataList;
+
+ // load
+ this.load();
+ }
+
+ _getVariableList(type, callback) {
+ vpKernel.getDataList(type).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var dataList = JSON.parse(result);
+ dataList = dataList.map(function(x, idx) {
+ return {
+ ...x,
+ value: x.varName,
+ code: x.varName,
+ type: x.varType,
+ location: idx
+ };
+ });
+ callback(dataList);
+ } catch (e) {
+ callback([]);
+ }
+ });
+ }
+
+ _getColumnList(parent, callback) {
+ if (Array.isArray(parent) && parent.length > 1) {
+ vpKernel.getCommonColumnList(parent).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var colList = JSON.parse(result);
+ colList = colList.map(function(x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value,
+ type: x.dtype,
+ isNumeric: x.is_numeric
+ };
+ });
+ callback(colList);
+ } catch (e) {
+ callback([]);
+ }
+ });
+ } else {
+ vpKernel.getColumnList(parent).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var { list } = JSON.parse(result);
+ list = list.map(function(x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value,
+ type: x.dtype,
+ isNumeric: x.is_numeric
+ };
+ });
+ callback(list);
+ } catch (e) {
+ callback([]);
+ }
+ });
+ }
+ }
+
+ _getRowList(parent, callback) {
+ vpKernel.getRowList(parent).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var { list:rowList } = JSON.parse(result);
+ rowList = rowList.map(function(x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value,
+ type: x.dtype
+ };
+ });
+ callback(rowList);
+ } catch (e) {
+ callback([]);
+ }
+ });
+ }
+
+ _getNdarray(parent, dim, callback) {
+ let parentVar = '';
+ if (parent && parent.length > 0) {
+ parentVar = parent[0];
+
+ let cmd = com_util.formatString('{0}.shape[{1}]', parentVar, dim);
+ vpKernel.execute(cmd).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ let dimLength = parseInt(result);
+ let ndList = [];
+ for (let i = 0; i < dimLength; i++) {
+ ndList.push({
+ value: i,
+ code: i,
+ type: 'int',
+ location: i
+ });
+ }
+ callback(ndList);
+ } catch (e) {
+ callback([]);
+ }
+ });
+ } else {
+ callback([]);
+ }
+
+ }
+
+ load() {
+ $(this.frameSelector).html(this.templateForMultiSelector());
+ this.bindEvent();
+ this.bindDraggable();
+ this._bindItemClickEvent();
+ }
+
+ getDataList() {
+ var colTags = $(this.wrapSelector('.' + APP_SELECT_ITEM + '.added:not(.moving)'));
+ var dataList = [];
+ if (colTags.length > 0) {
+ for (var i = 0; i < colTags.length; i++) {
+ var name = $(colTags[i]).data('name');
+ var type = $(colTags[i]).data('type');
+ var code = $(colTags[i]).data('code');
+ if (code != null) {
+ dataList.push({ name: name, type: type, code: code});
+ }
+ }
+ }
+ return dataList;
+ }
+
+ templateForMultiSelector() {
+ var that = this;
+
+ var tag = new com_String();
+ if (this.showDescription === true) {
+ tag.appendLine('
Drag-and-drop columns to right to select. ');
+ }
+ tag.appendFormatLine('
', APP_SELECT_CONTAINER, this.uuid);
+ // select - left
+ tag.appendFormatLine('
', APP_SELECT_LEFT);
+ // tag.appendFormatLine(' '
+ // , APP_SELECT_SEARCH, 'Search Column');
+ var vpSearchSuggest = new SuggestInput();
+ vpSearchSuggest.addClass(APP_SELECT_SEARCH);
+ vpSearchSuggest.addClass('vp-input');
+ vpSearchSuggest.setPlaceholder('Search ' + this.mode);
+ vpSearchSuggest.setSuggestList(function() { return that.dataList; });
+ vpSearchSuggest.setSelectEvent(function(value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpSearchSuggest.setAutoFocus(false);
+ vpSearchSuggest.setNormalFilter(true);
+ tag.appendLine(vpSearchSuggest.toTagString());
+ tag.appendFormatLine(' ')
+
+ var selectionList = this.dataList.filter(data => !that.selectedList.includes(data.code));
+ tag.appendLine(this.renderSelectionBox(selectionList));
+ tag.appendLine('
'); // APP_SELECT_LEFT
+ // select - buttons
+ tag.appendFormatLine('
', APP_SELECT_BTN_BOX);
+ // LAB: img to url
+ // tag.appendFormatLine('
'
+ // , APP_SELECT_ADD_ALL_BTN, 'Add all items', com_Const.IMAGE_PATH + 'arrow_right_double.svg');
+ // tag.appendFormatLine('
'
+ // , APP_SELECT_ADD_BTN, 'Add selected items', com_Const.IMAGE_PATH + 'arrow_right.svg');
+ // tag.appendFormatLine('
'
+ // , APP_SELECT_DEL_BTN, 'Remove selected items', com_Const.IMAGE_PATH + 'arrow_left.svg');
+ // tag.appendFormatLine('
'
+ // , APP_SELECT_DEL_ALL_BTN, 'Remove all items', com_Const.IMAGE_PATH + 'arrow_left_double.svg');
+ tag.appendFormatLine('
'
+ , APP_SELECT_ADD_ALL_BTN, 'Add all items');
+ tag.appendFormatLine('
'
+ , APP_SELECT_ADD_BTN, 'Add selected items');
+ tag.appendFormatLine('
'
+ , APP_SELECT_DEL_BTN, 'Remove selected items');
+ tag.appendFormatLine('
'
+ , APP_SELECT_DEL_ALL_BTN, 'Remove all items');
+ tag.appendLine('
'); // APP_SELECT_BTNS
+ // select - right
+ tag.appendFormatLine('
', APP_SELECT_RIGHT);
+ var selectedList = this.dataList.filter(data => that.selectedList.includes(data.code));
+ tag.appendLine(this.renderSelectedBox(selectedList));
+ if (this.allowAdd) {
+ // add item
+ tag.appendLine('
');
+ tag.appendLine('
');
+ }
+ tag.appendLine('
'); // APP_SELECT_RIGHT
+ tag.appendLine('
');
+ tag.appendLine('
'); // APP_SELECT_CONTAINER
+ return tag.toString();
+ }
+
+ renderSelectionBox(dataList) {
+ let mode = this.mode;
+ var tag = new com_String();
+ tag.appendFormatLine('
', APP_SELECT_BOX, 'left', APP_DROPPABLE, 'no-selection vp-scrollbar');
+ // get data and make draggable items
+ dataList && dataList.forEach((data, idx) => {
+ // for column : data.array parsing
+ var info = com_util.safeString(data.array);
+ if (info && info != 'undefined') {
+ info = data.value + ':\n' + info;
+ } else {
+ info = '';
+ }
+ let iconStr = '';
+ let infoStr = '';
+ if (mode === 'columns') {
+ if (data.isNumeric === true) {
+ iconStr = '
';
+ } else {
+ iconStr = '
';
+ }
+ } else if (mode === 'variable') {
+ infoStr = `
| ${data.type} `;
+ }
+ // render item box
+ tag.appendFormat('
'
+ , APP_SELECT_ITEM, APP_DRAGGABLE, data.location, data.value, data.type, data.code, info);
+ tag.appendFormat('{0}{1} {2}', iconStr, data.value, infoStr);
+ tag.appendLine('
');
+ });
+ tag.appendLine('
'); // APP_SELECT_BOX
+ return tag.toString();
+ }
+
+ renderSelectedBox(dataList) {
+ let mode = this.mode;
+ var tag = new com_String();
+ tag.appendFormatLine('
', APP_SELECT_BOX, 'right', APP_DROPPABLE, 'no-selection vp-scrollbar');
+ // get data and make draggable items
+ dataList && dataList.forEach((data, idx) => {
+ // for column : data.array parsing
+ var info = com_util.safeString(data.array);
+ if (info && info != 'undefined') {
+ info = data.value + ':\n' + info;
+ } else {
+ info = '';
+ }
+ let iconStr = '';
+ let infoStr = '';
+ if (mode === 'columns') {
+ if (data.isNumeric === true) {
+ iconStr = '
';
+ } else {
+ iconStr = '
';
+ }
+ } else if (mode === 'variable') {
+ infoStr = `
| ${data.type} `;
+ }
+ // render item box
+ tag.appendFormat('
'
+ , APP_SELECT_ITEM, APP_DRAGGABLE, 'added', data.location, data.value, data.type, data.code, info);
+ tag.appendFormat('{0}{1} {2}', iconStr, data.value, infoStr);
+ tag.appendLine('
');
+ });
+ tag.appendLine('
'); // APP_SELECT_BOX
+ return tag.toString();
+ }
+
+ bindEvent() {
+ var that = this;
+ // item indexing - search
+ $(this.wrapSelector('.' + APP_SELECT_SEARCH)).on('change', function(event) {
+ var searchValue = $(this).val();
+
+ // filter added items
+ var addedTags = $(that.wrapSelector('.' + APP_SELECT_RIGHT + ' .' + APP_SELECT_ITEM + '.added'));
+ var addedList = [];
+ for (var i = 0; i < addedTags.length; i++) {
+ var value = $(addedTags[i]).attr('data-name');
+ addedList.push(value);
+ }
+ var filteredList = that.dataList.filter(x => x.value.includes(searchValue) && !addedList.includes(x.value));
+
+ // items indexing
+ $(that.wrapSelector('.' + APP_SELECT_BOX + '.left')).replaceWith(function() {
+ return that.renderSelectionBox(filteredList);
+ });
+
+ // draggable
+ that.bindDraggable();
+ that._bindItemClickEvent();
+ });
+
+ // item indexing - add all
+ $(this.wrapSelector('.' + APP_SELECT_ADD_ALL_BTN)).on('click', function(event) {
+ $(that.wrapSelector('.' + APP_SELECT_BOX + '.left .' + APP_SELECT_ITEM)).appendTo(
+ $(that.wrapSelector('.' + APP_SELECT_BOX + '.right'))
+ );
+ $(that.wrapSelector('.' + APP_SELECT_ITEM)).addClass('added');
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + '.selected')).removeClass('selected');
+ that.pointer = { start: -1, end: -1 };
+
+ that.change && that.change('add', that.getDataList());
+ });
+
+ // item indexing - add
+ $(this.wrapSelector('.' + APP_SELECT_ADD_BTN)).on('click', function(event) {
+ var selector = '.selected';
+
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + selector)).appendTo(
+ $(that.wrapSelector('.' + APP_SELECT_BOX + '.right'))
+ );
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + selector)).addClass('added');
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + selector)).removeClass('selected');
+ that.pointer = { start: -1, end: -1 };
+
+ that.change && that.change('add', that.getDataList());
+ });
+
+ // item indexing - del
+ $(this.wrapSelector('.' + APP_SELECT_DEL_BTN)).on('click', function(event) {
+ var selector = '.selected';
+ var targetBoxQuery = that.wrapSelector('.' + APP_SELECT_BOX + '.left');
+
+ var selectedTag = $(that.wrapSelector('.' + APP_SELECT_ITEM + selector));
+ selectedTag.appendTo(
+ $(targetBoxQuery)
+ );
+ // sort
+ $(targetBoxQuery + ' .' + APP_SELECT_ITEM).sort(function(a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo(
+ $(targetBoxQuery)
+ );
+ selectedTag.removeClass('added');
+ selectedTag.removeClass('selected');
+ that.pointer = { start: -1, end: -1 };
+
+ that.change && that.change('remove', that.getDataList());
+ });
+
+ // item indexing - delete all
+ $(this.wrapSelector('.' + APP_SELECT_DEL_ALL_BTN)).on('click', function(event) {
+ var targetBoxQuery = that.wrapSelector('.' + APP_SELECT_BOX + '.left');
+ $(that.wrapSelector('.' + APP_SELECT_BOX + '.right .' + APP_SELECT_ITEM)).appendTo(
+ $(targetBoxQuery)
+ );
+ // sort
+ $(targetBoxQuery + ' .' + APP_SELECT_ITEM).sort(function(a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo(
+ $(targetBoxQuery)
+ );
+ $(that.wrapSelector('.' + APP_SELECT_ITEM)).removeClass('added');
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + '.selected')).removeClass('selected');
+ that.pointer = { start: -1, end: -1 };
+
+ that.change && that.change('remove', that.getDataList());
+ });
+
+ // add new item
+ $(this.wrapSelector('.vp-cs-add-item-btn')).on('click', function(event) {
+ let newItemName = $(that.wrapSelector('.vp-cs-add-item-name')).val();
+ that._addNewItem(newItemName);
+
+ that.change && that.change('add', that.getDataList());
+ });
+ // add new item (by pushing enter key)
+ $(this.wrapSelector('.vp-cs-add-item-name')).on('keyup', function(event) {
+ var keycode = event.keyCode
+ ? event.keyCode
+ : event.which;
+ if (keycode == 13) { // enter
+ let newItemName = $(this).val();
+ that._addNewItem(newItemName);
+
+ that.change && that.change('add', that.getDataList());
+ }
+ });
+
+ // refresh
+ $(this.wrapSelector('.vp-cs-refresh')).on('click', function(event) {
+ that.loadDataList();
+ });
+
+ this._bindItemClickEvent();
+ }
+
+ _bindItemClickEvent() {
+ let that = this;
+ // item indexing
+ $(this.wrapSelector('.' + APP_SELECT_ITEM)).off('click');
+ $(this.wrapSelector('.' + APP_SELECT_ITEM)).on('click', function(event) {
+ var dataIdx = $(this).attr('data-idx');
+ var idx = $(this).index();
+ var added = $(this).hasClass('added'); // right side added item?
+ var selector = '';
+
+ // remove selection for select box on the other side
+ if (added) {
+ // remove selection for left side
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + ':not(.added)')).removeClass('selected');
+ // set selector
+ selector = '.added';
+ } else {
+ // remove selection for right(added) side
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + '.added')).removeClass('selected');
+ // set selector
+ selector = ':not(.added)';
+ }
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ // multi-select
+ that.pointer = { start: idx, end: -1 };
+ $(this).toggleClass('selected');
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ // slicing
+ var startIdx = that.pointer.start;
+
+ if (startIdx == -1) {
+ // no selection
+ that.pointer = { start: idx, end: -1 };
+ } else if (startIdx > idx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + APP_SELECT_ITEM + selector));
+ for (var i = idx; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.pointer = { start: startIdx, end: idx };
+ } else if (startIdx <= idx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + APP_SELECT_ITEM + selector));
+ for (var i = startIdx; i <= idx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.pointer = { start: startIdx, end: idx };
+ }
+ } else {
+ // single-select
+ that.pointer = { start: idx, end: -1 };
+ // un-select others
+ $(that.wrapSelector('.' + APP_SELECT_ITEM + selector)).removeClass('selected');
+ // select this
+ $(this).addClass('selected');
+ }
+ });
+
+ // item deleting (manually added item only)
+ $(this.wrapSelector('.vp-cs-del-item')).off('click');
+ $(this.wrapSelector('.vp-cs-del-item')).on('click', function(event) {
+ $(this).closest('.' + APP_SELECT_ITEM).remove();
+ that.pointer = { start: -1, end: -1 };
+
+ that.change && that.change('remove', that.getDataList());
+ });
+ }
+
+ _addNewItem(newItemName) {
+ if (newItemName && newItemName !== '') {
+ // check if it is already exist
+ // - if it is already added, just select that item
+ // get added items
+ var addedTags = $(this.wrapSelector('.' + APP_SELECT_RIGHT + ' .' + APP_SELECT_ITEM + '.added'));
+ var addedList = [];
+ for (var i = 0; i < addedTags.length; i++) {
+ var value = $(addedTags[i]).attr('data-name');
+ addedList.push(value);
+ }
+ if (addedList.includes(newItemName)) {
+ // just select that item and do nothing
+ var targetTag = $(this.wrapSelector(`.vp-cs-select-item.added[data-name="${newItemName}"]`));
+ this.pointer = { start: targetTag.index(), end: -1 };
+ // un-select others
+ $(this.wrapSelector('.' + APP_SELECT_ITEM)).removeClass('selected');
+ targetTag.addClass('selected');
+ return;
+ }
+ var filteredList = this.dataList.filter(x => x.value === newItemName);
+ if (filteredList.length > 0) {
+ // already exist -> move it to selected-box
+ var targetTag = $(this.wrapSelector(`.vp-cs-select-item[data-name="${newItemName}"]`));
+ $(targetTag).appendTo(
+ $(this.wrapSelector('.' + APP_SELECT_BOX + '.right'))
+ );
+ this.pointer = { start: targetTag.index(), end: -1 };
+ // un-select others
+ $(this.wrapSelector('.' + APP_SELECT_ITEM)).removeClass('selected');
+ targetTag.addClass('added');
+ targetTag.addClass('selected');
+ return;
+ }
+
+ // add item
+ let newItemIndex = this.dataList.length;
+ var targetTag = $(`
`);
+ $(targetTag).appendTo(
+ $(this.wrapSelector('.' + APP_SELECT_BOX + '.right'))
+ );
+ this.pointer = { start: targetTag.index(), end: -1 };
+ // un-select others
+ $(this.wrapSelector('.' + APP_SELECT_ITEM)).removeClass('selected');
+ // clear item input
+ $(this.wrapSelector('.vp-cs-add-item-name')).val('');
+ // bind click event
+ this._bindItemClickEvent();
+ // bind draggable
+ this.bindDraggable();
+ }
+ }
+
+ bindDraggable() {
+ var that = this;
+ var draggableQuery = this.wrapSelector('.' + APP_DRAGGABLE);
+ var droppableQuery = this.wrapSelector('.' + APP_DROPPABLE);
+
+ $(draggableQuery).draggable({
+ // containment: '.select-' + type + ' .' + APP_DROPPABLE,
+ // appendTo: droppableQuery,
+ // snap: '.' + APP_DRAGGABLE,
+ revert: 'invalid',
+ cursor: 'pointer',
+ connectToSortable: droppableQuery + '.right',
+ // cursorAt: { bottom: 5, right: 5 },
+ helper: function() {
+ // selected items
+ var widthString = parseInt($(this).outerWidth()) + 'px';
+ var selectedTag = $(this).parent().find('.selected');
+ if (selectedTag.length <= 0) {
+ selectedTag = $(this);
+ }
+ return $('
').append(selectedTag.clone().addClass('moving').css({
+ width: widthString, border: '0.25px solid #C4C4C4'
+ }));
+ }
+ });
+
+ $(droppableQuery).droppable({
+ accept: draggableQuery,
+ drop: function(event, ui) {
+ var dropped = ui.draggable;
+ var droppedOn = $(this);
+
+ // is dragging on same droppable container?
+ if (droppedOn.get(0) == $(dropped).parent().get(0)) {
+
+ return ;
+ }
+
+ var dropGroup = $(dropped).parent().find('.selected:not(.moving)');
+ // if nothing selected(as orange_text), use dragging item
+ if (dropGroup.length <= 0) {
+ dropGroup = $(dropped);
+ }
+ $(dropGroup).detach().css({top:0, left:0}).appendTo(droppedOn);
+
+ if ($(this).hasClass('right')) {
+ // add
+ $(dropGroup).addClass('added');
+ that.change && that.change('add', that.getDataList());
+ } else {
+ // del
+ $(dropGroup).removeClass('added');
+ // sort
+ $(droppedOn).find('.' + APP_SELECT_ITEM).sort(function(a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo( $(droppedOn) );
+ that.change && that.change('remove', that.getDataList());
+ }
+ // remove selection
+ $(droppableQuery).find('.selected').removeClass('selected');
+ that.pointer = { start: -1, end: -1 };
+ },
+ over: function(event, elem) {
+ },
+ out: function(event, elem) {
+ }
+ });
+ }
+ }
+
+ return MultiSelector;
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/com/component/NumpyComponent.js b/visualpython/js/com/component/NumpyComponent.js
new file mode 100644
index 00000000..d4bb217f
--- /dev/null
+++ b/visualpython/js/com/component/NumpyComponent.js
@@ -0,0 +1,179 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : NumpyComponent.js
+ * Author : Black Logic
+ * Note : Library Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] NumpyComponent
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_library/numpyComponent.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_library/numpyComponent'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_library/numpyLibrary',
+ 'vp_base/data/m_library/pythonLibrary'
+], function(libHtml, libCss, PopupComponent, com_generatorV2, numpyLibrary, pythonLibrary) {
+
+ /**
+ * NumpyComponent
+ */
+ class NumpyComponent extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+
+ this.packageId = this.id;
+ // deep copy package info
+ this.package = null;
+ try {
+ let packageName = this.path.split(' - ')[2];
+ let findPackage = null;
+ if (packageName == 'numpy') {
+ findPackage = numpyLibrary.NUMPY_LIBRARIES[this.packageId];
+ } else if (packageName == 'python') {
+ findPackage = pythonLibrary.PYTHON_LIBRARIES[this.packageId];
+ }
+ if (findPackage) {
+ this.package = JSON.parse(JSON.stringify(findPackage)); // deep copy of package
+ } else {
+ throw 'Cannot find package';
+ }
+ } catch(err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Cannot find package id from library: ' + this.packageId);
+ return;
+ }
+ this.config.checkModules = ['np'];
+
+ if (this.package.docs === undefined) {
+ if (packageName == 'numpy') {
+ this.config.docs = 'https://numpy.org/doc/';
+ } else if (packageName == 'python') {
+ this.config.docs = 'https://docs.python.org/3.11/library/index.html';
+ }
+ } else {
+ this.config.docs = this.package.docs;
+ }
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'loading state', this.state);
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // save change of vp-state component
+ $(this.wrapSelector('.vp-state')).on('change', function() {
+ let id = $(this)[0].id;
+ let val = $(this).val();
+ that.state[id] = val;
+ });
+ }
+
+ loadState() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, this.state);
+
+ let that = this;
+ Object.keys(this.state).forEach(key => {
+ if (key !== 'config') {
+ let tag = $(that.wrapSelector('#' + key));
+ let tagName = $(tag).prop('tagName');
+ let savedValue = that.state[key];
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(savedValue);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', savedValue);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(savedValue);
+ break;
+ }
+ }
+ });
+ }
+
+ saveState() {
+ let that = this;
+ $(this.wrapSelector('.vp-state')).each((idx, tag) => {
+ let id = tag.id;
+ let tagName = $(tag).prop('tagName');
+ let newValue = '';
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ newValue = $(tag).val();
+ break;
+ }
+ if (inputType == 'checkbox') {
+ newValue = $(tag).prop('checked');
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ newValue = $(tag).val();
+ break;
+ }
+
+ that.state[id] = newValue;
+ });
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'savedState', that.state);
+ }
+
+ templateForBody() {
+ return libHtml;
+ }
+
+ render() {
+ super.render();
+
+ // show interface
+ com_generatorV2.vp_showInterfaceOnPage(this, this.package, this.state);
+
+ // hide required page if no options
+ if ($.trim($(this.wrapSelector('#vp_inputOutputBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-require-box')).hide();
+ }
+
+ // hide optional page if no options
+ if ($.trim($(this.wrapSelector('#vp_optionBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-option-box')).hide();
+ }
+ }
+
+ open() {
+ super.open();
+ // hide optional page if no options
+ if ($.trim($(this.wrapSelector('#vp_optionBox table tbody')).html())=='') {
+ $(this.wrapSelector('.vp-option-box')).hide();
+ }
+ }
+
+ generateCode() {
+ let code = com_generatorV2.vp_codeGenerator(this, this.package, this.state);
+ return code;
+ }
+
+ }
+
+ return NumpyComponent;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/PackageManager.js b/visualpython/js/com/component/PackageManager.js
new file mode 100644
index 00000000..a808315e
--- /dev/null
+++ b/visualpython/js/com/component/PackageManager.js
@@ -0,0 +1,479 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : PackageManager.js
+ * Author : Black Logic
+ * Note : Component > PackageManager
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 06. 14
+ * Change Date :
+ */
+//============================================================================
+// [CLASS] PackageManager
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/packageManager.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/packageManager'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/js/com/component/LoadingSpinner'
+], function(ifHtml, ifCss, com_util, com_Const, com_String, com_interface, SuggestInput, PopupComponent, FileNavigation, LoadingSpinner) {
+
+ /**
+ * PackageManager
+ */
+ class PackageManager extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.name = 'Package Manager';
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.sizeLevel = 1;
+
+ this.state = {
+ selected: '',
+ popupType: '',
+ ...this.state
+ }
+
+ this.packageLib = {};
+ this.packageLibTemplate = {
+ 'numpy': { pipName: 'numpy' },
+ 'pandas': { pipName: 'pandas' },
+ 'pyarrow': { pipName: 'pyarrow' },
+ 'matplotlib': { pipName: 'matplotlib' },
+ 'seaborn': { pipName: 'seaborn' },
+ 'plotly': { pipName: 'plotly' },
+ 'wordcloud': { pipName: 'wordcloud' },
+ 'sklearn': { pipName: 'scikit-learn' },
+ 'scikit_posthocs': { pipName: 'scikit-posthocs' },
+ 'scipy': { pipName: 'scipy' },
+ 'statsmodels': { pipName: 'statsmodels' },
+ 'factor_analyzer': { pipName: 'factor-analyzer' },
+ 'pingouin': { pipName: 'pingouin' },
+ 'category_encoders': { pipName: 'category_encoders' },
+ 'imblearn': { pipName: 'imblearn' },
+ 'xgboost': { pipName: 'xgboost' },
+ 'lightgbm': { pipName: 'lightgbm' },
+ 'catboost': { pipName: 'catboost' },
+ 'autosklearn': { pipName: 'auto-sklearn' },
+ 'tpot': { pipName: 'tpot' },
+ 'pymupdf': { pipName: 'pymupdf' },
+ 'sweetviz': { pipName: 'sweetviz' },
+ }
+
+ if (vpConfig.extensionType === 'lite') {
+ this.packageLibTemplate = {
+ 'numpy': { pipName: 'numpy' },
+ 'pandas': { pipName: 'pandas' },
+ 'matplotlib': { pipName: 'matplotlib' },
+ 'seaborn': { pipName: 'seaborn' },
+ 'plotly': { pipName: 'plotly' },
+ 'sklearn': { pipName: 'scikit-learn' },
+ 'scikit_posthocs': { pipName: 'scikit-posthocs' },
+ 'scipy': { pipName: 'scipy' },
+ 'statsmodels': { pipName: 'statsmodels' },
+ 'factor_analyzer': { pipName: 'factor-analyzer' },
+ 'category_encoders': { pipName: 'category_encoders' },
+ 'imblearn': { pipName: 'imblearn' },
+ 'xgboost': { pipName: 'xgboost' },
+ 'lightgbm': { pipName: 'lightgbm' },
+ 'catboost': { pipName: 'catboost' },
+ 'autosklearn': { pipName: 'auto-sklearn' },
+ 'sweetviz': { pipName: 'sweetviz' },
+ }
+ }
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('.vp-pm-search'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // search item
+ $(document).on('change', this.wrapSelector('.vp-pm-search'), function(evt) {
+ var value = $(this).val();
+ if (value != '') {
+ $(that.wrapSelector('.vp-pm-item')).hide();
+ $(that.wrapSelector('.vp-pm-item')).filter(function() {
+ let key = $(this).data('key');
+ return key.search(value.toLowerCase()) >= 0;
+ }).show();
+ } else {
+ $(that.wrapSelector('.vp-pm-item')).show();
+ }
+ });
+
+ // sort menu popup
+ $(this.wrapSelector('.vp-pm-sort')).on('click', function(evt) {
+ evt.stopPropagation();
+ $(that.wrapSelector('.vp-pm-sort-menu-box')).toggle();
+ });
+
+ // sort item
+ $(this.wrapSelector('.vp-pm-sort-menu-item')).on('click', function() {
+ var menu = $(this).data('menu');
+ if (menu === 'registered') {
+ // sort by name
+ $(that.wrapSelector('.vp-pm-item')).sort(function(a, b) {
+ var keyA = parseInt($(a).data('seq'));
+ var keyB = parseInt($(b).data('seq'));
+ return keyA > keyB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-pm-table')))
+ } else if (menu === 'name') {
+ // sort by name
+ $(that.wrapSelector('.vp-pm-item')).sort(function(a, b) {
+ var keyA = $(a).data('key');
+ var keyB = $(b).data('key');
+ return keyA > keyB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-pm-table')))
+ } else if (menu === 'installed') {
+ // sort by date
+ $(that.wrapSelector('.vp-pm-item')).sort(function(a, b) {
+ var insA = $(a).data('installed');
+ var insB = $(b).data('installed');
+ if (insA === insB) {
+ var keyA = $(a).data('key');
+ var keyB = $(b).data('key');
+ return keyA > keyB ? 1 : -1
+ }
+ return insA < insB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-pm-table')))
+ } else if (menu === 'uninstalled') {
+ $(that.wrapSelector('.vp-pm-item')).sort(function(a, b) {
+ var insA = $(a).data('installed');
+ var insB = $(b).data('installed');
+ if (insA === insB) {
+ var keyA = $(a).data('key');
+ var keyB = $(b).data('key');
+ return keyA > keyB ? 1 : -1
+ }
+ return insA > insB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-pm-table')))
+ }
+ $(that.wrapSelector('.vp-pm-sort-menu-box')).hide();
+ });
+
+ // reload package list
+ $(this.wrapSelector('.vp-pm-func-reload')).on('click', function() {
+ // reset search keyword
+ $(that.wrapSelector('.vp-pm-search')).val('');
+
+ // load package list
+ that.loadPackageList();
+ });
+
+ // add package
+ $(this.wrapSelector('.vp-pm-add')).on('click', function() {
+ that.openOptionPopup('add');
+ });
+ }
+
+ bindItemEvent() {
+ let that = this;
+
+ // item menu click
+ $(this.wrapSelector('.vp-pm-item-menu-item')).off('click');
+ $(this.wrapSelector('.vp-pm-item-menu-item:not(.disabled)')).on('click', function(evt) {
+ var menu = $(this).data('menu');
+ var item = $(this).closest('.vp-pm-item');
+ var key = $(item).data('key');
+ if (menu === 'install') {
+ that.state.selected = key;
+ that.openOptionPopup('install');
+ } else if (menu === 'uninstall') {
+ var pipName = that.packageLib[key].pipName;
+ var code = com_util.formatString("!pip uninstall -y {0}", pipName);
+ if (vpConfig.extensionType === 'lite') {
+ code = com_util.formatString("%pip uninstall {0}", pipName);
+ }
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Package Manager');
+ that.loadPackageList();
+ } else if (menu === 'upgrade') {
+ var pipName = that.packageLib[key].pipName;
+ var code = com_util.formatString("!pip install --upgrade {0}", pipName);
+ if (vpConfig.extensionType === 'lite') {
+ code = com_util.formatString("%pip install {0}", pipName);
+ }
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Package Manager');
+ that.loadPackageList();
+ } else if (menu === 'delete') {
+ $(item).remove();
+ delete that.packageLib[key];
+ vpConfig.removeData('packageList', 'vppackman').then(function() {
+ vpConfig.setData({ 'packageList': that.packageLib }, 'vppackman');
+ that.loadPackageList();
+ });
+ }
+ evt.stopPropagation();
+ });
+ }
+
+ templateForBody() {
+ return ifHtml;
+ }
+
+ templateForAddPage() {
+ return `
+ Package name
+
+ Pip name
+
+
`;
+ }
+
+ templateForInstallPage() {
+ return `
+
Version selection
+
+
Latest version
+
+ Specified version
+
+
+
+
`;
+ }
+
+ openOptionPopup(type) {
+ let that = this;
+ let title = '';
+ let size = { width: 400, height: 250 };
+
+ $(this.wrapSelector('.vp-inner-popup-body')).empty();
+
+ this.state.popupType = type;
+ switch (type) {
+ case 'add':
+ title = 'Add new package to manage'
+ $(this.wrapSelector('.vp-inner-popup-body')).html(this.templateForAddPage());
+ break;
+ case 'install':
+ title = 'Install package'
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(this.templateForInstallPage());
+
+ $(this.wrapSelector('.vp-inner-popup-body input[name="ver_select"]')).on('change', function() {
+ let checkedType = $(this).val();
+ if (checkedType === 'specified') {
+ $(that.wrapSelector('.vp-inner-popup-version')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-version')).prop('disabled', true);
+ }
+ });
+ break;
+ }
+
+ // set size and position
+ $(this.wrapSelector('.vp-inner-popup-box')).css({
+ width: size.width,
+ height: size.height,
+ left: 'calc(50% - ' + (size.width/2) + 'px)',
+ top: 'calc(50% - ' + (size.height/2) + 'px)',
+ });
+
+ // show popup box
+ this.openInnerPopup(title);
+ }
+
+ handleInnerOk() {
+ switch (this.state.popupType) {
+ case 'add':
+ var packName = $(this.wrapSelector('.vp-inner-popup-package')).val();
+ var pipName = $(this.wrapSelector('.vp-inner-popup-pip')).val();
+ if (pipName === '') {
+ pipName = packName;
+ }
+ this.packageLib[packName] = { pipName: pipName };
+ vpConfig.setData({ 'packageList': this.packageLib }, 'vppackman');
+
+ // load package list
+ this.loadPackageList();
+ break;
+ case 'install':
+ let versionType = $(this.wrapSelector('.vp-inner-popup-body input[name="ver_select"]:checked')).val();
+ var pipName = this.packageLib[this.state.selected].pipName;
+ var code = com_util.formatString("!pip install {0}", pipName);
+ if (vpConfig.extensionType === 'lite') {
+ code = com_util.formatString("%pip install {0}", pipName);
+ }
+ if (versionType === 'specified') {
+ // specified version
+ let version = $(this.wrapSelector('.vp-inner-popup-version')).val();
+ if (version && version !== '') {
+ code = com_util.formatString("!pip install {0}=={1}", pipName, version);
+ if (vpConfig.extensionType === 'lite') {
+ code = com_util.formatString("%pip install {0}=={1}", pipName, version);
+ }
+ } else {
+ $(this.wrapSelector('.vp-inner-popup-version')).focus();
+ return false;
+ }
+ }
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Package Manager');
+
+ // load package list
+ this.loadPackageList();
+ break;
+ }
+
+ this.closeInnerPopup();
+ }
+
+ render() {
+ super.render();
+
+ let that = this;
+ let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.vp-popup-body')));
+ vpConfig.getData('', 'vppackman').then(function(savedData) {
+ // Reset abnormal data
+ if (savedData == undefined || savedData.packageList === undefined) {
+ savedData = { packageList: JSON.parse(JSON.stringify(that.packageLibTemplate)) };
+ vpConfig.setData({ savedData }, 'vppackman');
+ }
+
+ that.packageLib = {
+ ...savedData.packageList
+ };
+ loadingSpinner.remove();
+ // load package list
+ that.loadPackageList();
+ }).catch(function(err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+
+ that.packageLib = {
+ ...that.packageLibTemplate
+ };
+ loadingSpinner.remove();
+ // load package list
+ that.loadPackageList();
+ });
+ }
+
+ /**
+ *
+ * @param {String} key
+ * @param {Object} info installed, version, path
+ * @param {number} index sequence of initial package list
+ * @returns
+ */
+ renderPackageItem(key, info, index) {
+ var item = new com_String();
+ item.appendFormatLine('
', 'vp-pm-item', key, info.installed===true?'1':'0', index);
+ item.appendFormatLine('
', 'vp-pm-item-header', (info.path?info.path:''));
+ item.appendFormatLine('
{0} ', key);
+ if (info.installed === true) {
+ item.appendFormatLine('
{0} ', info.version);
+ } else {
+ item.appendLine('
Not installed ');
+ }
+ item.appendFormatLine('
', 'vp-pm-item-menu');
+ // install
+ item.appendFormatLine('
'
+ , 'vp-pm-item-menu-item', 'install', 'Install');
+ if (vpConfig.extensionType !== 'lite') {
+ // upgrade
+ item.appendFormatLine('
'
+ , 'vp-pm-item-menu-item', (info.installed===true?'':'disabled'), 'upgrade', 'Upgrade');
+ // uninstall
+ item.appendFormatLine('
'
+ , 'vp-pm-item-menu-item', (info.installed===true?'':'disabled'), 'uninstall', 'Uninstall');
+ }
+ item.appendLine('
'); // end of vp-pm-item-menu
+ item.appendLine('
'); // end of vp-pm-item-header
+ // delete button
+ item.appendLine('');
+ item.appendLine('
'); // end of vp-pm-item
+ return item.toString();
+ }
+
+ generateCode() {
+ return '';
+ }
+
+ loadPackageList() {
+ var that = this;
+ // import importlib
+ // _vp_pack = importlib.import_module('numpy')
+ // print(_vp_pack.__version__)
+
+ // clear table except head
+ $(this.wrapSelector('.vp-pm-table')).html('');
+
+ let packageList = Object.keys(this.packageLib);
+
+ // set auto search
+ let searchInput = new SuggestInput();
+ searchInput.addClass('vp-pm-search vp-input');
+ searchInput.setPlaceholder("Search");
+ searchInput.setSuggestList(function () { return packageList; });
+ $(this.wrapSelector('.vp-pm-search')).replaceWith(searchInput.toTagString());
+
+ let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.vp-popup-body')));
+ vpKernel.getPackageList(packageList).then(function(resultObj) {
+ let { result } = resultObj;
+ let packageInfo = JSON.parse(result);
+
+ // load code list
+ var innerFuncCode = new com_String();
+ Object.keys(packageInfo).forEach((key, idx) => {
+ let info = packageInfo[key]; // installed, version, path
+ if (info) {
+ var item = that.renderPackageItem(key, info, idx);
+ innerFuncCode.append(item);
+ }
+ });
+ $(that.wrapSelector('.vp-pm-table')).html(innerFuncCode.toString());
+
+ // bind item menu event
+ that.bindItemEvent();
+ }).catch(function() {
+
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }
+
+ }
+
+ return PackageManager;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/PopupComponent.js b/visualpython/js/com/component/PopupComponent.js
new file mode 100644
index 00000000..60b37260
--- /dev/null
+++ b/visualpython/js/com/component/PopupComponent.js
@@ -0,0 +1,1388 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : PopupComponent.js
+ * Author : Black Logic
+ * Note : Popup Components for rendering objects
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] PopupComponent
+//============================================================================
+// CHROME: notebook/js/codemirror-ipython
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object"){ // CommonJS
+ if (vpExtType === 'lab' || vpExtType === 'lite') {
+ mod(require("codemirror/lib/codemirror"),
+ require("codemirror/mode/python/python")
+ );
+ } else {
+ mod(requirejs("codemirror/lib/codemirror"),
+ requirejs("codemirror/mode/python/python")
+ );
+ }
+ } else if (typeof define == "function" && define.amd){ // AMD
+ define('notebook/js/codemirror-ipython',["codemirror/lib/codemirror",
+ "codemirror/mode/python/python"], mod);
+ } else {// Plain browser env
+ mod(CodeMirror);
+ }
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineMode("ipython", function(conf, parserConf) {
+ var pythonConf = {};
+ for (var prop in parserConf) {
+ if (parserConf.hasOwnProperty(prop)) {
+ pythonConf[prop] = parserConf[prop];
+ }
+ }
+ pythonConf.name = 'python';
+ pythonConf.singleOperators = new RegExp("^[\\+\\-\\*/%&|@\\^~<>!\\?]");
+ if (pythonConf.version === 3) {
+ pythonConf.identifiers = new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*");
+ } else if (pythonConf.version === 2) {
+ pythonConf.identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+ }
+ return CodeMirror.getMode(conf, pythonConf);
+ }, 'python');
+
+ CodeMirror.defineMIME("text/x-ipython", "ipython");
+});
+
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/popupComponent.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/popupComponent'), // INTEGRATION: unified version of css loader
+ '../com_util',
+ '../com_Const',
+ '../com_String',
+ '../com_interface',
+ './Component',
+ './DataSelector',
+ './HelpViewer',
+
+ /** codemirror */
+ 'codemirror/lib/codemirror',
+ 'codemirror/mode/python/python',
+ 'codemirror/addon/display/placeholder',
+ 'codemirror/addon/display/autorefresh',
+ // 'notebook/js/codemirror-ipython' // LAB: disabled to avoid error FIXME:
+], function(popupComponentHtml, popupComponentCss
+ , com_util, com_Const, com_String, com_interface, Component, DataSelector, HelpViewer, codemirror
+) {
+ 'use strict';
+
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * Component
+ */
+ class PopupComponent extends Component {
+ constructor(state={ config: { id: 'popup', name: 'Popup title', path: 'path/file', category: '' }}, prop={}) {
+ // CHROME: FIXME: #site -> .notebook-vertical
+ // super($('#site'), state, prop);
+ super($(vpConfig.parentSelector), state, prop);
+ }
+
+ _init() {
+ this.eventTarget = '#vp_wrapper';
+ var { config, ...state } = this.state;
+ this.state = state;
+ var { id, name, path, category, ...restConfig } = config;
+ this.id = id;
+ this.name = name;
+ this.path = path;
+ this.category = category;
+
+ this.config = {
+ sizeLevel: 0, // 0: 400x400 / 1: 500x500 / 2: 600x500 / 3: 750x500 / 4:
+ executeMode: 'code', // cell execute mode
+ // show header bar buttons
+ installButton: false, // install button (#popupInstall) // FIXME: after creating packagemanager, deprecate it
+ importButton: false, // import library button (#popupImport)
+ packageButton: false, // package manager button (#popupPackage)
+ // show view box
+ codeview: true,
+ dataview: true,
+ helpview: false,
+ // show footer
+ runButton: true,
+ footer: true,
+ // run type : run / run-save / add
+ runType: 'run',
+ // position and size
+ position: { right: 10, top: 120 },
+ size: { width: 400, height: 550 },
+ // additional modes and infos
+ saveOnly: false, // apply mode
+ resizable: true,
+ autoScroll: true,
+ checkModules: [], // module aliases or function names
+ docs: 'https://visual-python.gitbook.io/docs/getting-started/welcome-to-visual-python',
+ helpInfo: {
+ content: '', // method to show using help() ex) pd.DataFrame
+ useHelp: true, // custom text to show on help viewer
+ importCode: '' // import code for help
+ },
+ ...restConfig
+ };
+
+ // check BoardFrame width and set initial position of popup
+ let boardWidth = $('#vp_boardFrame').width();
+ this.config.position.right = boardWidth + 10;
+
+ this.cmPythonConfig = {
+ mode: {
+ name: 'python',
+ version: 3,
+ singleLineStringErrors: false
+ },
+ height: '100%',
+ width: '100%',
+ indentUnit: 4,
+ lineNumbers: true,
+ matchBrackets: true,
+ autoRefresh: true,
+ theme: "ipython",
+ extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
+ }
+ this.cmReadonlyConfig = {
+ ...this.cmPythonConfig,
+ readOnly: true,
+ lineNumbers: false,
+ scrollbarStyle: "null"
+ }
+
+ this.cmCodeview = null;
+ this.cmCodeList = [];
+
+ this.helpViewer = undefined;
+ }
+
+ wrapSelector(selector='') {
+ var sbSelector = new com_String();
+ var cnt = arguments.length;
+ if (cnt < 2) {
+ // if there's no more arguments
+ sbSelector.appendFormat(".vp-popup-frame.{0} {1}", this.uuid, selector);
+ } else {
+ // if there's more arguments
+ sbSelector.appendFormat(".vp-popup-frame.{0}", this.uuid);
+ for (var idx = 0; idx < cnt; idx++) {
+ sbSelector.appendFormat(" {0}", arguments[idx]);
+ }
+ }
+ return sbSelector.toString();
+ }
+
+ /**
+ * Add codemirror object
+ * usage:
+ * this._addCodemirror('code', this.wrapSelector('#code'));
+ * @param {String} key stateKey
+ * @param {String} selector textarea class name
+ * @param {boolean} type code(python)/readonly/markdown
+ * @param {Object} etcOpt { events:[{key, callback}, ...] }
+ * @returns Object { key, selector, type, cm, ... }
+ */
+ _addCodemirror(key, selector, type='code', etcOpt={}) {
+ this.cmCodeList.push({ key: key, selector: selector, type: type, cm: null, ...etcOpt });
+ return this.cmCodeList[this.cmCodeList.length - 1];
+ }
+
+ /**
+ * bind codemirror
+ * @param {string} selector
+ */
+ _bindCodemirror() {
+ // codemirror editor (if available)
+ for (let i = 0; i < this.cmCodeList.length; i++) {
+ let cmObj = this.cmCodeList[i];
+ if (cmObj.cm == null) {
+ let cm = this.initCodemirror(cmObj);
+ cmObj.cm = cm;
+ }
+ }
+
+ // code view
+ if (this.config.codeview) {
+ if (!this.cmCodeview) {
+ // codemirror setting
+ let selector = this.wrapSelector('.vp-popup-codeview-box textarea');
+ let textarea = $(selector);
+ if (textarea && textarea.length > 0) {
+ this.cmCodeview = codemirror.fromTextArea(textarea[0], this.cmReadonlyConfig);
+ } else {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'No text area to create codemirror. (selector: '+selector+')');
+ }
+ } else {
+ this.cmCodeview.refresh();
+ }
+ }
+ }
+
+ /**
+ * Initialize codemirror
+ * @param {Object} cmObj { key, selector, type, ... }
+ * - key : key to save its value as state (this.state[key])
+ * - selector : selector to distinguish codemirror tag (textarea)
+ * ex) this.wrapSelector('.cm-tag')
+ * - type : code / readonly / markdown
+ * - events : list of event objects
+ * ex) [{ key: 'change', callback: function() { ; } }]
+ */
+ initCodemirror(cmObj) {
+ let {key, selector, type, events} = cmObj;
+ let that = this;
+
+ let cmCode = null;
+ let targetTag = $(selector);
+ let cmConfig = this.cmPythonConfig;
+ if (type == 'readonly') {
+ cmConfig = {
+ ...cmConfig,
+ readOnly: true,
+ lineNumbers: false,
+ scrollbarStyle: "null"
+ }
+ } else if (type == 'markdown') {
+ cmConfig = {
+ ...cmConfig,
+ mode: 'markdown'
+ }
+ }
+
+ if (targetTag && targetTag.length > 0) {
+ cmCode = codemirror.fromTextArea(targetTag[0], cmConfig);
+ if (cmCode) {
+ // add class on text area
+ if (type != 'readonly') {
+ $(selector).parent().find('.CodeMirror').addClass('vp-writable-codemirror');
+ }
+ cmCode.on('focus', function() {
+ // disable other shortcuts
+ com_interface.disableOtherShortcut();
+ });
+ cmCode.on('blur', function(instance, evt) {
+ // enable other shortcuts
+ com_interface.enableOtherShortcut();
+ // instance = codemirror
+ // save its code to textarea component
+ instance.save();
+ that.state[key] = targetTag.val();
+ });
+ // bind events
+ events && events.forEach(evObj => {
+ cmCode.on(evObj.key, evObj.callback);
+ });
+ vpLog.display(VP_LOG_TYPE.DEVELOP, key, cmCode);
+ }
+ } else {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'No text area to bind codemirror. (selector: '+selector+')');
+ }
+
+ return cmCode;
+ }
+
+ setCmValue(key, value) {
+ let targetCmObj = this.cmCodeList.filter(obj => obj.key == key);
+ if (targetCmObj.length > 0) {
+ let cm = targetCmObj[0].cm;
+ if (cm) {
+ cm.setValue(value);
+ cm.save();
+ setTimeout(function () {
+ cm.refresh();
+ }, 1);
+ }
+ }
+ }
+
+ addCheckModules(module) {
+ if (this.config.checkModules.includes(module)) {
+ return ;
+ }
+ this.config.checkModules.push(module);
+ }
+
+ _bindEvent() {
+ var that = this;
+ // Popup click / focus event
+ $(this.wrapSelector()).on('click focus', function(evt) {
+ // Close on blur
+ if ($(that.wrapSelector('.vp-popup-button')).find(evt.target).length == 0) {
+ if (!$(evt.target).hasClass('vp-popup-codeview-box')
+ && $(that.wrapSelector('.vp-popup-codeview-box')).find(evt.target).length == 0) {
+ that.closeView('code');
+ }
+ }
+ if ($(that.wrapSelector('.vp-popup-button')).find(evt.target).length == 0) {
+ if (!$(evt.target).hasClass('vp-popup-dataview-box')
+ && $(that.wrapSelector('.vp-popup-dataview-box')).find(evt.target).length == 0) {
+ that.closeView('data');
+ }
+ }
+ });
+ // Close popup event
+ $(this.wrapSelector('.vp-popup-close')).on('click', function(evt) {
+ if (that.getTaskType() === 'task') {
+ $(that.eventTarget).trigger({
+ type: 'remove_option_page',
+ component: that
+ });
+ } else {
+ // if it's block, just hide it
+ $(that.eventTarget).trigger({
+ type: 'close_option_page',
+ component: that
+ });
+ }
+ });
+ // Toggle operation (minimize)
+ $(this.wrapSelector('.vp-popup-toggle')).on('click', function(evt) {
+ evt.stopPropagation();
+ that.hide();
+ });
+ // Maximize operation
+ $(this.wrapSelector('.vp-popup-maximize')).on('click', function(evt) {
+ // save position
+ that.config.position = $(that.wrapSelector()).position();
+ // save size
+ that.config.size = {
+ width: $(that.wrapSelector()).width(),
+ height: $(that.wrapSelector()).height()
+ }
+ // maximize popup
+ $(that.wrapSelector()).css({
+ width: '100%',
+ height: '100%',
+ top: 0,
+ left: 0
+ });
+ // show / hide buttons
+ $(this).hide();
+ $(that.wrapSelector('.vp-popup-return')).show();
+ });
+ // Return operation
+ $(this.wrapSelector('.vp-popup-return')).on('click', function(evt) {
+ // return size
+ $(that.wrapSelector()).css({
+ width: that.config.size.width + 'px',
+ height: that.config.size.height + 'px',
+ top: that.config.position.top,
+ left: that.config.position.left
+ });
+ // show / hide buttons
+ $(this).hide();
+ $(that.wrapSelector('.vp-popup-maximize')).show();
+ });
+
+ // Click install package
+ $(this.wrapSelector('#popupInstall')).on('click', function() {
+ // add install codes
+ var codes = that.generateInstallCode();
+ codes && codes.forEach(code => {
+ if (vpConfig.extensionType === 'lite') {
+ code = code.replace('!', '%');
+ }
+ com_interface.insertCell('code', code, true, that.getSigText());
+ });
+ });
+
+ // Click import library
+ $(this.wrapSelector('#popupImport')).on('click', function() {
+ // add import codes
+ var codes = that.generateImportCode();
+ codes && codes.forEach(code => {
+ // create block and run it
+ $('#vp_wrapper').trigger({
+ type: 'create_option_page',
+ blockType: 'block',
+ menuId: 'lgExe_code',
+ menuState: { taskState: { code: code } },
+ afterAction: 'run'
+ });
+ });
+ });
+
+ // Click package manager
+ $(this.wrapSelector('#popupPackage')).on('click', function() {
+ // TODO:
+ });
+
+
+ // Focus recognization
+ $(this.wrapSelector()).on('click', function() {
+ $(that.eventTarget).trigger({
+ type: 'focus_option_page',
+ component: that
+ });
+ });
+
+ // save state values
+ $(document).on('change', this.wrapSelector('.vp-state'), function() {
+ that._saveSingleState($(this)[0]);
+ });
+
+ // click input box with selection
+ $(document).on('focus', this.wrapSelector('input'), function() {
+ $(this).select();
+ });
+
+ // Click buttons
+ $(this.wrapSelector('.vp-popup-button')).on('click', function(evt) {
+ var btnType = $(this).data('type');
+ switch(btnType) {
+ case 'code':
+ if ($(that.wrapSelector('.vp-popup-codeview-box')).is(':hidden')) {
+ that.openView('code');
+ } else {
+ that.closeView('code');
+ }
+ evt.stopPropagation();
+ break;
+ case 'data':
+ if ($(that.wrapSelector('.vp-popup-dataview-box')).is(':hidden')) {
+ that.openView('data');
+ } else {
+ that.closeView('data');
+ }
+ evt.stopPropagation();
+ break;
+ case 'help':
+ if ($(that.wrapSelector('.vp-popup-dataview-box')).is(':hidden')) {
+ that.openView('help');
+ } else {
+ that.closeView('help');
+ }
+ evt.stopPropagation();
+ break;
+ case 'cancel':
+ if (that.getTaskType() === 'task') {
+ $(that.eventTarget).trigger({
+ type: 'remove_option_page',
+ component: that
+ });
+ } else {
+ // if it's block, just hide it
+ $(that.eventTarget).trigger({
+ type: 'close_option_page',
+ component: that
+ });
+ }
+ break;
+ case 'run':
+ var result = that.run();
+ if (result) {
+ // that.save();
+ that.close();
+ }
+ break;
+ case 'show-detail':
+ $(that.wrapSelector('.vp-popup-run-detailbox')).show();
+ // set run button
+ vpConfig.getData('runType', 'vpcfg').then(function(data) {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'Runtype get data', data);
+ that._setDefaultRunType(data);
+ });
+ evt.stopPropagation();
+ break;
+ case 'save':
+ that.save();
+ break;
+ case 'run-save':
+ var result = that.run();
+ if (result) {
+ that.save();
+ }
+ break;
+ case 'add':
+ var result = that.run(false);
+ if (result) {
+ // that.save();
+ that.close();
+ }
+ break;
+ }
+ });
+ // Click detail radio
+ $(this.wrapSelector('.vp-popup-run-type')).on('click', function(evt) {
+ let runType = $(that.wrapSelector('.vp-popup-run-type[name=runType]:checked')).val();
+ // save as vpConfig
+ vpConfig.setData({runType: runType}, 'vpcfg');
+ that._setDefaultRunType(runType);
+ });
+ // Click detail buttons
+ $(this.wrapSelector('.vp-popup-detail-action-button')).on('click', function(evt) {
+ var btnType = $(this).data('type');
+ vpConfig.setData({runType: btnType}, 'vpcfg');
+ that._setDefaultRunType(btnType); // run, run-save, add
+ switch(btnType) {
+ // case 'apply':
+ // that.save();
+ // break;
+ case 'run':
+ var result = that.run();
+ if (result) {
+ // that.save();
+ that.close();
+ }
+ break;
+ case 'run-save':
+ var result = that.run();
+ if (result) {
+ that.save();
+ }
+ break;
+ case 'add':
+ var result = that.run(false);
+ if (result) {
+ // that.save();
+ that.close();
+ }
+ break;
+ }
+ });
+ // Close event for inner popup
+ $(this.wrapSelector('.vp-inner-popup-close')).on('click', function(evt) {
+ that.closeInnerPopup();
+ });
+ // Click button event for inner popup
+ $(this.wrapSelector('.vp-inner-popup-button')).on('click', function(evt) {
+ let btnType = $(this).data('type');
+ switch(btnType) {
+ case 'cancel':
+ that.closeInnerPopup();
+ break;
+ case 'ok':
+ that.handleInnerOk();
+ break;
+ }
+ });
+
+ // blur on code, dataview
+ $(this.wrapSelector('.vp-popup-codeview-box')).on('hide', function() {
+ that.closeView('code');
+ });
+ $(this.wrapSelector('.vp-popup-dataview-box')).on('hide', function() {
+ that.closeView('data');
+ });
+
+ // focus on data selector input
+ $(this.wrapSelector('.vp-data-selector')).on('focus', function(evt) {
+
+ });
+
+ // click on data selector input filter
+ $(this.wrapSelector('.vp-data-selector')).on('click', function(evt) {
+
+ });
+ }
+
+ _unbindEvent() {
+ $(document).off('change', this.wrapSelector('.vp-state'));
+ $(document).off('focus', this.wrapSelector('input'));
+ }
+
+ _bindDraggable() {
+ var that = this;
+ let containment = 'body';
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ containment = '#main';
+ }
+ $(this.wrapSelector()).draggable({
+ handle: '.vp-popup-title',
+ containment: containment,
+ start: function(evt, ui) {
+ // check focused
+ $(that.eventTarget).trigger({
+ type: 'focus_option_page',
+ component: that
+ });
+ }
+ });
+
+ // inner popup draggable
+ $(this.wrapSelector('.vp-inner-popup-box')).draggable({
+ handle: '.vp-inner-popup-title',
+ containment: 'parent'
+ });
+ }
+
+ _unbindResizable() {
+ $(this.wrapSelector()).resizable('disable');
+ }
+
+ _bindResizable() {
+ let that = this;
+ $(this.wrapSelector()).resizable({
+ handles: 'all',
+ start: function(evt, ui) {
+ // show / hide buttons
+ $(that.wrapSelector('.vp-popup-return')).hide();
+ $(that.wrapSelector('.vp-popup-maximize')).show();
+ }
+ });
+ }
+
+ templateForBody() {
+ /** Implementation needed */
+ return '';
+ }
+
+ template() {
+ this.$pageDom = $(popupComponentHtml.replaceAll('${vp_base}', com_Const.BASE_PATH));
+ // set title
+ // this.$pageDom.find('.vp-popup-title').text(this.category + ' > ' + this.name);
+ if (this.category && this.category !== '') {
+ this.$pageDom.find('.vp-popup-title').html(`
${this.name} `);
+ } else {
+ this.$pageDom.find('.vp-popup-title').html(`
${this.name} `);
+ }
+ // set body
+ let bodyTemplate = this.templateForBody();
+ // CHROME: check url keyword and replace it
+ if (bodyTemplate) {
+ if (typeof bodyTemplate === 'string') {
+ // string replacement
+ bodyTemplate = bodyTemplate.replaceAll('${vp_base}', com_Const.BASE_PATH);
+ } else {
+ // object = jquery object
+
+ }
+ }
+ this.$pageDom.find('.vp-popup-content').html(bodyTemplate);
+ return this.$pageDom;
+ }
+
+ /**
+ * Render page
+ * @param {Object} config configure whether to use buttons or not
+ */
+ render(inplace=false) {
+ super.render(inplace);
+
+ let {
+ installButton, importButton, packageButton,
+ codeview, dataview, helpview, runButton, footer,
+ sizeLevel, position, autoScroll, docs
+ } = this.config;
+
+ // apply link to docs
+ if (docs) {
+ $(this.wrapSelector('.vp-popup-docs')).prop('href', docs);
+ }
+ // import & package manager button hide/show
+ if (!installButton) { // FIXME: Deprecated after creating package manager
+ $(this.wrapSelector('#popupInstall')).hide();
+ }
+ if (!importButton) {
+ $(this.wrapSelector('#popupImport')).hide();
+ }
+ if (!packageButton) {
+ $(this.wrapSelector('#popupPackage')).hide();
+ }
+ if (installButton || importButton || packageButton) {
+ // resize height
+ $(this.wrapSelector('.vp-popup-content')).css({
+ 'height': 'calc(100% - 30px)'
+ });
+ } else {
+ $(this.wrapSelector('.vp-popup-content')).css({
+ 'height': '100%'
+ });
+ }
+
+ // codeview & dataview button hide/show
+ if (!codeview) {
+ $(this.wrapSelector('.vp-popup-button[data-type="code"]')).hide();
+ }
+ if (!dataview) {
+ $(this.wrapSelector('.vp-popup-button[data-type="data"]')).hide();
+ }
+ if (!helpview) {
+ $(this.wrapSelector('.vp-popup-button[data-type="help"]')).hide();
+ }
+
+ // run button
+ if (!runButton) {
+ $(this.wrapSelector('.vp-popup-runadd-box')).hide();
+ }
+
+ // footer
+ if(!footer) {
+ $(this.wrapSelector('.vp-popup-footer')).hide();
+ // set body wider
+ $(this.wrapSelector('.vp-popup-body')).css({
+ 'height': 'calc(100% - 30px)'
+ })
+ } else {
+ // set run button
+ let that = this;
+ vpConfig.getData('runType', 'vpcfg').then(function(data) {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'Runtype get data', data);
+ that._setDefaultRunType(data);
+ });
+ }
+
+
+ // popup-frame size
+ switch (sizeLevel) {
+ case 1:
+ this.config.size = { width: 500, height: 550 };
+ break;
+ case 2:
+ this.config.size = { width: 600, height: 550 };
+ break;
+ case 3:
+ this.config.size = { width: 760, height: 550 };
+ break;
+ case 4:
+ this.config.size = { width: 840, height: 550 };
+ break;
+ case 5:
+ this.config.size = { width: 1064, height: 550 };
+ break;
+ }
+
+ if (autoScroll) {
+ $(this.wrapSelector('.vp-popup-body')).addClass('vp-scrollbar');
+ }
+
+ // set detailed size
+ $(this.wrapSelector()).css({
+ width: this.config.size.width + 'px',
+ height: this.config.size.height + 'px'
+ });
+
+ // position
+ $(this.wrapSelector()).css({ top: position.top, right: position.right });
+
+ // set apply mode
+ if (this.config.saveOnly) {
+ this.setSaveOnlyMode();
+ }
+
+ this._bindDraggable();
+ if (this.config.resizable) {
+ this._bindResizable();
+ }
+ }
+
+ templateForInnerPopup() {
+ /** Implementation needed */
+ return '';
+ }
+
+ /**
+ * Render inner popup for selecting columns
+ * @returns Inner popup page dom
+ */
+ renderInnerPopup() {
+ $(this.wrapSelector('.vp-inner-popup-body')).html(this.templateForInnerPopup());
+
+
+ // set position to center
+ let width = $(this.wrapSelector('.vp-inner-popup-box')).width();
+ let height = $(this.wrapSelector('.vp-inner-popup-box')).height();
+
+ $(this.wrapSelector('.vp-inner-popup-box')).css({
+ left: 'calc(50% - ' + parseInt(width/2) + 'px)',
+ top: 'calc(50% - ' + parseInt(height/2) + 'px)',
+ })
+ }
+
+ templateForDataView() {
+ /** Implementation needed */
+ return '';
+ }
+
+ renderDataView() {
+ $('.vp-popup-dataview-box').html('');
+ $('.vp-popup-dataview-box').html(this.templateForDataView());
+ }
+
+ /**
+ * Generated on clicking Install Package button
+ * @returns Array of installment codes
+ */
+ generateInstallCode() {
+ /** Implementation needed - Generated on clicking Install Package button */
+ return [];
+ }
+
+ generateImportCode() {
+ /** Implementation needed - Generated on clicking Import Library button */
+ return [];
+ }
+
+ generateCode() {
+ /** Implementation needed */
+ return '';
+ }
+
+ load() {
+
+ }
+
+ loadState() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, this.state);
+
+ let that = this;
+ Object.keys(this.state).forEach(key => {
+ if (key && key !== '' && key !== 'config') {
+ let tag = $(that.wrapSelector('#' + key) + ', ' + that.wrapSelector('input[name="' + key + '"]'));
+ let tagName = $(tag).prop('tagName');
+ let savedValue = that.state[key];
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType === 'text' || inputType === 'number' || inputType === 'hidden') {
+ $(tag).val(savedValue);
+ break;
+ }
+ if (inputType === 'checkbox') {
+ $(tag).prop('checked', savedValue);
+ break;
+ }
+ if (inputType === 'radio') {
+ $(tag).filter(`[value="${savedValue}"]`).prop('checked', true);
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(savedValue);
+ break;
+ }
+ }
+ });
+ }
+
+ saveState() {
+ /** Implementation needed */
+ let that = this;
+ $(this.wrapSelector('.vp-state')).each((idx, tag) => {
+ that._saveSingleState(tag);
+ });
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'savedState', that.state);
+ }
+
+ _setDefaultRunType(runType) {
+ if (runType == undefined || runType == null || runType === '') {
+ runType = 'run'; // default = run
+ }
+ this.config.runType = runType;
+ $(this.wrapSelector(`.vp-popup-run-type[value="${runType}"]`)).prop('checked', true);
+ $(this.wrapSelector('.vp-popup-run-button')).attr('data-type', runType);
+ let runTitle = 'Run code'; // when runType is 'run'
+ switch (runType) {
+ case 'run-save':
+ runTitle = 'Save to block & Run code';
+ break;
+ case 'add':
+ runTitle = 'Add code to cell';
+ break;
+ }
+ $(this.wrapSelector('.vp-popup-run-button')).prop('title', runTitle);
+ }
+
+ _getTagValue(tag) {
+ let id = tag.id;
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let newValue = '';
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'checkbox') {
+ newValue = $(tag).prop('checked');
+ } else if (inputType == 'radio') {
+ let radioGroup = $(tag).prop('name');
+ let checked = $(tag).prop('checked');
+ if (checked === true) {
+ id = radioGroup;
+ newValue = $(tag).val();
+ } else {
+ return ;
+ }
+ } else {
+ // inputType == 'text' || inputType == 'number' || inputType == 'hidden' || inputType == 'color' || inputType == 'range'
+ newValue = $(tag).val();
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ newValue = $(tag).val();
+ if (!newValue) {
+ newValue = '';
+ }
+ break;
+ }
+ return newValue;
+ }
+
+ _saveSingleState(tag) {
+ let id = tag.id;
+ let customKey = $(tag).data('key');
+
+ let newValue = this._getTagValue(tag);
+ // if custom key is available, use it
+ if (customKey && customKey != '') {
+ // allow custom key until level 2
+ let customKeys = customKey.split('.');
+ if (customKeys.length === 3) {
+ this.state[customKeys[0]][customKeys[1]][customKeys[2]] = newValue;
+ } else if (customKeys.length === 2) {
+ this.state[customKeys[0]][customKeys[1]] = newValue;
+ } else {
+ this.state[customKey] = newValue;
+ }
+ } else {
+ this.state[id] = newValue;
+ }
+ }
+
+ getSigText() {
+ let sigText = '';
+ if (this.getTaskType() == 'block') {
+ let block = this.taskItem;
+ sigText = block.sigText;
+ } else {
+ try {
+ let menuGroup = this.path.split(' - ')[1];
+ let menuGroupLabel = vpConfig.getMenuGroupLabel(menuGroup);
+ if (menuGroupLabel != undefined && menuGroupLabel !== '') {
+ sigText = menuGroupLabel + ' > ' + this.name;
+ } else {
+ sigText = this.name;
+ }
+ } catch {}
+ }
+ return sigText;
+ }
+
+ /**
+ * Check if required option is filled
+ * @returns true if it's ok / false if there is empty required option
+ */
+ checkRequiredOption() {
+ let requiredFilled = true;
+ let requiredTags = $(this.wrapSelector('input[required=true]:visible') + ',' + this.wrapSelector('input[required=required]:visible'));
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'checkRequiredOption', this, requiredTags);
+
+ if (requiredTags) {
+ for (let i = 0; i < requiredTags.length; i++) {
+ let thisTag = $(requiredTags[i]);
+ // if it's visible and empty, focus on it
+ if (thisTag.is(':visible') && thisTag.val() == '') {
+ $(requiredTags[i]).focus();
+ requiredFilled = false;
+ break;
+ }
+ }
+ }
+
+ if (requiredFilled) {
+ requiredFilled = this.checkBeforeRun();
+ }
+
+ return requiredFilled;
+ }
+
+ /**
+ * Check options and do some operation before run
+ * @returns {boolean} check options and returns true or false (false will stop code running)
+ */
+ checkBeforeRun() {
+ /** Implementation needed */
+
+ return true;
+ }
+
+ checkAndRunModules(execute=true, background=false) {
+ let sigText = this.getSigText();
+
+ let checkModules = this.config.checkModules;
+ return new Promise(function(resolve, reject) {
+ // CHROME: TODO: 9: checkmodule works strange...
+ if (checkModules.length > 0) {
+ vpKernel.checkModule(checkModules).then(function(resultObj) {
+ let { result } = resultObj;
+ vpLog.display(VP_LOG_TYPE.DEVELOP, resultObj);
+ let checkedList = JSON.parse(result);
+ let executeList = [];
+ checkedList && checkedList.forEach((mod, idx) => {
+ if (mod === false) {
+ let modInfo = vpConfig.getModuleCode(checkModules[idx]);
+ if (modInfo && modInfo?.code !== '') {
+ executeList.push(modInfo.code);
+ }
+ }
+ });
+ if (executeList && executeList.length > 0) {
+ com_interface.insertCell('code', executeList.join('\n'), execute, sigText);
+ }
+ resolve(executeList);
+ });
+ } else {
+ resolve([]);
+ }
+ // resolve([]);
+ });
+ }
+
+ run(execute=true, addcell=true) {
+ // check required
+ if (this.checkRequiredOption() === false) {
+ return false;
+ }
+
+ let mode = this.config.executeMode;
+ let sigText = this.getSigText();
+ let code = this.generateCode();
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, sigText, mode, code);
+
+ // check modules
+ this.checkAndRunModules(execute).then(function(executeList) {
+ if (addcell) {
+ if (Array.isArray(code)) {
+ // insert cells if it's array of codes
+ com_interface.insertCells(mode, code, execute, sigText);
+ } else {
+ com_interface.insertCell(mode, code, execute, sigText);
+ }
+ }
+ });
+ return true;
+ }
+
+ _beforeOpen() {
+ /** Implementation needed - Generated on clicking Install Package button */
+ }
+
+ /**
+ * Open popup
+ * - show popup
+ * - focus popup
+ * - bind codemirror
+ */
+ open(targetFrame=undefined) {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'open popup', this);
+ this.loadState();
+
+ this._beforeOpen();
+ if (targetFrame !== undefined) {
+ // hide popup frame
+ $(this.wrapSelector('.vp-popup-header')).hide();
+ $(this.wrapSelector('.vp-popup-footer')).hide();
+ // set width and height to 100%
+ $(this.wrapSelector()).css({
+ width: '100%',
+ height: '100%',
+ 'min-height': 'unset',
+ display: 'block',
+ position: 'initial',
+ border: '0px'
+ });
+ $(this.wrapSelector('.vp-popup-body')).css({
+ padding: '0px'
+ });
+ // show on targetFrame
+ $(this.wrapSelector()).appendTo($(targetFrame));
+ } else {
+ this.show();
+
+ // set popup position if its top-left side is outside of view
+ let pos = $(this.wrapSelector()).position();
+ if (pos) {
+ if (pos.top < 0) {
+ $(this.wrapSelector()).css({ top: 0 });
+ }
+ if (pos.left < 0) {
+ $(this.wrapSelector()).css({ left: 0 });
+ }
+ }
+ }
+
+ this._bindCodemirror();
+
+ if (targetFrame == undefined) {
+ $(this.eventTarget).trigger({
+ type: 'focus_option_page',
+ component: this
+ });
+ }
+ }
+
+ setSaveOnlyMode() {
+ // show save button only
+ $(this.wrapSelector('.vp-popup-runadd-box')).hide();
+ $(this.wrapSelector('.vp-popup-save-button')).show();
+ }
+
+ /**
+ * Close popup
+ * - remove popup
+ * - unbind event
+ */
+ close() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'close popup', this);
+ this.saveState();
+ if (this.getTaskType() === 'task') {
+ $(this.eventTarget).trigger({
+ type: 'remove_option_page',
+ component: this
+ });
+ } else {
+ // if it's block, just hide it
+ this.hide();
+ }
+ }
+
+ save() {
+ if (this.prop.finish && typeof this.prop.finish == 'function') {
+ var code = this.generateCode();
+ this.prop.finish(code, this.state);
+ }
+ $(this.eventTarget).trigger({
+ type: 'apply_option_page',
+ blockType: 'block',
+ component: this
+ });
+ }
+
+ remove() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'remove popup', this);
+ this._unbindResizable();
+ this._unbindEvent();
+ this.closeHelpView();
+ $(this.wrapSelector()).remove();
+ }
+
+ focus() {
+ $('.vp-popup-frame').removeClass('vp-focused');
+ $('.vp-popup-frame').css({ 'z-index': 1200 });
+ $(this.wrapSelector()).addClass('vp-focused');
+ $(this.wrapSelector()).css({ 'z-index': 1205 }); // move forward
+ // focus on its block
+ if (this.taskItem) {
+ this.taskItem.focusItem();
+ }
+ }
+
+ blur() {
+ $(this.wrapSelector()).removeClass('vp-focused');
+ // blur on its block
+ if (this.taskItem) {
+ this.taskItem.blurItem();
+ }
+ }
+
+ show() {
+ this.taskItem && this.taskItem.focusItem();
+ $(this.wrapSelector()).show();
+ }
+
+ showInstallButton() {
+ $(this.wrapSelector('#popupInstall')).show();
+ }
+
+ showImportButton() {
+ $(this.wrapSelector('#popupImport')).show();
+ }
+
+ hide() {
+ this.closeHelpView();
+ this.taskItem && this.taskItem.blurItem();
+ $(this.wrapSelector()).hide();
+ }
+
+ hideInstallButton() {
+ $(this.wrapSelector('#popupInstall')).hide();
+ }
+
+ hideImportButton() {
+ $(this.wrapSelector('#popupImport')).hide();
+ }
+
+ isHidden() {
+ return !$(this.wrapSelector()).is(':visible');
+ }
+
+ /**
+ * minimize and maximize
+ */
+ toggle() {
+ let $this = $(this.wrapSelector());
+ let isClosed = $this.hasClass('vp-close');
+ if (isClosed) {
+ // show
+ $this.removeClass('vp-close');
+ $(this.wrapSelector('.vp-popup-toggle')).attr('src', com_Const.IMAGE_PATH + 'tri_down_fill_dark.svg');
+ } else {
+ // hide
+ $this.addClass('vp-close');
+ $(this.wrapSelector('.vp-popup-toggle')).attr('src', com_Const.IMAGE_PATH + 'tri_right_fill_dark.svg');
+ }
+ }
+
+ /**
+ * Open view
+ * @param {*} viewType code / data
+ */
+ openView(viewType) {
+ if (viewType === 'code') {
+ this.saveState();
+ var code = this.generateCode();
+ let codeText = '';
+ if (Array.isArray(code)) {
+ codeText = code.join('\n');
+ } else {
+ codeText = code;
+ }
+ this.cmCodeview.setValue(codeText);
+ this.cmCodeview.save();
+
+ var that = this;
+ setTimeout(function() {
+ that.cmCodeview.refresh();
+ }, 1);
+ this.closeView('data');
+ $(this.wrapSelector('.vp-popup-codeview-box')).show();
+ } else if (viewType === 'data') {
+ this.renderDataView();
+ this.closeView('code');
+ $(this.wrapSelector('.vp-popup-dataview-box')).show();
+ } else if (viewType === 'help') {
+ this.closeView('code');
+ this.closeView('data');
+ this.openHelpView();
+ }
+ }
+
+ closeView(viewType) {
+ if (viewType === 'code') {
+ // reset codeview
+ if (this.cmCodeview) {
+ this.cmCodeview.setValue('');
+ this.cmCodeview.save();
+
+ var that = this;
+ setTimeout(function() {
+ that.cmCodeview.refresh();
+ }, 1);
+ }
+ } else if (viewType === 'data') {
+ // reset dataview
+ $(this.wrapSelector('.vp-popup-dataview-box')).html('');
+ }
+ // hide view
+ $(this.wrapSelector('.vp-popup-'+viewType+'view-box')).hide();
+ }
+
+ /**
+ * Open HelpViewer
+ * - only one helpviewer at once
+ */
+ openHelpView() {
+ this.closeHelpView();
+ this.helpViewer = new HelpViewer();
+ this.helpViewer.open(this.config.helpInfo.content, this.config.helpInfo.useHelp, this.config.helpInfo.importCode);
+ }
+
+ /**
+ * Close helpViewer
+ */
+ closeHelpView() {
+ if (this.helpViewer !== undefined) {
+ this.helpViewer.remove();
+ }
+ }
+
+ /**
+ * Set HelpViewer content
+ * @param {string} content
+ * @param {boolean} useHelp
+ * @param {string} importCode
+ */
+ setHelpContent(content, useHelp=true, importCode='') {
+ this.config.helpInfo = {
+ content: content,
+ useHelp: useHelp,
+ importCode: importCode
+ };
+ }
+
+ /**
+ * Open inner popup box
+ */
+ openInnerPopup(title) {
+ $(this.wrapSelector('.vp-inner-popup-title')).text(title);
+ $(this.wrapSelector('.vp-inner-popup-box')).show();
+
+ // focus on first input
+ $(this.wrapSelector('.vp-inner-popup-box input:not(:readonly):not(:disabled):visible:first')).focus();
+ // disable Jupyter key
+ com_interface.disableOtherShortcut();
+ }
+
+ /**
+ * Close inner popup box
+ */
+ closeInnerPopup() {
+ this.handleInnerCancel();
+ $(this.wrapSelector('.vp-inner-popup-box')).hide();
+ }
+
+ handleInnerCancel() {
+ /** Implementation needed */
+ }
+
+ handleInnerOk() {
+ /** Implementation needed */
+ }
+
+ //========================================================================
+ // Get / set
+ //========================================================================
+ getCodemirror(key) {
+ let filteredCm = this.cmCodeList.find(cmObj => cmObj.key == key);
+ return filteredCm;
+ }
+
+ //========================================================================
+ // Control task item
+ //========================================================================
+ setTaskItem(taskItem) {
+ this.taskItem = taskItem;
+ }
+
+ getTaskType() {
+ if (this.taskItem) {
+ if (this.taskItem.constructor.name == 'Block') {
+ return 'block';
+ }
+ if (this.taskItem.constructor.name == 'TaskItem') {
+ return 'task';
+ }
+ }
+ return null;
+ }
+
+ removeBlock() {
+ this.taskItem && this.taskItem.removeItem();
+ }
+ }
+
+ return PopupComponent;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/com/component/SampleComponent.js b/visualpython/js/com/component/SampleComponent.js
new file mode 100644
index 00000000..588372cd
--- /dev/null
+++ b/visualpython/js/com/component/SampleComponent.js
@@ -0,0 +1,66 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : SampleComponent.js
+ * Author : Black Logic
+ * Note : Sample Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] SampleComponent
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/Component'
+], function(com_String, Component) {
+
+ /**
+ * SampleComponent
+ * Add below code in /data/libraries.json
+ {
+ "id" : "apps_sample",
+ "type" : "function",
+ "level": 1,
+ "name" : "Sample",
+ "tag" : "SAMPLE,APPS",
+ "path" : "visualpython - apps - sample",
+ "desc" : "Sample app for testing",
+ "file" : "m_apps/SampleApp",
+ "apps" : {
+ "color": 4,
+ "icon": "apps/apps_white.svg"
+ }
+ }
+ */
+ class SampleComponent extends Component {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+
+ }
+
+ _bindEvent() {
+ /** Implement binding events */
+
+ }
+
+ template() {
+ /** Implement generating template */
+ var page = new com_String();
+
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+ /** Implement after rendering */
+
+ }
+
+ }
+
+ return SampleComponent;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/SuccessMessage.js b/visualpython/js/com/component/SuccessMessage.js
new file mode 100644
index 00000000..164dd7b2
--- /dev/null
+++ b/visualpython/js/com/component/SuccessMessage.js
@@ -0,0 +1,50 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : SuccessMessage.js
+ * Author : Black Logic
+ * Note : SuccessMessage
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] SuccessMessage
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/component/successMessage.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/component/successMessage'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/component/Component'
+], function(msgHtml, msgCss, com_Const, Component) {
+
+ /**
+ * SuccessMessage
+ */
+ class SuccessMessage extends Component {
+ constructor(title, timeout=1500) {
+ super($('#header'), { title: title, timeout: timeout });
+ }
+
+ template() {
+ return msgHtml.replaceAll('${vp_base}', com_Const.BASE_PATH);
+ }
+
+ render() {
+ super.render();
+
+ // set title
+ $(this.wrapSelector('.vp-successMessage-title')).text(this.state.title);
+
+ let that = this;
+ // remove after timeout
+ setTimeout( function() {
+ $(that.wrapSelector()).remove();
+ }, this.state.timeout);
+ }
+
+ }
+
+ return SuccessMessage;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/SuggestInput.js b/visualpython/js/com/component/SuggestInput.js
new file mode 100644
index 00000000..2c7fa96e
--- /dev/null
+++ b/visualpython/js/com/component/SuggestInput.js
@@ -0,0 +1,189 @@
+define([
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/Component',
+], function (com_util, com_String, Component) {
+ /**
+ * @class SuggestInput
+ * @constructor
+ */
+ class SuggestInput extends Component{
+ constructor() {
+ super(null, {});
+ }
+
+ _init() {
+ this._value = "";
+ this._placeholder = "Select variable";
+ this._compID = "";
+ this._additionalClass = "";
+ this._autoFocus = true;
+ this._normalFilter = true;
+ this._suggestList = new Array();
+ this._selectEvent = undefined;
+ this._attributes = {};
+ this._minLength = 0;
+ }
+
+ render() {
+ ;
+ }
+ /**
+ * value
+ * @param {String} value value
+ */
+ setValue(value = "") {
+ this._value = value;
+ }
+ /**
+ * placeholder
+ * @param {String} placeholder placeholder
+ */
+ setPlaceholder(placeholder = "") {
+ this._placeholder = placeholder;
+ }
+ /**
+ * Component id
+ * @param {String} compID
+ */
+ setComponentID(compID = "") {
+ this._compID = compID;
+ }
+ /**
+ * set auto focus on enter
+ * @param {boolean} autoFocus
+ */
+ setAutoFocus(autoFocus = true) {
+ this._autoFocus = autoFocus;
+ }
+ /**
+ * normal filter usage
+ * @param {String} normalFilter
+ */
+ setNormalFilter(normalFilter = true) {
+ this._normalFilter = normalFilter;
+ }
+ /**
+ * suggest list or object list [{ label, value } ...]
+ * @param {Array or Function} suggestList
+ */
+ setSuggestList(suggestList = new Array()) {
+ this._suggestList = suggestList;
+ }
+ /**
+ * show default list
+ * - true: autocomplete.minLength to 0
+ * - false: autocomplete.minLength to 1
+ * @param {bool} showDefaultList
+ */
+ setMinSearchLength(minLength) {
+ this._minLength = minLength;
+ }
+ /**
+ * Additional Class
+ * @param {String} additionalClass
+ */
+ addClass(additionalClass = "") {
+ if (additionalClass == "")
+ return;
+ this._additionalClass = com_util.formatString("{0} {1}", this._additionalClass, additionalClass);
+ }
+ addAttribute(key, value) {
+ this._attributes = {
+ ...this._attributes,
+ [key]: value
+ };
+ }
+ /**
+ * selection event
+ * @param {function} selectEvent
+ */
+ setSelectEvent(selectEvent) {
+ if (typeof selectEvent != "function") {
+ selectEvent = undefined;
+ }
+ this._selectEvent = selectEvent;
+ }
+ /**
+ * icon input box tag
+ * @returns html icon input text tag string
+ */
+ toTagString() {
+ var sbTagString = new com_String();
+ var that = this;
+
+ let minLength = this._minLength;
+
+ // make attributes
+ var attributes = Object.keys(this._attributes).map(key => key + '="' + this._attributes[key] + '"').join(" ");
+
+ sbTagString.appendFormatLine(`
`,
+ that.uuid, 'suggest-input-uninit', that._additionalClass, that._compID == "" ? "" : com_util.formatString("id='{0}'", that._compID), that._placeholder, that._value, attributes);
+
+ $(document).on(com_util.formatString("focus.init-{0}", that.uuid), com_util.formatString(".{0}.{1}", that.uuid, 'suggest-input-uninit'), function () {
+ $(document).unbind(com_util.formatString(".init-{0}", that.uuid));
+
+ $(com_util.formatString(".{0}", that.uuid)).removeClass('suggest-input-uninit').addClass('suggest-input');
+
+ $(com_util.formatString(".{0}", that.uuid)).autocomplete({
+ autoFocus: that._autoFocus,
+ minLength: minLength,
+ source: function (req, res) {
+ var srcList = typeof that._suggestList == "function" ? that._suggestList() : that._suggestList;
+ var returlList = new Array();
+ if (that._normalFilter) {
+ for (var idx = 0; idx < srcList.length; idx++) {
+ // srcList as object array
+ if (typeof srcList[idx] == "object") {
+ // { label: string, value: string } format
+ if (srcList[idx].label.toString().toLowerCase().includes(req.term.trim().toLowerCase())) {
+ returlList.push(srcList[idx]);
+ }
+ } else if (srcList[idx].toString().toLowerCase().includes(req.term.trim().toLowerCase()))
+ returlList.push(srcList[idx]);
+ }
+ } else {
+ returlList = srcList;
+ }
+ res(returlList);
+ },
+ select: function (evt, ui) {
+ let result = true;
+ // trigger change
+ $(this).val(ui.item.value);
+
+ if (typeof that._selectEvent == "function") {
+ result = that._selectEvent(ui.item.value, ui.item);
+ }
+ $(this).trigger('change');
+ if (result != undefined) {
+ return result;
+ }
+ return true;
+ }
+ }).focus(function() {
+ $(this).select();
+ $(com_util.formatString(".{0}", that.uuid)).autocomplete('search', $(com_util.formatString(".{0}", that.uuid)).val());
+ }).click(function() {
+ $(this).select();
+ $(com_util.formatString(".{0}", that.uuid)).autocomplete('search', $(com_util.formatString(".{0}", that.uuid)).val());
+ }).autocomplete('instance')._renderItem = function(ul, item) {
+ $(ul).addClass('vp-scrollbar-vertical');
+ $(ul).css('max-height', '250px');
+ if (item.dtype != undefined) {
+ return $('
').attr('data-value', item.value)
+ .append(`${item.label} | ${item.dtype}
`)
+ .appendTo(ul);
+ }
+ return $(' ').attr('data-value', item.value)
+ .append(`${item.label}
`)
+ .appendTo(ul);
+ };;
+ });
+
+ return sbTagString.toString();
+ }
+ }
+
+ return SuggestInput;
+});
\ No newline at end of file
diff --git a/visualpython/js/com/component/VarSelector.js b/visualpython/js/com/component/VarSelector.js
new file mode 100644
index 00000000..7305ea0c
--- /dev/null
+++ b/visualpython/js/com/component/VarSelector.js
@@ -0,0 +1,349 @@
+define([
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+], function(com_Const, com_String, com_util) {
+
+ const VP_VS_BOX = 'vp-vs-box';
+ const VP_VS_DATA_TYPE = 'vp-vs-data-type';
+ const VP_VS_VARIABLES = 'vp-vs-variables';
+ const VP_VS_TYPING_INPUT = 'vp-vs-typing-input';
+ const VP_VS_COLUMN_INPUT = 'vp-vs-column-input';
+ const VP_VS_REFRESH = 'vp-vs-refresh';
+
+ /**
+ * @class VarSelector
+ * @param {Array} dataTypes
+ * @param {String} defaultType
+ * @constructor
+ *
+ * using sample:
+ var varSelector = new VarSelector(['DataFrame', 'Series'], 'DataFrame');
+ $(this.wrapSelector('.vp-vs-tester')).html(varSelector.render());
+ */
+ class VarSelector {
+ constructor(dataTypes, defaultType = '', showOthers = true, useTyping = true) {
+ this.uuid = 'u' + com_util.getUUID();
+ this.label = {
+ 'others': 'Others',
+ 'typing': 'Typing'
+ };
+
+ this.boxClass = [];
+
+ this.id = '';
+ this.class = [];
+ this.attributes = {};
+
+ this.typeClass = []; // type selector class
+ this.varClass = []; // variable selector class
+ this.colClass = []; // column selector class
+
+ this.dataTypes = dataTypes;
+ if (defaultType == '') {
+ if (dataTypes.length > 0) {
+ defaultType = dataTypes[0];
+ } else {
+ }
+ }
+ this.state = {
+ selectedType: defaultType,
+ varList: [],
+ column: ''
+ };
+
+ this.defaultType = defaultType;
+ this.defaultValue = '';
+ this.defaultColumn = '';
+
+ this.showOthers = showOthers;
+ this.useTyping = useTyping;
+ this.useColumn = false;
+
+ this.reload();
+ this.bindEvent();
+ }
+ setComponentId(id) {
+ this.id = id;
+ }
+ addBoxClass(classname) {
+ this.boxClass.push(classname);
+ }
+ addClass(classname) {
+ this.class.push(classname);
+ }
+ addTypeClass(classname) {
+ this.typeClass.push(classname);
+ }
+ addVarClass(classname) {
+ this.varClass.push(classname);
+ }
+ addColClass(classname) {
+ this.colClass.push(classname);
+ }
+ addAttribute(key, value) {
+ this.attributes.push({ [key]: value });
+ }
+ setValue(value) {
+ if (value == null || value == undefined) {
+ value = '';
+ }
+ this.defaultValue = value;
+ if (value.includes('[') && value.includes(']') ) {
+ // divide it to variable / column
+ let startIdx = value.indexOf('[');
+ let endIdx = value.indexOf(']');
+ this.defaultValue = value.substring(0, startIdx);
+ this.defaultColumn = value.substring(startIdx + 1, endIdx);
+ }
+ }
+ setState(newState) {
+ this.state = {
+ ...this.state,
+ ...newState
+ }
+ }
+ setUseColumn(useColumn) {
+ this.useColumn = useColumn;
+ }
+ wrapSelector(selector = '') {
+ return com_util.formatString('.{0} {1}', this.uuid, selector);
+ }
+ render(defaultType = this.defaultType, defaultValue = this.defaultValue) {
+ var tag = new com_String();
+
+ // var selector box
+ tag.appendFormatLine('', VP_VS_BOX, this.uuid, this.boxClass.join(' '));
+
+ // // hidden input value
+ // tag.appendFormatLine('
',
+ // this.attributes.id? 'id="' + this.attributes.id + '"': '');
+ // data type selector
+ tag.appendFormatLine('
', VP_VS_DATA_TYPE, 'vp-select m', this.typeClass.join(' '));
+ this.dataTypes.forEach((v, i) => {
+ tag.appendFormatLine('{2} ', v,
+ defaultType == v ? 'selected' : '', v);
+ });
+ if (this.showOthers) {
+ tag.appendFormatLine('{1} ', 'others', this.label.others);
+ }
+ if (this.useTyping) {
+ tag.appendFormatLine('{1} ', 'typing', this.label.typing);
+ }
+ tag.appendLine(' '); // VP_VS_DATA_TYPE
+
+
+ // variable selctor
+ tag.appendLine(this.renderVariableList(this.state.varList));
+
+ var attrStr = Object.keys(this.attributes).map(key => key + '="' + this.attributes[key] + '"').join(' ');
+
+ // typing
+ tag.appendFormatLine('
',
+ VP_VS_TYPING_INPUT, 'vp-input m', this.class.join(' '),
+ 'Type your code',
+ this.id ? 'id="' + this.id + '"' : '',
+ defaultValue,
+ defaultType,
+ attrStr);
+
+ // column for dataframe
+ tag.appendFormatLine('
',
+ VP_VS_COLUMN_INPUT, 'vp-select m', this.colClass.join(' '),
+ (this.useColumn == true && defaultType == 'DataFrame'?'':'style="display: none;"'));
+
+ // reload
+ // LAB: img to url
+ // tag.appendFormatLine('
',
+ // VP_VS_REFRESH, 'Refresh variables', com_Const.IMAGE_PATH + 'refresh.svg');
+ tag.appendFormatLine('
',
+ VP_VS_REFRESH, 'Refresh variables');
+
+ tag.appendLine('
'); // VP_VS_BOX
+ return tag.toString();
+ }
+ reload() {
+ var that = this;
+ // load using kernel
+ var dataTypes = this.showOthers ? [] : this.dataTypes;
+ vpKernel.getDataList(dataTypes).then(function (resultObj) {
+ try {
+ let { result, type, msg } = resultObj;
+ var varList = JSON.parse(result);
+ that.state.varList = varList;
+ // render variable list
+ that.loadVariableList(varList);
+ } catch (ex) {
+ // console.log(ex);
+ }
+ });
+ }
+ renderVariableList(varList) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_VS_VARIABLES, 'vp-select m', this.varClass.join(' '),
+ this.state.selectedType == 'typing' ? 'style="display:none;"' : '');
+ varList.forEach(vObj => {
+ // varName, varType
+ var label = vObj.varName;
+ if (this.state.selectedType == 'others') {
+ label += com_util.formatString(' ({0})', vObj.varType);
+ }
+ tag.appendFormatLine('{3} ',
+ vObj.varName, vObj.varType,
+ this.defaultValue == vObj.varName ? 'selected' : '',
+ label);
+ });
+ tag.appendLine(' '); // VP_VS_VARIABLES
+ return tag.toString();
+ }
+ loadVariableList(varList) {
+ var filteredList = varList;
+ var that = this;
+ let dataTypes = this.dataTypes;
+ // Include various index types for Index type
+ var INDEX_TYPES = ['RangeIndex', 'CategoricalIndex', 'MultiIndex', 'IntervalIndex', 'DatetimeIndex', 'TimedeltaIndex', 'PeriodIndex', 'Int64Index', 'UInt64Index', 'Float64Index'];
+ // Include various groupby types for Groupby type
+ var GROUPBY_TYPES = ['DataFrameGroupBy', 'SeriesGroupBy']
+ if (dataTypes.indexOf('Index') >= 0) {
+ dataTypes = dataTypes.concat(INDEX_TYPES);
+ }
+ if (dataTypes.indexOf('GroupBy') >= 0) {
+ dataTypes = dataTypes.concat(GROUPBY_TYPES);
+ }
+
+ if (this.state.selectedType == 'others') {
+ filteredList = varList.filter(v => !dataTypes.includes(v.varType));
+ } else if (this.state.selectedType == 'typing') {
+ filteredList = [];
+ } else {
+ let filterDataTypes = [ this.state.selectedType ];
+ if (filterDataTypes.indexOf('Index') >= 0) {
+ filterDataTypes = filterDataTypes.concat(INDEX_TYPES);
+ }
+ if (filterDataTypes.indexOf('GroupBy') >= 0) {
+ filterDataTypes = filterDataTypes.concat(GROUPBY_TYPES);
+ }
+
+ filteredList = varList.filter(v => filterDataTypes.includes(v.varType));
+ }
+
+ // replace
+ $(this.wrapSelector('.' + VP_VS_VARIABLES)).replaceWith(function () {
+ return that.renderVariableList(filteredList);
+ });
+ $(this.wrapSelector('.' + VP_VS_VARIABLES)).trigger('change');
+ }
+ loadColumnList(varName) {
+ let that = this;
+ // get result and show on detail box
+ vpKernel.getColumnList(varName).then(function(resultObj) {
+ try {
+ let { result, type, msg } = resultObj;
+ var { list } = JSON.parse(result);
+
+ let newTag = new com_String();
+ newTag.appendFormatLine('',
+ VP_VS_COLUMN_INPUT, 'vp-select m', that.colClass.join(' '),
+ (that.useColumn == true && that.defaultType == 'DataFrame'?'':'style="display: none;"'));
+ newTag.appendFormatLine('{2} ',
+ '', '', '');
+ list && list.forEach(col => {
+ // label, value, dtype, array, location, category
+ newTag.appendFormatLine('{3} ',
+ col.value, col.dtype,
+ that.defaultColumn == col.value ? 'selected' : '',
+ col.label);
+ });
+ newTag.appendLine(' ');
+ // replace
+ $(that.wrapSelector('.' + VP_VS_COLUMN_INPUT)).replaceWith(function() {
+ return newTag.toString();
+ });
+ } catch (e) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'varSelector - bindColumnSource: not supported data type. ', e);
+ }
+ });
+ }
+ bindEvent() {
+ var that = this;
+ // data type selection
+ $(document).on('change', this.wrapSelector('.' + VP_VS_DATA_TYPE), function (event) {
+ // re-renderVariableList
+ var dataType = $(this).val();
+ that.state.selectedType = dataType;
+ if (dataType == 'typing') {
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).val('');
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).attr('data-type', '');
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).show();
+ $(that.wrapSelector('.' + VP_VS_VARIABLES)).hide();
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).trigger({
+ type: 'var_changed',
+ value: '',
+ dataType: ''
+ });
+ } else {
+ $(that.wrapSelector('.' + VP_VS_VARIABLES)).show();
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).hide();
+ // 1) load variable once
+ that.loadVariableList(that.state.varList);
+ // 2) load on every selection of data types
+ // that.reload();
+ }
+
+ if (that.useColumn == true) {
+ if (dataType == 'DataFrame') {
+ $(that.wrapSelector('.' + VP_VS_COLUMN_INPUT)).show();
+ } else {
+ $(that.wrapSelector('.' + VP_VS_COLUMN_INPUT)).hide();
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_VS_COLUMN_INPUT)).hide();
+ }
+ });
+
+ // variable selection
+ $(document).on('change', this.wrapSelector('.' + VP_VS_VARIABLES), function (event) {
+ var value = $(this).val();
+ var dataType = $(this).find('option:selected').attr('data-type');
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).val(value);
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).attr('data-type', dataType);
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).trigger({
+ type: 'var_changed',
+ value: value,
+ dataType: dataType
+ });
+
+ // if datatype == dataframe, change column list
+ if (that.useColumn == true && dataType == 'DataFrame') {
+ that.loadColumnList(value);
+ }
+ });
+
+ // column selection
+ $(document).on('change', this.wrapSelector('.' + VP_VS_COLUMN_INPUT), function(event) {
+ var value = $(that.wrapSelector('.' + VP_VS_VARIABLES)).val();
+ var colValue = $(this).val();
+ var newValue = value;
+ if (colValue != '') {
+ newValue += '[' + colValue + ']';
+ }
+
+ var dataType = $(this).find('option:selected').attr('data-type');
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).val(newValue);
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).attr('data-type', dataType);
+ $(that.wrapSelector('.' + VP_VS_TYPING_INPUT)).trigger({
+ type: 'var_changed',
+ value: newValue,
+ dataType: 'DataFrame'
+ });
+ });
+
+ // refresh
+ $(document).on('click', this.wrapSelector('.' + VP_VS_REFRESH), function() {
+ that.reload();
+ });
+ }
+ }
+
+ return VarSelector;
+})
\ No newline at end of file
diff --git a/visualpython/js/com/component/VarSelector2.js b/visualpython/js/com/component/VarSelector2.js
new file mode 100644
index 00000000..eb667f3f
--- /dev/null
+++ b/visualpython/js/com/component/VarSelector2.js
@@ -0,0 +1,381 @@
+define([
+ '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(com_Const, com_String, com_util, Component) {
+ /**
+ * @class VarSelector
+ * @constructor
+ */
+ class VarSelector extends Component{
+ constructor(parentTag, dataTypes=['DataFrame', 'Series', 'ndarray', 'list', 'dict'], defaultType='', showOthers=true, showFilterbox=true) {
+ super(null, {parentTag: parentTag, dataTypes: dataTypes, defaultType: defaultType, showOthers: showOthers, showFilterbox: showFilterbox});
+ }
+
+ _init() {
+ this._value = "";
+ this._placeholder = "Select variable";
+ this._compID = "";
+ this._additionalClass = "";
+ this._normalFilter = true;
+ this._suggestList = new Array();
+ this._selectEvent = undefined;
+ this._attributes = {};
+ this._minLength = 0;
+
+ this._parentTag = this.state.parentTag;
+ this._dataTypes = this.state.dataTypes;
+ this._defaultType = this.state.defaultType;
+ this._showOthers = this.state.showOthers;
+ this._showFilterbox = this.state.showFilterbox;
+ if (this._defaultType == '') {
+ if (this._dataTypes.length > 0) {
+ this._defaultType = this._dataTypes[0];
+ } else {
+ }
+ }
+
+ this.state = {
+ selectedType: this._defaultType,
+ varList: [],
+ column: ''
+ }
+
+ this.reload();
+ this.bindEvent();
+ }
+
+ render() {
+ ;
+ }
+
+ bindEvent() {
+ let that = this;
+
+ // bind Event on focus/click box
+ $(document).on(com_util.formatString("focus.init-{0} click.init-{1}", that.uuid, that.uuid), com_util.formatString(".{0}.{1}", that.uuid, 'vp-vs-uninit'), function () {
+ // unbind initial event
+ $(document).unbind(com_util.formatString(".init-{0}", that.uuid));
+ $(com_util.formatString(".{0}.{1}", that.uuid, 'vp-vs-uninit')).removeClass('vp-vs-uninit').addClass('vp-vs-init');
+
+ // bind autocomplete
+ that.bindAutocomplete();
+
+ // bind Event
+ $(that._parentTag).on('click', that.wrapSelector('.vp-vs-filter'), function(evt) {
+ // check disabled
+ if (!$(this).parent().find('input').is(':disabled')) {
+ // toggle filter box
+ let isOpen = $(that.wrapSelector('.vp-vs-filter-box')).hasClass('vp-inline-block');
+ $('.vp-vs-filter-box').removeClass('vp-inline-block');
+
+ if (!isOpen) {
+ // open filter box
+ $(that.wrapSelector('.vp-vs-filter-box')).addClass('vp-inline-block');
+ }
+ }
+ evt.stopPropagation();
+ });
+
+ $(that._parentTag).on('click', function(evt) {
+ let target = evt.target;
+ if ($(that.wrapSelector('.vp-vs-filter-box')).find(target).length > 0
+ || $(target).hasClass('vp-vs-filter-box')) {
+ // trigger focus
+ $(that.wrapSelector('.vp-vs-input')).trigger('focus');
+ }
+ });
+
+ $(that._parentTag).on('change', that.wrapSelector('.vp-vs-filter-select-all'), function() {
+ let checked = $(this).prop('checked');
+ // check all
+ $(that.wrapSelector('.vp-vs-filter-type')).prop('checked', checked);
+ // reload
+ that.reload().then(function() {
+ $(that.wrapSelector('.vp-vs-input')).trigger('focus');
+ });
+ });
+
+ $(that._parentTag).on('change', that.wrapSelector('.vp-vs-filter-type'), function() {
+ // if checked all
+ let allLength = $(that.wrapSelector('.vp-vs-filter-type')).length;
+ let checkedLength = $(that.wrapSelector('.vp-vs-filter-type:checked')).length;
+ if (allLength == checkedLength) {
+ $(that.wrapSelector('.vp-vs-filter-select-all')).prop('checked', true);
+ } else {
+ $(that.wrapSelector('.vp-vs-filter-select-all')).prop('checked', false);
+ }
+ that.reload().then(function() {
+ $(that.wrapSelector('.vp-vs-input')).trigger('focus');
+ });
+ });
+ });
+ }
+
+ /**
+ * value
+ * @param {String} value value
+ */
+ setValue(value = "") {
+ this._value = value;
+ }
+ /**
+ * placeholder
+ * @param {String} placeholder placeholder
+ */
+ setPlaceholder(placeholder = "") {
+ this._placeholder = placeholder;
+ }
+ /**
+ * Component id
+ * @param {String} compID
+ */
+ setComponentID(compID = "") {
+ this._compID = compID;
+ }
+ /**
+ * normal filter usage
+ * @param {String} normalFilter
+ */
+ setNormalFilter(normalFilter = true) {
+ this._normalFilter = normalFilter;
+ }
+ /**
+ * suggest list
+ * @param {Array or Function} suggestList
+ */
+ setSuggestList(suggestList = new Array()) {
+ this._suggestList = suggestList;
+ }
+ /**
+ * show default list
+ * - true: autocomplete.minLength to 0
+ * - false: autocomplete.minLength to 1
+ * @param {bool} showDefaultList
+ */
+ setMinSearchLength(minLength) {
+ this._minLength = minLength;
+ }
+ /**
+ * Additional Class
+ * @param {String} additionalClass
+ */
+ addClass(additionalClass = "") {
+ if (additionalClass == "")
+ return;
+ this._additionalClass = com_util.formatString("{0} {1}", this._additionalClass, additionalClass);
+ }
+ addAttribute(key, value) {
+ this._attributes = {
+ ...this._attributes,
+ [key]: value
+ };
+ }
+ /**
+ * selection event
+ * @param {function} selectEvent
+ */
+ setSelectEvent(selectEvent) {
+ if (typeof selectEvent != "function") {
+ selectEvent = undefined;
+ }
+ this._selectEvent = selectEvent;
+ }
+
+ reload() {
+ var that = this;
+ // load using kernel
+ let dataTypes = this._dataTypes;
+ let excludeTypes = [];
+ let othersChecked = this._showOthers;
+ // check filter
+ if ($(this.wrapSelector('.vp-vs-filter-box')).length > 0) {
+ let filterTypes = [];
+ let filterTypeTags = $(this.wrapSelector('.vp-vs-filter-type'));
+ filterTypeTags.each((i, tag) => {
+ let checked = $(tag).prop('checked');
+ let dtype = $(tag).data('dtype');
+ if (checked) {
+ if (dtype == 'others') {
+ othersChecked = true;
+ } else {
+ filterTypes.push(dtype);
+ }
+ } else {
+ if (dtype == 'others') {
+ othersChecked = false;
+ } else {
+ excludeTypes.push(dtype);
+ }
+ }
+ });
+ let allChecked = $(this.wrapSelector('.vp-vs-filter-select-all')).prop('checked');
+ if (allChecked) {
+ if (othersChecked) {
+ dataTypes = []; // load all types of variables
+ excludeTypes = [];
+ } else {
+ dataTypes = filterTypes;
+ }
+ } else {
+ if (othersChecked) {
+ dataTypes = [];
+ } else {
+ if (filterTypes.length == 0) {
+ // nothing checked
+ // no variable list
+ this.state.varList = [];
+ this._suggestList = [];
+ return new Promise(function(resolve, reject) {
+ resolve([]);
+ });
+ }
+ dataTypes = filterTypes;
+ }
+
+ }
+ } else {
+ dataTypes = [];
+ }
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'VarSelector2 - reload ', dataTypes, excludeTypes);
+
+ return new Promise(function(resolve, reject) {
+ vpKernel.getDataList(dataTypes, excludeTypes).then(function (resultObj) {
+ try {
+ let { result, type, msg } = resultObj;
+ var varList = JSON.parse(result);
+ // re-mapping variable list
+ varList = varList.map(obj => {
+ return {
+ label: obj.varName,
+ value: obj.varName,
+ dtype: obj.varType
+ };
+ });
+
+ // save variable list as state
+ that.state.varList = varList;
+ that._suggestList = varList;
+ resolve(varList);
+
+ } catch (ex) {
+ reject(ex);
+ }
+ });
+ });
+ }
+
+ bindAutocomplete() {
+ let that = this;
+ let minLength = this._minLength;
+
+ $(com_util.formatString(".{0} input", that.uuid)).autocomplete({
+ autoFocus: true,
+ minLength: minLength,
+ source: function (req, res) {
+ var srcList = typeof that._suggestList == "function" ? that._suggestList() : that._suggestList;
+ var returlList = new Array();
+ if (that._normalFilter) {
+ for (var idx = 0; idx < srcList.length; idx++) {
+ // srcList as object array
+ if (typeof srcList[idx] == "object") {
+ // { label: string, value: string } format
+ if (srcList[idx].label.toString().toLowerCase().includes(req.term.trim().toLowerCase())) {
+ returlList.push(srcList[idx]);
+ }
+ } else if (srcList[idx].toString().toLowerCase().includes(req.term.trim().toLowerCase()))
+ returlList.push(srcList[idx]);
+ }
+ } else {
+ returlList = srcList;
+ }
+ res(returlList);
+ },
+ select: function (evt, ui) {
+ let result = true;
+ // trigger change
+ $(this).val(ui.item.value);
+ $(this).trigger('change');
+
+ // select event
+ if (typeof that._selectEvent == "function")
+ result = that._selectEvent(ui.item.value, ui.item);
+ if (result != undefined) {
+ return result;
+ }
+ return true;
+ },
+ search: function(evt, ui) {
+ return true;
+ },
+ open: function(evt, ui) {
+ if (!$(that.wrapSelector('.vp-vs-filter-box')).hasClass('vp-inline-block')) {
+ $(that.wrapSelector('.vp-vs-filter-box')).addClass('vp-inline-block');
+ }
+ },
+ close: function(evt, ui) {
+ // $(that.wrapSelector('.vp-vs-filter-box')).removeClass('vp-inline-block');
+ evt.preventDefault();
+ return false;
+ }
+ }).focus(function () {
+ $(this).select();
+ $(this).autocomplete('search', $(this).val());
+ }).click(function () {
+ $(this).select();
+ $(this).autocomplete('search', $(this).val());
+ }).autocomplete('instance')._renderItem = function(ul, item) {
+ return $(' ').attr('data-value', item.value)
+ .append(`${item.label} | ${item.dtype}
`)
+ .appendTo(ul);
+ };
+ }
+
+ /**
+ * icon input box tag
+ * @returns html icon input text tag string
+ */
+ toTagString() {
+ var sbTagString = new com_String();
+ var that = this;
+
+ // make attributes
+ var attributes = Object.keys(this._attributes).map(key => key + '="' + this._attributes[key] + '"').join(" ");
+
+ sbTagString.appendFormatLine('', this.uuid, 'vp-vs-box vp-vs-uninit');
+ sbTagString.appendFormatLine(`
`,
+ 'vp-vs-input', that._additionalClass, that._compID == "" ? "" : com_util.formatString('id="{0}"', that._compID), that._placeholder, that._value, attributes);
+ if (this._showFilterbox) {
+ // filter icon
+ // LAB: img to url
+ // sbTagString.appendFormatLine('
', 'vp-vs-filter', com_Const.IMAGE_PATH + 'filter.svg');
+ sbTagString.appendFormatLine('
', 'vp-vs-filter', 'vp-icon-filter');
+ // filter box
+ sbTagString.appendFormatLine('
', 'vp-vs-filter-box');
+ sbTagString.appendLine('
');
+ sbTagString.appendFormatLine('{3} ',
+ this.uuid + '_vsSelectAll', 'vp-vs-filter-select-all', this.uuid + '_vsSelectAll', 'Select All');
+ this._dataTypes && this._dataTypes.forEach(dt => {
+ let tmpId = that.uuid + '_' + dt;
+ sbTagString.appendFormatLine('{4} ',
+ tmpId, 'vp-vs-filter-type', dt, tmpId, dt);
+ });
+ if (this._showOthers) {
+ let tmpId = that.uuid + '_others';
+ sbTagString.appendFormatLine('{4} ',
+ tmpId, 'vp-vs-filter-type', 'others', tmpId, 'Others');
+ }
+ sbTagString.appendLine('
'); // end of vp-grid-box
+ sbTagString.appendLine('
'); // end of vp-vs-filter-box
+ }
+ sbTagString.appendLine('
'); // end of vp-vs-box
+
+ return sbTagString.toString();
+ }
+
+ }
+
+ return VarSelector;
+});
\ No newline at end of file
diff --git a/src/common/__init__.py b/visualpython/js/com/component/__init__.py
similarity index 100%
rename from src/common/__init__.py
rename to visualpython/js/com/component/__init__.py
diff --git a/visualpython/js/loadVisualpython.js b/visualpython/js/loadVisualpython.js
new file mode 100644
index 00000000..b06ffb62
--- /dev/null
+++ b/visualpython/js/loadVisualpython.js
@@ -0,0 +1,349 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : loadVisualpython.js
+ * Author : Black Logic
+ * Note : Load Visual Python
+ * License : GPLv3 (GNU General Public License v3.0)
+ * Date : 2021. 08. 14
+ * Change Date :
+ */
+
+//============================================================================
+// Load Visual Python
+//============================================================================
+// CHROME: removed code
+define([
+ // CHROME: removed .css extension type
+ __VP_CSS_LOADER__('vp_base/css/root'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Config',
+ 'vp_base/js/com/com_Log',
+ 'vp_base/js/com/com_Kernel',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/MainFrame'
+], function (rootCss, com_Const, com_util, com_Config, com_Log, com_Kernel, com_interface, MainFrame) {
+ 'use strict';
+
+ //========================================================================
+ // Define variable
+ //========================================================================
+ var Jupyter = null;
+ var events;
+ var liveNotebook = false;
+
+ var metadataSettings;
+ var vpPosition;
+ var vpFrame;
+
+ //========================================================================
+ // Require: Jupyter & events
+ //========================================================================
+ try {
+ // namespace's specified checking. events exception can occur
+ // this will work in a live notebook because nbextensions & custom.js are loaded
+ // by/after notebook.js, which requires base/js/namespace
+ Jupyter = require('base/js/namespace');
+ events = require('base/js/events');
+ liveNotebook = true;
+ } catch (err) {
+ // We *are* theoretically in a non-live notebook
+ console.log('[vp] working in non-live notebook'); //, err);
+ // in non-live notebook, there's no event structure, so we make our own
+ if (window.events === undefined) {
+ var Events = function () { };
+ window.events = $([new Events()]);
+ }
+ events = window.events;
+ }
+
+ //========================================================================
+ // Internal call function
+ //========================================================================
+
+ /**
+ * Add toolbar button
+ */
+ var _addToolBarVpButton = function () {
+ // Call notebookApp initialize event, if toolbar is not yet ready
+ if (!Jupyter.toolbar) {
+ events.on('app_initialized.NotebookApp', function (evt) {
+ _addToolBarVpButton();
+ });
+ return;
+ }
+
+ // Add toolbar button, if it's not existing
+ if ($('#' + com_Const.TOOLBAR_BTN_INFO.ID).length === 0) {
+ $(Jupyter.toolbar.add_buttons_group([
+ Jupyter.keyboard_manager.actions.register({
+ 'help': com_Const.TOOLBAR_BTN_INFO.HELP
+ , 'icon': com_Const.TOOLBAR_BTN_INFO.ICON
+ , 'handler': function () {
+ // on clicking extension button
+ vpFrame.toggleVp();
+ }
+ }, com_Const.TOOLBAR_BTN_INFO.NAME, com_Const.TOOLBAR_BTN_INFO.PREFIX)
+ ])).find('.btn').attr('id', com_Const.TOOLBAR_BTN_INFO.ID).addClass(com_Const.TOOLBAR_BTN_INFO.ICON_CONTAINER);
+ }
+ };
+
+ /**
+ * Create vp
+ * @param {Object} cfg configuration
+ * @param {*} st
+ */
+ var _loadVpResource = function (cfg, st) {
+ if (!liveNotebook)
+ cfg = $.extend(true, {}, vpConfig.defaultConfig, cfg);
+
+ vpFrame = new MainFrame();
+ if (vpConfig.extensionType !== 'lab' && vpConfig.extensionType !== 'lite') {
+ vpFrame.loadMainFrame();
+ }
+
+ // TODO: hotkey control -> Implement under InputComponent or Event class
+ // input:text - hotkey control
+ $(document).on('focus', com_util.wrapSelector('input'), function() {
+ com_interface.disableOtherShortcut();
+ });
+ $(document).on('blur', com_util.wrapSelector('input'), function() {
+ com_interface.enableOtherShortcut();
+ });
+ $(document).on('focus', '.vp-popup-frame input', function() {
+ com_interface.disableOtherShortcut();
+ });
+ $(document).on('blur', '.vp-popup-frame input', function() {
+ com_interface.enableOtherShortcut();
+ });
+ $(document).on('focus', '#vp_fileNavigation input', function() {
+ com_interface.disableOtherShortcut();
+ });
+ $(document).on('blur', '#vp_fileNavigation input', function() {
+ com_interface.enableOtherShortcut();
+ });
+ $(document).on('focus', '.vp-dataselector input', function() {
+ com_interface.disableOtherShortcut();
+ });
+ $(document).on('blur', '.vp-dataselector input', function() {
+ com_interface.enableOtherShortcut();
+ });
+ // textarea - hotkey control
+ $(document).on('focus', com_util.wrapSelector('.vp-popup-frame textarea'), function() {
+ com_interface.disableOtherShortcut();
+ });
+ $(document).on('blur', com_util.wrapSelector('.vp-popup-frame textarea'), function() {
+ com_interface.enableOtherShortcut();
+ });
+
+
+ // CHROME: TODO: 2: background <-> vp
+ //======================================================================
+ // Event listener
+ //======================================================================
+ if (window.colab) {
+ document.removeEventListener('vpcomm', _vpcommHandler);
+ document.addEventListener('vpcomm', _vpcommHandler);
+ }
+ };
+
+ var _vpcommHandler = function(e) {
+ let detailObj = e.detail;
+ switch (detailObj.type) {
+ // case 'sendBase':
+ // // get base url of its extension
+ // vpBase = detailObj.data;
+ // // initialize vp environment
+ // vp_init();
+ // break;
+ case 'toggle':
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'received from inject - ', e.detail.type, e);
+ // toggle vp_wrapper
+ if (window.vpBase != '' && window.$ && $('#vp_wrapper').length > 0) {
+ vpFrame.toggleVp();
+ } else {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'No vp...');
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ var _setGlobalVariables = function() {
+ /**
+ * visualpython log util
+ * - use it instead of console.log
+ * ex) vpLog.display(VP_LOG_TYPE.LOG, 'log text');
+ */
+ window.vpLog = new com_Log();
+ /**
+ * visualpython log util types
+ * DEVELOP, LOG, ERROR
+ */
+ window.VP_LOG_TYPE = com_Log.LOG_TYPE;
+ /**
+ * visualpython config util
+ */
+ if (window.colab) {
+ // CHROME: added extType as 'colab' // CHROME: FIXME: use window.vpExtType = 'colab'
+ window.vpConfig = new com_Config('colab');
+ } else if (window.vpExtType === 'lab') {
+ // LAB: added extType as 'lab'
+ window.vpConfig = new com_Config('lab');
+ } else if (window.vpExtType === 'lite') {
+ // LITE: added extType as 'lite'
+ window.vpConfig = new com_Config('lite');
+ } else {
+ window.vpConfig = new com_Config();
+ }
+ window.VP_MODE_TYPE = com_Config.MODE_TYPE;
+ /**
+ * visualpython kernel
+ */
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ window.vpKernel = new com_Kernel(vpLab);
+ } else {
+ window.vpKernel = new com_Kernel();
+ }
+ }
+
+ //========================================================================
+ // External call function
+ //========================================================================
+ /**
+ * Read our config from server config & notebook metadata
+ * This function should only be called when both:
+ * 1. the notebook (and its metadata) has fully loaded
+ * AND
+ * 2. Jupyter.notebook.config.loaded has resolved
+ */
+ var readConfig = function () {
+ var cfg = vpConfig.defaultConfig;
+
+ if (!liveNotebook) {
+ return cfg;
+ }
+
+ // config may be specified at system level or at document level. first, update
+ // defaults with config loaded from server
+ let defaultMetadata = JSON.parse(JSON.stringify(vpConfig.metadataSettings));
+ let metadata = vpConfig.getMetadata();
+
+ vpConfig.resetMetadata();
+
+ if (metadata && defaultMetadata.vp_config_version == metadata.vp_config_version) {
+ Object.keys(defaultMetadata).forEach(key => {
+ let value = (metadata && metadata.hasOwnProperty(key) ? metadata : defaultMetadata)[key];
+ vpConfig.setMetadata({ [key]: value });
+ cfg[key] = value;
+ });
+ } else {
+ // if config version is different, overwrite config
+ vpConfig.setMetadata(defaultMetadata);
+ }
+
+ return cfg;
+ };
+
+ /**
+ * Initialize Visual Python
+ */
+ var initVisualpython = function () {
+ _setGlobalVariables();
+
+ let cfg = readConfig();
+
+ vpConfig.readKernelFunction();
+ // CHROME: edited
+ if (Jupyter) {
+ _addToolBarVpButton();
+ }
+ _loadVpResource(cfg);
+ vpConfig.checkVersionTimestamp();
+
+ if ((cfg.vp_section_display && vpFrame)
+ || vpConfig.extensionType === 'colab') { // CHROME: default to display vp
+ vpFrame.openVp();
+ }
+
+ // Operations on kernel restart
+ if (vpConfig.extensionType === 'notebook') {
+ events.on('kernel_ready.Kernel', function (evt, info) {
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp operations for kernel ready...');
+ // read vp functions
+ vpConfig.isReady = true;
+ vpConfig.readKernelFunction();
+ });
+ } else if (vpConfig.extensionType === 'colab') {
+ // CHROME: ready for colab kernel connected, and restart vp
+ colab.global.notebook.kernel.listen('connected', function(x) {
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp operations for kernel ready...');
+ // read vp functions
+ vpConfig.isReady = true;
+ vpConfig.readKernelFunction();
+ });
+ } else if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ // LAB: if widget is ready or changed, ready for lab kernel connected, and restart vp
+ vpLab.shell._currentChanged.connect(function(s1, value) {
+ // var { newValue } = value;
+ // LAB 4.x: get currentWidget
+ var newValue = s1.currentWidget;
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'jupyterlab shell currently changed', s1, newValue);
+ // kernel restart for notebook and console
+ if (newValue && newValue.sessionContext) {
+ vpConfig.hideProtector();
+ if (newValue.sessionContext.isReady) {
+ if (vpConfig.isReady === false) {
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp operations for kernel ready...');
+ vpConfig.isReady = true;
+ vpConfig.readKernelFunction();
+ vpConfig.checkVersionTimestamp();
+ }
+ }
+ newValue.sessionContext._connectionStatusChanged.connect(function(s2, status) {
+ if (status === 'connected') {
+ if (vpConfig.isReady === false) {
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp operations for kernel ready...');
+ vpConfig.isReady = true;
+ vpConfig.readKernelFunction();
+ vpConfig.checkVersionTimestamp();
+ }
+ }
+ });
+ } else {
+ vpLog.display(VP_LOG_TYPE.LOG, 'No widget detected...');
+ vpConfig.isReady = false;
+ vpConfig.showProtector();
+ if (vpConfig.extensionType === 'lite') {
+ vpLab.serviceManager.sessions.runningChanged.connect(handleRunningChanged);
+ }
+ }
+ });
+ }
+
+ return vpFrame;
+ }
+
+ var handleRunningChanged = function(a, b) {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'Current widget:', vpLab.shell.currentWidget);
+ if (vpLab.shell.currentWidget) {
+ vpLab.shell.currentWidget.sessionContext.statusChanged.connect(function(currentWidget, status) {
+ if (status === 'idle' && vpConfig.isReady === false) {
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp operations for kernel ready...');
+ vpConfig.isReady = true;
+ vpConfig.hideProtector();
+ vpConfig.readKernelFunction();
+ vpConfig.checkVersionTimestamp();
+ }
+ });
+ vpLab.serviceManager.sessions.runningChanged.disconnect(handleRunningChanged);
+ }
+ }
+
+ return { initVisualpython: initVisualpython, readConfig: readConfig };
+
+}); /* function, define */
+
+/* End of file */
diff --git a/visualpython/js/m_apps/Bind.js b/visualpython/js/m_apps/Bind.js
new file mode 100644
index 00000000..8d5e42af
--- /dev/null
+++ b/visualpython/js/m_apps/Bind.js
@@ -0,0 +1,682 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Bind.js
+ * Author : Black Logic
+ * Note : Apps > Bind
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Bind
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/bind.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/bind'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/MultiSelector'
+], function(bindHtml, bindCss, com_util, com_String, PopupComponent, SuggestInput, MultiSelector) {
+
+ /**
+ * Bind
+ */
+ class Bind extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.helpview = true;
+
+ this.howList = [
+ { label: 'Inner', value: 'inner', desc: 'Inner join' },
+ { label: 'Full outer', value: 'outer', desc: 'Full outer join' },
+ { label: 'Left outer', value: 'left', desc: 'Left outer join' },
+ { label: 'Right outer', value: 'right', desc: 'Right outer join' },
+ { label: 'Cross', value: 'cross', desc: 'Cartesian product' },
+ ]
+
+ this.state = {
+ type: 'concat',
+ concat: {
+ variable: [], // DataFrame, Series
+ join: 'outer',
+ axis: 0, // 0: index, 1: column
+ sort: false
+ },
+ merge: {
+ left: {
+ variable: '',
+ on: [],
+ useIndex: false,
+ suffix: ''
+ },
+ right: {
+ variable: '',
+ on: [],
+ useIndex: false,
+ suffix: ''
+ },
+ on: [],
+ how: 'inner',
+ },
+ userOption: '',
+ allocateTo: '',
+ resetIndex: false,
+ withoutColumn: 'True',
+ ...this.state
+ }
+ this.popup = {
+ type: '',
+ targetSelector: '',
+ MultiSelector: undefined
+ }
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('#vp_bdType'));
+
+ $(document).off('change', this.wrapSelector('#vp_bdVariable'));
+ $(document).off('click', this.wrapSelector('#vp_bdVariable'));
+ $(document).off('change', this.wrapSelector('#vp_bdJoin'));
+ $(document).off('change', this.wrapSelector('#vp_bdAxis'));
+ $(document).off('change', this.wrapSelector('#vp_bdSort'));
+
+ $(document).off('change', this.wrapSelector('#vp_bdLeftDataframe'));
+ $(document).off('change', this.wrapSelector('#vp_bdRightDataframe'));
+ $(document).off('click', this.wrapSelector('.vp-bd-df-refresh'));
+ $(document).off('change', this.wrapSelector('#vp_bdHow'));
+ $(document).off('change', this.wrapSelector('#vp_bdOn'));
+ $(document).off('click', this.wrapSelector('#vp_bdOn'));
+ $(document).off('change', this.wrapSelector('#vp_bdLeftOn'));
+ $(document).off('click', this.wrapSelector('#vp_bdLeftOn'));
+ $(document).off('change', this.wrapSelector('#vp_gbLeftIndex'));
+ $(document).off('change', this.wrapSelector('#vp_bdRightOn'));
+ $(document).off('click', this.wrapSelector('#vp_bdRightOn'));
+ $(document).off('change', this.wrapSelector('#vp_gbRightIndex'));
+ $(document).off('change', this.wrapSelector('#vp_bdLeftSuffix'));
+ $(document).off('change', this.wrapSelector('#vp_bdRightSuffix'));
+ $(document).off('change', this.wrapSelector('#vp_bdUserOption'));
+ $(document).off('change', this.wrapSelector('#vp_bdAllocateTo'));
+ $(document).off('change', this.wrapSelector('#vp_bdResetIndex'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ var that = this;
+ //====================================================================
+ // User operation Events
+ //====================================================================
+ $(document).on('change', this.wrapSelector('#vp_bdType'), function() {
+ var type = $(this).val();
+ that.state.type = type;
+ if (type == 'concat') {
+ $(that.wrapSelector('.vp-bd-type-box.concat')).show();
+ $(that.wrapSelector('.vp-bd-type-box.merge')).hide();
+ $(that.wrapSelector('#vp_bdWithoutColumn')).hide();
+ } else {
+ $(that.wrapSelector('.vp-bd-type-box.merge')).show();
+ $(that.wrapSelector('.vp-bd-type-box.concat')).hide();
+ $(that.wrapSelector('#vp_bdWithoutColumn')).show();
+ }
+ // clear user option
+ $(that.wrapSelector('#vp_bdUserOption')).val('');
+ that.state.userOption = '';
+
+ that.setHelpContent('_vp_pd.' + type);
+ });
+
+ //====================================================================
+ // Concat box Events
+ //====================================================================\
+ // variable change event
+ $(document).on('change', this.wrapSelector('#vp_bdVariable'), function(event) {
+ var varList = event.dataList;
+ that.state.concat.variable = varList;
+ });
+
+ // variable select button event
+ $(document).on('click', this.wrapSelector('#vp_bdVariable'), function() {
+ that.openVariablePopup($(that.wrapSelector('#vp_bdVariable')));
+ });
+
+ // join
+ $(document).on('change', this.wrapSelector('#vp_bdJoin'), function() {
+ that.state.concat.join = $(this).val();
+ });
+
+ // axis
+ $(document).on('change', this.wrapSelector('#vp_bdAxis'), function() {
+ that.state.concat.axis = $(this).val();
+ });
+
+ // sort
+ $(document).on('change', this.wrapSelector('#vp_bdSort'), function() {
+ that.state.concat.sort = $(this).val() == 'yes';
+ });
+
+ //====================================================================
+ // Merge box Events
+ //====================================================================
+ // Left variable change event
+ $(document).on('change', this.wrapSelector('#vp_bdLeftDataframe'), function() {
+ // if variable changed, clear groupby, display
+ var newVal = $(this).val();
+ if (newVal != that.state.merge.left.variable) {
+ $(that.wrapSelector('#vp_bdOn')).val('');
+ $(that.wrapSelector('#vp_bdLeftOn')).val('');
+ that.state.merge.left.variable = newVal;
+ that.state.merge.left.on = [];
+ that.state.merge.on = [];
+ }
+ });
+ // Right variable change event
+ $(document).on('change', this.wrapSelector('#vp_bdRightDataframe'), function() {
+ // if variable changed, clear groupby, display
+ var newVal = $(this).val();
+ if (newVal != that.state.merge.right.variable) {
+ $(that.wrapSelector('#vp_bdOn')).val('');
+ $(that.wrapSelector('#vp_bdRightOn')).val('');
+ that.state.merge.right.variable = newVal;
+ that.state.merge.right.on = [];
+ that.state.merge.on = [];
+ }
+ });
+
+ // variable refresh event
+ $(document).on('click', this.wrapSelector('.vp-bd-df-refresh'), function() {
+ that.loadVariableList();
+ });
+
+ // how
+ $(document).on('change', this.wrapSelector('#vp_bdHow'), function() {
+ that.state.merge.how = $(this).val();
+ });
+
+ // on change event
+ $(document).on('change', this.wrapSelector('#vp_bdOn'), function(event) {
+ var colList = event.dataList;
+ that.state.merge.on = colList;
+
+ if (colList && colList.length > 0) {
+ $(that.wrapSelector('#vp_bdLeftOn')).attr('disabled', true);
+ $(that.wrapSelector('#vp_bdRightOn')).attr('disabled', true);
+ $(that.wrapSelector('#vp_bdLeftIndex')).attr('disabled', true);
+ $(that.wrapSelector('#vp_bdRightIndex')).attr('disabled', true);
+ } else {
+ $(that.wrapSelector('#vp_bdLeftOn')).attr('disabled', false);
+ $(that.wrapSelector('#vp_bdRightOn')).attr('disabled', false);
+ $(that.wrapSelector('#vp_bdLeftIndex')).attr('disabled', false);
+ $(that.wrapSelector('#vp_bdRightIndex')).attr('disabled', false);
+ }
+ });
+
+ // on select button event
+ $(document).on('click', this.wrapSelector('#vp_bdOn'), function() {
+ var targetVariable = [ that.state.merge.left.variable, that.state.merge.right.variable ];
+ that.openColumnPopup(targetVariable, $(that.wrapSelector('#vp_bdOn')), 'Select columns from both dataframe');
+ });
+
+ // Left on change event
+ $(document).on('change', this.wrapSelector('#vp_bdLeftOn'), function(event) {
+ var colList = event.dataList;
+ that.state.merge.left.on = colList;
+
+ if ((colList && colList.length > 0)
+ || that.state.merge.right.on && that.state.merge.right.on.length > 0) {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', true);
+ } else {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', false);
+ }
+ });
+
+ // Left on select button event
+ $(document).on('click', this.wrapSelector('#vp_bdLeftOn'), function() {
+ var targetVariable = [ that.state.merge.left.variable ];
+ that.openColumnPopup(targetVariable, $(that.wrapSelector('#vp_bdLeftOn')), 'Select columns from left dataframe');
+ });
+
+ // Left use index
+ $(document).on('change', this.wrapSelector('#vp_bdLeftIndex'), function() {
+ var useIndex = $(this).prop('checked');
+ that.state.merge.left.useIndex = useIndex;
+
+ if (useIndex || that.state.merge.right.useIndex) {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', true);
+ $(that.wrapSelector('#vp_bdLeftOn')).attr('disabled', true);
+ } else {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', false);
+ $(that.wrapSelector('#vp_bdLeftOn')).attr('disabled', false);
+ }
+ });
+
+ // Right on change event
+ $(document).on('change', this.wrapSelector('#vp_bdRightOn'), function(event) {
+ var colList = event.dataList;
+ that.state.merge.right.on = colList;
+
+ if ((colList && colList.length > 0)
+ || that.state.merge.left.on && that.state.merge.left.on.length > 0) {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', true);
+ } else {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', false);
+ }
+ });
+
+ // Right on select button event
+ $(document).on('click', this.wrapSelector('#vp_bdRightOn'), function() {
+ var targetVariable = [ that.state.merge.right.variable ];
+ that.openColumnPopup(targetVariable, $(that.wrapSelector('#vp_bdRightOn')), 'Select columns from right dataframe');
+ });
+
+ // Right use index
+ $(document).on('change', this.wrapSelector('#vp_bdRightIndex'), function() {
+ var useIndex = $(this).prop('checked');
+ that.state.merge.right.useIndex = useIndex;
+
+ if (useIndex || that.state.merge.left.useIndex) {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', true);
+ $(that.wrapSelector('#vp_bdRightOn')).attr('disabled', true);
+ } else {
+ $(that.wrapSelector('#vp_bdOn')).attr('disabled', false);
+ $(that.wrapSelector('#vp_bdRightOn')).attr('disabled', false);
+ }
+ });
+
+ // Left suffix change event
+ $(document).on('change', this.wrapSelector('#vp_bdLeftSuffix'), function() {
+ that.state.merge.left.suffix = $(this).val();
+ });
+
+ // Right suffix change event
+ $(document).on('change', this.wrapSelector('#vp_bdRightSuffix'), function() {
+ that.state.merge.right.suffix = $(this).val();
+ });
+
+ // userOption event
+ $(document).on('change', this.wrapSelector('#vp_bdUserOption'), function() {
+ that.state.userOption = $(this).val();
+ });
+
+ // allocateTo event
+ $(document).on('change', this.wrapSelector('#vp_bdAllocateTo'), function() {
+ that.state.allocateTo = $(this).val();
+ });
+
+ // reset index checkbox event
+ $(document).on('change', this.wrapSelector('#vp_bdResetIndex'), function() {
+ let isChecked = $(this).prop('checked');
+ $(that.wrapSelector('#vp_bdWithoutColumn')).prop('disabled', !isChecked);
+ that.state.resetIndex = isChecked;
+ });
+
+ // with/without column select event
+ $(this.wrapSelector('#vp_bdWithoutColumn')).on('change', function() {
+ that.state.withoutColumn = $(this).val();
+ });
+ }
+
+ templateForBody() {
+ return bindHtml;
+ }
+
+ templateForDataView() {
+ return '';
+ }
+
+ renderDataView() {
+ super.renderDataView();
+
+ this.loadDataPage();
+ $(this.wrapSelector('.vp-popup-dataview-box')).css('height', '300px');
+ }
+
+ renderDataPage(renderedText, isHtml = true) {
+ var tag = new com_String();
+ tag.appendFormatLine('', 'vp_rendered_html'); // 'rendered_html' style from jupyter output area
+ if (isHtml) {
+ tag.appendLine(renderedText);
+ } else {
+ tag.appendFormatLine('
{0} ', renderedText);
+ }
+ tag.appendLine('
');
+ $(this.wrapSelector('.vp-popup-dataview-box')).html(tag.toString());
+ }
+
+ loadDataPage() {
+ var that = this;
+ var code = this.generateCode();
+ // if not, get output of all data in selected pandasObject
+ vpKernel.execute(code).then(function(resultObj) {
+ let { msg } = resultObj;
+ if (msg.content && msg.content.data) {
+ var htmlText = String(msg.content.data["text/html"]);
+ var codeText = String(msg.content.data["text/plain"]);
+ if (htmlText != 'undefined') {
+ that.renderDataPage(htmlText);
+ } else if (codeText != 'undefined') {
+ // plain text as code
+ that.renderDataPage(codeText, false);
+ } else {
+ that.renderDataPage('');
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ that.renderDataPage(errorContent);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ that.renderDataPage(errorContent);
+ });
+ }
+
+ render() {
+ super.render();
+
+ // check its type
+ if (this.state.type === 'concat') {
+ $(this.wrapSelector('#vp_bdWithoutColumn')).hide();
+ } else {
+ $(this.wrapSelector('#vp_bdWithoutColumn')).hide();
+ }
+
+ this.setHelpContent('_vp_pd.' + this.state.type);
+
+ this.loadVariableList();
+ }
+
+ /**
+ * Render variable list (for dataframe)
+ * @param {Array} varList
+ * @param {string} defaultValue previous value
+ */
+ renderVariableList(id, varList, defaultValue='') {
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID(id);
+ variableInput.addClass('vp-state');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.setNormalFilter(true);
+ variableInput.setValue(defaultValue);
+ variableInput.addAttribute('required', true);
+ $(this.wrapSelector('#' + id)).replaceWith(function() {
+ return variableInput.toTagString();
+ });
+ }
+
+ /**
+ * Load variable list (dataframe)
+ */
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var varList = JSON.parse(result);
+ // render variable list
+ // get prevvalue
+ var prevValue = that.state.merge.left.variable;
+ // replace
+ that.renderVariableList('vp_bdLeftDataframe', varList, prevValue);
+ $(that.wrapSelector('#vp_bdLeftDataframe')).trigger('change');
+
+ prevValue = that.state.merge.right.variable;
+ that.renderVariableList('vp_bdRightDataframe', varList, prevValue);
+ $(that.wrapSelector('#vp_bdRightDataframe')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Bind:', result);
+ }
+ });
+ }
+
+ generateCode() {
+ var code = new com_String();
+ var {
+ type, concat, merge, allocateTo, resetIndex, withoutColumn, userOption
+ } = this.state;
+
+ //====================================================================
+ // Allocation
+ //====================================================================
+ if (allocateTo && allocateTo != '') {
+ code.appendFormat('{0} = ', allocateTo);
+ }
+
+ //====================================================================
+ // Dataframe variables
+ //====================================================================
+ code.appendFormat('pd.{0}(', type);
+
+ if (type == 'concat') {
+ //====================================================================
+ // Concat
+ //====================================================================
+ // FIXME: consider default
+ code.appendFormat("[{0}], join='{1}', axis={2}", concat.variable.map(data=>data.code).join(','), concat.join, concat.axis);
+
+ //====================================================================
+ // Sort
+ //====================================================================
+ if (concat.sort) {
+ code.append(', sort=True');
+ }
+
+ //====================================================================
+ // Reset index
+ //====================================================================
+ if (resetIndex) {
+ code.append(', ignore_index=True');
+ }
+
+ //====================================================================
+ // User option
+ //====================================================================
+ if (userOption && userOption != '') {
+ code.appendFormat(", {0}", userOption);
+ }
+
+ code.append(')');
+
+ } else {
+ //====================================================================
+ // Merge
+ //====================================================================
+ code.appendFormat('{0}, {1}', merge.left.variable, merge.right.variable);
+
+ if (merge.on && merge.on.length > 0) {
+ //================================================================
+ // On columns
+ //================================================================
+ code.appendFormat(', on=[{0}]', merge.on.map(col => col.code));
+ } else {
+ //====================================================================
+ // Left & Right On columns
+ //====================================================================
+ if (merge.left.useIndex) {
+ code.append(', left_index=True');
+ } else {
+ if (merge.left.on && merge.left.on.length > 0) {
+ code.appendFormat(', left_on=[{0}]', merge.left.on.map(col => col.code));
+ }
+ }
+
+ if (merge.right.useIndex) {
+ code.append(', right_index=True');
+ } else {
+ if (merge.right.on && merge.right.on.length > 0) {
+ code.appendFormat(', right_on=[{0}]', merge.right.on.map(col => col.code));
+ }
+ }
+ }
+ //====================================================================
+ // How
+ //====================================================================
+ if (merge.how) {
+ code.appendFormat(", how='{0}'", merge.how);
+ }
+
+ //====================================================================
+ // Suffixes
+ //====================================================================
+ if (merge.left.suffix != '' || merge.right.suffix != '') {
+ code.appendFormat(", suffixes=('{0}', '{1}')", merge.left.suffix, merge.right.suffix);
+ }
+
+ //====================================================================
+ // User option
+ //====================================================================
+ if (userOption && userOption != '') {
+ code.appendFormat(", {0}", userOption);
+ }
+
+ code.append(')');
+
+ //====================================================================
+ // Reset index
+ //====================================================================
+ if (resetIndex) {
+ if (withoutColumn === 'True') {
+ code.append('.reset_index(drop=True)');
+ } else {
+ code.append('.reset_index()');
+ }
+ }
+ }
+
+ if (allocateTo && allocateTo != '') {
+ code.appendLine();
+ code.append(allocateTo);
+ }
+
+ return code.toString();
+ }
+
+ loadState() {
+ super.loadState();
+ var {
+ type, concat, merge, userOption, allocateTo, resetIndex, withoutColumn
+ } = this.state;
+
+ // type
+ $(this.wrapSelector('#vp_bdType')).val(type);
+
+ if (type == 'concat') {
+ // load concat state
+ this._loadSelectorInput(this.wrapSelector('#vp_bdVariable'), concat.variable);
+ $(this.wrapSelector('#vp_bdJoin')).val(concat.join);
+ $(this.wrapSelector('#vp_bdAxis')).val(concat.axis);
+ $(this.wrapSelector('#vp_bdSort')).val(concat.sort?'yes':'no');
+
+ } else {
+ // load merge state
+ $(this.wrapSelector('#vp_bdLeftDataframe')).val(merge.left.variable);
+ $(this.wrapSelector('#vp_mpRightDataframe')).val(merge.right.variable);
+
+ $(this.wrapSelector('#vp_bdHow')).val(merge.how);
+ this._loadSelectorInput(this.wrapSelector('#vp_bdOn'), merge.on);
+ if (merge.on && merge.on.length > 0) {
+ $(this.wrapSelector('#vp_bdLeftOn')).attr('disabled', true);
+ $(this.wrapSelector('#vp_bdRightOn')).attr('disabled', true);
+ $(this.wrapSelector('#vp_bdLeftIndex')).attr('disabled', true);
+ $(this.wrapSelector('#vp_bdRightIndex')).attr('disabled', true);
+ }
+ this._loadSelectorInput(this.wrapSelector('#vp_bdLeftOn'), merge.left.on);
+ this._loadSelectorInput(this.wrapSelector('#vp_bdRightOn'), merge.right.on);
+ if (merge.left.on.length > 0 || merge.right.on.length > 0
+ || merge.left.useIndex || merge.right.useIndex) {
+ $(this.wrapSelector('#vp_bdOn')).attr('disabled', true);
+ }
+
+ $(this.wrapSelector('#vp_bdLeftIndex')).prop('checked', merge.left.useIndex);
+ $(this.wrapSelector('#vp_bdRightIndex')).prop('checked', merge.right.useIndex);
+
+ $(this.wrapSelector('#vp_bdLeftSuffix')).val(merge.left.suffix);
+ $(this.wrapSelector('#vp_bdRightSuffix')).val(merge.right.suffix);
+ }
+ $(this.wrapSelector('#vp_bdUserOption')).val(userOption);
+ $(this.wrapSelector('#vp_bdAllocateTo')).val(allocateTo);
+ $(this.wrapSelector('#vp_bdResetIndex')).prop('checked', resetIndex);
+ $(this.wrapSelector('#vp_bdWithoutColumn')).val(withoutColumn);
+
+ $(this.wrapSelector('.vp-bd-type-box')).hide();
+ $(this.wrapSelector('.vp-bd-type-box.' + type)).show();
+
+ }
+
+ _loadSelectorInput(tag, dataList) {
+ $(tag).val(dataList.map(data=>data.code).join(','));
+ $(tag).data('list', dataList)
+ }
+
+ /**
+ * Open Inner popup page for variable selection
+ * @param {Object} targetSelector
+ */
+ openVariablePopup(targetSelector) {
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(data => data.code)
+ }
+ this.popup.MultiSelector = new MultiSelector(
+ this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'variable', type: ['DataFrame', 'Series'], selectedList: previousList }
+ );
+
+ this.openInnerPopup('Select variables');
+ }
+
+ /**
+ * Open Inner popup page for column selection
+ * @param {Array} targetVariable
+ * @param {Object} targetSelector
+ * @param {string} title
+ */
+ openColumnPopup(targetVariable, targetSelector, title='Select Columns') {
+ this.popup.targetVariable = targetVariable;
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(col => col.code)
+ }
+
+ this.popup.MultiSelector = new MultiSelector(
+ this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'columns', parent: targetVariable, selectedList: previousList }
+ );
+
+ this.openInnerPopup(title);
+ }
+
+ handleInnerOk() {
+ // ok input popup
+ var dataList = this.popup.MultiSelector.getDataList();
+
+ $(this.popup.targetSelector).val(dataList.map(data => { return data.code }).join(','));
+ $(this.popup.targetSelector).data('list', dataList);
+ $(this.popup.targetSelector).trigger({ type: 'change', dataList: dataList });
+ this.closeInnerPopup();
+ }
+ }
+
+ return Bind;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/File.js b/visualpython/js/m_apps/File.js
new file mode 100644
index 00000000..7e6bd848
--- /dev/null
+++ b/visualpython/js/m_apps/File.js
@@ -0,0 +1,580 @@
+/*
+ * 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 = 2;
+ this.config.checkModules = ['pd'];
+
+ this.fileExtensions = {
+ 'csv': ['csv', 'tsv', 'txt'],
+ 'excel': ['xlsx', 'xls'],
+ 'json': ['json'],
+ 'pickle': [],
+ 'sas': [], // xport or sas7bdat
+ 'spss': [],
+ 'parquet': ['parquet']
+ }
+
+ 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 = {
+ fileType: 'csv',
+ 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',
+ 'parquet':'pd_readParquet'
+ },
+ 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',
+ 'parquet':'pd_toParquet'
+ },
+ 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'
+ }
+ ]
+ }
+ }
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('#fileReadAs'));
+ }
+
+ _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();
+
+ if (pageType === 'Read' && that.fileState[pageType].selectedType === 'spss') {
+ // show install button
+ that.showInstallButton();
+ // show install note below File type selection
+ $(`
+ NOTE:
+ pyreadstat package is required to read spss file.
+ `).insertAfter($(that.wrapSelector('#fileType')).closest('tr'));
+ } else {
+ that.hideInstallButton();
+ $(that.wrapSelector('.vp-spss-note')).remove();
+ }
+
+
+ //set fileExtensions
+ that.fileResultState = {
+ ...that.fileState[pageType].fileResultState
+ };
+ });
+
+ // fileReadAs change Event, Use PyArrow
+ $(document).on('change', this.wrapSelector('#fileReadAs'), function() {
+ let isChecked = $(this).prop('checked');
+ var fileioType = that.state.vp_fileioType;
+ var prefix = '#vp_file' + fileioType + ' ';
+ var selectedType = that.fileState[fileioType]['selectedType'];
+ var fileioTypePrefix = fileioType.toLowerCase();
+ if(fileioTypePrefix == 'write'){
+ fileioTypePrefix = "to";
+ }
+ let fileId = that.fileState[fileioType].fileTypeId[selectedType];
+
+ if (isChecked) { // pyArrow
+ fileId = "pa_" + fileioTypePrefix + selectedType[0].toUpperCase() + selectedType.slice(1);
+ // that.fileState[fileioType].fileTypeId[that.state.fileExtension] = "pa_" + fileioTypePrefix + selectedFileFormat[0].toUpperCase() + selectedFileFormat.slice(1);
+ $(that.wrapSelector(prefix + '#vp_optionBox')).closest('.vp-accordian-container').hide();
+ } else { // pandas
+ // that.fileState[fileioType].fileTypeId[that.state.fileExtension] = "pd_" + fileioTypePrefix + selectedFileFormat[0].toUpperCase() + selectedFileFormat.slice(1);
+ if (that.state.fileType != 'parquet'){ // parquet has no options area
+ $(that.wrapSelector(prefix + '#vp_optionBox')).closest('.vp-accordian-container').show();
+ }
+ }
+
+ let pdLib = pandasLibrary.PANDAS_FUNCTION;
+ let thisPkg = JSON.parse(JSON.stringify(pdLib[fileId]));
+
+ that.fileState[fileioType].package = thisPkg;
+ });
+
+ }
+
+ _bindEventByType(pageType) {
+ var that = this;
+ var prefix = '#vp_file' + pageType + ' ';
+
+ var fileioTypePrefix = pageType.toLowerCase();
+ if(fileioTypePrefix == 'write'){
+ fileioTypePrefix = "to";
+ }
+ // select file type
+ $(this.wrapSelector(prefix + '#fileType')).change(function() {
+ var fileType = $(this).val();
+ that.fileState[pageType].selectedType = fileType;
+
+ // reload
+ that.renderPage(pageType);
+ that._bindEventByType(pageType);
+ });
+
+ // open file navigation
+ $(this.wrapSelector(prefix + '#vp_openFileNavigationBtn')).click(function() {
+
+ let type = 'save';
+ if (pageType == 'Read') {
+ type = 'open';
+ }
+
+ let extensionList = [];
+ if (that.state.fileExtension && that.state.fileExtension.length > 0) {
+ 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' || selectedType == 'parquet') {
+ // 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' || selectedType == 'parquet') {
+ 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));
+
+ // pyarrow can r/w parquet, csv and only read json.
+ if ((pageType == 'Read' && selectedType == 'json') || selectedType == 'parquet'|| selectedType == 'csv') {
+ // add checkbox 'Use PyArrow', next to File Type
+ $(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).prepend(
+ $('').append($(`File Type `))
+ .append($(' Use PyArrow '))
+ );
+ } else {
+ $(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).prepend(
+ $(' ').append($(`File Type `))
+ .append($(' '))
+ );
+ }
+
+ // prepend file type selector
+ var fileTypeList = Object.keys(fileTypeObj);
+ fileTypeList.forEach(type => {
+ $(this.wrapSelector(prefix + '#fileType')).append(
+ $(`${type} `)
+ );
+ });
+
+ // prepend user option
+ let hasAllocateTo = $(this.wrapSelector(prefix + '#o0')).length > 0;
+ if (hasAllocateTo) {
+ $(this.wrapSelector(prefix + '#o0')).closest('tr').after(
+ $(' ').append($(`User Option `))
+ .append($(' '))
+ )
+ } else {
+ $(this.wrapSelector(prefix + '#vp_inputOutputBox table tbody')).append(
+ $(' ').append($(`User Option `))
+ .append($(' '))
+ )
+ }
+
+ $(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('
'
+ , 'vp-file-browser-button')
+ );
+ } else if (selectedType == 'pickle' || selectedType == 'parquet') {
+ $(prefix + '#path').parent().html(
+ com_util.formatString('
'
+ , 'vp-file-browser-button')
+ );
+ } else {
+ $(this.fileState[pageType]['fileResultState']['pathInputId']).parent().html(
+ com_util.formatString('
'
+ , 'i1'
+ , 'vp-file-browser-button')
+ );
+ }
+ } else {
+ $(this.fileState[pageType]['fileResultState']['pathInputId']).parent().html(
+ com_util.formatString('
'
+ , 'i0'
+ , 'vp-file-browser-button')
+ );
+ }
+
+ if (pageType === 'Read' && selectedType === 'spss') {
+ // show install button
+ this.showInstallButton();
+ // show install note below File type selection
+ $(`
+ NOTE:
+ pyreadstat package is required to read spss file.
+ `).insertAfter($(this.wrapSelector('#fileType')).closest('tr'));
+ } else {
+ this.hideInstallButton();
+ }
+
+ // 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();
+ });
+
+ // separator suggest input
+ $(this.wrapSelector('#sep')).replaceWith(function() {
+ // separator list :
+ var sepList = [',', '|', '\\t', '\\n', ':', ';', '-', '_', '&', '/', '\\'];
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('sep');
+ suggestInput.addClass('vp-input vp-state');
+ suggestInput.setSuggestList(function() { return sepList; });
+ suggestInput.setPlaceholder('Input separator');
+ 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;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Frame.js b/visualpython/js/m_apps/Frame.js
new file mode 100644
index 00000000..4e91083d
--- /dev/null
+++ b/visualpython/js/m_apps/Frame.js
@@ -0,0 +1,4003 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Frame.js
+ * Author : Black Logic
+ * Note : Apps > Frame
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Frame
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/frame.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/frame'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(frameHtml, frameCss, com_Const, com_String, com_util, PopupComponent, SuggestInput, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * Frame
+ */
+ class Frame extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 5;
+ this.config.checkModules = ['pd'];
+
+ // state
+ this.state = {
+ originObj: '',
+ tempObj: '_vp',
+ returnObj: 'vp_df',
+ inplace: false,
+ menu: '',
+ menuItem: '',
+ columnLevel: 1,
+ columnList: [],
+ indexLevel: 1,
+ indexList: [],
+ selected: [],
+ axis: FRAME_AXIS.NONE,
+ lines: TABLE_LINES,
+ steps: [],
+ popup: {
+ type: FRAME_EDIT_TYPE.NONE,
+ replace: { index: 0 }
+ },
+ selection: {
+ start: -1,
+ end: -1
+ },
+ ...this.state
+ }
+
+ // numpy.dtype or python type
+ this.astypeList = [
+ 'object', 'int64', 'float64', 'bool',
+ 'datetime64[ns]', 'timedelta[ns]', 'category'
+ ];
+
+ // {
+ // id: 'id',
+ // label: 'menu label',
+ // child: [
+ // {
+ // id: 'id', label: 'label', code: 'code',
+ // axis: 'col/row', single_select: true/false,
+ // numeric_only: true/false
+ // }
+ // ]
+ // }
+ this.menuList = [
+ {
+ id: 'edit',
+ label: 'Edit',
+ child: [
+ { id: 'add_col', label: 'Add column', selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.ADD_COL },
+ { id: 'add_row', label: 'Add row', selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.ADD_ROW },
+ { id: 'delete', label: 'Delete', selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.DROP },
+ { id: 'rename', label: 'Rename', selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.RENAME },
+ { id: 'as_type', label: 'As type', selection: FRAME_SELECT_TYPE.NONE, axis: FRAME_AXIS.COLUMN, menuType: FRAME_EDIT_TYPE.AS_TYPE },
+ { id: 'to_datetime', label: 'To Datetime', selection: FRAME_SELECT_TYPE.SINGLE, axis: FRAME_AXIS.COLUMN, menuType: FRAME_EDIT_TYPE.TO_DATETIME },
+ { id: 'replace', label: 'Replace', selection: FRAME_SELECT_TYPE.SINGLE, axis: FRAME_AXIS.COLUMN, menuType: FRAME_EDIT_TYPE.REPLACE },
+ { id: 'discretize', label: 'Discretize', selection: FRAME_SELECT_TYPE.SINGLE, axis: FRAME_AXIS.COLUMN, numeric_only: true, menuType: FRAME_EDIT_TYPE.DISCRETIZE }
+ ]
+ },
+ {
+ id: 'transform',
+ label: 'Transform',
+ child: [
+ { id: 'set_index', label: 'Set index', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.SET_IDX },
+ { id: 'reset_index', label: 'Reset index', selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.RESET_IDX },
+ { id: 'data_shift', label: 'Data shift', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.DATA_SHIFT }
+ ]
+ },
+ {
+ id: 'sort',
+ label: 'Sort',
+ axis: FRAME_AXIS.COLUMN,
+ child: [
+ { id: 'sort_index', label: 'Sort index', selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.SORT_INDEX },
+ { id: 'sort_values', label: 'Sort values', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.SORT_VALUES },
+ ]
+ },
+ {
+ id: 'encoding',
+ label: 'Encoding',
+ axis: FRAME_AXIS.COLUMN,
+ selection: FRAME_SELECT_TYPE.MULTI,
+ child: [
+ { id: 'label_encoding', label: 'Label encoding', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.LABEL_ENCODING },
+ { id: 'one_hot_encoding', label: 'Onehot encoding', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.ONE_HOT_ENCODING },
+ ]
+ },
+ {
+ id: 'data_cleaning',
+ label: 'Data cleaning',
+ axis: FRAME_AXIS.COLUMN,
+ child: [
+ { id: 'fillna', label: 'Fill NA', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.FILL_NA },
+ { id: 'dropna', label: 'Drop NA', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.DROP_NA },
+ { id: 'fill_outlier', label: 'Fill outlier', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.FILL_OUT },
+ { id: 'drop_outlier', label: 'Drop outlier', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.MULTI, menuType: FRAME_EDIT_TYPE.DROP_OUT },
+ { id: 'drop_duplicates', label: 'Drop duplicates', axis: FRAME_AXIS.COLUMN, selection: FRAME_SELECT_TYPE.NONE, menuType: FRAME_EDIT_TYPE.DROP_DUP },
+ ]
+ },
+ ];
+
+ // Add/Replace - subset
+ this.subsetCm = null;
+ this.subsetEditor = null;
+
+ this.loading = false;
+
+ // this._addCodemirror('previewCode', this.wrapSelector('#vp_fePreviewCode'), 'readonly');
+ }
+
+ loadState() {
+ super.loadState();
+ var {
+ originObj,
+ returnObj,
+ steps
+ } = this.state;
+
+ // $(this.wrapSelector('#vp_feVariable')).val(originObj);
+
+ // $(this.wrapSelector('#vp_feReturn')).val(returnObj);
+
+ // // execute all steps
+ if (steps && steps.length > 0) {
+ var code = steps.join('\n');
+ this.state.steps = [];
+ this.loadCode(code);
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // select df
+ $(document).on('change', this.wrapSelector('#vp_feVariable'), function() {
+ // set temporary df
+ var origin = $(this).val();
+
+ if (origin) {
+ // initialize state values
+ that.state.originObj = origin;
+ that.state.tempObj = '_vp';
+ that.state.returnObj = 'vp_df';
+ if (that.state.inplace === true) {
+ that.state.returnObj = origin;
+ }
+ that.initState();
+
+ // reset return obj
+ $(that.wrapSelector('#vp_feReturn')).val(that.state.returnObj);
+
+ // reset table
+ $(that.wrapSelector('.' + VP_FE_TABLE)).replaceWith(function() {
+ return that.renderTable('');
+ });
+
+ // load code with temporary df
+ that.loadCode(that.getTypeCode(FRAME_EDIT_TYPE.INIT));
+ that.loadInfo();
+ }
+ });
+
+ // refresh df
+ $(document).on('click', this.wrapSelector('.vp-fe-df-refresh'), function() {
+ that.loadVariableList();
+ });
+
+ $(document).on('click', this.wrapSelector('.' + VP_FE_INFO), function(evt) {
+ evt.stopPropagation();
+ });
+
+ // input return variable
+ $(document).on('change', this.wrapSelector('#vp_feReturn'), function() {
+ var returnVariable = $(this).val();
+ if (returnVariable == '') {
+ returnVariable = that.state.tempObj;
+ }
+ // check if it's same with origin obj
+ if (returnVariable === that.state.originObj) {
+ $(that.wrapSelector('#inplace')).prop('checked', true);
+ that.state.inplace = true;
+ } else {
+ $(that.wrapSelector('#inplace')).prop('checked', false);
+ that.state.inplace = false;
+ }
+
+ // show preview with new return variable
+ that.state.returnObj = returnVariable;
+ that.setPreview(that.getCurrentCode());
+ });
+
+ // check/uncheck inplace
+ $(this.wrapSelector('#inplace')).on('change', function() {
+ let checked = $(this).prop('checked');
+ let returnVariable = 'vp_df';
+ if (checked === true) {
+ returnVariable = that.state.originObj;
+ }
+ $(that.wrapSelector('#vp_feReturn')).val(returnVariable);
+
+ // show preview with new return variable
+ that.state.inplace = checked;
+ that.state.returnObj = returnVariable;
+ that.setPreview(that.getCurrentCode());
+ });
+
+ // menu on column (Deprecated on v2.3.6 - Temporarily Show on v.2.4.4)
+ $(document).on('contextmenu', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(event) {
+ event.preventDefault();
+
+ var idx = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN)).index(this); // 1 ~ n
+ var hasSelected = $(this).hasClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+ // select col/idx
+ if (!hasSelected) {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+
+ $(this).addClass('selected');
+ that.state.selection = { start: idx, end: -1 };
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ }
+ // select its group
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${$(this).data('parent')}"]`)).addClass('selected');
+
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+
+ // show menu
+ var thisPos = $(this).position();
+ var thisRect = $(this)[0].getBoundingClientRect();
+ that.showMenu(thisPos.left, thisPos.top + thisRect.height);
+ });
+
+ // menu on row (Deprecated on v2.3.6 - Temporarily Show on v.2.4.4)
+ $(document).on('contextmenu', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW), function(event) {
+ event.preventDefault();
+ var idx = $(that.wrapSelector('.' + VP_FE_TABLE_ROW)).index(this); // 0 ~ n
+ var hasSelected = $(this).hasClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ // select col/idx
+ if (!hasSelected) {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+ $(this).addClass('selected');
+ that.state.selection = { start: idx, end: -1 };
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ }
+
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+
+ // show menu
+ var thisPos = $(this).position();
+ var thisRect = $(this)[0].getBoundingClientRect();
+ var tblPos = $(that.wrapSelector('.' + VP_FE_TABLE)).position();
+ var scrollTop = $(that.wrapSelector('.' + VP_FE_TABLE)).scrollTop();
+ that.showMenu(tblPos.left + thisRect.width, tblPos.top + thisPos.top - scrollTop);
+ });
+
+ // un-select every selection and menu box
+ $(document).on('click', this.wrapSelector('.vp-fe-table'), function(evt) {
+ evt.stopPropagation();
+ var target = evt.target;
+ if ($('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN).find(target).length == 0
+ && !$(target).hasClass('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN) ) {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+ $(that.wrapSelector('.vp-fe-menu-box')).hide();
+
+ // reset selected columns/indexes
+ that.state.axis = FRAME_AXIS.NONE;
+ that.state.selected = [];
+ // load toolbar
+ that.renderToolbar();
+ }
+ });
+
+ // select column group
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP), function(evt) {
+ evt.stopPropagation();
+
+ let hasSelected = $(this).hasClass('selected');
+ let colLabel = $(this).data('label');
+ let firstIdx = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]:first`)).index();
+ let lastIdx = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]:last`)).index();
+ if (firstIdx === lastIdx) {
+ lastIdx = -1;
+ }
+
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ if (!hasSelected) {
+ that.state.selection = { start: firstIdx, end: -1 };
+ $(this).addClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).addClass('selected');
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ } else {
+ $(this).removeClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).removeClass('selected');
+ }
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ var axis = that.state.axis;
+ var startIdx = that.state.selection.start;
+ if (axis != FRAME_AXIS.COLUMN) {
+ startIdx = -1;
+ }
+
+ if (startIdx == -1) {
+ // no selection
+ that.state.selection = { start: firstIdx, end: -1 };
+ } else if (startIdx > firstIdx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ let parentSet = new Set();
+ for (var i = firstIdx - 1; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ parentSet.add($(tags[i]).data('parent'));
+ }
+ parentSet.forEach(parentKey => {
+ let length = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${parentKey}"]`)).length;
+ let selectedLength = $(that.wrapSelector(`.${VP_FE_TABLE} th.selected[data-parent="${parentKey}"]`)).length;
+ if (length === selectedLength) {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).addClass('selected');
+ } else {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).removeClass('selected');
+ }
+ });
+ that.state.selection = { start: startIdx, end: firstIdx };
+ } else if (startIdx <= firstIdx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ let parentSet = new Set();
+ for (var i = startIdx; i < lastIdx; i++) {
+ $(tags[i]).addClass('selected');
+ parentSet.add($(tags[i]).data('parent'));
+ }
+ parentSet.forEach(parentKey => {
+ let length = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${parentKey}"]`)).length;
+ let selectedLength = $(that.wrapSelector(`.${VP_FE_TABLE} th.selected[data-parent="${parentKey}"]`)).length;
+ if (length === selectedLength) {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).addClass('selected');
+ } else {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).removeClass('selected');
+ }
+ });
+ that.state.selection = { start: startIdx, end: lastIdx };
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+
+ $(this).addClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).addClass('selected');
+ that.state.selection = { start: firstIdx, end: lastIdx };
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ }
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+ });
+
+ /**
+ * Drag and drop selection TODO: release for later version v2.3.8
+ */
+ // drag start column
+ // $(document).on('mousedown', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(evt) {
+ // var idx = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN)).index(this); // 1 ~ n
+ // that.state.axis = FRAME_AXIS.COLUMN;
+ // that.state.selection = { start: idx, end: -1 };
+ // that.isMouseDown = true;
+ // console.log('down');
+
+ // $(document).on('mouseover', that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(evt) {
+ // evt.stopPropagation();
+ // var idx = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN)).index(this); // 1 ~ n
+ // var axis = that.state.axis;
+ // var startIdx = that.state.selection.start;
+ // if (that.isMouseDown === true) {
+ // if (axis === FRAME_AXIS.ROW) {
+ // startIdx = -1;
+ // }
+
+ // if (startIdx == -1) {
+ // // no selection
+ // that.state.selection = { start: idx, end: -1 };
+ // } else if (startIdx > idx) {
+ // // add selection from idx to startIdx
+ // var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ // for (var i = idx; i <= startIdx; i++) {
+ // $(tags[i]).addClass('selected');
+ // }
+ // that.state.selection = { start: startIdx, end: idx };
+ // } else if (startIdx <= idx) {
+ // // add selection from startIdx to idx
+ // var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ // for (var i = startIdx; i <= idx; i++) {
+ // $(tags[i]).addClass('selected');
+ // }
+ // that.state.selection = { start: startIdx, end: idx };
+ // }
+
+ // that.loadInfo();
+ // // load toolbar
+ // that.renderToolbar();
+ // }
+ // });
+ // });
+
+ // $(document).on('mouseup', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(evt) {
+ // that.isMouseDown = false;
+ // console.log('up');
+ // $(document).off('mouseover', that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN));
+ // });
+
+ // select column
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(evt) {
+ evt.stopPropagation();
+
+ var idx = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN)).index(this); // 1 ~ n
+ var hasSelected = $(this).hasClass('selected');
+
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ if (!hasSelected) {
+ that.state.selection = { start: idx, end: -1 };
+ $(this).addClass('selected');
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ } else {
+ $(this).removeClass('selected');
+ }
+
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ var axis = that.state.axis;
+ var startIdx = that.state.selection.start;
+ if (axis === FRAME_AXIS.ROW) {
+ startIdx = -1;
+ }
+
+ if (startIdx == -1) {
+ // no selection
+ that.state.selection = { start: idx, end: -1 };
+ } else if (startIdx > idx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ for (var i = idx; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ } else if (startIdx <= idx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ for (var i = startIdx; i <= idx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+
+ $(this).addClass('selected');
+ that.state.selection = { start: idx, end: -1 };
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ }
+ // select its group
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${$(this).data('parent')}"]`)).addClass('selected');
+
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+ });
+
+ // select row
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW), function(evt) {
+ evt.stopPropagation();
+
+ var idx = $(that.wrapSelector('.' + VP_FE_TABLE_ROW)).index(this); // 0 ~ n
+ var hasSelected = $(this).hasClass('selected');
+
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ if (!hasSelected) {
+ that.state.selection = { start: idx, end: -1 };
+ $(this).addClass('selected');
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ } else {
+ $(this).removeClass('selected');
+ }
+
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ var axis = that.state.axis;
+ var startIdx = that.state.selection.start;
+ if (axis != FRAME_AXIS.ROW) {
+ startIdx = -1;
+ }
+
+ if (startIdx == -1) {
+ // no selection
+ that.state.selection = { start: idx, end: -1 };
+ } else if (startIdx > idx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_ROW));
+ for (var i = idx; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ } else if (startIdx <= idx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_ROW));
+ for (var i = startIdx; i <= idx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+ if (!hasSelected) {
+ $(this).addClass('selected');
+ that.state.selection = { start: idx, end: -1 };
+ var newAxis = $(this).data('axis');
+ that.state.axis = newAxis;
+ } else {
+ $(this).removeClass('selected');
+ }
+ }
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+ });
+
+ // add column
+ $(document).on('click', this.wrapSelector('.' + VP_FE_ADD_COLUMN), function() {
+ // add column
+ that.openInputPopup(FRAME_EDIT_TYPE.ADD_COL);
+ });
+
+ // add row
+ $(document).on('click', this.wrapSelector('.' + VP_FE_ADD_ROW), function() {
+ // add row
+ that.openInputPopup(FRAME_EDIT_TYPE.ADD_ROW);
+ });
+
+ // more rows
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE_MORE), function() {
+ that.state.lines += TABLE_LINES;
+ that.loadCode(that.getTypeCode(FRAME_EDIT_TYPE.SHOW), true);
+ });
+
+ // click toolbar item (Deprecated on v2.3.6 - Temporarily Show on v.2.4.4)
+ $(document).on('click', this.wrapSelector('.vp-fe-toolbar-item'), function(evt) {
+ evt.stopPropagation();
+ var itemType = $(this).data('type');
+ switch (parseInt(itemType)) {
+ case FRAME_EDIT_TYPE.ADD_COL:
+ case FRAME_EDIT_TYPE.ADD_ROW:
+ that.openInputPopup(itemType);
+ break;
+ }
+ });
+
+ // click menu item
+ $(document).on('click', this.wrapSelector('.' + VP_FE_MENU_ITEM + ':not(.disabled)'), function(event) {
+ event.stopPropagation();
+ var editType = $(this).data('type');
+ switch (parseInt(editType)) {
+ case FRAME_EDIT_TYPE.ADD_COL:
+ case FRAME_EDIT_TYPE.ADD_ROW:
+ case FRAME_EDIT_TYPE.RENAME:
+ case FRAME_EDIT_TYPE.REPLACE:
+ case FRAME_EDIT_TYPE.AS_TYPE:
+ case FRAME_EDIT_TYPE.TO_DATETIME:
+ case FRAME_EDIT_TYPE.DISCRETIZE:
+ case FRAME_EDIT_TYPE.DATA_SHIFT:
+ case FRAME_EDIT_TYPE.SORT_INDEX:
+ case FRAME_EDIT_TYPE.SORT_VALUES:
+ case FRAME_EDIT_TYPE.FILL_NA:
+ case FRAME_EDIT_TYPE.DROP_NA:
+ case FRAME_EDIT_TYPE.DROP_DUP:
+ case FRAME_EDIT_TYPE.FILL_OUT:
+ case FRAME_EDIT_TYPE.DROP_OUT:
+ case FRAME_EDIT_TYPE.DROP:
+ // open inner popup
+ that.openInputPopup(editType);
+ break;
+ default:
+ that.loadCode(that.getTypeCode(editType));
+ break;
+ }
+ that.hideMenu();
+ });
+
+ // popup : replace - add button
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-replace-add'), function() {
+ var newInput = $(that.renderReplaceInput(++that.state.popup.replace.index));
+ newInput.insertBefore(
+ $(that.wrapSelector('.vp-inner-popup-replace-table tr:last'))
+ );
+ });
+
+ // popup : replace - delete row
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-delete'), function() {
+ $(this).closest('tr').remove();
+ });
+
+
+ // popup : add column - dataframe selection 1
+ $(document).on('var_changed change', this.wrapSelector('.vp-inner-popup-var1'), function() {
+ var type = $(that.wrapSelector('.vp-inner-popup-var1box .vp-vs-data-type')).val();
+ if (type == 'DataFrame') {
+ var df = $(this).val();
+ vpKernel.getColumnList(df).then(function(resultObj) {
+ let { result } = resultObj;
+ var { list } = JSON.parse(result);
+ var tag = new com_String();
+ tag.appendFormatLine('', 'vp-inner-popup-var1col');
+ list && list.forEach(col => {
+ tag.appendFormatLine('{2} '
+ , col.value, col.label, col.label);
+ });
+ tag.appendLine(' ');
+ // replace column list
+ $(that.wrapSelector('.vp-inner-popup-var1col')).replaceWith(function() {
+ return tag.toString();
+ });
+ });
+ }
+ });
+
+ // popup : add column - dataframe selection 2
+ $(document).on('var_changed change', this.wrapSelector('.vp-inner-popup-var2'), function() {
+ var type = $(that.wrapSelector('.vp-inner-popup-var2box .vp-vs-data-type')).val();
+ if (type == 'DataFrame') {
+ var df = $(this).val();
+ vpKernel.getColumnList(df).then(function(resultObj) {
+ let { result } = resultObj;
+ var { list } = JSON.parse(result);
+ var tag = new com_String();
+ tag.appendFormatLine('', 'vp-inner-popup-var2col');
+ list && list.forEach(col => {
+ tag.appendFormatLine('{2} '
+ , col.value, col.label, col.label);
+ });
+ tag.appendLine(' ');
+ // replace column list
+ $(that.wrapSelector('.vp-inner-popup-var2col')).replaceWith(function() {
+ return tag.toString();
+ });
+ });
+ }
+ });
+ }
+
+ handleInnerOk() {
+ // ok input popup
+ var type = parseInt(this.state.popup.type);
+ var content = this.getPopupContent(type);
+ // required data check
+ if (type === FRAME_EDIT_TYPE.ADD_COL
+ || type === FRAME_EDIT_TYPE.ADD_ROW) {
+ if (content.name === '' || content.name === "''") {
+ $(this.wrapSelector('.vp-inner-popup-input0')).focus();
+ return;
+ }
+ } else if (type === FRAME_EDIT_TYPE.REPLACE) {
+ ;
+ } else if (type === FRAME_EDIT_TYPE.FILL_NA) {
+ if (content.method === 'value' && content.value === '') {
+ $(this.wrapSelector('.vp-inner-popup-value')).focus();
+ return;
+ }
+ } else if (type === FRAME_EDIT_TYPE.FILL_OUT) {
+ if (content.filltype === 'value' && content.fillvalue === '') {
+ $(this.wrapSelector('.vp-inner-popup-fillvalue')).focus();
+ return;
+ }
+ } else if (type === FRAME_EDIT_TYPE.TO_DATETIME) {
+ if (content.newcol === '') {
+ $(this.wrapSelector('.vp-inner-popup-todt-new-col')).focus();
+ }
+ }
+ // run check modules for outliers and load codes
+ if (type === FRAME_EDIT_TYPE.FILL_OUT) {
+ this.config.checkModules = ['pd', 'np', 'vp_fill_outlier'];
+ let that = this;
+ this.checkAndRunModules(true).then(function() {
+ that.loadCode(that.getTypeCode(that.state.popup.type, content));
+ });
+ } else if (type === FRAME_EDIT_TYPE.DROP_OUT) {
+ this.config.checkModules = ['pd', 'np', 'vp_drop_outlier'];
+ let that = this;
+ this.checkAndRunModules(true).then(function() {
+ that.loadCode(that.getTypeCode(that.state.popup.type, content));
+ });
+ } else {
+ var code = this.loadCode(this.getTypeCode(this.state.popup.type, content));
+ if (code == '') {
+ return;
+ }
+ }
+ this.closeInnerPopup();
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off(this.wrapSelector('*'));
+
+ $(document).off('change', this.wrapSelector('#vp_feVariable'));
+ $(document).off('click', this.wrapSelector('.vp-fe-df-refresh'));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_INFO));
+ $(document).off('change', this.wrapSelector('#vp_feReturn'));
+ $(document).off('click', this.wrapSelector('.vp-popup-body'));
+ $(document).off('contextmenu', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN));
+ $(document).off('contextmenu', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_ADD_COLUMN));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_ADD_ROW));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_TABLE_MORE));
+ $(document).off('click', this.wrapSelector('.vp-fe-toolbar-item'));
+ $(document).off('click', this.wrapSelector('.' + VP_FE_MENU_ITEM));
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-replace-add'));
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-delete'));
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-var1'));
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-var2'));
+ }
+
+ bindEventForPopupPage(menuType) {
+ var that = this;
+
+ if (menuType === FRAME_EDIT_TYPE.ADD_COL
+ || menuType === FRAME_EDIT_TYPE.ADD_ROW
+ || menuType === FRAME_EDIT_TYPE.REPLACE) {
+ // Add page
+ if (menuType === FRAME_EDIT_TYPE.ADD_COL
+ || menuType === FRAME_EDIT_TYPE.ADD_ROW) {
+ ///// add page
+ // 1. add type
+ $(this.wrapSelector('.vp-inner-popup-addtype')).on('change', function() {
+ var tab = $(this).val();
+ $(that.wrapSelector('.vp-inner-popup-tab')).hide();
+ $(that.wrapSelector('.vp-inner-popup-tab.' + tab)).show();
+
+ if (tab === 'apply') {
+ let colName = $(that.wrapSelector('.vp-inner-popup-apply-column option:selected')).text();
+ $(that.wrapSelector('.vp-inner-popup-apply-target-name')).text(colName);
+ $(that.wrapSelector('.vp-inner-popup-apply-column')).trigger('change');
+ }
+ });
+
+ // 2-1. hide column selection box
+ $(this.wrapSelector('.vp-inner-popup-var1box .vp-vs-data-type')).on('change', function() {
+ var type = $(this).val();
+ if (type == 'DataFrame') {
+ $(that.wrapSelector('.vp-inner-popup-var1col')).show();
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-var1col')).hide();
+ }
+ });
+
+ $(this.wrapSelector('.vp-inner-popup-var2box .vp-vs-data-type')).on('change', function() {
+ var type = $(this).val();
+ if (type == 'DataFrame') {
+ $(that.wrapSelector('.vp-inner-popup-var2col')).show();
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-var2col')).hide();
+ }
+ });
+
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-vartype'));
+ $(document).on('change', this.wrapSelector('.vp-inner-popup-vartype'), function() {
+ var type = $(this).val();
+ $(this).closest('tr').find('.vp-inner-popup-vartype-box').hide();
+ $(this).closest('tr').find('.vp-inner-popup-vartype-box.' + type).show();
+ });
+ }
+
+ // Replace page
+ if (menuType === FRAME_EDIT_TYPE.REPLACE) {
+ $(this.wrapSelector('.vp-inner-popup-replacetype')).on('change', function() {
+ var tab = $(this).val();
+ $(that.wrapSelector('.vp-inner-popup-tab')).hide();
+ $(that.wrapSelector('.vp-inner-popup-tab.' + tab)).show();
+
+ if (tab === 'apply') {
+ let colName = $(that.wrapSelector('.vp-inner-popup-apply-column option:selected')).text();
+ $(that.wrapSelector('.vp-inner-popup-apply-target-name')).text(colName);
+ $(that.wrapSelector('.vp-inner-popup-apply-column')).trigger('change');
+ }
+ });
+ }
+
+ // Add & Replace page
+ // condition add
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-add-cond'));
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-add-cond'), function (event) {
+ that.handleConditionAdd();
+ });
+
+ // condition delete
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-del-cond'));
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-del-cond'), function (event) {
+ event.stopPropagation();
+
+ // clear previous one
+ $(this).closest('tr').remove();
+ $(that.wrapSelector('.vp-inner-popup-oper-connect:last')).hide();
+ });
+
+ // change column selection for condition page
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-col-list'));
+ $(document).on('change', this.wrapSelector('.vp-inner-popup-col-list'), function () {
+ var thisTag = $(this);
+ var varName = that.state.tempObj;
+ var colName = $(this).find('option:selected').attr('data-code');
+ var colDtype = $(this).find('option:selected').attr('data-dtype');
+
+ var operTag = $(this).closest('td').find('.vp-inner-popup-oper-list');
+ var condTag = $(this).closest('td').find('.vp-inner-popup-condition');
+
+ if (colName == '.index') {
+ // index
+ $(thisTag).closest('td').find('.vp-inner-popup-cond-use-text').prop('checked', false);
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator('');
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput([], '');
+ });
+ that.generateCode();
+ } else {
+ // get result and load column list
+ vpKernel.getColumnCategory(varName, colName).then(function (resultObj) {
+ let { result } = resultObj;
+ try {
+ var category = JSON.parse(result);
+ if (category && category.length > 0 && colDtype == 'object') {
+ // if it's categorical column and its dtype is object, check 'Text' as default
+ $(thisTag).closest('td').find('.vp-inner-popup-cond-use-text').prop('checked', true);
+ } else {
+ $(thisTag).closest('td').find('.vp-inner-popup-cond-use-text').prop('checked', false);
+ }
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype);
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput(category, colDtype);
+ });
+ } catch {
+ $(thisTag).closest('td').find('.vp-inner-popup-cond-use-text').prop('checked', false);
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype);
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput([], colDtype);
+ });
+ }
+ });
+ }
+ });
+
+ // change operator selection
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-oper-list'));
+ $(document).on('change', this.wrapSelector('.vp-inner-popup-oper-list'), function () {
+ var oper = $(this).val();
+ var condTag = $(this).closest('td').find('.vp-inner-popup-condition');
+ var useTextTag = $(this).closest('td').find('.vp-inner-popup-cond-use-text');
+ // var colDtype = $(this).closest('td').find('.vp-col-list option:selected').attr('data-dtype');
+
+ // if operator is isnull(), notnull(), disable condition input
+ if (oper == 'isnull()' || oper == 'notnull()') {
+ $(condTag).prop('disabled', true);
+ $(useTextTag).prop('disabled', true);
+ } else {
+ $(condTag).prop('disabled', false);
+ $(useTextTag).prop('disabled', false);
+ }
+ });
+
+ // apply page
+ // 4. apply
+ $(this.wrapSelector('.vp-inner-popup-apply-column')).on('change', function() {
+ // TODO: change apply-condition (save value)
+ let colLabel = $(that.wrapSelector('.vp-inner-popup-apply-column option:selected')).text();
+ $(that.wrapSelector('.vp-inner-popup-apply-target-name')).text(colLabel);
+
+ var varName = that.state.tempObj;
+ let colName = $(this).val();
+ var colDtype = $(this).find('option:selected').attr('data-dtype');
+ var operTag = $(that.wrapSelector('.vp-inner-popup-apply-oper-list'));
+ var condTag = $(that.wrapSelector('.vp-inner-popup-apply-condition'));
+ // get result and load column list
+ vpKernel.getColumnCategory(varName, colName).then(function (resultObj) {
+ let { result } = resultObj;
+ try {
+ var category = JSON.parse(result);
+ if (category && category.length > 0 && colDtype == 'object') {
+ // if it's categorical column and its dtype is object, check 'Text' as default
+ $(that.wrapSelector('.vp-inner-popup-apply-cond-usetext')).prop('checked', true);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-apply-cond-usetext')).prop('checked', false);
+ }
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype, 'vp-inner-popup-apply-oper-list', $(this).val());
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput(category, colDtype, 'vp-inner-popup-apply-condition', $(this).val());
+ });
+ } catch {
+ $(that.wrapSelector('.vp-inner-popup-apply-cond-usetext')).prop('checked', false);
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype, 'vp-inner-popup-apply-oper-list');
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput([], colDtype, 'vp-inner-popup-apply-condition');
+ });
+ }
+ });
+ });
+
+ // change operator selection
+ $(document).off('change', this.wrapSelector('.vp-inner-popup-apply-oper-list'));
+ $(document).on('change', this.wrapSelector('.vp-inner-popup-apply-oper-list'), function () {
+ var oper = $(this).val();
+ var condTag = $(this).closest('td').find('.vp-inner-popup-apply-condition');
+ var useTextTag = $(this).closest('td').find('.vp-inner-popup-apply-cond-usetext');
+
+ // if operator is isnull(), notnull(), disable condition input
+ if (oper == 'isnull()' || oper == 'notnull()') {
+ $(condTag).prop('disabled', true);
+ $(useTextTag).prop('disabled', true);
+ } else {
+ $(condTag).prop('disabled', false);
+ $(useTextTag).prop('disabled', false);
+ }
+ });
+
+ $(this.wrapSelector('.vp-inner-popup-toggle-else')).on('click', function() {
+ // toggle else on/off
+ let elseOn = $(this).attr('data-else'); // on / off
+ if (elseOn === 'off') {
+ // off -> on
+ $(this).attr('data-else', 'on');
+ $(this).text('Else off');
+ $(that.wrapSelector('.vp-inner-popup-apply-else-value')).prop('disabled', false);
+ $(that.wrapSelector('.vp-inner-popup-apply-else-usetext')).prop('disabled', false);
+ } else {
+ // on -> off
+ $(this).attr('data-else', 'off');
+ $(this).text('Else on');
+ $(that.wrapSelector('.vp-inner-popup-apply-else-value')).prop('disabled', true);
+ $(that.wrapSelector('.vp-inner-popup-apply-else-usetext')).prop('disabled', true);
+ }
+ });
+
+ $(this.wrapSelector('.vp-inner-popup-add-case')).on('click', function() {
+ // add case
+ $(this).parent().find('.vp-inner-popup-apply-case-box').append($(that.templateForApplyCase()));
+ $(that.wrapSelector('.vp-inner-popup-apply-column')).trigger('change');
+ });
+
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-apply-add-cond'));
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-apply-add-cond'), function() {
+ // add condition
+ $(this).parent().find('.vp-inner-popup-apply-cond-box').append($(that.templateForApplyCondition()));
+ // show operator except last operator
+ $(this).parent().find('.vp-inner-popup-apply-oper-connect:not(:last)').show();
+ $(that.wrapSelector('.vp-inner-popup-apply-column')).trigger('change');
+ });
+
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-apply-del-cond'));
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-apply-del-cond'), function() {
+ let condBox = $(this).closest('.vp-inner-popup-apply-cond-box');
+ // delete apply cond
+ $(this).parent().remove();
+ // hide last operator
+ $(condBox).find('.vp-inner-popup-apply-oper-connect:last').hide();
+ });
+
+ $(document).off('click', this.wrapSelector('.vp-inner-popup-apply-del-case'));
+ $(document).on('click', this.wrapSelector('.vp-inner-popup-apply-del-case'), function() {
+ // delete apply case
+ $(this).parent().remove();
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.DISCRETIZE) {
+ // change bins
+ $(this.wrapSelector('.vp-inner-popup-bins')).on('change', function() {
+ let binsCount = $(this).val();
+ that.handleDiscretizeEdges(binsCount);
+ });
+
+ // change cut to qcut(quantile based discretization)
+ $(this.wrapSelector('.vp-inner-popup-discretizetype')).on('change', function() {
+ let binsCount = $(that.wrapSelector('.vp-inner-popup-bins')).val();
+ let discretizeType = $(this).val();
+ // disable right and range table
+ if (discretizeType === 'qcut') {
+ $(that.wrapSelector('.vp-inner-popup-right')).prop('disabled', true);
+ $(that.wrapSelector('.vp-inner-popup-range-table input.vp-inner-popup-left-edge')).val('');
+ $(that.wrapSelector('.vp-inner-popup-range-table input.vp-inner-popup-right-edge')).val('');
+ $(that.wrapSelector('.vp-inner-popup-range-table input:not(.vp-inner-popup-label)')).prop('disabled', true);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-right')).prop('disabled', false);
+ $(that.wrapSelector('.vp-inner-popup-range-table input.vp-inner-popup-left-edge')).val('');
+ $(that.wrapSelector('.vp-inner-popup-range-table input.vp-inner-popup-right-edge')).val('');
+ $(that.wrapSelector('.vp-inner-popup-range-table input:not(.vp-inner-popup-label)')).prop('disabled', false);
+ }
+ that.handleDiscretizeEdges(binsCount);
+ });
+
+ // change right option
+ $(this.wrapSelector('.vp-inner-popup-right')).on('change', function() {
+ let binsCount = $(that.wrapSelector('.vp-inner-popup-bins')).val();
+ let right = $(this).prop('checked');
+ that.handleDiscretizeEdges(binsCount, right);
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.SORT_INDEX
+ || menuType === FRAME_EDIT_TYPE.SORT_VALUES) {
+ $(this.wrapSelector('.vp-inner-popup-axis')).on('change', function() {
+ let axis = $(this).val();
+ if (axis === '0') {
+ axis = FRAME_AXIS.ROW;
+ } else {
+ axis = FRAME_AXIS.COLUMN;
+ }
+ $(that.wrapSelector('.vp-inner-popup-sortby')).replaceWith(that.templateForSortByBox('index', axis));
+ // re-bind events
+ $(that.wrapSelector('.vp-inner-popup-sortby-up')).on('click', function() {
+ let tag = $(this).closest('.vp-inner-popup-sortby-item');
+ tag.insertBefore(tag.prev());
+ });
+ $(that.wrapSelector('.vp-inner-popup-sortby-down')).on('click', function() {
+ let tag = $(this).closest('.vp-inner-popup-sortby-item');
+ tag.insertAfter(tag.next());
+ });
+ });
+
+ $(this.wrapSelector('.vp-inner-popup-sortby-up')).on('click', function() {
+ let tag = $(this).closest('.vp-inner-popup-sortby-item');
+ tag.insertBefore(tag.prev());
+ });
+ $(this.wrapSelector('.vp-inner-popup-sortby-down')).on('click', function() {
+ let tag = $(this).closest('.vp-inner-popup-sortby-item');
+ tag.insertAfter(tag.next());
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.FILL_OUT) {
+ $(this.wrapSelector('.vp-inner-popup-filltype')).on('change', function() {
+ let filltype = $(this).val();
+ if (filltype === 'value') {
+ $(that.wrapSelector('.vp-inner-popup-fillvalue')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-fillvalue')).prop('disabled', true);
+ }
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.DROP_NA) {
+ $(this.wrapSelector('.vp-inner-popup-how')).on('change', function() {
+ let val = $(this).val();
+ if (val === '') {
+ $(that.wrapSelector('.vp-inner-popup-thresh')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-thresh')).prop('disabled', true);
+ }
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.FILL_NA) {
+ // bind event on method
+ $(this.wrapSelector('.vp-inner-popup-method')).on('change', function() {
+ let changedVal = $(this).val();
+ if (changedVal === 'value') {
+ // show value row
+ $(that.wrapSelector('.vp-inner-popup-value-row')).show();
+ $(that.wrapSelector('.vp-inner-popup-fill-row')).hide();
+ } else if (changedVal === 'ffill' || changedVal === 'bfill') {
+ // show method fill row
+ $(that.wrapSelector('.vp-inner-popup-value-row')).hide();
+ $(that.wrapSelector('.vp-inner-popup-fill-row')).show();
+ } else {
+ // hide all
+ $(that.wrapSelector('.vp-inner-popup-value-row')).hide();
+ $(that.wrapSelector('.vp-inner-popup-fill-row')).hide();
+ }
+ });
+ } else if (menuType === FRAME_EDIT_TYPE.TO_DATETIME) {
+ // bind event for selecting format
+ $(this.wrapSelector('.vp-inner-popup-todt-format')).on('change', function() {
+ let format = $(this).val();
+ if (format === 'auto') {
+ $(that.wrapSelector('.vp-inner-popup-todt-dayfirst')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-todt-dayfirst')).prop('disabled', true);
+ $(that.wrapSelector('.vp-inner-popup-todt-dayfirst')).val('');
+ }
+
+ if (format === 'typing') {
+ $(that.wrapSelector('.vp-inner-popup-todt-format-typing')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-inner-popup-todt-format-typing')).prop('disabled', true);
+ }
+ });
+
+ // Add column set event
+ $(this.wrapSelector('.vp-inner-popup-todt-addcol')).on('click', function() {
+ let dateTypeList = [ // df[col].dt[{dateType}]
+ { label: 'Year', value: 'year' },
+ { label: 'Month', value: 'month' },
+ { label: 'Day', value: 'day' },
+ { label: 'Date', value: 'date' },
+ { label: 'DayOfWeek', value: 'dayofweek' },
+ { label: 'DayOfYear', value: 'dayofyear' },
+ { label: 'DaysInMonth', value: 'daysinmonth' },
+ { label: 'Quarter', value: 'quarter' },
+ { label: 'Time', value: 'time' },
+ { label: 'Hour', value: 'hour' },
+ { label: 'Minute', value: 'minute' },
+ { label: 'Second', value: 'second' },
+ { label: 'Nanosecond', value: 'nanosecond' },
+ ];
+ let dateTypeOptionTag = new com_String();
+ dateTypeList.forEach(opt => {
+ dateTypeOptionTag.appendFormat('{1} ', opt.value, opt.label);
+ });
+
+ let addColItemTag = $(``);
+ $(that.wrapSelector('.vp-inner-popup-todt-addcol-content')).append(addColItemTag);
+ $(addColItemTag)[0].scrollIntoView();
+
+ // bind event for selecting date type option
+ $(that.wrapSelector('.vp-inner-popup-todt-addcol-type')).off('change');
+ $(that.wrapSelector('.vp-inner-popup-todt-addcol-type')).on('change', function() {
+ let dateTypeVal = $(this).val();
+ $(this).parent().find('.vp-inner-popup-todt-addcol-colname').val(dateTypeVal);
+ });
+
+ // bind event for deleting
+ $(that.wrapSelector('.vp-inner-popup-todt-addcol-del')).off('click');
+ $(that.wrapSelector('.vp-inner-popup-todt-addcol-del')).on('click', function() {
+ // delete item
+ $(this).closest('.vp-inner-popup-todt-addcol-item').remove();
+ });
+ });
+ }
+
+ }
+
+ handleDiscretizeEdges(binsCount=1, right=true) {
+ let that = this;
+ $(this.wrapSelector('.vp-inner-popup-range-table tbody')).html('');
+ $(this.wrapSelector('.vp-inner-popup-islabelchanged')).val("false");
+ $(that.wrapSelector('.vp-inner-popup-isedgechanged')).val("false");
+
+ let code = new com_String();
+ code.appendFormatLine("_out, _bins = pd.cut({0}[{1}], bins={2}, right={3}, retbins=True)"
+ , this.state.tempObj, this.state.selected[0].code, binsCount, right?'True':'False');
+ code.append("_vp_print({'edges': list(_bins)})");
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ let { edges } = JSON.parse(result);
+
+ let labelLength = edges.length - 1;
+ let edgeTbody = new com_String();
+ for (let idx = 0; idx < labelLength; idx++ ) {
+ let leftDisabled = 'disabled';
+ let rightDisabled = '';
+ if (idx === (labelLength - 1)) {
+ rightDisabled = 'disabled';
+ }
+ edgeTbody.append('');
+ edgeTbody.appendFormatLine(' ', idx, idx);
+ edgeTbody.appendLine(': ');
+ edgeTbody.appendFormatLine(' ', idx, edges[idx], leftDisabled);
+ edgeTbody.appendLine('~ ');
+ edgeTbody.appendFormatLine(' ', idx + 1, edges[idx+1], rightDisabled);
+ edgeTbody.append(' ');
+ }
+ $(that.wrapSelector('.vp-inner-popup-range-table tbody')).html(edgeTbody.toString());
+
+ // label change event
+ $(that.wrapSelector('.vp-inner-popup-label')).change(function() {
+ $(that.wrapSelector('.vp-inner-popup-islabelchanged')).val("true");
+ });
+
+ // edge change event
+ $(that.wrapSelector('.vp-inner-popup-left-edge')).change(function() {
+ let idx = $(this).data('idx');
+ let val = $(this).val();
+ $(that.wrapSelector(`.vp-inner-popup-right-edge[data-idx=${idx}]`)).val(val);
+ $(that.wrapSelector('.vp-inner-popup-isedgechanged')).val("true");
+ });
+ $(that.wrapSelector('.vp-inner-popup-right-edge')).change(function() {
+ let idx = $(this).data('idx');
+ let val = $(this).val();
+ $(that.wrapSelector(`.vp-inner-popup-left-edge[data-idx=${idx}]`)).val(val);
+ $(that.wrapSelector('.vp-inner-popup-isedgechanged')).val("true");
+ });
+
+ }).catch(function(errObj) {
+ vpLog.display(VP_LOG_TYPE.ERROR, errObj);
+ });
+ }
+
+ templateForBody() {
+ let page = $(frameHtml);
+
+ // Removed dataselector for Allocation input
+ // let allocateSelector = new DataSelector({
+ // pageThis: this, id: 'vp_feReturn', placeholder: 'Variable name', required: true, value: 'vp_df'
+ // });
+ // $(page).find('#vp_feReturn').replaceWith(allocateSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ var {
+ originObj,
+ returnObj,
+ inplace,
+ steps
+ } = this.state;
+
+ this.loadVariableList();
+
+ this.renderToolbar();
+
+ $(this.wrapSelector('#vp_feVariable')).val(originObj);
+
+ $(this.wrapSelector('#vp_feReturn')).val(returnObj);
+
+ $(this.wrapSelector('#inplace')).prop('checked', inplace);
+
+ // execute all steps
+ if (steps && steps.length > 0) {
+ var code = steps.join('\n');
+ // this.state.steps = [];
+ this.loadCode(code);
+ }
+
+ // resize codeview
+ $(this.wrapSelector('.vp-popup-codeview-box')).css({'height': '300px'})
+ }
+
+ renderVariableList(varList, defaultValue='') {
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID('vp_feVariable');
+ variableInput.addClass('vp-state');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.addAttribute('required', true);
+ variableInput.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ variableInput.setNormalFilter(true);
+ variableInput.setValue(defaultValue);
+ $(this.wrapSelector('#vp_feVariable')).replaceWith(function() {
+ return variableInput.toTagString();
+ });
+ }
+
+ /**
+ * Render toolbar and contextmenu
+ */
+ renderToolbar() {
+ let that = this;
+ $(this.wrapSelector('.vp-fe-toolbox')).html('');
+ $(this.wrapSelector('.vp-fe-menu-box')).html('');
+ // add menu list
+ this.menuList & this.menuList.forEach((menuObj, idx) => {
+ // show menu list dynamically
+ let { id, label, child, axis, selection } = menuObj;
+ let enabled = true;
+ if ((that.state.axis !== FRAME_AXIS.NONE) && (axis !== undefined) && (axis !== FRAME_AXIS.NONE) && (that.state.axis !== axis)) {
+ enabled = false;
+ }
+ if (selection !== undefined && (selection !== FRAME_SELECT_TYPE.NONE)) {
+ if ((selection === FRAME_SELECT_TYPE.SINGLE) && (that.state.selected.length !== 1)) {
+ enabled = false;
+ }
+ if ((selection === FRAME_SELECT_TYPE.MULTI) && (that.state.selected.length === 0)) {
+ enabled = false;
+ }
+ }
+ let selected = id === that.state.menu;
+ let $toolbar = $(``);
+ let $menubox = '';
+ if (child !== undefined) {
+ $menubox = $(``);
+ } else {
+ $menubox = $(``);
+ }
+ child && child.forEach(itemObj => {
+ let { id, label, menuType, axis, selection } = itemObj;
+ let enabled = true;
+ if ((that.state.axis !== FRAME_AXIS.NONE) && (axis !== undefined) && (axis !== FRAME_AXIS.NONE) && (that.state.axis !== axis)) {
+ enabled = false;
+ }
+ if (selection !== undefined && (selection !== FRAME_SELECT_TYPE.NONE)) {
+ if ((selection === FRAME_SELECT_TYPE.SINGLE) && (that.state.selected.length !== 1)) {
+ enabled = false;
+ }
+ if ((selection === FRAME_SELECT_TYPE.MULTI) && (that.state.selected.length === 0)) {
+ enabled = false;
+ }
+ }
+ let selected = that.state.menuItem === id;
+ $toolbar.find('.vp-dropdown-content')
+ .append($(``));
+ $menubox.find('.vp-fe-menu-sub-box')
+ .append($(``))
+ });
+ $(this.wrapSelector('.vp-fe-toolbox')).append($toolbar);
+ $(this.wrapSelector('.vp-fe-menu-box')).append($menubox);
+ });
+ }
+
+ renderTable(renderedText, isHtml=true) {
+ var tag = new com_String();
+ // Table
+ tag.appendFormatLine('', VP_FE_TABLE, 'vp_rendered_html', 'vp-scrollbar');
+ if (isHtml) {
+ tag.appendFormatLine('
', renderedText);
+ // More button
+ tag.appendFormatLine('
Show more
', VP_FE_TABLE_MORE, 'vp-button');
+ } else {
+ tag.appendFormatLine('
{0} ', renderedText);
+ }
+ tag.appendLine('
'); // End of Table
+ return tag.toString();
+ }
+
+ /**
+ * Get last code to set preview
+ * @returns
+ */
+ getCurrentCode() {
+ let { inplace, steps, tempObj, returnObj } = this.state;
+ let codeList = steps;
+ if (inplace === true) {
+ codeList = steps.slice(1, steps.length);
+ }
+
+ // get last code
+ let currentCode = codeList[codeList.length - 1];
+ if (currentCode && currentCode != '') {
+ currentCode = currentCode.replaceAll(tempObj, returnObj);
+ } else {
+ currentCode = '';
+ }
+ return currentCode;
+ }
+
+ generateCode() {
+ var code = '';
+ // if inplace is true, join steps without .copy()
+ if (this.state.inplace === true) {
+ code = this.state.steps.slice(1).join('\n');
+ } else {
+ code = this.state.steps.join('\n');
+ }
+ var returnVariable = $(this.wrapSelector('#vp_feReturn')).val();
+ if (returnVariable != '') {
+ code = code.replaceAll(this.state.tempObj, returnVariable);
+
+ if (code != '') {
+ code += '\n' + returnVariable;
+ }
+ } else {
+ code += '\n' + this.state.tempObj;
+ }
+ return code;
+ }
+
+ initState() {
+ this.state.selected = [];
+ this.state.axis = FRAME_AXIS.NONE;
+ this.state.lines = TABLE_LINES;
+ this.state.steps = [];
+ }
+
+ // FIXME:
+ renderButton() {
+ // set button next to input tag
+ var buttonTag = new com_String();
+ buttonTag.appendFormat('{3} '
+ , VP_FE_BTN, this.uuid, 'vp-button', 'Edit');
+ if (this.pageThis) {
+ $(this.pageThis.wrapSelector('#' + this.targetId)).parent().append(buttonTag.toString());
+ }
+ }
+
+ setPreview(previewCodeStr) {
+ // get only last line of code
+ var previewCode = previewCodeStr;
+ if (previewCodeStr.includes('\n') === true) {
+ let previewCodeLines = previewCodeStr.split('\n');
+ previewCode = previewCodeLines.pop();
+ }
+ this.setCmValue('previewCode', previewCode);
+ }
+
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var varList = JSON.parse(result);
+ // render variable list
+ // get prevvalue
+ var prevValue = that.state.originObj;
+ // if (varList && varList.length > 0 && prevValue == '') {
+ // prevValue = varList[0].varName;
+ // that.state.originObj = prevValue;
+ // }
+ // replace
+ that.renderVariableList(varList, prevValue);
+ $(that.wrapSelector('#vp_feVariable')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'FrameEditor:', result);
+ }
+ });
+ }
+
+ /**
+ * Render Inner popup page
+ * @param {*} type
+ * @returns
+ */
+ renderAddPage(type = '') {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-addpage');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendFormatLine('New {1} ', 'vp-orange-text', type);
+ if (type === 'row') {
+ content.appendFormatLine(' ', 'vp-inner-popup-input0', 'Type row name');
+ } else {
+ content.appendFormatLine(' ', 'vp-inner-popup-input0', 'level 0');
+ }
+ content.appendFormatLine('{1} '
+ , 'vp-inner-popup-inputastext0', 'Text');
+ content.appendLine(' ');
+ if (type === 'column' && this.state.columnLevel > 1) {
+ for (let i = 1; i < this.state.columnLevel; i++ ) {
+ content.appendLine(' ');
+ content.appendFormatLine(' ', 'vp-inner-popup-input' + i, 'level ' + i);
+ content.appendFormatLine('{1} '
+ , 'vp-inner-popup-inputastext' + i, 'Text');
+ content.appendLine(' ');
+ }
+ }
+ if (type === 'column') {
+ content.appendLine('Add type ');
+ content.appendFormatLine('', 'vp-inner-popup-addtype');
+ content.appendFormatLine('{1} ', 'calculate', 'Calculate');
+ content.appendFormatLine('{1} ', 'statistics', 'Statistics');
+ content.appendFormatLine('{1} ', 'replace', 'Replace');
+ content.appendFormatLine('{1} ', 'condition', 'Condition');
+ content.appendFormatLine('{1} ', 'apply', 'Apply');
+ content.appendLine(' ');
+ }
+ content.appendLine('
');
+ content.appendLine('
'); // end of vp-inner-popup-header
+
+ content.appendLine('
');
+
+ // tab 1. calculate
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'calculate');
+ content.appendLine('
');
+ content.appendLine('');
+ content.appendFormatLine('', 'vp-inner-popup-addvalue');
+ content.appendLine('
');
+ content.appendLine('
'); // end of vp-inner-popup-tab value
+
+ // tab 2. statistics
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'statistics');
+ content.appendFormatLine('
', 'vp-grid-col-120');
+ content.appendLine('
Columns ');
+ content.appendFormatLine('
', 'vp-inner-popup-stats-col-list');
+ content.appendLine('
Method ');
+ content.appendFormatLine('
', 'vp-inner-popup-stats-method');
+ let methodList = [
+ 'sum', 'mean', 'median', 'max', 'min', 'std', 'var'
+ ];
+ methodList.forEach(method => {
+ content.appendFormatLine('{2} ',
+ method, method, method);
+ });
+ content.appendLine(' ');
+
+ content.appendLine('
');
+ content.appendLine('
');
+
+ // tab 3. replace
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'replace');
+ content.appendFormatLine('
', 'vp-grid-col-120');
+ content.appendLine('Target column ');
+ content.appendFormatLine('', 'vp-inner-popup-value-col-list');
+ this.state.columnList.forEach(col => {
+ content.appendFormatLine('{3} ',
+ col.code, col.type, col.code, col.label);
+ });
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendFormatLine('
{1} ', 'vp-inner-popup-use-regex', 'Use Regular Expression');
+ content.appendLine('
');
+ content.appendFormatLine('
', 'vp-inner-popup-replace-table');
+ content.appendLine('
');
+ content.appendLine(' ');
+ content.appendFormatLine('{0} {1} ', 'Value', 'New value');
+ content.appendLine('');
+ content.appendLine(this.renderReplaceInput(0));
+ content.appendFormatLine('{2} ', 'vp-button', 'vp-inner-popup-replace-add', '+ Add value');
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendLine('
');
+
+ // tab 4. condition
+ // replace page - 2. condition
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'condition');
+ // value
+ content.appendLine('
');
+ // condition table
+ content.appendLine('');
+ content.appendLine('
');
+
+ // tab 5. apply
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'apply');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendLine('
Target column ');
+ content.appendLine('
');
+ content.appendLine(this.renderColumnList(this.state.columnList));
+ content.appendLine('
');
+ content.appendLine('
');
+ // content.appendFormatLine('
'
+ // , 'vp_popupAddApply', 'vp-input vp-inner-popup-apply-lambda', 'Type code manually');
+ // render condition
+ content.appendLine('
');
+ content.appendFormatLine('
+ Case ', 'vp-inner-popup-add-case');
+ content.appendLine('
'); // end of else value line
+ content.appendLine('
');
+ content.appendLine('
'); // end of vp-inner-popup-tab apply
+ content.appendLine('
'); // end of vp-inner-popup-addpage
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderAddValueBox(idx) {
+ // add dataselector
+ let valueSelector = new DataSelector({
+ pageThis: this, classes: 'vp-inner-popup-value', placeholder: 'Type value', withPopup: false
+ });
+ $(this.wrapSelector('.vp-inner-popup-body')).find('.vp-inner-popup-value:nth(' + idx + ')').replaceWith(valueSelector.toTagString());
+ }
+
+ templateForApplyCase() {
+ return ``;
+ }
+
+ templateForApplyCondition() {
+ let colLabel = $(this.wrapSelector('.vp-inner-popup-apply-column option:selected'))?.text();
+ return ``;
+ }
+
+ renderCalculator(idx) {
+ let content = new com_String();
+ content.appendFormatLine('', 'vp-input s vp-inner-popup-oper', idx);
+ let operList = ['+', '-', '*', '/', '%', '//', '==', '!=', '>=', '>', '<=', '<', 'and', 'or'];
+ operList.forEach(oper => {
+ content.appendFormatLine('{1} ', oper, oper);
+ });
+ content.appendFormatLine(' ');
+ return content.toString();
+ }
+
+ renderColumnList = function(columnList) {
+ var selectTag = new com_String();
+ selectTag.appendFormatLine('', 'vp-inner-popup-apply-column');
+ // columnList && columnList.forEach(col => {
+ // selectTag.appendFormatLine('{1} ', col.code, col.label);
+ // });
+ columnList && columnList.forEach(col => {
+ selectTag.appendFormatLine('{3} ',
+ col.code, col.type, col.code, col.label);
+ });
+ selectTag.appendLine(' ');
+ return selectTag.toString();
+ }
+
+ renderDropPage() {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-drop-page');
+ content.appendFormatLine('Are you sure to delete {0} below?', (this.state.axis === FRAME_AXIS.COLUMN?'columns':'rows'));
+ content.appendFormatLine('
{0} ', this.state.selected.map(col=>col.code).join(', '))
+ content.appendLine('
');
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ /**
+ * Render rename page
+ * @param {string} type FRAME_AXIS
+ * @returns
+ */
+ renderRenamePage = function(type = FRAME_AXIS.COLUMN) {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-rename-page', 'vp-scrollbar');
+ if (type === FRAME_AXIS.COLUMN && this.state.columnLevel > 1) {
+ content.appendFormatLine('
', 'vp-grid-col-110');
+ content.appendLine('Level ');
+ content.appendFormatLine('', 'vp-inner-popup-level');
+ for (let i = 0; i < this.state.columnLevel; i++) {
+ content.appendFormatLine('{1} ', i, i);
+ }
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+ }
+ content.appendLine('
');
+ content.appendLine(' ');
+ content.appendLine('');
+ if (this.state.columnLevel > 1) {
+ let selectedList = this.state.selected;
+ let selectedStr = '';
+ if (selectedList.length === 0) {
+ // select all
+ selectedList = this.state.columnList;
+ selectedStr = selectedList.map(col => "(" + col.code.join(',') + ")").join(',')
+ } else {
+ selectedStr = selectedList.map(col => col.code).join(',');
+ }
+ let codeStr = com_util.formatString("_vp_print([ list(col) for col in {0}[[{1}]].columns.to_list()])"
+ , this.state.tempObj, selectedStr);
+ let that = this;
+ vpKernel.execute(codeStr).then(function(resultObj) {
+ let { result } = resultObj;
+ let colList = JSON.parse(result);
+ let colTags = new com_String();
+ for (let i = 0; i < colList.length; i++) {
+ let colLevels = colList[i];
+ for (let j = 0; j < colLevels.length; j++) {
+ let idx = (i + 1) * j
+ colTags.appendFormatLine('', 'vp-inner-popup-input-row');
+ colTags.appendFormatLine('{1} ', j * 10, colLevels[j]);
+ colTags.appendFormatLine(' '
+ , 'vp-inner-popup-input' + idx, com_util.convertToStr(colLevels[j], true)); // FIXME: text or num ?
+ colTags.appendFormatLine('{1} ', 'vp-inner-popup-istext' + idx, 'Text');
+ colTags.appendLine(' ');
+ }
+ }
+ $(that.wrapSelector('.vp-inner-popup-rename-page tbody')).html(colTags.toString());
+ });
+ } else {
+ let selectedList = this.state.selected;
+ if (selectedList.length === 0) {
+ // select all
+ selectedList = this.state.columnList;
+ }
+ selectedList.forEach((col, idx) => {
+ content.appendFormatLine('', 'vp-inner-popup-input-row');
+ content.appendFormatLine('{0} ', col.label);
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-input' + idx, col.code);
+ content.appendFormatLine('{1} '
+ , 'vp-inner-popup-istext' + idx, 'Text');
+ content.appendLine(' ');
+ });
+ }
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderDiscretizePage() {
+ var content = new com_String();
+ content.appendLine(`
+
+ `)
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderShiftPage() {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-shift-page');
+ content.appendLine('
');
+ content.appendLine(' ');
+ content.appendLine('');
+ content.appendFormatLine('{0} ', 'Periods');
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-periods', 'Type number');
+ content.appendLine(' ');
+ content.appendFormatLine('{0} {1} '
+ , 'NOTE:', 'Number of periods to shift. Can be positive or negative.');
+ content.appendLine('');
+ content.appendLine('');
+ content.appendFormatLine('{0} ', 'Frequency');
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-freq', 'Offset for timeseries');
+ content.appendLine(' ');
+ content.appendLine('');
+ content.appendFormatLine('{0} ', 'Fill value');
+ content.appendLine('');
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-fillvalue', 'Type value to fill');
+ content.appendFormatLine('{1} ', 'vp-inner-popup-fillvalueastext', 'Text');
+ content.appendLine(' ');
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ /**
+ *
+ * @param {int} method index / values
+ * @returns
+ */
+ renderSortPage(method='values') {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-sort-page');
+ content.appendLine('
');
+ // axis
+ let sortByStr = 'column';
+ if (method === 'index') {
+ content.appendFormatLine('{0} ', 'Axis');
+ content.appendFormatLine('', 'vp-inner-popup-axis');
+ content.appendFormatLine('{1} ', "0", "Index (default)");
+ content.appendFormatLine('{1} ', "1", "Column");
+ content.appendLine(' ');
+ sortByStr = 'level';
+ }
+ // sort by
+ content.appendFormatLine('{0} {1} ', 'Sort by', sortByStr);
+ content.appendLine(this.templateForSortByBox(method));
+
+ // ascending
+ content.appendFormatLine('{0} ', 'Ascending');
+ content.appendFormatLine('', 'vp-inner-popup-isascending');
+ content.appendFormatLine('{1} ', "True", "True (default)");
+ content.appendFormatLine('{1} ', "False", "False");
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ templateForSortByBox(method='index', axis=FRAME_AXIS.ROW) {
+ var content = new com_String();
+ let sortByList = [];
+ if (method === 'values') {
+ // sort_values
+ sortByList = this.state.selected;
+ } else {
+ // sort_index
+ if (axis === FRAME_AXIS.ROW) {
+ sortByList = Array.from({ length:this.state.indexLevel },(v,k)=>{ return {label: k, code: k} });
+ } else {
+ sortByList = Array.from({ length:this.state.columnLevel },(v,k)=>{ return {label: k, code: k} });
+ }
+ }
+
+ // movable list
+ content.appendLine('');
+ return content.toString();
+ }
+
+ renderReplacePage() {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-replacepage');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendFormatLine('{1} ', '', 'Column');
+ var target = this.state.selected[0];
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-input1', target.label, target.code);
+ content.appendLine(' ');
+ content.appendLine('Replace type ');
+ content.appendFormatLine('', 'vp-inner-popup-replacetype');
+ content.appendFormatLine('{1} ', 'replace', 'Replace');
+ content.appendFormatLine('{1} ', 'condition', 'Condition');
+ content.appendFormatLine('{1} ', 'apply', 'Apply');
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
'); // end of vp-inner-popup-header
+
+ content.appendLine('
');
+ // replace page - 1. replace
+ content.appendFormatLine('
', 'vp-inner-popup-tab replace');
+ content.appendFormatLine('
{1} ', 'vp-inner-popup-use-regex', 'Use Regular Expression');
+ content.appendLine('
');
+ content.appendFormatLine('
', 'vp-inner-popup-replace-table');
+ content.appendLine('
');
+ content.appendLine(' ');
+ content.appendFormatLine('{0} {1} ', 'Value', 'New value');
+ content.appendLine('');
+ content.appendLine(this.renderReplaceInput(0));
+ content.appendFormatLine('{2} ', 'vp-button', 'vp-inner-popup-replace-add', '+ Add value');
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendLine('
');
+ // replace page - 2. condition
+ content.appendFormatLine('
', 'vp-inner-popup-tab condition');
+ // value
+ content.appendLine('
');
+ // condition table
+ content.appendLine('');
+ content.appendLine('
'); // end of vp-inner-popup-tab condition
+
+ // replace page - 3. apply
+ content.appendFormatLine('
', 'vp-inner-popup-tab', 'apply');
+ content.appendLine('
');
+ content.appendLine('
');
+ content.appendLine('
Target column ');
+ content.appendLine('
');
+ content.appendLine(this.renderColumnList(this.state.columnList));
+ content.appendLine('
');
+ content.appendLine('
');
+ // content.appendFormatLine('
'
+ // , 'vp_popupAddApply', 'vp-input vp-inner-popup-apply-lambda', 'Type code manually');
+ // render condition
+ content.appendLine('
');
+ content.appendLine('
'); // end of else value line
+ content.appendLine('
');
+ content.appendLine('
'); // end of vp-inner-popup-tab apply
+
+ content.appendLine('
'); // end of vp-inner-popup-addpage
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderReplaceInput(index) {
+ var content = new com_String();
+ content.appendLine('');
+ content.appendLine('');
+ content.appendFormatLine(' ', 'vp-inner-popup-origin' + index, 'Origin');
+ content.appendFormatLine('{1} ', 'vp-inner-popup-origin-istext' + index, 'Text');
+ content.appendLine(' ');
+ content.appendLine('');
+ content.appendFormatLine(' ', 'vp-inner-popup-replace' + index, 'Replace');
+ content.appendFormatLine('{1} ', 'vp-inner-popup-replace-istext' + index, 'Text');
+ content.appendLine(' ');
+ // LAB: img to url
+ // content.appendFormatLine(' ', 'vp-inner-popup-delete', 'vp-cursor', com_Const.IMAGE_PATH + 'close_small.svg');
+ content.appendFormatLine('
', 'vp-inner-popup-delete', 'vp-cursor', 'vp-icon-close-small');
+ content.appendLine(' ');
+ return content.toString();
+ }
+
+ handleConditionAdd() {
+ var conditonBox = $(this.renderReplaceCondition());
+
+ // hide last connect operator
+ conditonBox.find('.vp-inner-popup-oper-connect').hide();
+
+ // show connect operator right before last one
+ $(this.wrapSelector('.vp-inner-popup-oper-connect:last')).show();
+ conditonBox.insertBefore(this.wrapSelector('.vp-inner-popup-condition-tbl tr:last'));
+ }
+
+ renderReplaceCondition() {
+ var content = new com_String();
+ content.appendLine('');
+ // delete condition button
+ content.appendLine('');
+ // condition line
+ content.appendLine('');
+ // - 1. column list
+ content.appendFormatLine('', 'vp-select m', 'vp-inner-popup-col-list');
+ // add .index
+ content.appendFormatLine('{2} ', '.index', '.index', 'index');
+ this.state.columnList.forEach(col => {
+ content.appendFormatLine('{3} ',
+ col.code, col.type, col.code, col.label);
+ });
+ content.appendLine(' ');
+ // - 2. operator
+ content.appendLine(this.templateForConditionOperator(''));
+ // - 3. oper-value
+ content.appendLine('');
+ // use text
+ content.appendFormatLine('{3} ',
+ 'vp-inner-popup-condition-use-text', 'vp-inner-popup-cond-use-text', 'Uncheck it if you want to use variable or numeric values.', 'Text');
+ content.appendLine('
');
+ content.appendLine('');
+ content.appendLine('');
+ content.appendLine('
');
+ content.appendLine(' ');
+ return content.toString();
+ }
+
+ templateForConditionOperator(dtype='object', className='vp-inner-popup-oper-list', prevValue='') {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-select s', className);
+ var operList = ['', '==', '!=', '<', '<=', '>', '>=', 'contains', 'not contains', 'starts with', 'ends with', 'isnull()', 'notnull()'];
+ if (dtype == '') {
+ // .index
+ operList = ['', '==', '!=', '<', '<=', '>', '>='];
+ } else if (dtype != 'object') {
+ operList = ['', '==', '!=', '<', '<=', '>', '>=', 'isnull()', 'notnull()'];
+ }
+ operList.forEach(oper => {
+ if (oper === prevValue) {
+ content.appendFormatLine('{1} ', oper, oper);
+ } else {
+ content.appendFormatLine('{1} ', oper, oper);
+ }
+ });
+ content.appendLine(' ');
+ return content.toString();
+ }
+
+ templateForConditionCondInput(category, dtype='object', className='vp-inner-popup-condition', prevValue='') {
+ var vpCondSuggest = new SuggestInput();
+ vpCondSuggest.addClass('vp-input m ' + className);
+ if (prevValue !== '') {
+ vpCondSuggest.setValue(prevValue);
+ }
+ if (category && category.length > 0) {
+ vpCondSuggest.setPlaceholder((dtype=='object'?'Categorical':dtype) + " dtype");
+ vpCondSuggest.setSuggestList(function () { return category; });
+ vpCondSuggest.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpCondSuggest.setNormalFilter(false);
+ } else {
+ vpCondSuggest.setPlaceholder(dtype==''?'Value':(dtype + " dtype"));
+ }
+ return vpCondSuggest.toTagString();
+ }
+
+ renderAsType() {
+ var astypeList = this.astypeList;
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-astype');
+ content.appendFormatLine('
', 'vp-inner-popup-astype-table');
+ content.appendLine(' ');
+ content.appendFormatLine('{0} {1} {3} '
+ , 'Column', 'Data type', 'vp-orange-text', 'New data type');
+ content.appendLine('');
+ let selectedList = this.state.selected;
+ if (selectedList.length === 0) {
+ // select all
+ selectedList = this.state.columnList;
+ }
+ selectedList.forEach((col, idx) => {
+ content.appendLine('');
+ content.appendFormatLine('{1} ', col.label, col.label);
+ content.appendFormatLine(' ', col.type);
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-inner-popup-astype' + idx);
+ suggestInput.addAttribute('data-col', col.code);
+ suggestInput.setSuggestList(function() { return astypeList; });
+ suggestInput.setPlaceholder('Data type');
+ content.appendFormatLine('{0} ', suggestInput.toTagString());
+ content.appendLine(' ');
+ });
+ content.appendLine('
');
+ content.append('
');
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderToDatetime() {
+ var content = new com_String();
+ let formatList = [
+ { label: 'Auto', value: 'auto' },
+ { label: '%Y/%m/%d', value: '%Y/%m/%d' },
+ { label: '%Y-%m-%d', value: '%Y-%m-%d' },
+ { label: '%y/%m/%d', value: '%y/%m/%d' },
+ { label: '%y-%m-%d', value: '%y-%m-%d' },
+ { label: '%d/%m/%Y', value: '%d/%m/%Y' },
+ { label: '%d-%m-%Y', value: '%d-%m-%Y' },
+ { label: '%d/%m/%y', value: '%d/%m/%y' },
+ { label: '%d-%m-%y', value: '%d-%m-%y' },
+ { label: 'Typing', value: 'typing' }
+ ];
+ let formatOptionTag = new com_String();
+ formatList.forEach(opt => {
+ formatOptionTag.appendFormat('{1} ', opt.value, opt.label);
+ });
+
+ content.appendFormat(`
+ `, this.state.selected[0].label, formatOptionTag.toString(), this.state.selected[0].label);
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderFillNAPage() {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-fillna-page');
+ content.appendLine('
');
+ content.appendLine(' ');
+ content.appendLine('');
+ content.appendFormatLine('{0} ', 'Method');
+ content.appendFormatLine('', 'vp-inner-popup-method');
+ content.appendFormatLine('{1} ', "value", "Value");
+ content.appendFormatLine('{1} ', "ffill", "Forward fill");
+ content.appendFormatLine('{1} ', "bfill", "Back fill");
+ let statsMethodList = ['mean', 'median', 'mode', 'min', 'max'];
+ content.appendLine('');
+ statsMethodList.forEach(opt => {
+ content.appendFormatLine('{1} ', opt, opt);
+ })
+ content.appendLine(' ');
+ content.appendLine(' ');
+ content.appendLine(' ');
+ content.appendFormatLine('', 'vp-inner-popup-value-row');
+ content.appendFormatLine('{0} ', 'Fill value');
+ content.appendLine('');
+ content.appendFormatLine(' '
+ , 'vp_fillValue', 'vp-inner-popup-value', 'Type or select value');
+ content.appendFormatLine('{1} '
+ , 'vp-inner-popup-valueastext', 'Text');
+ content.appendLine(' ');
+ content.appendLine(' ');
+ content.appendFormatLine('', 'vp-inner-popup-fill-row');
+ content.appendFormatLine('{0} ', 'Limit');
+ content.appendLine('');
+ content.appendFormatLine(' '
+ , 'vp-inner-popup-limit', 'Type limit to fill');
+ content.appendLine(' ');
+ content.appendLine(' ');
+ content.appendLine('
');
+ content.appendLine('
');
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ renderDropNAPage() {
+ // how / thresh / ignore_index
+ let content = ``;
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content);
+ return content.toString();
+ }
+
+ renderDropDupPage() {
+ // keep / ignore_index
+ let content = ``;
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content);
+ return content.toString();
+ }
+
+ renderFillOutPage() {
+ let content = ``;
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content);
+ return content.toString();
+ }
+
+
+ renderDropOutPage() {
+ var content = new com_String();
+ content.appendFormatLine('', 'vp-inner-popup-dropout-page');
+ content.appendLine('Are you sure to drop outliers from columns below?');
+ content.appendFormatLine('
{0} ', this.state.selected.map(col=>col.code).join(', '))
+ content.appendLine('
');
+
+ // set content
+ $(this.wrapSelector('.vp-inner-popup-body')).html(content.toString());
+ return content.toString();
+ }
+
+ openInputPopup(type, width=450, height=450) {
+ var title = '';
+ var content = '';
+ let size = { width: width, height: height };
+ let that = this;
+
+ $(this.wrapSelector('.vp-inner-popup-body')).empty();
+
+ switch (parseInt(type)) {
+ case FRAME_EDIT_TYPE.ADD_COL:
+ title = 'Add column';
+ size = { width: 550, height: 480 };
+ content = this.renderAddPage('column');
+ this.renderAddValueBox(0);
+
+ // bind event for adding values to calculate
+ $(this.wrapSelector('.vp-inner-popup-addvalue')).on('click', function() {
+ let valueCount = $(that.wrapSelector('.vp-inner-popup-value')).length;
+ let columnOptStr = '';
+ that.state.columnList.forEach(col => {
+ columnOptStr += `${col.label} `;
+ });
+ $(`
+ `).insertBefore($(that.wrapSelector('.vp-inner-popup-addvalue-row')));
+ that.renderAddValueBox(valueCount);
+
+ $(that.wrapSelector('.vp-inner-popup-delete-value')).off('click');
+ $(that.wrapSelector('.vp-inner-popup-delete-value')).on('click', function() {
+ // delete variable item
+ let index = $(this).closest('tr.vp-inner-popup-value-row').index();
+ $(that.wrapSelector('.vp-inner-popup-oper-row:nth(' + (index - 2) + ')')).remove();
+ $(that.wrapSelector('.vp-inner-popup-value-row:nth(' + (index - 1) + ')')).remove();
+ });
+ });
+
+ // bind multiselector
+ this.statsSelector = new MultiSelector(this.wrapSelector('.vp-inner-popup-stats-col-list'),
+ { mode: 'columns', parent: this.state.tempObj, showDescription: false }
+ );
+
+ // bind codemirror for apply textarea
+ this.applyCm = this.initCodemirror({
+ key: 'vp-inner-popup-apply-lambda',
+ selector: this.wrapSelector('.vp-inner-popup-apply-lambda'),
+ });
+ break;
+ case FRAME_EDIT_TYPE.ADD_ROW:
+ title = 'Add row';
+ size = { width: 450, height: 450 };
+ content = this.renderAddPage('row');
+ this.renderAddValueBox(0);
+
+ // bind event for adding values to calculate
+ $(this.wrapSelector('.vp-inner-popup-addvalue')).on('click', function() {
+ let valueCount = $(that.wrapSelector('.vp-inner-popup-value')).length;
+ $(`
+ `).insertBefore($(that.wrapSelector('.vp-inner-popup-addvalue-row')));
+ that.renderAddValueBox(valueCount);
+
+ $(that.wrapSelector('.vp-inner-popup-delete-value')).off('click');
+ $(that.wrapSelector('.vp-inner-popup-delete-value')).on('click', function() {
+ // delete variable item
+ let index = $(this).closest('tr.vp-inner-popup-value-row').index();
+ $(that.wrapSelector('.vp-inner-popup-oper-row:nth(' + (index - 2) + ')')).remove();
+ $(that.wrapSelector('.vp-inner-popup-value-row:nth(' + (index - 1) + ')')).remove();
+ });
+ });
+ break;
+ case FRAME_EDIT_TYPE.DROP:
+ title = 'Drop ';
+ if (this.state.axis === FRAME_AXIS.COLUMN) {
+ title += 'columns';
+ } else {
+ title += 'rows';
+ }
+ size = { width: 400, height: 200 };
+ content = this.renderDropPage();
+ break;
+ case FRAME_EDIT_TYPE.RENAME:
+ title = 'Rename ';
+ if (this.state.axis === FRAME_AXIS.ROW) {
+ title += 'rows';
+ content = this.renderRenamePage(FRAME_AXIS.ROW);
+ } else {
+ title += 'columns';
+ content = this.renderRenamePage(FRAME_AXIS.COLUMN);
+ }
+ break;
+ case FRAME_EDIT_TYPE.DISCRETIZE:
+ title = 'Discretize';
+ size = { width: 450, height: 450 };
+ content = this.renderDiscretizePage();
+ break;
+ case FRAME_EDIT_TYPE.DATA_SHIFT:
+ title = 'Data shift';
+ size = { width: 450, height: 300 };
+ content = this.renderShiftPage();
+
+ // set suggestinput
+ let freqFormats = [
+ {'label': 'infer', 'value': 'infer'},
+ {'label': 'second', 'value': 's'},
+ {'label': 'minute', 'value': 'T'},
+ {'label': 'hour', 'value': 'H'},
+ {'label': 'day', 'value': 'D'},
+ {'label': 'weekdays', 'value': 'B'},
+ {'label': 'week(Sunday)', 'value': 'W'},
+ {'label': 'week(Monday)', 'value': 'W-MON'},
+ {'label': 'first day of month', 'value': 'MS'},
+ {'label': 'last day of month', 'value': 'M'},
+ {'label': 'first weekday of month', 'value': 'BMS'},
+ {'label': 'last weekday of month', 'value': 'BM'}
+ ];
+ var freqInput = new SuggestInput();
+ freqInput.addClass('vp-inner-popup-freq');
+ freqInput.setPlaceholder('Type frequency');
+ freqInput.setSuggestList(freqFormats);
+ freqInput.setNormalFilter(true);
+ $(this.wrapSelector('.vp-inner-popup-freq')).replaceWith(function() {
+ return freqInput.toTagString();
+ });
+ break;
+ case FRAME_EDIT_TYPE.SORT_INDEX:
+ title = 'Sort by index';
+ content = this.renderSortPage('index');
+ break;
+ case FRAME_EDIT_TYPE.SORT_VALUES:
+ title = 'Sort by values';
+ content = this.renderSortPage('values');
+ break;
+ case FRAME_EDIT_TYPE.REPLACE:
+ title = 'Replace';
+ content = this.renderReplacePage();
+ size = { width: 550, height: 480 };
+
+ // // bind codemirror
+ // this.subsetCm = this.initCodemirror({
+ // key: 'vp-inner-popup-subset',
+ // selector: this.wrapSelector('.vp-inner-popup-subset'),
+ // type: 'readonly'
+ // });
+ // // set subset
+ // let contentState = that.getPopupContent(type);
+ // this.subsetEditor = new Subset({
+ // pandasObject: this.state.tempObj,
+ // selectedColumns: [ com_util.convertToStr(contentState.name, contentState.nameastext) ],
+ // config: { name: 'Subset' } },
+ // {
+ // useInputVariable: true,
+ // useInputColumns: true,
+ // targetSelector: this.wrapSelector('.vp-inner-popup-subset'),
+ // pageThis: this,
+ // allowSubsetTypes: ['iloc', 'loc'],
+ // beforeOpen: function(subsetThis) {
+ // let contentState = that.getPopupContent(type);
+ // let name = com_util.convertToStr(contentState.name, contentState.nameastext);
+ // subsetThis.state.selectedColumns = [ name ];
+ // },
+ // finish: function(code) {
+ // that.subsetCm.setValue(code);
+ // that.subsetCm.save();
+ // setTimeout(function () {
+ // that.subsetCm.refresh();
+ // }, 1);
+ // }
+ // });
+ // initial code
+ // var code = this.subsetEditor.generateCode();
+ // this.subsetCm.setValue(code);
+ // this.subsetCm.save();
+ // setTimeout(function () {
+ // that.subsetCm.refresh();
+ // }, 1);
+
+ // set dataselector
+ let replaceVarSelector = new DataSelector({
+ pageThis: this, id: 'vp_replaceVariable', classes: 'vp-inner-popup-value', placeholder: 'Type or select variable'
+ , withPopup: false
+ });
+ $(this.wrapSelector('.vp-inner-popup-body')).find('.vp-inner-popup-value').replaceWith(replaceVarSelector.toTagString());
+ break;
+ case FRAME_EDIT_TYPE.AS_TYPE:
+ title = 'Convert type';
+ content = this.renderAsType();
+ break;
+ case FRAME_EDIT_TYPE.TO_DATETIME:
+ title = 'Convert to Datetime';
+ size = { width: 500, height: 450 };
+ content = this.renderToDatetime();
+ break;
+ case FRAME_EDIT_TYPE.FILL_NA:
+ title = 'Fill NA';
+ content = this.renderFillNAPage();
+
+ // set dataselector
+ let valueSelector = new DataSelector({
+ pageThis: this, classes: 'vp-inner-popup-value', placeholder: 'Type or select value',
+ withPopup: false
+ });
+ $(this.wrapSelector('.vp-inner-popup-body')).find('.vp-inner-popup-value').replaceWith(valueSelector.toTagString());
+ break;
+ case FRAME_EDIT_TYPE.DROP_NA:
+ title = 'Drop NA';
+ content = this.renderDropNAPage();
+ break;
+ case FRAME_EDIT_TYPE.DROP_DUP:
+ title = 'Drop duplicates';
+ content = this.renderDropDupPage();
+ break;
+ case FRAME_EDIT_TYPE.FILL_OUT:
+ title = 'Fill outlier';
+ content = this.renderFillOutPage();
+
+ // set dataselector
+ let fillvalueSelector = new DataSelector({
+ pageThis: this, classes: 'vp-inner-popup-fillvalue', placeholder: 'Type or select value',
+ withPopup: false
+ });
+ $(this.wrapSelector('.vp-inner-popup-body')).find('.vp-inner-popup-fillvalue').replaceWith(fillvalueSelector.toTagString());
+ $(this.wrapSelector('.vp-inner-popup-body')).find('.vp-inner-popup-fillvalue').prop('disabled', true);
+ break;
+ case FRAME_EDIT_TYPE.DROP_OUT:
+ title = 'Drop outlier';
+ size = { width: 400, height: 200 };
+ content = this.renderDropOutPage();
+ break;
+ default:
+ type = FRAME_EDIT_TYPE.NONE;
+ break;
+ }
+
+ this.state.popup.type = type;
+
+ // set size and position
+ $(this.wrapSelector('.vp-inner-popup-box')).css({
+ width: size.width,
+ height: size.height,
+ left: 'calc(50% - ' + (size.width/2) + 'px)',
+ top: 'calc(50% - ' + (size.height/2) + 'px)',
+ });
+
+ // bindEventForAddPage
+ this.bindEventForPopupPage(type);
+
+ // set column list
+ vpKernel.getColumnList(this.state.tempObj).then(function(resultObj) {
+ let { result } = resultObj;
+ var { list } = JSON.parse(result);
+ var tag1 = new com_String();
+ var tag2 = new com_String();
+ tag1.appendFormatLine('', 'vp-inner-popup-var1col');
+ tag2.appendFormatLine('', 'vp-inner-popup-var2col');
+ list && list.forEach(col => {
+ tag1.appendFormatLine('{2} '
+ , col.value, col.label, col.label);
+ tag2.appendFormatLine('{2} '
+ , col.value, col.label, col.label);
+ });
+ tag1.appendLine(' ');
+ tag2.appendLine(' ');
+ // replace column list
+ $(that.wrapSelector('.vp-inner-popup-var1col')).replaceWith(function() {
+ return tag1.toString();
+ });
+ $(that.wrapSelector('.vp-inner-popup-var2col')).replaceWith(function() {
+ return tag2.toString();
+ });
+ });
+
+ // show popup box
+ this.openInnerPopup(title);
+ }
+
+ getPopupContent = function(type) {
+ let that = this;
+ var content = {};
+ switch (type) {
+ case FRAME_EDIT_TYPE.ADD_COL:
+ case FRAME_EDIT_TYPE.ADD_ROW:
+ let variableTuple = [];
+ let thisLevel = this.state.columnLevel;
+ if (type === FRAME_EDIT_TYPE.ADD_ROW) {
+ thisLevel = this.state.indexLevel;
+ }
+ for (let i = 0; i < thisLevel; i++) {
+ let val = $(this.wrapSelector('.vp-inner-popup-input' + i)).val();
+ let istext = $(this.wrapSelector('.vp-inner-popup-inputastext' + i)).prop('checked');
+ variableTuple.push(com_util.convertToStr(val, istext));
+ }
+ if (variableTuple.length > 1) {
+ content['name'] = '(' + variableTuple.join(',') + ')';
+ } else {
+ content['name'] = variableTuple.join(',');
+ }
+ var tab = $(this.wrapSelector('.vp-inner-popup-addtype')).val();
+ if (type === FRAME_EDIT_TYPE.ADD_ROW) {
+ tab = 'calculate';
+ }
+ content['addtype'] = tab;
+ if (tab == 'calculate') {
+ let values = [];
+ let opers = [];
+ $(this.wrapSelector('.vp-inner-popup-tab.calculate tr.vp-inner-popup-value-row')).each((idx, tag) => {
+ let varType = $(tag).find('.vp-inner-popup-vartype').val();
+ if (varType === 'variable') {
+ let valueastext = $(tag).find('.vp-inner-popup-istext').prop('checked');
+ values.push(com_util.convertToStr($(tag).find('.vp-inner-popup-value').val(), valueastext));
+ } else {
+ // columns
+ let column = $(tag).find('.vp-inner-popup-var-col-list').val();
+ values.push(com_util.formatString("{0}[{1}]", this.state.tempObj, column));
+ }
+ let oper = $(that.wrapSelector('.vp-inner-popup-oper:nth(' + idx + ')')).val();
+ if (oper && oper !== '') {
+ opers.push(oper);
+ }
+ });
+ content['values'] = values;
+ content['opers'] = opers;
+ } else if (tab == 'statistics') {
+ var colList = this.statsSelector.getDataList();
+ content['columns'] = colList.map(x => x.code);
+ content['method'] = $(this.wrapSelector('.vp-inner-popup-stats-method')).val();
+ } else if (tab == 'replace') {
+ content['target'] = $(this.wrapSelector('.vp-inner-popup-value-col-list option:selected')).data('code');
+ var useregex = $(this.wrapSelector('.vp-inner-popup-use-regex')).prop('checked');
+ content['useregex'] = useregex;
+ content['list'] = [];
+ for (var i=0; i <= this.state.popup.replace.index; i++) {
+ var origin = $(this.wrapSelector('.vp-inner-popup-origin' + i)).val();
+ var origintext = $(this.wrapSelector('.vp-inner-popup-origin-istext'+i)).prop('checked');
+ var replace = $(this.wrapSelector('.vp-inner-popup-replace' + i)).val();
+ var replacetext = $(this.wrapSelector('.vp-inner-popup-replace-istext'+i)).prop('checked');
+ if (origin && replace) {
+ content['list'].push({
+ origin: origin,
+ origintext: origintext,
+ replace: replace,
+ replacetext: replacetext
+ });
+ }
+ }
+ } else if (tab == 'apply') {
+ content['target'] = $(this.wrapSelector('.vp-inner-popup-apply-column')).val();
+ let caseList = [];
+ $(this.wrapSelector('.vp-inner-popup-apply-case-item')).each((idx, caseTag) => {
+ let condList = [];
+ let replaceValue = $(caseTag).find('.vp-inner-popup-apply-case-val').val();
+ let replaceValText = $(caseTag).find('.vp-inner-popup-apply-case-usetext').prop('checked');
+
+ let operTag = $(caseTag).find('.vp-inner-popup-apply-oper-list');
+ let condTag = $(caseTag).find('.vp-inner-popup-apply-condition');
+ let condTextTag = $(caseTag).find('.vp-inner-popup-apply-cond-usetext');
+ let operConnTag = $(caseTag).find('.vp-inner-popup-apply-oper-connect');
+ for (let i=0; i {
+ let condList = [];
+ let replaceValue = $(caseTag).find('.vp-inner-popup-apply-case-val').val();
+ let replaceValText = $(caseTag).find('.vp-inner-popup-apply-case-usetext').prop('checked');
+
+ let operTag = $(caseTag).find('.vp-inner-popup-apply-oper-list');
+ let condTag = $(caseTag).find('.vp-inner-popup-apply-condition');
+ let condTextTag = $(caseTag).find('.vp-inner-popup-apply-cond-usetext');
+ let operConnTag = $(caseTag).find('.vp-inner-popup-apply-oper-connect');
+ for (let i=0; i 1) {
+ content['level'] = $(this.wrapSelector('.vp-inner-popup-level')).val();
+ }
+ break;
+ case FRAME_EDIT_TYPE.SORT_INDEX:
+ content['axis'] = $(this.wrapSelector('.vp-inner-popup-axis')).val();
+ case FRAME_EDIT_TYPE.SORT_VALUES:
+ let values = [];
+ $(this.wrapSelector('.vp-inner-popup-sortby-item')).each((idx, tag) => {
+ values.push($(tag).data('code'));
+ });
+ content['values'] = values;
+ content['ascending'] = $(this.wrapSelector('.vp-inner-popup-isascending')).val();
+ break;
+ case FRAME_EDIT_TYPE.AS_TYPE:
+ let selectedList = this.state.selected;
+ if (selectedList.length === 0) {
+ // select all
+ selectedList = this.state.columnList;
+ }
+ selectedList.forEach((col, idx) => {
+ var value = $(this.wrapSelector('.vp-inner-popup-astype'+idx)).val();
+ if (value !== undefined && value !== '') {
+ content[idx] = {
+ label: col.code,
+ value: value
+ };
+ }
+ });
+ break;
+ case FRAME_EDIT_TYPE.TO_DATETIME:
+ content['format'] = $(this.wrapSelector('.vp-inner-popup-todt-format')).val();
+ content['format_typing'] = $(this.wrapSelector('.vp-inner-popup-todt-format-typing')).val();
+ content['dayfirst'] = $(this.wrapSelector('.vp-inner-popup-todt-dayfirst')).val();
+ content['newcol'] = $(this.wrapSelector('.vp-inner-popup-todt-new-col')).val();
+ var colList = [];
+ var addcolItemTags = $(this.wrapSelector('.vp-inner-popup-todt-addcol-item'));
+ addcolItemTags && addcolItemTags.each((idx, tag) => {
+ let colName = $(tag).find('.vp-inner-popup-todt-addcol-colname').val();
+ let dateType = $(tag).find('.vp-inner-popup-todt-addcol-type').val();
+ if (colName !== '' && dateType !== '') {
+ colList.push({ colName: colName, dateType: dateType });
+ }
+ });
+ content['collist'] = colList;
+ break;
+ case FRAME_EDIT_TYPE.DISCRETIZE:
+ content['input'] = $(this.wrapSelector('.vp-inner-popup-input')).val();
+ content['inputastext'] = $(this.wrapSelector('.vp-inner-popup-inputastext')).prop('checked');
+ content['bins'] = $(this.wrapSelector('.vp-inner-popup-bins')).val();
+ content['type'] = $(this.wrapSelector('.vp-inner-popup-discretizetype')).val();
+ content['isright'] = $(this.wrapSelector('.vp-inner-popup-right')).prop('checked');
+ let labelastext = $(this.wrapSelector('.vp-inner-popup-labelastext')).prop('checked');
+ let islabelchanged = $(this.wrapSelector('.vp-inner-popup-islabelchanged')).val() === 'true';
+ let isedgechanged = $(this.wrapSelector('.vp-inner-popup-isedgechanged')).val() === 'true';
+ let rangeTableTags = $(this.wrapSelector('.vp-inner-popup-range-table tbody tr'));
+ let labels = [];
+ let edges = [];
+ rangeTableTags && rangeTableTags.each((idx, tag) => {
+ if (islabelchanged === true) {
+ labels.push(com_util.convertToStr($(tag).find('.vp-inner-popup-label').val(), labelastext));
+ }
+ if (content['type'] === 'cut' && isedgechanged === true) {
+ edges.push($(tag).find('.vp-inner-popup-left-edge').val());
+ if (idx === (rangeTableTags.length - 1)) {
+ edges.push($(tag).find('.vp-inner-popup-right-edge').val());
+ }
+ }
+ });
+ content['labels'] = labels;
+ content['edges'] = edges;
+ break;
+ case FRAME_EDIT_TYPE.DATA_SHIFT:
+ content['periods'] = $(this.wrapSelector('.vp-inner-popup-periods')).val();
+ content['freq'] = $(this.wrapSelector('.vp-inner-popup-freq')).val();
+ let fillValue = $(this.wrapSelector('.vp-inner-popup-fillvalue')).val();
+ let fillValueAsText= $(this.wrapSelector('.vp-inner-popup-fillvalueastext')).prop('checked');
+ content['fill_value'] = '';
+ if (fillValue && fillValue !== '') {
+ content['fill_value'] = com_util.convertToStr(fillValue, fillValueAsText);
+ }
+ break;
+ case FRAME_EDIT_TYPE.FILL_NA:
+ content['method'] = $(this.wrapSelector('.vp-inner-popup-method')).val();
+ content['value'] = $(this.wrapSelector('.vp-inner-popup-value')).val();
+ content['valueastext'] = $(this.wrapSelector('.vp-inner-popup-valueastext')).prop('checked');
+ content['limit'] = $(this.wrapSelector('.vp-inner-popup-limit')).val();
+ break;
+ case FRAME_EDIT_TYPE.DROP_NA:
+ content['how'] = $(this.wrapSelector('.vp-inner-popup-how')).val();
+ content['thresh'] = $(this.wrapSelector('.vp-inner-popup-thresh')).val();
+ content['ignore_index'] = $(this.wrapSelector('.vp-inner-popup-ignoreindex')).val();
+ break;
+ case FRAME_EDIT_TYPE.FILL_OUT:
+ content['filltype'] = $(this.wrapSelector('.vp-inner-popup-filltype')).val();
+ content['fillvalue'] = $(this.wrapSelector('.vp-inner-popup-fillvalue')).val();
+ break;
+ case FRAME_EDIT_TYPE.DROP_DUP:
+ content['keep'] = $(this.wrapSelector('.vp-inner-popup-how')).val();
+ content['ignore_index'] = $(this.wrapSelector('.vp-inner-popup-ignoreindex')).val();
+ break;
+ default:
+ break;
+ }
+ return content;
+ }
+
+ templateForDataView() {
+ return this.renderInfoPage('');
+ }
+
+ renderDataView() {
+ super.renderDataView();
+
+ this.loadInfo();
+ $(this.wrapSelector('.vp-popup-dataview-box')).css('height', '300px');
+ }
+
+ renderInfoPage = function(renderedText, isHtml = true) {
+ var tag = new com_String();
+ tag.appendFormatLine('');
+ return tag.toString();
+ }
+
+ loadInfo() {
+ var that = this;
+
+ // get selected columns/indexes
+ var selected = [];
+ $(this.wrapSelector(`.${VP_FE_TABLE} th:not(.${VP_FE_TABLE_COLUMN_GROUP}).selected`)).each((idx, tag) => {
+ var label = $(tag).text();
+ var code = $(tag).data('code');
+ var type = $(tag).data('type');
+ selected.push({ label: label, code: code, type: type });
+ });
+ this.state.selected = selected;
+
+ var code = new com_String();
+ var locObj = new com_String();
+ locObj.appendFormat("{0}", this.state.tempObj);
+ if (this.state.selected.length > 0) {
+ var rowCode = ':';
+ var colCode = ':';
+ if (this.state.axis == FRAME_AXIS.ROW) {
+ rowCode = '[' + this.state.selected.map(col=>col.code).join(',') + ']';
+ }
+ if (this.state.axis == FRAME_AXIS.COLUMN) {
+ colCode = '[' + this.state.selected.map(col=>col.code).join(',') + ']';
+ }
+ locObj.appendFormat(".loc[{0},{1}]", rowCode, colCode);
+ }
+ // code.append(".value_counts()");
+ code.appendFormat('_vp_display_dataframe_info({0})', locObj.toString());
+
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { msg } = resultObj;
+ if (msg.content.data) {
+ var htmlText = String(msg.content.data["text/html"]);
+ var codeText = String(msg.content.data["text/plain"]);
+ if (htmlText != 'undefined') {
+ $(that.wrapSelector('.' + VP_FE_INFO_CONTENT)).replaceWith(function() {
+ return that.renderInfoPage(htmlText);
+ });
+ } else if (codeText != 'undefined') {
+ // plain text as code
+ $(that.wrapSelector('.' + VP_FE_INFO_CONTENT)).replaceWith(function() {
+ return that.renderInfoPage(codeText, false);
+ });
+ } else {
+ $(that.wrapSelector('.' + VP_FE_INFO_CONTENT)).replaceWith(function() {
+ return that.renderInfoPage('');
+ });
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ $(that.wrapSelector('.' + VP_FE_INFO_CONTENT)).replaceWith(function() {
+ return that.renderInfoPage(errorContent);
+ });
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ $(that.wrapSelector('.' + VP_FE_INFO_CONTENT)).replaceWith(function() {
+ return that.renderInfoPage(errorContent);
+ });
+ })
+ }
+
+ getTypeCode(type, content={}) {
+ var tempObj = this.state.tempObj;
+ var orgObj = this.state.originObj;
+ var type = parseInt(type);
+
+ if (!orgObj || orgObj == '') {
+ // object not selected
+
+ return '';
+ }
+
+ var selectedName = this.state.selected.map(col=>col.code).join(',');
+ var axis = this.state.axis;
+ var subsetObjStr = tempObj;
+ if (selectedName && selectedName !== '') {
+ if (this.state.selected.length > 1) {
+ subsetObjStr += "[[" + selectedName + "]]";
+ } else {
+ subsetObjStr += "[" + selectedName + "]";
+ }
+ }
+
+ var code = new com_String();
+ switch (type) {
+ case FRAME_EDIT_TYPE.INIT:
+ code.appendFormat('{0} = {1}.copy()', tempObj, orgObj);
+ this.config.checkModules = ['pd'];
+ break;
+ case FRAME_EDIT_TYPE.DROP:
+ code.appendFormat("{0}.drop([{1}], axis={2}, inplace=True)", tempObj, selectedName, axis);
+ break;
+ case FRAME_EDIT_TYPE.RENAME:
+ var renameList = [];
+ Object.keys(content['list']).forEach((key, idx) => {
+ if (content['list'][key].value !== undefined && content['list'][key].value !== '') {
+ renameList.push(com_util.formatString("{0}: {1}", content['list'][key].label, com_util.convertToStr(content['list'][key].value, content['list'][key].istext)));
+ }
+ });
+ if (renameList.length > 0) {
+ code.appendFormat("{0}.rename({1}={{2}}", tempObj, axis==FRAME_AXIS.ROW?'index':'columns', renameList.join(', '));
+ if (content['level'] !== undefined) {
+ code.appendFormat(", level={0}", content['level']);
+ }
+ code.append(', inplace=True)')
+ }
+ break;
+ case FRAME_EDIT_TYPE.DROP_NA:
+ var dropNAOptions = [];
+ if (axis == FRAME_AXIS.ROW) {
+ dropNAOptions.push("axis=1");
+ } else {
+ dropNAOptions.push("axis=0");
+ }
+ if (selectedName && selectedName !== '') {
+ dropNAOptions.push(com_util.formatString("subset=[{0}]", selectedName));
+ }
+ if (content.how && content.how !== '') {
+ dropNAOptions.push(com_util.formatString("how='{0}'", content.how));
+ }
+ if (content.thresh && content.thresh !== '') {
+ dropNAOptions.push(com_util.formatString("thresh={0}", content.thresh));
+ }
+ if (content.ignore_index && content.ignore_index !== '') {
+ dropNAOptions.push(com_util.formatString("ignore_index={0}", content.ignore_index));
+ }
+ dropNAOptions.push("inplace=True");
+ code.appendFormat("{0}.dropna({1})", tempObj, dropNAOptions.join(', '));
+ break;
+ case FRAME_EDIT_TYPE.DROP_DUP:
+ let dropDupOptions = [];
+ if (selectedName && selectedName !== '') {
+ dropDupOptions.push(com_util.formatString("subset=[{0}]", selectedName));
+ }
+ if (content.keep && content.keep !== '') {
+ dropDupOptions.push(com_util.formatString("keep={0}", content.keep));
+ }
+ if (content.ignore_index && content.ignore_index !== '') {
+ dropDupOptions.push(com_util.formatString("ignore_index={0}", content.ignore_index));
+ }
+ dropDupOptions.push("inplace=True");
+ code.appendFormat("{0}.drop_duplicates({1})", tempObj, dropDupOptions.join(', '));
+ break;
+ case FRAME_EDIT_TYPE.FILL_OUT:
+ if (axis == FRAME_AXIS.COLUMN) {
+ code.appendFormat("{0} = vp_fill_outlier({1}, [{2}], fill_type='{3}'", tempObj, tempObj, selectedName, content.filltype);
+ if (content.filltype === 'value') {
+ code.appendFormat(", fill_value_lst={0}", content.fillvalue);
+ }
+ code.append(")");
+ }
+ break;
+ case FRAME_EDIT_TYPE.DROP_OUT:
+ if (axis == FRAME_AXIS.COLUMN) {
+ code.appendFormat("{0} = vp_drop_outlier({1}, [{2}])", tempObj, tempObj, selectedName);
+ }
+ break;
+ case FRAME_EDIT_TYPE.LABEL_ENCODING:
+ if (axis == FRAME_AXIS.COLUMN) {
+ let encodedColNameList = this.state.selected.map(col=> {
+ if (col.code !== col.label) {
+ return { 'origin': com_util.formatString("'{0}'", col.label), 'encoded': com_util.formatString("'{0}'", col.label + '_label') };
+ }
+ return { 'origin': col.label, 'encoded': col.label + '_label' };
+ });
+ encodedColNameList.forEach((encodedColObj, idx) => {
+ if (idx > 0) {
+ code.appendLine();
+ }
+ code.appendFormat("{0}[{1}] = pd.Categorical({2}[{3}]).codes", tempObj, encodedColObj['encoded'], tempObj, encodedColObj['origin']);
+ });
+ }
+ break;
+ case FRAME_EDIT_TYPE.ONE_HOT_ENCODING:
+ if (axis == FRAME_AXIS.COLUMN) {
+ code.appendFormat("{0} = pd.get_dummies(data={1}, columns=[{2}])", tempObj, tempObj, selectedName);
+ }
+ break;
+ case FRAME_EDIT_TYPE.SET_IDX:
+ if (axis == FRAME_AXIS.COLUMN) {
+ code.appendFormat("{0}.set_index([{1}], inplace=True)", tempObj, selectedName);
+ }
+ break;
+ case FRAME_EDIT_TYPE.RESET_IDX:
+ code.appendFormat("{0}.reset_index(inplace=True)", tempObj);
+ break;
+ case FRAME_EDIT_TYPE.SORT_INDEX:
+ let selectedStr = '';
+ if (content.values.length > 1) {
+ selectedStr = content.values.join(',');
+ }
+ code.appendFormat("{0}.sort_index(axis={1}, ascending={2}", tempObj, content.axis, content.ascending);
+ if (selectedStr !== '') {
+ code.appendFormat(', level=[{0}]', selectedStr);
+ }
+ code.append(', inplace=True)');
+ break;
+ case FRAME_EDIT_TYPE.SORT_VALUES:
+ if (axis == FRAME_AXIS.COLUMN) {
+ let selectedStr = '';
+ if (content.values.length > 1) {
+ selectedStr = "[" + content.values.join(',') + "]";
+ } else {
+ selectedStr = content.values[0];
+ }
+ code.appendFormat("{0}.sort_values(by={1}, ascending={2}, inplace=True)", tempObj, selectedStr, content.ascending);
+ }
+ break;
+ case FRAME_EDIT_TYPE.ADD_COL:
+ // if no name entered
+ if (content.name == '') {
+ return '';
+ }
+ var tab = content.addtype;
+ if (tab == 'calculate') {
+ let values = [];
+ content['values'] && content['values'].forEach((val, idx) => {
+ if (idx > 0) {
+ values.push(content['opers'][idx - 1]);
+ }
+ values.push(val);
+ });
+ let valueStr = values.join(' ');
+ if (valueStr === "" || valueStr === "''") {
+ code.appendFormat("{0}[{1}] = np.nan", tempObj, content.name);
+ } else {
+ code.appendFormat("{0}[{1}] = {2}", tempObj, content.name, valueStr);
+ }
+ } else if (tab == 'statistics') {
+ code.appendFormat("{0}[{1}] = ", tempObj, content.name);
+ code.append(tempObj);
+ if (content['columns'].length > 0) {
+ code.appendFormat("[[{0}]]", content['columns'].join(','));
+ }
+ code.appendFormat(".apply(lambda x: x.{0}(numeric_only=True), axis=1)", content.method);
+ // code.appendFormat(".{0}(axis=1)", content.method); // FIXME: for pandas version upper 2.0.0
+ } else if (tab == 'replace') {
+ var replaceStr = new com_String();
+ var targetName = content['target'];
+ var useRegex = content['useregex'];
+ content['list'].forEach((obj, idx) => {
+ if (idx == 0) {
+ replaceStr.appendFormat("{0}: {1}"
+ , com_util.convertToStr(obj.origin, obj.origintext, useRegex)
+ , com_util.convertToStr(obj.replace, obj.replacetext, useRegex));
+ } else {
+ replaceStr.appendFormat(", {0}: {1}"
+ , com_util.convertToStr(obj.origin, obj.origintext, useRegex)
+ , com_util.convertToStr(obj.replace, obj.replacetext, useRegex));
+ }
+ });
+ code.appendFormat("{0}[{1}] = {2}[[{3}]].replace({{4}}", tempObj, content.name, tempObj, targetName, replaceStr);
+ if (useRegex) {
+ code.append(', regex=True');
+ }
+ code.append(')');
+ } else if (tab == 'apply') {
+ // code.appendFormat("{0}[{1}] = {2}[{3}].apply({4})", tempObj, content.name, tempObj, content.column, content.apply);
+ let lambdaCode = 'lambda x: ';
+ content['caseList'].forEach(obj => {
+ // value if (cond list) else
+ let caseCode = obj.value + ' ';
+ let condCode = '';
+ obj.condList.forEach((condObj, idx) => {
+ let { oper, cond, connector } = condObj;
+ if (oper === 'isnull()') {
+ condCode += `(pd.isnull(x))`;
+ } else if (oper === 'notnull()') {
+ condCode += `(pd.notnull(x))`;
+ } else if (oper === 'contains') {
+ condCode += `(${cond} in x)`;
+ } else if (oper === 'not contains') {
+ condCode += `(${cond} not in x)`;
+ } else if (oper === 'starts with') {
+ condCode += `(x.startswith(${cond}))`;
+ } else if (oper === 'ends with') {
+ condCode += `(x.endswith(${cond}))`;
+ } else {
+ condCode += `(x ${oper} ${cond})`;
+ }
+ if (connector !== undefined) {
+ condCode += ` ${connector} `;
+ }
+ });
+ caseCode += 'if ' + condCode + ' else ';
+ lambdaCode += caseCode;
+ });
+ lambdaCode += content['else'];
+ code.appendFormat("{0}[{1}] = {2}[{3}].apply({4})", tempObj, content.name, tempObj, content.target, lambdaCode);
+ } else if (tab === 'condition') {
+ code.appendFormat("{0}.loc[", tempObj);
+ content['list'].forEach((obj, idx) => {
+ let { colName, oper, cond, condAsText, connector } = obj;
+ code.append('(');
+
+ let colValue = tempObj;
+ if (colName && colName != '') {
+ if (colName == '.index') {
+ colValue += colName;
+ } else {
+ colValue += com_util.formatString('[{0}]', colName);
+ }
+ }
+ let condValue = com_util.convertToStr(cond, condAsText);
+ if (oper == 'contains') {
+ code.appendFormat('{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'not contains') {
+ code.appendFormat('~{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'starts with') {
+ code.appendFormat('{0}.str.startswith({1})', colValue, condValue);
+ } else if (oper == 'ends with') {
+ code.appendFormat('{0}.str.endswith({1})', colValue, condValue);
+ } else if (oper == 'isnull()' || oper == 'notnull()') {
+ code.appendFormat('{0}.{1}', colValue, oper);
+ } else {
+ code.appendFormat('{0}{1}{2}', colValue, oper != ''?(' ' + oper):'', condValue != ''?(' ' + condValue):'');
+ }
+ code.append(')');
+ if (idx < (content['list'].length - 1)) {
+ code.append(connector);
+ }
+ });
+ var value = com_util.convertToStr(content.value, content.valueastext);
+ if (value === '') {
+ value = 'np.nan';
+ }
+ code.appendFormat(", {0}] = {1}", content.name, value);
+ }
+ break;
+ case FRAME_EDIT_TYPE.ADD_ROW:
+ // if no name entered
+ if (content.name == '') {
+ return '';
+ }
+ var tab = content.addtype;
+ let values = [];
+ content['values'] && content['values'].forEach((val, idx) => {
+ if (idx > 0) {
+ values.push(content['opers'][idx - 1]);
+ }
+ values.push(val);
+ });
+ code.appendFormat("{0}.loc[{1}] = {2}", tempObj, content.name, values.join(' '));
+ break;
+ case FRAME_EDIT_TYPE.REPLACE:
+ var name = content.name;
+ var tab = content.replacetype;
+ if (tab === 'replace') {
+ var replaceStr = new com_String();
+ var useRegex = content['useregex'];
+ content['list'].forEach((obj, idx) => {
+ if (idx == 0) {
+ replaceStr.appendFormat("{0}: {1}"
+ , com_util.convertToStr(obj.origin, obj.origintext, useRegex)
+ , com_util.convertToStr(obj.replace, obj.replacetext, useRegex));
+ } else {
+ replaceStr.appendFormat(", {0}: {1}"
+ , com_util.convertToStr(obj.origin, obj.origintext, useRegex)
+ , com_util.convertToStr(obj.replace, obj.replacetext, useRegex));
+ }
+ });
+ if (selectedName && selectedName != '') {
+ selectedName = '[[' + selectedName + ']]';
+ }
+ code.appendFormat("{0}[{1}] = {2}{3}.replace({{4}}", tempObj, name, tempObj, selectedName, replaceStr);
+ if (useRegex) {
+ code.append(', regex=True');
+ }
+ code.append(')');
+ } else if (tab === 'condition') {
+ code.appendFormat("{0}.loc[", tempObj);
+ var condCode = new com_String();
+ content['list'].forEach((obj, idx) => {
+ let { colName, oper, cond, condAsText, connector } = obj;
+ condCode.append('(');
+
+ let colValue = tempObj;
+ if (colName && colName != '') {
+ if (colName == '.index') {
+ colValue += colName;
+ } else {
+ colValue += com_util.formatString('[{0}]', colName);
+ }
+ }
+ let condValue = com_util.convertToStr(cond, condAsText);
+ if (oper == 'contains') {
+ condCode.appendFormat('{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'not contains') {
+ condCode.appendFormat('~{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'starts with') {
+ condCode.appendFormat('{0}.str.startswith({1})', colValue, condValue);
+ } else if (oper == 'ends with') {
+ condCode.appendFormat('{0}.str.endswith({1})', colValue, condValue);
+ } else if (oper == 'isnull()' || oper == 'notnull()') {
+ condCode.appendFormat('{0}.{1}', colValue, oper);
+ } else {
+ condCode.appendFormat('{0}{1}{2}', colValue, oper != ''?(' ' + oper):'', condValue != ''?(' ' + condValue):'');
+ }
+ condCode.append(')');
+ if (idx < (content['list'].length - 1)) {
+ condCode.append(connector);
+ }
+ });
+ if (condCode.toString() === '') {
+ condCode.append(':');
+ }
+ var value = com_util.convertToStr(content.value, content.valueastext);
+ if (value === '') {
+ value = 'np.nan';
+ }
+ code.appendFormat("{0}, {1}] = {2}", condCode.toString(), content.name, value);
+ } else if (tab == 'apply') {
+ // code.appendFormat("{0}[{1}] = {2}[{3}].apply({4})", tempObj, content.name, tempObj, content.column, content.apply);
+ let lambdaCode = 'lambda x: ';
+ content['caseList'].forEach(obj => {
+ // value if (cond list) else
+ let caseCode = obj.value + ' ';
+ let condCode = '';
+ obj.condList.forEach((condObj, idx) => {
+ let { oper, cond, connector } = condObj;
+ if (oper === 'isnull()') {
+ condCode += `pd.isnull(x)`;
+ } else if (oper === 'notnull()') {
+ condCode += `pd.notnull(x)`;
+ } else if (oper === 'contains') {
+ condCode += `(${cond} in x)`;
+ } else if (oper === 'not contains') {
+ condCode += `(${cond} not in x)`;
+ } else if (oper === 'starts with') {
+ condCode += `(x.startswith(${cond}))`;
+ } else if (oper === 'ends with') {
+ condCode += `(x.endswith(${cond}))`;
+ } else {
+ condCode += `(x ${oper} ${cond})`;
+ }
+ if (connector !== undefined) {
+ condCode += ` ${connector} `;
+ }
+ });
+ caseCode += 'if ' + condCode + ' else ';
+ lambdaCode += caseCode;
+ });
+ lambdaCode += content['else'];
+ code.appendFormat("{0}[{1}] = {2}[{3}].apply({4})", tempObj, content.name, tempObj, content.target, lambdaCode);
+ }
+ break;
+ case FRAME_EDIT_TYPE.AS_TYPE:
+ var astypeStr = new com_String();
+ Object.keys(content).forEach((key, idx) => {
+ if (idx == 0) {
+ astypeStr.appendFormat("{0}: '{1}'", content[key].label, content[key].value);
+ } else {
+ astypeStr.appendFormat(", {0}: '{1}'", content[key].label, content[key].value);
+ }
+ });
+ code.appendFormat("{0} = {1}.astype({{2}})", tempObj, tempObj, astypeStr.toString());
+ break;
+ case FRAME_EDIT_TYPE.TO_DATETIME:
+ code.appendFormat("{0}['{1}'] = pd.to_datetime({2}[{3}]", tempObj, content['newcol'], tempObj, selectedName);
+ let optionList = [];
+ if (content['format'] === 'auto') {
+ if (content['dayfirst'] !== '') {
+ optionList.push(`dayfirst=${content['dayfirst']}`);
+ }
+ } else if (content['format'] === 'typing') {
+ if (content['format_typing'] !== '') {
+ optionList.push(`format='${content['format_typing']}'`);
+ }
+ } else {
+ optionList.push(`format='${content['format']}'`);
+ }
+ if (optionList.length > 0) {
+ code.appendFormat(', {0}', optionList.join(', '));
+ }
+ code.append(')');
+ if (content['collist'].length > 0) {
+ content['collist'].forEach(obj => {
+ code.appendLine();
+ code.appendFormat("{0}['{1}'] = {2}['{3}'].dt.{4}", tempObj, obj.colName, tempObj, content['newcol'], obj.dateType);
+ });
+ }
+ break;
+ case FRAME_EDIT_TYPE.DISCRETIZE:
+ let newColumn = com_util.convertToStr(content['input'], content['inputastext']);
+ let method = content['type'];
+ let bins = content['bins'];
+ if (method === 'cut') {
+ if (content['edges'] && content['edges'].length > 0) {
+ bins = "[" + content['edges'].join(',') + "]";
+ }
+ }
+
+ code.appendFormat("{0}[{1}] = pd.{2}({3}[{4}], {5}"
+ , tempObj, newColumn, method, tempObj, selectedName, bins);
+
+ if (method === 'cut' && content['isright'] === false) {
+ code.append(", right=False");
+ }
+ if (content['labels'] && content['labels'].length > 0) {
+ code.appendFormat(", labels=[{0}]", content['labels'].join(', '));
+ } else {
+ code.append(", labels=False");
+ }
+ code.append(')');
+ break;
+ case FRAME_EDIT_TYPE.DATA_SHIFT:
+ code.appendFormat("{0} = {1}.shift({2}", subsetObjStr, subsetObjStr, content['periods']);
+ if (content['freq'] && content['freq'] !== '') {
+ code.appendFormat(", freq='{0}'", content['freq']);
+ }
+ if (content['fill_value'] && content['fill_value'] !== '') {
+ code.appendFormat(", fill_value={0}", content['fill_value']);
+ }
+ code.append(')');
+ break;
+ case FRAME_EDIT_TYPE.FILL_NA:
+ code.appendFormat("{0} = {1}.fillna(", subsetObjStr, subsetObjStr);
+ if (content['method'] == 'value') {
+ code.append(com_util.convertToStr(content['value'], content['valueastext']));
+ } else if (content['method'] === 'ffill' || content['method'] === 'bfill') {
+ code.appendFormat("method='{0}'", content['method']);
+ if (content['limit'] && content['limit'] !== '') {
+ code.appendFormat(", limit={0}", content['limit']);
+ }
+ } else {
+ if (content['method'] === 'mode') {
+ // get mode()'s first element (mode returns Series)
+ code.appendFormat("{0}.{1}()[0]", subsetObjStr, content['method']);
+ } else {
+ code.appendFormat("{0}.{1}()", subsetObjStr, content['method']);
+ }
+ }
+ code.append(')');
+ break;
+ case FRAME_EDIT_TYPE.SHOW:
+ break;
+ }
+
+ return code.toString();
+ }
+
+ loadCode(codeStr, more=false) {
+ if (this.loading) {
+ return;
+ }
+
+ var that = this;
+ let { tempObj, lines, indexList } = this.state;
+ var prevLines = 0;
+ var scrollPos = -1;
+ if (more) {
+ prevLines = indexList.length;
+ scrollPos = $(this.wrapSelector('.vp-fe-table')).scrollTop();
+ }
+
+ var code = new com_String();
+ code.appendLine(codeStr);
+ code.appendFormat("{0}.iloc[{1}:{2}].to_json(orient='{3}')", tempObj, prevLines, lines, 'split');
+
+
+ this.loading = true;
+ vpKernel.execute(com_util.ignoreWarning(code.toString())).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ if (!result || result.length <= 0) {
+ return;
+ }
+ result = result.substr(1,result.length - 2).replaceAll('\\\\', '\\');
+ result = result.replaceAll('\'', "\\'"); // TEST: need test
+ // result = result.replaceAll('\\"', "\"");
+ var data = JSON.parse(result);
+
+ vpKernel.getColumnList(tempObj).then(function(colResObj) {
+ try {
+ let columnResult = colResObj.result;
+ var columnInfo = JSON.parse(columnResult);
+ let { name:columnName='', level:columnLevel, list:columnList } = columnInfo;
+ // var columnList = data.columns;
+ var indexList = data.index;
+ var dataList = data.data;
+
+ columnList = columnList.map(col => { return { label: col.label, type: col.dtype, code: col.value, isNumeric: col.is_numeric } });
+ indexList = indexList.map(idx => { return { label: idx, code: idx } });
+
+ if (!more) {
+ // table
+ var table = new com_String();
+ // table.appendFormatLine('', 1, 'dataframe');
+ table.appendLine('');
+ if (columnLevel > 1) {
+ for (let colLevIdx = 0; colLevIdx < columnLevel; colLevIdx++) {
+ table.appendLine(' ');
+ let colIdx = 0;
+ let colSpan = 1;
+ while (colIdx < columnList.length) {
+ let col = columnList[colIdx];
+ let colCode = col.code.slice(0, colLevIdx + 1).join(',');
+ var colIcon = '';
+ if (col.isNumeric === true) {
+ colIcon = ' ';
+ } else {
+ colIcon = ' ';
+ }
+ let nextCol = columnList[colIdx + 1];
+ if (nextCol && nextCol.code.slice(0, colLevIdx + 1).join(',') === colCode) {
+ colSpan++;
+ } else {
+ let colClass = '';
+ let selected = ''; // set class if it's leaf node of columns on multi-level
+ if (that.state.axis == FRAME_AXIS.COLUMN && that.state.selected.map(col=>col.code[colLevIdx]).includes(colCode)) {
+ selected = 'selected';
+ }
+ if ((columnLevel - 1) === colLevIdx) {
+ colClass = VP_FE_TABLE_COLUMN;
+ } else {
+ colClass = VP_FE_TABLE_COLUMN_GROUP;
+ }
+ table.appendFormatLine('{8}{9} '
+ , colCode, FRAME_AXIS.COLUMN, col.type, col.label[colLevIdx-1], col.label[colLevIdx], colClass, selected, colSpan, colIcon, col.label[colLevIdx]);
+ colSpan = 1;
+ }
+ colIdx++;
+ }
+
+ // add column
+ // LAB: img to url
+ // table.appendFormatLine(' ', VP_FE_ADD_COLUMN, com_Const.IMAGE_PATH + 'plus.svg');
+ if (colLevIdx === 0) {
+ table.appendFormatLine('
', VP_FE_ADD_COLUMN, 'vp-icon-plus');
+ }
+
+ table.appendLine(' ');
+ }
+ } else {
+ table.appendLine(' ');
+ columnList && columnList.forEach(col => {
+ var colCode = col.code;
+ var colIcon = '';
+ if (col.isNumeric === true) {
+ colIcon = ' ';
+ } else {
+ colIcon = ' ';
+ }
+ var colClass = '';
+ if (that.state.axis == FRAME_AXIS.COLUMN && that.state.selected.map(col=>col.code).includes(colCode)) {
+ colClass = 'selected';
+ }
+ table.appendFormatLine('{6}{7} '
+ , colCode, FRAME_AXIS.COLUMN, col.type, col.label, VP_FE_TABLE_COLUMN, colClass, colIcon, col.label);
+ });
+ // // add column
+ table.appendFormatLine('
', VP_FE_ADD_COLUMN, 'vp-icon-plus');
+
+ table.appendLine(' ');
+ }
+ table.appendLine(' ');
+ table.appendLine('');
+
+ dataList && dataList.forEach((row, idx) => {
+ table.appendLine('');
+ var idxName = indexList[idx].label;
+ var idxLabel = com_util.convertToStr(idxName, typeof idxName == 'string');
+ var idxClass = '';
+ if (that.state.axis == FRAME_AXIS.ROW && that.state.selected.includes(idxLabel)) {
+ idxClass = 'selected';
+ }
+ table.appendFormatLine('{4} ', idxLabel, FRAME_AXIS.ROW, VP_FE_TABLE_ROW, idxClass, idxName);
+ row.forEach((cell, colIdx) => {
+ if (cell == null) {
+ cell = 'NaN';
+ }
+ var cellType = columnList[colIdx].type;
+ if (cellType.includes('datetime')) {
+ cell = new Date(parseInt(cell)).toLocaleString();
+ }
+ table.appendFormatLine('{0} ', cell);
+ });
+ // empty data
+ // table.appendLine(' ');
+ table.appendLine(' ');
+ });
+ // add row
+ table.appendLine('');
+ // LAB: img to url
+ // table.appendFormatLine(' ', VP_FE_ADD_ROW, com_Const.IMAGE_PATH + 'plus.svg');
+ // table.appendFormatLine('
', VP_FE_ADD_ROW, 'vp-icon-plus');
+ table.appendLine(' ');
+ table.appendLine(' ');
+ $(that.wrapSelector('.' + VP_FE_TABLE)).replaceWith(function() {
+ return that.renderTable(table.toString());
+ });
+ } else {
+ var table = new com_String();
+ dataList && dataList.forEach((row, idx) => {
+ table.appendLine('');
+ var idxName = indexList[idx].label;
+ var idxLabel = com_util.convertToStr(idxName, typeof idxName == 'string');
+ var idxClass = '';
+ if (that.state.axis == FRAME_AXIS.ROW && that.state.selected.includes(idxLabel)) {
+ idxClass = 'selected';
+ }
+ table.appendFormatLine('{4} ', idxLabel, FRAME_AXIS.ROW, VP_FE_TABLE_ROW, idxClass, idxName);
+ row.forEach((cell, colIdx) => {
+ if (cell == null) {
+ cell = 'NaN';
+ }
+ var cellType = columnList[colIdx].type;
+ if (cellType.includes('datetime')) {
+ cell = new Date(parseInt(cell)).toLocaleString();
+ }
+ table.appendFormatLine('{0} ', cell);
+ });
+ // empty data
+ // table.appendLine(' ');
+ table.appendLine(' ');
+ });
+ // insert before last tr tag(add row button)
+ $(table.toString()).insertBefore($(that.wrapSelector('.' + VP_FE_TABLE + ' tbody tr:last')));
+ }
+
+ // save columnList & indexList as state
+ that.state.columnLevel = columnLevel;
+ that.state.columnList = columnList;
+ if (!more) {
+ that.state.indexList = indexList;
+ } else {
+ that.state.indexList = that.state.indexList.concat(indexList);
+ }
+
+
+ // load info
+ that.loadInfo();
+ // load toolbar
+ that.renderToolbar();
+ // add to stack
+ if (codeStr !== '') {
+ let newSteps = codeStr.split('\n');
+ that.state.steps = [
+ ...that.state.steps,
+ ...newSteps
+ ]
+ var replacedCode = codeStr.replaceAll(that.state.tempObj, that.state.returnObj);
+ that.setPreview(replacedCode);
+ }
+
+ // if add column, go to the right position
+ if (that.state.popup.type === FRAME_EDIT_TYPE.ADD_COL) {
+ $(that.wrapSelector('.vp-fe-add-column'))[0].scrollIntoView();
+ }
+
+ // if scrollPos is saved, go to the position
+ if (scrollPos >= 0) {
+ $(that.wrapSelector('.vp-fe-table')).scrollTop(scrollPos);
+ }
+
+ that.loading = false;
+ } catch (err1) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err1);
+ that.loading = false;
+ throw err1;
+ }
+ });
+ } catch (err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+ that.loading = false;
+ }
+ }).catch(function(resultObj) {
+ let { result, msg, ename, evalue, status } = resultObj;
+ if (result) {
+ // NOTEBOOK: notebook error FIXME: migrate it on com_Kernel.execute
+ vpLog.display(VP_LOG_TYPE.ERROR, result?.ename + ': ' + result?.evalue, msg, code.toString());
+ if (that.isHidden() == false) {
+ // show alert modal only if this popup is visible
+ com_util.renderAlertModal(result?.ename + ': ' + result?.evalue, { content: code.toString(), type: 'code' });
+ }
+ } else {
+ // LAB: lab error FIXME: migrate it on com_Kernel.execute
+ vpLog.display(VP_LOG_TYPE.ERROR, ename + ': ' + evalue, status, code.toString());
+ if (that.isHidden() == false) {
+ // show alert modal only if this popup is visible
+ com_util.renderAlertModal(ename + ': ' + evalue, { content: code.toString(), type: 'code' });
+ }
+ }
+ that.loading = false;
+ });
+
+ return code.toString();
+ }
+
+ showMenu(left, top) {
+ if (this.state.axis == 0) {
+ // row
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).find('div[data-axis="col"]').hide();
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).find('div[data-axis="row"]').show();
+
+ // change sub-box style
+ $(this.wrapSelector(com_util.formatString('.{0}.vp-fe-sub-cleaning', VP_FE_MENU_SUB_BOX))).css({ 'top': '90px'});
+ } else if (this.state.axis == 1) {
+ // column
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).find('div[data-axis="row"]').hide();
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).find('div[data-axis="col"]').show();
+
+ // change sub-box style
+ $(this.wrapSelector(com_util.formatString('.{0}.vp-fe-sub-cleaning', VP_FE_MENU_SUB_BOX))).css({ 'top': '120px'});
+ }
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).css({ top: top, left: left })
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).show();
+ }
+
+ hideMenu() {
+ $(this.wrapSelector(com_util.formatString('.{0}', VP_FE_MENU_BOX))).hide();
+ }
+
+ hide() {
+ super.hide();
+ this.subsetEditor && this.subsetEditor.hide();
+ }
+
+ close() {
+ super.close();
+ this.subsetEditor && this.subsetEditor.close();
+ }
+
+ remove() {
+ super.remove();
+ this.subsetEditor && this.subsetEditor.remove();
+ }
+
+ }
+
+ const VP_FE_BTN = 'vp-fe-btn';
+
+ const VP_FE_TITLE = 'vp-fe-title';
+
+ const VP_FE_MENU_BOX = 'vp-fe-menu-box';
+ const VP_FE_MENU_SUB_BOX = 'vp-fe-menu-sub-box';
+ const VP_FE_MENU_ITEM = 'vp-fe-menu-item';
+
+ const VP_FE_POPUP_BOX = 'vp-fe-popup-box';
+ const VP_FE_POPUP_BODY = 'vp-fe-popup-body';
+ const VP_FE_POPUP_OK = 'vp-fe-popup-ok';
+
+ const VP_FE_TABLE = 'vp-fe-table';
+ const VP_FE_TABLE_COLUMN = 'vp-fe-table-column';
+ const VP_FE_TABLE_COLUMN_GROUP = 'vp-fe-table-column-group';
+ const VP_FE_TABLE_ROW = 'vp-fe-table-row';
+ const VP_FE_ADD_COLUMN = 'vp-fe-add-column';
+ const VP_FE_ADD_ROW = 'vp-fe-add-row';
+ const VP_FE_TABLE_MORE = 'vp-fe-table-more';
+
+ const VP_FE_INFO = 'vp-fe-info';
+ const VP_FE_INFO_CONTENT = 'vp-fe-info-content';
+
+ const VP_FE_PREVIEW_BOX = 'vp-fe-preview-box';
+ const VP_FE_BUTTON_PREVIEW = 'vp-fe-btn-preview';
+ const VP_FE_BUTTON_DATAVIEW = 'vp-fe-btn-dataview';
+
+ // search rows count at once
+ const TABLE_LINES = 10;
+
+ const FRAME_EDIT_TYPE = {
+ NONE: -1,
+ INIT: 0,
+
+ ADD_COL: 97,
+ ADD_ROW: 98,
+ DROP: 3,
+ RENAME: 2,
+ AS_TYPE: 10,
+ TO_DATETIME: 19,
+ REPLACE: 9,
+ DISCRETIZE: 15,
+
+ SET_IDX: 7,
+ RESET_IDX: 8,
+ DATA_SHIFT: 14,
+
+ SORT_INDEX: 16,
+ SORT_VALUES: 17,
+
+ ONE_HOT_ENCODING: 6,
+ LABEL_ENCODING: 12,
+
+ FILL_NA: 13,
+ DROP_NA: 4,
+ FILL_OUT: 18,
+ DROP_OUT: 11,
+ DROP_DUP: 5,
+
+ SHOW: 99
+ }
+
+ const FRAME_AXIS = {
+ NONE: -1,
+ ROW: 0,
+ COLUMN: 1
+ }
+
+ const FRAME_SELECT_TYPE = {
+ NONE: -1, // no problem with every selection type
+ SINGLE: 0, // only single select supported
+ MULTI: 1 // more than 1 selection needed
+ }
+
+ return Frame;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Groupby.js b/visualpython/js/m_apps/Groupby.js
new file mode 100644
index 00000000..589882f0
--- /dev/null
+++ b/visualpython/js/m_apps/Groupby.js
@@ -0,0 +1,1129 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Groupby.js
+ * Author : Black Logic
+ * Note : Apps > Groupby
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Groupby
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/groupby.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/groupby'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/MultiSelector'
+], function(gbHtml, gbCss, com_Const, com_String, com_util, PopupComponent, SuggestInput, MultiSelector) {
+
+ /**
+ * Groupby
+ */
+ class Groupby extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.size = { width: 700, height: 550 };
+ this.config.checkModules = ['pd'];
+
+ this.periodList = [
+ { label: 'business day', value: 'B'},
+ { label: 'custom business day', value: 'C'},
+ { label: 'calendar day', value: 'D'},
+ { label: 'weekly', value: 'W'},
+ { label: 'month end', value: 'M'},
+ { label: 'semi-month end', value: 'SM'},
+ { label: 'business month end', value: 'BM'},
+ { label: 'custom business month end', value: 'CBM'},
+ { label: 'month start', value: 'MS'},
+ { label: 'semi-month start', value: 'SMS'},
+ { label: 'business month start', value: 'BMS'},
+ { label: 'custom business month start', value: 'CBMS'},
+ { label: 'quarter end', value: 'Q'},
+ { label: 'business quarter end', value: 'BQ'},
+ { label: 'quarter start', value: 'QS'},
+ { label: 'business quarter start', value: 'BQS'},
+ { label: 'year end', value: 'Y'},
+ { label: 'business year end', value: 'BY'},
+ { label: 'year start', value: 'YS'},
+ { label: 'business year start', value: 'BYS'},
+ { label: 'business hour', value: 'BH'},
+ { label: 'hourly', value: 'H'},
+ { label: 'minutely', value: 'min'},
+ { label: 'secondly', value: 'S'},
+ { label: 'milliseconds', value: 'ms'},
+ { label: 'microseconds', value: 'us'},
+ { label: 'nanoseconds', value: 'N'}
+ ]
+
+ this.methodList = [
+ { label: 'None', value: '' },
+ { label: 'count', value: "count" },
+ { label: 'first', value: "first" },
+ { label: 'last', value: "last" },
+ { label: 'size', value: "size" },
+ { label: 'std', value: "std" },
+ { label: 'sum', value: "sum" },
+ { label: 'max', value: "max" },
+ { label: 'mean', value: "mean" },
+ { label: 'median', value: "median" },
+ { label: 'min', value: "min" },
+ { label: 'quantile', value: "quantile" },
+ ]
+
+ this.state = {
+ variable: '',
+ groupby: [],
+ useGrouper: false,
+ grouperNumber: 0,
+ grouperPeriod: this.periodList[0].value,
+ display: [],
+ method: this.methodList[0].value,
+ advanced: false,
+ allocateTo: '',
+ resetIndex: false,
+
+ advPageDom: '',
+ advColList: [],
+ advMethodList: [],
+ advMethodUserList: [],
+ advNamingList: [],
+ ...this.state
+ };
+
+ this.popup = {
+ type: '',
+ targetSelector: '',
+ ColSelector: undefined
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ //====================================================================
+ // User operation Events
+ //====================================================================
+ // variable change event
+ $(document).on('change', this.wrapSelector('#vp_gbVariable'), function() {
+ // if variable changed, clear groupby, display
+ var newVal = $(this).val();
+ if (newVal != that.state.variable) {
+ $(that.wrapSelector('#vp_gbBy')).val('');
+ $(that.wrapSelector('#vp_gbDisplay')).val('');
+ that.state.variable = newVal;
+ that.state.groupby = [];
+ that.state.display = [];
+ }
+ });
+
+ // variable refresh event
+ $(document).on('click', this.wrapSelector('.vp-gb-df-refresh'), function() {
+ that.loadVariableList();
+ });
+
+ // groupby change event
+ $(document).on('change', this.wrapSelector('#vp_gbBy'), function(event) {
+ var colList = event.dataList;
+ that.state.groupby = colList;
+
+ if (colList && colList.length == 1
+ && colList[0].type.includes('datetime')) {
+ $(that.wrapSelector('#vp_gbByGrouper')).removeAttr('disabled');
+ } else {
+ $(that.wrapSelector('#vp_gbByGrouper')).attr('disabled', true);
+ }
+ });
+
+ // groupby select button event
+ $(document).on('click', this.wrapSelector('#vp_gbBy'), function() {
+ that.openColumnSelector($(that.wrapSelector('#vp_gbBy')), 'Select columns to group');
+ });
+
+ // groupby grouper event
+ $(document).on('change', this.wrapSelector('#vp_gbByGrouper'), function() {
+ var useGrouper = $(this).prop('checked');
+ that.state.useGrouper = useGrouper;
+
+ if (useGrouper == true) {
+ $(that.wrapSelector('.vp-gb-by-grouper-box')).show();
+ } else {
+ $(that.wrapSelector('.vp-gb-by-grouper-box')).hide();
+ }
+ });
+
+ // grouper number change event
+ $(document).on('change', this.wrapSelector('#vp_gbByGrouperNumber'), function() {
+ that.state.grouperNumber = $(this).val();
+ });
+
+ // grouper period change event
+ $(document).on('change', this.wrapSelector('#vp_gbByGrouperPeriod'), function() {
+ that.state.grouperPeriod = $(this).val();
+ });
+
+ // display change event
+ $(document).on('change', this.wrapSelector('#vp_gbDisplay'), function(event) {
+ var colList = event.dataList;
+ that.state.display = colList;
+
+ if ((colList && colList.length == 1) || that.state.method === 'size') {
+ $(that.wrapSelector('#vp_gbToFrame')).parent().show();
+ } else {
+ $(that.wrapSelector('#vp_gbToFrame')).parent().hide();
+ }
+ });
+
+ // display select button event
+ $(document).on('click', this.wrapSelector('#vp_gbDisplay'), function() {
+ // exclude groupby columns
+ let excludeList = that.state.groupby.map(x => x.code);
+ that.openColumnSelector($(that.wrapSelector('#vp_gbDisplay')), 'Select columns to display', [], excludeList);
+ });
+
+ // method select event
+ $(document).on('change', this.wrapSelector('#vp_gbMethodSelect'), function() {
+ var method = $(this).val();
+ that.state.method = method;
+ $(that.wrapSelector('#vp_gbMethod')).val(method);
+
+ if (method === 'size' || (that.state.display && that.state.display.length == 1)) {
+ $(that.wrapSelector('#vp_gbToFrame')).parent().show();
+ } else {
+ $(that.wrapSelector('#vp_gbToFrame')).parent().hide();
+ }
+ });
+
+ // advanced checkbox event
+ $(document).on('change', this.wrapSelector('#vp_gbAdvanced'), function() {
+ var advanced = $(this).prop('checked');
+ that.state.advanced = advanced;
+
+ if (advanced == true) {
+ // change method display
+ $(that.wrapSelector('#vp_gbMethod')).val('aggregate');
+ $(that.wrapSelector('#vp_gbMethodSelect')).hide();
+ $(that.wrapSelector('#vp_gbMethod')).show();
+ // show advanced box
+ $(that.wrapSelector('.vp-gb-adv-box')).show();
+ } else {
+ $(that.wrapSelector('#vp_gbMethod')).val('sum');
+ $(that.wrapSelector('#vp_gbMethodSelect')).show();
+ $(that.wrapSelector('#vp_gbMethod')).hide();
+ // hide advanced box
+ $(that.wrapSelector('.vp-gb-adv-box')).hide();
+ }
+ });
+
+
+ // allocateTo event
+ $(document).on('change', this.wrapSelector('#vp_gbAllocateTo'), function() {
+ that.state.allocateTo = $(this).val();
+ });
+
+ // to dataframe event
+ $(document).on('change', this.wrapSelector('#vp_gbToFrame'), function() {
+ that.state.toFrame = $(this).prop('checked') == true;
+ });
+
+ // reset index checkbox event
+ $(document).on('change', this.wrapSelector('#vp_gbResetIndex'), function() {
+ that.state.resetIndex = $(this).prop('checked');
+ });
+
+ //====================================================================
+ // Advanced box Events
+ //====================================================================
+ // add advanced item
+ $(document).on('click', this.wrapSelector('#vp_gbAdvAdd'), function() {
+ that.renderAdvancedItem();
+ });
+
+ // advanced item - column change event
+ $(document).on('change', this.wrapSelector('.vp-gb-adv-col'), function(event) {
+ var colList = event.dataList;
+ var idx = $(that.wrapSelector('.vp-gb-adv-col')).index(this);
+
+ // if there's change, reset display namings
+ // var previousList = that.state.advColList[idx];
+ // if (!previousList || colList.length !== previousList.length
+ // || !colList.map(col=>col.code).slice().sort().every((val, idx) => {
+ // return val === previousList.map(col=>col.code).slice().sort()[idx]
+ // })) {
+ // that.state.advNamingList = []
+ // $(this).parent().find('.vp-gb-adv-naming').val('');
+ // $(this).parent().find('.vp-gb-adv-naming').data('dict', {});
+ // }
+ var namingDict = that.state.advNamingList[idx];
+ if (namingDict) {
+ // namingDict = namingDict.filter(key => colList.map(col=>col.code).includes(key));
+ Object.keys(namingDict).forEach(key => {
+ if (!colList.map(col=>col.code).includes(key)) {
+ delete namingDict[key];
+ }
+ });
+ that.state.advNamingList[idx] = namingDict;
+ $(this).parent().find('.vp-gb-adv-naming').val(Object.values(namingDict).map(val => "'" + val +"'").join(','));
+ $(this).parent().find('.vp-gb-adv-naming').data('dict', namingDict);
+ }
+
+ that.state.advColList[idx] = colList;
+ });
+
+ // edit target columns
+ $(document).on('click', this.wrapSelector('.vp-gb-adv-col'), function() {
+ var includeList = that.state.display;
+ if (includeList && includeList.length > 0) {
+ includeList = includeList.map(col => col.code);
+ }
+ // exclude groupby columns
+ let excludeList = that.state.groupby.map(x => x.code);
+ that.openColumnSelector($(this).parent().find('.vp-gb-adv-col'), 'Select columns', includeList, excludeList);
+ });
+
+ // select method
+ $(document).on('click', this.wrapSelector('.vp-gb-adv-method'), function() {
+ // var method = $(this).val();
+ // var parentDiv = $(this).parent();
+ // if (method == 'typing') {
+ // // change it to typing input
+ // $(parentDiv).find('.vp-gb-adv-method-selector').hide();
+ // $(parentDiv).find('.vp-gb-adv-method').val('');
+ // $(parentDiv).find('.vp-gb-adv-method-box').show();
+ // } else {
+ // $(parentDiv).find('.vp-gb-adv-method').val(com_util.formatString("'{0}'", method));
+ // }
+ that.openMethodSelector($(this).parent().find('.vp-gb-adv-method'), 'Select methods');
+ });
+
+ // return to selecting method
+ // $(document).on('click', this.wrapSelector('.vp-gb-adv-method-return'), function() {
+ // var defaultValue = '';
+ // var parentDiv = $(this).parent().parent();
+ // $(parentDiv).find('.vp-gb-adv-method-selector').val(defaultValue);
+ // $(parentDiv).find('.vp-gb-adv-method').val(defaultValue);
+ // // show and hide
+ // $(parentDiv).find('.vp-gb-adv-method-selector').show();
+ // $(parentDiv).find('.vp-gb-adv-method-box').hide();
+ // });
+ // advanced item - method change event
+ $(document).on('change', this.wrapSelector('.vp-gb-adv-method'), function(event) {
+ var { list, userList } = event;
+ var idx = $(that.wrapSelector('.vp-gb-adv-method')).index(this);
+ that.state.advMethodList[idx] = list;
+ that.state.advMethodUserList[idx] = userList;
+ });
+
+ // advanced item - user method add event
+ $(document).on('click', this.wrapSelector('#vp_gbMethodUserAdd'), function(event) {
+ let userMethod = $(that.wrapSelector('#vp_gbMethodUser')).val();
+ let useText = $(that.wrapSelector('#vp_gbMethodUserAsText')).prop('checked');
+ let userCode = userMethod;
+ if (useText) {
+ userCode = "'" + userMethod + "'";
+ }
+ that._addUserMethod(userCode);
+ });
+
+ // advanced item - user method add event by enter
+ $(document).on('keyup', this.wrapSelector('#vp_gbMethodUser'), function(event) {
+ var keycode = event.keyCode
+ ? event.keyCode
+ : event.which;
+ if (keycode == 13) { // enter
+ let userMethod = $(this).val();
+ let useText = $(that.wrapSelector('#vp_gbMethodUserAsText')).prop('checked');
+ let userCode = userMethod;
+ if (useText) {
+ userCode = "'" + userMethod + "'";
+ }
+ that._addUserMethod(userCode);
+ }
+ });
+
+
+ // advanced item - naming change event
+ $(document).on('change', this.wrapSelector('.vp-gb-adv-naming'), function(event) {
+ var namingDict = event.namingDict;
+ var idx = $(that.wrapSelector('.vp-gb-adv-naming')).index(this);
+ that.state.advNamingList[idx] = namingDict;
+ });
+
+ // edit columns naming
+ $(document).on('click', this.wrapSelector('.vp-gb-adv-naming'), function() {
+ var parentDiv = $(this).parent();
+ var columns = $(parentDiv).find('.vp-gb-adv-col').data('list');
+ if (columns && columns.length > 0) {
+ columns = columns.map(col => col.code);
+ }
+ var method = $(parentDiv).find('.vp-gb-adv-method').data('list');
+ var userMethod = $(parentDiv).find('.vp-gb-adv-method').data('userList');
+ method = [ ...method, ...userMethod ];
+ if (method == undefined || method.length <= 0) {
+ // set focus on selecting method tag
+ $(parentDiv).find('.vp-gb-adv-method').focus();
+ return;
+ }
+ that.openNamingPopup($(parentDiv).find('.vp-gb-adv-naming'), columns, method);
+ });
+
+ // delete advanced item
+ $(document).on('click', this.wrapSelector('.vp-gb-adv-item-delete'), function() {
+ if ($(that.wrapSelector('.vp-gb-adv-item')).length > 1) {
+ $(this).closest('.vp-gb-adv-item').remove();
+ }
+ });
+ }
+
+ _addUserMethod(userMethod) {
+ var addedMethodTag = $(this.wrapSelector(`.vp-gb-method-user-func[value="${userMethod}"]`));
+ if (addedMethodTag.length > 0) {
+ // already added
+ addedMethodTag.prop('checked', true);
+ $(this.wrapSelector('#vp_gbMethodUser')).val('');
+ return;
+ }
+ $(`${userMethod} `)
+ .appendTo($(this.wrapSelector('.vp-gb-method-user-box')));
+
+ $(this.wrapSelector('#vp_gbMethodUser')).val('');
+ }
+
+ /**
+ * Unbind events
+ */
+ _unbindEvent() {
+ super._unbindEvent();
+ // user operation event
+ $(document).off('change', this.wrapSelector('#vp_gbVariable'));
+ $(document).off('click', this.wrapSelector('.vp-gb-df-refresh'));
+ $(document).off('change', this.wrapSelector('#vp_gbBy'));
+ $(document).off('click', this.wrapSelector('#vp_gbBy'));
+ $(document).off('change', this.wrapSelector('#vp_gbByGrouper'));
+ $(document).off('change', this.wrapSelector('#vp_gbByGrouperNumber'));
+ $(document).off('change', this.wrapSelector('#vp_gbByGrouperPeriod'));
+ $(document).off('change', this.wrapSelector('#vp_gbDisplay'));
+ $(document).off('click', this.wrapSelector('#vp_gbDisplay'));
+ $(document).off('change', this.wrapSelector('#vp_gbMethodSelect'));
+ $(document).off('change', this.wrapSelector('#vp_gbAdvanced'));
+ $(document).off('change', this.wrapSelector('#vp_gbAllocateTo'));
+ $(document).off('change', this.wrapSelector('#vp_gbToFrame'));
+ $(document).off('change', this.wrapSelector('#vp_gbResetIndex'));
+
+ $(document).off('click', this.wrapSelector('#vp_gbAdvAdd'));
+ $(document).off('change', this.wrapSelector('.vp-gb-adv-col'));
+ $(document).off('click', this.wrapSelector('.vp-gb-adv-col'));
+ // $(document).off('change', this.wrapSelector('.vp-gb-adv-method-selector'));
+ $(document).off('click', this.wrapSelector('.vp-gb-adv-method'));
+ // $(document).off('click', this.wrapSelector('.vp-gb-adv-method-return'));
+ $(document).off('change', this.wrapSelector('.vp-gb-adv-naming'));
+ $(document).off('click', this.wrapSelector('.vp-gb-adv-naming'));
+ $(document).off('click', this.wrapSelector('.vp-gb-adv-item-delete'));
+ $(document).off('click.' + this.uuid);
+ }
+
+ templateForBody() {
+ return gbHtml;
+ }
+
+ /**
+ * Template for variable list (for dataframe)
+ * @param {Array} varList
+ * @param {string} defaultValue previous value
+ */
+ templateForVariableList(varList, defaultValue='') {
+ // var tag = new com_String();
+ // tag.appendFormatLine('', 'vp_gbVariable');
+ // varList.forEach(vObj => {
+ // // varName, varType
+ // var label = vObj.varName;
+ // tag.appendFormatLine('{3} '
+ // , vObj.varName, vObj.varType
+ // , defaultValue == vObj.varName?'selected':''
+ // , label);
+ // });
+ // tag.appendLine(' '); // VP_VS_VARIABLES
+ // return tag.toString();
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID('vp_gbVariable');
+ variableInput.addClass('vp-state');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.setNormalFilter(true);
+ variableInput.addAttribute('required', true);
+ variableInput.setValue(defaultValue);
+
+ return variableInput.toTagString();
+ }
+
+ /**
+ * Template for advanced item and return it
+ * @returns Advanced box's item
+ */
+ templateForAdvancedItem() {
+ var page = new com_String();
+ page.appendFormatLine('', 'vp-gb-adv-item');
+ // target columns
+ page.appendFormatLine('
'
+ , 'vp-gb-adv-col', 'All columns', 'Apply All columns, if not selected');
+ // method select
+ // page.appendFormatLine('
', 'vp-gb-adv-method-selector');
+ // var defaultMethod = '';
+ // page.appendFormatLine('{1} ', '', 'Select method type');
+ // page.appendFormatLine('{1} ', 'typing', 'Typing');
+ // page.appendLine('----------------------- ');
+ // this.methodList.forEach(method => {
+ // if (method.value == '') {
+ // return;
+ // }
+ // page.appendFormatLine('{1} ', method.value, method.label);
+ // });
+ // page.appendLine(' ');
+ page.appendFormatLine('
'
+ , 'vp-gb-adv-method', 'Select methods to apply', '');
+ page.appendFormatLine('
', 'vp-gb-adv-method-box');
+ // page.appendFormatLine('
', 'vp-gb-adv-method', 'Type function name', "'" + defaultMethod + "'");
+ // page.appendFormatLine('
', 'vp-gb-adv-method-return');
+ // page.appendFormatLine('
'
+ // , 'vp-icon-arrow-left', 'vp-gb-adv-method-return', 'Return to select method');
+ page.appendLine('
');
+ // naming
+ page.appendFormatLine('
', 'vp-gb-adv-naming', 'Click to rename columns', 'Click to rename columns');
+ // delete button
+ page.appendFormatLine('
', 'vp-gb-adv-item-delete', 'vp-cursor', 'vp-icon-close-small');
+ page.appendLine('
');
+ return page.toString();
+ }
+
+ templateForDataView() {
+ return '';
+ }
+
+ renderDataView() {
+ super.renderDataView();
+
+ this.loadDataPage();
+ $(this.wrapSelector('.vp-popup-dataview-box')).css('height', '300px');
+ }
+
+ renderDataPage(renderedText, isHtml = true) {
+ var tag = new com_String();
+ tag.appendFormatLine('');
+ $(this.wrapSelector('.vp-popup-dataview-box')).html(tag.toString());
+ }
+
+ loadDataPage() {
+ var that = this;
+ var code = this.generateCode();
+ // if not, get output of all data in selected pandasObject
+ vpKernel.execute(code).then(function(resultObj) {
+ let { msg } = resultObj;
+ if (msg.content.data) {
+ var htmlText = String(msg.content.data["text/html"]);
+ var codeText = String(msg.content.data["text/plain"]);
+ if (htmlText != 'undefined') {
+ that.renderDataPage(htmlText);
+ } else if (codeText != 'undefined') {
+ // plain text as code
+ that.renderDataPage(codeText, false);
+ } else {
+ that.renderDataPage('');
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ that.renderDataPage(errorContent);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ that.renderDataPage(errorContent);
+ });
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariableList();
+ this.renderPeriodList();
+ this.renderMethodList();
+ this.renderAdvancedItem();
+ }
+
+ renderPeriodList() {
+ let page = new com_String();
+ page.appendFormatLine('', 'vp_gbByGrouperPeriod');
+ var savedPeriod = this.state.period;
+ this.periodList.forEach(period => {
+ page.appendFormatLine('{2} ', period.value, savedPeriod==period.value?' selected':'',period.label);
+ });
+ page.appendLine(' ');
+ $(this.wrapSelector('#vp_gbByGrouperPeriod')).replaceWith(page.toString());
+ }
+
+ renderMethodList() {
+ let page = new com_String();
+ page.appendFormatLine('', 'vp_gbMethodSelect');
+ var savedMethod = this.state.method;
+ this.methodList.forEach(method => {
+ page.appendFormatLine('{2} ', method.value, savedMethod==method.value?' selected':'',method.label);
+ });
+ page.appendLine(' ');
+ $(this.wrapSelector('#vp_gbMethodSelect')).replaceWith(page.toString());
+ }
+
+ renderAdvancedItem() {
+ $(this.templateForAdvancedItem()).insertBefore($(this.wrapSelector('#vp_gbAdvAdd')));
+ }
+
+ /**
+ * Render column selector using MultiSelector module
+ * @param {Array} previousList previous selected columns
+ * @param {Array} includeList columns to include
+ * @param {Array} excludeList columns to exclude
+ */
+ renderMultiSelector(previousList, includeList, excludeList) {
+ this.popup.ColSelector = new MultiSelector(this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'columns', parent: [this.state.variable], selectedList: previousList, includeList: includeList, excludeList: excludeList }
+ );
+ }
+
+ /**
+ * Render method selector
+ * @param {Array} previousList previously selected methods ["'count'", ... ]
+ * @param {Array} userList previously added user methods ["np.sum", "'sum'", ...]
+ */
+ renderMethodSelector(previousList = [], userList = []) {
+ var page = new com_String();
+ page.appendFormatLine('', 'vp-gb-method-selector');
+ // method list
+ page.appendFormatLine('
', 'vp-gb-method-box');
+ this.methodList.forEach((method, idx) => {
+ if (idx == 0) {
+ return ;
+ }
+ var methodStr = "'" + method.value + "'";
+ var checked = "";
+ if (previousList && previousList.includes(methodStr)) {
+ checked = "checked"
+ }
+ page.appendFormatLine('{2} '
+ , methodStr, checked, method.label);
+ });
+ page.appendLine('
');
+ page.appendLine('
');
+ // user method list
+ page.appendFormatLine('
', 'vp-gb-method-user-box');
+ userList && userList.forEach(userFunc => {
+ page.appendFormatLine('{1} '
+ , userFunc, userFunc);
+ });
+ page.appendLine('
');
+ page.appendLine('
');
+ // add user method
+ page.appendFormatLine('
', 'vp-gb-method-user');
+ page.appendFormatLine('{0} ', 'User option');
+ page.appendFormatLine(' ', 'Type user method');
+ page.appendFormatLine('{0} '
+ , 'Text');
+ page.appendLine('Add ');
+ page.appendLine('
');
+ page.appendLine('
');
+ $(this.wrapSelector('.vp-inner-popup-body')).html(page.toString());
+ }
+
+ /**
+ * Render naming box
+ * @param {Array} columns
+ * @param {Array} method
+ * @param {Object} previousDict
+ * @returns
+ */
+ renderNamingBox(columns, methods, previousDict) {
+ var page = new com_String();
+ page.appendFormatLine('', 'vp-gb-naming-box');
+ if (columns && columns.length > 0) {
+ columns.forEach(col => {
+ page.appendLine('
');
+ page.appendFormatLine('
{0} ', col);
+ methods.forEach(met => {
+ page.appendFormatLine('
', 'vp-gb-naming-item');
+ page.appendFormatLine('{0} ', met);
+ var previousValue = '';
+ var key = col + '.' + met;
+ if (previousDict[key]) {
+ previousValue = previousDict[key];
+ }
+ page.appendFormatLine(' '
+ , 'vp-gb-naming-text', 'Name to replace ' + met, previousValue, key);
+ page.appendLine('
');
+ });
+ page.appendLine('
');
+ });
+ } else {
+ page.appendLine('
Rename methods ');
+ methods.forEach(met => {
+ page.appendFormatLine('
', 'vp-gb-naming-item');
+ page.appendFormatLine('{0} ', met);
+ var previousValue = '';
+ var key = met;
+ if (previousDict[key]) {
+ previousValue = previousDict[key];
+ }
+ page.appendFormatLine(' '
+ , 'vp-gb-naming-text', 'Name to replace ' + met, previousValue, key);
+ page.appendLine('
');
+ });
+ }
+ page.appendLine('
');
+ $(this.wrapSelector('.vp-inner-popup-body')).html(page.toString());
+ }
+
+ generateCode() {
+ var code = new com_String();
+ var {
+ variable, groupby, useGrouper, grouperNumber, grouperPeriod,
+ display, method, advanced, allocateTo, toFrame, resetIndex
+ } = this.state;
+
+ if (!variable || variable == '') {
+ return '';
+ }
+
+ // mapping colList states
+ groupby = groupby.map(col => col.code);
+ display = display.map(col => col.code);
+
+ //====================================================================
+ // Allocation
+ //====================================================================
+ if (allocateTo && allocateTo != '') {
+ code.appendFormat('{0} = ', allocateTo);
+ }
+
+ //====================================================================
+ // Dataframe variable & Groupby(with Grouper) columns
+ //====================================================================
+ var byStr = '';
+ if (groupby.length <= 1) {
+ byStr = groupby.join('');
+ } else {
+ byStr = '[' + groupby.join(',') + ']';
+ }
+
+ // Grouper
+ if (useGrouper) {
+ byStr = com_util.formatString("pd.Grouper(key={0}, freq='{1}')", byStr, grouperNumber + grouperPeriod);
+ } else if (resetIndex === true) {
+ // as_index option cannot use with Grouper -> use .reset_index() at the end
+ byStr += ', as_index=False';
+ }
+ // variable & groupby columns & option
+ code.appendFormat('{0}.groupby({1})', variable, byStr);
+
+ //====================================================================
+ // Display columns
+ //====================================================================
+ var colStr = '';
+ if (display && display.length > 0) {
+ if (toFrame || display.length > 1) {
+ // over 2 columns
+ colStr = '[[' + display.join(',') + ']]';
+ } else if (display.length == 1) {
+ // for 1 column
+ colStr = '[' + display.join('') + ']';
+ }
+ }
+
+ //====================================================================
+ // Aggregation/Method code generation
+ //====================================================================
+ var methodStr = new com_String();
+ if (advanced) {
+ //================================================================
+ // Aggregation code generation
+ //================================================================
+ methodStr.append('agg(');
+ // prepare variables for aggregation
+ var advItemTags = $(this.wrapSelector('.vp-gb-adv-item'));
+ if (advItemTags && advItemTags.length > 0) {
+ var advColumnDict = {
+ 'nothing': []
+ }
+ for (var i = 0; i < advItemTags.length; i++) {
+ var advColumns = $(advItemTags[i]).find('.vp-gb-adv-col').data('list');
+ if (advColumns && advColumns.length > 0) {
+ advColumns = advColumns.map(col => col.code);
+ }
+ var advMethod = $(advItemTags[i]).find('.vp-gb-adv-method').data('list');
+ var advUserMethod = $(advItemTags[i]).find('.vp-gb-adv-method').data('userList');
+ if (!advMethod || advMethod == null) {
+ advMethod = [];
+ }
+ if (!advUserMethod || advUserMethod == null) {
+ advUserMethod = [];
+ }
+ advMethod = [ ...advMethod, ...advUserMethod ];
+ var advNaming = $(advItemTags[i]).find('.vp-gb-adv-naming').data('dict');
+ if (!advMethod || advMethod.length <= 0) {
+ continue;
+ }
+ if (advColumns && advColumns.length > 0) {
+ advColumns.forEach(col => {
+ advMethod.forEach(method => {
+ var naming = advNaming[col + '.' + method];
+ if (naming && naming != '') {
+ naming = "'" + naming + "'";
+ }
+ if (Object.keys(advColumnDict).includes(col)) {
+ advColumnDict[col].push({ method: method, naming: naming})
+ } else {
+ advColumnDict[col] = [{ method: method, naming: naming}];
+ }
+ });
+ });
+
+ } else {
+ var naming = advNaming[advMethod];
+ if (naming && naming != '') {
+ naming = "'" + naming + "'";
+ }
+ advMethod.forEach(method => {
+ var naming = advNaming[method];
+ if (naming && naming != '') {
+ naming = "'" + naming + "'";
+ }
+ advColumnDict['nothing'].push({ method: method, naming: naming});
+ });
+ }
+ }
+
+ // if target columns not selected
+ if (Object.keys(advColumnDict).length == 1) {
+ // EX) .agg([('average', 'mean'), ('maximum value', max')])
+ var noColList = advColumnDict['nothing'];
+ if (noColList.length == 1) {
+ // 1 method
+ if (noColList[0].naming && noColList[0].naming != '') {
+ methodStr.appendFormat("[({0}, {1})]", noColList[0].naming, noColList[0].method);
+ } else {
+ methodStr.appendFormat("{0}", noColList[0].method);
+ }
+ } else {
+ // more than 1 method
+ var tmpList = [];
+ noColList.forEach(obj => {
+ if (obj.naming && obj.naming != '') {
+ tmpList.push(com_util.formatString("({0}, {1})", obj.naming, obj.method));
+ } else {
+ tmpList.push(obj.method);
+ }
+ });
+ methodStr.appendFormat("[{0}]", tmpList.join(', '));
+ }
+ } else {
+ // EX) .agg({'col1':[('average', 'mean')], 'col2': 'max')})
+ // apply method with empty column to all columns(display)
+ var noColList = advColumnDict['nothing'];
+ delete advColumnDict['nothing'];
+ noColList.forEach(obj => {
+ display.forEach(col => {
+ if (Object.keys(advColumnDict).includes(col)) {
+ if (advColumnDict[col].filter(x => x.method == obj.method).length == 0) {
+ advColumnDict[col].push({ method: obj.method, naming: obj.naming})
+ }
+ } else {
+ advColumnDict[col] = [{ method: obj.method, naming: obj.naming}];
+ }
+ });
+ });
+
+ // with target columns
+ var tmpList1 = [];
+ Object.keys(advColumnDict).forEach(key => {
+ var colList = advColumnDict[key];
+ var tmpList2 = [];
+ var useTuple = false;
+ colList.forEach(obj => {
+ if (obj.naming && obj.naming != '') {
+ tmpList2.push(com_util.formatString("({0}, {1})", obj.naming, obj.method));
+ useTuple = true;
+ } else {
+ tmpList2.push(obj.method);
+ }
+ });
+ var tmpStr = tmpList2.join(',');
+ if (tmpList2.length > 1 || useTuple) {
+ tmpStr = '[' + tmpStr + ']';
+ }
+ tmpList1.push(com_util.formatString("{0}: {1}", key, tmpStr));
+ });
+ methodStr.appendFormat('{{0}}', tmpList1.join(', '));
+ }
+ }
+ methodStr.append(')');
+ } else {
+ //================================================================
+ // Method code generation
+ //================================================================
+ if (method != '') {
+ let numericOnlyList = ['std', 'sum', 'mean', 'median', 'quantile'];
+ if (numericOnlyList.includes(method)) {
+ methodStr.appendFormat('{0}(numeric_only=True)', method);
+ } else {
+ methodStr.appendFormat('{0}()', method);
+ if (method === 'size' && toFrame === true) {
+ // if to_Frame on size() method
+ methodStr.append(".to_frame(name='size')");
+ }
+ }
+ }
+ }
+
+ if (method != '' || advanced) {
+ // when using as_index option with Grouper, use .reset_index()
+ if (useGrouper && resetIndex) {
+ methodStr.append('.reset_index()');
+ }
+ // display columns
+ code.appendFormat('{0}.{1}', colStr, methodStr.toString());
+ }
+
+ if (allocateTo && allocateTo != '') {
+ code.appendLine();
+ code.append(allocateTo);
+ }
+ return code.toString();
+ }
+
+ /**
+ * Load state and set values on components
+ * @param {object} state
+ */
+ loadState() {
+ super.loadState();
+ var {
+ variable, groupby, useGrouper, grouperNumber, grouperPeriod,
+ display, method, advanced, allocateTo, toFrame, resetIndex,
+ advPageDom, advColList, advNamingList, advMethodList, advMethodUserList
+ } = this.state;
+
+ $(this.wrapSelector('#vp_gbVariable')).val(variable);
+ $(this.wrapSelector('#vp_gbBy')).val(groupby.map(col=>col.code).join(','));
+ $(this.wrapSelector('#vp_gbBy')).data('list', groupby);
+ if (useGrouper) {
+ $(this.wrapSelector('#vp_gbByGrouper')).removeAttr('disabled');
+ $(this.wrapSelector('#vp_gbByGrouper')).prop('checked', useGrouper);
+ $(this.wrapSelector('#vp_gbByGrouperNumber')).val(grouperNumber);
+ $(this.wrapSelector('#vp_gbByGrouperPeriod')).val(grouperPeriod);
+ $(this.wrapSelector('.vp-gb-by-grouper-box')).show();
+ }
+ $(this.wrapSelector('#vp_gbDisplay')).val(display.map(col=>col.code).join(','));
+ $(this.wrapSelector('#vp_gbDisplay')).data('list', display);
+ $(this.wrapSelector('#vp_gbMethod')).val(method);
+ $(this.wrapSelector('#vp_gbMethodSelector')).val(method);
+ $(this.wrapSelector('#vp_gbAdvanced')).prop('checked', advanced);
+ if (advanced) {
+ $(this.wrapSelector('#vp_gbAdvanced')).trigger('change');
+ }
+ $(this.wrapSelector('#vp_gbAllocateTo')).val(allocateTo);
+ $(this.wrapSelector('#vp_gbToFrame')).val(toFrame);
+ $(this.wrapSelector('#vp_gbResetIndex')).prop('checked', resetIndex);
+
+ if (advPageDom != '') {
+ $(this.wrapSelector('.vp-gb-adv-box')).html(advPageDom);
+ }
+
+ advColList.forEach((arr, idx) => {
+ $($(this.wrapSelector('.vp-gb-adv-col'))[idx]).data('list', arr);
+ });
+ advMethodList.forEach((arr, idx) => {
+ $($(this.wrapSelector('.vp-gb-adv-method'))[idx]).data('list', arr);
+ });
+ advMethodUserList.forEach((arr, idx) => {
+ $($(this.wrapSelector('.vp-gb-adv-method'))[idx]).data('userList', arr);
+ });
+ advNamingList.forEach((obj, idx) => {
+ $($(this.wrapSelector('.vp-gb-adv-naming'))[idx]).data('dict', obj);
+ });
+ }
+
+ /**
+ * Save now state of components
+ */
+ saveState() {
+ super.saveState();
+ // save input state
+ $(this.wrapSelector('.vp-gb-adv-box input')).each(function () {
+ this.defaultValue = this.value;
+ });
+
+ // save checkbox state
+ $(this.wrapSelector('.vp-gb-adv-box input[type="checkbox"]')).each(function () {
+ this.defaultValue = this.value;
+ });
+
+ // save select state
+ $(this.wrapSelector('.vp-gb-adv-box select > option')).each(function () {
+ if (this.selected) {
+ this.setAttribute("selected", true);
+ } else {
+ this.removeAttribute("selected");
+ }
+ });
+
+ // save advanced box
+ this.state.advPageDom = $(this.wrapSelector('.vp-gb-adv-box')).html();
+ }
+
+ /**
+ * Open Inner popup page for column selection
+ * @param {Object} targetSelector
+ * @param {string} title
+ * @param {Array} includeList
+ * @param {Array} excludeList
+ */
+ openColumnSelector(targetSelector, title='Select columns', includeList=[], excludeList=[]) {
+ this.popup.type = 'column';
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(col => col.code)
+ }
+ this.renderMultiSelector(previousList, includeList, excludeList);
+ this.openInnerPopup(title);
+ }
+
+ /**
+ * Open Inner popup page for method selection
+ * @param {Object} targetSelector
+ * @param {string} title
+ */
+ openMethodSelector(targetSelector, title='Select methods') {
+ this.popup.type = 'method';
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ var userList = this.popup.targetSelector.data('userList');
+ this.renderMethodSelector(previousList, userList);
+ this.openInnerPopup(title);
+ }
+
+ /**
+ * Open Naming popup page
+ * @param {Object} targetSelector
+ * @param {Array} columns
+ * @param {string} method
+ */
+ openNamingPopup(targetSelector, columns, method) {
+ this.popup.type = 'naming';
+ this.popup.targetSelector = targetSelector;
+ this.renderNamingBox(columns, method, $(this.popup.targetSelector).data('dict'));
+ this.openInnerPopup('Replace naming');
+ }
+
+ handleInnerOk() {
+ // ok input popup
+ if (this.popup.type == 'column') {
+ var dataList = this.popup.ColSelector.getDataList();
+
+ $(this.popup.targetSelector).val(dataList.map(col => { return col.code }).join(','));
+ $(this.popup.targetSelector).data('list', dataList);
+ $(this.popup.targetSelector).trigger({ type: 'change', dataList: dataList });
+ this.closeInnerPopup();
+ } else if (this.popup.type == 'method') {
+ var methodList = [];
+ var tags = $(this.wrapSelector('.vp-gb-method-checkbox:checked'));
+ for (var i = 0; i < tags.length; i++) {
+ var val = $(tags[i]).val();
+ if (val && val != '') {
+ methodList.push(val);
+ }
+ }
+
+ var userList = [];
+ tags = $(this.wrapSelector('.vp-gb-method-user-func:checked'));
+ for (var i = 0; i < tags.length; i++) {
+ var val = $(tags[i]).val();
+ if (val && val != '') {
+ userList.push(val);
+ }
+ }
+ var targetValue = [ ...methodList, ...userList ].join(',');
+ $(this.popup.targetSelector).val(targetValue);
+ $(this.popup.targetSelector).data('list', methodList);
+ $(this.popup.targetSelector).data('userList', userList);
+ $(this.popup.targetSelector).trigger({ type: 'change', list: methodList, userList: userList });
+ this.closeInnerPopup();
+ } else if (this.popup.type == 'naming') {
+ var dict = {};
+ // get dict
+ var tags = $(this.wrapSelector('.vp-gb-naming-text'));
+ for (var i = 0; i < tags.length; i++) {
+ var key = $(tags[i]).data('code');
+ var val = $(tags[i]).val();
+ if (val && val != '') {
+ dict[key] = val;
+ }
+ }
+
+ $(this.popup.targetSelector).val(Object.values(dict).map(val => "'" + val +"'").join(','));
+ $(this.popup.targetSelector).data('dict', dict);
+ $(this.popup.targetSelector).trigger({ type: 'change', namingDict: dict });
+ this.closeInnerPopup();
+ }
+ }
+
+ /**
+ * Load variable list (dataframe)
+ */
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var varList = JSON.parse(result);
+ // render variable list
+ // get prevvalue
+ var prevValue = that.state.variable;
+ // replace
+ $(that.wrapSelector('#vp_gbVariable')).replaceWith(function() {
+ return that.templateForVariableList(varList, prevValue);
+ });
+ $(that.wrapSelector('#vp_gbVariable')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Groupby:', result);
+ }
+ });
+ }
+
+ }
+
+ return Groupby;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Import.js b/visualpython/js/m_apps/Import.js
new file mode 100644
index 00000000..bc0321d5
--- /dev/null
+++ b/visualpython/js/m_apps/Import.js
@@ -0,0 +1,287 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Import.js
+ * Author : Black Logic
+ * Note : Apps > Import
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Import
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/m_apps/import'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(importCss, com_util, com_Const, com_String, PopupComponent) {
+
+ const importTemplates = {
+ 'data-analysis': [
+ { i0: 'numpy', i1: 'np', type: 'module', checked: 'checked'},
+ { i0: 'pandas', i1: 'pd', type: 'module', checked: 'checked'},
+ {
+ i0: 'matplotlib.pyplot', i1: 'plt', type: 'module'
+ , include: [
+ '%matplotlib inline'
+ ], checked: 'checked'
+ },
+ { i0: 'seaborn', i1: 'sns', type: 'module', checked: 'checked'},
+ {
+ i0: 'plotly.express', i1: 'px', type: 'module'
+ , include: [
+ 'from plotly.offline import init_notebook_mode',
+ 'init_notebook_mode(connected=True)'
+ ], checked: ''
+ },
+ { i0: 'pyarrow', i1: 'pa', type: 'module', checked: ''},
+ ],
+ 'machine-learning': [
+ { i0: 'sklearn.model_selection', i1: 'train_test_split', type: 'function', checked: 'checked' },
+ { i0: 'sklearn', i1: 'metrics', type: 'function', checked: 'checked' }
+ ]
+ }
+
+ /**
+ * Import
+ */
+ class Import extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+
+ let savedData = vpConfig.getDataSimple('', 'vpimport');
+ // Reset abnormal data
+ if (savedData == undefined || savedData.tabType == undefined) {
+ savedData = {};
+ vpConfig.setData(null, 'vpimport');
+ }
+
+ this.state = {
+ tabType: 'data-analysis',
+ importMeta: [],
+ ...savedData,
+ ...this.state
+ }
+
+ this.importTemplatesCopy = JSON.parse(JSON.stringify(importTemplates));
+
+ if (!this.state.importMeta || this.state.importMeta.length <= 0) {
+ this.state.importMeta = JSON.parse(JSON.stringify(this.importTemplatesCopy[this.state.tabType]));
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+
+ // select tab
+ $(this.wrapSelector('.vp-tab-button')).on('click', function() {
+ let tabType = $(this).data('tab');
+ // set button selected
+ that.state.tabType = tabType;
+ $(that.wrapSelector('.vp-tab-button')).removeClass('vp-tab-selected');
+ $(this).addClass('vp-tab-selected');
+ // replace libraries
+ that.state.importMeta = that.importTemplatesCopy[tabType];
+ $(that.wrapSelector('#vp_tblImport')).replaceWith(function() {
+ return that.templateTable(that.state.importMeta);
+ });
+ });
+
+ // delete lib
+ $(this.wrapSelector()).on("click", '.vp-remove-option', function() {
+ $(this).closest('tr').remove();
+
+ that.checkAll();
+ });
+ // check/uncheck all
+ $(this.wrapSelector()).on('change', '#vp_libraryCheckAll', function() {
+ var checked = $(this).prop('checked');
+ $(that.wrapSelector('.vp-item-check')).prop('checked', checked);
+ });
+ // check item
+ $(this.wrapSelector()).on('change', '.vp-item-check', function() {
+ var checked = $(this).prop('checked');
+ // if unchecked at least one item, uncheck check-all
+ if (!checked) {
+ $(that.wrapSelector('.vp-check-all')).prop('checked', false);
+ } else {
+ // if all checked, check check-all
+ that.checkAll();
+ }
+ });
+
+ // add module
+ $(this.wrapSelector('#vp_addModule')).click(function() {
+ var libsLength = $(that.wrapSelector("#vp_tblImport tbody tr")).length;
+ var tagTr = $(that.templateForModule(libsLength, '', ''));
+
+ $(that.wrapSelector("#vp_tblImport tr:last")).after(tagTr);
+ });
+ // add function
+ $(this.wrapSelector('#vp_addFunction')).click(function() {
+ var libsLength = $(that.wrapSelector("#vp_tblImport tbody tr")).length;
+ var tagTr = $(that.templateForFunction(libsLength, '', ''));
+
+ $(that.wrapSelector("#vp_tblImport tr:last")).after(tagTr);
+ });
+ }
+
+ checkAll() {
+ // check if all checked
+ // if all checked, check check-all
+ var allLength = $(this.wrapSelector('.vp-item-check')).length;
+ var checkedLength = $(this.wrapSelector('.vp-item-check:checked')).length;
+ if (allLength == checkedLength) {
+ $(this.wrapSelector('.vp-check-all')).prop('checked', true);
+ } else {
+ $(this.wrapSelector('.vp-check-all')).prop('checked', false);
+ }
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ // tab buttons
+ page.appendLine('');
+ page.appendFormatLine('
{2}
'
+ , this.state.tabType=='data-analysis'?'vp-tab-selected':'', 'data-analysis', 'Data Analysis');
+ page.appendFormatLine('
{2}
'
+ , this.state.tabType=='machine-learning'?'vp-tab-selected':'', 'machine-learning', 'Machine Learning');
+ page.appendLine('
');
+ // import table
+ page.appendLine(this.templateTable(this.state.importMeta));
+ page.appendLine(' ');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ templateTable(libraries) {
+ var page = new com_String();
+ page.appendLine('');
+ return page.toString();
+ }
+
+ templateForModule(idx, moduleName, aliasName, checked=true) {
+ var tag = new com_String();
+ tag.append('');
+ // checkbox
+ tag.appendFormat(' '
+ , 'vp_libraryCheck' + idx, checked?'checked':'');
+ // inputs
+ tag.appendFormat('import ', 'text-align="center";');
+ tag.appendFormat(' '
+ , 'vp_i0_' + idx, 'vp-input m vp-add-i0', 'Type module', moduleName);
+ tag.appendFormat('as ', 'text-align="center";');
+ tag.appendFormat(' '
+ , 'vp_i1_' + idx, 'vp-input m vp-add-i1', 'Type alias', aliasName);
+ // LAB: img to url
+ // tag.appendFormat(' ', 'vp-remove-option w100 vp-cursor', com_Const.IMAGE_PATH + 'close_small.svg');
+ tag.appendFormat(' ', 'vp-remove-option w100 vp-cursor', 'vp-icon-close-small');
+ tag.append(' ');
+ return tag.toString();
+ }
+
+ templateForFunction(idx, moduleName, functionName, checked=true) {
+ var tag = new com_String();
+ tag.append('');
+ // checkbox
+ tag.appendFormat(' '
+ , 'vp_libraryCheck' + idx, checked?'checked':'');
+ // inputs
+ tag.appendFormat('from ', 'text-align="center";');
+ tag.appendFormat(' '
+ , 'vp_i0_' + idx, 'vp-input m vp-add-i0', 'Type module', moduleName);
+ tag.appendFormat('import ', 'text-align="center";');
+ tag.appendFormat(' '
+ , 'vp_i1_' + idx, 'vp-input m vp-add-i1', 'Type function', functionName);
+ // LAB: img to url
+ // tag.appendFormat(' ', 'vp-remove-option w100 vp-cursor', com_Const.IMAGE_PATH + 'close_small.svg');
+ tag.appendFormat(' ', 'vp-remove-option w100 vp-cursor', 'vp-icon-close-small');
+ tag.append(' ');
+ return tag.toString();
+ }
+
+ render() {
+ super.render();
+
+ this.checkAll();
+ }
+
+ generateCode() {
+ var sbCode = new com_String();
+
+ // code generate with library list
+ var importMeta = [];
+ var libraryList = $(this.wrapSelector("#vp_tblImport tbody tr"));
+ for (var idx = 0; idx < libraryList.length; idx++) {
+ var pacType = $(libraryList[idx]).data('type');
+ var pacI0 = $(libraryList[idx]).find('.vp-add-i0').val();
+ var pacI1 = $(libraryList[idx]).find('.vp-add-i1').val().trim();
+ var pacChecked = $(libraryList[idx]).find('.vp-item-check').prop('checked');
+
+ if (pacI0 == "") {
+ continue;
+ }
+ if (pacChecked === true) {
+ if (sbCode.toString().trim().length > 0) {
+ sbCode.appendLine();
+ }
+ if (pacType == 'function') {
+ // function
+ sbCode.appendFormat("from {0} import {1}", pacI0, pacI1);
+ } else {
+ // module
+ sbCode.appendFormat("import {0}{1}", pacI0, ((pacI1 === undefined || pacI1 === "") ? "" : (" as " + pacI1)));
+ }
+
+ // Need additional code?
+ if (pacI0 == 'matplotlib.pyplot' || pacI0 == 'matplotlib') {
+ sbCode.appendLine();
+ sbCode.append('%matplotlib inline');
+ }
+ if (pacI0 == 'plotly.express' || pacI0 == 'plotly') {
+ sbCode.appendLine();
+ sbCode.appendLine('from plotly.offline import init_notebook_mode');
+ sbCode.append('init_notebook_mode(connected=True)');
+ }
+ }
+
+ importMeta.push({ i0: pacI0, i1: pacI1, type: pacType, checked: (pacChecked?'checked':'') });
+ }
+ this.state.importMeta = importMeta;
+
+ // save import packages
+ vpConfig.setData({ tabType: this.state.tabType, importMeta: importMeta }, 'vpimport');
+
+ this.generatedCode = sbCode.toString();
+ return sbCode.toString();
+ }
+
+ }
+
+ return Import;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Information.js b/visualpython/js/m_apps/Information.js
new file mode 100644
index 00000000..319c8877
--- /dev/null
+++ b/visualpython/js/m_apps/Information.js
@@ -0,0 +1,928 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Information.js
+ * Author : Black Logic
+ * Note : Apps > Information
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 04. 05
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Information
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/information.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/information'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/LoadingSpinner'
+], function(varHtml, varCss, com_String, com_util, com_interface, PopupComponent, DataSelector, LoadingSpinner) {
+
+ /**
+ * Information
+ */
+ class Information extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 5;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.checkModules = ['pd', 'plt'];
+
+ this.state = {
+ data: '',
+ selected: [], // selected items depend on dtype (ex. DataFrame - columns)
+ menu: '', // selected menu id
+ menuItem: [], // selected menu item
+ // DataFrame
+ selection: { // selection of columns
+ start: -1,
+ end: -1
+ },
+ columnLevel: 1,
+ columnList: [],
+ indexLevel: 1,
+ indexList: [],
+ lines: TABLE_LINES,
+ ...this.state
+ }
+
+ this.menuList = [
+ {
+ id: 'general',
+ label: 'General',
+ dtype: ['DataFrame', 'Series'],
+ child: [
+ { id: 'info', label: 'Info', code: '${data}.info()', dtype: ['DataFrame', 'Series'] },
+ { id: 'describe', label: 'Describe', code: '${data}.describe()', dtype: ['DataFrame', 'Series'] },
+ { id: 'head', label: 'Head', code: '${data}.head()', dtype: ['DataFrame', 'Series'] },
+ { id: 'tail', label: 'Tail', code: '${data}.tail()', dtype: ['DataFrame', 'Series'] },
+ ]
+ },
+ {
+ id: 'status',
+ label: 'Status',
+ dtype: ['DataFrame', 'Series'],
+ child: [
+ { id: 'null_count', label: 'Null count',
+ code: "pd.DataFrame({'Null Count': ${data}.isnull().sum(), 'Non-Null Count': ${data}.notnull().sum()})", dtype: ['DataFrame', 'Series'], toframe: true },
+ // { id: 'duplicates', label: 'Duplicated', code: '${data}.duplicated()', dtype: ['DataFrame', 'Series'] },
+ { id: 'duplicates', label: 'Duplicated', code: "_duplicated = ([${data}.duplicated().sum()] + [${data}[col].duplicated().sum() for col in ${data}.columns])\
+\n_duplicated_df = pd.DataFrame({\
+\n 'Rows':[len(${data})]*len(_duplicated),\
+\n 'Unique':[len(${data}) - dups for dups in _duplicated],\
+\n 'Duplicated': _duplicated,\
+\n 'Duplicated by': ['All columns'] + ${data}.columns.to_list()\
+\n}, index=['Combination']+${data}.columns.to_list())\
+\n_duplicated_df", dtype: ['DataFrame', 'Series'], toframe: true },
+ { id: 'unique', label: 'Unique', code: '${data}.unique()', dtype: ['Series'] },
+ { id: 'value_counts', label: 'Value counts',
+ // code: "_value_counts_dict = {}\
+ // \nfor col in ${data}.columns:\
+ // \n if pd.api.types.is_numeric_dtype(${data}[col]):\
+ // \n _value_counts = ${data}[col].value_counts(bins=10, sort=False)\
+ // \n _value_counts_dict[(col, 'bins')] = list(_value_counts.index) + ['']*(10 - len(_value_counts))\
+ // \n else:\
+ // \n _value_counts = ${data}[col].value_counts()\
+ // \n _value_counts_dict[(col, 'category')] = list(_value_counts.index) + ['']*(10 - len(_value_counts))\
+ // \n _value_counts_dict[(col, 'count')] = list(_value_counts.values) + ['']*(10 - len(_value_counts))\
+ // \npd.DataFrame(_value_counts_dict)",
+ code: "_dfr = pd.DataFrame()\
+\nfor col in ${data}.columns:\
+\n if pd.api.types.is_numeric_dtype(${data}[col]) and ${data}[col].value_counts().size > 10:\
+\n _value_counts = ${data}[col].value_counts(bins=10, sort=False)\
+\n _dfr = pd.concat([_dfr, pd.DataFrame({(col,'bins'): _value_counts.index})], axis=1)\
+\n else:\
+\n _value_counts = ${data}[col].value_counts()\
+\n _dfr = pd.concat([_dfr, pd.DataFrame({(col,'category'): _value_counts.index})], axis=1)\
+\n _dfr = pd.concat([_dfr, pd.DataFrame({(col,'count'): _value_counts.values})], axis=1)\
+\n_dfr.replace(np.nan,'')",
+ code2: "${data}.value_counts()",
+ dtype: ['DataFrame', 'Series'], toframe: true },
+ ]
+ },
+ {
+ id: 'statistics',
+ label: 'Statistics',
+ dtype: ['DataFrame', 'Series'],
+ child: [
+ /** checkbox */
+ { id: 'count', label: 'count', code: '${data}.count()' },
+ { id: 'min', label: 'min', code: '${data}.min(numeric_only=True)' },
+ { id: 'max', label: 'max', code: '${data}.max(numeric_only=True)' },
+ { id: 'quantile', label: 'quantile', code: '${data}.quantile(numeric_only=True)' },
+ { id: 'sum', label: 'sum', code: '${data}.sum(numeric_only=True)' },
+ { id: 'mean', label: 'mean', code: '${data}.mean(numeric_only=True)' },
+ { id: 'median', label: 'median', code: '${data}.median(numeric_only=True)' },
+ // { id: 'mad', label: 'mad', code: '${data}.mad(numeric_only=True)' }, // FutureWarning: Deprecated and will be removed
+ { id: 'var', label: 'var', code: '${data}.var(numeric_only=True)' },
+ { id: 'std', label: 'std', code: '${data}.std(numeric_only=True)' },
+ { id: 'skew', label: 'skew', code: '${data}.skew(numeric_only=True)' },
+ { id: 'kurtosis', label: 'kurtosis', code: '${data}.kurtosis(numeric_only=True)' },
+ /** radio */
+ { id: 'cumsum', label: 'cumsum', code: '${data}.cumsum()', type: 'radio' },
+ { id: 'cummin', label: 'cummin', code: '${data}.cummin()', type: 'radio' },
+ { id: 'cummax', label: 'cummax', code: '${data}.cummax()', type: 'radio' },
+ { id: 'cumprod', label: 'cumprod', code: '${data}.cumprod()', type: 'radio' },
+ { id: 'diff', label: 'diff', code: '${data}.diff()', type: 'radio' },
+ { id: 'pct_change', label: 'pct_change', code: '${data}.pct_change()', type: 'radio' }
+ ]
+ },
+ {
+ id: 'corr_menu',
+ label: 'Correlation',
+ dtype: ['DataFrame'],
+ child: [
+ { id: 'corr', label: 'Correlation table', code: '${data}.corr(numeric_only=True)', dtype: ['DataFrame'] },
+ { id: 'corr_matrix', label: 'Correlation matrix'
+ , code: "_corr = ${data}.corr(numeric_only=True)\n_corr.style.background_gradient(cmap='coolwarm')", dtype: ['DataFrame'] },
+ ]
+ },
+ {
+ id: 'distribution',
+ label: 'Distribution',
+ dtype: ['DataFrame', 'Series'],
+ child: [
+ { id: 'hist', label: 'Histogram', code: "${data}.hist()\nplt.show()", dtype: ['DataFrame', 'Series'] },
+ { id: 'scatter_matrix', label: 'Scatter matrix'
+ , code: "pd.plotting.scatter_matrix(${data}, marker='o', hist_kwds={'bins': 30}, s=30, alpha=.8)\nplt.show()"
+ , dtype: ['DataFrame'] },
+ { id: 'boxplot', label: 'Box plot', code: "${data}.plot(kind='box')\nplt.show()", dtype: ['DataFrame', 'Series'] },
+ { id: 'count_plot', label: 'Count plot', code: "${data}.value_counts().plot(kind='bar', rot=30)\nplt.show()", dtype: ['DataFrame', 'Series'] }
+ ]
+ }
+
+ ];
+
+ this.loading = false;
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+
+ $(document).off('click', this.wrapSelector('.vp-popup-body'));
+ $(document).off('click', this.wrapSelector('.vp-information-menu'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // change data
+ $(this.wrapSelector('#data')).on('change', function() {
+ let val = $(this).val();
+ });
+
+ // un-select every selection
+ $(document).on('click', this.wrapSelector('.vp-variable-table'), function(evt) {
+ evt.stopPropagation();
+ var target = evt.target;
+ // if(!$(target).is("input") && !$(target).is("label")) {
+ if (that.state.selected.length > 0) {
+ if ($('.vp-dropdown-content').find(target).length == 0
+ && !$(target).hasClass('vp-dropdown-content') ) {
+ $(that.wrapSelector('.vp-variable-table thead th')).removeClass('selected');
+ that.state.selected = [];
+
+ // load menu
+ that.renderMenu();
+ // load info
+ that.loadInfo();
+ }
+ }
+
+ });
+
+ // click menu
+ $(document).on('click', this.wrapSelector('.vp-information-menu:not(.disabled)'), function(event) {
+ event.stopPropagation();
+ let menuId = $(this).data('menu');
+ let menuParent = $(this).data('parent');
+
+ if (menuParent) {
+ if (menuParent === 'statistics') {
+ let menuType = $(this).attr('type'); // checkbox or radio
+ if (menuType === 'radio') {
+ // uncheck all checkbox
+ $(that.wrapSelector('.vp-information-menu[data-parent="statistics"][type="checkbox"]:checked')).prop('checked', false);
+ } else {
+ // uncheck all radio
+ $(that.wrapSelector('.vp-information-menu[data-parent="statistics"][type="radio"]:checked')).prop('checked', false);
+ }
+ // allow multi-select
+ that.state.menu = menuParent;
+ that.state.menuItem = [];
+ $('.vp-information-menu[data-parent="statistics"]:checked').each((i, tag) => {
+ that.state.menuItem.push(tag.id);
+ });
+ // add selection
+ $(that.wrapSelector('.vp-information-menu')).removeClass('selected');
+ if (that.state.menuItem.length > 0) {
+ $(that.wrapSelector('.vp-information-menu[data-menu="statistics"]')).addClass('selected');
+ } else {
+ // all selection removed from statistics
+ that.state.menu = '';
+ }
+ } else {
+ that.state.menu = menuParent;
+ that.state.menuItem = [ menuId ];
+ // remove checkbox selection for statistics
+ $(that.wrapSelector('.vp-information-menu[data-parent="statistics"]:checked')).prop('checked', false);
+ // add selection
+ $(that.wrapSelector('.vp-information-menu')).removeClass('selected');
+ $(this).addClass('selected');
+ $(that.wrapSelector(`.vp-information-menu[data-menu="${menuParent}"]`)).addClass('selected');
+ }
+
+ that.loadInfo();
+ }
+ });
+
+ // column group selection
+ // select column group
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP), function(evt) {
+ evt.stopPropagation();
+
+ let hasSelected = $(this).hasClass('selected');
+ let colLabel = $(this).data('label');
+ let firstIdx = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]:first`)).index();
+ let lastIdx = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]:last`)).index();
+ if (firstIdx === lastIdx) {
+ lastIdx = -1;
+ }
+
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ if (!hasSelected) {
+ that.state.selection = { start: firstIdx, end: -1 };
+ $(this).addClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).addClass('selected');
+ } else {
+ $(this).removeClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).removeClass('selected');
+ }
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ var startIdx = that.state.selection.start;
+
+ if (startIdx == -1) {
+ // no selection
+ that.state.selection = { start: firstIdx, end: -1 };
+ } else if (startIdx > firstIdx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ let parentSet = new Set();
+ for (var i = firstIdx - 1; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ parentSet.add($(tags[i]).data('parent'));
+ }
+ parentSet.forEach(parentKey => {
+ let length = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${parentKey}"]`)).length;
+ let selectedLength = $(that.wrapSelector(`.${VP_FE_TABLE} th.selected[data-parent="${parentKey}"]`)).length;
+ if (length === selectedLength) {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).addClass('selected');
+ } else {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).removeClass('selected');
+ }
+ });
+ that.state.selection = { start: startIdx, end: firstIdx };
+ } else if (startIdx <= firstIdx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ let parentSet = new Set();
+ for (var i = startIdx; i < lastIdx; i++) {
+ $(tags[i]).addClass('selected');
+ parentSet.add($(tags[i]).data('parent'));
+ }
+ parentSet.forEach(parentKey => {
+ let length = $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${parentKey}"]`)).length;
+ let selectedLength = $(that.wrapSelector(`.${VP_FE_TABLE} th.selected[data-parent="${parentKey}"]`)).length;
+ if (length === selectedLength) {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).addClass('selected');
+ } else {
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${parentKey}"]`)).removeClass('selected');
+ }
+ });
+ that.state.selection = { start: startIdx, end: lastIdx };
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+
+ $(this).addClass('selected');
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-parent="${colLabel}"]`)).addClass('selected');
+ that.state.selection = { start: firstIdx, end: lastIdx };
+ }
+ var selected = [];
+ $(that.wrapSelector(`.${VP_FE_TABLE} th:not(.${VP_FE_TABLE_COLUMN_GROUP}).selected`)).each((idx, tag) => {
+ var label = $(tag).text();
+ var code = $(tag).data('code');
+ var type = $(tag).data('type');
+ selected.push({ label: label, code: code, type: type });
+ });
+ that.state.selected = selected;
+
+ // load info
+ that.renderMenu();
+ that.loadInfo();
+ });
+
+ // column selection
+ // select column
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN), function(evt) {
+ evt.stopPropagation();
+
+ var idx = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN)).index(this); // 1 ~ n
+ var hasSelected = $(this).hasClass('selected');
+
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_ROW)).removeClass('selected');
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ if (!hasSelected) {
+ that.state.selection = { start: idx, end: -1 };
+ $(this).addClass('selected');
+ } else {
+ $(this).removeClass('selected');
+ }
+
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ var startIdx = that.state.selection.start;
+
+ if (startIdx == -1) {
+ // no selection
+ that.state.selection = { start: idx, end: -1 };
+ } else if (startIdx > idx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ for (var i = idx; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ } else if (startIdx <= idx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_FE_TABLE_COLUMN));
+ for (var i = startIdx; i <= idx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state.selection = { start: startIdx, end: idx };
+ }
+ } else {
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN)).removeClass('selected');
+ $(that.wrapSelector('.' + VP_FE_TABLE + ' .' + VP_FE_TABLE_COLUMN_GROUP)).removeClass('selected');
+
+ $(this).addClass('selected');
+ that.state.selection = { start: idx, end: -1 };
+ }
+ // select its group
+ $(that.wrapSelector(`.${VP_FE_TABLE} th[data-label="${$(this).data('parent')}"]`)).addClass('selected');
+
+ var selected = [];
+ $(that.wrapSelector(`.${VP_FE_TABLE} th:not(.${VP_FE_TABLE_COLUMN_GROUP}).selected`)).each((idx, tag) => {
+ var label = $(tag).text();
+ var code = $(tag).data('code');
+ var type = $(tag).data('type');
+ selected.push({ label: label, code: code, type: type });
+ });
+ that.state.selected = selected;
+
+ // load info
+ that.renderMenu();
+ that.loadInfo();
+ });
+
+ // click more button for more rows
+ $(document).on('click', this.wrapSelector('.' + VP_FE_TABLE_MORE), function() {
+ that.state.lines += TABLE_LINES;
+ that.loadCode(that.state.data, true);
+ });
+
+
+ // click run button
+ $(this.wrapSelector('.vp-information-run-button')).click(function(event) {
+ // get code
+ var code = that.generateCodeForInfo();
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Data Analysis > Data Info');
+ });
+ }
+
+ handleChangeData(data, dtype) {
+ this.state.data = data;
+ this.state.dtype = dtype;
+ this.state.menu = '';
+ this.state.menuItem = [];
+ this.state.selected = [];
+ this.state.selection = { start: -1, end: -1 };
+ this.renderMenu();
+ $(this.wrapSelector('.' + VP_FE_TABLE)).html('');
+ this.loadCode(data);
+ this.loadInfo(data, this.state.menu);
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ let that = this;
+ let page = $(varHtml);
+
+ // add Data Selector
+ let targetSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data',
+ finish: function(value, dtype) {
+ // $(that.wrapSelector('#data')).trigger({type: 'change', value: value, dtype: dtype});
+ that.handleChangeData(value, dtype);
+ },
+ select: function(value, dtype) {
+ // $(that.wrapSelector('#data')).trigger({type: 'change', value: value, dtype: dtype});
+ that.handleChangeData(value, dtype);
+ // that.updateValue(value);
+ // that.reloadInsEditor();
+ }
+ });
+ $(page).find('#data').replaceWith(targetSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ this.renderMenu();
+ }
+
+ renderMenu() {
+ let that = this;
+ $(this.wrapSelector('.vp-information-toolbox')).html('');
+ // get current dtype
+ let currentDtype = this.state.dtype;
+ if (currentDtype === 'DataFrame' && this.state.selected.length == 1) {
+ currentDtype = 'Series';
+ }
+ // add menu list
+ this.menuList & this.menuList.forEach(menuObj => {
+ // show menu list dynamically
+ let { id, label, child, dtype } = menuObj;
+ let enabled = dtype.includes(currentDtype);
+ let selected = id === that.state.menu;
+ let $menu = $(``);
+ if (id === 'statistics') {
+ $menu.find('.vp-dropdown-content').css({'width': '300px'});
+ $menu.find('.vp-dropdown-content').append(`
`);
+ child && child.forEach(itemObj => {
+ let { id, label, type='checkbox' } = itemObj;
+ let selected = that.state.menuItem.includes(id);
+ if (type === 'checkbox') {
+ // checkbox to allow multi-select
+ $menu.find('.vp-dropdown-content .vp-information-multi-box')
+ .append($(`${label} `));
+ } else {
+ // radio to allow only single-select
+ $menu.find('.vp-dropdown-content .vp-information-single-box')
+ .append($(`${label} `));
+ }
+ });
+ } else {
+ child && child.forEach(itemObj => {
+ let { id, label, dtype } = itemObj;
+ let enabled = dtype.includes(currentDtype);
+ let selected = that.state.menuItem.includes(id);
+ if (enabled === false && selected === true) {
+ // if disabled menu is selected, remove selection
+ $menu.find('.vp-information-menu').removeClass('selected');
+ selected = false;
+ that.state.menu = '';
+ that.state.menuItem = [];
+ }
+ // disable item depends on dtype
+ $menu.find('.vp-dropdown-content')
+ .append($(``));
+ });
+ }
+ $(this.wrapSelector('.vp-information-toolbox')).append($menu);
+ });
+ }
+
+ renderTable(renderedText, isHtml=true) {
+ var tag = new com_String();
+ // Table
+ tag.appendFormatLine('', VP_FE_TABLE, 'vp_rendered_html', 'vp-scrollbar');
+ if (isHtml) {
+ tag.appendFormatLine('
', renderedText);
+ // More button
+ tag.appendFormatLine('
Show more
', VP_FE_TABLE_MORE, 'vp-button');
+ } else {
+ tag.appendFormatLine('
{0} ', renderedText);
+ }
+ tag.appendLine('
'); // End of Table
+ return tag.toString();
+ }
+
+ generateCode() {
+ return this.tempCode;
+ }
+
+ generateCodeForInfo() {
+ let { data, dtype, menu, menuItem } = this.state;
+
+ var selected = [];
+ $(this.wrapSelector(`.${VP_FE_TABLE} th:not(.${VP_FE_TABLE_COLUMN_GROUP}).selected`)).each((idx, tag) => {
+ var label = $(tag).text();
+ var code = $(tag).data('code');
+ var type = $(tag).data('type');
+ selected.push({ label: label, code: code, type: type });
+ });
+ this.state.selected = selected;
+
+ let currentDtype = dtype;
+ let dataVar = new com_String();
+ dataVar.append(data);
+ if (dtype === 'DataFrame') {
+ if (selected.length > 0) {
+ if (selected.length == 1) {
+ // series
+ dataVar.appendFormat("[{0}]", selected[0].code);
+ currentDtype = 'Series';
+ } else {
+ // dataframe
+ dataVar.appendFormat("[[{0}]]", selected.map(col=>col.code).join(','));
+ }
+ }
+ }
+
+ if (menu && menu !== '') {
+ // get code pattern string
+ let codePattern = '';
+
+ // add info methods
+ let infoObj = this.menuList.find(obj=>obj.id === menu);
+ if (menu === 'statistics') {
+ // allow multi-select
+ if (menuItem && menuItem.length > 0) {
+ if (menuItem.length > 1) {
+ let statList = [];
+ menuItem && menuItem.forEach(itemId => {
+ let childObj = infoObj.child.find(obj=>obj.id === itemId);
+ statList.push(com_util.formatString("'{0}': {1}", itemId, childObj.code));
+ });
+ if (currentDtype === 'Series' && selected.length > 0) {
+ // if multiple stats selected, set series data as dataframe
+ dataVar = new com_String();
+ dataVar.appendFormat("{0}[[{1}]]", data, selected.map(col=>col.code).join(','));
+ currentDtype = 'DataFrame';
+ }
+ codePattern = com_util.formatString("pd.DataFrame({{0}})", statList.join(','));
+ } else {
+ if (currentDtype === 'Series' && selected.length > 0) {
+ // if multiple stats selected, set series data as dataframe
+ dataVar = new com_String();
+ dataVar.appendFormat("{0}[[{1}]]", data, selected.map(col=>col.code).join(','));
+ currentDtype = 'DataFrame';
+ }
+ let childObj = infoObj.child.find(obj=>obj.id === menuItem[0]);
+ codePattern = childObj.code;
+ }
+ } else {
+ codePattern = infoObj.code;
+ }
+ } else {
+ // only one method selected
+ if (menuItem.length > 0 && infoObj.child) {
+ let childObj = infoObj.child.find(obj=>obj.id === menuItem[0]);
+ if (menuItem[0] === 'value_counts') {
+ if (currentDtype === 'Series') {
+ codePattern = childObj.code2;
+ } else {
+ codePattern = childObj.code;
+ }
+ } else {
+ if (childObj.toframe === true) {
+ if (dtype === 'Series') {
+ dataVar = new com_String();
+ dataVar.appendFormat("{0}.to_frame()", data);
+ currentDtype = 'DataFrame';
+ } else if (currentDtype === 'Series') { // DataFrame with single column selected
+ dataVar = new com_String();
+ dataVar.appendFormat("{0}[[{1}]]", data, selected.map(col=>col.code).join(','));
+ currentDtype = 'DataFrame';
+ }
+ }
+ codePattern = childObj.code;
+ }
+ } else {
+ codePattern = infoObj.code;
+ }
+ }
+
+ // match code pattern with data
+ if (codePattern) {
+ let code = codePattern.replaceAll('${data}', dataVar.toString());
+ return code;
+ }
+ }
+ // else if (currentDtype == 'DataFrame') {
+ // // if dtype is dataframe, show describe + info preview
+ // let codePattern = "_desc = ${data}.describe().T\
+ // \n_info = pd.DataFrame({'Non-Null Count': ${data}.notnull().sum(), 'Dtype': ${data}.dtypes})\
+ // \ndisplay(pd.concat([_info, _desc], axis=1).fillna(''))";
+
+ // let code = codePattern.replaceAll('${data}', dataVar.toString());
+ // return code;
+ // }
+
+ // add ignore options TODO:
+ // let ignoreCode = `import warnings\
+ // \nwith warnings.catch_warnings():
+ // \n warnings.simplefilter("ignore")\n`;
+
+ return `display(${dataVar.toString()})`;
+ }
+
+ loadCode(codeStr, more=false) {
+ if (this.loading === true) {
+ return;
+ }
+
+ var that = this;
+ let { data, lines, indexList } = this.state;
+ var prevLines = 0;
+ var scrollPos = -1;
+ if (more) {
+ prevLines = indexList.length;
+ scrollPos = $(this.wrapSelector('.vp-variable-table')).scrollTop();
+ }
+
+ var code = new com_String();
+ code.appendLine(codeStr);
+ code.appendFormat("{0}.iloc[{1}:{2}].to_json(orient='{3}')", data, prevLines, lines, 'split');
+
+ this.loading = true;
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ if (!result || result.length <= 0) {
+ return;
+ }
+ result = result.substr(1,result.length - 2).replaceAll('\\\\', '\\');
+ result = result.replaceAll('\'', "\\'"); // TEST: need test
+ // result = result.replaceAll('\\"', "\"");
+ var dataJson = JSON.parse(result);
+
+ vpKernel.getColumnList(data).then(function(colResObj) {
+ try {
+ let columnResult = colResObj.result;
+ var columnInfo = JSON.parse(columnResult);
+ let { name:columnName='', level:columnLevel, list:columnList } = columnInfo;
+ // var columnList = data.columns;
+ var indexList = dataJson.index;
+ var dataList = dataJson.data;
+
+ columnList = columnList.map(col => { return { label: col.label, type: col.dtype, code: col.value } });
+ indexList = indexList.map(idx => { return { label: idx, code: idx } });
+
+ if (!more) {
+ // table
+ var table = new com_String();
+ // table.appendFormatLine('', 1, 'dataframe');
+ table.appendLine('');
+ if (columnLevel > 1) {
+ for (let colLevIdx = 0; colLevIdx < columnLevel; colLevIdx++) {
+ table.appendLine(' ');
+ let colIdx = 0;
+ let colSpan = 1;
+ while (colIdx < columnList.length) {
+ let col = columnList[colIdx];
+ let colCode = col.code.slice(0, colLevIdx + 1).join(',');
+ let nextCol = columnList[colIdx + 1];
+ if (nextCol && nextCol.code.slice(0, colLevIdx + 1).join(',') === colCode) {
+ colSpan++;
+ } else {
+ let colClass = '';
+ let selected = ''; // set class if it's leaf node of columns on multi-level
+ if (that.state.selected.map(col=>col.code[colLevIdx]).includes(colCode)) {
+ selected = 'selected';
+ }
+ if ((columnLevel - 1) === colLevIdx) {
+ colClass = VP_FE_TABLE_COLUMN;
+ } else {
+ colClass = VP_FE_TABLE_COLUMN_GROUP;
+ }
+ table.appendFormatLine('{8} '
+ , colCode, FRAME_AXIS.COLUMN, col.type, col.label[colLevIdx-1], col.label[colLevIdx], colClass, selected, colSpan, col.label[colLevIdx]);
+ colSpan = 1;
+ }
+ colIdx++;
+ }
+
+ table.appendLine(' ');
+ }
+ } else {
+ table.appendLine(' ');
+ columnList && columnList.forEach(col => {
+ var colCode = col.code;
+ var colClass = '';
+ if (that.state.selected.map(col=>col.code).includes(colCode)) {
+ colClass = 'selected';
+ }
+ table.appendFormatLine('{6} '
+ , colCode, FRAME_AXIS.COLUMN, col.type, col.label, VP_FE_TABLE_COLUMN, colClass, col.label);
+ });
+ table.appendLine(' ');
+ }
+ table.appendLine(' ');
+ table.appendLine('');
+
+ dataList && dataList.forEach((row, idx) => {
+ table.appendLine('');
+ var idxName = indexList[idx].label;
+ var idxLabel = com_util.convertToStr(idxName, typeof idxName == 'string');
+ var idxClass = '';
+ table.appendFormatLine('{4} ', idxLabel, FRAME_AXIS.ROW, VP_FE_TABLE_ROW, idxClass, idxName);
+ row.forEach((cell, colIdx) => {
+ if (cell == null) {
+ cell = 'NaN';
+ }
+ var cellType = columnList[colIdx].type;
+ if (cellType.includes('datetime')) {
+ cell = new Date(parseInt(cell)).toLocaleString();
+ }
+ table.appendFormatLine('{0} ', cell);
+ });
+ table.appendLine(' ');
+ });
+ // add row
+ table.appendLine('');
+ table.appendLine(' ');
+ table.appendLine(' ');
+ $(that.wrapSelector('.' + VP_FE_TABLE)).replaceWith(function() {
+ return that.renderTable(table.toString());
+ });
+ } else {
+ var table = new com_String();
+ dataList && dataList.forEach((row, idx) => {
+ table.appendLine('');
+ var idxName = indexList[idx].label;
+ var idxLabel = com_util.convertToStr(idxName, typeof idxName == 'string');
+ var idxClass = '';
+ table.appendFormatLine('{4} ', idxLabel, FRAME_AXIS.ROW, VP_FE_TABLE_ROW, idxClass, idxName);
+ row.forEach((cell, colIdx) => {
+ if (cell == null) {
+ cell = 'NaN';
+ }
+ var cellType = columnList[colIdx].type;
+ if (cellType.includes('datetime')) {
+ cell = new Date(parseInt(cell)).toLocaleString();
+ }
+ table.appendFormatLine('{0} ', cell);
+ });
+ table.appendLine(' ');
+ });
+ // insert before last tr tag(add row button)
+ $(table.toString()).insertBefore($(that.wrapSelector('.' + VP_FE_TABLE + ' tbody tr:last')));
+ }
+
+ // save columnList & indexList as state
+ that.state.columnLevel = columnLevel;
+ that.state.columnList = columnList;
+ if (!more) {
+ that.state.indexList = indexList;
+ } else {
+ that.state.indexList = that.state.indexList.concat(indexList);
+ }
+
+ // if scrollPos is saved, go to the position
+ if (scrollPos >= 0) {
+ $(that.wrapSelector('.vp-variable-table')).scrollTop(scrollPos);
+ }
+
+ that.loading = false;
+ } catch (err1) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err1);
+ that.loading = false;
+ throw err1;
+ }
+ });
+ } catch (err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+ that.loading = false;
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content?.evalue, msg.content?.detail);
+ }
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ $(variablePreviewTag).html(errorContent);
+ that.loading = false;
+ });
+
+ return code.toString();
+ }
+
+ /**
+ * Load information preview
+ */
+ loadInfo() {
+ let that = this;
+ let { menu, menuItem } = this.state;
+
+ $(this.wrapSelector('#informationPreviewTitle')).text('');
+ if (menu) {
+ let { label, child } = this.menuList.find(x => x.id === menu);
+ let menuItemLabelList = child.filter(x => menuItem.includes(x.id)).map(x => x.label);
+
+ // load preview title
+ $(this.wrapSelector('#informationPreviewTitle')).text(com_util.formatString('{0} > {1}', label, menuItemLabelList.join(', ')));
+ }
+ // load preview content
+ let $infoPreviewTag = $(this.wrapSelector('#informationPreview'));
+ $infoPreviewTag.html('');
+ let code = this.generateCodeForInfo();
+ this.tempCode = code;
+
+ // use default pandas option
+ // let defaultPOCode = new com_String();
+ // defaultPOCode.appendLine("with pd.option_context('display.min_rows', 10, 'display.max_rows', 60, 'display.max_columns', 0, 'display.max_colwidth', 50, 'display.expand_frame_repr', True, 'display.precision', 6, 'display.chop_threshold', None):");
+ // defaultPOCode.append(' ' + code.replaceAll('\n', '\n '));
+
+ let loadingSpinner = new LoadingSpinner($(this.wrapSelector('#informationPreview')));
+ // show variable information on clicking variable
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (type !== 'error' && result) {
+ $infoPreviewTag.html('');
+ if (type == 'text/html') {
+ // 1. HTML tag
+ $infoPreviewTag.append(result);
+ } else if (type == 'image/png') {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $infoPreviewTag.append(imgTag);
+ } else if (type == 'text/plain' || type == 'text') {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(result);
+ $infoPreviewTag.html(preTag);
+ } else {
+ $infoPreviewTag.append('(Select data to preview.)');
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ }
+ $infoPreviewTag.html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg, ename, evalue } = resultObj;
+ var errorContent = '';
+ if (msg && msg?.content?.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ } else if (ename && evalue) {
+ errorContent = com_util.templateForErrorBox(ename, evalue);
+ vpLog.display(VP_LOG_TYPE.ERROR, ename, evalue, resultObj);
+ }
+ $infoPreviewTag.html(errorContent);
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }
+ }
+
+ // search rows count at once
+ const TABLE_LINES = 10;
+
+ const VP_FE_TABLE = 'vp-variable-table';
+ const VP_FE_TABLE_COLUMN = 'vp-variable-table-column';
+ const VP_FE_TABLE_COLUMN_GROUP = 'vp-variable-table-column-group';
+ const VP_FE_TABLE_ROW = 'vp-variable-table-row';
+ const VP_FE_TABLE_MORE = 'vp-variable-table-more';
+
+ const FRAME_AXIS = {
+ NONE: -1,
+ ROW: 0,
+ COLUMN: 1
+ }
+
+ return Information;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Instance.js b/visualpython/js/m_apps/Instance.js
new file mode 100644
index 00000000..1095ef31
--- /dev/null
+++ b/visualpython/js/m_apps/Instance.js
@@ -0,0 +1,402 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Instance.js
+ * Author : Black Logic
+ * Note : Apps > Instance
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Instance
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/instance.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/instance'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/InstanceEditor',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(insHtml, insCss, com_String, com_util, PopupComponent, InstanceEditor, DataSelector, Subset) {
+
+ const MAX_STACK_SIZE = 20;
+
+ /**
+ * Instance
+ */
+ class Instance extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 5;
+ this.config.checkModules = ['pd'];
+
+ this.state = {
+ target: '',
+ vp_instanceVariable: '',
+ variable: {
+ stack: []
+ },
+ selectedBox: 'variable',
+ allocate: '',
+ ...this.state
+ }
+ this.pointer = this.state.variable;
+ this.subsetEditor = null;
+ this.insEditor = null;
+
+ this._addCodemirror('vp_instanceVariable', this.wrapSelector('#vp_instanceVariable'), 'readonly');
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+ // target change
+ $(this.wrapSelector('#vp_instanceTarget')).on('change', function(event) {
+ let value = $(this).val();
+ that.updateValue(value);
+ that.reloadInsEditor();
+ });
+ // clear
+ $(this.wrapSelector('#vp_instanceClear')).on('click', function(event) {
+ that.addStack();
+ that.updateValue('');
+ that.reloadInsEditor();
+ });
+
+ // undo
+ $(this.wrapSelector('#vp_instanceUndo')).on('click', function(event) {
+ that.popStack();
+ that.reloadInsEditor();
+ });
+
+ // backspace
+ $(document).on('keyup', this.wrapSelector('.CodeMirror'), function(event) {
+ var keycode = event.keyCode
+ ? event.keyCode
+ : event.which;
+ if (keycode == 8) {
+ // backspace
+ that.popStack();
+ that.reloadInsEditor();
+ }
+ });
+
+ // subset button clicked
+ $(document).on('click', this.wrapSelector('.vp-ds-button'), function(event) {
+ var insEditorType = $(this).closest('.vp-instance-box').hasClass('variable')? 'variable': 'allocate';
+ $(that.wrapSelector('.CodeMirror')).removeClass('selected');
+ if (insEditorType == 'variable') {
+ // variable
+ that.pointer = that.state.variable;
+ $(that.wrapSelector('.variable .CodeMirror')).addClass('selected');
+ } else if (insEditorType == 'allocate'){
+ // allocate
+ that.pointer = that.state.allocate;
+ $(that.wrapSelector('.allocate .CodeMirror')).addClass('selected');
+ } else {
+ // that.state.variable.insEditor.hide();
+ // that.state.allocate.insEditor.hide();
+ }
+ });
+
+ // subset applied - variable
+ $(document).on('change apps_run', this.wrapSelector('#vp_instanceVariable'), function(event) {
+ var val = $(this).val();
+ that.addStack();
+ that.updateValue(val);
+ });
+
+ // codemirror clicked
+ $(document).on('click', this.wrapSelector('.CodeMirror'), function(event) {
+ $(that.wrapSelector('.CodeMirror')).removeClass('selected');
+ $(this).addClass('selected');
+
+ // show/hide insEditor
+ var insEditorType = $(this).closest('.vp-instance-box').hasClass('variable')? 'variable': 'allocate';
+
+ if (insEditorType == 'variable') {
+ // variable
+ that.state.selectedBox = 'variable';
+ that.pointer = that.state.variable;
+ } else if (insEditorType == 'allocate'){
+ // allocate
+ that.state.selectedBox = 'allocate';
+ that.pointer = that.state.allocate;
+ } else {
+ that.state.selectedBox = '';
+ }
+ });
+
+ $(document).on('focus', this.wrapSelector('.CodeMirror'), function(event) {
+ $(this).trigger('click');
+ });
+
+ // instance_editor_selected - variable
+ $(document).on('instance_editor_selected', this.wrapSelector('#vp_instanceVariable'), function(event) {
+ that.addStack();
+ let cmObj = that.getCodemirror('vp_instanceVariable');
+ var nowCode = (cmObj && cmObj.cm)?cmObj.cm.getValue():'';
+ if (nowCode != '') {
+ nowCode += '.'
+ }
+ var selectedVariable = event.varName;
+ let fullCode = nowCode + selectedVariable;
+ that.updateValue(fullCode);
+ that.reloadInsEditor();
+ });
+
+ // instance_editor_replaced - variable
+ $(document).on('instance_editor_replaced', this.wrapSelector('#vp_instanceVariable'), function(event) {
+ that.addStack();
+
+ var newCode = event.newCode;
+ that.updateValue(newCode);
+ that.reloadInsEditor();
+ });
+
+ // co-op with Subset
+ // $(this.wrapSelector('#vp_instanceVariable')).on('remove_option_page', function(evt) {
+ // let component = evt.component;
+ // component.close();
+ // });
+ // $(this.wrapSelector('#vp_instanceVariable')).on('close_option_page', function(evt) {
+ // let component = evt.component;
+ // component.close();
+ // });
+ // $(this.wrapSelector('#vp_instanceVariable')).on('focus_option_page', function(evt) {
+ // let component = evt.component;
+ // component.focus();
+ // });
+ // $(this.wrapSelector('#vp_instanceVariable')).on('apply_option_page', function(evt) {
+ // let component = evt.component;
+ // // apply its value
+ // let code = component.generateCode();
+ // component.close();
+ // that.addStack();
+ // that.state.subsetEditor.state.pandasObject = code;
+ // that.updateValue(code);
+ // });
+ }
+
+ templateForBody() {
+ let that = this;
+ let page = $(insHtml);
+ $(page).find('#vp_instanceVariable').val(this.state.vp_instanceVariable);
+
+ let targetSelector = new DataSelector({
+ pageThis: this, id: 'vp_instanceTarget', placeholder: 'Select variable',
+ allowDataType: [
+ 'module', 'DataFrame', 'Series', 'dict', 'list', 'int'
+ ],
+ allowModule: true,
+ finish: function(value, dtype) {
+ $(that.wrapSelector('#vp_instanceTarget')).trigger({type: 'change', value: value});
+ that.updateValue(value);
+ that.reloadInsEditor();
+ },
+ select: function(value, dtype) {
+ $(that.wrapSelector('#vp_instanceTarget')).trigger({type: 'change', value: value});
+ that.updateValue(value);
+ that.reloadInsEditor();
+ }
+ });
+ $(page).find('#vp_instanceTarget').replaceWith(targetSelector.toTagString());
+
+ // Removed dataselector for Allocation input
+ // let allocateSelector = new DataSelector({
+ // pageThis: this, id: 'vp_instanceAllocate', placeholder: 'Variable name'
+ // });
+ // $(page).find('#vp_instanceAllocate').replaceWith(allocateSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ let that = this;
+
+ // vpSubsetEditor
+ this.subsetEditor = new Subset({ pandasObject: '', config: { name: 'Subset', category: this.name } },
+ {
+ useInputVariable: true,
+ targetSelector: this.wrapSelector('#vp_instanceVariable'),
+ pageThis: this,
+ finish: function(code) {
+ that.addStack();
+ that.subsetEditor.state.pandasObject = code;
+ that.updateValue(code);
+ }
+ });
+ this.subsetEditor.disableButton();
+
+ this.ALLOW_SUBSET_TYPES = this.subsetEditor.getAllowSubsetTypes();
+
+ // vpInstanceEditor
+ this.insEditor = new InstanceEditor(this, "vp_instanceVariable", 'vp_variableInsEditContainer', { targetType: 'outside' });
+
+ this.insEditor.show();
+
+ // variable load
+ this.reloadInsEditor();
+ }
+
+ loadState() {
+ super.loadState();
+
+ // load metadata
+ let { vp_instanceVariable, allocate } = this.state;
+ this.updateValue(vp_instanceVariable);
+ $(this.wrapSelector('#vp_instanceAllocate')).val(allocate);
+ }
+
+ generateCode() {
+ var sbCode = new com_String();
+
+ var leftCode = $(this.wrapSelector('#vp_instanceAllocate')).val();
+ let cmObj = this.getCodemirror('vp_instanceVariable');
+ let rightCode = (cmObj && cmObj.cm)?cmObj.cm.getValue():'';
+ if (leftCode && leftCode != '') {
+ sbCode.appendFormatLine('{0} = {1}', leftCode, rightCode);
+ sbCode.append(leftCode); // show allocation (from version 2.4.10)
+ } else {
+ sbCode.appendFormat('{0}', rightCode);
+ }
+
+ return sbCode.toString();
+ }
+
+ hide() {
+ super.hide();
+ this.subsetEditor && this.subsetEditor.hide();
+ }
+
+ close() {
+ super.close();
+ this.subsetEditor && this.subsetEditor.close();
+ }
+
+ remove() {
+ super.remove();
+ this.subsetEditor && this.subsetEditor.remove();
+ }
+
+ updateValue(value) {
+ let cmObj = this.getCodemirror('vp_instanceVariable');
+ if (cmObj && cmObj.cm) {
+ let cm = cmObj.cm;
+ cm.setValue(value);
+ cm.save();
+ cm.focus();
+ cm.setCursor({ line: 0, ch: value.length});
+ }
+ this.state.vp_instanceVariable = value;
+
+ // show preview
+ this.loadPreview(value);
+ }
+
+ loadPreview(code) {
+ let that = this;
+ if (!code || code === '') {
+ $(that.wrapSelector('#instancePreview')).html('');
+ return;
+ }
+ // show variable information on clicking variable
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (msg.content.data) {
+ var textResult = msg.content.data["text/plain"];
+ var htmlResult = msg.content.data["text/html"];
+ var imgResult = msg.content.data["image/png"];
+
+ $(that.wrapSelector('#instancePreview')).html('');
+ if (htmlResult != undefined) {
+ // 1. HTML tag
+ $(that.wrapSelector('#instancePreview')).append(htmlResult);
+ } else if (imgResult != undefined) {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $(that.wrapSelector('#instancePreview')).append(imgTag);
+ } else if (textResult != undefined) {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(textResult);
+ $(that.wrapSelector('#instancePreview')).html(preTag);
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ }
+ $(that.wrapSelector('#instancePreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg, ename, evalue, status } = resultObj;
+ var errorContent = '';
+ if (msg && msg.content && msg.content.ename) {
+ // NOTEBOOK: notebook error FIXME: migrate it on com_Kernel.execute
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ } else {
+ // LAB: lab error FIXME: migrate it on com_Kernel.execute
+ errorContent = com_util.templateForErrorBox(ename, evalue, '');
+ vpLog.display(VP_LOG_TYPE.ERROR, ename, evalue);
+ }
+ $(that.wrapSelector('#instancePreview')).html(errorContent);
+ });
+ }
+
+ addStack() {
+ let cmObj = this.getCodemirror('vp_instanceVariable');
+ var currentValue = (cmObj && cmObj.cm)?cmObj.cm.getValue():'';
+ this.pointer.stack.push(currentValue);
+
+ // if stack over MAX_STACK_SIZE
+ if (this.pointer.stack.length > MAX_STACK_SIZE) {
+ this.pointer.stack.splice(0, 1);
+ }
+ // console.log('add stack', currentValue, this.pointer.stack);
+ }
+
+ popStack(replace=true) {
+ var lastValue = this.pointer.stack.pop();
+ if (!lastValue) {
+ lastValue = '';
+ }
+ if (replace) {
+ this.updateValue(lastValue);
+ }
+ // console.log('pop stack', lastValue, this.pointer.stack);
+ return lastValue;
+ }
+
+ reloadInsEditor() {
+ var that = this;
+ var tempPointer = this.pointer;
+ this.subsetEditor.disableButton();
+ var callbackFunction = function (varObj) {
+ var varType = varObj.type;
+
+ if (that.ALLOW_SUBSET_TYPES.includes(varType)) {
+ that.subsetEditor.state.dataType = varType;
+ let cmObj = that.getCodemirror('vp_instanceVariable');
+ let nowCode = (cmObj && cmObj.cm)?cmObj.cm.getValue():'';
+ that.subsetEditor.state.pandasObject = nowCode;
+ that.subsetEditor.enableButton();
+ }
+ };
+
+ this.insEditor.reload(callbackFunction);
+ }
+ }
+
+ return Instance;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Markdown.js b/visualpython/js/m_apps/Markdown.js
new file mode 100644
index 00000000..ccceec89
--- /dev/null
+++ b/visualpython/js/m_apps/Markdown.js
@@ -0,0 +1,670 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Markdown.js
+ * Author : Black Logic
+ * Note : Apps > Markdown
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Markdown
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/m_apps/markdown'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation',
+ // CHROME: remove mathjaxutils - use MathJax in colab
+ 'mathjaxutils',
+ // 'marked',
+// ], function(markdownCss, com_String, com_util, PopupComponent, FileNavigation, marked, mathjaxutils) {
+], function(markdownCss, com_String, com_util, PopupComponent, FileNavigation, mathjaxutils) {
+
+ // markdown default text
+ const VP_MARKDOWN_DEFAULT_NEW_TITLE_TEXT = 'New Title';
+ const VP_MARKDOWN_DEFAULT_BOLD_TEXT = 'Bold Text';
+ const VP_MARKDOWN_DEFAULT_ITALIC_TEXT = 'Italic Text';
+ const VP_MARKDOWN_DEFAULT_CODE_TEXT = 'Formatted by code';
+ const VP_MARKDOWN_DEFAULT_LINK_TEXT = 'link Text';
+ const VP_MARKDOWN_DEFAULT_INDENT_TEXT = '\n\n> Indented block\n\n';
+ const VP_MARKDOWN_DEFAULT_LIST_TEXT = 'Add item';
+
+ /**
+ * Markdown
+ */
+ class Markdown extends PopupComponent {
+ _init() {
+ super._init();
+
+ /** Write codes executed before rendering */
+ this.config.executeMode = 'markdown';
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+ this.config.checkModules = ['pd'];
+
+ this.state = {
+ editor: '',
+ preview: '',
+ generatedCode: '',
+ attachments: [],
+ ...this.state
+ }
+
+ let that = this;
+ this._addCodemirror('editor', this.wrapSelector('#vp_markdownEditor'), 'markdown', {
+ events: [
+ { key: 'change', callback: function() {
+ that.previewRender();
+ } }
+ ]
+ });
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+ /** Implement binding events */
+ $(document).on(com_util.formatString("propertychange change keyup paste input.{0}", that.uuid), that.wrapSelector("#vp_markdownEditor"), function(evt) {
+ evt.stopPropagation();
+ that.previewRender();
+ });
+
+ $(document).on('click', this.wrapSelector('.vp-markdown-editor-toolbar div'), function(evt) {
+ // jquery object convert to javascript object for get selection properies
+ const textarea = $(that.wrapSelector("#vp_markdownEditor")).get(0);
+ let cmObj = that.getCodemirror('editor');
+ if (!cmObj) {
+ return;
+ }
+ let cm = cmObj.cm;
+ let menu = $(this).data('menu');
+
+ switch (menu) {
+ case 'title':
+ that.adjustTitle(cm);
+ break;
+ case 'bold':
+ that.adjustBold(cm);
+ break;
+ case 'italic':
+ that.adjustItalic(cm);
+ break;
+ case 'code':
+ that.adjustCode(cm);
+ break;
+ case 'link':
+ that.adjustLink(cm);
+ break;
+ case 'image':
+ that.openImageFile(cm);
+ break;
+ case 'indent':
+ that.addIndentStyle(cm);
+ break;
+ case 'order-list':
+ that.addOrderdList(cm);
+ break;
+ case 'unorder-list':
+ that.addUnorderdList(cm);
+ break;
+ case 'horizontal-line':
+ that.addHorizontalLine(cm);
+ break;
+ }
+
+ // image renders on the process of opening image
+ if (menu != 'image') {
+ // render markdown
+ that.previewRender();
+ }
+ });
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ page.appendLine(this.templateForToolbar());
+ page.appendFormatLine('
', 'vp_markdownEditor', this.state.editor);
+ page.appendFormatLine('
', "vp_attachEncodedDataArea");
+ page.appendLine('
');
+ page.appendFormatLine('{1}
', 'vp_markdownPreview', this.state.preview);
+ return page.toString();
+ }
+
+ templateForToolbar() {
+ return ``;
+ }
+
+ render() {
+ super.render();
+
+ let cm = this.getCodemirror('editor').cm;
+ if (cm) {
+ cm.setSize(null, '255px'); // set width, height of codemirror
+ }
+ }
+
+ generateCode() {
+ var that = this;
+
+ var gCode = this.state['editor'];
+
+ $(this.wrapSelector("#vp_attachEncodedDataArea input[type=hidden]")).each(function() {
+ var indicator = $(this).data('indicator');
+ var data = $(this).val();
+
+ that.state.attachments.push({
+ indicator: indicator
+ , data: data
+ });
+
+ gCode = gCode.replace(indicator, data);
+ });
+
+ // metadata save for attachments
+ $('#vp_imgAttachment').val(encodeURIComponent(JSON.stringify(this.state.attachments)));
+
+ this.state.generatedCode = gCode;
+
+ return this.state.generatedCode;
+ }
+
+ /**
+ * Render markdown
+ */
+ previewRender = function() {
+ let text = this.getCodemirror('editor').cm.getValue();
+ $(com_util.wrapSelector(com_util.formatString("#{0} input[type=hidden]", "vp_attachEncodedDataArea"))).each(function() {
+ text = text.replace($(this).data("indicator"), $(this).val());
+ });
+
+ var math = null;
+ var text_and_math = mathjaxutils.remove_math(text);
+ text = text_and_math[0];
+ math = text_and_math[1];
+
+ // CHROME: TODO: 4: marked is not loaded, before fix it comment it
+ if (vpConfig.extensionType === 'notebook') {
+ var marked = window.require('components/marked/lib/marked');
+ var renderer = new marked.Renderer();
+
+ // get block
+ let block = this.getTaskType() == 'block'? this.taskItem: null;
+
+ let that = this;
+ // render preview
+ marked(text, { renderer: renderer }, function (err, html) {
+ html = mathjaxutils.replace_math(html, math);
+ let preview = `${html}
`;
+ if (html == '') {
+ preview = '';
+ }
+ that.state.preview = preview;
+ $(that.wrapSelector("#vp_markdownPreview")).html(preview);
+
+ MathJax.Hub.Queue(["Typeset", MathJax.Hub, "vp_markdownPreview"]);
+ });
+ } else if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ var marked = require('marked');
+
+ // get block
+ let block = this.getTaskType() == 'block'? this.taskItem: null;
+
+ let that = this;
+ // render preview
+ let html = marked.parse(text);
+ html = mathjaxutils.replace_math(html, math);
+ let preview = ``;
+ if (html == '') {
+ preview = '';
+ }
+ that.state.preview = preview;
+ $(that.wrapSelector("#vp_markdownPreview")).html(preview);
+ $(that.wrapSelector('#vp_markdownIFrame')).contents().find('body').html(html);
+ }
+
+ }
+
+ getPreview() {
+ return this.state.preview;
+ }
+
+ ///////////////////////////////////////////////////// EDIT BELOW /////////////////////////////////////////////////////////////
+
+ importImageByPath(cm, path) {
+ // get cursor info
+ let {line, ch} = cm.getCursor();
+
+ let that = this;
+ vpKernel.getImageFile(path).then(function(resultObj) {
+ let data = resultObj.result;
+ var imgResult = data["image/png"];
+
+ let imgVal = com_util.formatString("", path, path);
+
+ // create file attach id
+ var pathSplit = path.split('.').join('/').split('/');
+ var fileId = pathSplit[pathSplit.length - 2];
+ var attachID = com_util.formatString("{0}__{1}", 'vpImportImage', fileId);
+
+ if ($(that.wrapSelector(com_util.formatString("#{0} #{1}", "vp_attachEncodedDataArea", attachID))).length > 0) {
+ $(that.wrapSelector(com_util.formatString("#{0} #{1}", "vp_attachEncodedDataArea", attachID))).val('(data:image/png;base64,' + imgResult + ')')
+ } else {
+ $(that.wrapSelector(com_util.formatString("#{0}", "vp_attachEncodedDataArea")))
+ .append(com_util.formatString(" ", attachID, 'vpImportImage', path, imgResult));
+ }
+
+ cm.setCursor({line: line+1, ch: 0});
+ cm.replaceSelection(imgVal);
+ cm.setSelection({line: line+1, ch: 0}, {line: line+1});
+ cm.focus();
+ that.previewRender();
+ });
+ }
+ /**
+ * Open file navigator for selecting image file
+ */
+ openImageFile(cm) {
+ // open file navigation
+ // allow image extensions
+ let allowExtensionList = ['jpg', 'png', 'gif', 'jpeg', 'xbm', 'tif', 'pjp', 'jfif', 'ico', 'tiff', 'svg', 'webp', 'svgz', 'bmp', 'pjpeg', 'avif'];
+ let that = this;
+ let fileNavi = new FileNavigation({ type: 'open', extensions: allowExtensionList, finish: function(filesPath, status, error) {
+ // after selection
+ let { file, path } = filesPath[0];
+ that.importImageByPath(cm, path);
+ }});
+ fileNavi.open();
+ };
+
+ /**
+ * Adjust title
+ * @param {object} cm CodeMirror Object
+ */
+ adjustTitle(cm) {
+ // cursor position
+ var { line, ch, sticky } = cm.getCursor();
+
+ // cursor line text
+ var lineText = cm.getLine(line);
+ // set default text
+ if (lineText.trim() == "") {
+ lineText = VP_MARKDOWN_DEFAULT_NEW_TITLE_TEXT;
+ }
+ var adjustText;
+ // check if this line is using title markdown
+ if (/^[#]{6}\s{1,}/i.test(lineText)) { // ######(6) -> #(1)
+ adjustText = "#" + lineText.replace("######", "");
+ } else if (/^[#]{1,5}\s{1,}/i.test(lineText)) { // #(1~5) -> # + #(add 1 #)
+ adjustText = "#" + lineText
+ } else { // #(>6 or =0) -> add # and whitespace('# ')
+ adjustText = "# " + lineText
+ }
+
+ // Apply adjusted text
+ // select all text in this line
+ cm.setSelection({line: line, ch: 0}, {line: line});
+ // repace selection
+ cm.replaceSelection(adjustText);
+ // TODO: set block code
+ cm.focus();
+ }
+
+ /**
+ * Adjust bold
+ * @param {object} cm CodeMirror Object
+ */
+ adjustBold(cm) {
+ // cursor
+ var { line, ch, sticky } = cm.getCursor();
+ // this line
+ var lineText = cm.getLine(line);
+
+ var targetText = '';
+ var adjustText; // adjusted text
+ let preSpace = ''; // space needed for previous
+ let postSpace = ''; // space needed for posterior
+
+ // no selection area
+ if (!cm.somethingSelected()) {
+ // previous text checking
+ var preCh = 0;
+ var postCh = 0;
+
+ let preText = lineText.substring(0, ch);
+ let boldPos1 = preText.lastIndexOf('**');
+ let spacePos1 = preText.lastIndexOf(' ') + 1;
+
+ // posterior text checking
+ let postText = lineText.substring(ch);
+ let boldPos2 = postText.indexOf('**') + 1;
+ let spacePos2 = postText.indexOf(' ') - 1;
+
+
+ preCh = Math.max(boldPos1, spacePos1, 0);
+ postCh = Math.min(boldPos2, spacePos2);
+ if (postCh < 0) postCh = lineText.length;
+
+ if (preCh == boldPos1 && postCh == boldPos2) {
+ ; // no problem
+ } else {
+ // if only one part of prev & post is bold, remove that part
+ if (preCh == boldPos1 && boldPos1 < 0) {
+ preCh = Math.min(boldPos1 + 2, lineText.length);
+ preSpace = ' ';
+ }
+ if (postCh == boldPos2 && boldPos2 < 0) {
+ postCh = Math.max(boldPos2 - 2, 0);
+ postSpace = ' ';
+ }
+ }
+
+ // set target text
+ targetText = lineText.substring(preCh, postCh);
+
+ // set selection
+ cm.setSelection({ line: line, ch: preCh }, { line: line, ch: postCh });
+ } else {
+ // has selection area
+ targetText = cm.getSelection();
+ }
+
+ let regExp = /^[*]{2}(.*?)[*]{2}$/;
+ // if bold(**) is included, remove it
+ if (regExp.test(targetText.trim())) {
+ adjustText = targetText.substring(2, targetText.length - 2);
+ ch -= 2;
+ } else {
+ // add bold(**) before and after
+ if (targetText == '') {
+ targetText = VP_MARKDOWN_DEFAULT_BOLD_TEXT;
+ }
+ adjustText = preSpace + '**' + targetText + '**' + postSpace;
+ ch += preSpace.length + 2;
+ }
+
+ // replace selection
+ cm.replaceSelection(adjustText);
+ // set cursor
+ cm.setCursor({line: line, ch: ch});
+ cm.focus();
+ }
+
+ /**
+ * Italic
+ * @param {object} cm CodeMirror editor
+ */
+ adjustItalic(cm) {
+ // cursor
+ var { line, ch, sticky } = cm.getCursor();
+ // this line
+ var lineText = cm.getLine(line);
+
+ var targetText = '';
+ var adjustText; // adjusted text
+ let preSpace = ''; // space needed for previous
+ let postSpace = ''; // space needed for posterior
+
+ // no selection area
+ if (!cm.somethingSelected()) {
+ // previous text checking
+ var preCh = 0;
+ var postCh = 0;
+
+ let preText = lineText.substring(0, ch);
+ let italPos1 = preText.lastIndexOf('*');
+ let spacePos1 = preText.lastIndexOf(' ') + 1;
+
+ // posterior text checking
+ let postText = lineText.substring(ch);
+ let italPos2 = postText.indexOf('*');
+ let spacePos2 = postText.indexOf(' ') - 1;
+
+
+ preCh = Math.max(italPos1, spacePos1, 0);
+ postCh = Math.min(italPos2, spacePos2);
+ if (postCh < 0) postCh = lineText.length;
+
+ if (preCh == italPos1 && postCh == italPos2) {
+ ; // no problem
+ } else {
+ // if only one part of prev & post is italic, remove that part
+ if (preCh == italPos1 && italPos1 < 0) {
+ preCh = Math.min(italPos1 + 1, lineText.length);
+ preSpace = ' ';
+ }
+ if (postCh == italPos2 && italPos2 < 0) {
+ postCh = Math.max(italPos2 - 1, 0);
+ postSpace = ' ';
+ }
+ }
+
+ // set target text
+ targetText = lineText.substring(preCh, postCh);
+
+ // set selection
+ cm.setSelection({ line: line, ch: preCh }, { line: line, ch: postCh });
+ } else {
+ // has selection area
+ targetText = cm.getSelection();
+ }
+
+ let regExp = /^[*]{1}(.*?)[*]{1}$/;
+ // if italic(*) is included, remove it
+ if (regExp.test(targetText.trim())) {
+ adjustText = targetText.substring(1, targetText.length - 1);
+ ch -= 1;
+ } else {
+ // add italic(*) before and after
+ if (targetText == '') {
+ targetText = VP_MARKDOWN_DEFAULT_ITALIC_TEXT;
+ }
+ adjustText = preSpace + '*' + targetText + '*' + postSpace;
+ ch += preSpace.length + 1;
+ }
+
+ // replace selection
+ cm.replaceSelection(adjustText);
+ // set cursor
+ cm.setCursor({line: line, ch: ch});
+ cm.focus();
+ }
+
+ /**
+ * Code
+ * @param {object} cm Codemirror Object
+ */
+ adjustCode(cm) {
+ // cursor
+ var { line, ch, sticky } = cm.getCursor();
+ // this line
+ var lineText = cm.getLine(line);
+
+ var targetText = '';
+ var adjustText; // adjusted text
+ let preSpace = ''; // space needed for previous
+ let postSpace = ''; // space needed for posterior
+ let multiLine = false;
+
+ // no selection area
+ if (!cm.somethingSelected()) {
+ // previous text checking
+ var preCh = 0;
+ var postCh = 0;
+
+ let preText = lineText.substring(0, ch);
+ let codePos1 = preText.lastIndexOf('`');
+ let spacePos1 = preText.lastIndexOf(' ') + 1;
+
+ // posterior text checking
+ let postText = lineText.substring(ch);
+ let codePos2 = postText.indexOf('`');
+ let spacePos2 = postText.indexOf(' ') - 1;
+
+
+ preCh = Math.max(codePos1, spacePos1, 0);
+ postCh = Math.min(codePos2, spacePos2);
+ if (postCh < 0) postCh = lineText.length;
+
+ if (preCh == codePos1 && postCh == codePos2) {
+ ; // no problem
+ } else {
+ // if only one part of prev & post is italic, remove that part
+ if (preCh == codePos1 && codePos1 < 0) {
+ preCh = Math.min(codePos1 + 1, lineText.length);
+ preSpace = ' ';
+ }
+ if (postCh == codePos2 && codePos2 < 0) {
+ postCh = Math.max(codePos2 - 1, 0);
+ postSpace = ' ';
+ }
+ }
+
+ // set target text
+ targetText = lineText.substring(preCh, postCh);
+
+ // set selection
+ cm.setSelection({ line: line, ch: preCh }, { line: line, ch: postCh });
+ } else {
+ // has selection area
+ targetText = cm.getSelection();
+
+ let preCur = cm.getCursor('from');
+ let postCur = cm.getCursor('to');
+
+ if (preCur.line != postCur.line) {
+ multiLine = true;
+ }
+ }
+
+ let regExp = /^[`]{1}(.*?)[`]{1}$/;
+ let sigNum = 1; // code sign numbering 1 or 3(for multi-line)
+ let sign = '`';
+ if (multiLine) {
+ // if multi line, use 3 sign
+ regExp = /^[`]{3}(.*?)[`]{3}$/;
+ sigNum = 3;
+ sign = '```';
+ }
+
+ // if code(`) is included, remove it
+ if (regExp.test(targetText.trim())) {
+ adjustText = targetText.substring(sigNum, targetText.length - sigNum);
+ ch -= sigNum;
+ } else {
+ // add code(`) before and after
+ if (targetText == '') {
+ targetText = VP_MARKDOWN_DEFAULT_CODE_TEXT;
+ }
+ adjustText = preSpace + sign + targetText + sign + postSpace;
+ ch += preSpace.length + sigNum;
+ }
+
+ // replace selection
+ cm.replaceSelection(adjustText);
+ // set cursor
+ cm.setCursor({line: line, ch: ch});
+ cm.focus();
+ }
+
+ /**
+ * Link
+ * @param {object} cm Codemirror Object
+ */
+ adjustLink(cm) {
+ // selected text
+ let { line, ch } = cm.getCursor();
+ var selectedText = cm.getSelection();
+ var linkText;
+ if (selectedText.startsWith("http://") || selectedText.startsWith("https://")) {
+ linkText = com_util.formatString("[{0}]({1})", VP_MARKDOWN_DEFAULT_LINK_TEXT, selectedText);
+ } else {
+ linkText = com_util.formatString("[{0}](https://)", (selectedText == undefined || selectedText == "" ? VP_MARKDOWN_DEFAULT_LINK_TEXT : selectedText));
+ }
+ cm.replaceSelection(linkText);
+ // set cursor
+ cm.setCursor({line: line, ch: ch});
+ cm.focus();
+ }
+
+ /**
+ * Indent style
+ * @param {object} cm Codemirror Object
+ */
+ addIndentStyle(cm) {
+ let {line, ch} = cm.getCursor();
+ let indentText = VP_MARKDOWN_DEFAULT_INDENT_TEXT;
+ // add indent style below this line
+ cm.setSelection({line: line+1, ch: 0});
+ cm.replaceSelection(indentText);
+ // select default indent block text
+ cm.setSelection({line: line+3, ch: 2}, {line: line+3});
+ cm.focus();
+ }
+
+ /**
+ * Ordered list style
+ * @param {object} cm
+ */
+ addOrderdList(cm) {
+ let {line, ch} = cm.getCursor();
+ let listText = com_util.formatString("\n\n1. {0}\n2. {1}\n\n", VP_MARKDOWN_DEFAULT_LIST_TEXT, VP_MARKDOWN_DEFAULT_LIST_TEXT);
+ // add list style below this line
+ cm.setSelection({line: line+1, ch: 0});
+ cm.replaceSelection(listText);
+ // set cursor
+ cm.setSelection({line: line+3, ch: 5}, {line: line+3});
+ cm.focus();
+ }
+
+ /**
+ * Unordered list style
+ * @param {object} cm
+ */
+ addUnorderdList(cm) {
+ let {line, ch} = cm.getCursor();
+ let listText = com_util.formatString("\n\n* {0}\n* {1}\n\n", VP_MARKDOWN_DEFAULT_LIST_TEXT, VP_MARKDOWN_DEFAULT_LIST_TEXT);
+ // add list style below this line
+ cm.setSelection({line: line+1, ch: 0});
+ cm.replaceSelection(listText);
+ // set cursor
+ cm.setSelection({line: line+3, ch: 4}, {line: line+3});
+ cm.focus();
+ }
+
+ /**
+ * Horizontal line
+ * @param {object} cm
+ */
+ addHorizontalLine(cm) {
+ let {line, ch} = cm.getCursor();
+ let lineText = "\n\n---\n\n";
+ // add line style below this line
+ cm.setSelection({line: line+1, ch: 0});
+ cm.replaceSelection(lineText);
+ // set cursor
+ cm.setCursor({line: line+3, ch: 3});
+ cm.focus();
+ }
+
+ }
+
+ return Markdown;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/PDF.js b/visualpython/js/m_apps/PDF.js
new file mode 100644
index 00000000..e5fdf2ce
--- /dev/null
+++ b/visualpython/js/m_apps/PDF.js
@@ -0,0 +1,206 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : PDF.js
+ * Author : Black Logic
+ * Note : Apps > PDF
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] PDF
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/pdf.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/pdf'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation'
+], function(pdfHtml, pdfCss, com_String, com_interface, PopupComponent, FileNavigation) {
+
+ var PDF_SHOW = '!pip show PyMuPDF nltk'
+ var PDF_INSTALL1 = '!pip install PyMuPDF'
+ var PDF_INSTALL2 = '!pip install nltk'
+
+ const PDF_IMPORT = `import pandas as pd
+import fitz
+import nltk
+nltk.download('punkt')`;
+
+ const PDF_FUNC = `def vp_pdf_get_sentence(fname_lst):
+ '''
+ Get sentence from pdf file by PyMuPDF
+ '''
+ df = pd.DataFrame()
+ for fname in fname_lst:
+ if fname.split('.')[-1] != 'pdf': continue
+ try:
+ doc = fitz.open(fname)
+ sentence_lst = []
+ for page in doc:
+ block_lst = page.get_text('blocks')
+
+ text_lst = [block[4] for block in block_lst if block[6] == 0]
+ text = '\\n'.join(text_lst)
+
+ sentence_lst.extend([sentence for sentence in nltk.sent_tokenize(text)])
+
+ doc.close()
+ except Exception as e:
+ print(e)
+ continue
+
+ df_doc = pd.DataFrame({
+ 'fname': fname.split('/')[-1],
+ 'sentence': sentence_lst
+ })
+ df = pd.concat([df,df_doc])
+
+ return df.reset_index().drop('index', axis=1)`;
+
+ const PDF_CMD = 'df = vp_pdf_get_sentence(pdf_lst)\ndf'
+ /**
+ * PDF
+ */
+ class PDF extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.installButton = true;
+ this.config.importButton = true;
+ this.config.dataview = false;
+ this.config.size = { width: 500, height: 400 };
+ this.config.checkModules = ['pd', 'fitz', 'nltk', 'vp_pdf_get_sentence'];
+
+ this.state = {
+ vp_pdfFile: '',
+ vp_pdfReturn: '',
+ ...this.state
+ }
+
+ if (vpConfig.extensionType === 'lite') {
+ PDF_SHOW = PDF_SHOW.replace('!', '%');
+ PDF_INSTALL1 = PDF_INSTALL1.replace('!', '%');
+ PDF_INSTALL2 = PDF_INSTALL2.replace('!', '%');
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // click file navigation button
+ $(this.wrapSelector('#vp_openFileNavigationBtn')).on('click', function() {
+ let fileNavi = new FileNavigation({
+ type: 'open',
+ extensions: ['pdf'],
+ finish: function(filesPath, status, error) {
+ let pathList = filesPath.map(obj => obj.path);
+ let pathStr = "'" + pathList.join("', '") + "'";
+ $(that.wrapSelector('#vp_pdfFile')).val(pathStr);
+ }
+ });
+ fileNavi.open();
+ });
+ }
+
+ templateForBody() {
+ return pdfHtml;
+ }
+
+ loadState() {
+ $(this.wrapSelector('#vp_pdfFile')).val(this.state.vp_pdfFile);
+ $(this.wrapSelector('#vp_pdfReturn')).val(this.state.vp_pdfReturn);
+ }
+
+ render() {
+ super.render();
+
+ this.checkInstalled();
+ }
+
+ generateInstallCode() {
+ return [
+ PDF_INSTALL1,
+ PDF_INSTALL2
+ ];
+ }
+
+ generateImportCode() {
+ return [
+ PDF_IMPORT,
+ PDF_FUNC
+ ];
+ }
+
+ generateCode() {
+ var code = new com_String();
+
+ var filePath = $(this.wrapSelector('#vp_pdfFile')).val();
+ var allocateTo = $(this.wrapSelector('#vp_pdfReturn')).val();
+
+ // FIXME: change it after implementing filenavigation multi-select
+ code.appendFormatLine("pdf_lst = [{0}]", filePath);
+
+ if (allocateTo && allocateTo != '') {
+ code.appendFormat('{0} = ', allocateTo);
+ }
+ code.append('vp_pdf_get_sentence(pdf_lst)');
+
+ if (allocateTo && allocateTo != '') {
+ code.appendLine();
+ code.append(allocateTo);
+ }
+
+ return code.toString();
+ }
+
+ checkInstalled() {
+ var that = this;
+ // set state as 'Checking'
+ $(this.wrapSelector('.vp-pdf-install-btn')).text('Checking...');
+ // set disabled
+ if (!$(that.wrapSelector('.vp-pdf-install-btn')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-pdf-install-btn')).addClass('disabled');
+ }
+ var checking = true;
+
+ // check installed
+ vpKernel.execute(PDF_SHOW).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (!checking) {
+ return;
+ }
+ if (msg.content['text'].includes('not found')) {
+ checking = false;
+ $(that.wrapSelector('.vp-pdf-install-btn')).text('Install');
+ // set enabled
+ if ($(that.wrapSelector('.vp-pdf-install-btn')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-pdf-install-btn')).removeClass('disabled');
+ }
+ } else {
+ $(that.wrapSelector('.vp-pdf-install-btn')).text('Installed');
+ // set disabled
+ if (!$(that.wrapSelector('.vp-pdf-install-btn')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-pdf-install-btn')).addClass('disabled');
+ }
+ }
+ }).catch(function(msg) {
+ // if stderr occurs
+ checking = false;
+ $(that.wrapSelector('.vp-pdf-install-btn')).text('Install');
+ // set enabled
+ if ($(that.wrapSelector('.vp-pdf-install-btn')).hasClass('disabled')) {
+ $(that.wrapSelector('.vp-pdf-install-btn')).removeClass('disabled');
+ }
+ });
+ }
+
+ }
+
+ return PDF;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/PandasOption.js b/visualpython/js/m_apps/PandasOption.js
new file mode 100644
index 00000000..359de409
--- /dev/null
+++ b/visualpython/js/m_apps/PandasOption.js
@@ -0,0 +1,150 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : PandasOption.js
+ * Author : Black Logic
+ * Note : Pandas option
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 03. 28
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] PandasOption
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/pandasOption.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(poHTML, com_util, com_Const, com_String, PopupComponent) {
+
+ /**
+ * PandasOption
+ */
+ class PandasOption extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://pandas.pydata.org/docs/user_guide/options.html';
+
+ this.state = {
+ filter_warning: '',
+ min_rows: '',
+ max_rows: '',
+ max_columns: '',
+ max_colwidth: '',
+ expand_frame_repr: '',
+ precision: '',
+ chop_threshold: '',
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // setting popup - set default
+ $(this.wrapSelector('#resetDisplay')).on('change', function() {
+ let checked = $(this).prop('checked');
+
+ if (checked) {
+ // disable input
+ $(that.wrapSelector('.vp-po-option-item')).prop('disabled', true);
+ } else {
+ // enable input
+ $(that.wrapSelector('.vp-po-option-item')).prop('disabled', false);
+ }
+ });
+
+ // show all rows
+ $(this.wrapSelector('#showAllRows')).on('change', function() {
+ let checked = $(this).prop('checked');
+ if (checked) {
+ $(that.wrapSelector('#max_rows')).prop('disabled', true);
+ } else {
+ $(that.wrapSelector('#max_rows')).prop('disabled', false);
+ }
+ });
+
+ // show all columns
+ $(this.wrapSelector('#showAllColumns')).on('change', function() {
+ let checked = $(this).prop('checked');
+ if (checked) {
+ $(that.wrapSelector('#max_columns')).prop('disabled', true);
+ } else {
+ $(that.wrapSelector('#max_columns')).prop('disabled', false);
+ }
+ });
+
+ // setting popup - reset warning
+ $(this.wrapSelector('#resetWarning')).on('change', function() {
+ let checked = $(this).prop('checked');
+
+ if (checked) {
+ // disable input
+ $(that.wrapSelector('.vp-po-warning-item')).prop('disabled', true);
+ } else {
+ // enable input
+ $(that.wrapSelector('.vp-po-warning-item')).prop('disabled', false);
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(poHTML);
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+
+ }
+
+ generateCode() {
+ let that = this;
+ let code = [];
+
+ let resetDisplay = $(this.wrapSelector('#resetDisplay')).prop('checked');
+ let resetWarning = $(this.wrapSelector('#resetWarning')).prop('checked');
+
+ // warning options
+ if (resetWarning === true) {
+ code.push("import warnings\nwarnings.resetwarnings()");
+ } else{
+ if (that.state['filter_warning'] && that.state['filter_warning'] != '') {
+ code.push(com_util.formatString("import warnings\nwarnings.simplefilter(action='{0}', category=Warning)", that.state['filter_warning']));
+ }
+ }
+
+ // display options
+ if (resetDisplay === true) {
+ code.push("pd.reset_option('^display')");
+ } else {
+ let showAllRows = $(this.wrapSelector('#showAllRows')).prop('checked');
+ let showAllCols = $(this.wrapSelector('#showAllColumns')).prop('checked');
+ Object.keys(this.state).forEach((key) => {
+ if ((showAllRows === true && key === 'max_rows')
+ || (showAllCols === true && key === 'max_columns')) {
+ code.push(com_util.formatString("pd.set_option('display.{0}', {1})", key, 'None'));
+ } else if (key !== 'filter_warning' && that.state[key] && that.state[key] != '') {
+ code.push(com_util.formatString("pd.set_option('display.{0}', {1})", key, that.state[key]));
+ }
+ });
+ }
+
+ return code.join('\n');
+ }
+
+ }
+
+ return PandasOption;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Profiling.js b/visualpython/js/m_apps/Profiling.js
new file mode 100644
index 00000000..e1df8df3
--- /dev/null
+++ b/visualpython/js/m_apps/Profiling.js
@@ -0,0 +1,360 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Profiling.js
+ * Author : Black Logic
+ * Note : Apps > Profiling
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+/** DEPRECATED on v2.3.4
+ * - libraries.json
+ {
+ "id" : "apps_profiling",
+ "type" : "function",
+ "level": 1,
+ "name" : "Profiling",
+ "tag" : "PROFILING,PANDAS PROFILING,APPS",
+ "path" : "visualpython - apps - profiling",
+ "desc" : "Pandas Profiling",
+ "file" : "m_apps/Profiling",
+ "apps" : {
+ "color": 4,
+ "icon": "apps/apps_profiling.svg"
+ }
+ }
+ */
+
+//============================================================================
+// [CLASS] Profiling
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/profiling.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/profiling'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/FileNavigation'
+], function(proHTML, proCss, com_Const, com_String, com_interface, PopupComponent, SuggestInput, FileNavigation) {
+
+ const PROFILE_TYPE = {
+ NONE: -1,
+ GENERATE: 1
+ }
+
+ const LIST_MENU_ITEM = {
+ SHOW: 'show',
+ DELETE: 'delete',
+ SAVE: 'save'
+ }
+
+ /**
+ * Profiling
+ */
+ class Profiling extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.installButton = true;
+ this.config.importButton = true;
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.size = { width: 500, height: 500 };
+ this.config.checkModules = ['ProfileReport'];
+
+ this.selectedReport = '';
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // refresh df
+ $(this.wrapSelector('.vp-pf-df-refresh')).on('click', function() {
+ that.loadVariableList();
+ });
+
+ // click menu
+ $(this.wrapSelector('.vp-pf-menu-item')).on('click', function() {
+ // check required filled
+ if (that.checkRequiredOption() === false) {
+ return ;
+ }
+
+ var type = $(this).data('type');
+ var df = $(that.wrapSelector('#vp_pfVariable')).val();
+ var saveas = $(that.wrapSelector('#vp_pfReturn')).val();
+ if (saveas == '') {
+ saveas = '_vp_profile';
+ }
+ var title = $(that.wrapSelector('#vp_pfTitle')).val();
+ var code = new com_String();
+ switch(parseInt(type)) {
+ case PROFILE_TYPE.GENERATE:
+ code.appendFormatLine("{0} = ProfileReport({1}, title='{2}')", saveas, df, title);
+ code.append(saveas);
+ break;
+ }
+ that.checkAndRunModules(true).then(function() {
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Profiling');
+ that.loadReportList();
+ });
+ });
+ }
+
+ bindReportListEvent() {
+ let that = this;
+ // click list item menu
+ $(this.wrapSelector('.vp-pf-list-menu-item')).off('click');
+ $(this.wrapSelector('.vp-pf-list-menu-item')).on('click', function(evt) {
+ var menu = $(this).data('menu');
+ var itemTag = $(this).closest('.vp-pf-list-item');
+ var varName = $(itemTag).data('name');
+ var title = $(itemTag).data('title');
+
+ var code = new com_String();
+ switch(menu) {
+ case LIST_MENU_ITEM.SHOW:
+ code.appendFormat("{0}.to_notebook_iframe()", varName);
+ break;
+ case LIST_MENU_ITEM.DELETE:
+ code.appendFormat("del {0}", varName);
+ break;
+ case LIST_MENU_ITEM.SAVE:
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: ['html'],
+ fileName: 'report',
+ finish: function(filesPath, status, error) {
+ filesPath.forEach( fileObj => {
+ var fileName = fileObj.file;
+ var path = fileObj.path;
+ if (varName == '') {
+ varName = '_vp_profile';
+ }
+ var code = new com_String();
+ code.appendFormat("{0}.to_file('{1}')", varName, path);
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Profiling');
+
+ that.selectedReport = '';
+ });
+ }
+ });
+ fileNavi.open();
+ return;
+ default:
+ return;
+ }
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Profiling');
+ that.loadReportList();
+ });
+ }
+
+ templateForBody() {
+ return proHTML;
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariableList();
+ this.loadReportList();
+ this.checkInstalled();
+ }
+
+ generateInstallCode() {
+ return [
+ '!pip install pandas-profiling'
+ ];
+ }
+
+ generateImportCode() {
+ return [
+ 'from pandas_profiling import ProfileReport'
+ ];
+ }
+
+ generateCode() {
+ return "";
+ }
+
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ try {
+ let { result, msg } = resultObj;
+ var varList = JSON.parse(result);
+ // render variable list
+ // replace
+ $(that.wrapSelector('#vp_pfVariable')).replaceWith(function() {
+ return that.templateForVariableList(varList);
+ });
+ $(that.wrapSelector('#vp_pfVariable')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Profiling:', result);
+ }
+ });
+ }
+
+ templateForVariableList(varList) {
+ var beforeValue = $(this.wrapSelector('#vp_pfVariable')).val();
+ if (beforeValue == null) {
+ beforeValue = '';
+ }
+ // var tag = new com_String();
+ // tag.appendFormatLine('', 'vp_pfVariable');
+ // varList.forEach(vObj => {
+ // // varName, varType
+ // var label = vObj.varName;
+ // tag.appendFormatLine('{3} '
+ // , vObj.varName, vObj.varType
+ // , beforeValue == vObj.varName?'selected':''
+ // , label);
+ // });
+ // tag.appendLine(' '); // VP_VS_VARIABLES
+ // return tag.toString();
+
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID('vp_pfVariable');
+ variableInput.addClass('vp-pf-select');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.setNormalFilter(true);
+ variableInput.addAttribute('required', true);
+ variableInput.setValue(beforeValue);
+
+ return variableInput.toTagString();
+ }
+
+ /**
+ * Toggle check button state
+ * @param {String} mode install/checking/installed
+ */
+ toggleCheckState(mode='checking') {
+ let message = 'Checking...';
+ let disable = true;
+ switch (mode) {
+ case 'install':
+ message = 'Install';
+ disable = false;
+ break;
+ case 'installed':
+ message = 'Installed';
+ disable = true;
+ break;
+ case 'installing':
+ message = 'Installing';
+ disable = true;
+ break;
+ }
+ $(this.wrapSelector('.vp-pf-install-btn')).text(message);
+ if (disable) {
+ // set state as 'Checking'
+ // set disabled
+ if (!$(this.wrapSelector('.vp-pf-install-btn')).hasClass('disabled')) {
+ $(this.wrapSelector('.vp-pf-install-btn')).addClass('disabled');
+ }
+ } else {
+ // set enabled
+ $(this.wrapSelector('.vp-pf-install-btn')).removeClass('disabled');
+ }
+ }
+
+ checkInstalled() {
+ var that = this;
+ // set state as 'Checking'
+ this.toggleCheckState();
+ this.checking = true;
+
+ // check installed
+ vpKernel.execute('!pip show pandas-profiling').then(function(resultObj) {
+ let { result, msg } = resultObj;
+ if (!that.checking) {
+ return;
+ }
+ if (msg.content['text'].includes('not found')) {
+ that.toggleCheckState('install');
+ } else {
+ that.toggleCheckState('installed');
+ }
+ that.checking = false;
+ }).catch(function(err) {
+ that.toggleCheckState('install');
+ that.checking = false;
+ });
+ }
+
+ loadReportList() {
+ var that = this;
+ // load using kernel
+ vpKernel.getProfilingList().then(function(resultObj) {
+ try {
+ let { result } = resultObj;
+ var varList = JSON.parse(result);
+ // render variable list
+ // replace
+ $(that.wrapSelector('.vp-pf-list-box')).replaceWith(function() {
+ return that.renderReportList(varList);
+ });
+
+ that.bindReportListEvent();
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Profiling:', result);
+ // console.log(ex);
+ }
+ });
+ }
+
+ renderReportList = function(reportList=[]) {
+ var page = new com_String();
+ page.appendFormatLine('', 'vp-pf-list-box');
+ page.appendFormatLine('
', 'vp-pf-list-header');
+ page.appendFormatLine('
{1}
', 'vp-pf-list-header-item', 'Allocated to');
+ page.appendFormatLine('
{1}
', 'vp-pf-list-header-item', 'Report Title');
+ page.appendFormatLine('
{1}
', 'vp-pf-list-header-item', '');
+ page.appendLine('
');
+ page.appendFormatLine('
', 'vp-apiblock-scrollbar');
+ page.appendFormatLine('
', 'vp-pf-list-body', 'vp-apiblock-scrollbar');
+ reportList.forEach((report, idx) => {
+ var { varName, title } = report;
+ page.appendFormatLine('
', 'vp-pf-list-item', varName, title);
+ page.appendFormatLine('
{0}
', varName);
+ page.appendFormatLine('
{0}
', title);
+ // button box
+ page.appendFormatLine('
', 'vp-pf-list-button-box');
+ // LAB: img to url
+ // page.appendFormatLine('
'
+ // , 'vp-pf-list-menu-item', LIST_MENU_ITEM.SHOW, 'Show report', com_Const.IMAGE_PATH + 'snippets/run.svg');
+ // page.appendFormatLine('
'
+ // , 'vp-pf-list-menu-item', LIST_MENU_ITEM.DELETE, 'Delete report', com_Const.IMAGE_PATH + 'delete.svg');
+ // page.appendFormatLine('
'
+ // , 'vp-pf-list-menu-item', LIST_MENU_ITEM.SAVE, 'Save report', com_Const.IMAGE_PATH + 'snippets/export.svg');
+ page.appendFormatLine('
'
+ , 'vp-pf-list-menu-item', 'vp-icon-run', LIST_MENU_ITEM.SHOW, 'Show report');
+ page.appendFormatLine('
'
+ , 'vp-pf-list-menu-item', 'vp-icon-delete', LIST_MENU_ITEM.DELETE, 'Delete report');
+ page.appendFormatLine('
'
+ , 'vp-pf-list-menu-item', 'vp-icon-export', LIST_MENU_ITEM.SAVE, 'Save report');
+ page.appendLine('
');
+ page.appendLine('
');
+ });
+ page.appendLine('
'); // VP_PF_LIST_BODY
+ page.appendLine('
');
+ page.appendLine('
'); // 'vp-pf-list-box'
+ return page.toString();
+ }
+
+ }
+
+ return Profiling;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Reshape.js b/visualpython/js/m_apps/Reshape.js
new file mode 100644
index 00000000..995ddd1e
--- /dev/null
+++ b/visualpython/js/m_apps/Reshape.js
@@ -0,0 +1,632 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Reshape.js
+ * Author : Black Logic
+ * Note : Apps > Reshape
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Reshape
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/reshape.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/reshape'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/MultiSelector'
+], function(reshapeHtml, reshapeCss, com_String, com_util, PopupComponent, SuggestInput, MultiSelector) {
+
+ /**
+ * Reshape
+ */
+ class Reshape extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+
+ this.state = {
+ variable: '',
+ type: 'pivot',
+ resetIndex: false,
+ withoutColumn: 'True',
+ pivot: {
+ index: [],
+ columns: [],
+ values: [],
+ aggfunc: []
+ },
+ melt: {
+ idVars: [],
+ ValueVars: [],
+ varName: '',
+ varNameText: true,
+ valueName: '',
+ valueNameText: true
+ },
+ userOption: '',
+ allocateTo: '',
+ ...this.state
+ }
+ this.popup = {
+ type: '',
+ targetSelector: '',
+ ColSelector: undefined
+ }
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('#vp_rsDataframe'));
+ $(document).off('click', this.wrapSelector('.vp-rs-df-refresh'));
+ $(document).off('change', this.wrapSelector('#vp_rsType'));
+ $(document).off('change', this.wrapSelector('#vp_rsIndex'));
+ $(document).off('click', this.wrapSelector('#vp_rsIndex'));
+ $(document).off('change', this.wrapSelector('#vp_rsColumns'));
+ $(document).off('click', this.wrapSelector('#vp_rsColumns'));
+ $(document).off('change', this.wrapSelector('#vp_rsValues'));
+ $(document).off('click', this.wrapSelector('#vp_rsValues'));
+ $(document).off('change', this.wrapSelector('#vp_rsIdVars'));
+ $(document).off('click', this.wrapSelector('#vp_rsIdVars'));
+ $(document).off('change', this.wrapSelector('#vp_rsValueVars'));
+ $(document).off('click', this.wrapSelector('#vp_rsValueVars'));
+ $(document).off('change', this.wrapSelector('#vp_rsUserOption'));
+ $(document).off('change', this.wrapSelector('#vp_rsAllocateTo'));
+ $(document).off('change', this.wrapSelector('#vp_rsResetIndex'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+ //====================================================================
+ // User operation Events
+ //====================================================================
+ // variable change event
+ $(document).on('change', this.wrapSelector('#vp_rsDataframe'), function() {
+ // if variable changed
+ var newVal = $(this).val();
+ if (newVal != that.state.variable) {
+ that.state.variable = newVal;
+ // initial child values
+ that._resetColumnSelector(that.wrapSelector('#vp_rsIndex'));
+ that._resetColumnSelector(that.wrapSelector('#vp_rsColumns'));
+ that._resetColumnSelector(that.wrapSelector('#vp_rsValues'));
+
+ that._resetColumnSelector(that.wrapSelector('#vp_rsIdVars'));
+ that._resetColumnSelector(that.wrapSelector('#vp_rsValueVars'));
+
+ that.state.pivot = {
+ index: [], columns: [], values: [], aggfunc: []
+ };
+ that.state.melt = {
+ idVars: [], valueVars: []
+ };
+ }
+ });
+
+ // variable refresh event
+ $(document).on('click', this.wrapSelector('.vp-rs-df-refresh'), function() {
+ that.loadVariableList();
+ });
+
+ // on change event
+ $(document).on('change', this.wrapSelector('#vp_rsType'), function(event) {
+ var type = $(this).val();
+ that.state.type = type;
+ // change visibility
+ $(that.wrapSelector('.vp-rs-type-box')).hide();
+ $(that.wrapSelector('.vp-rs-type-box.' + type)).show();
+
+ // clear user option
+ $(that.wrapSelector('#vp_rsUserOption')).val('');
+ that.state.userOption = '';
+ });
+
+ // index change event
+ $(document).on('change', this.wrapSelector('#vp_rsIndex'), function(event) {
+ var colList = event.dataList;
+ that.state.pivot.index = colList;
+ });
+
+ // index select button event
+ $(document).on('click', this.wrapSelector('#vp_rsIndex'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = [ ...that.state.pivot.columns, ...that.state.pivot.values ].map(obj => obj.code);
+ that.openColumnSelector(targetVariable, $(that.wrapSelector('#vp_rsIndex')), 'Select columns', excludeList);
+ });
+
+ // columns change event
+ $(document).on('change', this.wrapSelector('#vp_rsColumns'), function(event) {
+ var colList = event.dataList;
+ that.state.pivot.columns = colList;
+ });
+
+ // columns select button event
+ $(document).on('click', this.wrapSelector('#vp_rsColumns'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = [ ...that.state.pivot.index, ...that.state.pivot.values ].map(obj => obj.code);
+ that.openColumnSelector(targetVariable, $(that.wrapSelector('#vp_rsColumns')), 'Select columns', excludeList);
+ });
+
+ // values change event
+ $(document).on('change', this.wrapSelector('#vp_rsValues'), function(event) {
+ var colList = event.dataList;
+ that.state.pivot.values = colList;
+ });
+
+ // values select button event
+ $(document).on('click', this.wrapSelector('#vp_rsValues'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = [ ...that.state.pivot.index, ...that.state.pivot.columns ].map(obj => obj.code);
+ that.openColumnSelector(targetVariable, $(that.wrapSelector('#vp_rsValues')), 'Select columns', excludeList);
+ });
+
+ // aggfunc change event
+ $(document).on('change', this.wrapSelector('#vp_rsAggfunc'), function(event) {
+ var colList = event.dataList;
+ that.state.pivot.aggfunc = colList;
+ });
+
+ // aggfunc select button event
+ $(document).on('click', this.wrapSelector('#vp_rsAggfunc'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = that.state.pivot.aggfunc.map(obj => obj.code);
+ that.openMethodSelector(targetVariable, $(that.wrapSelector('#vp_rsAggfunc')), 'Select columns', excludeList);
+ });
+
+ // id vars change event
+ $(document).on('change', this.wrapSelector('#vp_rsIdVars'), function(event) {
+ var colList = event.dataList;
+ that.state.melt.idVars = colList;
+ });
+
+ // id vars select button event
+ $(document).on('click', this.wrapSelector('#vp_rsIdVars'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = that.state.melt.valueVars.map(obj => obj.code);
+ that.openColumnSelector(targetVariable, $(that.wrapSelector('#vp_rsIdVars')), 'Select columns', excludeList);
+ });
+
+ // value vars change event
+ $(document).on('change', this.wrapSelector('#vp_rsValueVars'), function(event) {
+ var colList = event.dataList;
+ that.state.melt.valueVars = colList;
+ });
+
+ // value vars select button event
+ $(document).on('click', this.wrapSelector('#vp_rsValueVars'), function() {
+ var targetVariable = [ that.state.variable ];
+ var excludeList = that.state.melt.idVars.map(obj => obj.code);
+ that.openColumnSelector(targetVariable, $(that.wrapSelector('#vp_rsValueVars')), 'Select columns', excludeList);
+ });
+
+ // userOption event
+ $(document).on('change', this.wrapSelector('#vp_rsUserOption'), function() {
+ that.state.userOption = $(this).val();
+ });
+
+ // allocateTo event
+ $(document).on('change', this.wrapSelector('#vp_rsAllocateTo'), function() {
+ that.state.allocateTo = $(this).val();
+ });
+
+ // reset index checkbox event
+ $(document).on('change', this.wrapSelector('#vp_rsResetIndex'), function() {
+ let isChecked = $(this).prop('checked');
+ $(that.wrapSelector('#vp_rsWithoutColumn')).prop('disabled', !isChecked);
+ that.state.resetIndex = isChecked;
+ });
+
+ // with/without column select event
+ $(this.wrapSelector('#vp_rsWithoutColumn')).on('change', function() {
+ that.state.withoutColumn = $(this).val();
+ });
+
+ }
+
+ templateForBody() {
+ return reshapeHtml
+ }
+
+ templateForDataView() {
+ return '';
+ }
+
+ renderDataView() {
+ super.renderDataView();
+
+ this.loadDataPage();
+ $(this.wrapSelector('.vp-popup-dataview-box')).css('height', '300px');
+ }
+
+ renderDataPage(renderedText, isHtml = true) {
+ var tag = new com_String();
+ tag.appendFormatLine('');
+ $(this.wrapSelector('.vp-popup-dataview-box')).html(tag.toString());
+ }
+
+ loadDataPage() {
+ var that = this;
+ var code = this.generateCode();
+ // if not, get output of all data in selected pandasObject
+ vpKernel.execute(code).then(function(resultObj) {
+ let { msg } = resultObj;
+ if (msg.content.data) {
+ var htmlText = String(msg.content.data["text/html"]);
+ var codeText = String(msg.content.data["text/plain"]);
+ if (htmlText != 'undefined') {
+ that.renderDataPage(htmlText);
+ } else if (codeText != 'undefined') {
+ // plain text as code
+ that.renderDataPage(codeText, false);
+ } else {
+ that.renderDataPage('');
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ that.renderDataPage(errorContent);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ that.renderDataPage(errorContent);
+ });
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariableList();
+
+ var {
+ variable, type, pivot, melt, userOption, allocateTo, resetIndex, withoutColumn
+ } = this.state;
+
+ $(this.wrapSelector('#vp_rsDataframe')).val(variable);
+ $(this.wrapSelector('#vp_rsType')).val(type);
+ $(this.wrapSelector('#vp_rsType')).trigger('change');
+
+ // pivot
+ this._loadColumnSelectorInput(this.wrapSelector('#vp_rsIndex'), pivot.index);
+ this._loadColumnSelectorInput(this.wrapSelector('#vp_rsColumns'), pivot.columns);
+ this._loadColumnSelectorInput(this.wrapSelector('#vp_rsValues'), pivot.values);
+
+ // melt
+ this._loadColumnSelectorInput(this.wrapSelector('#vp_rsIdVars'), melt.idVars);
+ this._loadColumnSelectorInput(this.wrapSelector('#vp_rsValueVars'), melt.valueVars);
+ $(this.wrapSelector('#vp_rsVarName')).val(melt.varName);
+ $(this.wrapSelector('#varNameText')).prop('checked', melt.varNameText);
+ $(this.wrapSelector('#vp_rsValueName')).val(melt.valueName);
+ $(this.wrapSelector('#valueNameText')).prop('checked', melt.valueNameText);
+
+ // userOption
+ $(this.wrapSelector('#vp_rsUserOption')).val(userOption);
+
+ // allocateTo
+ $(this.wrapSelector('#vp_rsAllocateTo')).val(allocateTo);
+ $(this.wrapSelector('#vp_rsResetIndex')).prop('checked', resetIndex);
+ $(this.wrapSelector('#vp_rsWithoutColumn')).val(withoutColumn);
+ }
+
+ /**
+ * Render variable list (for dataframe)
+ * @param {Array} varList
+ * @param {string} defaultValue previous value
+ */
+ renderVariableList(id, varList, defaultValue='') {
+ // var tag = new com_String();
+ // tag.appendFormatLine('', id);
+ // varList.forEach(vObj => {
+ // // varName, varType
+ // var label = vObj.varName;
+ // tag.appendFormatLine('{3} '
+ // , vObj.varName, vObj.varType
+ // , defaultValue == vObj.varName?'selected':''
+ // , label);
+ // });
+ // tag.appendLine(' '); // VP_VS_VARIABLES
+ // $(this.wrapSelector('#' + id)).replaceWith(function() {
+ // return tag.toString();
+ // });
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID(id);
+ variableInput.addClass('vp-state');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.setNormalFilter(true);
+ variableInput.setValue(defaultValue);
+ variableInput.addAttribute('required', true);
+ $(this.wrapSelector('#' + id)).replaceWith(function() {
+ return variableInput.toTagString();
+ });
+ }
+
+ /**
+ * Render column selector using ColumnSelector module
+ * @param {Array} previousList previous selected columns
+ * @param {Array} excludeList columns to exclude
+ */
+ renderColumnSelector(targetVariable, previousList, excludeList) {
+ this.popup.ColSelector = new MultiSelector(
+ this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'columns', parent: targetVariable, selectedList: previousList, excludeList: excludeList }
+ );
+ }
+
+ /**
+ * Render method selector using MultiSelector module
+ * @param {Array} previousList previous selected methods
+ * @param {Array} excludeList methods to exclude
+ */
+ renderMethodSelector(targetVariable, previousList, excludeList) {
+ let methodList = [
+ { value: 'count', code: "'count'" },
+ { value: 'first', code: "'first'" },
+ { value: 'last', code: "'last'" },
+ { value: 'size', code: "'size'" },
+ { value: 'std', code: "'std'" },
+ { value: 'sum', code: "'sum'" },
+ { value: 'max', code: "'max'" },
+ { value: 'mean', code: "'mean'" },
+ { value: 'median', code: "'median'" },
+ { value: 'min', code: "'min'" },
+ { value: 'quantile', code: "'quantile'" },
+ ];
+
+ this.popup.ColSelector = new MultiSelector(
+ this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'data', parent: targetVariable, dataList: methodList, selectedList: previousList, excludeList: excludeList }
+ );
+ }
+
+ /**
+ * Load variable list (dataframe)
+ */
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var varList = JSON.parse(result);
+ // render variable list
+ // get prevvalue
+ var prevValue = that.state.variable;
+ // replace
+ that.renderVariableList('vp_rsDataframe', varList, prevValue);
+ $(that.wrapSelector('#vp_rsDataframe')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Reshape:', result);
+ }
+ });
+ }
+
+ generateCode() {
+ var code = new com_String();
+ var { variable, type, userOption, allocateTo, resetIndex, withoutColumn, pivot, melt } = this.state;
+
+ //====================================================================
+ // Allocation
+ //====================================================================
+ if (allocateTo && allocateTo != '') {
+ code.appendFormat('{0} = ', allocateTo);
+ }
+
+ //====================================================================
+ // Dataframe variables
+ //====================================================================
+ code.appendFormat('{0}.{1}(', variable, type);
+
+ var options = [];
+ if (type == 'pivot') {
+ //================================================================
+ // pivot
+ //================================================================
+ // index (optional)
+ if (pivot.index && pivot.index.length > 0) {
+ if (pivot.index.length == 1) {
+ options.push(com_util.formatString("index={0}", pivot.index[0].code));
+ } else {
+ options.push(com_util.formatString("index=[{0}]", pivot.index.map(col => col.code).join(',')));
+ }
+ }
+
+ // columns
+ if (pivot.columns && pivot.columns.length > 0) {
+ if (pivot.columns.length == 1) {
+ options.push(com_util.formatString("columns={0}", pivot.columns[0].code));
+ } else {
+ options.push(com_util.formatString("columns=[{0}]", pivot.columns.map(col => col.code).join(',')));
+ }
+ }
+
+ // values (optional)
+ if (pivot.values && pivot.values.length > 0) {
+ if (pivot.values.length == 1) {
+ options.push(com_util.formatString("values={0}", pivot.values[0].code));
+ } else {
+ options.push(com_util.formatString("values=[{0}]", pivot.values.map(col => col.code).join(',')));
+ }
+ }
+
+ } else if (type == 'pivot_table') {
+ //================================================================
+ // pivot_table
+ //================================================================
+ // index (optional)
+ if (pivot.index && pivot.index.length > 0) {
+ if (pivot.index.length == 1) {
+ options.push(com_util.formatString("index={0}", pivot.index[0].code));
+ } else {
+ options.push(com_util.formatString("index=[{0}]", pivot.index.map(col => col.code).join(',')));
+ }
+ }
+
+ // columns
+ if (pivot.columns && pivot.columns.length > 0) {
+ if (pivot.columns.length == 1) {
+ options.push(com_util.formatString("columns={0}", pivot.columns[0].code));
+ } else {
+ options.push(com_util.formatString("columns=[{0}]", pivot.columns.map(col => col.code).join(',')));
+ }
+ }
+
+ // values (optional)
+ if (pivot.values && pivot.values.length > 0) {
+ if (pivot.values.length == 1) {
+ options.push(com_util.formatString("values={0}", pivot.values[0].code));
+ } else {
+ options.push(com_util.formatString("values=[{0}]", pivot.values.map(col => col.code).join(',')));
+ }
+ }
+
+ // aggfunc
+ if (pivot.aggfunc && pivot.aggfunc.length > 0) {
+ if (pivot.aggfunc.length == 1) {
+ options.push(com_util.formatString("aggfunc={0}", pivot.aggfunc[0].code));
+ } else {
+ options.push(com_util.formatString("aggfunc=[{0}]", pivot.aggfunc.map(col => col.code).join(',')));
+ }
+ }
+ } else {
+ //================================================================
+ // melt
+ //================================================================
+ // id vars (optional)
+ if (melt.idVars && melt.idVars.length > 0) {
+ if (melt.idVars.length == 1) {
+ options.push(com_util.formatString("id_vars={0}", melt.idVars[0].code));
+ } else {
+ options.push(com_util.formatString("id_vars=[{0}]", melt.idVars.map(col => col.code).join(',')));
+ }
+ }
+
+ // value vars (optional)
+ if (melt.valueVars && melt.valueVars.length > 0) {
+ if (melt.valueVars.length == 1) {
+ options.push(com_util.formatString("value_vars={0}", melt.valueVars[0].code));
+ } else {
+ options.push(com_util.formatString("value_vars=[{0}]", melt.valueVars.map(col => col.code).join(',')));
+ }
+ }
+
+ // var name (optional)
+ if (melt.varName) {
+ options.push(com_util.formatString("var_name={0}", com_util.convertToStr(melt.varName, melt.varNameText)));
+ }
+
+ // value name (optional)
+ if (melt.valueName) {
+ options.push(com_util.formatString("value_name={0}", com_util.convertToStr(melt.valueName, melt.valueNameText)));
+ }
+ }
+
+ // userOption
+ if (userOption && userOption != '') {
+ options.push(userOption);
+ }
+
+ code.appendFormat('{0})', options.join(', '));
+
+ //====================================================================
+ // Reset index
+ //====================================================================
+ if (resetIndex) {
+ if (withoutColumn === 'True') {
+ code.append('.reset_index(drop=True)');
+ } else {
+ code.append('.reset_index()');
+ }
+ }
+
+ if (allocateTo && allocateTo != '') {
+ code.appendLine();
+ code.append(allocateTo);
+ }
+
+ return code.toString();
+ }
+
+ loadState() {
+ super.loadState();
+ }
+
+ _resetColumnSelector(target) {
+ $(target).val('');
+ $(target).data('list', []);
+ }
+
+ _loadColumnSelectorInput(tag, colList) {
+ let colStr = colList? colList.map(col => col.code).join(','): '';
+ $(tag).val(colStr);
+ $(tag).data('list', colList)
+ }
+
+ /**
+ * Open Inner popup page for column selection
+ * @param {Object} targetSelector
+ * @param {string} title
+ * @param {Array} excludeList
+ */
+ openColumnSelector(targetVariable, targetSelector, title='Select columns', excludeList=[]) {
+ this.popup.targetVariable = targetVariable;
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(col => col.code)
+ }
+ this.renderColumnSelector(targetVariable, previousList, excludeList);
+
+ // set title
+ this.openInnerPopup(title);
+ }
+
+ openMethodSelector(targetVariable, targetSelector, title='Select methods', excludeList=[]) {
+ this.popup.targetVariable = targetVariable;
+ this.popup.targetSelector = targetSelector;
+ var previousList = this.popup.targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(col => col.code)
+ }
+ this.renderMethodSelector(targetVariable, previousList, excludeList);
+
+ // set title
+ this.openInnerPopup(title);
+ }
+
+ handleInnerOk() {
+ // ok input popup
+ var dataList = this.popup.ColSelector.getDataList();
+
+ $(this.popup.targetSelector).val(dataList.map(col => { return col.code }).join(','));
+ $(this.popup.targetSelector).data('list', dataList);
+ $(this.popup.targetSelector).trigger({ type: 'change', dataList: dataList });
+ this.closeInnerPopup();
+ }
+
+ }
+
+ return Reshape;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/SampleApp.js b/visualpython/js/m_apps/SampleApp.js
new file mode 100644
index 00000000..b7988042
--- /dev/null
+++ b/visualpython/js/m_apps/SampleApp.js
@@ -0,0 +1,76 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : SampleApp.js
+ * Author : Black Logic
+ * Note : Sample app
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] SampleApp
+//============================================================================
+define([
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector'
+], function(com_util, com_Const, com_String, PopupComponent, DataSelector) {
+
+ /**
+ * SampleApp
+ */
+ class SampleApp extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // $(this.wrapSelector('#sample')).on('click', function() {
+ // let dataSelector = new DataSelector({
+ // type: 'data',
+ // target: $(that.wrapSelector('#sample')),
+ // finish: function() {
+
+ // }
+ // });
+ // dataSelector.open();
+ // });
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ return `This is sample.
+ `;
+ }
+
+ render() {
+ super.render();
+
+ let dataSelector = new DataSelector({
+ type: 'data',
+ pageThis: this,
+ id: 'sample',
+ finish: function() {
+ ;
+ }
+ });
+ $(this.wrapSelector('#sample')).replaceWith(dataSelector.toTagString());
+ }
+
+ generateCode() {
+ return "print('sample code')";
+ }
+
+ }
+
+ return SampleApp;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Snippets.js b/visualpython/js/m_apps/Snippets.js
new file mode 100644
index 00000000..1fecfce7
--- /dev/null
+++ b/visualpython/js/m_apps/Snippets.js
@@ -0,0 +1,711 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Snippets.js
+ * Author : Black Logic
+ * Note : Apps > Snippets
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Snippets
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/snippets.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/snippets'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/js/com/component/LoadingSpinner'
+], function(snHtml, snCss, com_util, com_Const, com_String, com_interface, PopupComponent, FileNavigation, LoadingSpinner) {
+
+ /**
+ * Snippets
+ */
+ class Snippets extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.sizeLevel = 3;
+
+ this.state = {
+ vp_userCode: '',
+ ...this.state
+ }
+
+ this.codemirrorList = {};
+ this.importedList = [];
+ this.title_no = 0;
+
+ // double click setter
+ this.clicked = 0;
+
+ this.defaultSnippets = {
+ 'default import': [
+ 'import numpy as np',
+ 'import pandas as pd',
+ 'import matplotlib.pyplot as plt',
+ '%matplotlib inline',
+ 'import seaborn as sns',
+ 'import plotly.express as px'
+ ],
+ 'matplotlib customizing': [
+ 'import matplotlib.pyplot as plt',
+ '%matplotlib inline',
+ '',
+ "plt.rc('figure', figsize=(12, 8))",
+ '',
+ 'from matplotlib import rcParams',
+ "rcParams['font.family'] = 'New Gulim'",
+ "rcParams['font.size'] = 10",
+ "rcParams['axes.unicode_minus'] = False"
+ ],
+ 'as_float': [
+ 'def as_float(x):',
+ ' """',
+ " usage: df['col'] = df['col'].apply(as_float)",
+ ' """',
+ ' if not isinstance(x, str):',
+ ' return 0.0',
+ ' else:',
+ ' try:',
+ ' result = float(x)',
+ ' return result',
+ ' except ValueError:',
+ ' return 0.0'
+ ],
+ 'as_int': [
+ 'def as_int(x):',
+ ' """',
+ " usage: df['col'] = df['col'].apply(as_int)",
+ ' """',
+ ' if not isinstance(x, str):',
+ ' return 0',
+ ' else:',
+ ' try:',
+ ' result = int(x)',
+ ' return result',
+ ' except ValueError:',
+ ' return 0.0'
+ ]
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // menu popup
+ $(this.wrapSelector('.vp-sn-menu')).on('click', function(evt) {
+ evt.stopPropagation();
+ $(that.wrapSelector('.vp-sn-menu-box')).toggle();
+ });
+
+ // sort menu popup
+ $(this.wrapSelector('.vp-sn-sort')).on('click', function(evt) {
+ evt.stopPropagation();
+ $(that.wrapSelector('.vp-sn-sort-menu-box')).toggle();
+ });
+
+ // menu click
+ $(this.wrapSelector('.vp-sn-menu-item')).on('click', async function(evt) {
+ var menu = $(this).data('menu');
+ if (menu == 'import') {
+ let fileNavi = new FileNavigation({
+ type: 'open',
+ extensions: ['sn'],
+ finish: function(filesPath, status, error) {
+ // import sn file
+ filesPath.forEach(fileObj => {
+ var fileName = fileObj.file;
+ var selectedPath = fileObj.path;
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ vpKernel.readFile(selectedPath).then(function(resultObj) {
+ try {
+ var snippetData = JSON.parse(resultObj.result);
+ var timestamp = new Date().getTime();
+
+ var keys = Object.keys(snippetData);
+ var importKeys = [];
+ var newSnippet = {};
+ keys.forEach(key => {
+ var importKey = key;
+ var importNo = 1;
+ var titleList = Object.keys(that.codemirrorList);
+ // set duplicate title
+ while(titleList.includes(importKey)) {
+ importKey = key + '_imported' + importNo;
+ importNo += 1;
+ }
+ newSnippet = { ...newSnippet, [importKey]: { code: snippetData[key], timestamp: timestamp } };
+
+ importKeys.push(importKey);
+ });
+ vpConfig.setData(newSnippet).then(function() {
+ that.importedList = [ ...importKeys ];
+ that.loadUdfList();
+ com_util.renderSuccessMessage(fileName + ' imported ');
+ });
+ } catch (ex) {
+ com_util.renderAlertModal('Not applicable file contents with vp format! (JSON)');
+ }
+ }).catch(function(err) {
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+ });
+ } else {
+ fetch(selectedPath).then(function(file) {
+ if (file.status != 200) {
+ alert("The file format is not valid.");
+ return;
+ }
+
+ file.text().then(function(data) {
+ var snippetData = JSON.parse(data);
+ var timestamp = new Date().getTime();
+
+ var keys = Object.keys(snippetData);
+ var importKeys = [];
+ keys.forEach(key => {
+ var importKey = key;
+ var importNo = 1;
+ var titleList = Object.keys(that.codemirrorList);
+ // set duplicate title
+ while(titleList.includes(importKey)) {
+ importKey = key + '_imported' + importNo;
+ importNo += 1;
+ }
+ var newSnippet = { [importKey]: { code: snippetData[key], timestamp: timestamp } };
+ vpConfig.setData(newSnippet);
+
+ importKeys.push(importKey);
+ });
+ that.importedList = [ ...importKeys ];
+
+ that.loadUdfList();
+
+ com_util.renderSuccessMessage(fileName + ' imported ');
+ });
+ });
+ }
+
+ });
+
+ }
+ });
+ fileNavi.open();
+ } else if (menu == 'export') {
+ // set as export mode
+ $(that.wrapSelector()).addClass('vp-sn-export-mode');
+
+ // check all
+ $(that.wrapSelector('.vp-sn-check-all')).prop('checked', true);
+ $(that.wrapSelector('.vp-sn-item-check')).prop('checked', true);
+ } else if (menu == 'default-snippets') {
+ // import default snippets
+ let loadingSpinner = new LoadingSpinner($(that.wrapSelector('.vp-sn-table')));
+ var timestamp = new Date().getTime();
+ var keys = Object.keys(that.defaultSnippets);
+ var importKeys = [];
+ var newSnippet = {};
+ keys.forEach(key => {
+ var importKey = key;
+ var importNo = 1;
+ var titleList = Object.keys(that.codemirrorList);
+ // set duplicate title
+ while(titleList.includes(importKey)) {
+ importKey = key + '_imported' + importNo;
+ importNo += 1;
+ }
+ var code = that.defaultSnippets[key].join('\n');
+ newSnippet = { ...newSnippet, [importKey]: { code: code, timestamp: timestamp } };
+ importKeys.push(importKey);
+ });
+
+ vpConfig.setData(newSnippet).then(function() {
+ that.importedList = [ ...importKeys ];
+ that.loadUdfList();
+ com_util.renderSuccessMessage('Default snippets imported');
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }
+ $(that.wrapSelector('.vp-sn-menu-box')).hide();
+ evt.stopPropagation();
+ });
+
+ // search item
+ $(this.wrapSelector('.vp-sn-search')).on('change', function(evt) {
+ var value = $(this).val();
+ if (value != '') {
+ $(that.wrapSelector('.vp-sn-item')).hide();
+ $(that.wrapSelector('.vp-sn-item')).filter(function() {
+ return $(this).data('title').search(value) >= 0;
+ }).show();
+ } else {
+ $(that.wrapSelector('.vp-sn-item')).show();
+ }
+ });
+
+ // sort item
+ $(this.wrapSelector('.vp-sn-sort-menu-item')).on('click', function() {
+ var menu = $(this).data('menu');
+ if (menu == 'name') {
+ // sort by name
+ $(that.wrapSelector('.vp-sn-item')).sort(function(a, b) {
+ var titleA = $(a).data('title');
+ var titleB = $(b).data('title');
+ return titleA > titleB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-sn-table')))
+ } else if (menu == 'date') {
+ // sort by date
+ $(that.wrapSelector('.vp-sn-item')).sort(function(a, b) {
+ var timeA = $(a).data('timestamp');
+ var timeB = $(b).data('timestamp');
+ return timeA < timeB ? 1 : -1
+ }).appendTo($(that.wrapSelector('.vp-sn-table')))
+ }
+ });
+
+ // create item
+ $(this.wrapSelector('.vp-sn-create')).on('click', function() {
+ var titleList = Object.keys(that.codemirrorList);
+ var newTitle = 'untitled' + that.title_no;
+ while(titleList.includes(newTitle)) {
+ that.title_no += 1;
+ newTitle = 'untitled' + that.title_no;
+ }
+
+ var timestamp = new Date().getTime();
+ var newItem = $(that.renderSnippetItem(newTitle, '', timestamp));
+ $(that.wrapSelector('.vp-sn-table')).append(newItem);
+ // bind snippet item
+ that.bindSnippetItem();
+
+ // save it
+ var newSnippet = { [newTitle]: { code: '', timestamp: timestamp } };
+ vpConfig.setData(newSnippet);
+
+ var tag = $(that.wrapSelector('.vp-sn-item[data-title="' + newTitle + '"] textarea'));
+ that.bindCodeMirror(newTitle, tag[0]);
+ $(newItem).find('.vp-sn-indicator').trigger('click');
+
+ that.title_no += 1;
+ });
+
+
+ //////////////// export mode ///////////////////////
+ // check all
+ $(this.wrapSelector('.vp-sn-check-all')).on('change', function() {
+ var checked = $(this).prop('checked');
+ $(that.wrapSelector('.vp-sn-item-check')).prop('checked', checked);
+ });
+
+ // export snippets
+ $(this.wrapSelector('.vp-sn-export')).on('click', async function() {
+ var menu = $(this).data('menu');
+ if (menu == 'cancel') {
+ // cancel
+ // return to default mode
+ $(that.wrapSelector()).removeClass('vp-sn-export-mode');
+ } else if (menu == 'export') {
+ var checked = $(that.wrapSelector('.vp-sn-item-check:checked'));
+ if (checked.length <= 0) {
+ return ;
+ }
+
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: ['sn'],
+ finish: function(filesPath, status, error) {
+ let fileObj = filesPath[0];
+ var fileName = fileObj.file;
+ var selectedPath = fileObj.path;
+
+ // get checked snippets
+ var snippets = {};
+ $(that.wrapSelector('.vp-sn-item-check:checked')).each((idx, tag) => {
+ var title = $(tag).closest('.vp-sn-item').data('title');
+ var codemirror = that.codemirrorList[title];
+ codemirror.save();
+ var code = codemirror.getValue();
+ snippets[title] = code;
+ });
+
+ // make as file
+ var fileData = JSON.stringify(snippets);
+ vpKernel.saveFile(fileName, selectedPath, fileData);
+
+ // return to default mode
+ $(that.wrapSelector()).removeClass('vp-sn-export-mode');
+ }
+ });
+ fileNavi.open();
+ }
+
+ });
+ }
+
+ bindSnippetItem() {
+ let that = this;
+ // item header click (select item) & double click (edit title)
+ $(this.wrapSelector('.vp-sn-item-header')).off('click');
+ $(this.wrapSelector('.vp-sn-item-header')).on('click', function(evt) {
+ // stop propagation on checkbox
+ if ($(evt.target).hasClass('vp-sn-item-check')) {
+ return;
+ }
+
+ var thisHeader = this;
+ that.clicked++;
+ if (that.clicked == 1) {
+ setTimeout(function(){
+ let selected = $(thisHeader).hasClass('selected');
+ if(selected || that.clicked > 1) {
+ // double click or clicked after selection
+ // enable input
+ $(thisHeader).find('.vp-sn-item-title').prop('readonly', false);
+ $(thisHeader).find('.vp-sn-item-title').select();
+ $(thisHeader).find('.vp-sn-item-title').focus();
+
+ }
+ // single click
+ // select item
+ // remove selection
+ $(that.wrapSelector('.vp-sn-item-header')).removeClass('selected');
+ // select item
+ $(thisHeader).addClass('selected');
+ that.clicked = 0;
+ }, 200);
+ }
+ evt.stopPropagation();
+ });
+
+ // item indicator click (toggle item)
+ $(this.wrapSelector('.vp-sn-indicator')).off('click');
+ $(this.wrapSelector('.vp-sn-indicator')).on('click', function(evt) {
+ // toggle item
+ var parent = $(this).parent().parent();
+ var indicator = $(this);
+ var hasOpen = $(indicator).hasClass('open');
+ // Deprecated: hide all codebox
+ // $(that.wrapSelector('.vp-sn-indicator')).removeClass('open');
+ // $(that.wrapSelector('.vp-sn-item-code')).hide();
+
+ if (!hasOpen) {
+ // show code
+ $(indicator).addClass('open');
+ $(parent).find('.vp-sn-item-code').show();
+ } else {
+ // hide code
+ $(indicator).removeClass('open');
+ $(parent).find('.vp-sn-item-code').hide();
+ }
+ });
+
+ // prevent occuring header click event by clicking input
+ $(this.wrapSelector('.vp-sn-item-title')).off('click');
+ $(this.wrapSelector('.vp-sn-item-title')).on('click', function(evt) {
+ // evt.stopPropagation();
+ });
+
+ // item title save
+ $(this.wrapSelector('.vp-sn-item-title')).off('blur');
+ $(this.wrapSelector('.vp-sn-item-title')).on('blur', function(evt) {
+ var prevTitle = $(this).closest('.vp-sn-item').data('title');
+ var inputTitle = $(this).val();
+ var $thisItem = $(this);
+
+ if (prevTitle == inputTitle) {
+ ;
+ } else {
+ // check duplicated
+ var titleList = Object.keys(that.codemirrorList);
+ var newTitle = inputTitle;
+ var dupNo = 0
+ while(titleList.includes(newTitle)) {
+ dupNo += 1;
+ newTitle = inputTitle + '_' + dupNo;
+ }
+
+ let cmCode = that.codemirrorList[prevTitle];
+ if (cmCode) {
+ cmCode.save();
+ var code = cmCode.getValue();
+ // Remove original title
+ vpConfig.removeData(prevTitle).then(function() {
+ // Save data with new title
+ // save udf
+ var newTimestamp = new Date().getTime();
+ var newSnippet = { [newTitle]: { code: code, timestamp: newTimestamp } };
+ vpConfig.setData(newSnippet);
+
+ // update title & codemirror
+ $thisItem.closest('.vp-sn-item-title').val(newTitle);
+ $thisItem.closest('.vp-sn-item').data('title', newTitle);
+ // update codemirror
+ that.codemirrorList[newTitle] = that.codemirrorList[prevTitle];
+ delete that.codemirrorList[prevTitle];
+ });
+ }
+ }
+
+ // disable
+ $(this).prop('readonly', true);
+ });
+
+ // item menu click
+ $(this.wrapSelector('.vp-sn-item-menu-item')).off('click');
+ $(this.wrapSelector('.vp-sn-item-menu-item')).on('click', function(evt) {
+ var menu = $(this).data('menu');
+ var item = $(this).closest('.vp-sn-item');
+ var title = $(item).data('title');
+ if (menu == 'run') {
+ // get codemirror
+ let cmCode = that.codemirrorList[title];
+ cmCode.save();
+ var code = cmCode.getValue();
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Data Analysis > Snippets');
+ } else if (menu == 'duplicate') {
+ var dupNo = 1;
+ var timestamp = new Date().getTime();
+ var dupTitle = title + '_dup' + dupNo;
+ var titleList = Object.keys(that.codemirrorList);
+ // set duplicate title
+ while(titleList.includes(dupTitle)) {
+ dupNo += 1;
+ dupTitle = title + '_dup' + dupNo;
+ }
+
+ // add duplicated one
+ var code = that.codemirrorList[title].getValue();
+
+ var dupItem = $(that.renderSnippetItem(dupTitle, code, timestamp));
+ $(that.wrapSelector('.vp-sn-table')).append(dupItem);
+ // bind snippet item
+ that.bindSnippetItem();
+
+ // save it
+ var dupSnippet = { [dupTitle]: { code: code, timestamp: timestamp } };
+ vpConfig.setData(dupSnippet);
+
+ var tag = $(that.wrapSelector('.vp-sn-item[data-title="' + dupTitle + '"] textarea'));
+ that.bindCodeMirror(dupTitle, tag[0]);
+ $(dupItem).find('.vp-sn-indicator').trigger('click');
+
+ } else if (menu == 'delete') {
+ let loadingSpinner = new LoadingSpinner($(that.wrapSelector('.vp-sn-table')));
+ // remove key
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ vpConfig.getData('').then(function(data) {
+ let dataObj = data;
+ // remove data
+ delete dataObj[title];
+ vpConfig._writeToLab(dataObj).then(function() {
+ delete that.codemirrorList[title];
+ // remove item
+ $(that.wrapSelector('.vp-sn-item[data-title="' + title + '"]')).remove();
+
+ // vp-multilang for success message
+ com_util.renderSuccessMessage('Successfully removed!');
+ }).catch(function(err) {
+ com_util.renderAlertModal('Failed to remove data...', { content: err });
+ // load again
+ that.loadUdfList();
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }).catch(function(err) {
+
+ })
+ } else {
+ vpConfig.removeData(title).then(function() {
+ delete that.codemirrorList[title];
+ // remove item
+ $(that.wrapSelector('.vp-sn-item[data-title="' + title + '"]')).remove();
+
+ // vp-multilang for success message
+ com_util.renderSuccessMessage('Successfully removed!');
+ }).catch(function(err) {
+ com_util.renderAlertModal('Failed to remove data...', { content: err });
+ // load again
+ that.loadUdfList();
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }
+
+ } else if (menu == 'save') {
+ if (!$(this).hasClass('vp-disable')) {
+ var codemirror = that.codemirrorList[title];
+ codemirror.save();
+ var code = codemirror.getValue();
+
+ // save changed code
+ var timestamp = new Date().getTime();
+ var updateSnippet = { [title]: { code: code, timestamp: timestamp } };
+ vpConfig.setData(updateSnippet);
+
+ // disable it
+ $(this).addClass('vp-disable');
+ }
+ }
+ evt.stopPropagation();
+ });
+
+ // check items
+ $(this.wrapSelector('.vp-sn-item-check')).off('change');
+ $(this.wrapSelector('.vp-sn-item-check')).on('change', function() {
+ var checked = $(this).prop('checked');
+ // if unchecked at least one item, uncheck check-all
+ if (!checked) {
+ $(that.wrapSelector('.vp-sn-check-all')).prop('checked', false);
+ } else {
+ // if all checked, check check-all
+ var allLength = $(that.wrapSelector('.vp-sn-item-check')).length;
+ var checkedLength = $(that.wrapSelector('.vp-sn-item-check:checked')).length;
+ if (allLength == checkedLength) {
+ $(that.wrapSelector('.vp-sn-check-all')).prop('checked', true);
+ }
+ }
+ });
+ }
+
+ bindCodeMirror(title, selector) {
+ let cmCode = this.initCodemirror({
+ key: title,
+ selector: selector,
+ type: 'code',
+ events: [{
+ key: 'change',
+ callback: function(evt, chgObj) {
+ if (chgObj.removed.join('') != '' || chgObj.text.join('') != '') {
+ // enable save button
+ $(selector).parent().find('.vp-sn-save').removeClass('vp-disable');
+ }
+ }
+ }]
+ });
+ this.codemirrorList[title] = cmCode;
+ }
+
+ templateForBody() {
+ return snHtml;
+ }
+
+ render() {
+ super.render();
+
+ // load udf list
+ this.loadUdfList();
+ }
+
+ renderSnippetItem(title, code, timestamp, hasImported=false) {
+ var item = new com_String();
+ item.appendFormatLine('', 'vp-sn-item', title, timestamp);
+ item.appendFormatLine('
', 'vp-sn-item-header');
+ item.appendFormatLine('
', 'vp-sn-indicator');
+ item.appendFormatLine('
', 'vp-sn-item-title', title);
+ if (hasImported) {
+ item.appendFormatLine('
', 'fa fa-circle vp-sn-imported-item');
+ }
+ item.appendFormatLine('
', 'vp-sn-item-menu');
+ // LAB: img to url
+ item.appendFormatLine('
'
+ , 'vp-sn-item-menu-item vp-icon-run', 'run', 'Run');
+ // item.appendFormatLine('
', com_Const.IMAGE_PATH + 'snippets/run.svg');
+ item.appendLine('
');
+ // LAB: img to url
+ item.appendFormatLine('
'
+ , 'vp-sn-item-menu-item vp-icon-duplicate', 'duplicate', 'Duplicate');
+ // item.appendFormatLine('
', com_Const.IMAGE_PATH + 'snippets/duplicate.svg');
+ item.appendLine('
');
+ // LAB: img to url
+ item.appendFormatLine('
'
+ , 'vp-sn-item-menu-item vp-icon-delete', 'delete', 'Delete');
+ // item.appendFormatLine('
', com_Const.IMAGE_PATH + 'delete.svg');
+ item.appendLine('
');
+ item.appendLine('
'); // end of vp-sn-item-menu
+ // export mode checkbox
+ item.appendFormatLine('
', 'vp-sn-checkbox', 'vp-sn-item-check');
+ item.appendLine('
'); // end of vp-sn-item-header
+ item.appendFormatLine('
', 'vp-sn-item-code');
+ item.appendFormatLine('
', code);
+ // LAB: img to url
+ item.appendFormatLine('
', 'vp-sn-item-menu-item', 'vp-sn-save', 'save', 'Save changes');
+ // item.appendFormatLine('
', com_Const.IMAGE_PATH + 'snippets/save_orange.svg');
+ item.appendLine('
'); // vp-sn-save
+ item.appendLine('
'); // end of vp-sn-item-code
+ item.appendLine('
'); // end of vp-sn-item
+ return item.toString();
+ }
+
+ generateCode() {
+ return '';
+ }
+
+ loadUdfList() {
+ var that = this;
+
+ // clear table except head
+ $(this.wrapSelector('.vp-sn-table')).html('');
+
+ // load udf list to table 'vp_udfList'
+ let loadingSpinner = new LoadingSpinner($(this.wrapSelector('.vp-sn-table')));
+ vpConfig.getData().then(function(udfObj) {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'Snippets get data', udfObj);
+ var snippets = new com_String();
+ if (udfObj !== undefined) {
+ Object.keys(udfObj).forEach(key => {
+ let obj = udfObj[key];
+ if (obj.code != null && obj.code != undefined) {
+
+ var hasImported = false;
+ if (that.importedList.includes(key)) {
+ // set new label
+ hasImported = true;
+ }
+ var item = that.renderSnippetItem(key, obj.code, obj.timestamp, hasImported);
+ snippets.append(item);
+ }
+ });
+ }
+ $(that.wrapSelector('.vp-sn-table')).html(snippets.toString());
+
+ // bind snippet item
+ that.bindSnippetItem();
+
+ // load codemirror
+ var codeList = $(that.wrapSelector('.vp-sn-item-code textarea'));
+ codeList.each((idx, tag) => {
+ var title = $(tag).closest('.vp-sn-item').data('title');
+ that.bindCodeMirror(title, tag);
+ });
+ }).catch(function(err) {
+ // com_util.renderAlertModal(err);
+ vpLog.display(VP_LOG_TYPE.ERROR, err);
+ }).finally(function() {
+ loadingSpinner.remove();
+ });
+ }
+
+ }
+
+ return Snippets;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Subset.js b/visualpython/js/m_apps/Subset.js
new file mode 100644
index 00000000..41af3ef4
--- /dev/null
+++ b/visualpython/js/m_apps/Subset.js
@@ -0,0 +1,2092 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Subset.js
+ * Author : Black Logic
+ * Note : Apps > Subset
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Subset
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/subset.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/subset'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/VarSelector',
+ 'vp_base/js/com/component/DataSelector'
+], function(subsetHtml, subsetCss, com_Const, com_String, com_util, PopupComponent, SuggestInput, VarSelector, DataSelector) {
+
+ /**
+ * Subset
+ * ====================================
+ * Special mode
+ * 1. useAsModule : Use subset as module like DataSelector
+ * - No allocation
+ * - No run to cell (able to use apply button instead)
+ * - renders button to target
+ * 2. useInputVariable : Use subset as module but use applied variable
+ * - No allocation
+ * - No data selection
+ * - No run to cell
+ * - renders button to target
+ * 3. useInputColumns : Use subset as module but use applied columns
+ * - No allocation
+ * - No column selection
+ */
+ class Subset extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 3;
+ this.config.checkModules = ['pd'];
+ // use Run/Add cell
+ this.useCell = true;
+
+ /** Write codes executed before rendering */
+ this.targetSelector = this.prop.targetSelector;
+ this.pageThis = this.prop.pageThis;
+
+ this.useAsModule = this.prop.useAsModule;
+ this.useInputVariable = this.prop.useInputVariable;
+ if (this.useInputVariable === true || this.useAsModule === true) {
+ this.eventTarget = this.targetSelector;
+ this.useCell = false; // show apply button only
+ }
+ this.useInputColumns = this.prop.useInputColumns;
+ this.beforeOpen = this.prop.beforeOpen;
+ this.finish = this.prop.finish;
+
+ // specify pandas object types
+ this.pdObjTypes = ['DataFrame', 'Series'];
+ this.allowSubsetTypes = ['subset', 'iloc', 'loc', 'query'];
+ this.subsetLabels = {
+ 'subset': 'subset',
+ 'iloc' : 'iloc (integer location)',
+ 'loc' : 'loc (location)',
+ 'query' : 'query'
+ };
+ if (this.prop.allowSubsetTypes) {
+ this.allowSubsetTypes = this.prop.allowSubsetTypes;
+ }
+
+ this.stateLoaded = false;
+
+ this.state = {
+ viewAll: false,
+ previewCode: '',
+
+ // all variables list on opening popup
+ dataList: [],
+ allocateTo: '',
+ pandasObject: '',
+ dataType: 'DataFrame',
+ isTimestamp: false,
+
+ useCopy: false,
+ toFrame: false,
+ subsetType: 'loc', // subset / loc / iloc / query
+ returnType: '',
+
+ rowType: 'condition',
+ rowList: [],
+ rowLimit: 10,
+ rowPointer: { start: -1, end: -1 },
+ rowPageDom: '',
+
+ colType: 'indexing',
+ columnList: [],
+ colPointer: { start: -1, end: -1 },
+ colPageDom: '',
+ selectedColumns: [],
+ ...this.state
+ };
+
+ this._addCodemirror('previewCode', this.wrapSelector('#vp_ssPreviewCode'), 'readonly');
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariables();
+ let { subsetType, rowList, columnList } = this.state;
+ // set subset type
+ $(this.wrapSelector('.' + VP_DS_SUBSET_TYPE)).val(subsetType);
+ // render
+ this.renderRowSubsetType(subsetType);
+ this.renderRowIndexing(rowList);
+ this.renderRowSlicingBox(rowList);
+ this.renderColumnConditionList(columnList);
+
+ this.renderColumnSubsetType(subsetType);
+ this.renderColumnIndexing(columnList);
+ this.renderColumnSlicingBox(columnList);
+
+ this.loadStateAfterRender();
+
+ // render button
+ if (this.useAsModule) {
+ // render button
+ this.renderButton();
+
+ // hide allocate to
+ $(this.wrapSelector('.' + VP_DS_ALLOCATE_TO)).closest('tr').hide();
+ }
+ if (this.useInputVariable) {
+ // set readonly
+ $(this.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).attr('disabled', true);
+ // render button
+ this.renderButton();
+
+ // hide allocate to
+ $(this.wrapSelector('.' + VP_DS_ALLOCATE_TO)).closest('tr').hide();
+ }
+
+ if (this.useInputColumns) {
+ // hide make copy
+ $(this.wrapSelector('.' + VP_DS_USE_COPY)).parent().hide();
+ // hide to frame
+ $(this.wrapSelector('.' + VP_DS_TO_FRAME)).parent().hide();
+ // hide allocate to
+ $(this.wrapSelector('.' + VP_DS_ALLOCATE_TO)).closest('tr').hide();
+ // hide column box
+ $(this.wrapSelector('.' + VP_DS_TAB_PAGE_BOX + '.subset-column')).hide();
+ }
+ }
+
+ generateCode() {
+ return this.generateCodeForSubset();
+ }
+
+ templateForBody() {
+ let page = $(subsetHtml);
+
+ let that = this;
+ // Removed dataselector for Allocation input
+ // let allocateSelector = new DataSelector({
+ // pageThis: this, id: 'allocateTo', classes: VP_DS_ALLOCATE_TO, placeholder: 'New variable name',
+ // finish: function() {
+ // that.generateCode();
+ // }
+ // });
+ // $(page).find('.' + VP_DS_ALLOCATE_TO).replaceWith(allocateSelector.toTagString());
+
+ return page;
+ }
+ templateForDataView() {
+ let tag = new com_String();
+ // data view type
+ tag.appendFormatLine('{3}
',
+ VP_DS_DATA_VIEW_ALL_DIV, VP_DS_DATA_VIEW_ALL, (this.state.viewAll?'checked':''), "view all");
+ // data view
+ tag.appendFormatLine('
', VP_DS_DATA_VIEW_BOX,
+ 'vp_rendered_html'); // 'rendered_html' style from jupyter output area
+ return tag.toString();
+ }
+ getAllowSubsetTypes() {
+ return this.pdObjTypes;
+ }
+ ///////////////////////// render //////////////////////////////////////////////////////
+ renderButton() {
+ // set button next to input tag
+ var buttonTag = new com_String();
+ buttonTag.appendFormat('{3} ',
+ VP_DS_BTN, this.uuid, 'vp-button', 'Subset');
+ if (this.pageThis) {
+ $(buttonTag.toString()).insertAfter($(this.targetSelector));
+ }
+ }
+ renderSubsetType(dataType) {
+ var subsetType = this.state.subsetType;
+ let that = this;
+
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SUBSET_TYPE, 'vp-select');
+ this.allowSubsetTypes.forEach(thisType => {
+ if (thisType != 'query' || dataType == 'DataFrame') {
+ let label = that.subsetLabels[thisType];
+ tag.appendFormatLine('{2} ', thisType, subsetType == thisType?'selected':'', label);
+ }
+ });
+ // tag.appendFormatLine('{2} ', 'subset', subsetType == 'subset'?'selected':'', 'subset');
+ // tag.appendFormatLine('{2} ', 'loc', subsetType == 'loc'?'selected':'', 'loc');
+ // tag.appendFormatLine('{2} ', 'iloc', subsetType == 'iloc'?'selected':'', 'iloc');
+ // if (dataType == 'DataFrame') {
+ // tag.appendFormatLine('{2} ', 'query', subsetType == 'query'?'selected':'', 'query');
+ // }
+ tag.appendLine(' ');
+
+ return tag.toString();
+ }
+ renderRowSubsetType(subsetType, timestamp = false) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_ROWTYPE, 'vp-select m');
+ if (subsetType == 'loc' || subsetType == 'iloc' || this.state.dataType == 'Series') {
+ tag.appendFormatLine('{1} ', 'indexing', 'Indexing');
+ }
+ if (subsetType == 'subset' || subsetType == 'loc' || subsetType == 'iloc') {
+ tag.appendFormatLine('{1} ', 'slicing', 'Slicing');
+ }
+ if (subsetType == 'subset' || subsetType == 'loc' || subsetType == 'query') {
+ tag.appendFormatLine('{1} ', 'condition', 'Condition');
+ }
+ if ((subsetType == 'subset' || subsetType == 'loc') && timestamp) {
+ tag.appendFormatLine('{1} ', 'timestamp', 'Timestamp');
+ }
+ tag.appendLine(' ');
+ // render
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE)).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ renderColumnSubsetType(subsetType) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_COLTYPE, 'vp-select m');
+ tag.appendFormatLine('{1} ', 'indexing', 'Indexing');
+ if (subsetType == 'loc' || subsetType == 'iloc') {
+ tag.appendFormatLine('{1} ', 'slicing', 'Slicing');
+ }
+ tag.appendLine(' ');
+ // render
+ $(this.wrapSelector('.' + VP_DS_COLTYPE)).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ /**
+ * Render row selection list
+ * - search box
+ * - row list box (left)
+ * - buttons (add/del to right box)
+ * - apply box (right)
+ * @param {Array} rowList
+ */
+ renderRowIndexing(rowList) {
+ var that = this;
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SELECT_CONTAINER, 'select-row');
+ // row select - left
+ tag.appendFormatLine('
', VP_DS_SELECT_LEFT);
+ // tag.appendFormatLine('
'
+ // , VP_DS_SELECT_SEARCH, 'Search Row');
+ var vpSearchSuggest = new SuggestInput();
+ vpSearchSuggest.addClass(VP_DS_SELECT_SEARCH);
+ vpSearchSuggest.setPlaceholder('Search Row');
+ vpSearchSuggest.setSuggestList(function () { return that.state.rowList; });
+ vpSearchSuggest.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpSearchSuggest.setNormalFilter(true);
+ tag.appendLine(vpSearchSuggest.toTagString());
+
+ tag.appendFormatLine('
', VP_DS_SELECT_BOX, 'left', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+ tag.appendLine('
'); // VP_DS_SELECT_LEFT
+
+ // row select - buttons
+ tag.appendFormatLine('
', VP_DS_SELECT_BTN_BOX);
+ // LAB: img to url
+ // tag.appendFormatLine('
',
+ // VP_DS_SELECT_ADD_ALL_BTN, 'select-row', 'Add all items', com_Const.IMAGE_PATH + 'arrow_right_double.svg');
+ // tag.appendFormatLine('
', VP_DS_SELECT_ADD_BTN, 'select-row', com_Const.IMAGE_PATH + 'arrow_right.svg');
+ // tag.appendFormatLine('
', VP_DS_SELECT_DEL_BTN, 'select-row', com_Const.IMAGE_PATH + 'arrow_left.svg');
+ // tag.appendFormatLine('
',
+ // VP_DS_SELECT_DEL_ALL_BTN, 'select-row', 'Remove all items', com_Const.IMAGE_PATH + 'arrow_left_double.svg');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_ADD_ALL_BTN, 'select-row', 'Add all items');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_ADD_BTN, 'select-row');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_DEL_BTN, 'select-row');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_DEL_ALL_BTN, 'select-row', 'Remove all items');
+ tag.appendLine('
'); // VP_DS_SELECT_BTNS
+
+ // row select - right
+ tag.appendFormatLine('
', VP_DS_SELECT_RIGHT);
+ tag.appendFormatLine('
', VP_DS_SELECT_BOX, 'right', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+ tag.appendLine('
'); // VP_DS_SELECT_BOX
+ tag.appendLine('
'); // VP_DS_SELECT_RIGHT
+ tag.appendLine('
'); // VP_DS_SELECT_CONTAINER
+ // render
+ $(this.wrapSelector('.' + VP_DS_SELECT_CONTAINER + '.select-row')).replaceWith(function () {
+ return tag.toString();
+ });
+ this.renderRowSelectionBox(rowList);
+ }
+ /**
+ * Render row list box
+ * @param {Array} rowList
+ */
+ renderRowSelectionBox(rowList) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SELECT_BOX, 'left', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+
+ // get row data and make draggable items
+ rowList.forEach((row, idx) => {
+ tag.appendFormatLine('
{7}
',
+ VP_DS_SELECT_ITEM, 'select-row', VP_DS_DRAGGABLE, row.location, row.value, row.code, row.label, row.label);
+ });
+ tag.appendLine('
'); // VP_DS_SELECT_BOX
+ // render
+ $(this.wrapSelector('.select-row .' + VP_DS_SELECT_BOX + '.left')).replaceWith(function () {
+ return tag.toString();
+ });
+
+ // item indexing - scroll to bottom
+ let that = this;
+ $(this.wrapSelector('.select-row .vp-ds-select-box.left')).on('scroll', function() {
+ if ($(this).scrollTop() + $(this).innerHeight() >= ($(this)[0].scrollHeight - 2)) {
+ let scrollPos = $(this).scrollTop();
+ if (that.state.rowLimit > that.state.rowList.length){
+ return; // Prevents scroll from being fixed downwards
+ }
+ let start = that.state.rowLimit;
+ let end = start + 10;
+ let subsetVariable = com_util.formatString('{0}.iloc[{1}:{2}]', that.state.pandasObject, start, end);
+ vpKernel.getRowList(subsetVariable, start).then(function (resultObj) {
+ let { result } = resultObj;
+ var { list:rowList } = JSON.parse(result);
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value
+ };
+ });
+ // if iloc
+ if (that.state.subsetType == 'iloc') {
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ label: x.label + '',
+ value: x.value + '',
+ code: x.code + '',
+ };
+ });
+ }
+
+ let newRowList = [
+ ...that.state.rowList,
+ ...rowList
+ ];
+ that.state.rowList = [ ...newRowList ];
+
+ // filter with selected list
+ var selectedList = [];
+ var selectedTags = $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + '.select-row.added:not(.moving)'));
+ if (selectedTags.length > 0) {
+ for (var i = 0; i < selectedTags.length; i++) {
+ var rowValue = $(selectedTags[i]).data('code');
+ if (rowValue !== undefined) {
+ selectedList.push(rowValue);
+ }
+ }
+ }
+
+ newRowList = newRowList.filter(row => !selectedList.includes(row.code));
+
+ that.renderRowSelectionBox(newRowList);
+ that.bindDraggable('row');
+ that.generateCode();
+
+ // load scroll position
+ $(that.wrapSelector('.select-row .vp-ds-select-box.left')).scrollTop(scrollPos);
+
+ that.state.rowLimit = end;
+ });
+ }
+ });
+ }
+ /**
+ * Render row slicing box
+ * - slicing start/end with suggestInput
+ * @param {Array} rowList
+ */
+ renderRowSlicingBox(rowList) {
+ var that = this;
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SLICING_BOX, 'vp-grid-col-p50');
+ // var vpRowStart = new SuggestInput();
+ // vpRowStart.addClass(VP_DS_ROW_SLICE_START);
+ // vpRowStart.addClass('vp-input m');
+ // vpRowStart.setPlaceholder('start');
+ // vpRowStart.setSuggestList(function () { return rowList; });
+ // vpRowStart.setSelectEvent(function (value, item) {
+ // $(this.wrapSelector()).val(item.code);
+ // $(this.wrapSelector()).attr('data-code', item.code);
+ // // $(this.wrapSelector()).trigger('change');
+ // that.generateCode();
+ // });
+ // vpRowStart.setNormalFilter(false);
+
+ // var vpRowEnd = new SuggestInput();
+ // vpRowEnd.addClass(VP_DS_ROW_SLICE_END);
+ // vpRowEnd.addClass('vp-input m');
+ // vpRowEnd.setPlaceholder('end');
+ // vpRowEnd.setSuggestList(function () { return rowList; });
+ // vpRowEnd.setSelectEvent(function (value, item) {
+ // $(this.wrapSelector()).val(item.code);
+ // $(this.wrapSelector()).attr('data-code', item.code);
+ // // $(this.wrapSelector()).trigger('change');
+ // that.generateCode();
+ // });
+ // vpRowEnd.setNormalFilter(false);
+ // tag.appendLine(vpRowStart.toTagString());
+ // tag.appendLine(vpRowEnd.toTagString());
+ tag.appendLine('
');
+ tag.appendFormatLine(' ', VP_DS_ROW_SLICE_START, 'start');
+ tag.appendFormatLine('Text ', 'vp-ds-row-slice-start-text');
+ tag.appendLine('
');
+ tag.appendLine('
');
+ tag.appendFormatLine(' ', VP_DS_ROW_SLICE_END, 'end');
+ tag.appendFormatLine('Text ', 'vp-ds-row-slice-end-text');
+ tag.appendLine('
');
+ tag.appendLine('
');
+ // render
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + ' .' + VP_DS_SLICING_BOX)).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ /**
+ * Render column selection list
+ * - search box
+ * - column list box (left)
+ * - buttons (add/del to right box)
+ * - apply box (right)
+ * @param {Array} colList
+ */
+ renderColumnIndexing(colList) {
+ var that = this;
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SELECT_CONTAINER, 'select-col');
+ // col select - left
+ tag.appendFormatLine('
', VP_DS_SELECT_LEFT);
+ // tag.appendFormatLine('
'
+ // , VP_DS_SELECT_SEARCH, 'Search Column');
+ var vpSearchSuggest = new SuggestInput();
+ vpSearchSuggest.addClass(VP_DS_SELECT_SEARCH);
+ vpSearchSuggest.setPlaceholder('Search Column');
+ vpSearchSuggest.setSuggestList(function () { return that.state.columnList; });
+ vpSearchSuggest.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpSearchSuggest.setNormalFilter(true);
+ tag.appendLine(vpSearchSuggest.toTagString());
+ tag.appendFormatLine('
');
+
+ tag.appendFormatLine('
', VP_DS_SELECT_BOX, 'left', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+ tag.appendLine('
'); // VP_DS_SELECT_LEFT
+
+ // col select - buttons
+ tag.appendFormatLine('
', VP_DS_SELECT_BTN_BOX);
+ // LAB: img to url
+ // tag.appendFormatLine('
',
+ // VP_DS_SELECT_ADD_ALL_BTN, 'select-col', 'Add all items', com_Const.IMAGE_PATH + 'arrow_right_double.svg');
+ // tag.appendFormatLine('
', VP_DS_SELECT_ADD_BTN, 'select-col', com_Const.IMAGE_PATH + 'arrow_right.svg');
+ // tag.appendFormatLine('
', VP_DS_SELECT_DEL_BTN, 'select-col', com_Const.IMAGE_PATH + 'arrow_left.svg');
+ // tag.appendFormatLine('
',
+ // VP_DS_SELECT_DEL_ALL_BTN, 'select-col', 'Remove all items', com_Const.IMAGE_PATH + 'arrow_left_double.svg');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_ADD_ALL_BTN, 'select-col', 'Add all items');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_ADD_BTN, 'select-col');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_DEL_BTN, 'select-col');
+ tag.appendFormatLine('
',
+ VP_DS_SELECT_DEL_ALL_BTN, 'select-col', 'Remove all items');
+ tag.appendLine('
'); // VP_DS_SELECT_BTNS
+
+ // col select - right
+ tag.appendFormatLine('
', VP_DS_SELECT_RIGHT);
+ tag.appendFormatLine('
', VP_DS_SELECT_BOX, 'right', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+ tag.appendLine('
'); // VP_DS_SELECT_BOX
+ tag.appendLine('
'); // VP_DS_SELECT_RIGHT
+ tag.appendLine('
'); // VP_DS_SELECT_CONTAINER
+ // render
+ $(this.wrapSelector('.' + VP_DS_SELECT_CONTAINER + '.select-col')).replaceWith(function () {
+ return tag.toString();
+ });
+ this.renderColumnSelectionBox(colList);
+ }
+ /**
+ * Render column list box
+ * @param {Array} colList
+ */
+ renderColumnSelectionBox(colList) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SELECT_BOX, 'left', VP_DS_DROPPABLE, 'vp-scrollbar no-selection');
+ // get col data and make draggable items
+ colList.forEach((col, idx) => {
+ // col.array parsing
+ var colInfo = com_util.safeString(col.array);
+ // render column box
+ let numIconStr = '';
+ if (col.isNumeric === true) {
+ numIconStr = '
';
+ } else {
+ numIconStr = '
';
+ }
+ tag.appendFormatLine('
{8}{9}
',
+ VP_DS_SELECT_ITEM, 'select-col', VP_DS_DRAGGABLE, col.location, col.value, col.dtype, col.code, col.label + ': \n' + colInfo, numIconStr, col.label);
+ });
+ tag.appendLine('
'); // VP_DS_SELECT_BOX
+ $(this.wrapSelector('.select-col .' + VP_DS_SELECT_BOX + '.left')).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ /**
+ * Render column slicing box
+ * - slicing start/end with suggestInput
+ * @param {Array} colList
+ */
+ renderColumnSlicingBox(colList) {
+ var that = this;
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_SLICING_BOX);
+ // tag.appendFormatLine('{1} '
+ // , '', 'Slice');
+ // tag.appendFormatLine(' : ', VP_DS_COL_SLICE_START, 'vp-input m', 'start');
+ // tag.appendFormatLine(' ', VP_DS_COL_SLICE_END, 'vp-input m', 'end');
+ var vpColStart = new SuggestInput();
+ vpColStart.addClass(VP_DS_COL_SLICE_START);
+ vpColStart.addClass('vp-input');
+ vpColStart.setPlaceholder('start');
+ vpColStart.setSuggestList(function () { return colList; });
+ vpColStart.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(item.code);
+ $(this.wrapSelector()).data('code', item.code);
+ that.generateCode();
+ });
+ vpColStart.setNormalFilter(false);
+
+ var vpColEnd = new SuggestInput();
+ vpColEnd.addClass(VP_DS_COL_SLICE_END);
+ vpColEnd.addClass('vp-input');
+ vpColEnd.setPlaceholder('end');
+ vpColEnd.setSuggestList(function () { return colList; });
+ vpColEnd.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(item.code);
+ $(this.wrapSelector()).data('code', item.code);
+ that.generateCode();
+ });
+ vpColEnd.setNormalFilter(false);
+
+ tag.appendLine(vpColStart.toTagString());
+ tag.appendLine(vpColEnd.toTagString());
+ tag.appendLine('
');
+ $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + ' .' + VP_DS_SLICING_BOX)).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ /**
+ * Render Row Condition List with columns
+ * - column name
+ * - operator
+ * - condition string
+ * - and/or connector between prev/next conditions
+ * @param {Array} colList
+ */
+ renderColumnConditionList(colList) {
+ var tag = new com_String();
+ tag.appendFormatLine('', VP_DS_CONDITION_TBL);
+ tag.appendLine(this.templateForConditionBox(colList));
+ tag.appendLine('');
+ tag.appendFormatLine('{2} ',
+ VP_DS_BUTTON_ADD_CONDITION, 'vp-add-col', '+ Condition');
+ tag.appendLine(' ');
+ tag.appendLine('
');
+ $(this.wrapSelector('.' + VP_DS_CONDITION_TBL)).replaceWith(function () {
+ return tag.toString();
+ });
+ }
+ templateForConditionBox(colList) {
+ var tag = new com_String();
+ tag.appendLine('');
+ tag.appendLine('');
+ // del col
+ tag.appendLine('
');
+
+ var varList = this.state.dataList;
+
+ tag.appendLine('');
+ tag.appendLine(this.templateForConditionColumnInput(colList));
+ tag.appendLine(this.templateForConditionOperator(''));
+ tag.appendLine(' ');
+ tag.appendLine('
');
+
+ tag.appendLine('');
+ tag.appendLine('');
+ tag.appendLine('and ');
+ tag.appendLine('or ');
+ tag.appendLine(' ');
+
+ // use text
+ tag.appendFormatLine('{3} ',
+ 'vp-condition-use-text', 'vp-cond-use-text', 'Uncheck it if you want to use variable or numeric values.', 'Text');
+ tag.appendLine('
');
+
+ tag.appendLine(' ');
+ tag.appendLine(' ');
+ return tag.toString();
+ }
+ templateForConditionVariableInput(varList, defaultValue, defaultValuesType) {
+ var dataTypes = ['DataFrame', 'Series', 'nparray', 'list', 'str'];
+ var varSelector = new VarSelector(dataTypes, defaultValuesType, true, true);
+ varSelector.addClass('vp-cond-var');
+ varSelector.setValue(defaultValue);
+ return varSelector.render();
+ }
+ templateForConditionColumnInput(colList) {
+ var tag = new com_String();
+ tag.appendFormatLine('', 'vp-select m', 'vp-col-list');
+ // .index
+ tag.appendFormatLine('{2} ', '.index', '.index', 'index');
+ colList.forEach(col => {
+ tag.appendFormatLine('{3} ',
+ col.code, col.dtype, col.value, col.label);
+ });
+ tag.appendLine(' ');
+ return tag.toString();
+ }
+ templateForConditionOperator(dtype='object') {
+ var tag = new com_String();
+ tag.appendFormatLine('', 'vp-select s', 'vp-oper-list');
+ var operList = ['', '==', '!=', '<', '<=', '>', '>=', 'contains', 'not contains', 'starts with', 'ends with', 'isnull()', 'notnull()'];
+ if (dtype == '') {
+ // .index
+ operList = ['', '==', '!=', '<', '<=', '>', '>='];
+ } else if (dtype != 'object') {
+ operList = ['', '==', '!=', '<', '<=', '>', '>=', 'isnull()', 'notnull()'];
+ }
+ operList.forEach(oper => {
+ tag.appendFormatLine('{1} ', oper, oper);
+ });
+ tag.appendLine(' ');
+ return tag.toString();
+ }
+ templateForConditionCondInput(category, dtype='object') {
+ var vpCondSuggest = new SuggestInput();
+ vpCondSuggest.addClass('vp-input m vp-condition');
+
+ if (category && category.length > 0) {
+ vpCondSuggest.setPlaceholder((dtype=='object'?'Categorical':dtype) + " dtype");
+ vpCondSuggest.setSuggestList(function () { return category; });
+ vpCondSuggest.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpCondSuggest.setNormalFilter(false);
+ } else {
+ vpCondSuggest.setPlaceholder(dtype==''?'Value':(dtype + " dtype"));
+ }
+ return vpCondSuggest.toTagString();
+ }
+ renderDataView() {
+ super.renderDataView();
+
+ this.loadDataPage();
+ $(this.wrapSelector('.vp-popup-dataview-box')).css('height', '300px');
+ }
+ /**
+ * Render Data Tab Page
+ * @param {String} renderedText
+ */
+ renderDataPage(renderedText, isHtml = true) {
+ var tag = new com_String();
+ if (isHtml) {
+ tag.appendLine(renderedText);
+ } else {
+ tag.appendFormatLine('{0} ', renderedText);
+ }
+ $(this.wrapSelector('.' + VP_DS_DATA_VIEW_BOX)).html(tag.toString());
+ }
+ ///////////////////////// render end //////////////////////////////////////////////////////
+ ///////////////////////// load ///////////////////////////////////////////////////////////
+ /**
+ * Load Data Tab Page
+ * - execute generated current code and get html text from jupyter kernel
+ * - render data page with html text (msg.content.data['text/html'])
+ */
+ loadDataPage() {
+ var that = this;
+
+ var code = this.state.pandasObject;
+
+ // if view all is not checked, get current code
+ if (!this.state.viewAll) {
+ // get current code
+ code = this.generateCodeForSubset(false, false);
+ }
+ // if not, get output of all data in selected pandasObject
+ vpKernel.execute(code).then(function(resultObj) {
+ let { msg } = resultObj;
+ if (msg.content.data) {
+ var htmlText = String(msg.content.data["text/html"]);
+ var codeText = String(msg.content.data["text/plain"]);
+ if (htmlText != 'undefined') {
+ that.renderDataPage(htmlText);
+ } else if (codeText != 'undefined') {
+ // plain text as code
+ that.renderDataPage(codeText, false);
+ } else {
+ that.renderDataPage('');
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ that.renderDataPage(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ that.renderDataPage(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ });
+ }
+ /**
+ * Load pandasObject
+ * - search available pandasObject list
+ * - render on VP_DS_PANDAS_OBJECT
+ */
+ loadVariables() {
+ let that = this;
+ var types = that.pdObjTypes;
+ var prevValue = this.state.pandasObject;
+
+ // if get input variable through parameter
+ if (this.useInputVariable && prevValue != '') {
+ $(this.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).val(prevValue);
+
+ // get type of variable
+ vpKernel.execute(com_util.formatString('_vp_print(_vp_get_type({0}))', prevValue)).then(function (resultObj) {
+ let { result } = resultObj;
+ try {
+ var varType = JSON.parse(result);
+ that.state.pandasObject = prevValue;
+ that.state.dataType = varType;
+ that.state.returnType = varType;
+ $(that.wrapSelector('.' + VP_DS_PANDAS_OBJECT_BOX)).replaceWith(function () {
+ return $(com_util.formatString('
',
+ 'vp-input', VP_DS_PANDAS_OBJECT, prevValue));
+ });
+ if (!that.stateLoaded) {
+ that.reloadSubsetData();
+ }
+ } catch {
+ ;
+ }
+ });
+ } else {
+ // if get input variable through user's selection
+ vpKernel.getDataList(types).then(function (resultObj) {
+ let { result } = resultObj;
+ var varList = JSON.parse(result);
+ varList = varList.map(function (v) {
+ return { label: v.varName, value: v.varName, dtype: v.varType };
+ });
+
+ that.state.dataList = varList;
+
+ // 1. Target Variable
+ var prevValue = $(that.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).val();
+ // $(that.wrapSelector('.' + VP_DS_PANDAS_OBJECT_BOX)).replaceWith(function () {
+ // var pdVarSelect = new VarSelector(that.pdObjTypes, that.state.dataType, false, false);
+ // pdVarSelect.addClass(VP_DS_PANDAS_OBJECT);
+ // pdVarSelect.addBoxClass(VP_DS_PANDAS_OBJECT_BOX);
+ // pdVarSelect.setValue(prevValue);
+ // return pdVarSelect.render();
+ // });
+ var variableInput = new SuggestInput();
+ variableInput.addClass(VP_DS_PANDAS_OBJECT);
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return varList; });
+ variableInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).data('dtype', item.dtype);
+ that.state.pandasObject = value;
+ that.state.dataType = item.dtype;
+ that.state.returnType = item.dtype;
+ $(this.wrapSelector()).trigger('change');
+ });
+ variableInput.setNormalFilter(true);
+ variableInput.setValue(prevValue);
+ variableInput.addAttribute('required', true);
+ $(that.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).replaceWith(function() {
+ return variableInput.toTagString();
+ });
+ if (!that.stateLoaded) {
+ that.reloadSubsetData();
+ }
+ });
+ }
+ }
+ loadSubsetType(dataType) {
+ let that = this;
+ $(this.wrapSelector('.' + VP_DS_SUBSET_TYPE)).replaceWith(function () {
+ return that.renderSubsetType(dataType);
+ });
+ }
+ /**
+ * Load Row & Column option page based on subsetType
+ * @param {string} subsetType subset / loc / iloc / query
+ * @param {boolean} timestamp use timestamp? true / false
+ */
+ loadRowColumnSubsetType(subsetType, timestamp = false) {
+ var that = this;
+ // get current subset type of row & column
+ var rowSubset = this.state.rowType;
+ var colSubset = this.state.colType;
+
+ // render row & column option page
+ that.renderRowSubsetType(subsetType, timestamp);
+ that.renderColumnSubsetType(subsetType);
+
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE)).val(rowSubset);
+ $(this.wrapSelector('.' + VP_DS_COLTYPE)).val(colSubset);
+
+ var selectedRowType = $(this.wrapSelector('.' + VP_DS_ROWTYPE)).val();
+ var selectedColType = $(this.wrapSelector('.' + VP_DS_COLTYPE)).val();
+
+ if (selectedRowType != rowSubset) {
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE + ' option')).eq(0).prop('selected', true);
+ this.state.rowType = $(this.wrapSelector('.' + VP_DS_ROWTYPE)).val();
+ }
+ if (selectedColType != colSubset) {
+ $(this.wrapSelector('.' + VP_DS_COLTYPE + ' option')).eq(0).prop('selected', true);
+ this.state.colType = $(this.wrapSelector('.' + VP_DS_COLTYPE)).val();
+ }
+
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE)).trigger('change');
+ $(this.wrapSelector('.' + VP_DS_COLTYPE)).trigger('change');
+ }
+ /**
+ * Load Column List
+ * - change state.columnList
+ * - render column selection list
+ * - render column slicing box
+ * - render column condition list
+ * @param {Array} columnList
+ */
+ loadColumnList(columnList) {
+ var that = this;
+
+ // if iloc
+ if (this.state.subsetType == 'iloc') {
+ columnList = columnList.map(function (x) {
+ return {
+ ...x,
+ label: x.location + '',
+ value: x.location + '',
+ code: x.location + '',
+ dtype: 'int'
+ };
+ });
+ }
+
+ this.state.columnList = columnList;
+ this.state.colPointer = { start: -1, end: -1 };
+
+ // column selection
+ this.renderColumnIndexing(columnList);
+
+ // column slicing
+ this.renderColumnSlicingBox(columnList);
+
+ // column condition
+ this.renderColumnConditionList(columnList);
+ }
+ /**
+ * Load Row List
+ * - change state.rowList
+ * - render row selection list
+ * - render row slicing box
+ * @param {Array} rowList
+ */
+ loadRowList(rowList) {
+ var that = this;
+
+ this.state.rowList = rowList;
+ this.state.rowPointer = { start: -1, end: -1 };
+
+ // is timestampindex ?
+ if (rowList && rowList.length > 0 && rowList[0]['index_dtype'] == 'datetime64[ns]') {
+ this.state.isTimestamp = true;
+ } else {
+ this.state.isTimestamp = false;
+ }
+
+ // row selection
+ this.renderRowIndexing(rowList);
+
+ // row slicing
+ this.renderRowSlicingBox(rowList);
+
+ this.loadRowColumnSubsetType(this.state.subsetType, this.state.isTimestamp);
+ }
+ saveState() {
+ // save input state
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + this.state.rowType + ' input')).each(function () {
+ this.defaultValue = this.value;
+ });
+ $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + this.state.colType + ' input')).each(function () {
+ this.defaultValue = this.value;
+ });
+
+ // save checkbox state
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + this.state.rowType + ' input[type="checkbox"]')).each(function () {
+ if (this.checked) {
+ this.setAttribute("checked", true);
+ } else {
+ this.removeAttribute("checked");
+ }
+ });
+ $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + this.state.colType + ' input[type="checkbox"]')).each(function () {
+ if (this.checked) {
+ this.setAttribute("checked", true);
+ } else {
+ this.removeAttribute("checked");
+ }
+ });
+
+ // save select state
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + this.state.rowType + ' select > option')).each(function () {
+ if (this.selected) {
+ this.setAttribute("selected", true);
+ } else {
+ this.removeAttribute("selected");
+ }
+ });
+ $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + this.state.colType + ' select > option')).each(function () {
+ if (this.selected) {
+ this.setAttribute("selected", true);
+ } else {
+ this.removeAttribute("selected");
+ }
+ });
+
+ // save pageDom
+ this.state.rowPageDom = $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + this.state.rowType)).html();
+ this.state.colPageDom = $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + this.state.colType)).html();
+ }
+ loadStateAfterRender() {
+ var {
+ dataType, pandasObject, useCopy, toFrame, subsetType, allocateTo, rowType, colType, rowPageDom, colPageDom
+ } = this.state;
+ // load variable
+ $(this.wrapSelector('.' + VP_DS_PANDAS_OBJECT_BOX + ' .vp-vs-variables')).val(dataType);
+ $(this.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).val(pandasObject);
+ $(this.wrapSelector('.' + VP_DS_USE_COPY)).prop('checked', useCopy);
+ $(this.wrapSelector('.' + VP_DS_TO_FRAME)).prop('checked', toFrame);
+
+ // load method
+ $(this.wrapSelector('.' + VP_DS_SUBSET_TYPE)).val(subsetType);
+
+ // load allocate to
+ $(this.wrapSelector('.' + VP_DS_ALLOCATE_TO)).val(allocateTo);
+
+
+ // load rowPageDom
+ if (rowPageDom != '') {
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + rowType)).html(rowPageDom);
+ }
+
+ // load colPageDom
+ if (colPageDom != '') {
+ $(this.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + colType)).html(colPageDom);
+ }
+
+ // bind draggable
+ if (rowType == 'indexing') {
+ this.bindDraggable('row');
+ }
+ if (colType == 'indexing') {
+ this.bindDraggable('col');
+ }
+
+ // load rowType
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE)).val(rowType);
+ $(this.wrapSelector('.' + VP_DS_ROWTYPE)).trigger('change');
+
+ // load colType
+ $(this.wrapSelector('.' + VP_DS_COLTYPE)).val(colType);
+ $(this.wrapSelector('.' + VP_DS_COLTYPE)).trigger('change');
+
+
+ this.stateLoaded = true;
+
+ this.generateCode();
+ }
+ ///////////////////////// load end ///////////////////////////////////////////////////////////
+ /**
+ * Bind Draggable to VP_DS_SELECT_ITEM
+ * - bind draggable to VP_DS_DRAGGABLE
+ * - bind droppable to VP_DS_DROPPABLE
+ * @param {string} type 'row'/'col'
+ */
+ bindDraggable(type) {
+ var that = this;
+ var draggableQuery = this.wrapSelector('.' + VP_DS_DRAGGABLE + '.select-' + type);
+ var droppableQuery = this.wrapSelector('.select-' + type + ' .' + VP_DS_DROPPABLE);
+
+ $(draggableQuery).draggable({
+ // containment: '.select-' + type + ' .' + VP_DS_DROPPABLE,
+ // appendTo: droppableQuery,
+ // snap: '.' + VP_DS_DRAGGABLE,
+ revert: 'invalid',
+ cursor: 'pointer',
+ connectToSortable: droppableQuery + '.right',
+ // cursorAt: { bottom: 5, right: 5 },
+ helper: function () {
+ // selected items
+ var widthString = parseInt($(this).outerWidth()) + 'px';
+ var selectedTag = $(this).parent().find('.selected');
+ if (selectedTag.length <= 0) {
+ selectedTag = $(this);
+ }
+ return $('
').append(selectedTag.clone().addClass('moving').css({
+ width: widthString, border: '0.25px solid #C4C4C4'
+ }));
+ }
+ });
+
+ $(droppableQuery).droppable({
+ accept: draggableQuery,
+ drop: function (event, ui) {
+ var dropped = ui.draggable;
+ var droppedOn = $(this);
+
+ // is dragging on same droppable container?
+ if (droppedOn.get(0) == $(dropped).parent().get(0)) {
+
+ that.generateCode();
+ return;
+ }
+
+ var dropGroup = $(dropped).parent().find('.selected:not(.moving)');
+ // if nothing selected(as orange_text), use dragging item
+ if (dropGroup.length <= 0) {
+ dropGroup = $(dropped);
+ }
+ $(dropGroup).detach().css({ top: 0, left: 0 }).appendTo(droppedOn);
+
+ if ($(this).hasClass('right')) {
+ // add
+ $(dropGroup).addClass('added');
+ } else {
+ // del
+ $(dropGroup).removeClass('added');
+ // sort
+ $(droppedOn).find('.' + VP_DS_SELECT_ITEM).sort(function (a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo($(droppedOn));
+ }
+ // remove selection
+ $(droppableQuery).find('.selected').removeClass('selected');
+ that.state[type + 'Pointer'] = { start: -1, end: -1 };
+
+ that.generateCode();
+ },
+ over: function (event, elem) {
+ },
+ out: function (event, elem) {
+ }
+ });
+
+
+ }
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off(this.wrapSelector('*'));
+
+ $(document).off('var_changed change', this.wrapSelector('.' + VP_DS_PANDAS_OBJECT));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_USE_COPY));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_SUBSET_TYPE));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_TO_FRAME));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_ALLOCATE_TO));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_TAB_SELECTOR_BTN));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_DATA_VIEW_ALL));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_ROWTYPE));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_COLTYPE));
+ $(document).off('change', this.wrapSelector('.' + VP_DS_INDEXING_TIMESTAMP));
+ $(document).off('change', this.wrapSelector('.select-row .' + VP_DS_SELECT_SEARCH));
+ $(document).off('change', this.wrapSelector('.select-col .' + VP_DS_SELECT_SEARCH));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_SELECT_ITEM));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_SELECT_ADD_ALL_BTN));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_SELECT_ADD_BTN));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_SELECT_DEL_BTN));
+ $(document).off('click', this.wrapSelector('.' + VP_DS_SELECT_DEL_ALL_BTN));
+ $(document).off('click', this.wrapSelector('.vp-add-col'));
+ $(document).off('click', this.wrapSelector('.vp-del-col'));
+ $(document).off('change', this.wrapSelector('.vp-ds-slicing-box input[type="text"]'));
+ $(document).off('change var_changed', this.wrapSelector('.vp-ds-cond-tbl .vp-cond-var'));
+ $(document).off('change', this.wrapSelector('.vp-ds-cond-tbl .vp-col-list'));
+ $(document).off('change', this.wrapSelector('.vp-ds-cond-tbl .vp-cond-use-text'));
+ $(document).off('change', this.wrapSelector('.vp-ds-cond-tbl input[type="text"]'));
+ $(document).off('change', this.wrapSelector('.vp-ds-cond-tbl select'));
+ $(document).off('click.' + this.uuid);
+
+ $(document).off('keydown.' + this.uuid);
+ $(document).off('keyup.' + this.uuid);
+ }
+ /**
+ * Bind All Events
+ * - pandasObject select/change
+ * - use copy change
+ * - subset type change
+ * - tab change
+ * - row/column subset type change
+ * - row/column search value change
+ * - row/column indexing add/del button click
+ * - row/column slicing start/end value change
+ * - condition values change
+ * - condition add/del button click
+ */
+ _bindEvent() {
+ super._bindEvent();
+ var that = this;
+
+ if (this.targetSelector && this.targetSelector != '') {
+ // open popup
+ $(document).on('click', com_util.formatString('.{0}.{1}', VP_DS_BTN, this.uuid), function (event) {
+ if (!$(this).hasClass('disabled')) {
+ if (that.beforeOpen && typeof that.beforeOpen == 'function') {
+ that.beforeOpen(that);
+ }
+ that.open();
+ $(that.wrapSelector()).css({ 'z-index': 1205 }); // move forward
+ }
+ });
+
+ // co-op with parent Popup
+ $(this.targetSelector).on('remove_option_page', function(evt) {
+ that.close();
+ });
+ $(this.targetSelector).on('close_option_page', function(evt) {
+ that.close();
+ });
+ $(this.targetSelector).on('focus_option_page', function(evt) {
+ that.focus();
+ });
+ $(this.targetSelector).on('apply_option_page', function(evt) {
+ that.close();
+ });
+ }
+
+ // df selection/change
+ $(document).on('var_changed change', this.wrapSelector('.' + VP_DS_PANDAS_OBJECT), function (event) {
+ var varName = $(that.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).val();
+
+ if (that.state.pandasObject == varName
+ && that.state.dataType == event.dataType) {
+ // if newly selected object&type is same as before, do nothing.
+ return;
+ }
+
+ that.state.pandasObject = varName;
+ that.state.dataType = event.dataType ? event.dataType : that.state.dataType;
+ that.state.returnType = that.state.dataType;
+ that.state.rowList = [];
+ that.state.rowLimit = 10;
+ that.state.columnList = [];
+ that.state.rowPointer = { start: -1, end: -1 };
+ that.state.colPointer = { start: -1, end: -1 };
+
+ if (!varName || varName == '') {
+ that.loadRowList([]);
+ that.loadColumnList([]);
+ that.generateCode();
+ return;
+ }
+
+ that.loadSubsetType(that.state.dataType);
+ if (that.state.dataType == 'DataFrame') {
+ // get result and load column list
+ vpKernel.getColumnList(varName).then(function (resultObj) {
+ let { result } = resultObj;
+ var { list } = JSON.parse(result);
+ list = list.map(function (x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value,
+ isNumeric: x.is_numeric
+ };
+ });
+ that.loadColumnList(list);
+ that.bindDraggable('col');
+ that.generateCode();
+ });
+
+ // get result and load column list
+ let subsetVariable = com_util.formatString('{0}.iloc[:{1}]', varName, that.state.rowLimit);
+ vpKernel.getRowList(subsetVariable).then(function (resultObj) {
+ let { result } = resultObj;
+ var { list:rowList } = JSON.parse(result);
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value
+ };
+ });
+ // if iloc
+ if (that.state.subsetType == 'iloc') {
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ label: x.location + '',
+ value: x.location + '',
+ code: x.location + '',
+ };
+ });
+ }
+ that.loadRowList(rowList);
+ that.bindDraggable('row');
+ that.generateCode();
+ });
+
+ // show column box
+ if (that.useInputColumns != true) {
+ $(that.wrapSelector('.' + VP_DS_TAB_PAGE_BOX + '.subset-column')).show();
+ }
+ } else if (that.state.dataType == 'Series') {
+ // get result and load column list
+ let subsetVariable = com_util.formatString('{0}.iloc[:{1}]', varName, that.state.rowLimit);
+ vpKernel.getRowList(subsetVariable).then(function (resultObj) {
+ let { result } = resultObj;
+ var { list:rowList } = JSON.parse(result);
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ value: x.label,
+ code: x.value
+ };
+ });
+ // if iloc
+ if (that.state.subsetType == 'iloc') {
+ rowList = rowList.map(function (x) {
+ return {
+ ...x,
+ label: x.location + '',
+ value: x.location + '',
+ code: x.location + '',
+ };
+ });
+ }
+ that.loadRowList(rowList);
+ that.bindDraggable('row');
+ that.generateCode();
+ });
+
+ that.loadColumnList([]);
+
+ // hide to frame
+ $(that.wrapSelector('.' + VP_DS_TO_FRAME)).parent().hide();
+ // hide column box
+ $(that.wrapSelector('.' + VP_DS_TAB_PAGE_BOX + '.subset-column')).hide();
+ }
+ });
+
+ // use copy
+ $(document).on('change', this.wrapSelector('.' + VP_DS_USE_COPY), function (event) {
+ var checked = $(this).prop('checked');
+ that.state.useCopy = checked;
+
+ that.generateCode();
+ });
+
+ // subset type select
+ $(document).on('change', this.wrapSelector('.' + VP_DS_SUBSET_TYPE), function (event) {
+ var subsetType = $(this).val();
+ that.state.subsetType = subsetType;
+
+ that.reloadSubsetData();
+ });
+
+ // to frame
+ $(document).on('change', this.wrapSelector('.' + VP_DS_TO_FRAME), function (event) {
+ var checked = $(this).prop('checked');
+ that.state.toFrame = checked;
+ that.generateCode();
+ });
+
+ // allocate to
+ $(document).on('change', this.wrapSelector('.' + VP_DS_ALLOCATE_TO), function (evt) {
+ var allocateTo = $(this).val();
+ that.state.allocateTo = allocateTo;
+ that.generateCode();
+ });
+
+ // view all
+ $(document).on('change', this.wrapSelector('.' + VP_DS_DATA_VIEW_ALL), function (event) {
+ var checked = $(this).prop('checked');
+ that.state.viewAll = checked;
+
+ that.loadDataPage();
+ });
+
+ // row type selector
+ $(document).on('change', this.wrapSelector('.' + VP_DS_ROWTYPE), function (event) {
+ var rowType = $(this).val();
+ that.state.rowType = rowType;
+ // hide
+ $(that.wrapSelector('.' + VP_DS_ROWTYPE_BOX)).hide();
+ $(that.wrapSelector('.' + VP_DS_ROWTYPE_BOX + '.' + rowType)).show();
+
+ that.generateCode();
+ });
+
+ // column type selector
+ $(document).on('change', this.wrapSelector('.' + VP_DS_COLTYPE), function (event) {
+ var colType = $(this).val();
+ that.state.colType = colType;
+ // hide
+ $(that.wrapSelector('.' + VP_DS_COLTYPE_BOX)).hide();
+ $(that.wrapSelector('.' + VP_DS_COLTYPE_BOX + '.' + colType)).show();
+
+ that.generateCode();
+ });
+
+ // row indexing - timestamp
+ $(document).on('change', this.wrapSelector('.' + VP_DS_INDEXING_TIMESTAMP), function (event) {
+ that.generateCode();
+ });
+
+ // item indexing - search index
+ $(document).on('change', this.wrapSelector('.select-row .' + VP_DS_SELECT_SEARCH), function (event) {
+ var searchValue = $(this).val();
+
+ // filter added rows
+ var addedTags = $(that.wrapSelector('.select-row .' + VP_DS_SELECT_RIGHT + ' .' + VP_DS_SELECT_ITEM + '.added'));
+ var addedRowList = [];
+ for (var i = 0; i < addedTags.length; i++) {
+ var value = $(addedTags[i]).attr('data-rowname');
+ addedRowList.push(value);
+ }
+ var filteredRowList = that.state.rowList.filter(x => x.value.toString().includes(searchValue) && !addedRowList.includes(x.value.toString()));
+
+ // row indexing
+ that.renderRowSelectionBox(filteredRowList);
+
+ // draggable
+ that.bindDraggable('row');
+ });
+
+ // item indexing - search columns
+ $(document).on('change', this.wrapSelector('.select-col .' + VP_DS_SELECT_SEARCH), function (event) {
+ var searchValue = $(this).val();
+
+ // filter added columns
+ var addedTags = $(that.wrapSelector('.select-col .' + VP_DS_SELECT_RIGHT + ' .' + VP_DS_SELECT_ITEM + '.added'));
+ var addedColumnList = [];
+ for (var i = 0; i < addedTags.length; i++) {
+ var value = $(addedTags[i]).attr('data-colname');
+ addedColumnList.push(value);
+ }
+ var filteredColumnList = that.state.columnList.filter(x => x.value.includes(searchValue) && !addedColumnList.includes(x.value));
+
+ // column indexing
+ that.renderColumnSelectionBox(filteredColumnList);
+
+ // draggable
+ that.bindDraggable('col');
+ });
+
+ // item indexing
+ $(document).on('click', this.wrapSelector('.' + VP_DS_SELECT_ITEM), function (event) {
+ var dataIdx = $(this).attr('data-idx');
+ var idx = $(this).index();
+ var itemType = $(this).hasClass('select-row') ? 'row' : 'col';
+ var added = $(this).hasClass('added'); // right side added item?
+
+ var selector = '.select-' + itemType;
+
+ // remove selection for select box on the other side
+ if (added) {
+ // remove selection for left side
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + '.select-' + itemType + ':not(.added)')).removeClass('selected');
+ // set selector
+ selector += '.added';
+ } else {
+ // remove selection for right(added) side
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + '.select-' + itemType + '.added')).removeClass('selected');
+ // set selector
+ selector += ':not(.added)';
+ }
+
+ if (vpEvent.keyManager.keyCheck.ctrlKey) {
+ // multi-select
+ that.state[itemType + 'Pointer'] = { start: idx, end: -1 };
+ $(this).toggleClass('selected');
+ } else if (vpEvent.keyManager.keyCheck.shiftKey) {
+ // slicing
+ var startIdx = that.state[itemType + 'Pointer'].start;
+
+ if (startIdx == -1) {
+ // no selection
+ that.state[itemType + 'Pointer'] = { start: idx, end: -1 };
+ } else if (startIdx > idx) {
+ // add selection from idx to startIdx
+ var tags = $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector));
+ for (var i = idx; i <= startIdx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state[itemType + 'Pointer'] = { start: startIdx, end: idx };
+ } else if (startIdx <= idx) {
+ // add selection from startIdx to idx
+ var tags = $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector));
+ for (var i = startIdx; i <= idx; i++) {
+ $(tags[i]).addClass('selected');
+ }
+ that.state[itemType + 'Pointer'] = { start: startIdx, end: idx };
+ }
+ } else {
+ // single-select
+ that.state[itemType + 'Pointer'] = { start: idx, end: -1 };
+ // un-select others
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector)).removeClass('selected');
+ // select this
+ $(this).addClass('selected');
+ }
+ });
+
+ // item indexing - add all
+ $(document).on('click', this.wrapSelector('.' + VP_DS_SELECT_ADD_ALL_BTN), function (event) {
+ var itemType = $(this).hasClass('select-row') ? 'row' : 'col';
+ var selector = '.select-' + itemType;
+
+ $(that.wrapSelector('.' + VP_DS_SELECT_BOX + '.left .' + VP_DS_SELECT_ITEM + selector)).appendTo(
+ $(that.wrapSelector(selector + ' .' + VP_DS_SELECT_BOX + '.right'))
+ );
+ $(that.wrapSelector(selector + ' .' + VP_DS_SELECT_BOX + ' .' + VP_DS_SELECT_ITEM)).addClass('added');
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + '.selected')).removeClass('selected');
+ that.state[itemType + 'Pointer'] = { start: -1, end: -1 };
+
+ that.generateCode();
+ });
+
+ // item indexing - add
+ $(document).on('click', this.wrapSelector('.' + VP_DS_SELECT_ADD_BTN), function (event) {
+ var itemType = $(this).hasClass('select-row') ? 'row' : 'col';
+ var selector = '.select-' + itemType + '.selected';
+
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector)).appendTo(
+ $(that.wrapSelector('.select-' + itemType + ' .' + VP_DS_SELECT_BOX + '.right'))
+ );
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector)).addClass('added');
+ $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector)).removeClass('selected');
+ that.state[itemType + 'Pointer'] = { start: -1, end: -1 };
+
+ that.generateCode();
+ });
+
+ // item indexing - del
+ $(document).on('click', this.wrapSelector('.' + VP_DS_SELECT_DEL_BTN), function (event) {
+ var itemType = $(this).hasClass('select-row') ? 'row' : 'col';
+ var selector = '.select-' + itemType + '.selected';
+ var targetBoxQuery = that.wrapSelector('.select-' + itemType + ' .' + VP_DS_SELECT_BOX + '.left');
+
+ var selectedTag = $(that.wrapSelector('.' + VP_DS_SELECT_ITEM + selector));
+ selectedTag.appendTo(
+ $(targetBoxQuery)
+ );
+ // sort
+ $(targetBoxQuery + ' .' + VP_DS_SELECT_ITEM).sort(function (a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo(
+ $(targetBoxQuery)
+ );
+ selectedTag.removeClass('added');
+ selectedTag.removeClass('selected');
+ that.state[itemType + 'Pointer'] = { start: -1, end: -1 };
+
+ that.generateCode();
+ });
+
+ // item indexing - del all
+ $(document).on('click', this.wrapSelector('.' + VP_DS_SELECT_DEL_ALL_BTN), function (event) {
+ var itemType = $(this).hasClass('select-row') ? 'row' : 'col';
+ var selector = '.select-' + itemType;
+
+ var targetBoxQuery = that.wrapSelector(selector + ' .' + VP_DS_SELECT_BOX + '.left');
+ $(that.wrapSelector(selector + ' .' + VP_DS_SELECT_ITEM)).appendTo(
+ $(targetBoxQuery)
+ );
+ // sort
+ $(targetBoxQuery + ' .' + VP_DS_SELECT_ITEM).sort(function (a, b) {
+ return ($(b).data('idx')) < ($(a).data('idx')) ? 1 : -1;
+ }).appendTo(
+ $(targetBoxQuery)
+ );
+ $(that.wrapSelector(selector + ' .' + VP_DS_SELECT_ITEM)).removeClass('added');
+ $(that.wrapSelector(selector + ' .' + VP_DS_SELECT_ITEM)).removeClass('selected');
+ that.state[itemType + 'Pointer'] = { start: -1, end: -1 };
+
+ that.generateCode();
+ });
+
+ // row-column condition add
+ $(document).on('click', this.wrapSelector('.vp-add-col'), function (event) {
+ that.handleColumnAdd();
+
+ that.generateCode();
+ });
+
+ // row-column condition delete
+ $(document).on('click', this.wrapSelector('.vp-del-col'), function (event) {
+ event.stopPropagation();
+
+ var colList = $(that.wrapSelector('.' + VP_DS_CONDITION_TBL + ' tr td:not(:last)'));
+ // clear previous one
+ $(this).closest('tr').remove();
+ $(that.wrapSelector('.' + VP_DS_CONDITION_TBL + ' .vp-oper-connect:last')).hide();
+
+ that.generateCode();
+ });
+
+ // typing on slicing
+ $(document).on('change', this.wrapSelector('.vp-ds-slicing-box input'), function () {
+ $(this).data('code', $(this).val());
+ that.generateCode();
+ });
+
+ // change column selection for condition page
+ $(document).on('change', this.wrapSelector('.vp-ds-cond-tbl .vp-col-list'), function () {
+ var thisTag = $(this);
+ var varName = that.state.pandasObject;
+ var colName = $(this).find('option:selected').attr('data-code');
+ var colDtype = $(this).find('option:selected').attr('data-dtype');
+
+ var operTag = $(this).closest('td').find('.vp-oper-list');
+ var condTag = $(this).closest('td').find('.vp-condition');
+
+ if (colName == '.index') {
+ // index
+ $(thisTag).closest('td').find('.vp-cond-use-text').prop('checked', false);
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator('');
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput([], '');
+ });
+ that.generateCode();
+ } else {
+ // get result and load column list
+ vpKernel.getColumnCategory(varName, colName).then(function (resultObj) {
+ let { result } = resultObj;
+ try {
+ var category = JSON.parse(result);
+ if (category && category.length > 0 && colDtype == 'object') {
+ // if it's categorical column and its dtype is object, check 'Text' as default
+ $(thisTag).closest('td').find('.vp-cond-use-text').prop('checked', true);
+ } else {
+ $(thisTag).closest('td').find('.vp-cond-use-text').prop('checked', false);
+ }
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype);
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput(category, colDtype);
+ });
+ that.generateCode();
+ } catch {
+ $(thisTag).closest('td').find('.vp-cond-use-text').prop('checked', false);
+ $(operTag).replaceWith(function () {
+ return that.templateForConditionOperator(colDtype);
+ });
+ $(condTag).replaceWith(function () {
+ return that.templateForConditionCondInput([], colDtype);
+ });
+ that.generateCode();
+ }
+ });
+ }
+ });
+
+ // change operator selection
+ $(document).on('change', this.wrapSelector('.vp-ds-cond-tbl .vp-oper-list'), function () {
+ var oper = $(this).val();
+ var condTag = $(this).closest('td').find('.vp-condition');
+ var useTextTag = $(this).closest('td').find('.vp-cond-use-text');
+ // var colDtype = $(this).closest('td').find('.vp-col-list option:selected').attr('data-dtype');
+
+ // if operator is isnull(), notnull(), disable condition input
+ if (oper == 'isnull()' || oper == 'notnull()') {
+ $(condTag).prop('disabled', true);
+ $(useTextTag).prop('disabled', true);
+ } else {
+ $(condTag).prop('disabled', false);
+ $(useTextTag).prop('disabled', false);
+ }
+ });
+
+ // use text
+ $(document).on('change', this.wrapSelector('.vp-ds-cond-tbl .vp-cond-use-text'), function () {
+ that.generateCode();
+ });
+
+ // typing on condition
+ $(document).on('change', this.wrapSelector('.vp-ds-cond-tbl input[type="text"]'), function () {
+ that.generateCode();
+ });
+
+ $(document).on('change', this.wrapSelector('.vp-ds-cond-tbl select'), function () {
+ that.generateCode();
+ });
+ }
+ /**
+ * Handle Adding Condition
+ */
+ handleColumnAdd() {
+ var conditonBox = $(this.templateForConditionBox(this.state.columnList));
+
+ // hide last connect operator
+ conditonBox.find('.vp-oper-connect').hide();
+
+ // show connect operator right before last one
+ $(this.wrapSelector('.' + VP_DS_CONDITION_TBL + ' .vp-oper-connect:last')).show();
+ conditonBox.insertBefore(this.wrapSelector('.' + VP_DS_CONDITION_TBL + ' tr:last'));
+ }
+ /**
+ * Re-load subset data
+ * - trigger dataframe change event
+ */
+ reloadSubsetData() {
+ $(this.wrapSelector('.' + VP_DS_PANDAS_OBJECT)).trigger('var_changed');
+ }
+ /**
+ * Generate Code
+ * - default: # PREVIEW CODE
+ * - get 2 types of codes
+ * 1) rowSelection - indexing/slicing/condition code
+ * 2) colSelection - indexing/slicing code
+ * - consider 3 types of subset frame
+ * 1) subset - rowSelection & colSelection using 'indexing' type
+ * 2) loc - subset type 'loc'
+ * 3) iloc - subset type 'iloc'
+ * 4) query - subset type 'query'
+ * - consider use copy option
+ */
+ generateCodeForSubset(allocation = true, applyPreview = true) {
+ var code = new com_String();
+
+ // dataframe
+ if (this.state.pandasObject == '') {
+ // $(this.wrapSelector('.' + VP_DS_PREVIEW)).text('# PREVIEW CODE');
+ this.setPreview('# Code Preview');
+ return '';
+ }
+
+ // allocate to
+ if (allocation && this.state.allocateTo != '') {
+ code.appendFormat('{0} = ', this.state.allocateTo);
+ }
+
+ // object
+ code.append(this.state.pandasObject);
+
+ // row
+ var rowSelection = new com_String();
+ // depend on type
+ if (this.state.rowType == 'indexing') {
+ var rowTags = $(this.wrapSelector('.' + VP_DS_SELECT_ITEM + '.select-row.added:not(.moving)'));
+ if (rowTags.length > 0) {
+ var rowList = [];
+ for (var i = 0; i < rowTags.length; i++) {
+ var rowValue = $(rowTags[i]).data('code');
+ if (rowValue !== undefined) {
+ rowList.push(rowValue);
+ }
+ }
+ if (rowList.length == 1) {
+ // to Series when rowList's length is 1.
+ rowSelection.appendFormat('{0}', rowList.toString());
+ } else {
+ rowSelection.appendFormat('[{0}]', rowList.toString());
+ }
+ } else {
+ rowSelection.append(':');
+ }
+ } else if (this.state.rowType == 'slicing') {
+ let start = $(this.wrapSelector('.' + VP_DS_ROW_SLICE_START)).val();
+ let startText = $(this.wrapSelector('.vp-ds-row-slice-start-text')).prop('checked');
+ var end = $(this.wrapSelector('.' + VP_DS_ROW_SLICE_END)).val();
+ let endText = $(this.wrapSelector('.vp-ds-row-slice-end-text')).prop('checked');
+
+ rowSelection.appendFormat('{0}:{1}'
+ , start ? com_util.convertToStr(start, startText) : ''
+ , end ? com_util.convertToStr(end, endText) : '');
+ } else if (this.state.rowType == 'condition') {
+ // condition
+ var condList = $(this.wrapSelector('.' + VP_DS_CONDITION_TBL + ' tr td:not(:last)'));
+ var useCondition = false;
+ for (var i = 0; i < condList.length; i++) {
+ var colTag = $(condList[i]);
+ var varName = this.state.pandasObject;
+ var varType = this.state.dataType;
+ var colName = colTag.find('.vp-col-list').find('option:selected').data('code');
+ colName = colName ? colName : '';
+ var oper = colTag.find('.vp-oper-list').val();
+ var useText = colTag.find('.vp-cond-use-text').prop('checked');
+ var cond = colTag.find('.vp-condition').val();
+ var connector = i > 0 ? $(condList[i - 1]).find('.vp-oper-connect').val() : undefined;
+
+ // if no variable selected, pass
+ if (varName === "" || oper === "")
+ continue;
+ if (useCondition) {
+ rowSelection.append(connector);
+ }
+
+ if (this.state.subsetType == 'query') {
+ if (condList.length > 1) {
+ rowSelection.append('(');
+ }
+ let colValue = colTag.find('.vp-col-list').val();
+ if (colValue && colValue == '.index') {
+ colValue = 'index';
+ }
+ let condValue = cond;
+ // condition value as text
+ if (cond && useText) {
+ condValue = com_util.formatString("'{0}'", cond);
+ }
+ if (oper == 'contains') {
+ rowSelection.appendFormat('`{0}`.str.contains({1})', colValue, condValue);
+ } else if (oper == 'not contains') {
+ rowSelection.appendFormat('~`{0}`.str.contains({1})', colValue, condValue);
+ } else if (oper == 'starts with') {
+ rowSelection.appendFormat('`{0}`.str.startswith({1})', colValue, condValue);
+ } else if (oper == 'ends with') {
+ rowSelection.appendFormat('`{0}`.str.endswith({1})', colValue, condValue);
+ } else if (oper == 'isnull()' || oper == 'notnull()') {
+ rowSelection.appendFormat('`{0}`.{1}', colValue, oper);
+ } else {
+ rowSelection.appendFormat('`{0}`{1}{2}', colValue, oper != ''?(' ' + oper):'', condValue != ''?(' ' + condValue):'');
+ }
+ if (condList.length > 1) {
+ rowSelection.append(')');
+ }
+ } else {
+ if (varType == 'DataFrame') {
+ rowSelection.append('(');
+
+ let colValue = varName;
+ if (colName && colName != '') {
+ if (colName == '.index') {
+ colValue += colName;
+ } else {
+ colValue += com_util.formatString('[{0}]', colName);
+ }
+ }
+ let condValue = cond;
+ // condition value as text
+ if (cond && useText) {
+ condValue = com_util.formatString("'{0}'", cond);
+ }
+ if (oper == 'contains') {
+ rowSelection.appendFormat('{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'not contains') {
+ rowSelection.appendFormat('~{0}.str.contains({1})', colValue, condValue);
+ } else if (oper == 'starts with') {
+ rowSelection.appendFormat('{0}.str.startswith({1})', colValue, condValue);
+ } else if (oper == 'ends with') {
+ rowSelection.appendFormat('{0}.str.endswith({1})', colValue, condValue);
+ } else if (oper == 'isnull()' || oper == 'notnull()') {
+ rowSelection.appendFormat('{0}.{1}', colValue, oper);
+ } else {
+ rowSelection.appendFormat('{0}{1}{2}', colValue, oper != ''?(' ' + oper):'', condValue != ''?(' ' + condValue):'');
+ }
+ rowSelection.append(')');
+ } else {
+ rowSelection.appendFormat('({0}', varName);
+ if (colName == '.index') {
+ // index
+ rowSelection.append('.index');
+ }
+ oper && rowSelection.appendFormat(' {0}', oper);
+ if (cond) {
+ // condition value as text
+ if (useText) {
+ rowSelection.appendFormat(" '{0}'", cond);
+ } else {
+ rowSelection.appendFormat(" {0}", cond);
+ }
+ }
+ rowSelection.append(')');
+ }
+ }
+ useCondition = true;
+ }
+ if (rowSelection.toString() == '') {
+ rowSelection.append(':');
+ }
+ } else if (this.state.rowType == 'timestamp') {
+ var tsIndexing = $(this.wrapSelector('.' + VP_DS_INDEXING_TIMESTAMP)).val();
+ if (tsIndexing != '') {
+ rowSelection.appendFormat("'{0}'", tsIndexing);
+ } else {
+ rowSelection.appendFormat(":", tsIndexing);
+ }
+ } else {
+ rowSelection.append(':');
+ }
+
+ // columns
+ // selected colList
+ var colSelection = new com_String();
+
+ // hide to frame
+ $(this.wrapSelector('.' + VP_DS_TO_FRAME)).parent().hide();
+ if (this.state.dataType == 'DataFrame') {
+ if (this.state.colType == 'indexing') {
+ if (this.useInputColumns == true) {
+ colList = this.state.selectedColumns;
+ if (colList.length > 0) {
+ if (colList.length == 1) {
+ colSelection.appendFormat('{0}', colList.toString());
+ this.state.returnType = 'Series';
+ } else {
+ colSelection.appendFormat('[{0}]', colList.toString());
+ this.state.returnType = 'DataFrame';
+ }
+ }
+ } else {
+ var colTags = $(this.wrapSelector('.' + VP_DS_SELECT_ITEM + '.select-col.added:not(.moving)'));
+ if (colTags.length > 0) {
+ var colList = [];
+ for (var i = 0; i < colTags.length; i++) {
+ var colValue = $(colTags[i]).data('code');
+ if (colValue !== undefined) {
+ colList.push(colValue);
+ }
+ }
+
+ // hide/show to frame
+ if (colList.length == 1) {
+ $(this.wrapSelector('.' + VP_DS_TO_FRAME)).parent().show();
+
+ // to frame
+ if (this.state.toFrame === true) {
+ colSelection.appendFormat('[{0}]', colList.toString());
+ this.state.returnType = 'DataFrame';
+ } else {
+ colSelection.appendFormat('{0}', colList.toString());
+ this.state.returnType = 'Series';
+ }
+ } else {
+ colSelection.appendFormat('[{0}]', colList.toString());
+ this.state.returnType = 'DataFrame';
+ }
+
+ } else {
+ colSelection.append(':');
+ }
+ }
+ } else if (this.state.colType == 'slicing') {
+ var start = $(this.wrapSelector('.' + VP_DS_COL_SLICE_START)).data('code');
+ var end = $(this.wrapSelector('.' + VP_DS_COL_SLICE_END)).data('code');
+ colSelection.appendFormat('{0}:{1}', start ? start : '', end ? end : '');
+ }
+ }
+
+ // use simple selection
+ if ((rowSelection.toString() !== ':' && rowSelection.toString() !== '')
+ || (colSelection.toString() !== ':' && colSelection.toString() !== '')) {
+ if (this.state.subsetType == 'subset') {
+ if (rowSelection.toString() != ':' && rowSelection.toString() != '') {
+ code.appendFormat('[{0}]', rowSelection.toString());
+ }
+ if (colSelection.toString() != ':' && colSelection.toString() != '') {
+ code.appendFormat('[{0}]', colSelection.toString());
+ }
+ } else if (this.state.subsetType == 'loc') {
+ if (this.state.dataType == 'DataFrame') {
+ code.appendFormat('.loc[{0}, {1}]', rowSelection.toString(), colSelection.toString());
+ } else {
+ code.appendFormat('.loc[{0}]', rowSelection.toString());
+ }
+ } else if (this.state.subsetType == 'iloc') {
+ if (this.state.dataType == 'DataFrame') {
+ code.appendFormat('.iloc[{0}, {1}]', rowSelection.toString(), colSelection.toString());
+ } else {
+ code.appendFormat('.iloc[{0}]', rowSelection.toString());
+ }
+ } else if (this.state.subsetType == 'query') {
+ if (rowSelection.toString() != ':' && rowSelection.toString() != '') {
+ code.appendFormat('.query("{0}")', rowSelection.toString());
+ }
+ if (colSelection.toString() != ':' && colSelection.toString() != '') {
+ code.appendFormat('[{0}]', colSelection.toString());
+ }
+ }
+ }
+
+ // use copy
+ if (this.state.useCopy) {
+ code.append('.copy()');
+ }
+
+ if (applyPreview) {
+ this.setPreview(code.toString());
+ }
+
+ // display
+ if (this.useCell) {
+ if (allocation && this.state.allocateTo != '') {
+ code.appendLine();
+ code.append(this.state.allocateTo);
+ }
+ }
+ return code.toString();
+ }
+ setPreview(previewCodeStr) {
+ this.setCmValue('previewCode', previewCodeStr);
+ }
+
+ open() {
+ super.open();
+
+ if (this.useInputVariable) {
+ this.loadVariables();
+ this.reloadSubsetData();
+ }
+ if (this.useCell === false) {
+ // show save button only
+ this.setSaveOnlyMode();
+ }
+ // generate code after displaying page
+ // - codemirror can be set after display
+ this.generateCode();
+ }
+
+ //====================================================================
+ // Button to open Subset from other popup
+ //====================================================================
+
+ hideButton() {
+ if (this.useInputVariable === true || this.useAsModule === true) {
+ $(this.pageThis.wrapSelector('.' + VP_DS_BTN + '.' + this.uuid)).hide();
+ }
+ }
+
+ disableButton() {
+ if (this.useInputVariable === true || this.useAsModule === true) {
+ var buttonEle = $(this.pageThis.wrapSelector('.' + VP_DS_BTN + '.' + this.uuid));
+ if (!buttonEle.hasClass('disabled')) {
+ buttonEle.addClass('disabled');
+ }
+ }
+ }
+
+ enableButton() {
+ if (this.useInputVariable === true || this.useAsModule === true) {
+ $(this.pageThis.wrapSelector('.' + VP_DS_BTN + '.' + this.uuid)).removeClass('disabled');
+ }
+ }
+ showButton() {
+ if (this.useInputVariable === true || this.useAsModule === true) {
+ $(this.pageThis.wrapSelector('.' + VP_DS_BTN + '.' + this.uuid)).show();
+ }
+ }
+ }
+
+ // Temporary constant data
+ const VP_DS_BTN = 'vp-ds-button';
+ const VP_DS = 'vp-ds';
+ const VP_DS_CONTAINER = 'vp-ds-container';
+ const VP_DS_CLOSE = 'vp-ds-close';
+ const VP_DS_TITLE = 'vp-ds-title';
+ const VP_DS_BODY = 'vp-ds-body';
+
+ const VP_DS_PREVIEW = 'vp-ds-preview';
+
+ const VP_DS_LABEL = 'vp-ds-label';
+
+ const VP_DS_PANDAS_OBJECT_BOX = 'vp-ds-pandas-object-box';
+ const VP_DS_PANDAS_OBJECT = 'vp-ds-pandas-object';
+ const VP_DS_USE_COPY = 'vp-ds-use-copy';
+
+ const VP_DS_SUBSET_TYPE = 'vp-ds-subset-type';
+ const VP_DS_TO_FRAME = 'vp-ds-to-frame';
+
+ const VP_DS_ALLOCATE_TO = 'vp-ds-allocate-to';
+
+ /** tab selector */
+ const VP_DS_TAB_SELECTOR_BOX = 'vp-ds-tab-selector-box';
+ const VP_DS_TAB_SELECTOR_BTN = 'vp-ds-tab-selector-btn';
+ /** tab page */
+ const VP_DS_TAB_PAGE = 'vp-ds-tab-page';
+ const VP_DS_TAB_PAGE_BOX = 'vp-ds-tab-page-box';
+
+ const VP_DS_ROWCOL_SUBSET_TITLE = 'vp-ds-rowcol-subset-title';
+
+ const VP_DS_ROWTYPE = 'vp-ds-rowtype';
+ const VP_DS_ROWTYPE_BOX = 'vp-ds-rowtype-box';
+
+ /** indexing timestamp */
+ const VP_DS_INDEXING_TIMESTAMP = 'vp-ds-indexing-timestamp';
+
+ /** select */
+ const VP_DS_SELECT_CONTAINER = 'vp-ds-select-container';
+ const VP_DS_SELECT_LEFT = 'vp-ds-select-left';
+ const VP_DS_SELECT_BTN_BOX = 'vp-ds-select-btn-box';
+ const VP_DS_SELECT_RIGHT = 'vp-ds-select-right';
+
+ const VP_DS_SELECT_BOX = 'vp-ds-select-box';
+ const VP_DS_SELECT_ITEM = 'vp-ds-select-item';
+
+ /** select left */
+ const VP_DS_SELECT_SEARCH = 'vp-ds-select-search';
+ const VP_DS_DROPPABLE = 'vp-ds-droppable';
+ const VP_DS_DRAGGABLE = 'vp-ds-draggable';
+
+ /** select btns */
+ const VP_DS_SELECT_ADD_ALL_BTN = 'vp-ds-select-add-all-btn';
+ const VP_DS_SELECT_ADD_BTN = 'vp-ds-select-add-btn';
+ const VP_DS_SELECT_DEL_BTN = 'vp-ds-select-del-btn';
+ const VP_DS_SELECT_DEL_ALL_BTN = 'vp-ds-select-del-all-btn';
+
+ /** slicing box */
+ const VP_DS_SLICING_BOX = 'vp-ds-slicing-box';
+
+ /** row slice */
+ const VP_DS_ROW_SLICE_START = 'vp-ds-row-slice-start';
+ const VP_DS_ROW_SLICE_END = 'vp-ds-row-slice-end';
+
+ /** row condition */
+ const VP_DS_CONDITION_TBL = 'vp-ds-cond-tbl';
+ const VP_DS_BUTTON_ADD_CONDITION = 'vp-ds-btn-add-condition';
+
+ /** column selection/slicing */
+ const VP_DS_COLTYPE = 'vp-ds-coltype';
+ const VP_DS_COLTYPE_BOX = 'vp-ds-coltype-box';
+
+ /** column slice */
+ const VP_DS_COL_SLICE_START = 'vp-ds-col-slice-start';
+ const VP_DS_COL_SLICE_END = 'vp-ds-col-slice-end';
+
+ /** data view */
+ const VP_DS_DATA = 'vp-ds-data';
+ const VP_DS_DATA_TITLE = 'vp-ds-data-title';
+ const VP_DS_DATA_CONTENT = 'vp-ds-data-content';
+
+ const VP_DS_DATA_VIEW_ALL_DIV = 'vp-ds-data-view-all-div';
+ const VP_DS_DATA_VIEW_ALL = 'vp-ds-data-view-all';
+ const VP_DS_DATA_VIEW_BOX = 'vp-ds-data-view-box';
+
+ return Subset;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Sweetviz.js b/visualpython/js/m_apps/Sweetviz.js
new file mode 100644
index 00000000..2059189c
--- /dev/null
+++ b/visualpython/js/m_apps/Sweetviz.js
@@ -0,0 +1,370 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Sweetviz.js
+ * Author : Black Logic
+ * Note : Apps > Sweetviz
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Sweetviz
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/sweetviz.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/sweetviz'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/FileNavigation'
+], function(svHtml, svCss, com_Const, com_String, com_interface, PopupComponent, SuggestInput, FileNavigation) {
+
+ const PROFILE_TYPE = {
+ NONE: -1,
+ GENERATE: 1
+ }
+
+ const LIST_MENU_ITEM = {
+ SHOW: 'show',
+ DELETE: 'delete',
+ SAVE: 'save'
+ }
+
+ /**
+ * Sweetviz
+ */
+ class Sweetviz extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.installButton = true;
+ this.config.importButton = true;
+ this.config.codeview = false;
+ this.config.dataview = false;
+ this.config.runButton = false;
+ this.config.size = { width: 500, height: 500 };
+ this.config.checkModules = ['sweetviz'];
+
+ this.selectedReport = '';
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(this.wrapSelector('.vp-sv-df-refresh')).off('click');
+ $(this.wrapSelector('#vp_pfPathButton')).off('click');
+ $(this.wrapSelector('.vp-sv-menu-item')).off('click');
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+
+ // refresh df
+ $(this.wrapSelector('.vp-sv-df-refresh')).on('click', function() {
+ that.loadVariableList();
+ });
+
+ // click path
+ $(this.wrapSelector('#vp_pfPathButton')).on('click', function() {
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: ['html'],
+ finish: function(filesPath, status, error) {
+ let {file, path} = filesPath[0];
+
+ // set text
+ $(that.wrapSelector('#vp_pfPath')).data('file', file);
+ $(that.wrapSelector('#vp_pfPath')).val(path);
+ }
+ });
+ fileNavi.open();
+ });
+
+ // click menu
+ $(this.wrapSelector('.vp-sv-menu-item')).on('click', function() {
+ // check required filled
+ if (that.checkRequiredOption() === false) {
+ return ;
+ }
+
+ var type = $(this).data('type');
+ var df = $(that.wrapSelector('#vp_pfVariable')).val();
+ var saveas = $(that.wrapSelector('#vp_pfReturn')).val();
+ if (saveas == '') {
+ saveas = '_vp_sweetviz';
+ }
+ var title = $(that.wrapSelector('#vp_pfTitle')).val();
+ var filePath = $(that.wrapSelector('#vp_pfPath')).val();
+ // var openBrowser = $(that.wrapSelector('#vp_pfOpenBrowser')).prop('checked');
+ var code = new com_String();
+ switch(parseInt(type)) {
+ case PROFILE_TYPE.GENERATE:
+ // generate with/out title
+ if (title && title != '') {
+ code.appendFormatLine("{0} = sweetviz.analyze([{1}, '{2}'])", saveas, df, title);
+ } else {
+ code.appendFormatLine("{0} = sweetviz.analyze({1})", saveas, df);
+ }
+ // show notebook
+ code.appendFormat("{0}.show_notebook(", saveas);
+ if (filePath && filePath != '') {
+ code.appendFormat("filepath='{0}'", filePath);
+ }
+ // if (openBrowser === false) {
+ // code.append(", open_browser=False");
+ // }
+ code.appendLine(')');
+ code.append(saveas);
+ break;
+ }
+ that.checkAndRunModules(true).then(function() {
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Sweetviz');
+ that.loadReportList();
+ });
+ });
+ }
+
+ bindReportListEvent() {
+ let that = this;
+ // click list item menu
+ $(this.wrapSelector('.vp-sv-list-menu-item')).off('click');
+ $(this.wrapSelector('.vp-sv-list-menu-item')).on('click', function(evt) {
+ var menu = $(this).data('menu');
+ var itemTag = $(this).closest('.vp-sv-list-item');
+ var varName = $(itemTag).data('name');
+
+ var code = new com_String();
+ switch(menu) {
+ case LIST_MENU_ITEM.SHOW:
+ code.appendFormat("{0}.show_notebook()", varName);
+ break;
+ case LIST_MENU_ITEM.DELETE:
+ code.appendFormat("del {0}", varName);
+ break;
+ case LIST_MENU_ITEM.SAVE:
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: ['html'],
+ fileName: 'report',
+ finish: function(filesPath, status, error) {
+ filesPath.forEach( fileObj => {
+ var fileName = fileObj.file;
+ var path = fileObj.path;
+ if (varName == '') {
+ varName = '_vp_sweetviz';
+ }
+ var code = new com_String();
+ code.appendFormat("{0}.show_html(filepath='{1}')", varName, path);
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Sweetviz');
+
+ that.selectedReport = '';
+ });
+ }
+ });
+ fileNavi.open();
+ return;
+ default:
+ return;
+ }
+ com_interface.insertCell('code', code.toString(), true, 'Data Analysis > Sweetviz');
+ that.loadReportList();
+ });
+ }
+
+ templateForBody() {
+ return svHtml;
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariableList();
+ this.loadReportList();
+ this.checkInstalled();
+ }
+
+ generateInstallCode() {
+ return [
+ '!pip install sweetviz'
+ ];
+ }
+
+ generateImportCode() {
+ return [
+ 'import sweetviz'
+ ];
+ }
+
+ generateCode() {
+ return "";
+ }
+
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ try {
+ let { result, msg } = resultObj;
+ var varList = JSON.parse(result);
+ // render variable list
+ // replace
+ $(that.wrapSelector('#vp_pfVariable')).replaceWith(function() {
+ return that.templateForVariableList(varList);
+ });
+ $(that.wrapSelector('#vp_pfVariable')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Sweetviz:', result);
+ }
+ });
+ }
+
+ templateForVariableList(varList) {
+ var beforeValue = $(this.wrapSelector('#vp_pfVariable')).val();
+ if (beforeValue == null) {
+ beforeValue = '';
+ }
+
+ let mappedList = varList.map(obj => { return { label: obj.varName, value: obj.varName, dtype: obj.varType } });
+
+ var variableInput = new SuggestInput();
+ variableInput.setComponentID('vp_pfVariable');
+ variableInput.addClass('vp-sv-select');
+ variableInput.setPlaceholder('Select variable');
+ variableInput.setSuggestList(function () { return mappedList; });
+ variableInput.setNormalFilter(true);
+ variableInput.addAttribute('required', true);
+ variableInput.setValue(beforeValue);
+
+ return variableInput.toTagString();
+ }
+
+ /**
+ * Toggle check button state
+ * @param {String} mode install/checking/installed
+ */
+ toggleCheckState(mode='checking') {
+ let message = 'Checking...';
+ let disable = true;
+ switch (mode) {
+ case 'install':
+ message = 'Install';
+ disable = false;
+ break;
+ case 'installed':
+ message = 'Installed';
+ disable = true;
+ break;
+ case 'installing':
+ message = 'Installing';
+ disable = true;
+ break;
+ }
+ $(this.wrapSelector('.vp-sv-install-btn')).text(message);
+ if (disable) {
+ // set state as 'Checking'
+ // set disabled
+ if (!$(this.wrapSelector('.vp-sv-install-btn')).hasClass('disabled')) {
+ $(this.wrapSelector('.vp-sv-install-btn')).addClass('disabled');
+ }
+ } else {
+ // set enabled
+ $(this.wrapSelector('.vp-sv-install-btn')).removeClass('disabled');
+ }
+ }
+
+ checkInstalled() {
+ var that = this;
+ // set state as 'Checking'
+ this.toggleCheckState();
+ this.checking = true;
+
+ // check installed
+ let code = "_vp_print(_vp_check_package_list(['sweetviz']))";
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, msg } = resultObj;
+ if (!that.checking) {
+ return;
+ }
+ let installed = result['sweetviz'].installed;
+ if (installed === false) {
+ that.toggleCheckState('install');
+ } else {
+ that.toggleCheckState('installed');
+ }
+ that.checking = false;
+ }).catch(function(err) {
+ that.toggleCheckState('install');
+ that.checking = false;
+ });
+ }
+
+ loadReportList() {
+ var that = this;
+ // load using kernel
+ vpKernel.getSweetvizList().then(function(resultObj) {
+ try {
+ let { result } = resultObj;
+ var varList = JSON.parse(result);
+ // render variable list
+ // replace
+ $(that.wrapSelector('.vp-sv-list-box')).replaceWith(function() {
+ return that.renderReportList(varList);
+ });
+
+ that.bindReportListEvent();
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'Sweetviz:', result);
+ // console.log(ex);
+ }
+ });
+ }
+
+ renderReportList = function(reportList=[]) {
+ var page = new com_String();
+ page.appendFormatLine('', 'vp-sv-list-box');
+ page.appendFormatLine('
', 'vp-sv-list-header');
+ page.appendFormatLine('
{1}
', 'vp-sv-list-header-item', 'Allocated to');
+ page.appendFormatLine('
{1}
', 'vp-sv-list-header-item', 'Report Title');
+ page.appendFormatLine('
{1}
', 'vp-sv-list-header-item', '');
+ page.appendLine('
');
+ page.appendFormatLine('
', 'vp-apiblock-scrollbar');
+ page.appendFormatLine('
', 'vp-sv-list-body', 'vp-apiblock-scrollbar');
+ reportList.forEach((report, idx) => {
+ var { varName, title } = report;
+ page.appendFormatLine('
', 'vp-sv-list-item', varName, title);
+ page.appendFormatLine('
{0}
', varName);
+ page.appendFormatLine('
{0}
', title);
+ // button box
+ page.appendFormatLine('
', 'vp-sv-list-button-box');
+ // LAB: img to url
+ // page.appendFormatLine('
'
+ // , 'vp-sv-list-menu-item', LIST_MENU_ITEM.SHOW, 'Show report', com_Const.IMAGE_PATH + 'snippets/run.svg');
+ // page.appendFormatLine('
'
+ // , 'vp-sv-list-menu-item', LIST_MENU_ITEM.DELETE, 'Delete report', com_Const.IMAGE_PATH + 'delete.svg');
+ // page.appendFormatLine('
'
+ // , 'vp-sv-list-menu-item', LIST_MENU_ITEM.SAVE, 'Save report', com_Const.IMAGE_PATH + 'snippets/export.svg');
+ page.appendFormatLine('
'
+ , 'vp-sv-list-menu-item', 'vp-icon-run', LIST_MENU_ITEM.SHOW, 'Show report');
+ page.appendFormatLine('
'
+ , 'vp-sv-list-menu-item', 'vp-icon-delete', LIST_MENU_ITEM.DELETE, 'Delete report');
+ page.appendFormatLine('
'
+ , 'vp-sv-list-menu-item', 'vp-icon-export', LIST_MENU_ITEM.SAVE, 'Save report');
+ page.appendLine('
');
+ page.appendLine('
');
+ });
+ page.appendLine('
'); // VP_PF_LIST_BODY
+ page.appendLine('
');
+ page.appendLine('
'); // 'vp-sv-list-box'
+ return page.toString();
+ }
+
+ }
+
+ return Sweetviz;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_apps/Variable.js b/visualpython/js/m_apps/Variable.js
new file mode 100644
index 00000000..a0dd92d7
--- /dev/null
+++ b/visualpython/js/m_apps/Variable.js
@@ -0,0 +1,156 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Variable.js
+ * Author : Black Logic
+ * Note : Apps > Variable
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Variable
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_apps/variable.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_apps/variable'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(varHtml, varCss, com_String, PopupComponent) {
+
+ /**
+ * Variable
+ */
+ class Variable extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 3;
+
+ this.state = {
+ variable: '',
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // load variables on refresh
+ $(this.wrapSelector('#vp_varRefresh')).click(function(event) {
+ event.stopPropagation();
+ that.loadVariables();
+ });
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ return varHtml;
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariables();
+ }
+
+ generateCode() {
+ return this.state.variable;
+ }
+
+ loadVariables() {
+ var that = this;
+
+ // Searchable variable types
+ var types = [
+ ...vpConfig.getDataTypes(),
+ // ML Data types
+ ...vpConfig.getMLDataTypes()
+ ];
+
+ var tagTable = this.wrapSelector('#vp_var_variableBox table tbody');
+
+ // variable list table
+ var tagDetailTable = this.wrapSelector("#vp_varDetailTable");
+
+ // initialize tags
+ $(tagTable).find('tr').remove();
+ $(tagDetailTable).html('');
+
+ // HTML rendering
+ vpKernel.getDataList(types).then(function(resultObj) {
+ let varListStr = resultObj.result;
+ var varList = JSON.parse(varListStr);
+
+ // add variable list in table
+ varList.forEach((varObj, idx) => {
+ if (types.includes(varObj.varType) && varObj.varName[0] !== '_') {
+ let selected = false;
+ if ((that.state.variable == varObj.varName)) {
+ selected = true;
+ }
+ var tagTr = document.createElement('tr');
+ var tagTdName = document.createElement('td');
+ var tagTdType = document.createElement('td');
+ $(tagTr).attr({
+ 'data-var-name': varObj.varName,
+ 'data-var-type': varObj.varType,
+ 'class': selected?'vp-selected':''
+ });
+ tagTdName.innerText = varObj.varName;
+ tagTdType.innerText = varObj.varType;
+
+ $(tagTr).append(tagTdName);
+ $(tagTr).append(tagTdType);
+
+ // variable click
+ $(tagTr).click(function() {
+ $(this).parent().find('tr').removeClass('vp-selected');
+ $(this).addClass('vp-selected');
+ that.state.variable = varObj.varName;
+
+ // show variable information on clicking variable
+ vpKernel.execute(varObj.varName).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ var textResult = msg.content.data["text/plain"];
+ var htmlResult = msg.content.data["text/html"];
+ var imgResult = msg.content.data["image/png"];
+
+ $(tagDetailTable).html('');
+ if (htmlResult != undefined) {
+ // 1. HTML tag
+ $(tagDetailTable).append(htmlResult);
+ } else if (imgResult != undefined) {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $(tagDetailTable).append(imgTag);
+ } else if (textResult != undefined) {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(textResult);
+ $(tagDetailTable).html(preTag);
+ } else {
+ $(tagDetailTable).append('(Select variables to preview the data.)');
+ }
+ });
+ });
+
+ $(tagTable).append(tagTr);
+ }
+ });
+
+ if ($(that.wrapSelector('.vp-selected')).length == 0) {
+ $(that.wrapSelector('#vp_var_variableBox tbody tr:nth(0)')).addClass('vp-selected');
+ }
+
+ // trigger click of selected variable
+ $(that.wrapSelector('.vp-selected')).click();
+ });
+ }
+ }
+
+ return Variable;
+});
\ No newline at end of file
diff --git a/src/common/component/__init__.py b/visualpython/js/m_apps/__init__.py
similarity index 100%
rename from src/common/component/__init__.py
rename to visualpython/js/m_apps/__init__.py
diff --git a/src/common/template/__init__.py b/visualpython/js/m_library/__init__.py
similarity index 100%
rename from src/common/template/__init__.py
rename to visualpython/js/m_library/__init__.py
diff --git a/src/component/__init__.py b/visualpython/js/m_library/m_matplotlib/__init__.py
similarity index 100%
rename from src/component/__init__.py
rename to visualpython/js/m_library/m_matplotlib/__init__.py
diff --git a/visualpython/js/m_library/m_matplotlib/figure.js b/visualpython/js/m_library/m_matplotlib/figure.js
new file mode 100644
index 00000000..7fd6429e
--- /dev/null
+++ b/visualpython/js/m_library/m_matplotlib/figure.js
@@ -0,0 +1,306 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : figure.js
+ * Author : Black Logic
+ * Note : Library Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Figure
+//============================================================================
+define([
+ 'vp_base/js/com/component/LibraryComponent',
+ 'vp_base/js/com/component/VarSelector'
+], function(LibraryComponent, VarSelector) {
+ /**
+ * Figure
+ */
+ class Figure extends LibraryComponent {
+ _init() {
+ super._init();
+
+ this.state = {
+ subplotsRows: '',
+ subplotsCols: '',
+ o0: 'figure',
+ figsize: '',
+ ...this.state
+ }
+
+ this.package = {
+ name: 'plt.subplots()',
+ code: '${o0}, ax = plt.subplots(${subplotsRows}, ${subplotsCols}${v})',
+ input: [
+ {
+ name: 'subplotsRows',
+ type: 'int',
+ label: 'Number of Rows',
+ component: 'input_single'
+ },
+ {
+ name: 'subplotsCols',
+ type: 'int',
+ label: 'Number of Columns',
+ component: 'input_single'
+ }
+ ],
+ output: [
+ {
+ name: 'o0',
+ type: 'var',
+ label: 'Figure Variable',
+ component: 'input_single',
+ required: true
+ }
+ ],
+ variable: [
+ {
+ name: 'figsize',
+ type: 'var'
+ }
+ ]
+ };
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+
+ var that = this;
+
+ // add subplot box on changing subplots row/column
+ $(this.wrapSelector('#subplotsRows')).change(function() {
+ var row = $(that.wrapSelector('#subplotsRows')).val() * 1;
+ var col = $(that.wrapSelector('#subplotsCols')).val() * 1;
+ // nothing entered, set 1
+ if (row == 0) row = 1;
+ if (col == 0) col = 1;
+
+ $(that.wrapSelector('#subplotsRowsRange')).val(row);
+
+ $(that.wrapSelector('#vp_subplotsGrid')).attr('data-row', row);
+ $(that.wrapSelector('#vp_subplotsGrid')).css('height', 80 * row + 'px');
+ $(that.wrapSelector('#vp_subplotsGrid')).css('grid-template-rows', 'repeat(' + row + ', 1fr)');
+
+ $(that.wrapSelector('#vp_subplotsGrid')).html('');
+
+ for (var i = 0; i < row * col; i++) {
+ var div = document.createElement('div');
+ var r = parseInt(i / col);
+ var c = i % col;
+ $(div).attr({
+ 'class': 'grid-item',
+ 'data-idx': i,
+ 'data-row': r,
+ 'data-col': c
+ });
+
+ var position = i;
+ if (row > 1 && col > 1) {
+ position = r + ', ' + c;
+ }
+ $(div).text('[' + position + ']');
+ $(div).click(function(evt) { that.subplotBoxClickHandler(that, evt); });
+ $(that.wrapSelector('#vp_subplotsGrid')).append(div);
+ }
+
+ // initialize subplot value
+ that.selectedIdx = '0';
+ if (row > 1 && col > 1) {
+ that.selectedIdx = '0, 0';
+ }
+ that.subplotOption = [];
+ // add space for subplot
+ for (var i = 0; i < row * col; i++) {
+ that.subplotOption.push({idx: i});
+ }
+ });
+
+ $(this.wrapSelector('#subplotsCols')).change(function() {
+ var row = $(that.wrapSelector('#subplotsRows')).val() * 1;
+ var col = $(that.wrapSelector('#subplotsCols')).val() * 1;
+ // nothing entered, set 1
+ if (row == 0) row = 1;
+ if (col == 0) col = 1;
+
+ $(that.wrapSelector('#subplotsColsRange')).val(col);
+
+ $(that.wrapSelector('#vp_subplotsGrid')).attr('data-col', col);
+ $(that.wrapSelector('#vp_subplotsGrid')).css('width', 80 * col + 'px');
+ $(that.wrapSelector('#vp_subplotsGrid')).css('grid-template-columns', 'repeat(' + col + ', 1fr)');
+
+ $(that.wrapSelector('#vp_subplotsGrid')).html('');
+
+ for (var i = 0; i < row * col; i++) {
+ var div = document.createElement('div');
+ var r = parseInt(i / col);
+ var c = i % col;
+ $(div).attr({
+ 'class': 'grid-item',
+ 'data-idx': i,
+ 'data-row': r,
+ 'data-col': c
+ });
+
+ var position = i;
+ if (row > 1 && col > 1) {
+ position = r + ', ' + c;
+ }
+ $(div).text('[' + position + ']');
+ $(div).click(function(evt) { that.subplotBoxClickHandler(that, evt); });
+ $(that.wrapSelector('#vp_subplotsGrid')).append(div);
+ }
+
+ // initialize subplot value
+ that.selectedIdx = '0';
+ if (row > 1 && col > 1) {
+ that.selectedIdx = '0, 0';
+ }
+ that.subplotOption = [];
+ // add space for subplot
+ for (var i = 0; i < row * col; i++) {
+ that.subplotOption.push({idx: i});
+ }
+ });
+
+
+ // subplot 위치 버튼 클릭 시 해당 subplot의 옵션 설정을 위해 다음 페이지로 이동
+ // 참고 : vpContainer.js > tabPageShow($(this).index());
+ // - #vp_subplot span[data-caption-id="vp_functionDetail"]
+ // - #vp_subplotOptional span[data-caption-id="vp_functionDetail"]
+ $(this.wrapSelector('#vp_subplotsGrid div')).click(function (evt) {
+ that.subplotBoxClickHandler(that, evt);
+ });
+
+ // range 변경 시 값 표시
+ $(this.wrapSelector('#subplotsRowsRange')).change(function() {
+ var value = $(this).val();
+ $(that.wrapSelector('#subplotsRows')).val(value);
+ $(that.wrapSelector('#subplotsRows')).change();
+ });
+ $(this.wrapSelector('#subplotsColsRange')).change(function() {
+ var value = $(this).val();
+ $(that.wrapSelector('#subplotsCols')).val(value);
+ $(that.wrapSelector('#subplotsCols')).change();
+ });
+
+
+ }
+
+ bindCmapSelector() {
+ // 기존 cmap 선택하는 select 태그 안보이게
+ var cmapSelector = this.wrapSelector('#cmap');
+ $(cmapSelector).hide();
+
+ // cmap 데이터로 팔레트 div 동적 구성
+ this.cmap.forEach(ctype => {
+ var divColor = document.createElement('div');
+ $(divColor).attr({
+ 'class': 'vp-plot-cmap-item',
+ 'data-cmap': ctype,
+ 'data-url': 'pandas/cmap/' + ctype + '.JPG',
+ 'title': ctype
+ });
+ $(divColor).text(ctype);
+ // 이미지 url 바인딩
+ var url = Jupyter.notebook.base_url + vpConst.BASE_PATH + vpConst.RESOURCE_PATH + 'pandas/cmap/' + ctype + '.JPG';
+ $(divColor).css({
+ 'background-image' : 'url(' + url + ')'
+ })
+
+ var selectedCmap = this.wrapSelector('#vp_selectedCmap');
+
+ // 선택 이벤트 등록
+ $(divColor).click(function() {
+ if (!$(this).hasClass('selected')) {
+ $(this).parent().find('.vp-plot-cmap-item.selected').removeClass('selected');
+ $(this).addClass('selected');
+ // 선택된 cmap 이름 표시
+ $(selectedCmap).text(ctype);
+ // 선택된 cmap data-caption-id 변경
+ $(selectedCmap).attr('data-caption-id', ctype);
+ // select 태그 강제 선택
+ $(cmapSelector).val(ctype).prop('selected', true);
+ }
+ });
+ $(this.wrapSelector('#vp_plotCmapSelector')).append(divColor);
+ });
+
+ // 선택 이벤트
+ $(this.wrapSelector('.vp-plot-cmap-wrapper')).click(function() {
+ $(this).toggleClass('open');
+ });
+ }
+
+ templateForBody() {
+ return `
+
+
+ Allocate to
+
+
+
+
+
+ Figure Size
+
+
+
`;
+ }
+ render() {
+ super.render();
+
+ // add var selector
+ var varSelector = new VarSelector(['DataFrame', 'Series', 'Index'], 'DataFrame', false);
+ varSelector.setComponentId('i0');
+ varSelector.addClass('vp-state');
+ varSelector.setUseColumn(true);
+ varSelector.setValue(this.state.i0);
+ $(this.wrapSelector('#i0')).replaceWith(varSelector.render());
+ }
+
+ subplotBoxClickHandler(that, event) {
+ var target = event.target;
+ var parent = $(target).parent();
+
+ // 다음 옵션 페이지 이동
+ var thisPageIdx = $(target).closest(vpConst.OPTION_PAGE).index();
+ vpContainer.tabPageShow(thisPageIdx + 1);
+
+ // 다음 옵션 페이지의 위치 설명란에 [0,0] 표기
+ var row = $(target).data('row');
+ var col = $(target).data('col');
+
+ // 표기 : row나 col이 하나라도 1이면 1차원, 그 이상이면 2차원 배열로 접근
+ var position = $(target).data('idx');
+ var rowLen = $(parent).data('row') * 1;
+ var colLen = $(parent).data('col') * 1;
+
+ if (rowLen > 1 && colLen > 1) { // TODO: parent().data-row / data-col 받아와야댐
+ position = row + ', ' + col;
+ }
+ // 선택한 서브플롯 인덱스 설정
+ that.selectedIdx = position + '';
+
+ $(that.wrapSelector('span[data-caption-id="pageTitle"]'))[1].innerText = 'Subplot [' + position + '] Setting';
+ $(that.wrapSelector('span[data-caption-id="pageTitle"]'))[2].innerText = 'Subplot [' + position + '] Add Chart';
+ }
+ }
+
+ return Figure;
+});
\ No newline at end of file
diff --git a/src/component/fileNavigation/__init__.py b/visualpython/js/m_library/m_numpy/__init__.py
similarity index 100%
rename from src/component/fileNavigation/__init__.py
rename to visualpython/js/m_library/m_numpy/__init__.py
diff --git a/visualpython/js/m_library/m_numpy/array.js b/visualpython/js/m_library/m_numpy/array.js
new file mode 100644
index 00000000..705d7ac9
--- /dev/null
+++ b/visualpython/js/m_library/m_numpy/array.js
@@ -0,0 +1,50 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : array.js
+ * Author : Black Logic
+ * Note : array
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] NpArray
+//============================================================================
+define([
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/NumpyComponent'
+], function(com_util, com_Const, com_String, NumpyComponent) {
+
+ /**
+ * NpArray
+ */
+ class NpArray extends NumpyComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ return 'This is sample.';
+ }
+
+ generateCode() {
+ return "print('sample code')";
+ }
+
+ }
+
+ return NpArray;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_library/m_pandas/PandasPlot.js b/visualpython/js/m_library/m_pandas/PandasPlot.js
new file mode 100644
index 00000000..9d246f29
--- /dev/null
+++ b/visualpython/js/m_library/m_pandas/PandasPlot.js
@@ -0,0 +1,80 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : PandasPlot.js
+ * Author : Black Logic
+ * Note : Library Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 06. 22
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] PandasPlot
+//============================================================================
+define([
+ 'vp_base/js/com/component/LibraryComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/com_util'
+], function(LibraryComponent, DataSelector, com_util) {
+ /**
+ * PandasPlot
+ */
+ class PandasPlot extends LibraryComponent {
+ _init() {
+ super._init();
+
+ this.state = {
+ i0: '',
+ o0: '',
+ figWidth: '',
+ figHeight: '',
+ ...this.state
+ }
+ }
+
+ _bindEventAfterRender() {
+ let that = this;
+
+ $(this.wrapSelector('#figWidth')).on('blur', function() {
+ let width = $(this).val();
+ let height = $(that.wrapSelector('#figHeight')).val();
+
+ if (width !== '' || height !== '') {
+ $(that.wrapSelector('#figsize')).val(com_util.formatString('({0},{1})', width, height));
+ } else {
+ $(that.wrapSelector('#figsize')).val('');
+ }
+ });
+ $(this.wrapSelector('#figHeight')).on('blur', function() {
+ let width = $(that.wrapSelector('#figWidth')).val();
+ let height = $(this).val();
+
+ if (width !== '' || height !== '') {
+ $(that.wrapSelector('#figsize')).val(com_util.formatString('({0},{1})', width, height));
+ } else {
+ $(that.wrapSelector('#figsize')).val('');
+ }
+ });
+ }
+
+ render() {
+ super.render();
+
+ // add data selector
+ let dataSelector = new DataSelector({ pageThis: this, id: 'i0', value: this.state.i0, required: true });
+ $(this.wrapSelector('#i0')).replaceWith(dataSelector.toTagString());
+
+ // divide figure size option to width / height
+ let figSizeTemplate = `
+
+ `
+ $(this.wrapSelector('#figsize')).hide();
+ $(this.wrapSelector('#figsize')).parent().append(figSizeTemplate);
+
+ this._bindEventAfterRender();
+ }
+ }
+
+ return PandasPlot;
+});
\ No newline at end of file
diff --git a/src/container/__init__.py b/visualpython/js/m_library/m_pandas/__init__.py
similarity index 100%
rename from src/container/__init__.py
rename to visualpython/js/m_library/m_pandas/__init__.py
diff --git a/visualpython/js/m_library/m_pandas/getValueCounts.js b/visualpython/js/m_library/m_pandas/getValueCounts.js
new file mode 100644
index 00000000..3fe3c44f
--- /dev/null
+++ b/visualpython/js/m_library/m_pandas/getValueCounts.js
@@ -0,0 +1,46 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : getValueCounts.js
+ * Author : Black Logic
+ * Note : Library Component
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] ValueCounts
+//============================================================================
+define([
+ 'vp_base/js/com/component/LibraryComponent',
+ 'vp_base/js/com/component/VarSelector'
+], function(LibraryComponent, VarSelector) {
+ /**
+ * ValueCounts
+ */
+ class ValueCounts extends LibraryComponent {
+ _init() {
+ super._init();
+
+ this.state = {
+ i0: '',
+ o0: '',
+ ...this.state
+ }
+ }
+ render() {
+ super.render();
+
+ // add var selector
+ // var varSelector = new VarSelector(['DataFrame', 'Series', 'Index'], 'DataFrame', false);
+ // varSelector.setComponentId('i0');
+ // varSelector.addClass('vp-state');
+ // varSelector.setUseColumn(true);
+ // varSelector.setValue(this.state.i0);
+ // $(this.wrapSelector('#i0')).replaceWith(varSelector.render());
+ }
+ }
+
+ return ValueCounts;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_library/m_pandas/readFile.js b/visualpython/js/m_library/m_pandas/readFile.js
new file mode 100644
index 00000000..c9144db9
--- /dev/null
+++ b/visualpython/js/m_library/m_pandas/readFile.js
@@ -0,0 +1,254 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : readFile.js
+ * Author : Black Logic
+ * Note : read 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();
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+
+ this.state = {
+ fileExtension: 'csv',
+ selectedType: 'csv',
+ selectedFile: '',
+ selectedPath: '',
+ vp_pageDom: '',
+ ...this.state
+ }
+
+ this.fileExtensions = {
+ 'csv': 'csv',
+ 'excel': 'xlsx',
+ 'json': 'json',
+ 'pickle': '',
+ 'parquet': 'parquet'
+ }
+ this.dataPath = 'https://raw.githubusercontent.com/visualpython/visualpython/main/visualpython/data/sample_csv/';
+ this.fileResultState = {
+ pathInputId : this.wrapSelector('#i0'),
+ fileInputId : this.wrapSelector('#fileName')
+ };
+ this.fileState = {
+ fileTypeId: {
+ 'csv': 'pd_readCsv',
+ 'excel': 'pd_readExcel',
+ 'json': 'pd_readJson',
+ 'pickle': 'pd_readPickle',
+ 'parquet': 'pd_readParquet'
+ },
+ selectedType: 'csv',
+ package: null
+ };
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ this.bindEvent();
+ }
+
+ bindEvent() {
+ let that = this;
+
+ // select file type
+ $(this.wrapSelector('#fileType')).change(function() {
+ var value = $(this).val();
+ that.state.selectedType = value;
+
+ // reload
+ that.renderPage();
+ that.bindEvent();
+ });
+
+ // open file navigation
+ $(this.wrapSelector('#vp_openFileNavigationBtn')).click(function() {
+ let fileNavi = new FileNavigation({
+ type: 'open',
+ extensions: [ that.state.fileExtension ],
+ 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() {
+ // save input state
+ $(this.wrapSelector('input')).each(function () {
+ this.defaultValue = this.value;
+ });
+
+ // save checkbox state
+ $(this.wrapSelector('input[type="checkbox"]')).each(function () {
+ if (this.checked) {
+ this.setAttribute("checked", true);
+ } else {
+ this.removeAttribute("checked");
+ }
+ });
+
+ // save select state
+ $(this.wrapSelector('select > option')).each(function () {
+ if (this.selected) {
+ this.setAttribute("selected", true);
+ } else {
+ this.removeAttribute("selected");
+ }
+ });
+
+ var pageDom = $(this.wrapSelector('.vp-fileio-box')).html();
+ this.state['vp_pageDom'] = pageDom;
+ }
+
+ loadStateAfterRender() {
+ var pageDom = this.state['vp_pageDom'];
+
+ // load pageDom
+ $(this.wrapSelector('.vp-fileio-box')).html(pageDom);
+ }
+
+ templateForBody() {
+ return `
+
+
Required Input & Output
+
+
+
+
`;
+ }
+
+ render() {
+ super.render();
+
+ this.renderPage();
+
+ if (this.state.vp_pageDom && this.state.vp_pageDom != '') {
+ this.loadStateAfterRender();
+ }
+ this.bindEvent();
+ }
+
+ renderPage() {
+ var that = this;
+
+ // clear
+ $(this.wrapSelector('#vp_inputOutputBox table')).html(' ');
+ $(this.wrapSelector('#vp_optionBox table')).html(' ');
+
+ var fileTypeObj = this.fileState['fileTypeId'];
+ var selectedType = this.state['selectedType'];
+ let fileId = fileTypeObj[selectedType];
+ let pdLib = pandasLibrary.PANDAS_FUNCTION;
+ let thisPkg = JSON.parse(JSON.stringify(pdLib[fileId]));
+
+ this.fileState.package = thisPkg;
+ this.state.fileExtension = that.fileExtensions[selectedType];
+
+ // render interface
+ // pdGen.vp_showInterfaceOnPage(this.wrapSelector('.vp-fileio-box'), thisPkg);
+ pdGen.vp_showInterfaceOnPage(this, thisPkg, this.state);
+
+ // prepend file type selector
+ $(this.wrapSelector('#vp_inputOutputBox table tbody')).prepend(
+ $('').append($(`File Type `))
+ .append($(' '))
+ );
+ var fileTypeList = Object.keys(fileTypeObj);
+ fileTypeList.forEach(type => {
+ $(this.wrapSelector('#fileType')).append(
+ $(`${type} `)
+ );
+ });
+
+ $(this.wrapSelector('#fileType')).val(selectedType);
+
+ // add file navigation button
+ $(this.fileResultState['pathInputId']).parent().html(
+ com_util.formatString('
'
+ , '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');
+ suggestInput.setSuggestList(function() { return encodingList; });
+ suggestInput.setPlaceholder('encoding option');
+ return suggestInput.toTagString();
+ });
+
+
+ }
+
+ generateCode() {
+ var sbCode = new com_String;
+
+ this.saveState();
+
+ var thisPkg = JSON.parse(JSON.stringify(this.fileState.package));
+ thisPkg.options.push({
+ name: 'fileType',
+ type: 'var'
+ });
+ // var result = pdGen.vp_codeGenerator(this.uuid, thisPkg);
+ var result = pdGen.vp_codeGenerator(this, thisPkg, this.state);
+ sbCode.append(result);
+
+ return sbCode.toString();
+ }
+
+ }
+
+ return File;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_library/m_pandas/toFile.js b/visualpython/js/m_library/m_pandas/toFile.js
new file mode 100644
index 00000000..08bb45c8
--- /dev/null
+++ b/visualpython/js/m_library/m_pandas/toFile.js
@@ -0,0 +1,272 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : toFile.js
+ * Author : Black Logic
+ * Note : to 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();
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+
+ this.state = {
+ fileExtension: 'csv',
+ selectedType: 'csv',
+ selectedFile: '',
+ selectedPath: '',
+ vp_pageDom: '',
+ ...this.state
+ }
+
+ this.fileExtensions = {
+ 'csv': 'csv',
+ 'excel': 'xlsx',
+ 'json': 'json',
+ 'pickle': '',
+ 'parquet': 'parquet'
+ }
+ this.dataPath = 'https://raw.githubusercontent.com/visualpython/visualpython/main/visualpython/data/sample_csv/';
+ this.fileResultState = {
+ pathInputId : this.wrapSelector('#i1'),
+ fileInputId : this.wrapSelector('#fileName')
+ };
+ this.fileState = {
+ fileTypeId: {
+ 'csv': 'pd_toCsv',
+ 'excel': 'pd_toExcel',
+ 'json': 'pd_toJson',
+ 'pickle': 'pd_toPickle',
+ 'parquet': 'pd_toParquet'
+ },
+ selectedType: 'csv',
+ package: null
+ };
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ this.bindEvent();
+ }
+
+ bindEvent() {
+ let that = this;
+
+ // select file type
+ $(this.wrapSelector('#fileType')).change(function() {
+ var value = $(this).val();
+ that.state.selectedType = value;
+
+ // reload
+ that.renderPage();
+ that.bindEvent();
+ });
+
+ // open file navigation
+ $(this.wrapSelector('#vp_openFileNavigationBtn')).click(function() {
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: [ that.state.fileExtension ],
+ 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() {
+ // save input state
+ $(this.wrapSelector('input')).each(function () {
+ this.defaultValue = this.value;
+ });
+
+ // save checkbox state
+ $(this.wrapSelector('input[type="checkbox"]')).each(function () {
+ if (this.checked) {
+ this.setAttribute("checked", true);
+ } else {
+ this.removeAttribute("checked");
+ }
+ });
+
+ // save select state
+ $(this.wrapSelector('select > option')).each(function () {
+ if (this.selected) {
+ this.setAttribute("selected", true);
+ } else {
+ this.removeAttribute("selected");
+ }
+ });
+
+ var pageDom = $(this.wrapSelector('.vp-fileio-box')).html();
+ this.state['vp_pageDom'] = pageDom;
+ }
+
+ loadStateAfterRender() {
+ var pageDom = this.state['vp_pageDom'];
+
+ // load pageDom
+ $(this.wrapSelector('.vp-fileio-box')).html(pageDom);
+ }
+
+ templateForBody() {
+ return `
+
+
Required Input & Output
+
+
+
+
`;
+ }
+
+ render() {
+ super.render();
+
+ this.renderPage();
+
+ if (this.state.vp_pageDom && this.state.vp_pageDom != '') {
+ this.loadStateAfterRender();
+ }
+ this.bindEvent();
+ }
+
+ renderPage() {
+ var that = this;
+
+ // clear
+ $(this.wrapSelector('#vp_inputOutputBox table')).html(' ');
+ $(this.wrapSelector('#vp_optionBox table')).html(' ');
+
+ var fileTypeObj = this.fileState['fileTypeId'];
+ var selectedType = this.state['selectedType'];
+
+ let fileId = fileTypeObj[selectedType];
+ let pdLib = pandasLibrary.PANDAS_FUNCTION;
+ let thisPkg = JSON.parse(JSON.stringify(pdLib[fileId]));
+
+ this.fileState.package = thisPkg;
+ this.state.fileExtension = that.fileExtensions[selectedType];
+
+ if (selectedType == 'json') {
+ this.fileResultState.pathInputId = this.wrapSelector('#path_or_buf');
+ }
+ if (selectedType == 'pickle') {
+ this.fileResultState.pathInputId = this.wrapSelector('#path');
+ }
+
+ // render interface
+ // pdGen.vp_showInterfaceOnPage(this.wrapSelector('.vp-fileio-box'), thisPkg);
+ pdGen.vp_showInterfaceOnPage(this, thisPkg, this.state);
+
+ // prepend file type selector
+ $(this.wrapSelector('#vp_inputOutputBox table tbody')).prepend(
+ $('').append($(`File Type `))
+ .append($(' '))
+ );
+ var fileTypeList = Object.keys(fileTypeObj);
+ fileTypeList.forEach(type => {
+ $(this.wrapSelector('#fileType')).append(
+ $(`${type} `)
+ );
+ });
+
+ $(this.wrapSelector('#fileType')).val(selectedType);
+
+ // add file navigation button
+ if (selectedType == 'json') {
+ $(this.wrapSelector('#path_or_buf')).parent().html(
+ com_util.formatString('
'
+ , 'vp-file-browser-button')
+ );
+ } else if (selectedType == 'pickle') {
+ $(this.wrapSelector('#path')).parent().html(
+ com_util.formatString('
'
+ , 'vp-file-browser-button')
+ );
+ } else {
+ $(this.fileResultState['pathInputId']).parent().html(
+ com_util.formatString('
'
+ , 'i1'
+ , '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');
+ suggestInput.setSuggestList(function() { return encodingList; });
+ suggestInput.setPlaceholder('encoding option');
+ return suggestInput.toTagString();
+ });
+ }
+
+ generateCode() {
+ var sbCode = new com_String;
+
+ this.saveState();
+
+ var thisPkg = JSON.parse(JSON.stringify(this.fileState.package));
+ thisPkg.options.push({
+ name: 'fileType',
+ type: 'var'
+ });
+ // var result = pdGen.vp_codeGenerator(this.uuid, thisPkg);
+ var result = pdGen.vp_codeGenerator(this, thisPkg, this.state);
+ sbCode.append(result);
+
+ return sbCode.toString();
+ }
+
+ }
+
+ return File;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Break.js b/visualpython/js/m_logic/Break.js
new file mode 100644
index 00000000..b006ca82
--- /dev/null
+++ b/visualpython/js/m_logic/Break.js
@@ -0,0 +1,59 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : code.js
+ * Author : Black Logic
+ * Note : Logic > code
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] code
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Code
+ */
+ class Code extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: 'break',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Code;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Class.js b/visualpython/js/m_logic/Class.js
new file mode 100644
index 00000000..0912c3de
--- /dev/null
+++ b/visualpython/js/m_logic/Class.js
@@ -0,0 +1,68 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Class.js
+ * Author : Black Logic
+ * Note : Logic > class
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Class
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, com_util, PopupComponent) {
+
+ /**
+ * Class
+ */
+ class Class extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: '',
+ v2: '',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('Class Name
');
+ page.appendFormatLine(' '
+ , this.state.v1, 'Input class name');
+ page.appendLine('Super Class Name
');
+ page.appendFormatLine(' '
+ , this.state.v2, 'Input super class name');
+ return page.toString();
+ }
+
+ generateCode() {
+ let superClass = this.state.v2;
+ if (superClass != '') {
+ superClass = '(' + superClass + ')';
+ }
+ return com_util.formatString('class {0}{1}:', this.state.v1, superClass);
+ }
+
+ }
+
+ return Class;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Code.js b/visualpython/js/m_logic/Code.js
new file mode 100644
index 00000000..f35dc919
--- /dev/null
+++ b/visualpython/js/m_logic/Code.js
@@ -0,0 +1,59 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : code.js
+ * Author : Black Logic
+ * Note : Logic > code
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] code
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Code
+ */
+ class Code extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: '',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Code;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Comment.js b/visualpython/js/m_logic/Comment.js
new file mode 100644
index 00000000..fdec26fe
--- /dev/null
+++ b/visualpython/js/m_logic/Comment.js
@@ -0,0 +1,154 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Comment.js
+ * Author : Black Logic
+ * Note : Logic > comment
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Comment
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ const COMMENT_DEFAULT_CODE = '# Write down comments'
+ // Templates from NumPy Style Python Docstrings.
+ const COMMENT_CLASS_TEMPLATE =
+`"""Summarize the class in one line.
+Several sentences ...
+providing an extended description.
+Note
+----------
+Note about this class.
+Parameters
+----------
+param1 : param_type
+ Parameter description.
+param2 : param_type
+ Parameter description.
+Attributes
+----------
+attr1 : attr_type
+ Attibute description.
+attr2 : attr_type
+ Attibute description.
+Examples
+----------
+
+References
+----------
+"""`
+ const COMMENT_METHOD_TEMPLATE =
+`"""Summarize the function in one line.
+Several sentences ...
+providing an extended description.
+Parameters
+----------
+param1 : param_type
+ Parameter description.
+param2 : param_type
+ Parameter description.
+Returns
+-------
+return_type
+ Return description.
+Note
+----------
+Examples
+----------
+"""`
+
+ /**
+ * Comment
+ */
+ class Comment extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+ this.selectBoxClassName = 'vp-ct-option'; // Select Box ClassName
+ this.selectOptionPrefix = 'vp_template_'; // Select Options Class Prefix Name
+
+ this.state = {
+ v1: {"name": "Default", "code": COMMENT_DEFAULT_CODE},
+ v2 : {"name": "Class", "code": COMMENT_CLASS_TEMPLATE},
+ v3 : {"name": "Method", "code": COMMENT_METHOD_TEMPLATE},
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+
+ var commentTemplates = this.state;
+ let cmCodeListTemp = this.cmCodeList;
+
+ $('.' + this.selectBoxClassName).on('change', function(){
+ // get code mirror object
+ let targetCmObj = cmCodeListTemp.filter(obj => obj.key == 'code');
+ let cm = targetCmObj[0].cm;
+ var templateOption = $(this).val();
+
+ // Change Code Mirror Text
+ if(templateOption == commentTemplates.v1['name']){
+ cm.setValue(commentTemplates.v1['code']);
+ }else if(templateOption == commentTemplates.v2['name']){
+ cm.setValue(commentTemplates.v2['code']);
+ }else if(templateOption == commentTemplates.v3['name']){
+ cm.setValue(commentTemplates.v3['code']);
+ }
+ cm.save();
+ });
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.v1['code']);
+
+ // add select box
+ page.appendFormatLine('', this.selectBoxClassName);
+ for (var key in this.state) {
+ var optionName = this.state[key]['name'];
+ page.appendFormatLine('{2} ',
+ optionName,
+ this.selectOptionPrefix + optionName,
+ optionName);
+ }
+ page.appendFormatLine(' ');
+
+ return page.toString();
+ }
+
+ open() {
+ super.open();
+
+ if (this.state.code === COMMENT_DEFAULT_CODE) {
+ // set default selection
+ let cmObj = this.getCodemirror('code');
+ if (cmObj && cmObj.cm) {
+ cmObj.cm.setSelection({ line: 0, ch: 2 }, { line: 0 });
+ cmObj.cm.focus();
+ }
+ }
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Comment;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Continue.js b/visualpython/js/m_logic/Continue.js
new file mode 100644
index 00000000..bf7b87ac
--- /dev/null
+++ b/visualpython/js/m_logic/Continue.js
@@ -0,0 +1,59 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : code.js
+ * Author : Black Logic
+ * Note : Logic > code
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] code
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Code
+ */
+ class Code extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: 'continue',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Code;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Def.js b/visualpython/js/m_logic/Def.js
new file mode 100644
index 00000000..0dd2e11e
--- /dev/null
+++ b/visualpython/js/m_logic/Def.js
@@ -0,0 +1,141 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Def.js
+ * Author : Black Logic
+ * Note : Logic > def
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Def
+//============================================================================
+define([
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_Const, com_String, com_util, PopupComponent) {
+
+ /**
+ * Def
+ */
+ class Def extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: '',
+ v2: [],
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ $(this.wrapSelector('#vp_addParam')).on('click', function() {
+ that.state.v2.push({ param: '', value: ''});
+ $(that.wrapSelector('.v2 tbody')).append(that.templateForList(that.state.v2.length, '', ''));
+ });
+
+ // Delete param
+ $(document).on('click', this.wrapSelector('.v2-del'), function() {
+ let pos = $(this).closest('.v2-tr').index();
+
+ $(that.wrapSelector('.v2-tr:nth('+pos+')')).remove();
+ that.state.v2.splice(pos, 1);
+
+ // re-numbering
+ $(that.wrapSelector('.v2-tr')).each((idx, tag) => {
+ $(tag).find('th').text(idx + 1);
+ });
+ });
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.v2-del'));
+ }
+
+ saveState() {
+ let that = this;
+ let v2 = [];
+ $(this.wrapSelector('.v2-tr')).each((idx, tag) => {
+ let v2_ele = {};
+ v2_ele['param'] = $(tag).find('.v2-param').val();
+ v2_ele['value'] = $(tag).find('.v2-value').val();
+ v2.push(v2_ele);
+ });
+ this.state.v2 = v2;
+ }
+
+ loadState() {
+ super.loadState();
+ let { v1, v2 } = this.state;
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('Function Name
');
+ page.appendFormatLine(' '
+ , this.state.v1, 'Input code line');
+ page.appendLine('');
+ page.appendLine('Parameter Default Value ');
+ page.appendLine(' ');
+ let that = this;
+ this.state.v2.forEach((v, idx) => {
+ page.appendLine(that.templateForList(idx + 1, v.param, v.value));
+ });
+ page.appendLine('
');
+ page.appendFormatLine('+ Parameter ', 'vp_addParam');
+ return page.toString();
+ }
+
+ templateForList(idx, param, value) {
+ if (!value) {
+ value = '';
+ }
+ var page = new com_String();
+ page.appendFormatLine(' ', 'v2-tr');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v2-param', param, 'Variable');
+ page.appendLine('= ');
+ page.appendFormatLine(' '
+ , 'v2-value', value, 'Value');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v2-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v2-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ generateCode() {
+ this.saveState();
+
+ let parameters = [];
+ this.state.v2.forEach(v => {
+ let param = v.param;
+ if (v.value != '') {
+ param += '=' + v.value;
+ }
+ if (param == '') {
+ return;
+ }
+ parameters.push(param);
+ });
+ return com_util.formatString('def {0}({1}):', this.state.v1, parameters.join(', '));
+ }
+
+ }
+
+ return Def;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Elif.js b/visualpython/js/m_logic/Elif.js
new file mode 100644
index 00000000..91160984
--- /dev/null
+++ b/visualpython/js/m_logic/Elif.js
@@ -0,0 +1,223 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Elif.js
+ * Author : Black Logic
+ * Note : Logic > elif
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Elif
+//============================================================================
+define([
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(com_Const, com_String, com_util, PopupComponent, SuggestInput) {
+
+ /**
+ * Elif
+ */
+ class Elif extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: [{ type: 'condition', value: {} }],
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // Add param
+ $(this.wrapSelector('#vp_addCondition')).on('click', function() {
+ that.state.v1.push({ type: 'condition', value: {} });
+ $(that.wrapSelector('.v1-table')).append(that.templateForList(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ $(this.wrapSelector('#vp_addUserInput')).on('click', function() {
+ that.state.v1.push({ type: 'input', value: {} });
+ $(that.wrapSelector('.v1-table')).append(that.templateForInput(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+
+ // Delete param
+ $(document).on('click', this.wrapSelector('.v1-del'), function() {
+ let pos = $(this).closest('.v1-tr').index();
+
+ $(that.wrapSelector('.v1-tr:nth('+pos+')')).remove();
+ that.state.v1.splice(pos, 1);
+
+ // re-numbering
+ $(that.wrapSelector('.v1-tr')).each((idx, tag) => {
+ $(tag).find('th').text(idx + 1);
+ });
+
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.v1-del'));
+ }
+
+ saveState() {
+ let that = this;
+ let v1 = [];
+ $(this.wrapSelector('.v1-tr')).each((idx, tag) => {
+ let type = $(tag).data('type');
+ let v1_ele = {};
+ if (type == 'condition') {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i2'] = $(tag).find('.v1-i2').val();
+ v1_ele['i3'] = $(tag).find('.v1-i3').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ } else {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ }
+ v1.push({ type: type, value: v1_ele });
+ });
+ this.state.v1 = v1;
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ // page.appendLine('Parameter Default Value ');
+ page.appendLine(' ');
+ page.appendLine('');
+ this.state.v1.forEach((v, idx) => {
+ if (v.type == 'condition') {
+ page.appendLine(this.templateForList(idx + 1, v.value));
+ } else {
+ page.appendLine(this.templateForInput(idx + 1, v.value));
+ }
+ });
+ page.appendLine('
');
+ page.appendFormatLine('+ Condition ', 'vp_addCondition');
+ page.appendFormatLine('+ User Input ', 'vp_addUserInput');
+ return page.toString();
+ }
+
+ templateForList(idx, v) {
+ v = {
+ i1: '', i2: '', i3: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'condition');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ // suggestInput for operator
+ let operList = ['', '==', '!=', 'in', 'not in', '<', '<=', '>', '>='];
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input w70 v1-i2');
+ suggestInput.setSuggestList(function() { return operList; });
+ suggestInput.setPlaceholder('Operator');
+ suggestInput.setNormalFilter(false);
+ suggestInput.setValue(v.i2);
+ suggestInput.setSelectEvent(function(selectedValue) {
+ // trigger change
+ $(this.wrapSelector()).val(selectedValue);
+ $(this.wrapSelector()).trigger('change');
+ });
+ page.appendFormatLine('{0} ', suggestInput.toTagString());
+ page.appendFormatLine(' '
+ , 'v1-i3', v.i3, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+ templateForInput(idx, v) {
+ v = {
+ i1: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'input');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+
+ // disable last operator
+ $(this.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ }
+
+ generateCode() {
+ this.saveState();
+
+ let parameters = [];
+ let length = this.state.v1.length;
+ this.state.v1.forEach((v, idx) => {
+ let value = v.value;
+ let line = '';
+ if (v.type == 'condition') {
+ line = value.i1 + value.i2 + value.i3;
+ } else {
+ line = value.i1;
+ }
+ if (length > 1) {
+ line = '(' + line + ')';
+ }
+ if (idx + 1 < length) {
+ line += value.i4;
+ }
+ parameters.push(line);
+ });
+ return com_util.formatString('elif ({0}):', parameters.join(''));
+ }
+
+ }
+
+ return Elif;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Else.js b/visualpython/js/m_logic/Else.js
new file mode 100644
index 00000000..5a54fd44
--- /dev/null
+++ b/visualpython/js/m_logic/Else.js
@@ -0,0 +1,38 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Else.js
+ * Author : Black Logic
+ * Note : Logic > else
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Else
+//============================================================================
+define([
+ 'vp_base/js/com/component/PopupComponent'
+], function(PopupComponent) {
+
+ /**
+ * Else
+ */
+ class Else extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+ }
+
+ generateCode() {
+ return 'else:';
+ }
+
+ }
+
+ return Else;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Except.js b/visualpython/js/m_logic/Except.js
new file mode 100644
index 00000000..1e2d6a2d
--- /dev/null
+++ b/visualpython/js/m_logic/Except.js
@@ -0,0 +1,78 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Except.js
+ * Author : Black Logic
+ * Note : Logic > except
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Except
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(com_String, PopupComponent, SuggestInput) {
+
+ /**
+ * Except
+ */
+ class Except extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: '',
+ v2: '',
+ ...this.state
+ }
+ }
+
+ templateForBody() {
+ let { v1, v2 } = this.state;
+ let page = new com_String();
+ // suggestInput for operator
+ let errorList = [
+ 'AssertionError', 'SystemError', 'TypeError', 'ModuleNotFoundError',
+ 'BaseException', 'FileNotFoundError', 'ImportError',
+ 'IndexError', 'MemoryError', 'LookupError', 'BufferError',
+ 'EOFError'
+ ];
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('v1');
+ suggestInput.addClass('vp-input vp-state w150 v1');
+ suggestInput.setSuggestList(function() { return errorList; });
+ suggestInput.setPlaceholder('Error');
+ suggestInput.setNormalFilter(false);
+ suggestInput.setValue(v1);
+ suggestInput.setSelectEvent(function(selectedValue) {
+ // trigger change
+ $(this.wrapSelector()).val(selectedValue);
+ $(this.wrapSelector()).trigger('change');
+ });
+ page.appendLine(suggestInput.toTagString());
+ page.appendLine('as ');
+ page.appendFormatLine(' ', v2);
+ return page.toString();
+ }
+
+ generateCode() {
+ let { v1, v2 } = this.state;
+ let asVariableStr = '';
+ if (v2 != '') {
+ asVariableStr = ' as ' + v2;
+ }
+ return `except ${v1}${asVariableStr}:`;
+ }
+
+ }
+
+ return Except;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Finally.js b/visualpython/js/m_logic/Finally.js
new file mode 100644
index 00000000..ccd273a6
--- /dev/null
+++ b/visualpython/js/m_logic/Finally.js
@@ -0,0 +1,38 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Finally.js
+ * Author : Black Logic
+ * Note : Logic > finally
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Finally
+//============================================================================
+define([
+ 'vp_base/js/com/component/PopupComponent'
+], function(PopupComponent) {
+
+ /**
+ * Finally
+ */
+ class Finally extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+ }
+
+ generateCode() {
+ return 'finally:';
+ }
+
+ }
+
+ return Finally;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/For.js b/visualpython/js/m_logic/For.js
new file mode 100644
index 00000000..0938d832
--- /dev/null
+++ b/visualpython/js/m_logic/For.js
@@ -0,0 +1,223 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : For.js
+ * Author : Black Logic
+ * Note : Logic > for
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] For
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/m_logic/for'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector'
+], function(forCss, com_String, com_util, PopupComponent, VarSelector) {
+
+ /**
+ * For
+ */
+ class For extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.saveOnly = true;
+ this.config.sizeLevel = 1;
+
+ this.state = {
+ v1: 'idx', // index
+ v2: 'item', // item
+ v3: 'range', // Type : range/variable/typing
+ v4: '', // Range - start
+ v5: '', // - stop
+ v6: '', // - step
+ v7: '', // Variable
+ v8: '', // Typing
+ useEnumerate: true,
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ $(this.wrapSelector('#v3')).on('change', function() {
+ let type = $(this).val();
+
+ // show input
+ if (type == 'range') {
+ $(that.wrapSelector('#v2')).hide();
+ $(that.wrapSelector('.vp-enumerate-box')).hide();
+ } else {
+ $(that.wrapSelector('#v2')).show();
+ $(that.wrapSelector('.vp-enumerate-box')).show();
+ }
+ // show sub box
+ $('.vp-for-sub-box').hide();
+ $('.vp-sub-'+type).show();
+ });
+
+ $(this.wrapSelector('#v7')).on('var_changed', function(evt) {
+ let value = evt.value;
+ that.state.v7 = value;
+ });
+
+ $(this.wrapSelector('#useEnumerate')).on('change', function() {
+ let checked = $(this).prop('checked');
+ that.state.useEnumerate = checked;
+ if (checked) {
+ $(that.wrapSelector('#v1')).show();
+ } else {
+ $(that.wrapSelector('#v1')).hide();
+ }
+ });
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ page.appendLine('
');
+ page.appendLine('
');
+ page.appendLine('
In
');
+ page.appendLine('
');
+ page.appendLine('');
+ let types = ['Range', 'Variable', 'Typing'];
+ types.forEach(type => {
+ let val = type.toLowerCase();
+ page.appendFormatLine('{2} ', val, val==this.state.v3?'selected':'', type);
+ });
+ page.appendLine(' ');
+ page.appendLine('
');
+ page.appendLine('
');
+ page.appendLine(this.templateForRangeBox());
+ page.appendLine(this.templateForVariableBox());
+ page.appendLine(this.templateForTypingBox());
+ page.appendFormatLine('
', this.state.v3 == 'range'?'style="display:none;"':'');
+ page.appendFormatLine(`
+
Enumerate
+
`, this.state.useEnumerate?'checked':'');
+ page.appendLine('
');
+ return page.toString();
+ }
+
+ templateForRangeBox() {
+ return ``;
+ }
+
+ templateForVariableBox() {
+ var dataTypes = ['DataFrame', 'Series', 'nparray', 'list', 'str'];
+ var varSelector = new VarSelector(dataTypes, 'DataFrame', true, true);
+ varSelector.setComponentId('v7');
+ varSelector.addBoxClass('vp-flex-row-between wp100');
+ varSelector.addTypeClass('wp50');
+ varSelector.addVarClass('vp-state wp50');
+ varSelector.setValue(this.state.v7);
+
+ return `
+
+
+
+
+ ${varSelector.render()}
+
+
+
`;
+ }
+
+ templateForTypingBox() {
+ return ``;
+ }
+
+ generateCode() {
+ let { v1, v2, v3, v4 ,v5, v6, v7, v8, useEnumerate } = this.state;
+ let front = v2;
+ let back = '';
+ if (v3 == 'range') {
+ front = v1;
+ back = `range(${v4}${v5!=''?', '+v5:''}${v6!=''?', '+v6:''})`
+ } else if (v3 == 'variable') {
+ if (useEnumerate) {
+ let optionList = [];
+ if (v1 != '') {
+ optionList.push(v1);
+ }
+ if (v2 != '') {
+ optionList.push(v2);
+ }
+ front = optionList.join(', ');
+ }
+ back = `${useEnumerate?'enumerate':''}(${v7})`;
+ } else {
+ if (useEnumerate) {
+ let optionList = [];
+ if (v1 != '') {
+ optionList.push(v1);
+ }
+ if (v2 != '') {
+ optionList.push(v2);
+ }
+ front = optionList.join(', ');
+ }
+ back = `${useEnumerate?'enumerate':''}(${v8})`;
+ }
+
+ return com_util.formatString('for {0} in {1}:', front, back);
+ }
+
+ }
+
+ return For;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/If.js b/visualpython/js/m_logic/If.js
new file mode 100644
index 00000000..06e1636f
--- /dev/null
+++ b/visualpython/js/m_logic/If.js
@@ -0,0 +1,223 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : If.js
+ * Author : Black Logic
+ * Note : Logic > if
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] If
+//============================================================================
+define([
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(com_Const, com_String, com_util, PopupComponent, SuggestInput) {
+
+ /**
+ * If
+ */
+ class If extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: [{ type: 'condition', value: {} }],
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // Add param
+ $(this.wrapSelector('#vp_addCondition')).on('click', function() {
+ that.state.v1.push({ type: 'condition', value: {} });
+ $(that.wrapSelector('.v1-table')).append(that.templateForList(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ $(this.wrapSelector('#vp_addUserInput')).on('click', function() {
+ that.state.v1.push({ type: 'input', value: {} });
+ $(that.wrapSelector('.v1-table')).append(that.templateForInput(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+
+ // Delete param
+ $(document).on('click', this.wrapSelector('.v1-del'), function() {
+ let pos = $(this).closest('.v1-tr').index();
+
+ $(that.wrapSelector('.v1-tr:nth('+pos+')')).remove();
+ that.state.v1.splice(pos, 1);
+
+ // re-numbering
+ $(that.wrapSelector('.v1-tr')).each((idx, tag) => {
+ $(tag).find('th').text(idx + 1);
+ });
+
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.v1-del'));
+ }
+
+ saveState() {
+ let that = this;
+ let v1 = [];
+ $(this.wrapSelector('.v1-tr')).each((idx, tag) => {
+ let type = $(tag).data('type');
+ let v1_ele = {};
+ if (type == 'condition') {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i2'] = $(tag).find('.v1-i2').val();
+ v1_ele['i3'] = $(tag).find('.v1-i3').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ } else {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ }
+ v1.push({ type: type, value: v1_ele });
+ });
+ this.state.v1 = v1;
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ // page.appendLine('Parameter Default Value ');
+ page.appendLine(' ');
+ page.appendLine('');
+ this.state.v1.forEach((v, idx) => {
+ if (v.type == 'condition') {
+ page.appendLine(this.templateForList(idx + 1, v.value));
+ } else {
+ page.appendLine(this.templateForInput(idx + 1, v.value));
+ }
+ });
+ page.appendLine('
');
+ page.appendFormatLine('+ Condition ', 'vp_addCondition');
+ page.appendFormatLine('+ User Input ', 'vp_addUserInput');
+ return page.toString();
+ }
+
+ templateForList(idx, v) {
+ v = {
+ i1: '', i2: '', i3: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'condition');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ // suggestInput for operator
+ let operList = ['', '==', '!=', 'in', 'not in', '<', '<=', '>', '>='];
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input w70 v1-i2');
+ suggestInput.setSuggestList(function() { return operList; });
+ suggestInput.setPlaceholder('Operator');
+ suggestInput.setNormalFilter(false);
+ suggestInput.setValue(v.i2);
+ suggestInput.setSelectEvent(function(selectedValue) {
+ // trigger change
+ $(this.wrapSelector()).val(selectedValue);
+ $(this.wrapSelector()).trigger('change');
+ });
+ page.appendFormatLine('{0} ', suggestInput.toTagString());
+ page.appendFormatLine(' '
+ , 'v1-i3', v.i3, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+ templateForInput(idx, v) {
+ v = {
+ i1: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'input');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+
+ // disable last operator
+ $(this.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ }
+
+ generateCode() {
+ this.saveState();
+
+ let parameters = [];
+ let length = this.state.v1.length;
+ this.state.v1.forEach((v, idx) => {
+ let value = v.value;
+ let line = '';
+ if (v.type == 'condition') {
+ line = value.i1 + value.i2 + value.i3;
+ } else {
+ line = value.i1;
+ }
+ if (length > 1) {
+ line = '(' + line + ')';
+ }
+ if (idx + 1 < length) {
+ line += value.i4;
+ }
+ parameters.push(line);
+ });
+ return com_util.formatString('if ({0}):', parameters.join(''));
+ }
+
+ }
+
+ return If;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Lambda.js b/visualpython/js/m_logic/Lambda.js
new file mode 100644
index 00000000..32e937ab
--- /dev/null
+++ b/visualpython/js/m_logic/Lambda.js
@@ -0,0 +1,74 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Lambda.js
+ * Author : Black Logic
+ * Note : Logic > lambda
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Lambda
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ const LAMBDA_DEFAULT_CODE = 'lambda x: x';
+
+ /**
+ * Lambda
+ */
+ class Lambda extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: LAMBDA_DEFAULT_CODE,
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ open() {
+ super.open();
+
+ if (this.state.code === LAMBDA_DEFAULT_CODE) {
+ // set default selection
+ let cmObj = this.getCodemirror('code');
+ if (cmObj && cmObj.cm) {
+ cmObj.cm.setSelection({ line: 0, ch: 10 }, { line: 0 });
+ cmObj.cm.focus();
+ }
+ }
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Lambda;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Pass.js b/visualpython/js/m_logic/Pass.js
new file mode 100644
index 00000000..283ca2ed
--- /dev/null
+++ b/visualpython/js/m_logic/Pass.js
@@ -0,0 +1,59 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : code.js
+ * Author : Black Logic
+ * Note : Logic > code
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] code
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Code
+ */
+ class Code extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: 'pass',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Code;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Print.js b/visualpython/js/m_logic/Print.js
new file mode 100644
index 00000000..1200e28d
--- /dev/null
+++ b/visualpython/js/m_logic/Print.js
@@ -0,0 +1,68 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Print.js
+ * Author : Black Logic
+ * Note : Logic > print
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Print
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Print
+ */
+ class Print extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ code: 'print()',
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendFormatLine(''
+ , this.state.code);
+ return page.toString();
+ }
+
+ open() {
+ super.open();
+
+ // if start with print(, set default cursor on codemirror
+ if (this.state.code.substr(0, 6) === 'print(') {
+ // set default cursor
+ let cmObj = this.getCodemirror('code');
+ if (cmObj && cmObj.cm) {
+ cmObj.cm.setCursor({ line: 0, ch: 6 });
+ cmObj.cm.focus();
+ }
+ }
+ }
+
+ generateCode() {
+ return this.state.code;
+ }
+
+ }
+
+ return Print;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Return.js b/visualpython/js/m_logic/Return.js
new file mode 100644
index 00000000..f0c273e7
--- /dev/null
+++ b/visualpython/js/m_logic/Return.js
@@ -0,0 +1,113 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Return.js
+ * Author : Black Logic
+ * Note : Logic > Return
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Return
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(com_String, com_util, PopupComponent, SuggestInput) {
+
+ /**
+ * Return
+ */
+ class Return extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: [],
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // Add param
+ $(this.wrapSelector('#vp_addParam')).on('click', function() {
+ that.state.v1.push('');
+ $(that.wrapSelector('.v1 tbody')).append(that.templateForInput(that.state.v1.length, ''));
+ });
+
+ // Delete param
+ $(document).on('click', this.wrapSelector('.v1-del'), function() {
+ let pos = $(this).closest('.v1-tr').index();
+
+ $(that.wrapSelector('.v1-tr:nth('+pos+')')).remove();
+ that.state.v1.splice(pos, 1);
+
+ // re-numbering
+ $(that.wrapSelector('.v1-tr')).each((idx, tag) => {
+ $(tag).find('th').text(idx + 1);
+ });
+ });
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.v1-del'));
+ }
+
+ saveState() {
+ let that = this;
+ let v1 = [];
+ $(this.wrapSelector('.v1-tr')).each((idx, tag) => {
+ let value = $(tag).find('.v1-i1').val();
+ v1.push(value);
+ });
+ this.state.v1 = v1;
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ // page.appendLine('Parameter Default Value ');
+ page.appendLine(' ');
+ this.state.v1.forEach((v, idx) => {
+ this.templateForInput(idx + 1, v);
+ });
+ page.appendLine('
');
+ page.appendFormatLine('+ Parameter ', 'vp_addParam');
+ return page.toString();
+ }
+ templateForInput(idx, value) {
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', value, 'Input parameter');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', );
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ generateCode() {
+ this.saveState();
+ let params = this.state.v1.filter(v => v != '');
+
+ return com_util.formatString('return {0}', params.join(', '));
+ }
+
+ }
+
+ return Return;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/Try.js b/visualpython/js/m_logic/Try.js
new file mode 100644
index 00000000..691c9096
--- /dev/null
+++ b/visualpython/js/m_logic/Try.js
@@ -0,0 +1,54 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Try.js
+ * Author : Black Logic
+ * Note : Logic > try
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Try
+//============================================================================
+define([
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent'
+], function(com_String, PopupComponent) {
+
+ /**
+ * Try
+ */
+ class Try extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.codeview = false;
+ this.config.saveOnly = true;
+
+ this.state = {
+ ...this.state
+ }
+
+ this._addCodemirror('code', this.wrapSelector('#code'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ }
+
+ templateForBody() {
+ return '';
+ }
+
+ generateCode() {
+ return 'try:';
+ }
+
+ }
+
+ return Try;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_logic/While.js b/visualpython/js/m_logic/While.js
new file mode 100644
index 00000000..0ea865ea
--- /dev/null
+++ b/visualpython/js/m_logic/While.js
@@ -0,0 +1,224 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : While.js
+ * Author : Black Logic
+ * Note : Logic > while
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] While
+//============================================================================
+define([
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(com_Const, com_String, com_util, PopupComponent, SuggestInput) {
+
+ /**
+ * While
+ */
+ class While extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 1;
+ this.config.saveOnly = true;
+
+ this.state = {
+ v1: [{ type: 'condition', value: {} }],
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ let that = this;
+ // Add param
+ $(this.wrapSelector('#vp_addCondition')).on('click', function() {
+ that.state.v1.push({ type: 'condition', value: {} });
+ $(that.wrapSelector('.v1 tbody')).append(that.templateForList(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ $(this.wrapSelector('#vp_addUserInput')).on('click', function() {
+ that.state.v1.push({ type: 'input', value: {} });
+ $(that.wrapSelector('.v1 tbody')).append(that.templateForInput(that.state.v1.length, {}));
+
+ // enable and disable last one
+ // enable all operator
+ $(that.wrapSelector('.v1 .v1-i4')).prop('disabled', false);
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+
+ // Delete param
+ $(document).on('click', this.wrapSelector('.v1-del'), function() {
+ let pos = $(this).closest('.v1-tr').index();
+
+ $(that.wrapSelector('.v1-tr:nth('+pos+')')).remove();
+ that.state.v1.splice(pos, 1);
+
+ // re-numbering
+ $(that.wrapSelector('.v1-tr')).each((idx, tag) => {
+ $(tag).find('th').text(idx + 1);
+ });
+
+ // disable last operator
+ $(that.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ });
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.v1-del'));
+ }
+
+ saveState() {
+ let that = this;
+ let v1 = [];
+ $(this.wrapSelector('.v1-tr')).each((idx, tag) => {
+ let type = $(tag).data('type');
+ let v1_ele = {};
+ if (type == 'condition') {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i2'] = $(tag).find('.v1-i2').val();
+ v1_ele['i3'] = $(tag).find('.v1-i3').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ } else {
+ v1_ele['i1'] = $(tag).find('.v1-i1').val();
+ v1_ele['i4'] = $(tag).find('.v1-i4').val();
+ }
+ v1.push({ type: type, value: v1_ele });
+ });
+ this.state.v1 = v1;
+ }
+
+ templateForBody() {
+ /** Implement generating template */
+ var page = new com_String();
+ page.appendLine('');
+ // page.appendLine('Parameter Default Value ');
+ page.appendLine(' ');
+ page.appendLine('');
+ let that = this;
+ this.state.v1.forEach((v, idx) => {
+ if (v.type == 'condition') {
+ page.appendLine(that.templateForList(idx + 1, v.value));
+ } else {
+ page.appendLine(that.templateForInput(idx + 1, v.value));
+ }
+ });
+ page.appendLine('
');
+ page.appendFormatLine('+ Condition ', 'vp_addCondition');
+ page.appendFormatLine('+ User Input ', 'vp_addUserInput');
+ return page.toString();
+ }
+
+ templateForList(idx, v) {
+ v = {
+ i1: '', i2: '', i3: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'condition');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ // suggestInput for operator
+ let operList = ['', '==', '!=', 'in', 'not in', '<', '<=', '>', '>='];
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input w70 v1-i2');
+ suggestInput.setSuggestList(function() { return operList; });
+ suggestInput.setPlaceholder('Operator');
+ suggestInput.setNormalFilter(false);
+ suggestInput.setValue(v.i2);
+ suggestInput.setSelectEvent(function(selectedValue) {
+ // trigger change
+ $(this.wrapSelector()).val(selectedValue);
+ $(this.wrapSelector()).trigger('change');
+ });
+ page.appendFormatLine('{0} ', suggestInput.toTagString());
+ page.appendFormatLine(' '
+ , 'v1-i3', v.i3, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+ templateForInput(idx, v) {
+ v = {
+ i1: '', i4: '',
+ ...v
+ }
+ var page = new com_String();
+ page.appendFormatLine('', 'v1-tr', 'input');
+ page.appendFormatLine('{0} ', idx);
+ page.appendFormatLine(' '
+ , 'v1-i1', v.i1, 'Variable');
+ page.appendFormatLine('', 'v1-i4');
+ let operator2 = ['and', 'or'];
+ operator2.forEach(op => {
+ page.appendFormatLine('{2} ', op, op == v.i4? 'selected': '', op);
+ })
+ page.appendLine(' ');
+ // LAB: img to url
+ // page.appendFormatLine(' ', 'v1-del', com_Const.IMAGE_PATH);
+ page.appendFormatLine('
', 'v1-del');
+ page.appendLine(' ');
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+
+ // disable last operator
+ $(this.wrapSelector('.v1 tr:last .v1-i4')).prop('disabled', true);
+ }
+
+ generateCode() {
+ this.saveState();
+
+ let parameters = [];
+ let length = this.state.v1.length;
+ this.state.v1.forEach((v, idx) => {
+ let value = v.value;
+ let line = '';
+ if (v.type == 'condition') {
+ line = value.i1 + value.i2 + value.i3;
+ } else {
+ line = value.i1;
+ }
+ if (length > 1) {
+ line = '(' + line + ')';
+ }
+ if (idx + 1 < length) {
+ line += value.i4;
+ }
+ parameters.push(line);
+ });
+ return com_util.formatString('while ({0}):', parameters.join(''));
+ }
+
+ }
+
+ return While;
+});
\ No newline at end of file
diff --git a/src/file_io/__init__.py b/visualpython/js/m_logic/__init__.py
similarity index 100%
rename from src/file_io/__init__.py
rename to visualpython/js/m_logic/__init__.py
diff --git a/visualpython/js/m_ml/AutoML.js b/visualpython/js/m_ml/AutoML.js
new file mode 100644
index 00000000..73e30ce0
--- /dev/null
+++ b/visualpython/js/m_ml/AutoML.js
@@ -0,0 +1,275 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : AutoML.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] AutoML
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor) {
+
+ /**
+ * AutoML
+ */
+ class AutoML extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'tpot-rgs',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Regression': ['auto-sklearn-rgs', 'tpot-rgs'],
+ 'Classification': ['auto-sklearn-clf', 'tpot-clf']
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > AutoML');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ })
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Auto ML').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.show();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return AutoML;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/Classification.js b/visualpython/js/m_ml/Classification.js
new file mode 100644
index 00000000..f327b611
--- /dev/null
+++ b/visualpython/js/m_ml/Classification.js
@@ -0,0 +1,333 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Classification.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Classification
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor) {
+
+ /**
+ * Classification
+ */
+ class Classification extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'lg-rgs',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Classification': ['lg-rgs', 'bern-nb', 'mulnom-nb', 'gaus-nb', 'sv-clf', 'dt-clf', 'rf-clf', 'gbm-clf', 'xgb-clf', 'lgbm-clf', 'cb-clf'],
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model type
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+ that.viewOption();
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > Classification');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ });
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Classification').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.show();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ viewOption() {
+ // SVC - kernel selection
+ if (this.state.modelType == 'sv-clf') {
+ let kernelType = this.state.kernel;
+ switch (kernelType) {
+ case undefined: // default = rbf
+ case '':
+ case 'rbf': // gamma
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ // hide others
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ $(this.wrapSelector('label[for="coef0"]')).hide();
+ $(this.wrapSelector('#coef0')).hide();
+ break;
+ case 'poly': // gamma / degree / coef0
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ $(this.wrapSelector('label[for="degree"]')).show();
+ $(this.wrapSelector('#degree')).show();
+ $(this.wrapSelector('label[for="coef0"]')).show();
+ $(this.wrapSelector('#coef0')).show();
+ break;
+ case 'sigmoid': // gamma / coef0
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ $(this.wrapSelector('label[for="coef0"]')).show();
+ $(this.wrapSelector('#coef0')).show();
+ // hide others
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ break;
+ default:
+ // hide others
+ $(this.wrapSelector('label[for="gamma"]')).hide();
+ $(this.wrapSelector('#gamma')).hide();
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ $(this.wrapSelector('label[for="coef0"]')).hide();
+ $(this.wrapSelector('#coef0')).hide();
+ break;
+ }
+
+ // Model Creation - SVC kernel selection
+ let that = this;
+ $(this.wrapSelector('#kernel')).off('change');
+ $(this.wrapSelector('#kernel')).change(function() {
+ that.state.kernel = $(this).val();
+ that.viewOption();
+ });
+ }
+
+ }
+
+ render() {
+ super.render();
+
+ // Model Creation - dynamically view options
+ this.viewOption();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return Classification;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/Clustering.js b/visualpython/js/m_ml/Clustering.js
new file mode 100644
index 00000000..95ee735c
--- /dev/null
+++ b/visualpython/js/m_ml/Clustering.js
@@ -0,0 +1,278 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Clustering.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Clustering
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor) {
+
+ /**
+ * Clustering
+ */
+ class Clustering extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'k-means',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ // 'Regression': ['ln-rgs', 'sv-rgs', 'dt-rgs', 'rf-rgs', 'gbm-rgs', 'xgb-rgs', 'lgbm-rgs', 'cb-rgs'],
+ // 'Classification': ['lg-rgs', 'sv-clf', 'dt-clf', 'rf-clf', 'gbm-clf', 'xgb-clf', 'lgbm-clf', 'cb-clf'],
+ // 'Auto ML': ['tpot-rgs', 'tpot-clf'],
+ 'Clustering': ['k-means', 'agg-cls', 'gaus-mix', 'dbscan'],
+ // 'Dimension Reduction': ['pca', 'lda', 'svd', 'nmf']
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > Clustering');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ })
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Clustering').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.show();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return Clustering;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/DataPrep.js b/visualpython/js/m_ml/DataPrep.js
new file mode 100644
index 00000000..10b9625f
--- /dev/null
+++ b/visualpython/js/m_ml/DataPrep.js
@@ -0,0 +1,484 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : DataPrep.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] DataPrep
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor',
+ 'vp_base/js/com/component/MultiSelector'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor, MultiSelector) {
+
+ /**
+ * DataPrep
+ */
+ class DataPrep extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'prep-onehot',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.popup = {
+ type: '',
+ targetSelector: '',
+ colSelector: undefined // multi column selector
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Encoding': ['prep-onehot', 'prep-label', 'prep-ordinal', 'prep-target'],
+ 'Scaling': ['prep-standard', 'prep-robust', 'prep-minmax', 'prep-normalizer', 'prep-func-trsfrm-log', 'prep-func-trsfrm-exp', 'prep-poly-feat', 'prep-kbins-discretizer'],
+ 'ETC': ['prep-simple-imputer', 'prep-smote', 'make-column-transformer']
+ }
+
+ this.mctEstimator = {
+ 'Encoding': ['prep-onehot', 'prep-label', 'prep-ordinal', 'prep-target'],
+ 'Scaling': ['prep-standard', 'prep-robust', 'prep-minmax', 'prep-normalizer', 'prep-func-trsfrm-log', 'prep-func-trsfrm-exp', 'prep-poly-feat', 'prep-kbins-discretizer'],
+ }
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model type
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+
+ if (modelType === 'make-column-transformer') {
+ // load mct-targetData
+ that.loadVariableList();
+ that.bindMCT();
+ } else if (modelType === 'prep-simple-imputer') {
+ $(that.wrapSelector('#missing_values')).replaceWith(`
+ ${$(that.wrapSelector('#missing_values'))[0].outerHTML}
+ Text
+
`);
+ $(that.wrapSelector('#fill_value')).replaceWith(`
+ ${$(that.wrapSelector('#fill_value'))[0].outerHTML}
+ Text
+
`);
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > DataPrep');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ });
+ }
+
+ bindMCT() {
+ let that = this;
+ // mct : click column selector 1
+ $(this.wrapSelector('#mct_columns1btn')).on('click', function() {
+ that.openColumnSelector($(that.wrapSelector('#mct_columns1')), 'Select columns to transform');
+ });
+
+ // mct : click column selector 2
+ $(this.wrapSelector('#mct_columns2btn')).on('click', function() {
+ that.openColumnSelector($(that.wrapSelector('#mct_columns2')), 'Select columns to transform');
+ });
+ }
+
+ /**
+ * Open Inner popup page for column selection
+ * @param {Object} targetSelector
+ * @param {string} title
+ * @param {Array} includeList
+ */
+ openColumnSelector(targetSelector, title='Select columns', includeList=[]) {
+ this.popup.type = 'column';
+ this.popup.targetSelector = targetSelector;
+ var previousList = targetSelector.data('list');
+ if (previousList) {
+ previousList = previousList.map(col => col.code)
+ }
+ this.renderMultiSelector(previousList, includeList);
+ this.openInnerPopup(title);
+ }
+
+ /**
+ * Render column selector using MultiSelector module
+ * @param {Array} previousList previous selected columns
+ * @param {Array} includeList columns to include
+ */
+ renderMultiSelector(previousList, includeList) {
+ this.popup.colSelector = new MultiSelector(this.wrapSelector('.vp-inner-popup-body'),
+ { mode: 'columns', parent: [this.state.mct_targetData], selectedList: previousList, includeList: includeList }
+ );
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Data Preparation').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.show();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+ let optBox = new com_String();
+ if (modelType == 'make-column-transformer') {
+ let that = this;
+ // render tag
+ // DataFrame selection
+ optBox.appendLine('DataFrame ');
+ optBox.appendLine(' ');
+ // Estimator 1 selection
+ optBox.appendLine('Estimator 1 ');
+ optBox.appendLine('');
+ optBox.appendFormatLine('{1} ', '', 'None');
+ Object.keys(this.mctEstimator).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.mctEstimator[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.mct_estimator1) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ optBox.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ optBox.appendLine(' ');
+ // Estimator 1 column selection
+ optBox.appendLine('Columns 1 ');
+ optBox.appendLine('');
+ optBox.appendLine(' ');
+ optBox.appendLine('Edit ');
+ optBox.appendLine('
');
+
+ // Estimator 2 selection
+ optBox.appendLine('Estimator 2 ');
+ optBox.appendLine('');
+ optBox.appendFormatLine('{1} ', '', 'None');
+ Object.keys(this.mctEstimator).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.mctEstimator[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.mct_estimator2) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ optBox.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ optBox.appendLine(' ');
+ // Estimator 2 column selection
+ optBox.appendLine('Columns 2 ');
+ optBox.appendLine('');
+ optBox.appendLine(' ');
+ optBox.appendLine('Edit ');
+ optBox.appendLine('
');
+
+ } else {
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // show user option
+ if (config.code.includes('${etc}')) {
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ }
+ }
+ return optBox.toString();
+ }
+
+ /**
+ * Load variable list (dataframe)
+ */
+ loadVariableList() {
+ var that = this;
+ // load using kernel
+ var dataTypes = ['DataFrame'];
+ vpKernel.getDataList(dataTypes).then(function(resultObj) {
+ let { result } = resultObj;
+ try {
+ var varList = JSON.parse(result);
+ // render variable list
+ // get prevvalue
+ var prevValue = that.state.mct_targetData;
+ // replace
+ $(that.wrapSelector('#mct_targetData')).replaceWith(function() {
+ var tag = new com_String();
+ tag.appendFormatLine('', 'mct_targetData');
+ varList.forEach(vObj => {
+ // varName, varType
+ var label = vObj.varName;
+ tag.appendFormatLine('{3} '
+ , vObj.varName, vObj.varType
+ , prevValue == vObj.varName?'selected':''
+ , label);
+ });
+ tag.appendLine(' '); // VP_VS_VARIABLES
+ return tag.toString();
+ });
+ $(that.wrapSelector('#mct_targetData')).trigger('change');
+ } catch (ex) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'DataPrep:', result);
+ }
+ });
+ }
+
+ handleInnerOk() {
+ // ok input popup
+ var dataList = this.popup.colSelector.getDataList();
+
+ $(this.popup.targetSelector).val(dataList.map(col => { return col.code }).join(','));
+ $(this.popup.targetSelector).data('list', dataList);
+ $(this.popup.targetSelector).trigger({ type: 'change', dataList: dataList });
+ this.closeInnerPopup();
+ }
+
+ render() {
+ super.render();
+
+ this.loadVariableList();
+ this.bindMCT();
+
+ // Instance Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let state = JSON.parse(JSON.stringify(this.state));
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+
+ if (modelType === 'prep-simple-imputer') {
+ let checkList = ['missing_values', 'fill_value'];
+ checkList.forEach(checkKey => {
+ try {
+ state[checkKey] = com_util.convertToStr(state[checkKey], state[checkKey + '_istext']);
+ } catch(e) {
+ ;
+ }
+ });
+ }
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, state, (userOption != ''? ', ' + userOption : ''));
+
+ // generate mct code
+ if (modelType === 'make-column-transformer') {
+ let mctCodes = [];
+ let { mct_estimator1, mct_columns1='', mct_estimator2, mct_columns2='' } = state;
+ if (mct_estimator1 != undefined && mct_estimator1 != '') {
+ code.appendLine(this.modelConfig[mct_estimator1].import);
+ let estimator1code = com_generator.vp_codeGenerator(this, this.modelConfig[mct_estimator1], state, (userOption != ''? ', ' + userOption : ''));
+ mctCodes.push(com_util.formatString('({0}, [{1}])', estimator1code, mct_columns1));
+ }
+ if (mct_estimator2 != undefined && mct_estimator2 != '') {
+ code.appendLine(this.modelConfig[mct_estimator2].import);
+ let estimator2code = com_generator.vp_codeGenerator(this, this.modelConfig[mct_estimator2], state, (userOption != ''? ', ' + userOption : ''));
+ mctCodes.push(com_util.formatString('({0}, [{1}])', estimator2code, mct_columns2));
+ }
+ modelCode = modelCode.replace('${mct_code}', mctCodes.join(', '));
+ }
+
+ code.appendLine();
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return DataPrep;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/DataSets.js b/visualpython/js/m_ml/DataSets.js
new file mode 100644
index 00000000..5f0bec3b
--- /dev/null
+++ b/visualpython/js/m_ml/DataSets.js
@@ -0,0 +1,168 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : DataSets.js
+ * Author : Black Logic
+ * Note : Data Sets
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] DataSets
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/dataSets.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+], function(dsHTML, com_util, com_Const, com_String, PopupComponent, com_generator, ML_LIBRARIES) {
+
+ /**
+ * DataSets
+ */
+ class DataSets extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+ this.config.checkModules = ['pd'];
+
+ this.state = {
+ loadType: 'load_iris',
+ userOption: '',
+ allocateTo: 'ldata',
+ ...this.state
+ }
+
+ this.mlConfig = ML_LIBRARIES;
+ this.loadTypeList = {
+ 'Load Data': [
+ // 'load_boston', // `load_boston` has been removed from scikit-learn since version 1.2.
+ 'load_iris', 'load_diabetes', 'load_digits', 'load_linnerud', 'load_wine', 'load_breast_cancer'
+ ],
+ 'Create Data': [
+ 'make_classification', 'make_blobs', 'make_circles', 'make_moons'
+ ]
+ }
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+
+ // select model
+ $(this.wrapSelector('#loadType')).on('change', function() {
+ let loadType = $(this).val();
+ that.state.loadType = loadType;
+ $(that.wrapSelector('.vp-data-option-box')).html(that.templateForOption(loadType));
+
+ // change allocateTo default variable name
+ if (that.loadTypeList['Load Data'].includes(loadType)) {
+ $(that.wrapSelector('#allocateTo')).val('ldata');
+ that.state.allocateTo = 'ldata';
+ } else {
+ $(that.wrapSelector('#allocateTo')).val('df');
+ that.state.allocateTo = 'df';
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(dsHTML);
+
+ let that = this;
+ // load types
+ let loadTypeTag = new com_String();
+ Object.keys(this.loadTypeList).forEach(category => {
+ let optionTag = new com_String();
+ that.loadTypeList[category].forEach(opt => {
+ let optConfig = that.mlConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ optionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ loadTypeTag.appendFormatLine('{1} ',
+ category, optionTag.toString());
+ });
+ $(page).find('#loadType').html(loadTypeTag.toString());
+
+ // render option page
+ $(page).find('.vp-data-option-box').html(this.templateForOption(this.state.loadType));
+
+ return page;
+ }
+
+ templateForOption(loadType) {
+ let config = this.mlConfig[loadType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, opt.name);
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+
+ // show user option
+ if (config.code.includes('${etc}')) {
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ }
+ return optBox.toString();
+ }
+
+ generateCode() {
+ let { loadType, userOption, allocateTo } = this.state;
+ let code = new com_String();
+ let config = this.mlConfig[loadType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+
+ let allocateToVar = allocateTo;
+ if (this.loadTypeList['Load Data'].includes(loadType)) {
+ code.appendFormatLine('{0} = {1}', allocateTo, modelCode);
+ code.appendLine("# Create DataFrame");
+ code.appendFormatLine("df_{0} = pd.DataFrame(data={1}.data, columns={2}.feature_names)", allocateTo, allocateTo, allocateTo);
+ if (loadType == 'load_linnerud') {
+ code.appendFormat("df_{0}[{1}.target_names] = {2}.target", allocateTo, allocateTo, allocateTo);
+ } else {
+ code.appendFormat("df_{0}['target'] = {1}.target", allocateTo, allocateTo);
+ }
+ allocateToVar = 'df_' + allocateTo;
+ } else {
+ code.appendFormatLine("_X, _y = {0}", modelCode);
+ code.appendLine("# Create DataFrame");
+ code.appendLine("_feature_names = ['X{}'.format(i+1) for i in range(len(_X[0]))]");
+ code.appendFormatLine("{0} = pd.DataFrame(data=_X, columns=_feature_names)", allocateTo);
+ code.appendFormat("{0}['target'] = _y", allocateTo);
+ }
+
+ if (allocateToVar != '') {
+ code.appendLine();
+ code.append(allocateToVar);
+ }
+
+
+ return code.toString();
+ }
+ }
+
+ return DataSets;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/DimensionReduction.js b/visualpython/js/m_ml/DimensionReduction.js
new file mode 100644
index 00000000..c35be792
--- /dev/null
+++ b/visualpython/js/m_ml/DimensionReduction.js
@@ -0,0 +1,274 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : DimensionReduction.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] DimensionReduction
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor) {
+
+ /**
+ * DimensionReduction
+ */
+ class DimensionReduction extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'pca',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Dimension Reduction': ['pca', 'lda', 'svd', 'nmf', 'tsne']
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > DimensionReduction');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ })
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Dimension Reduction').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.show();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return DimensionReduction;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/FitPredict.js b/visualpython/js/m_ml/FitPredict.js
new file mode 100644
index 00000000..d48c20c5
--- /dev/null
+++ b/visualpython/js/m_ml/FitPredict.js
@@ -0,0 +1,836 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : FitPredict.js
+ * Author : Black Logic
+ * Note : Model fit / predict
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 04. 20
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] FitPredict
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/fitPredict.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_ml/fitPredict'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/SuggestInput'
+], function(msHtml, msCss, com_util, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, SuggestInput) {
+
+ /**
+ * FitPredict
+ */
+ class FitPredict extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model selection
+ category: 'All',
+ model: '',
+ modelType: '',
+ method: '',
+ action: {},
+ optionConfig: {},
+ modelEditorType: '',
+ modelEditorName: '',
+ userOption: '',
+ ...this.state
+ }
+
+ // categories : Data Preparation / Regression / Classification / Clustering / Dimension Reduction / Auto ML
+ this.modelCategories = [
+ 'All',
+ ...vpConfig.getMLCategories()
+ ]
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.loaded = false;
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // click category
+ $(this.wrapSelector('.vp-ins-select-list.category .vp-ins-select-item')).on('click', function() {
+ let category = $(this).data('var-name');
+
+ that.state.category = category;
+
+ $(that.wrapSelector('.vp-ins-select-list.category .vp-ins-select-item')).removeClass('selected');
+ $(this).addClass('selected');
+
+ // load model list for this category
+ that.loadModelList(category);
+ });
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model category list
+ let modelCategoryTag = new com_String();
+ this.modelCategories.forEach(category => {
+ let selected = '';
+ if (category == that.state.category) {
+ selected = 'selected';
+ }
+ modelCategoryTag.appendFormatLine('{5} ',
+ 'vp-ins-select-item', selected, category, 'category', category, category);
+ });
+ $(page).find('.vp-ins-select-list.category').html(modelCategoryTag.toString());
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let optionConfig = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ optionConfig.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ this.loadModelList(this.state.category);
+ }
+
+ loadModelList(category='') {
+ // reset page
+ try {
+ $(this.wrapSelector('.vp-ins-search')).autocomplete("destroy");
+ } catch { ; }
+ $(this.wrapSelector('.vp-ins-select-list.action')).html('');
+ $(this.wrapSelector('.vp-ins-parameter-box')).html('');
+
+ if (category == 'All') {
+ category = '';
+ }
+ // set model list
+ let that = this;
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList(category).then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach((model, idx) => {
+ let selectFlag = '';
+ // if this item is pre-selected model or first item of model list
+ if ((model.varName == that.state.model)
+ || (that.state.model == '' && idx == 0)) {
+ selectFlag = 'selected';
+ that.state.model = model.varName;
+ that.state.modelType = model.varType;
+ }
+ modelOptionTag.appendFormatLine('{5} ({6}) ',
+ 'vp-ins-select-item', selectFlag, model.varName, model.varType, model.varName, model.varName, model.varType);
+ });
+ $(that.wrapSelector('.vp-ins-select-list.model')).html(modelOptionTag.toString());
+
+ // click model event
+ $(that.wrapSelector('.vp-ins-select-list.model .vp-ins-select-item')).on('click', function() {
+ let model = $(this).data('var-name');
+ let modelType = $(this).data('var-type');
+
+ that.state.model = model;
+ that.state.modelType = modelType;
+
+ $(that.wrapSelector('.vp-ins-select-list.model .vp-ins-select-item')).removeClass('selected');
+ $(this).addClass('selected');
+
+ that.reload();
+ });
+
+ that.reload();
+ });
+ }
+
+ /**
+ * Load options for selected model
+ */
+ reload() {
+ // reset option page
+ try {
+ $(this.wrapSelector('.vp-ins-search')).autocomplete("destroy");
+ } catch { ; }
+ $(this.wrapSelector('.vp-ins-select-list.action')).html('');
+ $(this.wrapSelector('.vp-ins-parameter-box')).html('');
+
+ let model = this.state.model;
+ let modelType = this.state.modelType;
+
+ let actions = this.getAction(modelType);
+ this.state.action = { ...actions };
+
+ var actListTag = new com_String();
+
+ Object.keys(actions).forEach(actKey => {
+ let titleText = actions[actKey].description;
+ if (actions[actKey].name != actions[actKey].label) {
+ titleText = actions[actKey].name + ': ' + titleText;
+ }
+ actListTag.appendFormatLine('{4} ',
+ 'vp-ins-select-item', actKey, 'action', titleText, actions[actKey].label);
+ });
+
+ $(this.wrapSelector('.vp-ins-select-list.action')).html(actListTag.toString());
+
+ let that = this;
+ // action search suggest
+ var suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input');
+ suggestInput.addClass('vp-ins-search');
+ suggestInput.setPlaceholder("Search Action");
+ suggestInput.setSuggestList(function () { return Object.keys(actions); });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.vp-ins-type.action')).val(value);
+
+ $(that.wrapSelector('.vp-ins-select-item[data-var-name="' + value + '"]')).click();
+ });
+ $(that.wrapSelector('.vp-ins-search')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // bind event
+ // click option
+ $(this.wrapSelector('.vp-ins-select-list.action .vp-ins-select-item')).on('click', function() {
+ let name = $(this).data('var-name');
+ let type = $(this).data('var-type');
+
+ that.renderOptionPage(type, name);
+
+ let optionPage = $(that.wrapSelector('.vp-ins-parameter-box')).get(0);
+ optionPage && optionPage.scrollIntoView();
+ });
+
+ // load once on initializing page
+ if (this.loaded == false) {
+ let { modelEditorType, modelEditorName } = this.state;
+ if (modelEditorType != '' && modelEditorName != '') {
+ // render option page for saved state
+ that.renderOptionPage(modelEditorType, modelEditorName);
+ }
+ // set loaded true
+ this.loaded = true;
+ }
+ }
+
+ /**
+ * Render option page for selected option
+ * @param {String} type action / info
+ * @param {String} name option name (ex. fit/predict/...)
+ */
+ renderOptionPage(type, name) {
+ if (this.state[type] != undefined && this.state[type][name] != undefined) {
+ let optionConfig = this.state[type][name];
+ let optBox = new com_String();
+ // render tag
+ optionConfig && optionConfig.options && optionConfig.options.forEach(opt => {
+ let label = opt.name;
+ if (opt.label != undefined) {
+ label = opt.label;
+ }
+ // fix label
+ label = com_util.optionToLabel(label);
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, label);
+ let content = com_generator.renderContent(this, opt.component[0], opt, this.state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // replace option box
+ $(this.wrapSelector('.vp-ins-parameter-box')).html(optBox.toString());
+
+ this.state.optionConfig = optionConfig;
+
+ // add selection
+ let typeClass = '.vp-ins-select-list.' + type;
+ let nameClass = '.vp-ins-select-item[data-var-name="' + name + '"]';
+ $(this.wrapSelector(typeClass + ' ' + '.vp-ins-select-item')).removeClass('selected');
+ $(this.wrapSelector(typeClass + ' ' + nameClass)).addClass('selected');
+ // set state
+ $(this.wrapSelector('#modelEditorType')).val(type);
+ $(this.wrapSelector('#modelEditorName')).val(name);
+ this.state.modelEditorType = type;
+ this.state.modelEditorName = name;
+ }
+ }
+
+ generateCode() {
+ let { model, modelType, modelEditorName } = this.state;
+ let code = new com_String();
+ let replaceDict = {'${model}': model};
+
+ if (this.state.optionConfig.import != undefined) {
+ code.appendLine(this.state.optionConfig.import);
+ code.appendLine();
+ }
+ let modelCode = com_generator.vp_codeGenerator(this, this.state.optionConfig, this.state);
+ if (modelCode) {
+ Object.keys(replaceDict).forEach(key => {
+ modelCode = modelCode.replace(key, replaceDict[key]);
+ });
+ code.append(modelCode);
+
+ let allocateIdx = modelCode.indexOf(' = ');
+ if (allocateIdx >= 0) {
+ let allocateCode = modelCode.substr(0, allocateIdx);
+ code.appendLine();
+ code.append(allocateCode);
+ }
+ // Data Preparation > Scaling
+ const scalingTypeList = ['StandardScaler', 'RobustScaler', 'MinMaxScaler', 'Normalizer'];
+ // Dimension Reduction
+ const dimensionTypeList = ['PCA', 'NMF'];
+ if (scalingTypeList.includes(modelType) || dimensionTypeList.includes(modelType)) {
+ // fit_transform, transform returns df_trans also
+ switch (modelEditorName) {
+ case 'fit_transform':
+ const allocatedFitTrans = this.state.fit_trans_allocate || 'trans';
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("df_{0} = pd.DataFrame({1}, columns=[{2}])", allocatedFitTrans, allocatedFitTrans, this.state.fit_trans_featureData);
+ code.append("df_" + allocatedFitTrans);
+ break;
+ case 'transform':
+ const allocatedTrans = this.state.trans_allocate || 'trans';
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("df_{0} = pd.DataFrame({1}, columns=[{2}])", allocatedTrans, allocatedTrans, this.state.trans_featureData);
+ code.append("df_" + allocatedTrans);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ return code.toString();
+ }
+
+ getModelCategory(modelType) {
+ let mlDict = vpConfig.getMLDataDict();
+ let keys = Object.keys(mlDict);
+ let modelCategory = '';
+ for (let i = 0; i < keys.length; i++) {
+ let key = keys[i];
+ if (mlDict[key].includes(modelType)) {
+ modelCategory = key;
+ break;
+ }
+ }
+ return modelCategory;
+ }
+
+ getAction(modelType) {
+ let category = this.getModelCategory(modelType);
+ let defaultActions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Perform modeling from features, or distance matrix.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict the closest target data X belongs to.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'predict_proba': {
+ name: 'predict_proba',
+ label: 'Predict probability',
+ code: '${pred_prob_allocate} = ${model}.predict_proba(${pred_prob_featureData})',
+ description: 'Predict class probabilities for X.',
+ options: [
+ { name: 'pred_prob_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_prob_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Apply dimensionality reduction to X.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ };
+ let actions = {};
+ switch (category) {
+ case 'Data Preparation':
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit Encoder/Scaler to X.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit Encoder/Scaler to X, then transform X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform labels to normalized encoding.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ if (modelType != 'ColumnTransformer') {
+ actions = {
+ ...actions,
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Transform binary labels back to multi-class labels.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'LabelEncoder') {
+ actions = {
+ ...actions,
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit Encoder/Scaler to X.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit Encoder/Scaler to X, then transform X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform labels to normalized encoding.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X',
+ columnSelection: 'single', returnFrameType: 'Series' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ if (modelType === 'SMOTE') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Check inputs and statistics of the sampler.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ },
+ 'fit_resample': {
+ name: 'fit_resample',
+ label: 'Fit and resample',
+ code: '${fit_res_allocateX}, ${fit_res_allocatey} = ${model}.fit_resample(${fit_res_featureData}, ${fit_res_targetData})',
+ description: 'Resample the dataset.',
+ options: [
+ { name: 'fit_res_allocateX', label: 'Allocate feature', component: ['input'], placeholder: 'New variable', value: 'X_res' },
+ { name: 'fit_res_allocatey', label: 'Allocate target', component: ['input'], placeholder: 'New variable', value: 'y_res' },
+ { name: 'fit_res_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_res_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Regression':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict']
+ }
+ break;
+ case 'Classification':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict'],
+ 'predict_proba': defaultActions['predict_proba'],
+ }
+ if (['LogisticRegression', 'SVC', 'GradientBoostingClassifier'].includes(modelType)) {
+ actions = {
+ ...actions,
+ 'decision_function': {
+ name: 'decision_function',
+ label: 'Decision function',
+ code: '${dec_allocate} = ${model}.decision_function(${dec_featureData})',
+ description: 'Compute the decision function of X.',
+ options: [
+ { name: 'dec_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'dec_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Auto ML':
+ actions = {
+ 'fit': defaultActions['fit'],
+ 'predict': defaultActions['predict'],
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Fit and predict.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'predict_proba': defaultActions['predict_proba']
+ }
+ break;
+ case 'Clustering':
+ if (modelType == 'AgglomerativeClustering'
+ || modelType == 'DBSCAN') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Perform clustering from features, or distance matrix.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' }
+ ]
+ },
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Compute clusters from a data or distance matrix and predict labels.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ }
+ }
+ break;
+ }
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Compute clustering.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict the closest target data X belongs to.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'fit_predict': {
+ name: 'fit_predict',
+ label: 'Fit and predict',
+ code: '${fit_pred_allocate} = ${model}.fit_predict(${fit_pred_featureData})',
+ description: 'Compute cluster centers and predict cluster index for each sample.',
+ options: [
+ { name: 'fit_pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ }
+ }
+ if (modelType == 'KMeans') {
+ actions = {
+ ...actions,
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Compute clustering and transform X to cluster-distance space.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Transform X to a cluster-distance space.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ break;
+ case 'Dimension Reduction':
+ if (modelType == 'TSNE') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit X into an embedded space.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit X into an embedded space and return that transformed output.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ }
+ if (modelType == 'LinearDiscriminantAnalysis') { // LDA
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}, ${fit_targetData})',
+ description: 'Fit the Linear Discriminant Analysis model.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData}${fit_trans_targetData})',
+ description: 'Fit to data, then transform it.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Predict class labels for samples in X.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Project data to maximize class separation.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ }
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData})',
+ description: 'Fit X into an embedded space.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' }
+ ]
+ },
+ 'fit_transform': {
+ name: 'fit_transform',
+ label: 'Fit and transform',
+ code: '${fit_trans_allocate} = ${model}.fit_transform(${fit_trans_featureData})',
+ description: 'Fit the model with X and apply the dimensionality reduction on X.',
+ options: [
+ { name: 'fit_trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'fit_trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ },
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Transform data back to its original space.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Apply dimensionality reduction to X.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X', returnFrameType: 'DataFrame' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ break;
+ case 'ETC':
+ if (modelType === 'GridSearchCV') {
+ actions = {
+ 'fit': {
+ name: 'fit',
+ label: 'Fit',
+ code: '${model}.fit(${fit_featureData}${fit_targetData})',
+ description: 'Run fit with all sets of parameters.',
+ options: [
+ { name: 'fit_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fit_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train', usePair: true, pairKey: 'y' }
+ ]
+ },
+ 'predict': {
+ name: 'predict',
+ label: 'Predict',
+ code: '${pred_allocate} = ${model}.predict(${pred_featureData})',
+ description: 'Call predict on the estimator with the best found parameters.',
+ options: [
+ { name: 'pred_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'pred_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'pred' }
+ ]
+ },
+ 'inverse_transform': {
+ name: 'inverse_transform',
+ label: 'Inverse transform',
+ code: '${inverse_allocate} = ${model}.inverse_transform(${inverse_featureData})',
+ description: 'Call inverse_transform on the estimator with the best found params.',
+ options: [
+ { name: 'inverse_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'inverse_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'inv_trans' }
+ ]
+ },
+ 'transform': {
+ name: 'transform',
+ label: 'Transform',
+ code: '${trans_allocate} = ${model}.transform(${trans_featureData})',
+ description: 'Call transform on the estimator with the best found parameters.',
+ options: [
+ { name: 'trans_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'trans_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'trans' }
+ ]
+ }
+ }
+ }
+ break;
+ }
+ return actions;
+ }
+
+ }
+
+ return FitPredict;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/GridSearch.js b/visualpython/js/m_ml/GridSearch.js
new file mode 100644
index 00000000..1dfdbaa4
--- /dev/null
+++ b/visualpython/js/m_ml/GridSearch.js
@@ -0,0 +1,564 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : GridSearch.js
+ * Author : Black Logic
+ * Note : GridSearch
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 08. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] GridSearch
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/gridSearch.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_ml/gridSearch'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, msCss, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, MultiSelector, SuggestInput, ModelEditor) {
+
+ /**
+ * GridSearch
+ */
+ class GridSearch extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 3;
+ this.config.dataview = false;
+ this.config.docs = 'https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html';
+
+ this.state = {
+ modelType: 'ln-rgs',
+ userOption: '',
+ allocateToCreation: 'model',
+ ...this.state
+ }
+
+ this.targetSetTag = null;
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Regression': ['ln-rgs', 'ridge', 'lasso', 'elasticnet', 'sv-rgs', 'dt-rgs', 'rf-rgs', 'gbm-rgs', 'xgb-rgs', 'lgbm-rgs', 'cb-rgs'],
+ 'Classification': ['lg-rgs', 'bern-nb', 'mulnom-nb', 'gaus-nb', 'sv-clf', 'dt-clf', 'rf-clf', 'gbm-clf', 'xgb-clf', 'lgbm-clf', 'cb-clf']
+ }
+
+
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('click', this.wrapSelector('.vp-param-set-del'));
+ $(document).off('click', this.wrapSelector('.vp-param-item-add'));
+ $(document).off('click', this.wrapSelector('.vp-param-item-del'));
+ $(document).off('keyup', this.wrapSelector('.vp-param-val'));
+ $(document).off('click', this.wrapSelector('.vp-param-result-item-del'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // select model type
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ that.showInstallButton();
+ } else {
+ that.hideInstallButton();
+ }
+
+ that.handleScoringOptions(modelType);
+
+ // reset model param set
+ $(that.wrapSelector('.vp-param-grid-box')).html('');
+ $(that.wrapSelector('.vp-param-grid-box')).html(that.templateForParamSet());
+ });
+
+ // Add param set
+ $(this.wrapSelector('#vp_addParamSet')).on('click', function() {
+ let newSet = $(that.templateForParamSet());
+ $(that.wrapSelector('.vp-param-grid-box')).append(newSet);
+ // focus
+ $(newSet)[0].scrollIntoView();
+ });
+
+ // delete param set
+ $(document).on('click', this.wrapSelector('.vp-param-set-del'), function() {
+ $(this).closest('.vp-param-set-box').remove();
+
+ // rename param set
+ $(that.wrapSelector('.vp-param-set-name')).each((i, tag) => {
+ $(tag).text('Param set ' + (i + 1));
+ });
+ });
+
+ // Add param item
+ $(document).on('click', this.wrapSelector('.vp-param-item-add'), function() {
+ that.targetSetTag = $(this).parent(); // target param-set-box
+ that.openParamPopup();
+ });
+
+ // Delete param item
+ $(document).on('click', this.wrapSelector('.vp-param-item-del'), function() {
+ $(this).closest('.vp-param-item').remove();
+ });
+
+ // add param value - using enter
+ $(document).on('keyup', this.wrapSelector('.vp-param-val'), function(event) {
+ var keycode = event.keyCode
+ ? event.keyCode
+ : event.which;
+ if (keycode == vpEvent.keyManager.keyCode.enter) { // enter
+ that.handleAddParamValue($(this));
+ }
+ if (keycode === 188) {// ,<
+ let val = $(this).val();
+ $(this).val(val.split(',')[0]); // remove , and add param
+ that.handleAddParamValue($(this));
+ }
+ });
+
+ // delete param set item
+ $(document).on('click', this.wrapSelector('.vp-param-result-item-del'), function() {
+ $(this).closest('.vp-param-result-item').remove();
+ });
+ }
+
+ handleAddParamValue(thisTag) {
+ let parentTag = $(thisTag).parent();
+ let paramIsText = $(parentTag).find('.vp-param-val').data('type') === 'text'; // text / var
+ let paramVal = $(parentTag).find('.vp-param-val').val();
+ let reservedKeywordList = ['None', 'True', 'False', 'np.nan', 'np.NaN'];
+ if (reservedKeywordList.includes(paramVal)) {
+ paramIsText = false;
+ }
+ // check , and split it
+ let paramSplit = paramVal.split(',');
+ paramSplit && paramSplit.forEach(val => {
+ // add only if it is not empty value
+ if (val.trim() !== '') {
+ val = com_util.convertToStr(val.trim(), paramIsText);
+ $(parentTag).find('.vp-param-result-box').append(`
+ ${val}
+
+
+ `);
+ // clear param val
+ $(parentTag).find('.vp-param-val').val('');
+ }
+ });
+ }
+
+ bindEventForInnerPopup() {
+ let that = this;
+ // Inner popup: Select param
+ $(document).off('click', this.wrapSelector('.vp-inner-param-list-item'));
+ $(document).on('click', this.wrapSelector('.vp-inner-param-list-item'), function() {
+ if ($(this).hasClass('selected')) {
+ $(this).removeClass('selected');
+ } else {
+ $(this).addClass('selected');
+ }
+ });
+
+ // Inner popup: Add param
+ $(this.wrapSelector('.vp-add-param-btn')).on('click', function() {
+ let newParam = $(that.wrapSelector('.vp-add-param-name')).val();
+ if (newParam != undefined && newParam.trim() != '') {
+ // check if exist
+ let checkTag = $(that.wrapSelector(`.vp-inner-param-list-item[data-name="${newParam}"]`));
+ if (checkTag.length > 0) {
+ if (!checkTag.hasClass('selected')) {
+ checkTag.addClass('selected');
+ }
+ checkTag[0].scrollIntoView();
+ } else {
+ // add to param list
+ $(that.wrapSelector('.vp-inner-param-list-box')).append(
+ `${newParam}
`
+ );
+ // scroll to added item
+ $(that.wrapSelector('.vp-inner-param-list-item.selected:last'))[0].scrollIntoView();
+ }
+
+ // clear input value
+ $(that.wrapSelector('.vp-add-param-name')).val('');
+ }
+ });
+ }
+
+ handleScoringOptions(modelType) {
+ let options = {
+ 'Classification': [
+ "'accuracy'",
+ "'balanced_accuracy'",
+ "'top_k_accuracy'",
+ "'average_precision'",
+ "'neg_brier_score'",
+ "'f1'",
+ "'f1_micro'",
+ "'f1_macro'",
+ "'f1_weighted'",
+ "'f1_samples'",
+ "'neg_log_loss'",
+ "'precision' etc.",
+ "'recall' etc.",
+ "'jaccard' etc.",
+ "'roc_auc'",
+ "'roc_auc_ovr'",
+ "'roc_auc_ovo'",
+ "'roc_auc_ovr_weighted'",
+ "'roc_auc_ovo_weighted'",
+ ],
+ 'Regression': [
+ "'explained_variance'",
+ "'max_error'",
+ "'neg_mean_absolute_error'",
+ "'neg_mean_squared_error'",
+ "'neg_root_mean_squared_error'",
+ "'neg_mean_squared_log_error'",
+ "'neg_median_absolute_error'",
+ "'r2'",
+ "'neg_mean_poisson_deviance'",
+ "'neg_mean_gamma_deviance'",
+ "'neg_mean_absolute_percentage_error'",
+ "'d2_absolute_error_score'",
+ "'d2_pinball_score'",
+ "'d2_tweedie_score'"
+ ]
+ }
+ let modelCategory = this.modelTypeList['Regression'].includes(modelType)?'Regression':'Classification';
+
+ // Set suggestInput on scoring option
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('scoring');
+ suggestInput.setPlaceholder('Select option');
+ suggestInput.addClass('vp-input vp-state');
+ suggestInput.setSuggestList(function() { return options[modelCategory]; });
+ suggestInput.setNormalFilter(true);
+ $(this.wrapSelector('#scoring')).replaceWith(suggestInput.toTagString());
+ }
+
+ templateForParamSet() {
+ let paramSetNo = 1;
+ // set param set number
+ paramSetNo += $(this.wrapSelector('.vp-param-set-box')).length;
+ return `
+
+
Param set ${paramSetNo}
+
+
+
+
+
+
+ Add param
+
`;
+ }
+
+ templateForParamPopup() {
+ let config = this.modelConfig[this.state.modelType];
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2}
'
+ , opt.name, opt.name, opt.name);
+ });
+
+ return `
+ NOTE: Select parameters to add.
+
+ ${optBox.toString()}
+
+
+
+ Add
+
+ `;
+ }
+
+ openParamPopup() {
+ let size = { width: 400, height: 300 };
+
+ $(this.wrapSelector('.vp-inner-popup-body')).empty();
+
+ // set size and position
+ $(this.wrapSelector('.vp-inner-popup-box')).css({
+ width: size.width,
+ height: size.height,
+ left: 'calc(50% - ' + (size.width/2) + 'px)',
+ top: 'calc(50% - ' + (size.height/2) + 'px)',
+ });
+
+ $(this.wrapSelector('.vp-inner-popup-body')).html(this.templateForParamPopup());
+
+ this.bindEventForInnerPopup();
+
+ // show popup box
+ this.openInnerPopup('Add parameter');
+ }
+
+ handleInnerOk() {
+ // get selected param list
+ let paramList = [];
+ $(this.wrapSelector('.vp-inner-param-list-item.selected')).each((i, tag) => {
+ paramList.push($(tag).data('name'));
+ });
+
+ if (paramList.length > 0) {
+ // add param box
+ $(this.targetSetTag).find('.vp-param-item-box').append(this.templateForParamItemList(paramList));
+
+ this.closeInnerPopup();
+ } else {
+ com_util.renderAlertModal('No params selected. Please select more than one param.');
+ }
+
+ this.targetSetTag = null;
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ //================================================================
+ // GridSearch option
+ //================================================================
+ $(page).find('.vp-model-option-box').html(this.templateForOption('grid-search', ['estimator', 'param_grid']));
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ this.showInstallButton();
+ } else {
+ this.hideInstallButton();
+ }
+
+ // render option page
+ // $(page).find('.vp-model-param-box').html(this.templateForOption(this.state.modelType));
+
+ return page;
+ }
+
+ templateForOption(modelType, excludeOptList=[]) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ if (!excludeOptList.includes(opt.name)) {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ }
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ /**
+ * template for param box
+ * @param {*} paramList ['param-name1', 'param-name2', ...]
+ */
+ templateForParamItemList(paramList) {
+ let that = this;
+ let config = this.modelConfig[this.state.modelType];
+ let paramSet = new com_String();
+ paramList && paramList.forEach(name => {
+ // get option component
+ let componentType = 'input'; // default
+ let paramObj = config.options.filter(x => x.name === name).at(0);
+ if ((paramObj !== undefined) && (['option_select', 'bool_select'].includes(paramObj.component[0]))) {
+ componentType = 'option';
+ }
+ paramSet.appendLine('');
+ paramSet.appendFormatLine('
{1} ', name, com_util.optionToLabel(name));
+ paramSet.appendLine('
');
+ paramSet.appendLine('
'); // vp-param-item
+ });
+ return paramSet.toString();
+ }
+
+ render() {
+ super.render();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+
+ this.handleScoringOptions(this.state.modelType);
+ }
+
+ generateInstallCode() {
+ let installCode = this.modelConfig[this.state.modelType].install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ return [ installCode ];
+ }
+
+ checkBeforeRun() {
+ // if no param is registered, stop and show alert
+ if ($(this.wrapSelector('.vp-param-result-item')).length <= 0) {
+ com_util.renderAlertModal('No params added. Please add params.');
+ return false;
+ }
+
+ return true;
+ }
+
+ generateCode() {
+ let { modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let gsConfig = this.modelConfig['grid-search'];
+
+
+ let state = JSON.parse(JSON.stringify(this.state));
+ let estConfig = this.modelConfig[this.state.modelType];
+ let estimator = com_generator.vp_codeGenerator(null, estConfig, {}, '');
+ state['estimator'] = estimator;
+ state['param_grid'] = '{}';
+
+ let paramGrid = [];
+ // generate param_grid
+ $(this.wrapSelector('.vp-param-set-box')).each((i, tag) => {
+ let paramSet = {};
+ $(tag).find('.vp-param-result-box').each((j, resTag) => {
+ let paramName = $(resTag).data('name');
+ let paramValList = [];
+ $(resTag).find('.vp-param-result-item').each((k, itemTag) => {
+ let val = $(itemTag).data('value');
+ if (!isNaN(val)) {
+ // numeric string -> numeric
+ val = parseFloat(val);
+ }
+ paramValList.push(val);
+ });
+ if (paramValList.length > 0) {
+ // Add only its result exists
+ paramSet[paramName] = paramValList;
+ }
+ });
+ if (Object.keys(paramSet).length > 0) {
+ paramGrid.push(paramSet);
+ }
+ });
+
+ state['param_grid'] = this.paramStringify(paramGrid);
+
+ // import code
+ code.appendLine(gsConfig.import);
+ code.appendLine(estConfig.import);
+
+ // model code
+ let gsCode = gsConfig.code;
+ gsCode = com_generator.vp_codeGenerator(this, gsConfig, state, (userOption != ''? ', ' + userOption : ''));
+ code.appendLine();
+ code.appendFormat('{0} = {1}', allocateToCreation, gsCode);
+
+ return code.toString();
+ }
+
+ paramStringify(paramGridList=[]) {
+ let paramGridCode = new com_String();
+ if (paramGridList.length > 1) {
+ paramGridCode.append('[');
+ }
+ paramGridList.forEach((paramSet, i) => {
+ if (i > 0) {
+ paramGridCode.append(', \n ');
+ }
+ paramGridCode.append('{');
+ Object.keys(paramSet).forEach((paramName, j) => {
+ if (j > 0) {
+ paramGridCode.append(', ');
+ }
+ paramGridCode.appendFormat("'{0}': [{1}]", paramName, paramSet[paramName].toString());
+ });
+ paramGridCode.append('}');
+ })
+
+ if (paramGridList.length > 1) {
+ paramGridCode.append(']');
+ }
+ return paramGridCode.toString();
+ }
+
+ }
+
+ return GridSearch;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/ModelInfo.js b/visualpython/js/m_ml/ModelInfo.js
new file mode 100644
index 00000000..23bf679b
--- /dev/null
+++ b/visualpython/js/m_ml/ModelInfo.js
@@ -0,0 +1,943 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : ModelInfo.js
+ * Author : Black Logic
+ * Note : Model information
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 04. 20
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] ModelInfo
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/modelInfo.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_ml/modelInfo'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/SuggestInput'
+], function(msHtml, msCss, com_util, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, SuggestInput) {
+
+ /**
+ * ModelInfo
+ */
+ class ModelInfo extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model selection
+ category: 'All',
+ model: '',
+ modelType: '',
+ method: '',
+ info: {},
+ optionConfig: {},
+ userOption: '',
+ ...this.state
+ }
+
+ // categories : Data Preparation / Regression / Classification / Clustering / Dimension Reduction / Auto ML
+ this.modelCategories = [
+ 'All',
+ ...vpConfig.getMLCategories()
+ ]
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.loaded = false;
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // click category
+ $(this.wrapSelector('.vp-ins-select-list.category .vp-ins-select-item')).on('click', function() {
+ let category = $(this).data('var-name');
+
+ that.state.category = category;
+
+ $(that.wrapSelector('.vp-ins-select-list.category .vp-ins-select-item')).removeClass('selected');
+ $(this).addClass('selected');
+
+ // load model list for this category
+ that.loadModelList(category);
+ });
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model category list
+ let modelCategoryTag = new com_String();
+ this.modelCategories.forEach(category => {
+ let selected = '';
+ if (category == that.state.category) {
+ selected = 'selected';
+ }
+ modelCategoryTag.appendFormatLine('{5} ',
+ 'vp-ins-select-item', selected, category, 'category', category, category);
+ });
+ $(page).find('.vp-ins-select-list.category').html(modelCategoryTag.toString());
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let optionConfig = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ optionConfig.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ this.loadModelList(this.state.category);
+ }
+
+ loadModelList(category='') {
+ // reset page
+ try {
+ $(this.wrapSelector('.vp-ins-search')).autocomplete("destroy");
+ } catch { ; }
+ $(this.wrapSelector('.vp-ins-select-list.info')).html('');
+ $(this.wrapSelector('.vp-ins-parameter-box')).html('');
+
+ if (category == 'All') {
+ category = '';
+ }
+ // set model list
+ let that = this;
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList(category).then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach((model, idx) => {
+ let selectFlag = '';
+ // if this item is pre-selected model or first item of model list
+ if ((model.varName == that.state.model)
+ || (that.state.model == '' && idx == 0)) {
+ selectFlag = 'selected';
+ that.state.model = model.varName;
+ that.state.modelType = model.varType;
+ }
+ modelOptionTag.appendFormatLine('{5} ({6}) ',
+ 'vp-ins-select-item', selectFlag, model.varName, model.varType, model.varName, model.varName, model.varType);
+ });
+ $(that.wrapSelector('.vp-ins-select-list.model')).html(modelOptionTag.toString());
+
+ // click model event
+ $(that.wrapSelector('.vp-ins-select-list.model .vp-ins-select-item')).on('click', function() {
+ let model = $(this).data('var-name');
+ let modelType = $(this).data('var-type');
+
+ that.state.model = model;
+ that.state.modelType = modelType;
+
+ $(that.wrapSelector('.vp-ins-select-list.model .vp-ins-select-item')).removeClass('selected');
+ $(this).addClass('selected');
+
+ that.reload();
+ });
+
+ that.reload();
+ });
+ }
+
+ /**
+ * Load options for selected model
+ */
+ reload() {
+ // reset option page
+ try {
+ $(this.wrapSelector('.vp-ins-search')).autocomplete("destroy");
+ } catch { ; }
+ $(this.wrapSelector('.vp-ins-select-list.info')).html('');
+ $(this.wrapSelector('.vp-ins-parameter-box')).html('');
+
+ let model = this.state.model;
+ let modelType = this.state.modelType;
+
+ let infos = this.getInfo(modelType);
+ this.state.info = { ...infos };
+
+ var infoListTag = new com_String();
+
+ Object.keys(infos).forEach(infoKey => {
+ let titleText = infos[infoKey].description;
+ if (infos[infoKey].name != infos[infoKey].label) {
+ titleText = infos[infoKey].name + ': ' + titleText;
+ }
+ infoListTag.appendFormatLine('{4} ',
+ 'vp-ins-select-item', infoKey, 'info', titleText, infos[infoKey].label);
+ });
+
+ $(this.wrapSelector('.vp-ins-select-list.info')).html(infoListTag.toString());
+
+ let that = this;
+ // info search suggest
+ let suggestInput = new SuggestInput();
+ suggestInput.addClass('vp-input');
+ suggestInput.addClass('vp-ins-search');
+ suggestInput.setPlaceholder("Search information");
+ suggestInput.setSuggestList(function () { return Object.keys(infos); });
+ suggestInput.setSelectEvent(function (value, item) {
+ $(this.wrapSelector()).val(value);
+ $(that.wrapSelector('.vp-ins-type.info')).val(value);
+
+ $(that.wrapSelector('.vp-ins-select-item[data-var-name="' + value + '"]')).click();
+ });
+ $(that.wrapSelector('.vp-ins-search')).replaceWith(function () {
+ return suggestInput.toTagString();
+ });
+
+ // bind event
+ // click option
+ $(this.wrapSelector('.vp-ins-select-list.info .vp-ins-select-item')).on('click', function() {
+ let name = $(this).data('var-name');
+ let type = $(this).data('var-type');
+
+ if (name == 'feature_importances') {
+ that.config.checkModules = ['pd', 'vp_create_feature_importances'];
+ } else if (name == 'plot_feature_importances') {
+ that.config.checkModules = ['pd', 'plt', 'vp_create_feature_importances', 'vp_plot_feature_importances'];
+ } else if (name == 'permutation_importance') {
+ that.config.checkModules = ['pd', 'vp_create_permutation_importances'];
+ } else if (name == 'plot_permutation_importance') {
+ that.config.checkModules = ['pd', 'vp_create_permutation_importances', 'vp_plot_permutation_importances'];
+ } else {
+ that.config.checkModules = ['pd'];
+ }
+
+ that.renderOptionPage(type, name);
+
+ let optionPage = $(that.wrapSelector('.vp-ins-parameter-box')).get(0);
+ optionPage && optionPage.scrollIntoView();
+ });
+
+ // load once on initializing page
+ if (this.loaded == false) {
+ let { modelEditorType, modelEditorName } = this.state;
+ if (modelEditorType != '' && modelEditorName != '') {
+ // render option page for saved state
+ that.renderOptionPage(modelEditorType, modelEditorName);
+ }
+ // set loaded true
+ this.loaded = true;
+ }
+ }
+
+ /**
+ * Render option page for selected option
+ * @param {String} type action / info
+ * @param {String} name option name (ex. fit/predict/...)
+ */
+ renderOptionPage(type, name) {
+ if (this.state[type] != undefined && this.state[type][name] != undefined) {
+ let optionConfig = this.state[type][name];
+ let optBox = new com_String();
+ // render tag
+ optionConfig && optionConfig.options && optionConfig.options.forEach(opt => {
+ let label = opt.name;
+ if (opt.label != undefined) {
+ label = opt.label;
+ }
+ // fix label
+ label = com_util.optionToLabel(label);
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, label);
+ let content = com_generator.renderContent(this, opt.component[0], opt, this.state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // replace option box
+ $(this.wrapSelector('.vp-ins-parameter-box')).html(optBox.toString());
+
+ this.state.optionConfig = optionConfig;
+
+ // add selection
+ let typeClass = '.vp-ins-select-list.' + type;
+ let nameClass = '.vp-ins-select-item[data-var-name="' + name + '"]';
+ $(this.wrapSelector(typeClass + ' ' + '.vp-ins-select-item')).removeClass('selected');
+ $(this.wrapSelector(typeClass + ' ' + nameClass)).addClass('selected');
+ // set state
+ $(this.wrapSelector('#modelEditorType')).val(type);
+ $(this.wrapSelector('#modelEditorName')).val(name);
+ this.state.modelEditorType = type;
+ this.state.modelEditorName = name;
+ }
+ }
+
+ generateCode() {
+ let { model } = this.state;
+ let codeList = [];
+ let code = new com_String();
+ let replaceDict = {'${model}': model};
+
+ // If functions are available
+ if (this.state.optionConfig.functions != undefined) {
+ this.state.optionConfig.functions.forEach(func => {
+ codeList.push(func);
+ });
+ }
+
+ // If import code is available, generate its code in front of code
+ if (this.state.optionConfig.import != undefined) {
+ code.appendLine(this.state.optionConfig.import);
+ code.appendLine();
+ }
+
+ // Auto-generate model info code
+ let modelCode = com_generator.vp_codeGenerator(this, this.state.optionConfig, this.state);
+ if (modelCode) {
+ Object.keys(replaceDict).forEach(key => {
+ modelCode = modelCode.replace(key, replaceDict[key]);
+ });
+ code.append(modelCode);
+
+ // Exception for re-generating allocate variables
+ if (!modelCode.includes('plt.show()')) {
+ // Find allocate variable
+ let allocateIdx = modelCode.indexOf(' = ');
+ if (allocateIdx >= 0) {
+ // if available, show again to display its value
+ let allocateCode = modelCode.substr(0, allocateIdx);
+ code.appendLine();
+ code.append(allocateCode);
+ }
+ }
+ }
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ getModelCategory(modelType) {
+ let mlDict = vpConfig.getMLDataDict();
+ let keys = Object.keys(mlDict);
+ let modelCategory = '';
+ for (let i = 0; i < keys.length; i++) {
+ let key = keys[i];
+ if (mlDict[key].includes(modelType)) {
+ modelCategory = key;
+ break;
+ }
+ }
+ return modelCategory;
+ }
+
+ getInfo(modelType) {
+ let category = this.getModelCategory(modelType);
+ let infos = {};
+ let defaultInfos = {
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData}, ${score_targetData})',
+ description: '',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'score_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'get_params': {
+ name: 'get_params',
+ label: 'Get parameters',
+ code: '${param_allocate} = ${model}.get_params(${deep})',
+ description: 'Get parameters for this estimator.',
+ options: [
+ { name: 'deep', component: ['bool_select'], default: 'True', usePair: true },
+ { name: 'param_allocate', label: 'Allocate to', component: ['input'], value: 'params' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ 'feature_importances': {
+ name: 'feature_importances',
+ label: 'Feature importances',
+ code: "${fi_allocate} = vp_create_feature_importances(${model}, ${fi_featureData}${sort})",
+ description: 'Allocate feature_importances_',
+ options: [
+ { name: 'fi_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'fi_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'df_i' },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true }
+ ]
+ },
+ 'plot_feature_importances': {
+ name: 'plot_feature_importances',
+ label: 'Plot feature importances',
+ code: "vp_plot_feature_importances(${model}, ${fi_featureData}${sort}${top_count})",
+ description: 'Draw feature_importances_',
+ options: [
+ { name: 'fi_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true },
+ ]
+ }
+ }
+ switch (category) {
+ case 'Data Preparation':
+ if (modelType == 'OneHotEncoder') {
+ infos = {
+ 'categories_': { // TODO:
+ name: 'categories_',
+ label: 'Categories',
+ code: '${categories_allocate} = ${model}.categories_',
+ description: 'The categories of each feature determined during fitting',
+ options: [
+ { name: 'categories_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'categories' }
+ ]
+ },
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'LabelEncoder') {
+ infos = {
+ 'classes_': {
+ name: 'classes_',
+ label: 'Classes',
+ code: '${classes_allocate} = ${model}.classes_',
+ description: 'Holds the label for each class.',
+ options: [
+ { name: 'classes_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'classes' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'KBinsDiscretizer') {
+ infos = {
+ 'bin_edges': { // TODO:
+ name: 'bin_edges',
+ label: 'Bin edges',
+ code: '${bin_edges_allocate} = ${model}.bin_edges_',
+ description: 'The edges of each bin. Contain arrays of varying shapes',
+ options: [
+ { name: 'bin_edges_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'bin_edges' }
+ ]
+ }
+ }
+ }
+ if (modelType == 'ColumnTransformer') {
+ infos = {
+ 'transformers_': {
+ name: 'transformers_',
+ label: 'Transformers_',
+ code: '${transformers_allocate} = ${model}.transformers_',
+ description: 'The collection of fitted transformers as tuples of (name, fitted_transformer, column).',
+ options: [
+ { name: 'transformers_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'classes' }
+ ]
+ },
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ if (modelType === 'SMOTE') {
+ infos = {
+ 'get_feature_names_out': {
+ name: 'get_feature_names_out',
+ label: 'Get feature names',
+ code: '${feature_names_allocate} = ${model}.get_feature_names_out()',
+ description: 'Get output feature names for transformation.',
+ options: [
+ { name: 'feature_names_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'features' }
+ ]
+ }
+ }
+ }
+ infos = {
+ ...infos,
+ 'get_params': defaultInfos['get_params']
+ }
+ break;
+ case 'Regression':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the coefficient of determination of the prediction.'
+ },
+ 'cross_val_score': {
+ name: 'cross_val_score',
+ label: 'Cross validation score',
+ import: 'from sklearn.model_selection import cross_val_score',
+ code: '${cvs_allocate} = cross_val_score(${model}, ${cvs_featureData}, ${cvs_targetData}${scoring}${cv})',
+ description: 'Evaluate a score by cross-validation.',
+ options: [
+ { name: 'cvs_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'cvs_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'scoring', component: ['option_select'], usePair: true, type: 'text',
+ options: [
+ '',
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'cv', label: 'Cross Validation', component: ['input_number'], placeholder: '1 ~ 10', default: 5, usePair: true },
+ { name: 'cvs_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'explained_variance', 'max_error', 'neg_mean_absolute_error', 'neg_mean_squared_error', 'neg_root_mean_squared_error',
+ 'neg_mean_squared_log_error', 'neg_median_absolute_error', 'r2', 'neg_mean_poisson_deviance', 'neg_mean_gamma_deviance',
+ 'neg_mean_absolute_percentage_error'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ 'Coefficient': {
+ name: 'coef_',
+ label: 'Coefficient',
+ code: '${coef_allocate} = ${model}.coef_',
+ description: 'Weights assigned to the features.',
+ options: [
+ { name: 'coef_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'coef' }
+ ]
+ },
+ 'Intercept': {
+ name: 'intercept_',
+ label: 'Intercept',
+ code: '${intercept_allocate} = ${model}.intercept_',
+ description: 'Constants in decision function.',
+ options: [
+ { name: 'intercept_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'intercepts' }
+ ]
+ }
+ }
+ let svcList = [
+ 'DecisionTreeRegressor',
+ 'RandomForestRegressor',
+ 'GradientBoostingRegressor',
+ 'XGBRegressor', 'LGBMRegressor', 'CatBoostRegressor'
+ ];
+ if (svcList.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'feature_importances': defaultInfos['feature_importances'],
+ 'plot_feature_importances': defaultInfos['plot_feature_importances']
+ }
+ }
+ break;
+ case 'Classification':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'cross_val_score': {
+ name: 'cross_val_score',
+ label: 'Cross validation score',
+ import: 'from sklearn.model_selection import cross_val_score',
+ code: '${cvs_allocate} = cross_val_score(${model}, ${cvs_featureData}, ${cvs_targetData}${scoring}${cv})',
+ description: 'Evaluate a score by cross-validation.',
+ options: [
+ { name: 'cvs_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'cvs_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'scoring', component: ['option_select'], usePair: true, type: 'text',
+ options: [
+ '',
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'cv', label: 'Cross Validation', component: ['input_number'], placeholder: '1 ~ 10', default: 5, usePair: true },
+ { name: 'cvs_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ },
+ 'roc_curve': {
+ name: 'roc_curve',
+ label: 'ROC Curve',
+ import: 'from sklearn import metrics',
+ code: "fpr, tpr, thresholds = metrics.roc_curve(${roc_targetData}, ${model}.predict_proba(${roc_featureData})[:, 1])\
+ \nplt.plot(fpr, tpr, label='ROC Curve')\
+ \nplt.xlabel('Sensitivity')\
+ \nplt.ylabel('Specificity')\
+ \nplt.show()",
+ description: '',
+ options: [
+ { name: 'roc_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'roc_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_test' }
+ ]
+ },
+ 'auc': {
+ name: 'auc',
+ label: 'AUC',
+ import: 'from sklearn import metrics',
+ code: 'metrics.roc_auc_score(${auc_targetData}, ${model}.predict_proba(${auc_featureData})[:, 1])',
+ description: '',
+ options: [
+ { name: 'auc_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_test' },
+ { name: 'auc_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_test' }
+ ]
+ },
+ 'permutation_importance': {
+ name: 'permutation_importance',
+ label: 'Permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: '${importance_allocate} = vp_create_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'importance_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'importances' }
+ ]
+ },
+ 'plot_permutation_importance': {
+ name: 'plot_permutation_importance',
+ label: 'Plot permutation importance',
+ import: 'from sklearn.inspection import permutation_importance',
+ code: 'vp_plot_permutation_importances(${model}, ${importance_featureData}, ${importance_targetData}${scoring}${sort}${top_count})',
+ description: 'Permutation importance for feature evaluation.',
+ options: [
+ { name: 'importance_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X_train' },
+ { name: 'importance_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y_train' },
+ { name: 'scoring', component: ['option_suggest'], usePair: true, type: 'text',
+ options: [
+ 'accuracy', 'balanced_accuracy', 'top_k_accuracy', 'average_precision', 'neg_brier_score',
+ 'f1', 'f1_micro', 'f1_macro', 'f1_weighted', 'f1_samples', 'neg_log_loss', 'precision', 'recall', 'jaccard',
+ 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo', 'roc_auc_ovr_weighted', 'roc_auc_ovo_weighted'
+ ] },
+ { name: 'sort', label: 'Sort data', component: ['bool_checkbox'], value: true, usePair: true },
+ { name: 'top_count', label: 'Top count', component: ['input_number'], min: 0, usePair: true }
+ ]
+ },
+ }
+
+ // feature importances
+ let clfList = [
+ 'DecisionTreeClassifier',
+ 'RandomForestClassifier',
+ 'GradientBoostingClassifier',
+ 'XGBClassifier',
+ 'LGBMClassifier',
+ 'CatBoostClassifier',
+ ]
+ if (clfList.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'feature_importances': defaultInfos['feature_importances'],
+ 'plot_feature_importances': defaultInfos['plot_feature_importances']
+ }
+ }
+
+ // use decision_function on ROC, AUC
+ let decisionFunctionTypes = [
+ 'LogisticRegression', 'SVC', 'GradientBoostingClassifier'
+ ];
+ if (decisionFunctionTypes.includes(modelType)) {
+ infos = {
+ ...infos,
+ 'roc_curve': {
+ ...infos['roc_curve'],
+ code: "fpr, tpr, thresholds = metrics.roc_curve(${roc_targetData}, ${model}.decision_function(${roc_featureData}))\
+ \nplt.plot(fpr, tpr, label='ROC Curve')\
+ \nplt.xlabel('Sensitivity')\
+ \nplt.ylabel('Specificity')\
+ \nplt.show()"
+ },
+ 'auc': {
+ ...infos['auc'],
+ code: 'metrics.roc_auc_score(${auc_targetData}, ${model}.decision_function(${auc_featureData}))',
+ }
+ }
+ }
+ break;
+ case 'Auto ML':
+ infos = {
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'get_params': {
+ ...defaultInfos['get_params']
+ }
+ }
+ break;
+ case 'Clustering':
+ infos = {
+ 'get_params': {
+ ...defaultInfos['get_params']
+ }
+ }
+
+ if (modelType == 'KMeans') {
+ infos = {
+ ...infos,
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Return the mean accuracy on the given test data and labels.'
+ },
+ 'cluster_centers_': {
+ name: 'cluster_centers',
+ label: 'Cluster centers',
+ code: '${centers_allocate} = ${model}.cluster_centers_',
+ description: 'Coordinates of cluster centers.',
+ options: [
+ { name: 'centers_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'cluster_centers' }
+ ]
+ }
+ }
+ }
+
+ if (modelType == 'AgglomerativeClustering') {
+ infos = {
+ ...infos,
+ 'Dendrogram': { // FIXME:
+ name: 'dendrogram',
+ label: 'Dendrogram',
+ code: "# import\nfrom scipy.cluster.hierarchy import dendrogram, ward\n\nlinkage_array = ward(${dendro_data})\ndendrogram(linkage_array, p=3, truncate_mode='level', no_labels=True)\nplt.show()",
+ description: 'Draw a dendrogram',
+ options: [
+ { name: 'dendro_data', label: 'Data', component: ['data_select'], var_type: ['DataFrame'] }
+ ]
+ }
+ }
+ }
+
+ if (modelType == 'GaussianMixture') {
+ infos = {
+ ...infos,
+ 'score': {
+ ...defaultInfos['score'],
+ description: 'Compute the per-sample average log-likelihood of the given data X.'
+ }
+ }
+ }
+ break;
+ case 'Dimension Reduction':
+ if (modelType == 'LDA') {
+ infos = {
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData}, ${score_targetData})',
+ description: 'Return the average log-likelihood of all samples.',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'score_targetData', label: 'Target Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'y' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ }
+ }
+ break;
+ }
+ if (modelType == 'PCA') {
+ infos = {
+ 'explained_variance_ratio_': {
+ name: 'explained_variance_ratio_',
+ label: 'Explained variance ratio',
+ code: '${ratio_allocate} = ${model}.explained_variance_ratio_',
+ description: 'Percentage of variance explained by each of the selected components.',
+ options: [
+ { name: 'ratio_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'ratio' }
+ ]
+ }
+ }
+ }
+ infos = {
+ ...infos,
+ 'score': {
+ name: 'score',
+ label: 'Score',
+ code: '${score_allocate} = ${model}.score(${score_featureData})',
+ description: 'Return the average log-likelihood of all samples.',
+ options: [
+ { name: 'score_featureData', label: 'Feature Data', component: ['data_select'], var_type: ['DataFrame', 'Series', 'ndarray', 'list', 'dict'], value: 'X' },
+ { name: 'score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'scores' }
+ ]
+ }
+ }
+ break;
+ case 'ETC':
+ if (modelType === 'GridSearchCV') {
+ infos = {
+ 'best_estimator_': {
+ name: 'best_estimator_',
+ label: 'Best estimator',
+ code: '${best_estimator_allocate} = ${model}.best_estimator_',
+ description: 'Estimator that was chosen by the search.',
+ options: [
+ { name: 'best_estimator_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_estimator' }
+ ]
+ },
+ 'best_score_': {
+ name: 'best_score_',
+ label: 'Best score',
+ code: '${best_score_allocate} = ${model}.best_score_',
+ description: 'Mean cross-validated score of the best_estimator.',
+ options: [
+ { name: 'best_score_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_score' }
+ ]
+ },
+ 'best_params_': {
+ name: 'best_params_',
+ label: 'Best params',
+ code: '${best_params_allocate} = ${model}.best_params_',
+ description: 'Parameter setting that gave the best results on the hold out data.',
+ options: [
+ { name: 'best_params_allocate', label: 'Allocate to', component: ['input'], placeholder: 'New variable', value: 'best_params' }
+ ]
+ }
+ }
+ }
+ break;
+ }
+ return infos;
+ }
+
+ }
+
+ return ModelInfo;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/Pipeline.js b/visualpython/js/m_ml/Pipeline.js
new file mode 100644
index 00000000..856c33db
--- /dev/null
+++ b/visualpython/js/m_ml/Pipeline.js
@@ -0,0 +1,798 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Pipeline.js
+ * Author : Black Logic
+ * Note : Pipeline
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 08. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Pipeline
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/pipeline.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_ml/pipeline'),
+ __VP_RAW_LOADER__('vp_base/data/libraries.json'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, msCss, librariesJson, com_util, com_String, com_generator, ML_LIBRARIES, PopupComponent, SuggestInput, ModelEditor) {
+
+ /**
+ * Pipeline
+ */
+ class Pipeline extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 4;
+ this.config.dataview = false;
+ this.config.autoScroll = false;
+
+ this.state = {
+ templateType: '',
+ modelStep: -1, // get modelStep sequence
+ modelType: '', // get modelType
+ modelTypeName: '', // get modelTypeName
+ model: 'model',
+ // now selected pipeline info
+ pipeline: [
+ // copy of step + info
+ // { name, label, useApp, state, app }
+ ],
+ ...this.state
+ }
+
+ /**
+ * useApp
+ - Data Split
+ - Data Prep
+ - Regressor
+ - Classifier
+ - Clustering
+ - Dimension
+ - GridSearch
+ - Evaluation
+
+ - Fit
+ - Transform
+ - Predict
+ - Fit and Predict
+ - Fit and Transform
+ - Fit and Resample
+ */
+ this.templateList = {
+ 'data-prep': {
+ label: 'Data Preparation',
+ modelStep: 0,
+ step: [
+ /**
+ * ml_* is pre-defined app
+ * pp_* is defined only for Pipeline
+ */
+ { name: 'ml_dataPrep', label: 'Data Prep', useApp: true, child: ['pp_fit', 'pp_transform', 'pp_fit_resample'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_transform', label: 'Transform' },
+ { name: 'pp_fit_resample', label: 'Fit and Resample' }
+ ]
+ },
+ 'regression': {
+ label: 'Regression',
+ modelStep: 1,
+ step: [
+ { name: 'ml_dataSplit', label: 'Data Split', useApp: true },
+ { name: 'ml_regression', label: 'Regressor', useApp: true, child: ['pp_fit', 'pp_predict'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_predict', label: 'Predict' },
+ { name: 'ml_evaluation', label: 'Evaluation', useApp: true, state: { modelType: 'rgs' } },
+ ]
+ },
+ 'classification': {
+ label: 'Classification',
+ modelStep: 1,
+ step: [
+ { name: 'ml_dataSplit', label: 'Data Split', useApp: true },
+ { name: 'ml_classification', label: 'Classifier', useApp: true, child: ['pp_fit', 'pp_predict'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_predict', label: 'Predict' },
+ { name: 'ml_evaluation', label: 'Evaluation', useApp: true, state: { modelType: 'clf' } },
+ ]
+ },
+ 'clustering': {
+ label: 'Clustering',
+ modelStep: 0,
+ step: [
+ { name: 'ml_clustering', label: 'Clustering', useApp: true, child: ['pp_fit', 'pp_predict', 'pp_fit_predict', 'pp_transform'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_predict', label: 'Predict' },
+ { name: 'pp_fit_predict', label: 'Fit and Predict' },
+ { name: 'pp_transform', label: 'Transform' },
+ { name: 'ml_evaluation', label: 'Evaluation', useApp: true, state: { modelType: 'cls' } },
+ ]
+ },
+ 'dimension': {
+ label: 'Dimension Reduction',
+ modelStep: 0,
+ step: [
+ { name: 'ml_dimensionReduction', label: 'Dimension Reduction', useApp: true, child: ['pp_fit', 'pp_transform', 'pp_fit_transform'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_transform', label: 'Transform' },
+ { name: 'pp_fit_transform', label: 'Fit and Transform' },
+ ]
+ },
+ 'gridSearch': {
+ label: 'GridSearch',
+ modelStep: 1,
+ step: [
+ { name: 'ml_dataSplit', label: 'Data Split', useApp: true },
+ { name: 'ml_gridSearch', label: 'GridSearch', useApp: true, child: ['pp_fit', 'pp_predict'] },
+ { name: 'pp_fit', label: 'Fit' },
+ { name: 'pp_predict', label: 'Predict' },
+ { name: 'ml_evaluation', label: 'Evaluation', useApp: true },
+ ]
+ }
+ }
+
+ // menu libraries for ml
+ let libObj = {};
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ libObj = librariesJson;
+
+ this.MlAppComponent = {};
+ this.MlAppComponent['ml_dataSplit'] = require('./dataSplit');
+ this.MlAppComponent['ml_dataPrep'] = require('./DataPrep');
+ this.MlAppComponent['ml_regression'] = require('./Regression');
+ this.MlAppComponent['ml_classification'] = require('./Classification');
+ this.MlAppComponent['ml_clustering'] = require('./Clustering');
+ this.MlAppComponent['ml_dimensionReduction'] = require('./DimensionReduction');
+ this.MlAppComponent['ml_gridSearch'] = require('./GridSearch');
+ this.MlAppComponent['ml_evaluation'] = require('./evaluation');
+ } else {
+ libObj = JSON.parse(librariesJson);
+ }
+ this.mlAppList = libObj.library.item.filter(x => x.id === 'pkg_ml')[0].item;
+
+ this.modelConfig = ML_LIBRARIES;
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+
+ $(document).off('click', this.wrapSelector('.vp-pp-item[data-flag="enabled"]'));
+ $(document).off('click', this.wrapSelector('.vp-pp-item-toggle'));
+ $(document).off('change', this.wrapSelector(`#modelType`));
+ $(document).off('change', this.wrapSelector('#allocateToCreation'));
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // select template
+ $(this.wrapSelector('#templateType')).on('change', function() {
+ let type = $(this).val();
+ that.state.templateType = type;
+ that.state.model = 'model';
+ that.state.modelType = '';
+ that.state.modelTypeName = '';
+ that.state.modelStep = -1;
+
+ // reset pp-page
+ $(that.wrapSelector('.vp-pp-template')).html('');
+ $(that.wrapSelector('.vp-pp-step-content')).html('');
+ $(that.wrapSelector('.vp-pp-step-title')).text('');
+ that.state.pipeline = [];
+ $(that.wrapSelector('.vp-pp-step-prev')).addClass('disabled');
+ $(that.wrapSelector('.vp-pp-step-next')).addClass('disabled');
+
+ that.handleChangeTemplate(type);
+ });
+
+ // select pipeline item
+ $(document).on('click', this.wrapSelector('.vp-pp-item[data-flag="enabled"]'), function() {
+ if (!$(this).hasClass('selected')) {
+ let title = $(this).data('label');
+ let stepSeq = parseInt($(this).data('step')); // 0 ~ n
+ let name = $(this).data('name');
+ let ppObj = that.state.pipeline[stepSeq];
+ // set title
+ $(that.wrapSelector('.vp-pp-step-title')).text(title);
+
+ // show page
+ $(that.wrapSelector(`.vp-pp-step-page:not([data-name="${name}"])`)).hide();
+ $(that.wrapSelector(`.vp-pp-step-page[data-name="${name}"]`)).show();
+ if (ppObj.useApp === true) {
+ ppObj.app && that.handleAppView(name, ppObj.app);
+ ppObj.app && ppObj.app.open($(that.wrapSelector(`.vp-pp-step-page[data-name="${name}"]`)));
+ } else {
+ that.renderApp(name);
+ }
+
+ // check selected
+ $(that.wrapSelector('.vp-pp-item')).removeClass('selected');
+ $(this).addClass('selected');
+
+ // check prev/next
+ let prevTagList = $(this).prevAll('.vp-pp-item[data-flag="enabled"]:visible');
+ let nextTagList = $(this).nextAll('.vp-pp-item[data-flag="enabled"]:visible');
+ if (prevTagList.length == 0) {
+ $(that.wrapSelector('.vp-pp-step-prev')).addClass('disabled');
+ } else {
+ $(that.wrapSelector('.vp-pp-step-prev')).removeClass('disabled');
+ }
+ if (nextTagList.length == 0) {
+ $(that.wrapSelector('.vp-pp-step-next')).addClass('disabled');
+ } else {
+ $(that.wrapSelector('.vp-pp-step-next')).removeClass('disabled');
+ }
+ }
+ });
+
+ // pipeline item toggle (enable/disable)
+ $(document).on('click', this.wrapSelector('.vp-pp-item-toggle'), function(evt) {
+ evt.stopPropagation();
+ let itemTag = $(this).closest('.vp-pp-item');
+ let name = $(itemTag).attr('data-name');
+ let flag = $(itemTag).attr('data-flag'); // enabled / disabled
+ if (flag === 'enabled') {
+ $(itemTag).attr('data-flag', 'disabled');
+ $(this).prop('checked', false);
+ } else if (flag === 'disabled') {
+ $(itemTag).attr('data-flag', 'enabled');
+ $(this).prop('checked', true);
+ }
+
+ if ($(itemTag).hasClass('selected')) {
+ // check if this page is this item's, then hide it.
+ $(that.wrapSelector('.vp-pp-step-title')).text('');
+ $(that.wrapSelector(`.vp-pp-step-page[data-name="${name}"]`)).hide();
+ $(itemTag).removeClass('selected');
+
+ // disable prev/next
+ $(that.wrapSelector('.vp-pp-step-prev')).addClass('disabled');
+ $(that.wrapSelector('.vp-pp-step-next')).addClass('disabled');
+ } else {
+ // check prev/next
+ let selectedTag = $(that.wrapSelector('.vp-pp-item.selected'));
+ let prevTagList = $(selectedTag).prevAll('.vp-pp-item[data-flag="enabled"]:visible');
+ let nextTagList = $(selectedTag).nextAll('.vp-pp-item[data-flag="enabled"]:visible');
+ if (prevTagList.length == 0) {
+ $(that.wrapSelector('.vp-pp-step-prev')).addClass('disabled');
+ } else {
+ $(that.wrapSelector('.vp-pp-step-prev')).removeClass('disabled');
+ }
+ if (nextTagList.length == 0) {
+ $(that.wrapSelector('.vp-pp-step-next')).addClass('disabled');
+ } else {
+ $(that.wrapSelector('.vp-pp-step-next')).removeClass('disabled');
+ }
+ }
+
+ });
+
+ // model type change event
+ $(document).on('change', this.wrapSelector(`#modelType`), function() {
+ let name = $(this).closest('.vp-pp-step-page').data('name');
+ let modelCreatorList = ['ml_dataPrep', 'ml_regression', 'ml_classification', 'ml_clustering', 'ml_dimensionReduction', 'ml_gridSearch'];
+ if (modelCreatorList.includes(name)) {
+ let modelType = $(this).val();
+ let modelObj = that.modelConfig[modelType];
+ let modelTypeName = modelObj.returnType;
+
+ that.state.modelType = modelType;
+ that.state.modelTypeName = modelTypeName;
+
+ // show fit / predict / transform depends on model selection
+ let defaultActions = ['fit', 'predict', 'transform', 'fit_predict', 'fit_transform', 'fit_resample'];
+ let actions = that.modelEditor.getAction(modelTypeName);
+ defaultActions.forEach(actKey => {
+ if (actions[actKey] === undefined) {
+ // if undefined, hide step
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_${actKey}"]`)).hide();
+ } else {
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_${actKey}"]`)).show();
+ if (actKey === 'fit_predict') {
+ if (actions['fit'] === undefined || actions['predict'] === undefined) {
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_fit"]`)).hide();
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_predict"]`)).hide();
+ } else {
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_${actKey}"]`)).hide();
+ }
+ } else if (actKey === 'fit_transform') {
+ if (actions['fit'] === undefined || actions['transform'] === undefined) {
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_fit"]`)).hide();
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_transform"]`)).hide();
+ } else {
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_${actKey}"]`)).hide();
+ }
+ } else if (actKey === 'fit_resample') {
+ // for SMOTE: show fit_resample only
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_fit"]`)).hide();
+ $(that.wrapSelector(`.vp-pp-item[data-name="pp_transform"]`)).hide();
+ }
+ }
+ $(that.wrapSelector('.vp-pp-item')).removeClass('vp-last-visible');
+ $(that.wrapSelector('.vp-pp-item:visible:last')).addClass('vp-last-visible');
+ });
+
+ // change evaluation page's default selection
+ if (name === 'ml_gridSearch') {
+ let modelCategory = that.modelEditor.getModelCategory(modelTypeName); // Regression / Classification / Clustering
+ let evalModelTypeValue = 'rgs';
+ switch (modelCategory) {
+ case 'Regression':
+ evalModelTypeValue = 'rgs';
+ break;
+ case 'Classification':
+ evalModelTypeValue = 'clf';
+ break;
+ case 'Clustering':
+ evalModelTypeValue = 'cls';
+ break;
+ }
+ let evalPageTag = $(that.wrapSelector('.vp-pp-step-page[data-name="ml_evaluation"]'));
+ if (evalPageTag.is(':empty') === true) {
+ // evaluation page is not opened yet
+ // set state for evaluation page
+ let stepSeq = $(evalPageTag).data('step');
+ let ppObj = that.state.pipeline[stepSeq];
+ if (ppObj.app) {
+ ppObj.app.state.modelType = evalModelTypeValue;
+ }
+ } else {
+ let evalModelTypeTag = $(evalPageTag).find('#modelType');
+ $(evalModelTypeTag).val(evalModelTypeValue);
+ $(evalModelTypeTag).trigger('change');
+ }
+ }
+ }
+ });
+
+ // model allocation variable change
+ $(document).on('change', this.wrapSelector('#allocateToCreation'), function() {
+ let name = $(this).closest('.vp-pp-step-page').data('name');
+ let modelAllocation = $(this).val();
+ that.state.model = modelAllocation;
+ });
+
+ // click prev button
+ $(this.wrapSelector('.vp-pp-step-prev:not(.disabled)')).on('click', function() {
+ let selectedTag = $(that.wrapSelector('.vp-pp-item.selected'));
+ let prevTagList = $(selectedTag).prevAll('.vp-pp-item[data-flag="enabled"]:visible');
+ $(prevTagList[0]).trigger('click');
+ });
+
+ // click next button
+ $(this.wrapSelector('.vp-pp-step-next:not(.disabled)')).on('click', function() {
+ let selectedTag = $(that.wrapSelector('.vp-pp-item.selected'));
+ let nextTagList = $(selectedTag).nextAll('.vp-pp-item[data-flag="enabled"]:visible');
+ $(nextTagList[0]).trigger('click');
+ });
+ }
+
+ /**
+ *
+ * @param {*} type template type
+ */
+ handleChangeTemplate(type) {
+ let that = this;
+ if (type !== '') {
+ let tplObj = this.templateList[type];
+ this.state.modelStep = tplObj.modelStep;
+
+ let ppTag = new com_String();
+ let appFileList = [];
+ // load pipeline items
+ tplObj.step.forEach((stepObj, idx) => {
+ let { name, label, useApp=false, child=[], state={} } = stepObj;
+ ppTag.appendFormatLine(`
+ {3}
+
+
`, name, idx, label, label);
+
+ // get pages
+ if (useApp === true) {
+ let mlObj = that.mlAppList.filter(x => x.id === name)[0];
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ appFileList.push({ index: idx, name: name, file: 'vp_base/js/' + mlObj.file});
+ } else {
+ appFileList.push({ index: idx, name: name, file: 'vp_base/js/' + mlObj.file});
+ }
+ }
+ let pipeObj = {
+ name: name,
+ label: label,
+ useApp: useApp,
+ state: state
+ };
+ if (tplObj.modelStep === idx) {
+ pipeObj.modelStep = true;
+ pipeObj.child = child;
+ }
+ that.state.pipeline.push(pipeObj);
+ // append pages
+ $(that.wrapSelector('.vp-pp-step-content')).append(
+ `
`);
+ if (useApp === false) {
+ that.renderApp(name);
+ // hide
+ $(that.wrapSelector(`.vp-pp-step-page[data-name="${name}"]`)).hide();
+ }
+
+ });
+ $(that.wrapSelector('.vp-pp-template')).html(ppTag.toString());
+
+ // render pages
+ // for lite and lab
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ appFileList.forEach((obj, argIdx) => {
+ let MlComponent = that.MlAppComponent[obj.name];
+ if (MlComponent) {
+ // DUP AREA: pp-1
+ let { name, index, file } = obj;
+ let mlComponent = new MlComponent({
+ config: { id: name, name: that.state.pipeline[index].label, path: file, category: 'Pipeline', resizable: false },
+ ...that.state.pipeline[index].state
+ });
+ mlComponent.loadState();
+ // mlComponent.open($(that.wrapSelector(`.vp-pp-step-page[data-name="${appId}"]`)));
+ that.state.pipeline[index].app = mlComponent;
+
+ if (that.state.pipeline[index].modelStep === true) {
+ // set default model type
+ that.state.model = mlComponent.state.allocateToCreation;
+ that.state.modelType = mlComponent.state.modelType;
+ let modelObj = that.modelConfig[that.state.modelType];
+ that.state.modelTypeName = modelObj.code.split('(')[0];
+
+ that.state.pipeline[index].child.forEach(childId => {
+ that.renderApp(childId);
+ });
+ }
+ // handle app view
+ that.handleAppView(name, mlComponent);
+
+ // select first step
+ $(that.wrapSelector('.vp-pp-item[data-step="0"]')).click();
+ $(that.wrapSelector('#modelType')).trigger('change');
+ // end of DUP AREA: pp-1
+ }
+ });
+
+ } else {
+ // for notebook and others
+ window.require(appFileList.map(x => x.file), function() {
+ appFileList.forEach((obj, argIdx) => {
+ let MlComponent = arguments[argIdx];
+ if (MlComponent) {
+ // DUP AREA: pp-1
+ let { name, index, file } = obj;
+ let mlComponent = new MlComponent({
+ config: { id: name, name: that.state.pipeline[index].label, path: file, category: 'Pipeline', resizable: false },
+ ...that.state.pipeline[index].state
+ });
+ mlComponent.loadState();
+ // mlComponent.open($(that.wrapSelector(`.vp-pp-step-page[data-name="${appId}"]`)));
+ that.state.pipeline[index].app = mlComponent;
+
+ if (that.state.pipeline[index].modelStep === true) {
+ // set default model type
+ that.state.model = mlComponent.state.allocateToCreation;
+ that.state.modelType = mlComponent.state.modelType;
+ let modelObj = that.modelConfig[that.state.modelType];
+ that.state.modelTypeName = modelObj.code.split('(')[0];
+
+ that.state.pipeline[index].child.forEach(childId => {
+ that.renderApp(childId);
+ });
+ }
+ // handle app view
+ that.handleAppView(name, mlComponent);
+
+ // select first step
+ $(that.wrapSelector('.vp-pp-item[data-step="0"]')).click();
+ $(that.wrapSelector('#modelType')).trigger('change');
+ // end of DUP AREA: pp-1
+ }
+ })
+
+ });
+ }
+ }
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ //================================================================
+ // Template list creation
+ //================================================================
+ let tplTag = new com_String();
+ tplTag.appendLine('Select pipeline... ');
+ Object.keys(this.templateList).forEach(tplKey => {
+ let tplObj = that.templateList[tplKey];
+ let selectedFlag = '';
+ if (tplKey == that.state.templateType) {
+ selectedFlag = 'selected';
+ }
+ tplTag.appendFormatLine('{2} ',
+ tplKey, selectedFlag, tplObj.label);
+ });
+ $(page).find('#templateType').html(tplTag.toString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ // resize codeview
+ $(this.wrapSelector('.vp-popup-codeview-box')).css({'height': '300px'});
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+
+ // load state
+ if (this.state.templateType !== '') {
+ $(this.wrapSelector('#templateType')).trigger('change');
+ } else {
+ $(this.wrapSelector('.vp-pp-step-prev')).addClass('disabled');
+ $(this.wrapSelector('.vp-pp-step-next')).addClass('disabled');
+ }
+ }
+
+ /**
+ * Handle app view before open
+ * @param {string} appId
+ * @param {*} mlApp
+ */
+ handleAppView(appId, mlApp) {
+ switch (appId) {
+ case 'ml_dataSplit':
+ $(mlApp.wrapSelector('#inputData')).parent().hide();
+ break;
+ case 'ml_evaluation':
+ // for pipeline
+ $(mlApp.wrapSelector('.vp-upper-box')).hide();
+ $(mlApp.wrapSelector('.vp-upper-box.' + mlApp.state.modelType)).show();
+
+ $(mlApp.wrapSelector('.vp-eval-box')).hide();
+ $(mlApp.wrapSelector('.vp-eval-' + mlApp.state.modelType)).show();
+
+ if (mlApp.state.modelType == 'rgs') {
+ // Regression
+
+ } else if (mlApp.state.modelType == 'clf') {
+ // Classification
+ // if (this.state.roc_curve == false && this.state.auc == false) {
+ // $(page).find('.vp-ev-model.roc-auc').prop('disabled', true);
+ // }
+ } else {
+ // Clustering
+ if (mlApp.state.silhouetteScore == false) {
+ $(mlApp.wrapSelector('.vp-ev-model.silhouette')).prop('disabled', true);
+ }
+ if (mlApp.state.ari == false && mlApp.state.nmi == false) {
+ $(mlApp.wrapSelector('.vp-ev-model.ari-nmi')).prop('disabled', true);
+ }
+ }
+ break;
+ }
+ }
+
+ /**
+ * Custom pages
+ * @param {*} appId
+ */
+ renderApp(appId) {
+ let actions = this.modelEditor.getAction(this.state.modelTypeName);
+ let tag = '';
+ switch (appId) {
+ case 'pp_fit':
+ tag = this.templateForOptionPage(actions['fit']);
+ break;
+ case 'pp_predict':
+ tag = this.templateForOptionPage(actions['predict']);
+ break;
+ case 'pp_transform':
+ tag = this.templateForOptionPage(actions['transform']);
+ break;
+ case 'pp_fit_predict':
+ tag = this.templateForOptionPage(actions['fit_predict']);
+ break;
+ case 'pp_fit_transform':
+ tag = this.templateForOptionPage(actions['fit_transform']);
+ break;
+ case 'pp_fit_resample':
+ tag = this.templateForOptionPage(actions['fit_resample']);
+ break;
+ }
+ $(this.wrapSelector(`.vp-pp-step-page[data-name="${appId}"]`)).html(`
+ ${tag}
+ `);
+ }
+
+ templateForOptionPage(packageObj) {
+ let optBox = new com_String();
+ // render tag
+ packageObj && packageObj.options && packageObj.options.forEach(opt => {
+ let label = opt.name;
+ if (opt.label != undefined) {
+ label = opt.label;
+ }
+ // fix label
+ label = com_util.optionToLabel(label);
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, label);
+ let tmpState = {};
+ if (opt.value && opt.value !== '') {
+ tmpState[opt.name] = opt.value;
+ }
+ let content = com_generator.renderContent(this, opt.component[0], opt, tmpState);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ return optBox.toString();
+ }
+
+ checkBeforeRun() {
+ let that = this;
+ var result = true;
+ for (let idx = 0; idx < this.state.pipeline.length; idx++) {
+ let ppObj = this.state.pipeline[idx];
+ var { name, label, useApp, app } = ppObj;
+ let requiredList = [];
+ result = true;
+ let isVisible = $(that.wrapSelector(`.vp-pp-item[data-step="${idx}"]`)).is(':visible') === true;
+ let isEnabled = $(that.wrapSelector(`.vp-pp-item[data-step="${idx}"]`)).attr('data-flag') === 'enabled';
+ if (isVisible && isEnabled) {
+ switch (name) {
+ case 'ml_dataSplit':
+ requiredList = ['featureData', 'targetData'];
+ // check required data
+ for (let i = 0; i < requiredList.length; i++) {
+ let reqKey = requiredList[i];
+ result = that._checkIsEmpty($(app.wrapSelector('#' + reqKey)));
+ if (result === false) {
+ // show page and focus it
+ $(that.wrapSelector(`.vp-pp-item[data-name="${name}"]`)).click();
+ $(app.wrapSelector('#' + reqKey)).focus();
+ break;
+ }
+ }
+ break;
+ case 'ml_gridSearch':
+ result = app.checkBeforeRun();
+ if (result === false) {
+ // show page
+ $(that.wrapSelector(`.vp-pp-item[data-name="${name}"]`)).click();
+ break;
+ }
+ break;
+ }
+ }
+ if (result === false) {
+ break;
+ }
+ }
+ return result;
+
+ }
+
+ _checkIsEmpty(tag) {
+ let requiredFilled = true;
+ // if it's empty, focus on it
+ if (tag && $(tag) && $(tag).val() == '') {
+ requiredFilled = false;
+ }
+ return requiredFilled;
+ }
+
+ generateCodeForOptionPage(appId) {
+ let actions = this.modelEditor.getAction(this.state.modelTypeName);
+ let actObj = {};
+ switch (appId) {
+ case 'pp_fit':
+ actObj = actions['fit'];
+ break;
+ case 'pp_predict':
+ actObj = actions['predict'];
+ break;
+ case 'pp_transform':
+ actObj = actions['transform'];
+ break;
+ case 'pp_fit_predict':
+ actObj = actions['fit_predict'];
+ break;
+ case 'pp_fit_transform':
+ actObj = actions['fit_transform'];
+ break;
+ case 'pp_fit_resample':
+ actObj = actions['fit_resample'];
+ break;
+ }
+
+ let code = new com_String();
+ if (actObj.import != undefined) {
+ code.appendLine(actObj.import);
+ code.appendLine();
+ }
+
+ let that = this;
+ let state = {
+ model: this.state.model
+ };
+ $(this.wrapSelector(`.vp-pp-step-page[data-name="${appId}"] .vp-state`)).each((idx, tag) => {
+ let id = tag.id;
+ let value = that._getTagValue(tag);
+ state[id] = value;
+ });
+
+ let modelCode = com_generator.vp_codeGenerator(this, actObj, state);
+ modelCode = modelCode.replace('${model}', state.model);
+ code.append(modelCode);
+ return { state: state, code: code.toString() };
+ }
+
+ generateCode() {
+ let that = this;
+ let { template } = this.state;
+ let code = new com_String();
+
+ let stepNo = 1;
+ this.state.pipeline.forEach((ppObj, idx) => {
+ let { name, label, useApp, app } = ppObj;
+
+ // check disabled
+ let isVisible = $(that.wrapSelector(`.vp-pp-item[data-step="${idx}"]`)).is(':visible') === true;
+ let isEnabled = $(that.wrapSelector(`.vp-pp-item[data-step="${idx}"]`)).attr('data-flag') === 'enabled';
+ if (isVisible && isEnabled) {
+ if (code.toString() !== '') {
+ code.appendLine();
+ code.appendLine();
+ }
+ if (useApp === true) {
+ let appCode = app.generateCode();
+ if (appCode instanceof Array) {
+ appCode = appCode.join('\n');
+ }
+ if (appCode && appCode.trim() !== '') {
+ code.appendFormatLine("# [{0}] {1}", stepNo++, label);
+ if (name === 'ml_evaluation') {
+ // import auto generate
+ code.appendLine(app.generateImportCode().join('\n'));
+ }
+ code.append(appCode);
+ }
+ // save state
+ that.state.pipeline[idx].state = app.state;
+ } else {
+ let ppResult = that.generateCodeForOptionPage(name);
+ if (ppResult && ppResult?.code?.trim() !== '') {
+ code.appendFormatLine("# [{0}] {1}", stepNo++, label);
+ code.append(ppResult.code);
+ }
+ // save state
+ that.state.pipeline[idx].state = ppResult.state;
+ }
+ }
+ });
+
+ return code.toString();
+ }
+
+ }
+
+ return Pipeline;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/Regression.js b/visualpython/js/m_ml/Regression.js
new file mode 100644
index 00000000..3c21d077
--- /dev/null
+++ b/visualpython/js/m_ml/Regression.js
@@ -0,0 +1,333 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Regression.js
+ * Author : Black Logic
+ * Note : Model selection and fitting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Regression
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/model.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_ml/mlLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/ModelEditor'
+], function(msHtml, com_util, com_interface, com_String, com_generator, ML_LIBRARIES, PopupComponent, VarSelector2, ModelEditor) {
+
+ /**
+ * Regression
+ */
+ class Regression extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ // model creation
+ modelControlType: 'creation',
+ modelType: 'ln-rgs',
+ userOption: '',
+ featureData: 'X_train',
+ targetData: 'y_train',
+ allocateToCreation: 'model',
+ // model selection
+ model: '',
+ method: '',
+ ...this.state
+ }
+
+ this.modelConfig = ML_LIBRARIES;
+
+ this.modelTypeList = {
+ 'Regression': ['ln-rgs', 'ridge', 'lasso', 'elasticnet', 'sv-rgs', 'dt-rgs', 'rf-rgs', 'gbm-rgs', 'xgb-rgs', 'lgbm-rgs', 'cb-rgs'],
+ }
+
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+ // select model control type
+ $(this.wrapSelector('#modelControlType')).on('change', function() {
+ let modelControlType = $(this).val();
+ // show/hide model box
+ $(that.wrapSelector('.vp-model-box')).hide();
+ $(that.wrapSelector(`.vp-model-box[data-type="${modelControlType}"]`)).show();
+ });
+
+ // select model type
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+ $(that.wrapSelector('.vp-model-option-box')).html(that.templateForOption(modelType));
+ that.viewOption();
+
+ // show install button
+ if (that.modelConfig[modelType].install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+ });
+
+ // install library
+ $(this.wrapSelector('#vp_installLibrary')).on('click', function() {
+ let config = that.modelConfig[that.state.modelType];
+ if (config && config.install != undefined) {
+ // insert install code
+ let installCode = config.install;
+ if (vpConfig.extensionType === 'lite') {
+ installCode = installCode.replace('!', '%');
+ }
+ com_interface.insertCell('code', installCode, true, 'Machine Learning > Regression');
+ }
+ });
+
+ // change model
+ $(this.wrapSelector('#model')).on('change', function() {
+ that.modelEditor.reload();
+ })
+ }
+
+ templateForBody() {
+ let page = $(msHtml);
+
+ let that = this;
+
+ // model control type
+ $(page).find('.vp-model-box').hide();
+ $(page).find(`.vp-model-box[data-type="${this.state.modelControlType}"]`).show();
+
+ //================================================================
+ // Model creation
+ //================================================================
+ // model types
+ let modelTypeTag = new com_String();
+ Object.keys(this.modelTypeList).forEach(modelCategory => {
+ let modelOptionTag = new com_String();
+ that.modelTypeList[modelCategory].forEach(opt => {
+ let optConfig = that.modelConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.modelType) {
+ selectedFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ modelTypeTag.appendFormatLine('{1} ',
+ modelCategory, modelOptionTag.toString());
+ });
+ $(page).find('#modelType').html(modelTypeTag.toString());
+
+ // show install button
+ if (this.modelConfig[this.state.modelType].install != undefined) {
+ $(page).find('#vp_installLibrary').show();
+ } else {
+ $(page).find('#vp_installLibrary').hide();
+ }
+
+ // render option page
+ $(page).find('.vp-model-option-box').html(this.templateForOption(this.state.modelType));
+
+ let varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('featureData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.featureData);
+ $(page).find('#featureData').replaceWith(varSelector.toTagString());
+
+ varSelector = new VarSelector2(this.wrapSelector());
+ varSelector.setComponentID('targetData');
+ varSelector.addClass('vp-state vp-input');
+ varSelector.setValue(this.state.targetData);
+ $(page).find('#targetData').replaceWith(varSelector.toTagString());
+
+ //================================================================
+ // Model selection
+ //================================================================
+ // set model list
+ let modelOptionTag = new com_String();
+ vpKernel.getModelList('Regression').then(function(resultObj) {
+ let { result } = resultObj;
+ var modelList = JSON.parse(result);
+ modelList && modelList.forEach(model => {
+ let selectFlag = '';
+ if (model.varName == that.state.model) {
+ selectFlag = 'selected';
+ }
+ modelOptionTag.appendFormatLine('{3} ({4}) ',
+ model.varName, model.varType, selectFlag, model.varName, model.varType);
+ });
+ $(page).find('#model').html(modelOptionTag.toString());
+ $(that.wrapSelector('#model')).html(modelOptionTag.toString());
+
+ if (!that.state.model || that.state.model == '') {
+ that.state.model = $(that.wrapSelector('#model')).val();
+ }
+
+ that.modelEditor.reload();
+ });
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForOption(modelType) {
+ let config = this.modelConfig[modelType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ viewOption() {
+ // SVR - kernel selection
+ if (this.state.modelType == 'sv-rgs') {
+ let kernelType = this.state.kernel;
+ switch (kernelType) {
+ case undefined: // default = rbf
+ case '':
+ case 'rbf': // gamma
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ // hide others
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ $(this.wrapSelector('label[for="coef0"]')).hide();
+ $(this.wrapSelector('#coef0')).hide();
+ break;
+ case 'poly': // gamma / degree / coef0
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ $(this.wrapSelector('label[for="degree"]')).show();
+ $(this.wrapSelector('#degree')).show();
+ $(this.wrapSelector('label[for="coef0"]')).show();
+ $(this.wrapSelector('#coef0')).show();
+ break;
+ case 'sigmoid': // gamma / coef0
+ $(this.wrapSelector('label[for="gamma"]')).show();
+ $(this.wrapSelector('#gamma')).show();
+ $(this.wrapSelector('label[for="coef0"]')).show();
+ $(this.wrapSelector('#coef0')).show();
+ // hide others
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ break;
+ default:
+ // hide others
+ $(this.wrapSelector('label[for="gamma"]')).hide();
+ $(this.wrapSelector('#gamma')).hide();
+ $(this.wrapSelector('label[for="degree"]')).hide();
+ $(this.wrapSelector('#degree')).hide();
+ $(this.wrapSelector('label[for="coef0"]')).hide();
+ $(this.wrapSelector('#coef0')).hide();
+ break;
+ }
+
+ // Model Creation - SVC kernel selection
+ let that = this;
+ $(this.wrapSelector('#kernel')).off('change');
+ $(this.wrapSelector('#kernel')).change(function() {
+ that.state.kernel = $(this).val();
+ that.viewOption();
+ });
+ }
+
+ }
+
+ render() {
+ super.render();
+
+ // Model Creation - dynamically view options
+ this.viewOption();
+
+ // Model Editor
+ this.modelEditor = new ModelEditor(this, "model", "instanceEditor");
+ }
+
+ generateCode() {
+ let { modelControlType, modelType, userOption, allocateToCreation, model } = this.state;
+ let code = new com_String();
+ if (modelControlType == 'creation') {
+ /**
+ * Model Creation
+ * ---
+ * from module import model_function
+ * model = Model(key=value, ...)
+ */
+ let config = this.modelConfig[modelType];
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.appendFormat('{0} = {1}', allocateToCreation, modelCode);
+ } else {
+ /**
+ * Model Selection
+ * ---
+ * ...
+ */
+ code.append(this.modelEditor.getCode({'${model}': model}));
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return Regression;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/SaveLoad.js b/visualpython/js/m_ml/SaveLoad.js
new file mode 100644
index 00000000..454f468c
--- /dev/null
+++ b/visualpython/js/m_ml/SaveLoad.js
@@ -0,0 +1,121 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : SaveLoad.js
+ * Author : Black Logic
+ * Note : Save and load models
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 03. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] DataSets
+//============================================================================
+define([
+ __VP_CSS_LOADER__('vp_base/css/m_ml/saveLoad'),
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/saveLoad.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/data/m_ml/mlLibrary',
+], function(slCss, slHTML, com_util, com_Const, com_String, com_generator, PopupComponent, FileNavigation, ML_LIBRARIES) {
+
+ /**
+ * SaveLoad
+ */
+ class SaveLoad extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+ this.config.checkModules = ['joblib'];
+
+ this.state = {
+ modelio: 'model_save', // model_save / model_load
+ target: '',
+ allocateTo: '',
+ userOption: '',
+ savePath: '',
+ loadPath: '',
+ ...this.state
+ }
+
+ this.mlConfig = ML_LIBRARIES;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+
+ // select model
+ $(this.wrapSelector('#modelio')).on('change', function() {
+ let modelio = $(this).val();
+ that.state.modelio = modelio;
+ $(that.wrapSelector('.vp-modelio-option-box')).html(that.templateForOption(modelio));
+
+ $(that.wrapSelector('#userOption')).val('');
+ });
+
+ // user option
+ $(this.wrapSelector('#userOption')).on('change', function() {
+ that.state.userOption = $(this).val();
+ })
+ }
+
+ templateForBody() {
+ let page = $(slHTML);
+
+ // render option page
+ $(page).find('.vp-modelio-option-box').html(this.templateForOption(this.state.modelio));
+
+ $(page).find('#modelio').val(this.state.modelio);
+ $(page).find('#userOption').val(this.state.userOption);
+
+ return page;
+ }
+
+ templateForOption(modelio) {
+ let config = this.mlConfig[modelio];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{2} '
+ , opt.name, opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+
+ // render file navigation
+
+
+ // show user option
+ if (config.code.includes('${etc}')) {
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ }
+ return optBox.toString();
+ }
+
+ generateCode() {
+ let { modelio, userOption } = this.state;
+ let code = new com_String();
+ if (userOption && userOption != '') {
+ userOption = ', ' + userOption;
+ }
+
+ let modelCode = com_generator.vp_codeGenerator(this, this.mlConfig[modelio], this.state, userOption);
+ code.append(modelCode);
+ return code.toString();
+ }
+ }
+
+ return SaveLoad;
+});
\ No newline at end of file
diff --git a/src/markdown/__init__.py b/visualpython/js/m_ml/__init__.py
similarity index 100%
rename from src/markdown/__init__.py
rename to visualpython/js/m_ml/__init__.py
diff --git a/visualpython/js/m_ml/dataSplit.js b/visualpython/js/m_ml/dataSplit.js
new file mode 100644
index 00000000..a8c9417f
--- /dev/null
+++ b/visualpython/js/m_ml/dataSplit.js
@@ -0,0 +1,198 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : dataSplit.js
+ * Author : Black Logic
+ * Note : Data split
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Data split
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/dataSplit.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/js/com/component/DataSelector'
+], function(dsHtml, com_util, com_interface, com_Const, com_String, PopupComponent, VarSelector2, DataSelector) {
+
+ /**
+ * Data split
+ */
+ class DataSplit extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.sizeLevel = 2;
+ this.config.dataview = false;
+
+ this.state = {
+ inputData: 'with_target_data',
+ featureData: '',
+ targetData: '',
+ testSize: 0.25,
+ shuffle: 'True',
+ stratify: '',
+ trainFeatures: 'X_train',
+ trainTarget: 'y_train',
+ testFeatures: 'X_test',
+ testTarget: 'y_test',
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ var that = this;
+
+ // change input data
+ $(this.wrapSelector('#inputData')).on('change', function() {
+ let inputData = $(this).val();
+ if (inputData == 'with_target_data') {
+ // with target data
+ $(that.wrapSelector('.vp-target-data-box')).show();
+ // set label
+ $(that.wrapSelector('label[for=featureData]')).text('Feature data');
+ $(that.wrapSelector('label[for=trainFeatures]')).text('Train features');
+ $(that.wrapSelector('label[for=testFeatures]')).text('Test features');
+ // set value
+ $(that.wrapSelector('#trainFeatures')).val('X_train').trigger('change');
+ $(that.wrapSelector('#testFeatures')).val('X_test').trigger('change');
+ } else {
+ // without target data
+ // with target data
+ $(that.wrapSelector('.vp-target-data-box')).hide();
+ // set label
+ $(that.wrapSelector('label[for=featureData]')).text('Data');
+ $(that.wrapSelector('label[for=trainFeatures]')).text('Train data');
+ $(that.wrapSelector('label[for=testFeatures]')).text('Test data');
+ // set value
+ $(that.wrapSelector('#trainFeatures')).val('train').trigger('change');
+ $(that.wrapSelector('#testFeatures')).val('test').trigger('change');
+ }
+ });
+
+ // Stratify depends on Shuffle
+ $(this.wrapSelector('#shuffle')).on('change', function() {
+ let shuffle = $(this).val();
+ if (shuffle == 'True') {
+ // enable stratify
+ $(that.wrapSelector('#stratify')).prop('disabled', false);
+ } else {
+ // disable stratify
+ $(that.wrapSelector('#stratify')).prop('disabled', true);
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(dsHtml);
+
+ // test size generating
+ let sizeOptions = '';
+ for (let i=5; i<95; i+=5) {
+ sizeOptions += `
+ ${i}%${i==25?' (default)':''}
+ `;
+ }
+ $(page).find('#testSize').html(sizeOptions);
+
+ let featureSelector = new DataSelector({
+ pageThis: this, id: 'featureData', placeholder: 'Select feature data', required: true
+ });
+ $(page).find('#featureData').replaceWith(featureSelector.toTagString());
+
+ let targetSelector = new DataSelector({
+ pageThis: this, id: 'targetData', placeholder: 'Select target data', required: true
+ });
+ $(page).find('#targetData').replaceWith(targetSelector.toTagString());
+
+ let stratifySelector = new DataSelector({
+ pageThis: this, id: 'stratify', placeholder: 'None'
+ });
+ $(page).find('#stratify').replaceWith(stratifySelector.toTagString());
+
+ // load state
+ let that = this;
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+
+
+ }
+
+ generateCode() {
+ let {
+ trainFeatures, trainTarget, testFeatures, testTarget,
+ inputData, featureData, targetData,
+ testSize, randomState, shuffle, stratify
+ } = this.state;
+
+ let options = new com_String();
+ if (testSize != '0.25') {
+ options.appendFormat(', test_size={0}', testSize);
+ }
+ if (randomState && randomState != '') {
+ options.appendFormat(', random_state={0}', randomState);
+ }
+ if (shuffle && shuffle != 'True') {
+ options.appendFormat(', shuffle={0}', shuffle);
+ }
+ if (shuffle != 'False' && stratify && stratify != '') {
+ options.appendFormat(', stratify={0}', stratify);
+ }
+
+ let code = new com_String();
+ code.appendLine('from sklearn.model_selection import train_test_split');
+ code.appendLine();
+ if (inputData == 'with_target_data') {
+ code.appendFormat('{0}, {1}, {2}, {3} = train_test_split({4}, {5}{6})',
+ trainFeatures, testFeatures, trainTarget, testTarget,
+ featureData, targetData, options.toString());
+ } else {
+ code.appendFormat('{0}, {1} = train_test_split({2}{3})',
+ trainFeatures, testFeatures, featureData, options.toString());
+ }
+ return code.toString();
+ }
+
+ }
+
+ return DataSplit;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_ml/evaluation.js b/visualpython/js/m_ml/evaluation.js
new file mode 100644
index 00000000..ed63120c
--- /dev/null
+++ b/visualpython/js/m_ml/evaluation.js
@@ -0,0 +1,364 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : evaluation.js
+ * Author : Black Logic
+ * Note : Evaluation
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 02. 07
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Evaluation
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_ml/evaluation.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector'
+], function(evalHTML, com_util, com_interface, com_Const, com_String, PopupComponent, DataSelector) {
+
+ /**
+ * Evaluation
+ */
+ class Evaluation extends PopupComponent {
+ _init() {
+ super._init();
+ this.config.importButton = true;
+ this.config.dataview = false;
+ this.config.checkModules = ['metrics'];
+
+ this.state = {
+ modelType: 'rgs', // rgs / clf / cls
+ predictData: 'pred',
+ targetData: 'y_test',
+ // regression
+ r_squared: true, mae: true, mape: false, rmse: true, scatter_plot: false,
+ // classification
+ confusion_matrix: true, report: true,
+ accuracy: false, precision: false, recall: false, f1_score: false,
+ // clustering
+ clusteredIndex: 'clusters',
+ silhouetteScore: true, ari: false, nmi: false,
+ featureData2: 'X',
+ targetData2: 'y',
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // import library
+ $(this.wrapSelector('#vp_importLibrary')).on('click', function() {
+ com_interface.insertCell('code', 'from sklearn import metrics', true, 'Machine Learning > Evaluation');
+ });
+
+ // model type change
+ $(this.wrapSelector('#modelType')).on('change', function() {
+ let modelType = $(this).val();
+ that.state.modelType = modelType;
+
+ $(that.wrapSelector('.vp-upper-box')).hide();
+ $(that.wrapSelector('.vp-upper-box.' + modelType)).show();
+
+ $(that.wrapSelector('.vp-eval-box')).hide();
+ $(that.wrapSelector('.vp-eval-'+modelType)).show();
+
+ if (modelType == 'rgs') {
+ // Regression
+
+ } else if (modelType == 'clf') {
+ // Classification - model selection
+ // if (that.checkToShowSelector('roc-auc') == true) {
+ // $(that.wrapSelector('.vp-ev-model.roc-auc')).prop('disabled', false);
+ // } else {
+ // $(that.wrapSelector('.vp-ev-model.roc-auc')).prop('disabled', true);
+ // }
+ } else {
+ // Clustering
+ if (that.checkToShowSelector('silhouette') == true) {
+ $(that.wrapSelector('.vp-ev-model.silhouette')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-ev-model.silhouette')).prop('disabled', true);
+ }
+ if (that.checkToShowSelector('ari-nmi') == true) {
+ $(that.wrapSelector('.vp-ev-model.ari-nmi')).prop('disabled', false);
+ } else {
+ $(that.wrapSelector('.vp-ev-model.ari-nmi')).prop('disabled', true);
+ }
+ }
+ });
+
+ // check to enable/disable selector
+ $(this.wrapSelector('.vp-eval-check')).on('change', function() {
+ let checked = $(this).prop('checked');
+ let type = $(this).data('type');
+
+ if (checked) {
+ $(that.wrapSelector('.vp-ev-model.' + type)).prop('disabled', false);
+ } else {
+ if (that.checkToShowSelector(type) == false) {
+ $(that.wrapSelector('.vp-ev-model.' + type)).prop('disabled', true);
+ }
+ }
+ });
+ }
+
+ /**
+ * Check if anything checked available ( > 0)
+ * @returns
+ */
+ checkToShowSelector(type) {
+ let checked = $(this.wrapSelector('.vp-eval-check[data-type="' + type + '"]:checked')).length;
+ if (checked > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ templateForBody() {
+ let page = $(evalHTML);
+
+ $(page).find('.vp-eval-box').hide();
+ $(page).find('.vp-eval-'+this.state.modelType).show();
+
+ // data selector
+ let predDataSelector = new DataSelector({
+ pageThis: this, id: 'predictData', value: this.state.predictData, required: true
+ });
+ $(page).find('#predictData').replaceWith(predDataSelector.toTagString());
+
+ let targetDataSelector = new DataSelector({
+ pageThis: this, id: 'targetData', value: this.state.targetData, required: true
+ });
+ $(page).find('#targetData').replaceWith(targetDataSelector.toTagString());
+
+ // Clustering - data selection
+ let clusteredIdxSelector = new DataSelector({
+ pageThis: this, id: 'clusteredIndex', value: this.state.clusteredIndex, required: true
+ });
+ $(page).find('#clusteredIndex').replaceWith(clusteredIdxSelector.toTagString());
+
+ let featureData2Selector = new DataSelector({
+ pageThis: this, id: 'featureData2', value: this.state.featureData2, classes: 'vp-ev-model silhouette', required: true
+ });
+ $(page).find('#featureData2').replaceWith(featureData2Selector.toTagString());
+
+ let targetData2Selector = new DataSelector({
+ pageThis: this, id: 'targetData2', value: this.state.targetData2, classes: 'vp-ev-model ari-nmi', required: true
+ });
+ $(page).find('#targetData2').replaceWith(targetData2Selector.toTagString());
+
+ $(page).find('.vp-upper-box').hide();
+ $(page).find('.vp-upper-box.' + this.state.modelType).show();
+
+ $(page).find('.vp-eval-box').hide();
+ $(page).find('.vp-eval-' + this.state.modelType).show();
+
+ if (this.state.modelType == 'rgs') {
+ // Regression
+
+ } else if (this.state.modelType == 'clf') {
+ // Classification
+ // if (this.state.roc_curve == false && this.state.auc == false) {
+ // $(page).find('.vp-ev-model.roc-auc').prop('disabled', true);
+ // }
+ } else {
+ // Clustering
+ if (this.state.silhouetteScore == false) {
+ $(page).find('.vp-ev-model.silhouette').prop('disabled', true);
+ }
+ if (this.state.ari == false && this.state.nmi == false) {
+ $(page).find('.vp-ev-model.ari-nmi').prop('disabled', true);
+ }
+ }
+
+ return page;
+ }
+
+ generateImportCode() {
+ return ['from sklearn import metrics'];
+ }
+
+ generateCode() {
+ let codeCells = [
+ // ...this.generateImportCode() // run import codes
+ ];
+ let code = new com_String();
+ let {
+ modelType, predictData, targetData,
+ // classification
+ confusion_matrix, report, accuracy, precision, recall, f1_score,
+ // regression
+ coefficient, intercept, r_squared, mae, mape, rmse, scatter_plot,
+ // clustering
+ sizeOfClusters, silhouetteScore, ari, nmi,
+ clusteredIndex, featureData2, targetData2
+ } = this.state;
+ // add import code for display and Markdown
+ let needDisplay = false;
+ let needMarkdown = false;
+
+ //====================================================================
+ // Classification
+ //====================================================================
+ if (modelType == 'clf') {
+ if (confusion_matrix) {
+ code = new com_String();
+ code.appendLine("# Confusion Matrix");
+ code.appendLine("display(Markdown('### Confusion Matrix'))");
+ code.appendFormat('display(pd.crosstab({0}, {1}, margins=True))', targetData, predictData);
+ needMarkdown = true;
+ codeCells.push(code.toString());
+ }
+ if (report) {
+ code = new com_String();
+ code.appendLine("# Classification report");
+ code.appendFormat('print(metrics.classification_report({0}, {1}))', targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (accuracy) {
+ code = new com_String();
+ code.appendLine("# Accuracy");
+ code.appendFormat("print('Accuracy: {}'.format(metrics.accuracy_score({0}, {1})))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (precision) {
+ code = new com_String();
+ code.appendLine("# Precision");
+ code.appendFormat("print('Precision: {}'.format(metrics.precision_score({0}, {1}, average='weighted')))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (recall) {
+ code = new com_String();
+ code.appendLine("# Recall");
+ code.appendFormat("print('Recall: {}'.format(metrics.recall_score({0}, {1}, average='weighted')))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (f1_score) {
+ code = new com_String();
+ code.appendLine("# F1-score");
+ code.appendFormat("print('F1-score: {}'.format(metrics.f1_score({0}, {1}, average='weighted')))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ // if (roc_curve) {
+ // code = new com_String();
+ // code.appendLine("# ROC Curve");
+ // code.appendFormatLine("fpr, tpr, thresholds = metrics.roc_curve({0}, {1}.decision_function({2}))", predictData, model, targetData);
+ // code.appendLine("plt.plot(fpr, tpr, label='ROC Curve')");
+ // code.appendLine("plt.xlabel('Sensitivity') ");
+ // code.append("plt.ylabel('Specificity') ")
+ // codeCells.push(code.toString());
+ // }
+ // if (auc) {
+ // code = new com_String();
+ // code.appendLine("# AUC");
+ // code.appendFormat("metrics.roc_auc_score({0}, {1}.decision_function({2}))", predictData, model, targetData);
+ // codeCells.push(code.toString());
+ // }
+ }
+
+ //====================================================================
+ // Regression
+ //====================================================================
+ if (modelType == 'rgs') {
+ // if (coefficient) {
+ // code.appendLine("# Coefficient (scikit-learn only)");
+ // code.appendFormatLine('model.coef_');
+ // }
+ // if (intercept) {
+ // code.appendLine("# Intercept (scikit-learn only)");
+ // code.appendFormatLine('model.intercept_');
+ // }
+ if (r_squared) {
+ code = new com_String();
+ code.appendLine("# R squared");
+ code.appendFormat("print('R squared: {}'.format(metrics.r2_score({0}, {1})))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (mae) {
+ code = new com_String();
+ code.appendLine("# MAE(Mean Absolute Error)");
+ code.appendFormat("print('MAE: {}'.format(metrics.mean_absolute_error({0}, {1})))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (mape) {
+ code = new com_String();
+ code.appendLine("# MAPE(Mean Absolute Percentage Error)");
+ code.appendLine('def MAPE(y_test, y_pred):');
+ code.appendLine(' return np.mean(np.abs((y_test - pred) / y_test)) * 100');
+ code.appendLine();
+ code.appendFormat("print('MAPE: {}'.format(MAPE({0}, {1})))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (rmse) {
+ code = new com_String();
+ code.appendLine("# RMSE(Root Mean Squared Error)");
+ code.appendFormat("print('RMSE: {}'.format(metrics.mean_squared_error({0}, {1})**0.5))", targetData, predictData);
+ codeCells.push(code.toString());
+ }
+ if (scatter_plot) {
+ code = new com_String();
+ code.appendLine('# Regression plot');
+ code.appendLine("display(Markdown('### Regression plot'))");
+ code.appendFormatLine('plt.scatter({0}, {1})', targetData, predictData);
+ code.appendFormatLine("plt.xlabel('{0}')", targetData);
+ code.appendFormatLine("plt.ylabel('{0}')", predictData);
+ code.append('plt.show()');
+ needMarkdown = true;
+ codeCells.push(code.toString());
+ }
+ }
+ //====================================================================
+ // Clustering
+ //====================================================================
+ if (modelType == 'cls') {
+ // if (sizeOfClusters) {
+ // code.appendLine("# Size of clusters");
+ // code.appendFormatLine("print(f'Size of clusters: {np.bincount({0})}')", predictData);
+ // }
+ if (silhouetteScore) {
+ code = new com_String();
+ code.appendLine("# Silhouette score");
+ code.appendFormat("print('Silhouette score: {}'.format(metrics.cluster.silhouette_score({0}, {1})))", featureData2, clusteredIndex);
+ codeCells.push(code.toString());
+ }
+ if (ari) {
+ code = new com_String();
+ code.appendLine("# ARI(Adjusted Rand score)");
+ code.appendFormat("print('ARI: {}'.format(metrics.cluster.adjusted_rand_score({0}, {1})))", targetData2, clusteredIndex);
+ codeCells.push(code.toString());
+ }
+ if (nmi) {
+ code = new com_String();
+ code.appendLine("# NMI(Normalized Mutual Info Score)");
+ code.appendFormat("print('NM: {}'.format(metrics.cluster.normalized_mutual_info_score({0}, {1})))", targetData2, clusteredIndex);
+ codeCells.push(code.toString());
+ }
+ }
+ if (needMarkdown === true) {
+ codeCells = [
+ "from IPython.display import display, Markdown",
+ ...codeCells
+ ];
+ } else if (needDisplay === true) {
+ codeCells = [
+ "from IPython.display import display",
+ ...codeCells
+ ];
+ }
+ // return as separated cells
+ return codeCells;
+ }
+
+ }
+
+ return Evaluation;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/Anova.js b/visualpython/js/m_stats/Anova.js
new file mode 100644
index 00000000..4d6f901f
--- /dev/null
+++ b/visualpython/js/m_stats/Anova.js
@@ -0,0 +1,511 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Anova.js
+ * Author : Black Logic
+ * Note : ANOVA
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 24
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Anova
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/anova.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(nmHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, Subset) {
+
+ /**
+ * Anova
+ */
+ class Anova extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd', 'np', 'stats', 'vp_confidence_interval', 'vp_sem'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ testType: 'one-way',
+ data: '',
+ dataType: '',
+ depVar: '',
+ factor: '',
+ factorA: '',
+ factorB: '',
+ covariate: '',
+ sigLevel: 0.05,
+ // Post hoc analysis option
+ tukeyHSD: true,
+ tukey: false,
+ scheffe: false,
+ duncan: false,
+ bonferroni: false,
+ // Display option
+ statistics: true,
+ boxplot: true,
+ equalVariance: true,
+ interPlot: true,
+ ...this.state
+ };
+
+ this.columnBindList = ['depVar', 'factor', 'factorA', 'factorB', 'covariate'];
+
+ this.tmpInstallCode = []; // install codes
+
+ this.subsetEditor = {};
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#testType')).on('change', function() {
+ let testType = $(this).val();
+ that.state.testType = testType;
+
+ $(that.wrapSelector('.vp-st-option')).hide();
+ $(that.wrapSelector('.vp-st-option.' + testType)).show();
+
+ that.tmpInstallCode = [];
+ that.hideInstallButton();
+
+ if (testType === 'one-way' || testType === 'two-way') {
+ if (that.state.tukey || that.state.scheffe || that.state.duncan) {
+ // Add installation code
+ if (vpConfig.extensionType === 'lite') {
+ that.tmpInstallCode = ["%pip install scikit-posthocs"];
+ } else {
+ that.tmpInstallCode = ["!pip install scikit-posthocs"];
+ }
+ that.showInstallButton();
+ }
+ } else if (testType === 'ancova') {
+ // Add installation code : # pip install pingouin
+ if (vpConfig.extensionType === 'lite') {
+ that.tmpInstallCode = ["%pip install pingouin"];
+ } else {
+ that.tmpInstallCode = ["!pip install pingouin"];
+ }
+ that.showInstallButton();
+ }
+ });
+
+ $(this.wrapSelector('#data')).on('change', function() {
+ if (that.state.dataType === 'Series') {
+ // Series
+ that.columnBindList.forEach(id => {
+ $(that.wrapSelector('#' + id)).html('');
+ $(that.wrapSelector('#' + id)).prop('disabled', true);
+ });
+ } else {
+ // DataFrame
+ that.columnBindList.forEach(id => {
+ $(that.wrapSelector('#' + id)).prop('disabled', false);
+ });
+ com_generator.vp_bindColumnSource(that, 'data', that.columnBindList, 'select', false, false);
+ }
+ });
+
+ $(this.wrapSelector('.vp-st-posthoc-box .vp-state')).on('change', function() {
+ let id = $(this)[0].id;
+ let checked = $(this).prop('checked') === true;
+ that.state[id] = checked;
+ let { testType, tukey, scheffe, duncan } = that.state;
+ if (testType === 'one-way' || testType === 'two-way') {
+ if (tukey || scheffe || duncan) {
+ // Add installation code
+ if (vpConfig.extensionType === 'lite') {
+ that.tmpInstallCode = ["%pip install scikit-posthocs"];
+ } else {
+ that.tmpInstallCode = ["!pip install scikit-posthocs"];
+ }
+ that.showInstallButton();
+ } else {
+ that.hideInstallButton();
+ }
+ }
+ });
+
+ $(this.wrapSelector(''))
+ }
+
+ templateForBody() {
+ let page = $(nmHTML);
+ let that = this;
+
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor['data'] = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code, state) {
+ that.state.data = code;
+ $(that.wrapSelector('#data')).val(code);
+ that.state.dataType = state.returnType;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+
+ // bind column if data exist
+ if (this.state.data !== '') {
+ com_generator.vp_bindColumnSource(this, 'data', this.columnBindList, 'select', false, false);
+ }
+
+ // control display option
+ $(this.wrapSelector('.vp-st-option')).hide();
+ $(this.wrapSelector('.vp-st-option.' + this.state.testType)).show();
+ }
+
+ generateInstallCode() {
+ return this.tmpInstallCode;
+ }
+
+ generateCode() {
+ let {
+ testType, data, depVar, factor, factorA, factorB, covariate, sigLevel,
+ // Post hoc analysis option
+ tukeyHSD, tukey, scheffe, duncan, bonferroni,
+ // Display option
+ statistics, boxplot, equalVariance, interPlot
+ } = this.state;
+
+ // get only text without '' or ""
+ let depVarText = $(this.wrapSelector('#depVar option:selected')).text();
+ let factorText = $(this.wrapSelector('#factor option:selected')).text();
+ let factorAText = $(this.wrapSelector('#factorA option:selected')).text();
+ let factorBText = $(this.wrapSelector('#factorB option:selected')).text();
+ let covariateText = $(this.wrapSelector('#covariate option:selected')).text();
+
+ let codeList = [];
+ let code = new com_String();
+
+ // test type label
+ let testTypeLabel = $(this.wrapSelector('#testType option:selected')).text();
+ code.appendFormatLine("# {0}", testTypeLabel);
+ code.appendFormat("vp_df = {0}.dropna().copy()", data);
+
+ switch (testType) {
+ case 'one-way':
+ // 1. One-way ANOVA
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("_df = pd.DataFrame()");
+ code.appendFormatLine("for k, v in dict(list(vp_df.groupby({0})[{1}])).items():", factor, depVar);
+ code.appendLine(" _df_t = v.reset_index(drop=True)");
+ code.appendLine(" _df_t.name = k");
+ code.append(" _df = pd.concat([_df, _df_t], axis=1)");
+
+ // Display - Statistics
+ if (statistics === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendLine("display(pd.DataFrame(data={'Count':_df.count(),'Mean':_df.mean(numeric_only=True),'Std. Deviation':_df.std(numeric_only=True),'Min':_df.min(),'Max':_df.max(),");
+ code.appendLine(" 'Std. Error Mean':_df.apply(vp_sem),'Confidence interval':0.95,");
+ code.append(" 'Lower':_df.apply(vp_confidence_interval).T[0],'Upper':_df.apply(vp_confidence_interval).T[1] }))");
+ }
+ // Display - Boxplot
+ if (boxplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Boxplot");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" sns.boxplot(data=_df)");
+ code.append(" plt.show()");
+ }
+ // Display - Equal Variance
+ if (equalVariance === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Equal Variance test (Levene)");
+ code.appendLine("from scipy import stats");
+ code.appendLine("_lst = []");
+ code.appendLine("_df.apply(lambda x: _lst.append(x.dropna()))");
+ code.appendLine("_res = stats.levene(*_lst, center='mean')");
+ code.appendLine("display(Markdown('### Equal Variance test (Levene)'))");
+ code.append("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue}, index=['Equal Variance test (Levene)']))");
+ }
+
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# One-way ANOVA");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendLine("from statsmodels.stats.anova import anova_lm");
+ code.appendFormatLine("_model = smf.ols('{0} ~ C({1})', vp_df)", depVarText, factorText);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("_dfr = anova_lm(_result)");
+ code.appendLine("_dfr.loc['Total','df'] = _dfr['df'].sum()");
+ code.appendLine("_dfr.loc['Total','sum_sq'] = _dfr['sum_sq'].sum()");
+ code.appendLine("display(Markdown('### One-way ANOVA'))");
+ code.append("display(_dfr)");
+
+ // Post hoc analysis - Tukey HSD
+ if (tukeyHSD === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Tukey HSD");
+ code.appendLine("from statsmodels.sandbox.stats.multicomp import MultiComparison");
+ code.appendFormatLine("_res = MultiComparison(vp_df[{0}], vp_df[{1}]).tukeyhsd(alpha={2})", depVar, factor, sigLevel);
+ code.appendLine("display(Markdown('### Post-hoc: Tukey HSD'))");
+ code.append("display(_res.summary())");
+ }
+ // Post hoc analysis - Bonferroni
+ if (bonferroni === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Bonferroni");
+ code.appendLine("from statsmodels.sandbox.stats.multicomp import MultiComparison");
+ code.appendFormatLine("_res = MultiComparison(vp_df[{0}], vp_df[{1}]).allpairtest(stats.ttest_ind,alpha={2},method='bonf')", depVar, factor, sigLevel);
+ code.appendLine("display(Markdown('### Post-hoc: Bonferroni'))");
+ code.append("display(_res[0])");
+ }
+
+ if (tukey === true || scheffe === true || duncan === true) {
+ // Post hoc analysis - Tukey
+ if (tukey === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Tukey");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Tukey'))");
+ code.appendFormat("display(sph.posthoc_tukey(vp_df, val_col={0}, group_col={1}))", depVar, factor);
+ }
+ // Post hoc analysis - Scheffe
+ if (scheffe === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Scheffe");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Scheffe'))");
+ code.appendFormat("display(sph.posthoc_scheffe(vp_df, val_col={0}, group_col={1}))", depVar, factor);
+
+ }
+ // Post hoc analysis - duncan
+ if (duncan === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Duncan");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Duncan'))");
+ code.appendFormat("display(sph.posthoc_dunn(vp_df, val_col={0}, group_col={1}))", depVar, factor);
+ }
+ }
+
+ break;
+ case 'two-way':
+ // 1. Two-way ANOVA
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("_df = pd.DataFrame()");
+ code.appendFormatLine("for k, v in dict(list(vp_df.groupby([{0},{1}])[{2}])).items():", factorB, factorA, depVar);
+ code.appendLine(" _df_t = v.reset_index(drop=True)");
+ code.appendLine(" _df_t.name = k");
+ code.appendLine(" _df = pd.concat([_df, _df_t], axis=1)");
+ code.append(" _df.columns = [[x[0] for x in _df.columns],[x[1] for x in _df.columns]]");
+
+ // Display - Statistics
+ if (statistics === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendLine("display(pd.DataFrame(data={'Count':_df.count(),'Mean':_df.mean(numeric_only=True),'Std. Deviation':_df.std(numeric_only=True),'Min':_df.min(),'Max':_df.max(),");
+ code.appendLine(" 'Std. Error Mean':_df.apply(vp_sem),'Confidence interval':0.95,");
+ code.append(" 'Lower':_df.apply(vp_confidence_interval).T[0],'Upper':_df.apply(vp_confidence_interval).T[1] }))");
+ }
+ // Display - Boxplot
+ if (boxplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Boxplot");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" sns.boxplot(data=_df)");
+ code.append(" plt.show()");
+ }
+ // Display - Equal Variance test
+ if (equalVariance === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Equal Variance test (Levene)");
+ code.appendLine("from scipy import stats");
+ code.appendLine("_lst = []");
+ code.appendLine("_df.apply(lambda x: _lst.append(x.dropna()))");
+ code.appendLine("_res = stats.levene(*_lst, center='mean')");
+ code.appendLine("display(Markdown('### Equal Variance test (Levene)'))");
+ code.append("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue}, index=['Equal Variance test (Levene)']))");
+ }
+
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Two-way ANOVA");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendLine("from statsmodels.stats.anova import anova_lm");
+ code.appendFormatLine("_model = smf.ols('{0} ~ C({1}) + C({2}) + C({3}):C({4})', vp_df)", depVarText, factorAText, factorBText, factorAText, factorBText);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("_dfr = anova_lm(_result)");
+ code.appendLine("_dfr.loc['Total','df'] = _dfr['df'].sum()");
+ code.appendLine("_dfr.loc['Total','sum_sq'] = _dfr['sum_sq'].sum()");
+ code.appendLine("display(Markdown('### Two-way ANOVA'))");
+ code.append("display(_dfr)");
+
+ // Display - Interaction plot
+ if (interPlot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Interaction plot");
+ code.appendLine("from statsmodels.graphics.factorplots import interaction_plot");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendFormatLine(" fig = interaction_plot(x=vp_df[{0}], trace=vp_df[{1}], response=vp_df[{2}])", factorA, factorB, depVar);
+ code.append(" plt.show()");
+ }
+ // Post hoc analysis - Tukey HSD
+ if (tukeyHSD === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Tukey HSD");
+ code.appendLine("from statsmodels.sandbox.stats.multicomp import MultiComparison");
+ code.appendFormatLine("_res = MultiComparison(vp_df[{0}], vp_df[{1}]).tukeyhsd(alpha={2})", depVar, factorA, sigLevel);
+ code.appendLine("display(Markdown('### Post-hoc: Tukey HSD'))");
+ code.append("display(_res.summary())");
+ }
+ // Post hoc analysis - Bonferroni
+ if (bonferroni === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Bonferroni");
+ code.appendLine("from statsmodels.sandbox.stats.multicomp import MultiComparison");
+ code.appendFormatLine("_res = MultiComparison(vp_df[{0}], vp_df[{1}]).allpairtest(stats.ttest_ind,alpha={2},method='bonf')", depVar, factorA, sigLevel);
+ code.appendLine("display(Markdown('### Post-hoc: Bonferroni'))");
+ code.append("display(_res[0])");
+ }
+ if (tukey === true || scheffe === true || duncan === true) {
+ // Post hoc analysis - Tukey
+ if (tukey === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Tukey");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Tukey'))");
+ code.appendFormat("display(sph.posthoc_tukey(vp_df, val_col={0}, group_col={1}))", depVar, factorA);
+ }
+ // Post hoc analysis - Scheffe
+ if (scheffe === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Scheffe");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Scheffe'))");
+ code.appendFormat("display(sph.posthoc_scheffe(vp_df, val_col={0}, group_col={1}))", depVar, factorA);
+ }
+ // Post hoc analysis - Duncan
+ if (duncan === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Post-hoc: Duncan");
+ code.appendLine("import scikit_posthocs as sph");
+ code.appendLine("display(Markdown('### Post-hoc: Duncan'))");
+ code.appendFormat("display(sph.posthoc_dunn(vp_df, val_col={0}, group_col={1}))", depVar, factorA);
+ }
+ }
+ break;
+ case 'ancova':
+ // 1. ANCOVA
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("_df = pd.DataFrame()");
+ code.appendFormatLine("for k, v in dict(list(vp_df.groupby({0})[{1}])).items():", factor, depVar);
+ code.appendLine(" _df_t = v.reset_index(drop=True)");
+ code.appendLine(" _df_t.name = k");
+ code.append(" _df = pd.concat([_df, _df_t], axis=1)");
+
+ // Display - Statistics
+ if (statistics === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendLine("display(pd.DataFrame(data={'Count':_df.count(),'Mean':_df.mean(numeric_only=True),'Std. Deviation':_df.std(numeric_only=True),'Min':_df.min(),'Max':_df.max(),");
+ code.appendLine(" 'Std. Error Mean':_df.apply(vp_sem),'Confidence interval':0.95,");
+ code.append(" 'Lower':_df.apply(vp_confidence_interval).T[0],'Upper':_df.apply(vp_confidence_interval).T[1] }))");
+ }
+ // Display - Boxplot
+ if (boxplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Boxplot");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" sns.boxplot(data=_df)");
+ code.append(" plt.show()");
+ }
+
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# ANCOVA - Analysis of covariance");
+ code.appendLine("import pingouin as pg");
+ code.appendLine("display(Markdown('### ANCOVA - Analysis of covariance'))");
+ code.appendFormat("display(pg.ancova(data=vp_df, dv={0}, between={1}, covar={2}))", depVar, factor, covariate);
+ break;
+ }
+
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return Anova;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/Chi2test.js b/visualpython/js/m_stats/Chi2test.js
new file mode 100644
index 00000000..03d3cab2
--- /dev/null
+++ b/visualpython/js/m_stats/Chi2test.js
@@ -0,0 +1,215 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Chi2test.js
+ * Author : Black Logic
+ * Note : Chi-square test of independence
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 24
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Chi2test
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/chi2test.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(nmHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, Subset) {
+
+ /**
+ * Chi2test
+ */
+ class Chi2test extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ data: '',
+ dataType: '',
+ row: '',
+ column: '',
+ barplot: true,
+ crossTab: true,
+ cramersCoef: true,
+ ...this.state
+ };
+
+ this.subsetEditor = null;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#data')).on('change', function() {
+ let bindIdList = ['row', 'column'];
+ if (that.state.dataType === 'Series') {
+ // Series
+ bindIdList.forEach(id => {
+ $(that.wrapSelector('#' + id)).html('');
+ $(that.wrapSelector('#' + id)).prop('disabled', true);
+ });
+ } else {
+ // DataFrame
+ bindIdList.forEach(id => {
+ $(that.wrapSelector('#' + id)).prop('disabled', false);
+ });
+ com_generator.vp_bindColumnSource(that, 'data', bindIdList, 'select', false, false);
+ }
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ let bindIdList = ['row', 'column'];
+ if (that.state.dataType === 'DataFrame') {
+ // DataFrame
+ bindIdList.forEach(id => {
+ $(that.wrapSelector('#' + id)).html('');
+ $(that.wrapSelector('#' + id)).prop('disabled', false);
+ });
+ com_generator.vp_bindColumnSource(that, 'data', bindIdList, 'select', false, false);
+ } else {
+ // Others
+ bindIdList.forEach(id => {
+ $(that.wrapSelector('#' + id)).html('');
+ $(that.wrapSelector('#' + id)).prop('disabled', true);
+ });
+ }
+ }
+
+ templateForBody() {
+ let page = $(nmHTML);
+ let that = this;
+
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code, state) {
+ that.state.data = code;
+ that.state.dataType = state.returnType;
+ $(that.wrapSelector('#data')).val(code);
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+
+ // bind column if data exist
+ if (this.state.data !== '') {
+ com_generator.vp_bindColumnSource(this, 'data', ['row', 'column'], 'select', false, false);
+ }
+ }
+
+ generateCode() {
+ let { data, row, column, barplot, crossTab, cramersCoef } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+
+ // Display option
+ if (barplot === true) {
+ code.appendLine();
+ code.appendLine("# Count plot");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendFormatLine(" sns.countplot(data=vp_df, x={0}, hue={1})", row, column);
+ code.appendLine(" plt.show()");
+ }
+
+ code.appendLine("");
+ code.appendLine("# Chi-square test of independence");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_obs = pd.crosstab(index=vp_df[{0}], columns=vp_df[{1}])", row, column);
+ code.appendLine("_res1 = stats.chi2_contingency(_obs)");
+ code.appendLine("_res2 = stats.chi2_contingency(_obs, lambda_='log-likelihood')");
+
+ if (crossTab === true) {
+ code.appendLine("");
+ code.appendLine("# Cross tabulation: Count");
+ code.appendFormatLine("_dfc = pd.crosstab(index=vp_df[{0}],columns=vp_df[{1}],margins=True,margins_name='Total')", row, column);
+ code.appendLine("_dfc = _dfc.reset_index().reset_index()");
+ code.appendLine("_dfc[' '] = 'Count'");
+ code.appendLine("");
+ code.appendLine("# Cross tabulation: Expected count");
+ code.appendLine("_dfe = pd.DataFrame(_res1.expected_freq, index=_obs.index, columns=_obs.columns).round(1)");
+ code.appendLine("_dfe.loc['Total',:] = _dfe.sum(axis=0)");
+ code.appendLine("_dfe.loc[:,'Total'] = _dfe.sum(axis=1)");
+ code.appendLine("_dfe = _dfe.reset_index().reset_index()");
+ code.appendLine("_dfe[' '] = 'Expected count'");
+ code.appendLine("");
+ code.appendLine("# Cross tabulation: Count + Expected count");
+ code.appendLine("display(Markdown('### Cross tabulation'))");
+ code.appendFormatLine("display(pd.concat([_dfc, _dfe]).set_index([{0},' ']).sort_values('index').drop('index',axis=1))", row);
+ }
+
+ code.appendLine("");
+ code.appendLine("# Chi-square test");
+ code.appendLine("display(Markdown('### Chi-square test'))");
+ code.appendLine("display(pd.DataFrame(data = {'Value':[_res1.statistic,_res2.statistic,vp_df.dropna().shape[0]],");
+ code.appendLine(" 'df':[_res1.dof,_res2.dof,np.nan],");
+ code.appendLine(" 'p-value(two-sided)':[_res1.pvalue,_res2.pvalue,np.nan]},");
+ code.append(" index= ['Pearson Chi-square','Likelihood ratio','N of valid cases']))");
+
+ if (cramersCoef === true) {
+ code.appendLine("");
+ code.appendLine("");
+ code.appendLine("# Cramers' V coefficient");
+ code.appendLine("_X2 = stats.chi2_contingency(_obs)[0]");
+ code.appendLine("_sum = _obs.sum().sum()");
+ code.appendLine("_minDim = min(_obs.shape)-1");
+ code.appendLine("display(Markdown('### Cramers V coefficient'))");
+ code.append("display(pd.DataFrame(data={'Value':np.sqrt((_X2/_sum) / _minDim)}, index=['Cramers V coefficient']))");
+ }
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return Chi2test;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/CorrAnalysis.js b/visualpython/js/m_stats/CorrAnalysis.js
new file mode 100644
index 00000000..92251434
--- /dev/null
+++ b/visualpython/js/m_stats/CorrAnalysis.js
@@ -0,0 +1,202 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : CorrAnalysis.js
+ * Author : Black Logic
+ * Note : Correlation Analysis
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 24
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] CorrAnalysis
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/corrAnalysis.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, com_util, com_Const, com_String, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * CorrAnalysis
+ */
+ class CorrAnalysis extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ data: '',
+ variable: [],
+ corrType: 'pearson',
+ corrAnlaysis: true,
+ corrMatrix: true,
+ corrHeatmap: false,
+ scatterMatrix: false,
+ ...this.state
+ };
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: this.state.data, selectedList: this.state.variable?.map(x=>x.code), showDescription: false }
+ );
+ }
+
+ generateCode() {
+ let { data, variable, corrType, corrAnlaysis, corrMatrix, corrHeatmap, scatterMatrix } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ // data declaration
+ code.appendFormat("vp_df = {0}", data);
+ if (this.columnSelector) {
+ let columns = this.columnSelector.getDataList();
+ this.state.variable = columns;
+ if (columns.length > 0) {
+ code.appendFormat("[[{0}]]", columns.map(x => x.code).join(', '));
+ }
+ }
+ code.append('.dropna().copy()');
+
+ let corrTypeLabel = $(this.wrapSelector('#corrType option:selected')).text();
+
+ // Display option : Correlation Analysis
+ if (corrAnlaysis === true) {
+ // Inner function : vp_confidence_interval_corr
+ this.addCheckModules('vp_confidence_interval_corr');
+
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Correlation Analysis");
+ code.appendLine("from scipy import stats");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("_dfr = pd.DataFrame()");
+ code.appendLine("for i, col1 in enumerate(vp_df.columns):");
+ code.appendLine(" for j, col2 in enumerate(vp_df.columns):");
+ code.appendLine(" if i >= j: continue");
+ code.appendLine(" if pd.api.types.is_numeric_dtype(vp_df[col1]) and pd.api.types.is_numeric_dtype(vp_df[col2]):");
+ code.appendFormatLine(" _res = vp_confidence_interval_corr(vp_df[col1], vp_df[col2], method='{0}')", corrType);
+ code.appendLine(" _df_t = pd.DataFrame(data={'Variable1':col1,'Variable2':col2,'N':vp_df[col1].size,'Correlation coefficient':_res[0],");
+ code.appendLine(" 'p-value':_res[1],'Lower(95%)':_res[2],'Upper(95%)':_res[3]}, index=[0])");
+ code.appendLine(" _dfr = pd.concat([_dfr, _df_t]).reset_index(drop=True)");
+ code.appendFormatLine("display(Markdown('### Correlation Analysis: {0}'))", corrTypeLabel.replace("'", "\\'"));
+ code.append("display(_dfr)");
+ }
+
+ // Display option : Correlation Matrix
+ if (corrMatrix === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Correlation matrix: {0}", corrTypeLabel);
+ code.appendLine("from IPython.display import display");
+ code.appendFormat("display(vp_df.corr(method='{0}', numeric_only=True).round(2))", corrType);
+ }
+
+ if (corrHeatmap === true || scatterMatrix === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Chart");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.append(" warnings.simplefilter(action='ignore', category=Warning)");
+ // Display option : Correlation Heatmap
+ if (corrHeatmap === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Heatmap");
+ code.appendFormatLine(" sns.heatmap(vp_df.corr(method='{0}', numeric_only=True), annot=True, fmt='.2f', cmap='coolwarm')", corrType);
+ code.appendFormatLine(" plt.title('Correlation heatmap: {0}')", corrTypeLabel.replace("'", "\\'"));
+ code.append(" plt.show()");
+ }
+ // Display option : Scatter Matrix
+ if (scatterMatrix === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Scatter matrix");
+ code.appendLine(" pd.plotting.scatter_matrix(vp_df)");
+ code.append(" plt.show()");
+ }
+ }
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return CorrAnalysis;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/DescStats.js b/visualpython/js/m_stats/DescStats.js
new file mode 100644
index 00000000..e6a9aa45
--- /dev/null
+++ b/visualpython/js/m_stats/DescStats.js
@@ -0,0 +1,320 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : DescStats.js
+ * Author : Black Logic
+ * Note : Descriptive Statistics
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 31
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] DescStats
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/descStats.html'),
+ __VP_CSS_LOADER__('vp_base/css/m_stats/descStats'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, dsCss, com_util, com_Const, com_String, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * DescStats
+ */
+ class DescStats extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+
+ this.state = {
+ data: '',
+ variable: [],
+ // Central tendency
+ mean: true,
+ median: false,
+ mode: false,
+ sum: true,
+ // Dispersion
+ min: false,
+ max: false,
+ range: false,
+ std: true,
+ var: true,
+ semean: false,
+ skew: false,
+ kurtosis: false,
+ // Percentile values
+ quantile: true,
+ usePercentile: false,
+ percentiles: [],
+ // Frequency table
+ frequency: true,
+ percent: true,
+ validPercent: true,
+ cumulativePercent: true,
+ noUniqVals: 10,
+ // Display
+ histogram: true,
+ scatterMatrix: true,
+ boxplot: true,
+ ...this.state
+ };
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // data selection
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+
+ // use percentile
+ $(this.wrapSelector('#usePercentile')).on('change', function() {
+ let checked = $(this).prop('checked');
+ if (checked === true) {
+ // enable percentile editing
+ $(that.wrapSelector('#percentile')).prop('disabled', false);
+ $(that.wrapSelector('#addPercentile')).prop('disabled', false);
+ $(that.wrapSelector('.vp-percentile-box')).removeClass('disabled');
+ } else {
+ // disable percentile editing
+ $(that.wrapSelector('#percentile')).prop('disabled', true);
+ $(that.wrapSelector('#addPercentile')).prop('disabled', true);
+ $(that.wrapSelector('.vp-percentile-box')).addClass('disabled');
+
+ }
+ });
+
+ // add percentile
+ $(this.wrapSelector('#addPercentile')).on('click', function() {
+ let newVal = $(that.wrapSelector('#percentile')).val();
+ if (newVal && newVal !== '') {
+ let newValNum = parseInt(newVal);
+ that.addPercentile(newValNum);
+ that.state.percentiles.push(newValNum);
+ $(that.wrapSelector('#percentile')).val('');
+ }
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ addPercentile(percentile) {
+ if (this.state.percentiles.indexOf(percentile) === -1) {
+ $(this.wrapSelector('.vp-percentile-box')).append(
+ $(``));
+
+ // delete percentile
+ let that = this;
+ $(this.wrapSelector('.vp-percentile-box:not(.disabled) .vp-percentile-remove')).on('click', function() {
+ if (that.state.usePercentile === true) {
+ let delVal = parseInt($(this).parent().find('.vp-percentile-value').text());
+ that.state.percentiles = that.state.percentiles.filter(x => x !== delVal);
+ $(this).closest('.vp-percentile-item').remove();
+ }
+ });
+ }
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: this.state.data, showDescription: false }
+ );
+ }
+
+ generateCode() {
+ let { data, variable,
+ // Central tendency
+ mean,median,mode,sum,
+ // Dispersion
+ min,max,range,std,variance,semean,skew,kurtosis,
+ // Percentile values
+ quantile,usePercentile,percentiles,
+ // Frequency table
+ frequency,percent,validPercent,cumulativePercent,noUniqVals,
+ // Display
+ histogram,scatterMatrix,boxplot
+ } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ // data declaration
+ code.appendFormat("vp_df = {0}", data);
+ if (this.columnSelector) {
+ let columns = this.columnSelector.getDataList();
+ if (columns.length > 0) {
+ code.appendFormat("[[{0}]]", columns.map(x => x.code).join(', '));
+ }
+ }
+ code.appendLine('.copy()');
+
+ // Descriptive statistics
+ code.appendLine();
+ code.appendLine("# Descriptive statistics");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("display(Markdown('### Descriptive statistics'))");
+ code.appendLine("display(pd.DataFrame({");
+ code.appendLine(" 'N Total':vp_df.shape[0],");
+ code.appendLine(" 'N Valid':vp_df.count(numeric_only=True),");
+ code.appendLine(" 'N Missing':vp_df.loc[:,vp_df.apply(pd.api.types.is_numeric_dtype)].isnull().sum(),");
+ if (mean === true) code.appendLine(" 'Mean':vp_df.mean(numeric_only=True),");
+ if (median === true) code.appendLine(" 'Median':vp_df.median(numeric_only=True),");
+ if (mode === true) code.appendLine(" 'Mode':vp_df.mode(numeric_only=True).iloc[0],");
+ if (sum === true) code.appendLine(" 'Sum':vp_df.sum(numeric_only=True),");
+ if (min === true) code.appendLine(" 'Minimun':vp_df.min(numeric_only=True),");
+ if (max === true) code.appendLine(" 'Maximum':vp_df.max(numeric_only=True),");
+ if (range === true) code.appendLine(" 'Range':vp_df.max(numeric_only=True) - vp_df.min(numeric_only=True),");
+ if (std === true) code.appendLine(" 'Std. deviation':vp_df.std(numeric_only=True),");
+ if (variance === true) code.appendLine(" 'Variance':vp_df.var(numeric_only=True),");
+ if (semean === true) code.appendLine(" 'S.E. mean':vp_df.std(numeric_only=True)/np.sqrt(vp_df.count(numeric_only=True)),");
+ if (skew === true) code.appendLine(" 'Skewness':vp_df.skew(numeric_only=True),");
+ if (kurtosis === true) code.appendLine(" 'Kurtosis':vp_df.kurtosis(numeric_only=True),");
+ let sortedPercentiles = [];
+ if (quantile === true) {
+ sortedPercentiles = [25, 50, 75];
+ }
+ if (usePercentile === true && percentiles.length > 0) {
+ sortedPercentiles = [...sortedPercentiles, ...percentiles];
+ }
+ sortedPercentiles.sort((a, b) => { return a - b; });
+ sortedPercentiles.forEach(num => {
+ code.appendFormatLine(" 'Percentile: {0}':vp_df.quantile(q={1}, numeric_only=True),", num, (num / 100).toFixed(2));
+ });
+ code.appendLine("}).round(3).T)");
+
+ // Frequency table
+ code.appendLine();
+ code.appendLine("# Frequency table");
+ code.appendLine("display(Markdown('### Frequency table'))");
+ code.appendLine("for col in vp_df.columns:");
+ code.appendFormatLine(" if pd.api.types.is_numeric_dtype(vp_df[col]) and vp_df[col].value_counts().size > {0}:", noUniqVals);
+ code.appendFormatLine(" _bins = {0}", noUniqVals);
+ code.appendLine(" else: _bins = None");
+ code.appendLine(" ");
+ code.appendLine(" _dfr = pd.DataFrame({");
+ if (frequency === true) code.appendLine(" 'Frequency':vp_df[col].value_counts(bins=_bins, sort=False),");
+ if (percent === true) code.appendLine(" 'Percent':100*(vp_df[col].value_counts(bins=_bins, sort=False) / vp_df[col].size),");
+ if (validPercent === true) code.appendLine(" 'Valid percent':100*(vp_df[col].value_counts(bins=_bins, sort=False)/vp_df[col].count())");
+ code.appendLine("}).round(2)");
+ if (cumulativePercent === true) code.appendLine(" _dfr['Cumulative percent'] = _dfr['Valid percent'].cumsum()");
+ code.appendLine(" _dfr.loc['N Valid',:] = _dfr.iloc[:,:3].sum()");
+ code.appendLine(" _dfr.loc['N Missing','Frequency'] = vp_df[col].isnull().sum()");
+ code.appendLine(" _dfr.loc['N Total','Frequency'] = vp_df[col].size");
+ code.append(" display(_dfr)");
+
+ // Display option
+ if (histogram || scatterMatrix || boxplot) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Charts");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.append(" warnings.simplefilter(action='ignore', category=Warning)");
+ if (histogram === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Histogram");
+ code.appendLine(" idx = 1");
+ code.appendLine(" for col in vp_df.columns:");
+ code.appendLine(" plt.subplot(2,2, idx)");
+ code.appendFormatLine(" if pd.api.types.is_numeric_dtype(vp_df[col]) and vp_df[col].value_counts().size > {0}:", noUniqVals);
+ code.appendLine(" sns.histplot(data=vp_df, x=col, kde=True)");
+ code.appendLine(" else:");
+ code.appendLine(" sns.countplot(data=vp_df, x=col)");
+ code.appendLine(" ");
+ code.appendLine(" if idx < 4:");
+ code.appendLine(" idx += 1");
+ code.appendLine(" else:");
+ code.appendLine(" idx = 1");
+ code.appendLine(" plt.tight_layout()");
+ code.append(" plt.show()");
+ }
+ if (scatterMatrix === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Scatter matrix ");
+ code.appendLine(" pd.plotting.scatter_matrix(vp_df, marker='o', hist_kwds={'bins': 30}, s=30, alpha=.8)");
+ code.append(" plt.show()");
+ }
+ if (boxplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Boxplot");
+ code.appendLine(" sns.boxplot(vp_df)");
+ code.append(" plt.show()");
+ }
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return DescStats;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/EqualVarTest.js b/visualpython/js/m_stats/EqualVarTest.js
new file mode 100644
index 00000000..3f6569e1
--- /dev/null
+++ b/visualpython/js/m_stats/EqualVarTest.js
@@ -0,0 +1,246 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : EqualVarTest.js
+ * Author : Black Logic
+ * Note : Equal Variance test
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] EqualVarTest
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/equalVarTest.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * EqualVarTest
+ */
+ class EqualVarTest extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ testType: 'bartlett',
+ inputType: 'long-data',
+ data: '',
+ variableMulti: [],
+ variable: '',
+ factor: '',
+ center: 'mean',
+ histogram: true,
+ ...this.state
+ };
+
+ this.subsetEditor = {};
+ this.columnSelector = {};
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // change test type
+ $(this.wrapSelector('#testType')).on('change', function() {
+ let testType = $(this).val();
+ that.state.testType = testType;
+
+ $(that.wrapSelector('.vp-st-option')).hide();
+ $(that.wrapSelector('.vp-st-option.' + testType)).show();
+ });
+
+ // change input type
+ $(this.wrapSelector('input[name="inputType"]:radio')).on('change', function() {
+ let inputType = $(this).val();
+ that.state.inputType = inputType;
+ $(that.wrapSelector('.vp-variable-box')).hide();
+ $(that.wrapSelector('.vp-variable-box.' + inputType)).show();
+ });
+
+ // data change event
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ // render column selector
+ com_generator.vp_bindColumnSource(this, 'data', ['variable', 'factor'], 'select', false, false);
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variableMulti'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ if (this.state.data !== '') {
+ // render column selector
+ com_generator.vp_bindColumnSource(this, 'data', ['variable', 'factor'], 'select', false, false);
+ }
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variableMulti'),
+ { mode: 'columns', parent: this.state.data, selectedList: this.state.variableMulti?.map(x => x.code), showDescription: false }
+ );
+
+ $(this.wrapSelector('.vp-variable-box')).hide();
+ $(this.wrapSelector('.vp-variable-box.' + this.state.inputType)).show();
+
+ // control display option
+ $(this.wrapSelector('.vp-st-option')).hide();
+ $(this.wrapSelector('.vp-st-option.' + this.state.testType)).show();
+ }
+
+ generateCode() {
+ let { testType, inputType, data, variable, factor, center, histogram } = this.state;
+ let codeList = [];
+ let code = new com_String();
+ let that = this;
+
+ // test type label
+ let testTypeLabel = $(this.wrapSelector('#testType option:selected')).text();
+ code.appendFormatLine("# {0}", testTypeLabel);
+
+ if (inputType === 'long-data') {
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+ code.appendLine("_df = pd.DataFrame()");
+ code.appendFormatLine("for k, v in dict(list(vp_df.groupby({0})[{1}])).items():", factor, variable);
+ code.appendLine(" _df_t = v.reset_index(drop=True)");
+ code.appendLine(" _df_t.name = k");
+ code.append(" _df = pd.concat([_df, _df_t], axis=1)");
+ } else if (inputType === 'wide-data') {
+ // get variable multi
+ let columns = this.columnSelector.getDataList();
+ this.state.variableMulti = columns;
+ code.appendFormatLine("vp_df = {0}[[{1}]].copy()", data, columns.map(x => x.code).join(', ')); // without dropna
+ code.append("_df = vp_df.copy()");
+ }
+
+ // add variance code
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Variance");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendLine("_dfr = _df.var().to_frame()");
+ code.appendLine("_dfr.columns = ['Variance']");
+ code.append("display(_dfr)");
+
+ switch (testType) {
+ case 'bartlett':
+ // 1. Bartlett test
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Bartlett test");
+ code.appendLine("_lst = []");
+ code.appendLine("_df.apply(lambda x: _lst.append(x.dropna()))");
+ code.appendLine("_res = stats.bartlett(*_lst)");
+ code.appendLine("display(Markdown('### Bartlett test'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Equal Variance test (Bartlett)']))");
+ break;
+ case 'levene':
+ // 1. Levene test
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Levene test");
+ code.appendLine("_lst = []");
+ code.appendLine("_df.apply(lambda x: _lst.append(x.dropna()))");
+ code.appendFormatLine("_res = stats.levene(*_lst, center='{0}')", center);
+ code.appendLine("display(Markdown('### Levene test'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Equal Variance test (Levene)']))");
+ break;
+ case 'fligner':
+ // 1. Fligner test
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Fligner test");
+ code.appendLine("_lst = []");
+ code.appendLine("_df.apply(lambda x: _lst.append(x.dropna()))");
+ code.appendFormatLine("_res = stats.fligner(*_lst, center='{0}')", center);
+ code.appendLine("display(Markdown('### Fligner test'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Equal Variance test (Fligner)']))");
+ break;
+ }
+
+ // Display option
+ if (histogram === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Histogram");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" sns.histplot(_df, stat='density', kde=True)");
+ code.appendLine(" plt.title('Histogram')");
+ code.append(" plt.show()");
+ }
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return EqualVarTest;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/FactorAnalysis.js b/visualpython/js/m_stats/FactorAnalysis.js
new file mode 100644
index 00000000..188efe19
--- /dev/null
+++ b/visualpython/js/m_stats/FactorAnalysis.js
@@ -0,0 +1,301 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : FactorAnalysis.js
+ * Author : Black Logic
+ * Note : Factor Analysis
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 24
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] FactorAnalysis
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/factorAnalysis.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, com_util, com_Const, com_String, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * FactorAnalysis
+ */
+ class FactorAnalysis extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.installButton = true;
+ this.config.docs = 'https://factor-analyzer.readthedocs.io/en/latest/factor_analyzer.html';
+
+ this.state = {
+ data: '',
+ variable: [],
+ rotation: "'varimax'",
+ method: 'principal',
+ impute: 'drop',
+ extract: 'eigenvalue',
+ eigenvalue: 1,
+ factor: '',
+ corrMatrix: true,
+ screePlot: true,
+ ...this.state
+ };
+
+ this.rotationList = [
+ { label: "None", value: "None" },
+ { label: "varimax", value: "'varimax'" },
+ { label: "promax", value: "'promax'" },
+ { label: "oblimin", value: "'oblimin'" },
+ { label: "oblimax", value: "'oblimax'" },
+ { label: "quartimin", value: "'quartimin'" },
+ { label: "quartimax", value: "'quartimax'" },
+ { label: "equamax", value: "'equamax'" },
+ ];
+ this.methodList = [
+ { label: "minres", value: "minres" },
+ { label: "ml", value: "ml" },
+ { label: "principal", value: "principal" },
+ ];
+ this.imputeList = [
+ { label: "drop", value: "drop" },
+ { label: "mean", value: "mean" },
+ { label: "median", value: "median" },
+ ]
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ this.state.variable = [];
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ // generate rotation options
+ this.rotationList.forEach(obj => {
+ let selected = obj.value === that.state.rotation;
+ $(page).find('#rotation').append(`${obj.label} `);
+ });
+
+ // generate method options
+ this.methodList.forEach(obj => {
+ let selected = obj.value === that.state.method;
+ $(page).find('#method').append(`${obj.label} `);
+ });
+
+ // generate impute options
+ this.imputeList.forEach(obj => {
+ let selected = obj.value === that.state.impute;
+ $(page).find('#impute').append(`${obj.label} `);
+ });
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: this.state.data, selectedList: this.state.variable.map(x=>x.code), showDescription: false }
+ );
+ }
+
+ generateInstallCode() {
+ let installCode = '!pip install factor-analyzer';
+ // Add installation code
+ if (vpConfig.extensionType === 'lite') {
+ installCode = '%pip install factor-analyzer';
+ }
+ return [ installCode ];
+ }
+
+ generateCode() {
+ let { data, variable, rotation, method, impute, extract, eigenvalue, factor, corrMatrix, screePlot } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ // data declaration
+ code.appendFormat("vp_df = {0}", data);
+ if (this.columnSelector) {
+ let columns = this.columnSelector.getDataList();
+ this.state.variable = columns;
+ if (columns.length > 0) {
+ code.appendFormat("[[{0}]]", columns.map(x => x.code).join(', '));
+ }
+ }
+ code.appendLine('.dropna().copy()');
+
+ // KMO(Kaiser-Meyer-Olkin) measure of sampling adequacy
+ code.appendLine();
+ code.appendLine("# KMO(Kaiser-Meyer-Olkin) measure of sampling adequacy");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from factor_analyzer.factor_analyzer import calculate_kmo");
+ code.appendLine("_kmo = calculate_kmo(vp_df)");
+ code.appendLine("display(Markdown('### KMO measure of sampling adequacy'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic ':_kmo[1]}, index=['KMO measure of sampling adequacy']))");
+
+ // Bartlett's test of sphericity
+ code.appendLine();
+ code.appendLine("# Bartlett's test of sphericity");
+ code.appendLine("from factor_analyzer.factor_analyzer import calculate_bartlett_sphericity");
+ code.appendLine("_bartlett = calculate_bartlett_sphericity(vp_df)");
+ code.appendLine("display(Markdown('### Bartlett\\'s test of sphericity'))");
+ code.appendLine("display(pd.DataFrame(data={'Chi-square statistic':_bartlett[0],'p-value':_bartlett[1]}, index=['Bartlett test of sphericity']))");
+
+ // Initial of Factor Analysis
+ code.appendLine();
+ code.appendLine("# Initial");
+ code.appendLine("from factor_analyzer import FactorAnalyzer");
+ code.appendFormatLine("_fa1 = FactorAnalyzer(n_factors=vp_df.shape[1], rotation=None, method='{0}', impute='{1}')", method, impute);
+ code.appendLine("_fa1.fit(vp_df)");
+
+ // Number of Factor
+ code.appendLine();
+ code.appendLine("# Number of Factor");
+ if (extract === 'eigenvalue') {
+ code.appendFormatLine("_nof = (_fa1.get_eigenvalues()[0] > {0}).sum()", eigenvalue);
+ } else if (extract === 'factor') {
+ code.appendFormatLine("_nof = {0}", factor);
+ }
+
+ // Unrotated
+ code.appendLine();
+ code.appendLine("# Un-rotated");
+ code.appendFormatLine("_fa2 = FactorAnalyzer(n_factors=_nof, rotation=None, method='{0}', impute='{1}')", method, impute);
+ code.appendLine("_fa2.fit(vp_df)");
+
+ // Rotated
+ code.appendLine();
+ code.appendLine("# Rotated");
+ code.appendFormatLine("_fa3 = FactorAnalyzer(n_factors=_nof, rotation={0}, method='{1}', impute='{2}')", rotation, method, impute);
+ code.append("_fa3.fit(vp_df)");
+
+ // Display option : Correlation Matrix
+ if (corrMatrix === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Correlation matrix");
+ code.appendLine("display(Markdown('### Correlation matrix'))");
+ code.append("display(pd.DataFrame(data= _fa1.corr_ , index=vp_df.columns, columns=vp_df.columns).round(2))");
+ }
+
+ // Display option : Scree plot
+ if (screePlot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Scree plot");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" plt.plot(_fa1.get_factor_variance()[1], 'o-')");
+ code.appendLine(" plt.title('Scree Plot')");
+ code.appendLine(" plt.xlabel('Factors')");
+ code.appendLine(" plt.ylabel('Eigenvalue')");
+ code.append(" plt.show()");
+ }
+
+ // Communalities
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Communalities");
+ code.appendLine("display(Markdown('### Communalities'))");
+ code.appendLine("display(pd.DataFrame(data={'Initial':_fa1.get_communalities(),'Extraction':_fa2.get_communalities()},index=vp_df.columns).round(3))");
+
+ // Total variance explained
+ code.appendLine();
+ code.appendLine("# Total variance explained");
+ code.appendLine("# Initial Eigenvalues");
+ code.appendLine("_ss1 = pd.DataFrame(data=_fa1.get_factor_variance(),");
+ code.appendLine(" index=[['Initial Eigenvalues' for i in range(3)],['Total','% of variance','Cumulative %']]).T");
+ code.appendLine("# Extraction sums of squared loadings");
+ code.appendLine("_ss2 = pd.DataFrame(data=_fa1.get_factor_variance(),");
+ code.appendLine(" index=[['Extraction sums of squared loadings' for i in range(3)],['Total','% of variance','Cumulative %']]).T[:3]");
+ code.appendLine("# Rotation sums of squared loadings");
+ code.appendLine("_ss3 = pd.DataFrame(data=_fa3.get_factor_variance(),");
+ code.appendLine(" index=[['Rotation sums of squared loadings' for i in range(3)],['Total','% of variance','Cumulative %']]).T");
+ code.appendLine(" ");
+ code.appendLine("display(Markdown('### Total variance explained'))");
+ code.appendLine("display(pd.concat([_ss1,_ss2,_ss3], axis=1).round(3))");
+
+ // Factor Matrix
+ code.appendLine();
+ code.appendLine("# Factor matrix");
+ code.appendLine("display(Markdown('### Factor matrix'))");
+ code.appendLine("display(pd.DataFrame(data=_fa2.loadings_,index=vp_df.columns,");
+ code.appendLine(" columns=list(range(_nof))).round(3))");
+
+ // Rotated Factor Matrix
+ code.appendLine();
+ code.appendLine("# Rotated factor matrix");
+ code.appendLine("display(Markdown('### Rotated factor matrix'))");
+ code.appendLine("display(pd.DataFrame(data=_fa3.loadings_,index=vp_df.columns,");
+ code.append(" columns=list(range(_nof))).round(3))");
+
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return FactorAnalysis;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/LogisticRegression.js b/visualpython/js/m_stats/LogisticRegression.js
new file mode 100644
index 00000000..318f63f6
--- /dev/null
+++ b/visualpython/js/m_stats/LogisticRegression.js
@@ -0,0 +1,193 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : LogisticRegression.js
+ * Author : Black Logic
+ * Note : Correlation Analysis
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 06. 02
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] LogisticRegression
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/logisticRegression.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * LogisticRegression
+ */
+ class LogisticRegression extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://www.statsmodels.org/stable/api.html';
+
+ this.state = {
+ data: '',
+ dependent: '',
+ encoding: true,
+ independent: [],
+ showOdds: true,
+ multiCollinearity: true,
+ ...this.state
+ };
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('#dependent'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // data change
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+
+ // dependent change
+ $(document).on('change', this.wrapSelector('#dependent'), function() {
+ let depVal = $(this).val();
+ that.columnSelector = new MultiSelector(that.wrapSelector('#independent'),
+ {
+ mode: 'columns', parent: that.state.data, showDescription: false,
+ excludeList: [ depVal ]
+ }
+ );
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ this.state.dependent = '';
+ this.state.independent = [];
+ // render column
+ com_generator.vp_bindColumnSource(this, 'data', ['dependent'], 'select', false, false);
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#independent'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ // bind column if data exist
+ if (this.state.data !== '') {
+ com_generator.vp_bindColumnSource(this, 'data', ['dependent'], 'select', false, false);
+ }
+
+ let excludeList = [];
+ if (this.state.dependent !== '') {
+ excludeList = [ this.state.dependent ];
+ }
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#independent'),
+ { mode: 'columns', parent: this.state.data, selectedList: this.state.independent, excludeList: excludeList, showDescription: false });
+ }
+
+ generateCode() {
+ let { data, dependent, encoding, independent, showOdds, multiCollinearity } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ let dependentValue = $(this.wrapSelector('#dependent option:selected')).text();
+ let independentMulti = this.columnSelector.getDataList();
+ this.state.independent = independentMulti;
+
+ // data declaration
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+ if (encoding === true) {
+ code.appendFormatLine("vp_df['{0}'+'_EL'] = pd.Categorical(vp_df[{1}]).codes", dependentValue, dependent);
+ dependentValue = dependentValue + '_EL';
+ }
+ code.appendLine();
+ code.appendLine("# Logistic regression");
+ code.appendLine("from IPython.display import display");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.logit('{0} ~ {1}', vp_df)", dependentValue, independentMulti.map(x=>x.name).join(' + '));
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("print(_result.summary())");
+ code.appendLine("");
+ code.appendLine("# Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ if (showOdds === true) {
+ code.appendLine("_dfr['Odds'] = np.exp(_result.params)");
+ code.appendLine("_dfr['Lower(Odds)'] = np.exp(_result.conf_int()[0])");
+ code.appendLine("_dfr['Upper(Odds)'] = np.exp(_result.conf_int()[1])");
+ }
+ if (multiCollinearity === true) {
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ }
+ code.append("display(_dfr)");
+
+ return code.toString();
+ }
+
+ }
+
+ return LogisticRegression;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/NormTest.js b/visualpython/js/m_stats/NormTest.js
new file mode 100644
index 00000000..0669f6cf
--- /dev/null
+++ b/visualpython/js/m_stats/NormTest.js
@@ -0,0 +1,248 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : NormTest.js
+ * Author : Black Logic
+ * Note : Normality test
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] NormTest
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/normTest.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(nmHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, Subset) {
+
+ /**
+ * NormTest
+ */
+ class NormTest extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ testType: 'shapiro-wilk',
+ data0: '',
+ alterHypo: 'two-sided',
+ histogram: false,
+ boxplot: false,
+ qqplot: true,
+ ...this.state
+ };
+
+ this.subsetEditor = {};
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#testType')).on('change', function() {
+ let testType = $(this).val();
+ that.state.testType = testType;
+
+ $(that.wrapSelector('.vp-st-option')).hide();
+ $(that.wrapSelector('.vp-st-option.' + testType)).show();
+ });
+
+ $(this.wrapSelector('#data0')).on('change', function() {
+ if (that.state.data0type === 'DataFrame') {
+ // DataFrame
+ that.state.var0 = '';
+ $(that.wrapSelector('#var0')).prop('disabled', false);
+ com_generator.vp_bindColumnSource(that, 'data0', ['var0'], 'select', false, false);
+ } else {
+ // Series
+ that.state.var0 = '';
+ $(that.wrapSelector('#var0')).html('');
+ $(that.wrapSelector('#var0')).prop('disabled', true);
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(nmHTML);
+ let that = this;
+
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data0', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame', 'Series'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data0 = data;
+ that.state.data0type = type;
+ that.state.var0 = '';
+ $(that.wrapSelector('#data0')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data0 = data;
+ that.state.data0type = type;
+ that.state.var0 = '';
+ $(that.wrapSelector('#data0')).trigger('change');
+ }
+ });
+ $(page).find('#data0').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor['data0'] = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data0'),
+ pageThis: this,
+ finish: function(code, state) {
+ that.state.data0 = code;
+ $(that.wrapSelector('#data0')).val(code);
+ that.state.data0type = state.returnType;
+ $(that.wrapSelector('#data0')).trigger('change');
+ }
+ });
+
+ // control display option
+ $(this.wrapSelector('.vp-st-option')).hide();
+ $(this.wrapSelector('.vp-st-option.' + this.state.testType)).show();
+ }
+
+ generateCode() {
+ let { testType, data0, data0type, var0, alterHypo, histogram, boxplot, qqplot } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ // test type label
+ let testTypeLabel = $(this.wrapSelector('#testType option:selected')).text();
+ code.appendFormatLine('# {0}', testTypeLabel);
+
+ // variable declaration
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data0);
+
+ let dataVar = 'vp_df';
+ if (var0 !== '') {
+ dataVar += com_util.formatString("[{0}]", var0);
+ }
+
+ switch (testType) {
+ case 'shapiro-wilk':
+ // 1. Shapiro-wilk test
+ code.appendLine();
+ code.appendLine("# Normality test (Shapiro-Wilk)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.shapiro({0})", dataVar);
+ code.appendLine("display(Markdown('### Normality test (Shapiro-Wilk)'))");
+ code.append("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},index=['Normality test (Shapiro-Wilk)']))");
+ break;
+ case 'anderson-darling':
+ // 1. Anderson-Darling test
+ code.appendLine();
+ code.appendLine("# Normality test (Anderson-Darling)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.anderson({0})", dataVar);
+ code.appendLine("display(Markdown('### Normality test (Anderson-Darling)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':[_res.statistic],'Critical values':[_res.critical_values],");
+ code.appendLine(" 'Significance level(%)':[_res.significance_level]},");
+ code.append(" index=['Normality test (Anderson-Darling)']))");
+ break;
+ case 'kolmogorov-smirnov':
+ // 1. Kolmogorov-Smirnov test
+ code.appendLine();
+ code.appendLine("# Normality test (Kolmogorov-Smirnov)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.kstest({0}, 'norm', alternative='{1}')", dataVar, alterHypo);
+ code.appendLine("display(Markdown('### Normality test (Kolmogorov-Smirnov)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Normality test (Kolmogorov-Smirnov)']))");
+ break;
+ case 'dagostino-pearson':
+ // 1. D Agostino and Pearson test
+ code.appendLine();
+ code.appendLine("# Normality test (D Agostino and Pearson)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.normaltest({0})", dataVar);
+ code.appendLine("display(Markdown('### Normality test (D Agostino and Pearson)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Normality test (D Agostino and Pearson)']))");
+ break;
+ case 'jarque-bera':
+ // 1. Jarque-Bera test
+ code.appendLine();
+ code.appendLine("# Normality test (Jarque-Bera)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.jarque_bera({0})", dataVar);
+ code.appendLine("display(Markdown('### Normality test (Jarque-Bera)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.append(" index=['Normality test (Jarque-Bera)']))");
+ break;
+ }
+
+ // Display option
+ if (histogram === true || boxplot === true || qqplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Charts");
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.append(" warnings.simplefilter(action='ignore', category=Warning)");
+ let displayNum = 1;
+ if (histogram === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine(" plt.subplot(2,2,{0})", displayNum++);
+ code.appendFormatLine(" sns.histplot({0}, stat='density', kde=True)", dataVar);
+ code.append(" plt.title('Histogram')");
+ }
+ if (boxplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine(" plt.subplot(2,2,{0})", displayNum++);
+ code.appendFormatLine(" sns.boxplot(y={0})", dataVar);
+ code.append(" plt.title('Boxplot')");
+ }
+
+ if (qqplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine(" plt.subplot(2,2,{0})", displayNum);
+ code.appendFormatLine(" stats.probplot({0}, plot=plt)", dataVar);
+ code.append(" plt.title('Q-Q Plot')");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" plt.tight_layout()");
+ code.append(" plt.show()");
+ }
+
+ return code.toString();
+ }
+
+ }
+
+ return NormTest;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/ProbDist.js b/visualpython/js/m_stats/ProbDist.js
new file mode 100644
index 00000000..245cd9f6
--- /dev/null
+++ b/visualpython/js/m_stats/ProbDist.js
@@ -0,0 +1,440 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : ProbDist.js
+ * Author : Black Logic
+ * Note : Probability Distribution
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] ProbDist
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/probDist.html'),
+ __VP_CSS_LOADER__('vp_base/css/m_stats/probDist'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/data/m_stats/statsLibrary',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector'
+], function(pdHTML, pdCss, com_util, com_Const, com_String, com_generator, STATS_LIBRARIES, PopupComponent, DataSelector) {
+
+ /**
+ * ProbDist
+ */
+ class ProbDist extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd', 'plt'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+ this.config.helpview = true;
+
+ this.state = {
+ distType: 'normal',
+ userOption: '',
+ action: 'random-number',
+ // random-number
+ size: 10000,
+ randomState: '',
+ allocateTo: 'samples',
+ sampledDist: true,
+ // distribution-plot
+ probDensityFunc: true,
+ probMassFunc: true,
+ cumDistFunc: true,
+ // stats-to-pvalue
+ stats: '',
+ pAlter: 'two-sided',
+ // pvalue-to-stats
+ pvalue: '',
+ statsAlter: 'two-sided',
+ ...this.state
+ };
+
+ this.distList = [
+ {
+ label: 'Discrete probability distribution',
+ child: ['bernoulli', 'binomial', 'multinomial']
+ },
+ {
+ label: 'Continuous probability distribution',
+ child: ['uniform','normal','beta','gamma','studentst','chi2','f','dirichlet','multivariate_normal']
+ }
+ ];
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#distType')).on('change', function() {
+ let distType = $(this).val();
+ that.state.distType = distType;
+ $(that.wrapSelector('.vp-pd-dist-option-box')).html(that.templateForOption(distType));
+
+ $(that.wrapSelector('.vp-pd-display-option')).hide();
+ // show/hide display option
+ if (that.distList[0].child.includes(distType)) {
+ // discrete option
+ $(that.wrapSelector('.vp-pd-display-option.dist')).show();
+
+ // set size to 1000
+ $(that.wrapSelector('#size')).val(1000);
+ that.state.size = 1000;
+
+ // hide distribution plot for multinomial
+ if (distType === 'multinomial') {
+ $(that.wrapSelector('.vp-pd-display-option.dist-plot')).hide();
+ // hide other actions
+ if (that.state.action !== 'random-number') {
+ $(that.wrapSelector('#action')).val('random-number');
+ $(that.wrapSelector('#action')).trigger('change');
+ }
+ } else {
+ // hide continuous action
+ if (that.state.action === 'stats-to-pvalue' || that.state.action === 'pvalue-to-stats') {
+ $(that.wrapSelector('#action')).val('random-number');
+ $(that.wrapSelector('#action')).trigger('change');
+ }
+ }
+ } else {
+ // continuous option
+ $(that.wrapSelector('.vp-pd-display-option.cont')).show();
+
+ // set size to 10000
+ $(that.wrapSelector('#size')).val(10000);
+ that.state.size = 10000;
+ }
+
+ // show install button
+ let thisDistObj = STATS_LIBRARIES[distType];
+ if (thisDistObj.install != undefined) {
+ $(that.wrapSelector('#vp_installLibrary')).show();
+ } else {
+ $(that.wrapSelector('#vp_installLibrary')).hide();
+ }
+
+ // set help content
+ that.setHelpContent(thisDistObj.help);
+ });
+
+ $(this.wrapSelector('#action')).on('change', function() {
+ let action = $(this).val();
+ that.state.action = action;
+
+ $(that.wrapSelector('.vp-pd-action-box')).hide();
+ $(that.wrapSelector('.vp-pd-action-box.' + action)).show();
+
+ $(that.wrapSelector('.vp-pd-display-option')).hide();
+ // show/hide display option
+ if (that.distList[0].child.includes(that.state.distType)) {
+ // discrete option
+ $(that.wrapSelector('.vp-pd-display-option.dist')).show();
+ } else {
+ // continuous option
+ $(that.wrapSelector('.vp-pd-display-option.cont')).show();
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(pdHTML);
+ let that = this;
+
+ //================================================================
+ // Distribution type creation
+ //================================================================
+ // dist types
+ let distTypeTag = new com_String();
+ this.distList.forEach(distObj => {
+ let { label, child } = distObj;
+ let distOptionTag = new com_String();
+ child && child.forEach(opt => {
+ let optConfig = STATS_LIBRARIES[opt];
+ let selectedFlag = '';
+ if (opt == that.state.distType) {
+ selectedFlag = 'selected';
+ }
+ distOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, optConfig.name);
+ })
+ distTypeTag.appendFormatLine('{1} ',
+ label, distOptionTag.toString());
+ });
+ $(page).find('#distType').html(distTypeTag.toString());
+
+ // render option page
+ $(page).find('.vp-pd-dist-option-box').html(this.templateForOption(this.state.distType));
+
+ // control display option
+ $(this.wrapSelector('.vp-pd-display-option')).hide();
+ // show/hide display option
+ if (this.distList[0].child.includes(this.state.distType)) {
+ // discrete option
+ $(this.wrapSelector('.vp-pd-display-option.dist')).show();
+ } else {
+ // continuous option
+ $(this.wrapSelector('.vp-pd-display-option.cont')).show();
+ }
+
+ return page;
+ }
+
+ templateForOption(distType) {
+ let config = STATS_LIBRARIES[distType];
+ let state = this.state;
+
+ let optBox = new com_String();
+ // render tag
+ config.options.forEach(opt => {
+ optBox.appendFormatLine('{3} '
+ , opt.name, (opt.required===true?'vp-orange-text':''), opt.name, com_util.optionToLabel(opt.name));
+ let content = com_generator.renderContent(this, opt.component[0], opt, state);
+ optBox.appendLine(content[0].outerHTML);
+ });
+ // render user option
+ optBox.appendFormatLine('{1} ', 'userOption', 'User option');
+ optBox.appendFormatLine(' ',
+ 'userOption', 'key=value, ...', this.state.userOption);
+ return optBox.toString();
+ }
+
+ render() {
+ super.render();
+
+ let allocateSelector = new DataSelector({
+ type: 'data',
+ pageThis: this,
+ id: 'allocatedTo',
+ classes: 'vp-input vp-state',
+ placeholder: '_res',
+ finish: function() {
+ ;
+ }
+ });
+ $(this.wrapSelector('#allocatedTo')).replaceWith(allocateSelector.toTagString());
+
+ this.setHelpContent(STATS_LIBRARIES[this.state.distType].help, true, 'import scipy.stats as _vp_stats');
+ }
+
+ generateCode() {
+ this.config.checkModules = ['pd'];
+ let {
+ distType, userOption, action,
+ size, randomState, allocateTo, sampledDist,
+ probDensityFunc, probMassFunc, cumDistFunc,
+ stats, pAlter,
+ pvalue, statsAlter
+ } = this.state;
+
+ let codeList = [];
+ let code = new com_String();
+ /**
+ * Model Creation
+ */
+ let config = STATS_LIBRARIES[distType];
+ let label = config.name;
+ code.appendLine(config.import);
+ code.appendLine();
+
+ // model code
+ let modelCode = config.code;
+ modelCode = com_generator.vp_codeGenerator(this, config, this.state, (userOption != ''? ', ' + userOption : ''));
+ code.append(modelCode);
+
+ switch (action) {
+ case 'random-number':
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Generate random numbers ({0})", label);
+ code.appendLine("from IPython.display import display");
+ code.appendFormat('{0} = _rv.rvs(size={1}', allocateTo, size);
+ if (randomState !== '') {
+ code.appendFormat(", random_state={0}", randomState);
+ }
+ code.appendLine(')');
+ code.appendFormat("display({0})", allocateTo);
+
+ if (sampledDist === true) {
+ this.addCheckModules('plt');
+ this.addCheckModules('sns');
+
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Sample distribution ({0})", label);
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ if (distType === 'multinomial') {
+ // code.appendFormatLine(" plt.boxplot(x={0})", allocateTo);
+ code.appendFormatLine(" for i in range(0, {0}.shape[1]):", allocateTo);
+ code.appendLine(" plt.subplot(2, 2, i+1)");
+ code.appendLine(" plt.title('$x$=' + str(i))");
+ code.appendFormatLine(" sns.countplot(x=[ x[i] for x in {0} ])", allocateTo);
+ code.appendLine(" plt.suptitle('Generate random numbers: Multinomial')");
+ code.appendLine(" plt.tight_layout()");
+ code.appendLine(" plt.show()");
+ } else {
+ if (this.distList[0].child.includes(distType)) {
+ code.appendFormatLine(" sns.countplot(x={0})", allocateTo);
+ } else {
+ code.appendFormatLine(" sns.histplot({0}, stat='density', kde=True)", allocateTo);
+ }
+ code.appendFormatLine(" plt.title('Generate random numbers: {0}')", label.replace("'", "\\'"));
+ code.appendLine(" plt.xlabel('$x$')");
+ code.append(" plt.show()");
+ }
+ }
+ break;
+ case 'distribution-plot':
+ if (this.distList[0].child.includes(distType)) {
+ if (probMassFunc === true) {
+ this.addCheckModules('np');
+ this.addCheckModules('plt');
+
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Probability mass function ({0})", label);
+ if (distType === 'bernoulli') {
+ code.appendLine("plt.bar([0,1], _rv.pmf([0,1]))");
+ code.appendFormatLine("plt.title('Probability mass function: {0}')", label.replace("'", "\\'"));
+ code.appendLine("plt.xlim(-1, 2)");
+ code.appendLine("plt.ylim(0, 1)");
+ code.appendLine("plt.xticks([0, 1], ['x=0', 'x=1'])");
+ code.appendLine("plt.xlabel('$x$')");
+ code.appendLine("plt.ylabel('$p(x)$')");
+ code.append("plt.show()");
+ } else if (distType === 'binomial') {
+ var { n=10 } = this.state;
+ code.appendFormatLine("plt.bar(range(0,{0}), _rv.pmf(range(0,{1})))", n, n);
+ code.appendFormatLine("plt.title('Probability mass function: {0}')", label.replace("'", "\\'"));
+ code.appendFormatLine("plt.xlim(-1, {0})", n);
+ code.appendFormatLine("plt.xticks(range(0, {0}), ['x='+str(i) for i in range(0, {1})])", n, n);
+ code.appendLine("plt.xlabel('$x$')");
+ code.appendLine("plt.ylabel('$p(x)$')");
+ code.append("plt.show()");
+ } else if (distType === 'multinomial') {
+ code.appendFormatLine("for i in range(0, {0}.shape[1]):", allocateTo);
+ code.appendLine(" plt.subplot(2, 2, i+1)");
+ code.appendLine(" plt.title('$x$=' + str(i))");
+ code.appendFormatLine(" sns.countplot(x=[ x[i] for x in {0} ])", allocateTo);
+ code.appendLine("plt.suptitle('Probability mass function: Multinomial')");
+ code.appendLine("plt.tight_layout()");
+ code.append("plt.show()");
+ }
+ }
+ } else {
+ let start = -5;
+ let end = 5;
+ switch (distType) {
+ case 'normal':
+ case 'studentst':
+ case 'multivariate_normal':
+ start = -5;
+ end = 5;
+ break;
+ case 'uniform':
+ case 'beta':
+ case 'dirichlet':
+ start = 0;
+ end = 1;
+ break;
+ case 'gamma':
+ case 'chi2':
+ start = 0;
+ end = 30;
+ break;
+ case 'f':
+ start = 0;
+ end = 10;
+ break;
+ }
+
+ if (probDensityFunc === true || cumDistFunc === true) {
+ code.appendLine();
+ code.appendFormat("x = np.linspace({0}, {1}, 100)", start, end);
+ if (probDensityFunc === true) {
+ this.addCheckModules('np');
+ this.addCheckModules('plt');
+
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Probability density function ({0})", label);
+ code.appendLine("plt.plot(x, _rv.pdf(x))");
+ code.appendFormatLine("plt.title('Probability density function: {0}')", label.replace("'", "\\'"));
+ code.appendLine("plt.xlabel('$x$')");
+ code.appendLine("plt.ylabel('$p(x)$')");
+ code.append("plt.show()");
+ }
+ if (cumDistFunc === true) {
+ this.addCheckModules('np');
+ this.addCheckModules('plt');
+
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Cumulative distribution function ({0})", label);
+ code.appendLine("import warnings");
+ code.appendLine("with warnings.catch_warnings():");
+ code.appendFormatLine(" _x = np.linspace({0}, {1}, 100)", start, end);
+ code.appendLine(" plt.plot(_x, _rv.cdf(_x))");
+ code.appendLine();
+ code.appendFormatLine(" plt.title('Cumulative distribution function: {0}')", label.replace("'", "\\'"));
+ code.appendLine(" plt.xlabel('$x$')");
+ code.appendLine(" plt.ylabel('$F(x)$')");
+ code.append(" plt.show()");
+ }
+ }
+ }
+ break;
+ case 'stats-to-pvalue':
+ if (pAlter === 'one-sided') {
+ // one-sided
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Proportional values");
+ code.appendFormatLine("p_value = _rv.sf(abs({0}))", stats);
+ code.append("p_value");
+ } else {
+ // two-sided
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Proportional values");
+ code.appendFormatLine("p_value = _rv.sf(abs({0}))*2", stats);
+ code.append("p_value");
+ }
+ break;
+ case 'pvalue-to-stats':
+ if (statsAlter === 'one-sided') {
+ // one-sided
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Statistic");
+ code.appendFormatLine("statistic = _rv.isf({0})", pvalue);
+ code.append("statistic");
+ } else {
+ // two-sided
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Statistic");
+ code.appendFormatLine("statistic = _rv.isf({0}/2)", pvalue);
+ code.append("statistic");
+ }
+ break;
+ }
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return ProbDist;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/Regression.js b/visualpython/js/m_stats/Regression.js
new file mode 100644
index 00000000..a38c811b
--- /dev/null
+++ b/visualpython/js/m_stats/Regression.js
@@ -0,0 +1,789 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Regression.js
+ * Author : Black Logic
+ * Note : Equal Variance test
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] EqualVarTest
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/regression.html'),
+ __VP_CSS_LOADER__('vp_base/css/m_stats/regression'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, rgCss, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * Regression
+ */
+ class Regression extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://www.statsmodels.org/stable/api.html';
+
+ this.state = {
+ testType: 'simple',
+ // Data selection
+ data: '',
+ dataType: '',
+ dependent: '',
+ independent: '',
+ independentMulti: [],
+ moderated: '',
+ mediated: '',
+ // options
+ categorical: [],
+ method: 'enter',
+ meanCentering: true,
+ sobelTest: true,
+ // Multi-collinearity
+ multiCollinearity: true,
+ // Residual option
+ statistics: false,
+ normTest: true,
+ histogram: true,
+ scatterplot: true,
+ rmse: false,
+ ...this.state
+ };
+
+ this.colBindList = ['dependent', 'independent', 'moderated', 'mediated'];
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ $(document).off('change', this.wrapSelector('#dependent'));
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // change test type
+ $(this.wrapSelector('#testType')).on('change', function() {
+ let testType = $(this).val();
+ that.state.testType = testType;
+
+ $(that.wrapSelector('.vp-st-option')).hide();
+ $(that.wrapSelector('.vp-st-option.' + testType)).show();
+
+ let excludeList = [];
+ if (that.state.testType === 'multiple'
+ || that.state.testType === 'hierarchical'
+ || that.state.testType === 'dummy') {
+ let depVal = $(that.wrapSelector('#dependent')).val();
+ excludeList = [ depVal ];
+ }
+
+ // render variable selector
+ that.columnSelector = new MultiSelector(that.wrapSelector('#independentBox'),
+ {
+ mode: 'columns', parent: that.state.data, showDescription: false,
+ excludeList: excludeList,
+ change: function(type, list) {
+ that._handleMultiColumnChange(type, list);
+ }
+ });
+ });
+
+ // data change
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+
+ // dependent change
+ $(document).on('change', this.wrapSelector('#dependent'), function() {
+ let depVal = $(this).val();
+ if (that.state.testType === 'multiple'
+ || that.state.testType === 'hierarchical'
+ || that.state.testType === 'dummy') {
+ that.columnSelector = new MultiSelector(that.wrapSelector('#independentBox'),
+ {
+ mode: 'columns', parent: that.state.data, showDescription: false,
+ excludeList: [ depVal ],
+ change: function(type, list) {
+ that._handleMultiColumnChange(type, list);
+ }
+ }
+ );
+ }
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ this.state.independentMulti = [];
+ let that = this;
+ // bind column sources
+ if (this.state.dataType === 'DataFrame') {
+ // DataFrame
+ this.colBindList && this.colBindList.forEach(id => {
+ that.state[id] = '';
+ $(that.wrapSelector('#' + id)).prop('disabled', false);
+ });
+ com_generator.vp_bindColumnSource(this, 'data', this.colBindList, 'select', false, false);
+ } else {
+ // Others
+ this.colBindList && this.colBindList.forEach(id => {
+ that.state[id] = '';
+ $(that.wrapSelector('#' + id)).html('');
+ $(that.wrapSelector('#' + id)).prop('disabled', true);
+ });
+ }
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#independentBox'),
+ {
+ mode: 'columns', parent: data, showDescription: false,
+ change: function(type, list) {
+ that._handleMultiColumnChange(type, list);
+ }
+ }
+ );
+ }
+
+ _handleMultiColumnChange(type, list) {
+ let $newCateBox = $('
');
+ let that = this;
+ list && list.forEach(item => {
+ let checkedStr = 'checked';
+ if ($(that.wrapSelector('.vp-categorical-box input[data-name="' + item.name + '"]')).length > 0) {
+ $(that.wrapSelector('.vp-categorical-box input[data-name="' + item.name + '"]')).prop('checked')?'checked':'';
+ }
+ $newCateBox.append(`
+ ${item.name}
+ `);
+ });
+ $(this.wrapSelector('.vp-categorical-box')).replaceWith($newCateBox);
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ // depend on test type
+ $(page).find('.vp-st-option').hide();
+ $(page).find('.vp-st-option.' + this.state.testType).show();
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: this.state.data,
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code, state) {
+ that.state.data = code;
+ $(that.wrapSelector('#data')).val(code);
+ that.state.dataType = state.returnType;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+
+ let excludeList = [];
+ if (this.state.testType === 'multiple'
+ || this.state.testType === 'hierarchical'
+ || this.state.testType === 'dummy') {
+ if (this.state.dependent !== '') {
+ excludeList = [ this.state.dependent ];
+ }
+ }
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#indenpendentBox'),
+ {
+ mode: 'columns', parent: this.state.data,
+ selectedList: this.state.independentMulti.map(x=>x.code), excludeList: excludeList, showDescription: false
+ }
+ );
+
+ // bind column if data exist
+ if (this.state.data !== '') {
+ com_generator.vp_bindColumnSource(this, 'data', this.colBindList, 'select', false, false);
+ }
+
+ // control display option
+ $(this.wrapSelector('.vp-st-option')).hide();
+ $(this.wrapSelector('.vp-st-option.' + this.state.testType)).show();
+ }
+
+ generateCode() {
+ let { testType,
+ // Data selection
+ data, dataType, dependent, independent, independentMulti, moderated, mediated,
+ // options
+ method, meanCentering, sobelTest,
+ // Multi-collinearity
+ multiCollinearity,
+ // Residual option
+ statistics, normTest, histogram, scatterplot, rmse,
+ } = this.state;
+ let codeList = [];
+ let code = new com_String();
+ let that = this;
+ let lastModelNum = 0;
+
+ // Commentary
+ let testTypeLabel = $(this.wrapSelector('#testType option:selected')).text();
+ let methodLabel = $(this.wrapSelector('#method option:selected')).text();
+ if (testType === 'multiple') {
+ code.appendFormatLine("# {0} > Method: {1}", testTypeLabel, methodLabel);
+ } else {
+ code.appendFormatLine("# {0}", testTypeLabel);
+ }
+
+ // data declaration
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+
+ // data and columns
+ let dependentValue = $(this.wrapSelector('#dependent option:selected')).text();
+ let independentValue = $(this.wrapSelector('#independent option:selected')).text();
+ let moderatedValue = $(this.wrapSelector('#moderated option:selected')).text();
+ let mediatedValue = $(this.wrapSelector('#mediated option:selected')).text();
+ independentMulti = this.columnSelector.getDataList();
+ this.state.independentMulti = independentMulti;
+
+ switch (testType) {
+ case 'simple':
+ // 1. Simple
+ code.appendLine();
+ code.appendLine("# Simple linear regression");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendLine("# Model - Dependent variable ~ Independent variable");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", dependentValue, independentValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ // Multi-collinearity statistics
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ break;
+ case 'multiple':
+ // 2. Multiple
+ code.appendLine();
+ if (method === 'enter') {
+ code.appendLine("# Model - Dependent variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", dependentValue, independentMulti.map(x => x.name).join(' + '));
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ } else if (method === 'stepwise') {
+ // Inner function : vp_stepwise_select
+ this.addCheckModules('sm');
+ this.addCheckModules('vp_stepwise_select');
+
+ code.appendFormatLine("_selected_stepwise = vp_stepwise_select(vp_df[[{0}]], vp_df[{1}])", independentMulti.map(x => x.code).join(','), dependent);
+ code.appendLine("");
+ code.appendLine("# Model 1 - Dependent variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[_selected_stepwise[0]]))", dependent);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 1 - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Dependent variable ~ Stepwised variable");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[_selected_stepwise]))", dependent);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 2 - Dependent variable ~ Stepwised variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ // set last model number
+ lastModelNum = 2;
+ } else if (method === 'backward') {
+ // Inner function : vp_backward_select
+ this.addCheckModules('sm');
+ this.addCheckModules('vp_backward_select');
+
+ code.appendFormatLine("_selected_backward = vp_backward_select(vp_df[[{0}]], vp_df[{1}])", independentMulti.map(x => x.code).join(','), dependent);
+ code.appendLine();
+ code.appendLine("# Model 1 - Dependent variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[[{1}]]))", dependent, independentMulti.map(x => x.code).join(','));
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 1 - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Dependent variable ~ Backward variable");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[_selected_backward]))", dependent);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 2 - Dependent variable ~ Backward variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ // set last model number
+ lastModelNum = 2;
+ } else if (method === 'forward') {
+ // Inner function : vp_forward_select
+ this.addCheckModules('sm');
+ this.addCheckModules('vp_forward_select');
+
+ code.appendFormatLine("_selected_forward = vp_forward_select(vp_df[[{0}]], vp_df[{1}])", independentMulti.map(x => x.code).join(','), dependent);
+ code.appendLine();
+ code.appendLine("# Model 1 - Dependent variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[_selected_forward[0]]))", dependent);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 1 - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Dependent variable ~ Forward variable");
+ code.appendLine("import statsmodels.api as sm");
+ code.appendFormatLine("_model = sm.OLS(vp_df[{0}], sm.add_constant(vp_df[_selected_forward]))", dependent);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 2 - Dependent variable ~ Forward variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ // set last model number
+ lastModelNum = 2;
+ }
+ break;
+ case 'hierarchical':
+ // 3. Hierarchical
+ for (let i = 0; i < independentMulti.length; i++) {
+ if (i === 0) {
+ code.appendLine();
+ } else {
+ code.appendLine();
+ code.appendLine();
+ }
+ code.appendFormatLine("# Model {0} - Hierarchical linear regression", (i + 1));
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", dependentValue, independentMulti.slice(0, i + 1).map(x => x.name).join(' + '));
+ code.appendLine("_result = _model.fit()");
+ code.appendFormatLine("display(Markdown('### Model {0} - Dependent variable ~ Independent variable'))", (i + 1));
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# Model {0} - Multi-collinearity statistics", (i + 1));
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ }
+ lastModelNum = independentMulti.length;
+ break;
+ case 'moderated':
+ // 4. Moderated
+ // Mean centering
+ if (meanCentering === true) {
+ code.appendLine();
+ code.appendLine("# Mean Centering ");
+ independentValue = com_util.formatString("{0}_MC", independentValue);
+ moderatedValue = com_util.formatString("{0}_MC", moderatedValue);
+ code.appendFormatLine("vp_df['{0}'] = vp_df[{1}] - vp_df[{2}].mean(numeric_only=True)", independentValue, independent, independent);
+ code.appendFormatLine("vp_df['{0}'] = vp_df[{1}] - vp_df[{2}].mean(numeric_only=True)", moderatedValue, moderated, moderated);
+ }
+ // Model 1 to 3
+ code.appendLine();
+ code.appendLine("# Model 1 - Dependent variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", dependentValue, independentValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 1 - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Dependent variable ~ Independent variable + Moderated variable");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1} + {2}', vp_df)", dependentValue, independentValue, moderatedValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 2 - Dependent variable ~ Independent variable + Moderated variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 3 - Dependent variable ~ Independent variable + Moderated variable +Independent:Moderated");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1} + {2} + {3}:{4}', vp_df)", dependentValue, independentValue, moderatedValue, independentValue, moderatedValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 3 - Dependent variable ~ Independent variable + Moderated variable +Independent:Moderated'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 3 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ // set last model number
+ lastModelNum = 3;
+ break;
+ case 'mediated':
+ // 5. Mediated
+ if (sobelTest === true) {
+ this.addCheckModules('stats');
+ this.addCheckModules('vp_sobel');
+ }
+ code.appendLine();
+ code.appendLine("# Model 1 - Mediated variable ~ Independent variable");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", mediatedValue, independentValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 1 - Mediated variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ if (sobelTest === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 1 - Sobel test");
+ code.appendFormatLine("_sobel_M1 = _result.params[{0}]", independent);
+ code.appendFormat("_sobel_M1se = _result.bse[{0}]", independent);
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Dependent variable ~ Independent variable");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)", dependentValue, independentValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 2 - Dependent variable ~ Independent variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 2 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 3 - Dependent variable ~ Independent variable + Mediated variable");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1} + {2}', vp_df)", dependentValue, independentValue, mediatedValue);
+ code.appendLine("_result = _model.fit()");
+ code.appendLine("display(Markdown('### Model 3 - Dependent variable ~ Independent variable + Mediated variable'))");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 3 - Multi-collinearity statistics");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ if (sobelTest === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Model 3 - Sobel test");
+ code.appendFormatLine("_sobel_M3 = _result.params[{0}]", mediated);
+ code.appendFormatLine("_sobel_M3se = _result.bse[{0}]", mediated);
+ code.appendLine();
+ code.appendLine("# Mediated linear regression: Sobel test");
+ code.appendLine("from scipy import stats");
+ code.appendLine("_res = vp_sobel(_sobel_M1, _sobel_M3, _sobel_M1se, _sobel_M3se)");
+ code.appendLine("display(Markdown('### Sobel test'))");
+ code.append("display(pd.DataFrame(data={'Sobel Z-score':_res[0],'p-value':_res[2]},index=['Sobel test']))");
+ }
+ // set last model number
+ lastModelNum = 3;
+ break;
+ case 'dummy':
+ // 6. Dummy variable
+ code.appendLine();
+ code.appendLine("# Dummy variable linear regression");
+ code.appendLine("import statsmodels.formula.api as smf");
+ code.appendFormatLine("_model = smf.ols('{0} ~ {1}', vp_df)"
+ , dependentValue, independentMulti.map(item => {
+ let checked = $(that.wrapSelector('.vp-categorical-box input[data-name="' + item.name + '"]')).prop('checked');
+ if (checked === true) {
+ return 'C(' + item.name + ')';
+ } else {
+ return item.name;
+ }
+ }).join(' + '));
+ code.appendLine("_result = _model.fit()");
+ code.append("print(_result.summary())");
+ if (multiCollinearity === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Multi-collinearity statistics");
+ code.appendLine("from IPython.display import display");
+ code.appendLine("from statsmodels.stats.outliers_influence import variance_inflation_factor");
+ code.appendLine("_dfr = pd.DataFrame(_result.summary().tables[1].data[1:],columns=_result.summary().tables[1].data[0]).set_index('')");
+ code.appendLine("for i, col in enumerate(_model.exog_names[1:]):");
+ code.appendLine(" _vif = variance_inflation_factor(_model.exog, i+1)");
+ code.appendLine(" _dfr.loc[col,'Tolerance'] = 1/_vif");
+ code.appendLine(" _dfr.loc[col,'VIF'] = _vif");
+ code.append("display(_dfr)");
+ }
+ break;
+ }
+
+ // Residual option
+ if (statistics === true || normTest === true || histogram === true || scatterplot === true || rmse === true) {
+ let residualTitle = 'Residual'
+ if (lastModelNum > 0) {
+ residualTitle += ' - Model ' + lastModelNum;
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendFormatLine("# {0}", residualTitle);
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendLine("import statsmodels.api as sm");
+ if (testType === 'multiple' && ['stepwise', 'backward', 'forward'].includes(method)) {
+ code.appendLine("_predict = _result.predict(sm.add_constant(vp_df[_model.exog_names[1:]]))");
+ } else {
+ code.appendLine("_predict = _result.predict(vp_df)");
+ }
+
+ code.appendLine("_residual = _result.resid");
+ code.appendLine("vp_residual = pd.DataFrame({'predict':_predict,'residual':_residual,");
+ code.appendLine(" 'predict_z':stats.zscore(_predict),'residual_z':stats.zscore(_residual)})");
+ code.appendFormatLine("display(Markdown('### {0}'))", residualTitle);
+ code.append("display(vp_residual)");
+
+ if (statistics === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Residual statistics");
+ code.appendLine("display(Markdown('### Residual statistics'))");
+ code.appendLine("display(pd.DataFrame(data={'Min':vp_residual.min(),'Max':vp_residual.max(),'Mean':vp_residual.mean(numeric_only=True),");
+ code.append(" 'Std. Deviation':vp_residual.std(numeric_only=True),'N':vp_residual.count()}))");
+ }
+ if (normTest === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# Resisual Normality test (Shapiro-Wilk)");
+ code.appendLine("_res = stats.shapiro(vp_residual['residual_z'])");
+ code.appendLine("display(Markdown('### Residual Normality test (Shapiro-Wilk)'))");
+ code.append("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},index=['Resisual Normality test (Shapiro-Wilk)']))");
+ }
+ if (histogram === true || scatterplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("import seaborn as sns");
+ code.appendLine("import warnings");
+ code.append("with warnings.catch_warnings():");
+ let displayNum = 1;
+ if (histogram === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Residual histogram");
+ code.appendFormatLine(" plt.subplot(2,2,{0})", displayNum++);
+ code.appendLine(" warnings.simplefilter(action='ignore', category=Warning)");
+ code.appendLine(" sns.histplot(data=vp_residual, x='residual_z', kde=True)");
+ code.appendLine(" plt.title(f'Dependent variable: {_model.endog_names}')");
+ code.append(" plt.xlabel('Regression Standardized residual')");
+ }
+ if (scatterplot === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" # Residual scatterplot");
+ code.appendFormatLine(" plt.subplot(2,2,{0})", displayNum++);
+ code.appendLine(" sns.scatterplot(data=vp_residual, x='predict_z', y='residual_z')");
+ code.appendLine(" plt.title(f'Dependent variable: {_model.endog_names}')");
+ code.appendLine(" plt.xlabel('Regression Standardized predicted value')");
+ code.append(" plt.ylabel('Regression Standardized residual')");
+ }
+ code.appendLine();
+ code.appendLine();
+ code.appendLine(" plt.tight_layout()");
+ code.append(" plt.show()");
+ }
+ if (rmse === true) {
+ code.appendLine();
+ code.appendLine();
+ code.appendLine("# RMSE (Root Mean Squared Error)");
+ code.appendLine("_rmse = np.sqrt(_result.mse_resid)");
+ code.appendLine("display(Markdown('### RMSE (Root Mean Squared Error)'))");
+ code.append("display(Markdown(f'RMSE: {_rmse}'))");
+ }
+ }
+
+ codeList.push(code.toString());
+ return codeList;
+ }
+
+ }
+
+ return Regression;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/ReliabAnalysis.js b/visualpython/js/m_stats/ReliabAnalysis.js
new file mode 100644
index 00000000..989931b0
--- /dev/null
+++ b/visualpython/js/m_stats/ReliabAnalysis.js
@@ -0,0 +1,158 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : ReliabAnalysis.js
+ * Author : Black Logic
+ * Note : Reliability Analysis
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 24
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] ReliabAnalysis
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/reliabAnalysis.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/MultiSelector',
+ 'vp_base/js/m_apps/Subset'
+], function(eqHTML, com_util, com_Const, com_String, PopupComponent, DataSelector, MultiSelector, Subset) {
+
+ /**
+ * ReliabAnalysis
+ */
+ class ReliabAnalysis extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd', 'np', 'vp_cronbach_alpha'];
+
+ this.state = {
+ data: '',
+ variable: [],
+ ...this.state
+ };
+
+ this.subsetEditor = null;
+ this.columnSelector = null;
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+ }
+
+ handleVariableChange(data) {
+ this.state.data = data;
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: data, showDescription: false }
+ );
+ }
+
+ templateForBody() {
+ let page = $(eqHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset', category: this.name } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code) {
+ $(that.wrapSelector('#data')).val(code);
+ that.handleVariableChange(code);
+ }
+ });
+
+ // render variable selector
+ this.columnSelector = new MultiSelector(this.wrapSelector('#variable'),
+ { mode: 'columns', parent: this.state.data, selectedList: this.state.variable.map(x=>x.code), showDescription: false }
+ );
+ }
+
+ generateCode() {
+ let { data, variable } = this.state;
+ let codeList = [];
+ let code = new com_String();
+ let that = this;
+
+ // data declaration
+ code.appendFormat("vp_df = {0}", data);
+ if (this.columnSelector) {
+ let columns = this.columnSelector.getDataList();
+ this.state.variable = columns;
+ if (columns.length > 0) {
+ code.appendFormat("[[{0}]]", columns.map(x => x.code).join(', '));
+ }
+ }
+ code.appendLine('.dropna().copy()');
+
+ // Inner function : vp_cronbach_alpha
+
+ // Cronbach alpha
+ code.appendLine("");
+ code.appendLine("# Cronbach alpha");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("display(Markdown('### Cronbach alpha'))");
+ code.appendLine("display(pd.DataFrame({'Cronbach alpha':vp_cronbach_alpha(vp_df), 'N':vp_df.shape[1]},index=['Reliability statistics']).round(3))");
+ code.appendLine("");
+
+ // Item-total Statistics
+ code.appendLine("# Item-Total Statistics");
+ code.appendLine("_dfr = pd.DataFrame()");
+ code.appendLine("for i, col in enumerate(vp_df.columns):");
+ code.appendLine(" _sr = vp_df.drop(col,axis=1).sum(axis=1)");
+ code.appendLine(" _df_t = pd.DataFrame(data={'Scale Mean if Item Deleted':_sr.mean(),'Scale Variance if Item Deleted':_sr.var(),");
+ code.appendLine(" 'Corrected Item-Total Correlation':_sr.corr(vp_df[col]),");
+ code.appendLine(" 'Cronbach Alpha if Item Deleted':vp_cronbach_alpha(vp_df.drop(col,axis=1))}, index=[col])");
+ code.appendLine(" _dfr = pd.concat([_dfr, _df_t])");
+ code.appendLine("display(Markdown('### Item-Total Statistics'))");
+ code.append("display(_dfr.round(3))");
+ codeList.push(code.toString());
+
+ return codeList;
+ }
+
+ }
+
+ return ReliabAnalysis;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_stats/StudentstTest.js b/visualpython/js/m_stats/StudentstTest.js
new file mode 100644
index 00000000..d9b5b1a4
--- /dev/null
+++ b/visualpython/js/m_stats/StudentstTest.js
@@ -0,0 +1,410 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : StudentstTest.js
+ * Author : Black Logic
+ * Note : Student's t-test
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2023. 05. 09
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] StudentstTest
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_stats/studentstTest.html'),
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/m_apps/Subset'
+], function(stHTML, com_util, com_Const, com_String, com_generator, PopupComponent, DataSelector, SuggestInput, Subset) {
+
+ /**
+ * StudentstTest
+ * - confidence_interval is available on upper 1.10.0 version of scipy
+ */
+ class StudentstTest extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['pd'];
+ this.config.docs = 'https://docs.scipy.org/doc/scipy/reference/';
+
+ this.state = {
+ testType: 'one-sample',
+ inputType: 'long-data',
+ data: '',
+ dataType: '',
+ testVariable: '',
+ testVariable1: '',
+ testVariable2: '',
+ groupingVariable: '',
+ group1: '',
+ group2: '',
+ group1_istext: true,
+ group2_istext: true,
+ pairedVariable1: '',
+ pairedVariable2: '',
+ testValue: '',
+ alterHypo: 'two-sided',
+ confInt: '95',
+ ...this.state
+ };
+
+ this.columnBindDict = {
+ 'one-sample': ['testVariable'],
+ 'two-sample': ['testVariable', 'testVariable1', 'testVariable2', 'groupingVariable'],
+ 'paired-sample': ['pairedVariable1', 'pairedVariable2']
+ };
+
+ this.subsetEditor = null;
+ }
+
+ _unbindEvent() {
+ super._unbindEvent();
+ var that = this;
+
+ $(document).off(this.wrapSelector('#testVariable'), 'change');
+ $(document).off(this.wrapSelector('#groupingVariable'), 'change');
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ /** Implement binding events */
+ var that = this;
+
+ // change test type
+ $(this.wrapSelector('#testType')).on('change', function() {
+ let testType = $(this).val();
+ that.state.testType = testType;
+
+ that.handleVariableChange(that.state.data);
+
+ $(that.wrapSelector('.vp-st-option')).hide();
+ $(that.wrapSelector('.vp-st-option.' + testType)).show();
+ if (testType === 'two-sample') {
+ $(that.wrapSelector('.vp-st-option.two-sample-' + that.state.inputType)).show();
+ }
+ });
+
+ // change input type
+ $(this.wrapSelector('input[name="inputType"]:radio')).on('change', function() {
+ let inputType = $(this).val();
+ that.state.inputType = inputType;
+ $(that.wrapSelector('.vp-st-option.two-sample-long-data')).hide();
+ $(that.wrapSelector('.vp-st-option.two-sample-wide-data')).hide();
+ $(that.wrapSelector('.vp-st-option.two-sample-' + inputType)).show();
+ });
+
+ // data change event
+ $(this.wrapSelector('#data')).on('change', function() {
+ let data = $(this).val();
+ that.handleVariableChange(data);
+ });
+
+ // change test variable
+ $(document).on('change', this.wrapSelector('#testVariable'), function() {
+ if (that.state.testType === 'one-sample') {
+ // get mean of data and show on placeholder
+ $(that.wrapSelector('#testValue')).prop('placeholder', '');
+ vpKernel.execute(com_util.formatString("int({0}[{1}].mean())", that.state.data, that.state.testVariable)).then(function(resultObj) {
+ let { result } = resultObj;
+ $(that.wrapSelector('#testValue')).prop('placeholder', result);
+ });
+ }
+ });
+
+ // change grouping variable
+ $(document).on('change', this.wrapSelector('#groupingVariable'), function() {
+ let colCode = $(this).val();
+ var colName = $(this).find('option:selected').text();
+ var colDtype = $(this).find('option:selected').attr('data-type');
+ that.state.groupingVariable = colCode;
+ // get result and load column list
+ vpKernel.getColumnCategory(that.state.data, colCode).then(function(resultObj) {
+ let { result } = resultObj;
+ $(that.wrapSelector('#group1')).val('');
+ $(that.wrapSelector('#group2')).val('');
+ that.state.group1 = '';
+ that.state.group2 = '';
+ that.state.group1_istext = true;
+ that.state.group2_istext = true;
+ try {
+ var category = JSON.parse(result);
+ // if (category && category.length > 0 && colDtype == 'object') {
+ // // if it's categorical column and its dtype is object, check 'Text' as default
+ // category.forEach(obj => {
+ // let selected1 = obj.value === that.state.group1;
+ // let selected2 = obj.value === that.state.group2;
+ // $(that.wrapSelector('#group1')).append(`${obj.label} `);
+ // $(that.wrapSelector('#group2')).append(`${obj.label} `);
+ // });
+ // }
+ var groupSuggest1 = new SuggestInput();
+ groupSuggest1.setComponentID('group1');
+ groupSuggest1.addClass('vp-input vp-state');
+ groupSuggest1.setSuggestList(function() { return category; });
+ groupSuggest1.setNormalFilter(true);
+ groupSuggest1.setPlaceholder('Select value');
+ $(that.wrapSelector('#group1')).replaceWith(groupSuggest1.toTagString());
+ var groupSuggest2 = new SuggestInput();
+ groupSuggest2.setComponentID('group2');
+ groupSuggest2.addClass('vp-input vp-state');
+ groupSuggest2.setSuggestList(function() { return category; });
+ groupSuggest2.setNormalFilter(true);
+ groupSuggest2.setPlaceholder('Select value');
+ $(that.wrapSelector('#group2')).replaceWith(groupSuggest2.toTagString());
+
+ if (category && category.length > 0) {
+ that.state.group1 = category[0].value;
+ that.state.group2 = category[0].value;
+ }
+
+ if (colDtype == 'object') {
+ // check as default
+ $(that.wrapSelector('#group1_istext')).prop('checked', true);
+ $(that.wrapSelector('#group2_istext')).prop('checked', true);
+ that.state.group1_istext = true;
+ that.state.group2_istext = true;
+ } else {
+ $(that.wrapSelector('#group1_istext')).prop('checked', false);
+ $(that.wrapSelector('#group2_istext')).prop('checked', false);
+ that.state.group1_istext = false;
+ that.state.group2_istext = false;
+ }
+ } catch {
+ $(that.wrapSelector('#group1')).val('');
+ $(that.wrapSelector('#group2')).val('');
+ }
+ });
+ });
+ }
+
+ handleVariableChange(data) {
+ let that = this;
+ this.state.data = data;
+ let columnBindList = this.columnBindDict[this.state.testType];
+ if (this.state.dataType === 'DataFrame') {
+ // DataFrame
+ columnBindList.forEach(col => {
+ $(that.wrapSelector('#' + col)).prop('disabled', false);
+ });
+ com_generator.vp_bindColumnSource(that, 'data', columnBindList, 'select', false, false);
+ } else {
+ // Series
+ columnBindList.forEach(col => {
+ $(that.wrapSelector('#' + col)).html('');
+ $(that.wrapSelector('#' + col)).prop('disabled', true);
+ });
+ }
+ }
+
+ templateForBody() {
+ let page = $(stHTML);
+ let that = this;
+
+ // generate dataselector
+ let dataSelector = new DataSelector({
+ pageThis: this, id: 'data', placeholder: 'Select data', required: true, boxClasses: 'vp-flex-gap5',
+ allowDataType: ['DataFrame'], withPopup: false,
+ finish: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ },
+ select: function(data, type) {
+ that.state.data = data;
+ that.state.dataType = type;
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ return page;
+ }
+
+ render() {
+ super.render();
+ let that = this;
+
+ // render Subset
+ this.subsetEditor = new Subset({
+ pandasObject: '',
+ config: { name: 'Subset' } },
+ {
+ useAsModule: true,
+ useInputColumns: true,
+ targetSelector: this.wrapSelector('#data'),
+ pageThis: this,
+ finish: function(code, state) {
+ that.state.data = code;
+ that.state.dataType = state.returnType;
+ $(that.wrapSelector('#data')).val(code);
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+
+ if (this.state.data !== '') {
+ let columnBindList = this.columnBindDict[this.state.testType];
+ com_generator.vp_bindColumnSource(this, 'data', columnBindList, 'select', false, false);
+ }
+
+ // control display option
+ $(this.wrapSelector('.vp-st-option')).hide();
+ $(this.wrapSelector('.vp-st-option.' + this.state.testType)).show();
+ if (this.state.testType === 'two-sample') {
+ $(this.wrapSelector('.vp-st-option.two-sample-' + this.state.inputType)).show();
+ }
+ }
+
+ generateCode() {
+ let {
+ testType, inputType, data,
+ testVariable, testVariable1, testVariable2, groupingVariable,
+ pairedVariable1, pairedVariable2,
+ group1, group2, group1_istext, group2_istext,
+ testValue, alterHypo, confInt
+ } = this.state;
+ let codeList = [];
+ let code = new com_String();
+
+ // 95% -> 0.95
+ confInt = confInt/100;
+
+ switch (testType) {
+ case 'one-sample':
+ code.appendLine("# One-sample t-test");
+ // variable declaration
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+ code.appendLine("");
+ // 1. Normality test
+ code.appendLine("# Normality test (Shapiro-Wilk)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.shapiro(vp_df[{0}])", testVariable);
+ code.appendLine("display(Markdown('### Normality test (Shapiro-Wilk)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},index=['Normality test (Shapiro-Wilk)']))");
+ code.appendLine("");
+ // 2. One-sample Statistics
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendFormatLine("display(pd.DataFrame(data={'N':vp_df[{0}].size,'Mean':vp_df[{1}].mean(),", testVariable, testVariable);
+ code.appendFormatLine(" 'Std. Deviation':vp_df[{0}].std(),", testVariable);
+ code.appendFormatLine(" 'Std. Error Mean':vp_df[{0}].std()/np.sqrt(vp_df[{1}].size)},", testVariable, testVariable);
+ code.appendLine(" index=['Statistics']))");
+ code.appendLine("");
+ // 3. One-sample t-test
+ code.appendLine("# One-sample t-test");
+ code.appendFormatLine("_res = stats.ttest_1samp(vp_df[{0}], popmean={1}, alternative='{2}')", testVariable, testValue, alterHypo);
+ code.appendFormatLine("_lower, _upper = _res.confidence_interval(confidence_level={0})", confInt);
+ code.appendLine("display(Markdown('### One-sample t-test'))");
+ code.appendFormatLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'dof':_res.df,'Alternative':'{0}',", alterHypo);
+ code.appendFormatLine(" 'p-value':_res.pvalue,'Test Value':{0},'Mean difference':vp_df[{1}].mean()-{2},", testValue, testVariable, testValue);
+ code.appendFormatLine(" 'Confidence interval':{0},'Lower':_lower,'Upper':_upper},", confInt);
+ code.append(" index=['One-sample t-test']))");
+ break;
+ case 'two-sample':
+ code.appendLine("# Independent two-sample t-test");
+ // variable declaration
+ if (inputType === 'long-data') {
+ code.appendFormatLine("vp_df1 = {0}[({1}[{2}] == {3})][{4}].dropna().copy()", data, data, groupingVariable, com_util.convertToStr(group1, group1_istext), testVariable);
+ code.appendFormatLine("vp_df2 = {0}[({1}[{2}] == {3})][{4}].dropna().copy()", data, data, groupingVariable, com_util.convertToStr(group2, group2_istext), testVariable);
+ } else if (inputType === 'wide-data') {
+ code.appendFormatLine("vp_df1 = {0}[{1}].dropna().copy()", data, testVariable1);
+ code.appendFormatLine("vp_df2 = {0}[{1}].dropna().copy()", data, testVariable2);
+ }
+ code.appendLine("");
+ // 1. Normality test
+ code.appendLine("# Normality test (Shapiro-Wilk)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendLine("_res1 = stats.shapiro(vp_df1)");
+ code.appendLine("_res2 = stats.shapiro(vp_df2)");
+ code.appendLine("display(Markdown('### Normality test (Shapiro-Wilk)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':[_res1.statistic,_res2.statistic],'p-value':[_res1.pvalue,_res2.pvalue]},");
+ code.appendLine(" index=[['Normality test (Shapiro-Wilk)' for i in range(2)],['Variable1','Variable2']]))");
+ code.appendLine("");
+ // 2. Equal Variance test
+ code.appendLine("# Equal Variance test (Levene)");
+ code.appendLine("display(Markdown('### Equal Variance test (Levene)'))");
+ code.appendLine("_res = stats.levene(vp_df1, vp_df2, center='mean')");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue}, index=['Equal Variance test (Levene)']))");
+ code.appendLine("");
+ // 3. Independent two-sample Statistics
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendLine("display(pd.DataFrame(data={'N':[vp_df1.size,vp_df2.size],");
+ code.appendLine(" 'Mean':[vp_df1.mean(),vp_df2.mean()],");
+ code.appendLine(" 'Std. Deviation':[vp_df1.std(),vp_df2.std()],");
+ code.appendLine(" 'Std. Error mean':[vp_df1.std()/np.sqrt(vp_df1.size),");
+ code.appendLine(" vp_df2.std()/np.sqrt(vp_df2.size )]},");
+ code.appendLine(" index=[['Statistics' for i in range(2)],['Variable1','Variable2']]))");
+ code.appendLine("");
+ // 4. Independent two-sample t-test
+ code.appendLine("# Independent two-sample t-test");
+ code.appendFormatLine("_res1 = stats.ttest_ind(vp_df1, vp_df2, equal_var=True, alternative='{0}')", alterHypo);
+ code.appendFormatLine("_res2 = stats.ttest_ind(vp_df1, vp_df2, equal_var=False, alternative='{0}')", alterHypo);
+ code.appendLine("display(Markdown('### Independent two-sample t-test'))");
+ code.appendFormatLine("display(pd.DataFrame(data={'Statistic':[_res1.statistic,_res2.statistic],'Alternative':['{0}' for i in range(2)],", alterHypo);
+ code.appendLine(" 'p-value':[_res1.pvalue,_res2.pvalue],");
+ code.appendLine(" 'Mean difference':[vp_df1.mean()-vp_df2.mean() for i in range(2)]},");
+ code.appendLine(" index=[['Independent two-sample t-test' for i in range(2)],['Equal variance' for i in range(2)],[True,False]]))");
+ code.append("display(Markdown('If equal_var is False, perform Welch\\\'s t-test, which does not assume equal population variance'))");
+ break;
+ case 'paired-sample':
+ // variable declaration
+ code.appendLine("# Paired samples t-test");
+ code.appendFormatLine("vp_df = {0}.dropna().copy()", data);
+ code.appendLine("");
+ code.appendFormatLine("try: vp_df[{0}].reset_index(drop=True, inplace=True)", pairedVariable1);
+ code.appendLine("except: pass");
+ code.appendFormatLine("try: vp_df[{0}].reset_index(drop=True, inplace=True)", pairedVariable2);
+ code.appendLine("except: pass");
+ code.appendLine("");
+ // 1. Normality test
+ code.appendLine("# Normality test (Shapiro-Wilk)");
+ code.appendLine("from IPython.display import display, Markdown");
+ code.appendLine("from scipy import stats");
+ code.appendFormatLine("_res = stats.shapiro(vp_df[{0}]-vp_df[{1}])", pairedVariable1, pairedVariable2);
+ code.appendLine("display(Markdown('### Normality test (Shapiro-Wilk)'))");
+ code.appendLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'p-value':_res.pvalue},");
+ code.appendLine(" index=['Normality test (Shapiro-Wilk): Paired differences']))");
+ code.appendLine("");
+ // 2. Paired samples Statistics
+ code.appendLine("# Statistics");
+ code.appendLine("display(Markdown('### Statistics'))");
+ code.appendFormatLine("display(pd.DataFrame(data={'N':[vp_df[{0}].size,vp_df[{1}].size,vp_df[{2}].size],", pairedVariable1, pairedVariable2, pairedVariable1);
+ code.appendFormatLine(" 'Mean':[vp_df[{0}].mean(),vp_df[{1}].mean(),(vp_df[{2}]-vp_df[{3}]).mean()],", pairedVariable1, pairedVariable2, pairedVariable1, pairedVariable2);
+ code.appendFormatLine(" 'Std. Deviation':[vp_df[{0}].std(),vp_df[{1}].std(),(vp_df[{2}]-vp_df[{3}]).std()],", pairedVariable1, pairedVariable2, pairedVariable1, pairedVariable2);
+ code.appendFormatLine(" 'Std. Error mean':[vp_df[{0}].std()/np.sqrt(vp_df[{1}].size),", pairedVariable1, pairedVariable1);
+ code.appendFormatLine(" vp_df[{0}].std()/np.sqrt(vp_df[{1}].size),", pairedVariable2, pairedVariable2);
+ code.appendFormatLine(" (vp_df[{0}]-vp_df[{1}]).std()/np.sqrt(vp_df[{2}].size)]},", pairedVariable1, pairedVariable2, pairedVariable1);
+ code.appendLine(" index=[['Statistics' for i in range(3)],['Variable1','Variable2','Paired differences']]))");
+ code.appendLine("");
+ // 3. Paired samples t-test
+ code.appendLine("# Paired samples t-test");
+ code.appendFormatLine("_res = stats.ttest_rel(vp_df[{0}], vp_df[{1}], alternative='{2}')", pairedVariable1, pairedVariable2, alterHypo);
+ code.appendFormatLine("_lower, _upper = _res.confidence_interval(confidence_level={0})", confInt);
+ code.appendLine("display(Markdown('### Paired samples t-test'))");
+ code.appendFormatLine("display(pd.DataFrame(data={'Statistic':_res.statistic,'dof':_res.df,'Alternative':'{0}',", alterHypo);
+ code.appendFormatLine(" 'p-value':_res.pvalue,'Mean difference':(vp_df[{0}]-vp_df[{1}]).mean(),", pairedVariable1, pairedVariable2);
+ code.appendFormatLine(" 'Confidence interval':{0},'Lower':_lower,'Upper':_upper},", confInt);
+ code.append(" index=['Paired samples t-test']))");
+ break;
+ }
+ codeList.push(code.toString());
+
+
+ return codeList;
+ }
+
+ }
+
+ return StudentstTest;
+});
\ No newline at end of file
diff --git a/src/matplotlib/__init__.py b/visualpython/js/m_stats/__init__.py
similarity index 100%
rename from src/matplotlib/__init__.py
rename to visualpython/js/m_stats/__init__.py
diff --git a/visualpython/js/m_visualize/Chart.js b/visualpython/js/m_visualize/Chart.js
new file mode 100644
index 00000000..d979a6e1
--- /dev/null
+++ b/visualpython/js/m_visualize/Chart.js
@@ -0,0 +1,1326 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Chart.js
+ * Author : Black Logic
+ * Note : Apps > Chart
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 11. 18
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Chart
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_visualize/chart.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_visualize/chart'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_Const',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/com_generator',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/DataSelector'
+], function(chartHTml, chartCss, com_String, com_Const, com_util, com_interface, com_generator, PopupComponent, FileNavigation, SuggestInput, DataSelector) {
+
+ /**
+ * Chart
+ */
+ class Chart extends PopupComponent {
+ _init() {
+ super._init();
+ /** Write codes executed before rendering */
+ this.config.dataview = false;
+ this.config.sizeLevel = 2;
+ this.config.checkModules = ['plt'];
+ this.config.docs = 'https://matplotlib.org/stable/';
+
+ this.setDefaultVariables();
+ this.state = {
+ kind: 'plot',
+ ...this.state
+ }
+ this.package = this.plotPackage[this.state.kind];
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+ let that = this;
+
+ }
+
+ bindEventAfterRender() {
+ let that = this;
+ // show option based on chart type
+ $(this.wrapSelector('#vp_plotKind .vp-plot-item')).click(function() {
+ // plot item
+ $(this).parent().find('.vp-plot-item').removeClass('selected');
+ $(this).addClass('selected');
+
+ // load selected kind
+ var kind = $(this).data('kind');
+ $(that.wrapSelector('#kind')).val(kind).prop('selected', true);
+
+ var thisPackage = { ...that.plotPackage[kind] };
+ if (thisPackage == undefined) thisPackage = that.plotPackage['plot'];
+
+ // hide all (without chart type, variable)
+ $(that.wrapSelector('table.vp-plot-setting-table tr:not(:last)')).hide();
+
+ // show selected chart type's option page
+ thisPackage.input && thisPackage.input.forEach(obj => {
+ $(that.wrapSelector('#' + obj.name)).closest('tr').show();
+
+ var label = obj.label;
+ if (label != undefined) {
+ $(that.wrapSelector('#' + obj.name)).closest('tr').find('th').removeClass('vp-orange-text');
+ if (obj.required != false) {
+ // label = "* " + obj.label;
+ $(that.wrapSelector('#' + obj.name)).closest('tr').find('th').addClass('vp-orange-text');
+ $(that.wrapSelector('#' + obj.name)).attr({'required': true});
+ } else {
+ $(that.wrapSelector('#' + obj.name)).attr({'required': false});
+ }
+ // $(that.wrapSelector("label[for='" + obj.name + "']")).text(label);
+ $(that.wrapSelector('#' + obj.name)).closest('tr').find('th').text(label);
+ }
+ });
+ thisPackage.variable && thisPackage.variable.forEach(obj => {
+ $(that.wrapSelector('#' + obj.name)).closest('tr').show();
+ });
+
+ thisPackage.input = thisPackage.input.concat(that.addOption);
+ that.package = thisPackage;
+ });
+
+ // use color
+ $(this.wrapSelector('#useColor')).change(function() {
+ var checked = $(this).prop('checked');
+ if (checked == true) {
+ // enable color selector
+ $(that.wrapSelector('#color')).removeAttr('disabled');
+ } else {
+ $(that.wrapSelector('#color')).attr('disabled', 'true');
+ }
+ })
+
+ // marker selector
+ $(this.wrapSelector('#markerSelector')).change(function() {
+ var selected = $(this).val();
+ if (selected == "marker") {
+ $(this).parent().find('#marker').show();
+ $(this).parent().find('#marker').val('');
+ } else {
+ $(this).parent().find('#marker').hide();
+ $(this).parent().find('#marker').val(selected);
+ }
+ });
+
+ // select cmap
+ $(this.wrapSelector('.vp-plot-cmap-wrapper')).click(function() {
+ $(this).toggleClass('open');
+ });
+
+ // open file navigation
+ $(this.wrapSelector('#vp_openFileNavigationBtn')).click(function() {
+ let fileNavi = new FileNavigation({
+ type: 'save',
+ extensions: ['png'],
+ finish: function(filesPath, status, error) {
+ if (filesPath.length > 0) {
+ let { file, path } = filesPath[0];
+ $(that.wrapSelector('#savefigpath')).val(path);
+ $(that.wrapSelector('#fileName')).val(file);
+ }
+ }
+ });
+ fileNavi.open();
+ });
+
+ // xlimit
+ $(this.wrapSelector('#xlimit_min')).change(function() {
+ let xlim_min = $(that.wrapSelector('#xlimit_min')).val();
+ let xlim_max = $(that.wrapSelector('#xlimit_max')).val();
+ $(that.wrapSelector('#xlim')).val(com_util.formatString('({0}, {1})', xlim_min, xlim_max));
+ });
+ $(this.wrapSelector('#xlimit_max')).change(function() {
+ let xlim_min = $(that.wrapSelector('#xlimit_min')).val();
+ let xlim_max = $(that.wrapSelector('#xlimit_max')).val();
+ $(that.wrapSelector('#xlim')).val(com_util.formatString('({0}, {1})', xlim_min, xlim_max));
+ });
+ $(this.wrapSelector('#ylimit_min')).change(function() {
+ let ylim_min = $(that.wrapSelector('#ylimit_min')).val();
+ let ylim_max = $(that.wrapSelector('#ylimit_max')).val();
+ $(that.wrapSelector('#ylim')).val(com_util.formatString('({0}, {1})', ylim_min, ylim_max));
+ });
+ $(this.wrapSelector('#ylimit_max')).change(function() {
+ let ylim_min = $(that.wrapSelector('#ylimit_min')).val();
+ let ylim_max = $(that.wrapSelector('#ylimit_max')).val();
+ $(that.wrapSelector('#ylim')).val(com_util.formatString('({0}, {1})', ylim_min, ylim_max));
+ });
+ }
+
+ templateForBody() {
+ return chartHTml;
+ }
+
+ loadState() {
+ vpLog.display(VP_LOG_TYPE.DEVELOP, this.state);
+
+ let that = this;
+ Object.keys(this.state).forEach(key => {
+ if (key !== 'config') {
+ let tag = $(that.wrapSelector('#' + key));
+ let tagName = $(tag).prop('tagName');
+ let savedValue = that.state[key];
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(savedValue);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', savedValue);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(savedValue);
+ break;
+ }
+ }
+ });
+ }
+
+ render() {
+ super.render();
+
+ this.renderImportOptions();
+ this.renderSubplotOption1();
+ this.renderCmapSelector();
+
+ // bind event
+ this.bindEventAfterRender();
+ this.bindVariableSelector();
+ }
+
+ renderImportOptions() {
+ var that = this;
+
+ //====================================================================
+ // Stylesheet suggestinput
+ //====================================================================
+ var stylesheetTag = $(this.wrapSelector('#vp_plStyle'));
+ // search available stylesheet list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('import json');
+ code.append(`print(json.dumps([{ 'label': s, 'value': s } for s in plt.style.available]))`);
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available stylesheet list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('vp_plStyle');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('style name');
+ // suggestInput.setNormalFilter(false);
+ $(stylesheetTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ //====================================================================
+ // System font suggestinput
+ //====================================================================
+ var fontFamilyTag = $(this.wrapSelector('#vp_plFontName'));
+ // search system font list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import json');
+ code.appendLine("import matplotlib.font_manager as fm");
+ code.appendLine("_ttflist = fm.fontManager.ttflist");
+ code.append("print(json.dumps([{'label': f.name, 'value': f.name } for f in _ttflist]))");
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available font list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('vp_plFontName');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('font name');
+ // suggestInput.setNormalFilter(false);
+ $(fontFamilyTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ //====================================================================
+ // Events
+ //====================================================================
+ $(this.wrapSelector('#vp_plImportRun')).click(function() {
+ // generateImportCode
+ var code = that.generateImportCode();
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Visualization > Chart');
+ });
+ }
+
+ renderSubplotOption1() {
+ // render kind selector
+ this.renderKindSelector();
+
+ // show marker image
+ var optionTagList = $(this.wrapSelector('#markerSelector option'));
+ // [0] : except typing tag
+ for (var i = 1; i < optionTagList.length; i++) {
+ // file name
+ var imgFile = $(optionTagList[i]).data('img');
+ // bind url
+ var url = com_Const.IMAGE_PATH + 'chart/marker/' + imgFile;
+ $(optionTagList[i]).attr({
+ 'data-img': url
+ });
+ }
+ }
+
+ renderKindSelector() {
+ // chart type selector
+ var selector = $(this.wrapSelector('#kind'));
+ var that = this;
+ this.plotKind.forEach(kind => {
+ var option = document.createElement('option');
+ $(option).attr({
+ id: kind,
+ name: 'kind',
+ value: kind
+ });
+ var span = document.createElement('span');
+ $(span).attr({
+ // class="vp-multilang" data-caption-id="imshow"
+ class: 'vp-multilang',
+ 'data-caption-id':kind
+ });
+ span.append(document.createTextNode(that.plotKindLang[kind]))
+ option.appendChild(span);
+ selector.append(option);
+ });
+
+ // select chart type using metadata
+ var plotType = this.state.kind;
+
+ // select chart
+ $(selector).val(plotType);
+ $(this.wrapSelector(`#vp_plotKind .vp-plot-item[data-kind="${plotType}"]`)).addClass('selected');
+
+ // hide original selector
+ $(selector).hide();
+
+ // initial plot chart option
+ var plotPackage = { ...this.plotPackage[plotType] };
+ // hide all (except allocate to, chart type selector)
+ $(this.wrapSelector('table.vp-plot-setting-table tr:not(:last)')).hide();
+
+ // show only options for this plot type
+ plotPackage.input && plotPackage.input.forEach(obj => {
+ $(this.wrapSelector('#' + obj.name)).closest('tr').show();
+ var label = obj.label;
+ if (label != undefined) {
+ $(this.wrapSelector('#' + obj.name)).closest('tr').find('th').removeClass('vp-orange-text');
+ if (obj.required != false) {
+ // label = "* " + obj.label;
+ $(this.wrapSelector('#' + obj.name)).closest('tr').find('th').addClass('vp-orange-text');
+ $(this.wrapSelector('#' + obj.name)).attr({'required': true});
+ } else {
+ $(this.wrapSelector('#' + obj.name)).attr({'required': false});
+ }
+ // $(this.wrapSelector("label[for='" + obj.name + "']")).text(label);
+ $(this.wrapSelector('#' + obj.name)).closest('tr').find('th').text(label);
+ }
+ });
+ plotPackage.variable && plotPackage.variable.forEach(obj => {
+ $(this.wrapSelector('#' + obj.name)).closest('tr').show();
+ });
+
+ plotPackage.input = plotPackage.input.concat(this.addOption);
+ this.package = plotPackage;
+ }
+
+ renderCmapSelector() {
+ // hide original selector
+ var cmapSelector = this.wrapSelector('#cmap');
+ $(cmapSelector).hide();
+
+ // cmap selector
+ this.cmap.forEach(ctype => {
+ var option = document.createElement('option');
+ $(option).attr({
+ 'name': 'cmap',
+ 'value': ctype
+ });
+ $(option).text(ctype == ''?'none':ctype);
+ $(cmapSelector).append(option);
+ });
+
+ // dynamical div list for cmap data
+ this.cmap.forEach(ctype => {
+ var divColor = document.createElement('div');
+ $(divColor).attr({
+ 'class': 'vp-plot-cmap-item vp-scrollbar',
+ 'data-cmap': ctype,
+ 'data-url': 'pandas/cmap/' + ctype + '.JPG',
+ 'title': ctype
+ });
+ $(divColor).text(ctype == ''?'none':ctype);
+
+ // bind url
+ var url = com_Const.IMAGE_PATH + 'chart/cmap/' + ctype + '.JPG';
+ $(divColor).css({
+ 'background-image' : 'url(' + url + ')'
+ })
+
+ var selectedCmap = this.wrapSelector('#vp_selectedCmap');
+
+ // select color
+ $(divColor).click(function() {
+ if (!$(this).hasClass('selected')) {
+ $(this).parent().find('.vp-plot-cmap-item.selected').removeClass('selected');
+ $(this).addClass('selected');
+ // selected cmap name
+ $(selectedCmap).text(ctype == ''?'none':ctype);
+ // selected cmap data-caption-id
+ $(selectedCmap).attr('data-caption-id', ctype);
+ // force selection
+ $(cmapSelector).val(ctype).prop('selected', true);
+ }
+ });
+ $(this.wrapSelector('#vp_plotCmapSelector')).append(divColor);
+ });
+ }
+
+ bindVariableSelector() {
+ var that = this;
+
+ let xSelector = new DataSelector({
+ pageThis: this, id: 'x'
+ });
+ $(this.wrapSelector('#x')).replaceWith(xSelector.toTagString());
+
+ let ySelector = new DataSelector({
+ pageThis: this, id: 'y', required: true
+ });
+ $(this.wrapSelector('#y')).replaceWith(ySelector.toTagString());
+
+ let zSelector = new DataSelector({
+ pageThis: this, id: 'z'
+ });
+ $(this.wrapSelector('#z')).replaceWith(zSelector.toTagString());
+ }
+
+ getSelectCode() {
+ var code = new com_String();
+
+ // variable
+ var variable = $(this.wrapSelector('.vp-var-view-item.selected td:first')).text();
+ if (variable == undefined) return "";
+
+ code.append(variable);
+
+ // columns
+ var columnsTag = $(this.wrapSelector('.vp-column-select-item.selected'));
+ if (columnsTag.length > 0) {
+ if (columnsTag.length == 1) {
+ code.append('[');
+ } else {
+ code.append('[[');
+ }
+ columnsTag.each((i, tag) => {
+ if (i > 0) {
+ code.append(', ');
+ }
+ var colName = $(tag).data('col');
+ code.append(com_util.convertToStr(colName));
+ });
+ if (columnsTag.length == 1) {
+ code.append(']');
+ } else {
+ code.append(']]');
+ }
+ }
+
+ // method
+ var method = $(this.wrapSelector('.vp-method-select-item.selected')).data('method');
+ if (method != undefined) {
+ code.appendFormat('.{0}', method);
+ }
+
+ return code.toString();
+ }
+
+ refreshVariables (callback = undefined) {
+ var that = this;
+
+ var _DATA_TYPES_OF_INDEX = [
+ 'RangeIndex', 'CategoricalIndex', 'MultiIndex', 'IntervalIndex', 'DatetimeIndex', 'TimedeltaIndex', 'PeriodIndex', 'Int64Index', 'UInt64Index', 'Float64Index'
+ ];
+
+ var _DATA_TYPES_OF_GROUPBY = [
+ 'DataFrameGroupBy', 'SeriesGroupBy'
+ ];
+
+ var _SEARCHABLE_DATA_TYPES = [
+ 'DataFrame', 'Series', 'Index', 'Period', 'GroupBy', 'Timestamp'
+ , ..._DATA_TYPES_OF_INDEX
+ , ..._DATA_TYPES_OF_GROUPBY
+ ];
+
+ var types = _SEARCHABLE_DATA_TYPES;
+
+ // init view
+ var viewList = $(this.wrapSelector('#vp_varViewList tbody'));
+ $(viewList).html('');
+
+ vpKernel.getDataList(types).then(function(resultObj) {
+ let { result } = resultObj;
+ var jsonVars = result.replace(/'/gi, `"`);
+ var varList = JSON.parse(jsonVars);
+
+ var hasVariable = false;
+ // variable list
+ varList.forEach(varObj => {
+ if (types.includes(varObj.varType) && varObj.varName[0] !== '_') {
+ var varAttr = {
+ 'data-var-name': varObj.varName,
+ 'data-var-type': varObj.varType,
+ 'value': varObj.varName
+ };
+
+ // Add to View Table
+ var tagRow = $(`${varObj.varName} ${varObj.varType} `);
+ $(viewList).append(tagRow);
+ }
+ });
+
+ // callback
+ if (callback != undefined) {
+ callback(varList);
+ }
+
+ });
+ }
+
+ simpleCodeGenerator(code, input, variable=[]) {
+ var hasValue = false;
+ input && input.forEach(obj => {
+ var val = com_generator.vp_getTagValue(this.uuid, obj);
+ if (val != '' && val != 'plt') {
+ hasValue = true;
+ if (obj.type == 'text') {
+ val = "'"+val+"'";
+ } else if (obj.type == 'list') {
+ val = '['+val+']';
+ }
+ }
+ code = code.split('${' + obj.name + '}').join(val);
+ });
+ var opt_params = '';
+ variable && variable.forEach(obj => {
+ var val = com_generator.vp_getTagValue(this.uuid, obj);
+ if (val != '') {
+ hasValue = true;
+ if (obj.type == 'text') {
+ val = "'"+val+"'";
+ } else if (obj.type == 'list') {
+ val = '['+val+']';
+ }
+ opt_params += ', ' + obj.key + '=' + val;
+ }
+ });
+ code = code.split('${v}').join(opt_params);
+
+ code = code.split('(, ').join('(');
+
+ if (!hasValue) {
+ return '';
+ }
+
+ return code;
+ }
+
+ generateImportCode () {
+ var code = new com_String();
+
+ // get parameters
+ var figWidth = $(this.wrapSelector('#vp_plFigureWidth')).val();
+ var figHeight = $(this.wrapSelector('#vp_plFigureHeight')).val();
+ var styleName = $(this.wrapSelector('#vp_plStyle')).val();
+ var fontName = $(this.wrapSelector('#vp_plFontName')).val();
+ var fontSize = $(this.wrapSelector('#vp_plFontSize')).val();
+
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('%matplotlib inline');
+ if (styleName && styleName.length > 0) {
+ code.appendFormatLine("plt.style.use('{0}')", styleName);
+ }
+ code.appendFormatLine("plt.rc('figure', figsize=({0}, {1}))", figWidth, figHeight);
+ code.appendLine();
+
+ code.appendLine('from matplotlib import rcParams');
+ if (fontName && fontName.length > 0) {
+ code.appendFormatLine("rcParams['font.family'] = '{0}'", fontName);
+ }
+ if (fontSize && fontSize.length > 0) {
+ code.appendFormatLine("rcParams['font.size'] = {0}", fontSize);
+ }
+ code.append("rcParams['axes.unicode_minus'] = False");
+
+ return [code.toString()];
+ }
+
+
+ generateCode() {
+ try {
+ var sbCode = new com_String();
+
+ var i0Input = 'plt';
+
+ // copy package
+ var kind = $(this.wrapSelector('#kind')).val();
+ let thisPackage = this.package;
+
+ // if no color selected, not generate code
+ if ($(this.wrapSelector('#useColor')).prop('checked') != true) {
+ if (thisPackage.variable != undefined) {
+ var idx = thisPackage.variable.findIndex(function(item) {return item.name === 'color'});
+ if (idx > -1) {
+ thisPackage.variable.splice(idx, 1);
+ }
+ }
+ }
+
+ // get user option
+ var userOption = new com_String();
+ var userOptValue = $(this.wrapSelector('#vp_userOption')).val();
+ if (userOptValue != '') {
+ userOption.appendFormat(', {0}', userOptValue);
+ }
+
+ // plot component code
+ var plotCode = com_generator.vp_codeGenerator(this.uuid, thisPackage, userOption.toString());
+ sbCode.append(plotCode);
+
+ // tail code
+ if (thisPackage.tailCode != undefined) {
+ sbCode.append('\n' + thisPackage.tailCode.split('${i0}').join(i0Input));
+ }
+
+ // optional code
+ for (var i = 0; i < this.optPackList.length; i++) {
+ var opt = this.optPackList[i];
+ // pass if no value
+ if ($(this.wrapSelector('#'+opt)).val() == '') {
+ continue;
+ }
+
+ var pack = this.optionalPackage[opt];
+ // use plt
+ var code = this.simpleCodeGenerator(pack.code2, pack.input, pack.variable);
+ if (code != '') {
+ sbCode.append('\n' + code);
+ }
+ }
+
+ // plt.show()
+ sbCode.appendLine();
+ sbCode.append('plt.show()');
+
+ } catch (exmsg) {
+ // show error on alert modal
+ if (this.isHidden() == false) {
+ com_util.renderAlertModal(exmsg);
+ }
+ }
+
+ return sbCode.toString();
+ }
+
+ setDefaultVariables() {
+ this.plotPackage = {
+ 'plot': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value',
+ required: false
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'label',
+ type: 'text'
+ },
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ },
+ {
+ name: 'marker',
+ type: 'text'
+ },
+ {
+ name: 'linestyle',
+ type: 'text',
+ component: 'option_select',
+ default: '-'
+ }
+ ]
+ },
+ 'bar': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Height'
+ }
+ ],
+ variable: [
+ {
+ name: 'label',
+ type: 'text'
+ },
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ },
+ {
+ name: 'linestyle',
+ type: 'text',
+ component: 'option_select',
+ default: '-'
+ }
+ ]
+ },
+ 'barh': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'Y Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Width'
+ }
+ ],
+ variable: [
+ {
+ name: 'label',
+ type: 'text'
+ },
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ },
+ {
+ name: 'linestyle',
+ type: 'text',
+ component: 'option_select',
+ default: '-'
+ }
+ ]
+ },
+ 'hist': {
+ code: '${i0}.${kind}(${x}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'bins',
+ type: 'int',
+ required: true,
+ label: 'Bins'
+ },
+ {
+ name: 'label',
+ type: 'text'
+ },
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ },
+ {
+ name: 'linestyle',
+ type: 'text',
+ component: 'option_select',
+ default: '-'
+ }
+ ]
+ },
+ 'boxplot': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ],
+ variable: [
+ ]
+ },
+ 'stackplot': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ },
+ {
+ name: 'linestyle',
+ type: 'text',
+ component: 'option_select',
+ default: '-'
+ }
+ ]
+ },
+ 'pie': {
+ code: '${i0}.${kind}(${x}${v}${etc})',
+ tailCode: "${i0}.axis('equal')",
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'Value'
+ }
+ ],
+ variable: [
+ ]
+ },
+ 'scatter': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'cmap',
+ type: 'text'
+ },
+ {
+ name: 'marker',
+ type: 'text'
+ }
+ ]
+ },
+ 'hexbin': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ tailCode: '${i0}.colorbar()', // color bar
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'label',
+ type: 'text'
+ },
+ {
+ name: 'color',
+ type: 'text',
+ default: '#000000'
+ }
+ ]
+ },
+ 'contour': {
+ code: '${i0}.${kind}(${x}, ${y}, ${z}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ },
+ {
+ name: 'z',
+ type: 'var',
+ label: 'Z Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'cmap',
+ type: 'text'
+ },
+ {
+ name: 'label',
+ type: 'text'
+ }
+ ]
+ },
+ 'imshow': {
+ code: '${i0}.${kind}(${z}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'z',
+ type: 'var',
+ label: 'Value'
+ }
+ ],
+ variable: [
+ {
+ name: 'extent', // [xmin, xmax, ymin, ymax]
+ type: 'var'
+ },
+ {
+ name: 'origin',
+ type: 'text'
+ },
+ {
+ name: 'cmap',
+ type: 'text'
+ }
+ ]
+ },
+ 'errorbar': {
+ code: '${i0}.${kind}(${x}, ${y}${v}${etc})',
+ input: [
+ {
+ name: 'i0',
+ label: 'Axes Variable',
+ type: 'int',
+ required: false
+ },
+ {
+ name: 'kind',
+ type: 'var',
+ label: 'Chart Type'
+ },
+ {
+ name: 'x',
+ type: 'var',
+ label: 'X Value'
+ },
+ {
+ name: 'y',
+ type: 'var',
+ label: 'Y Value'
+ }
+ ]
+ }
+ };
+
+ this.optPackList = ['title', 'xlabel', 'ylabel', 'xlim', 'ylim', 'legend', 'savefig'];
+ this.optionalPackage = {
+ 'title': {
+ code: '${i0}.set_title(${title})',
+ code2: 'plt.title(${title})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var',
+ required: false
+ },
+ {
+ name: 'title',
+ type: 'text',
+ required: false
+ }
+ ]
+ },
+ 'xlabel': {
+ code: '${i0}.set_xlabel(${xlabel})',
+ code2: 'plt.xlabel(${xlabel})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var',
+ required: false
+ },
+ {
+ name: 'xlabel',
+ type: 'text',
+ required: false
+ }
+ ]
+ },
+ 'ylabel': {
+ code: '${i0}.set_ylabel(${ylabel})',
+ code2: 'plt.ylabel(${ylabel})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var',
+ required: false
+ },
+ {
+ name: 'ylabel',
+ type: 'text',
+ required: false
+ }
+ ]
+ },
+ 'xlim': {
+ code: '${i0}.set_xlim(${xlim})',
+ code2: 'plt.xlim(${xlim})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var',
+ required: false
+ },
+ {
+ name: 'xlim',
+ type: 'var',
+ required: false
+ }
+ ]
+ },
+ 'ylim': {
+ code: '${i0}.set_ylim(${ylim})',
+ code2: 'plt.ylim(${ylim})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var',
+ required: false
+ },
+ {
+ name: 'ylim',
+ type: 'var',
+ required: false
+ }
+ ]
+ },
+ 'legend': {
+ code: '${i0}.legend(${v})',
+ code2: 'plt.legend(${v})',
+ input: [
+ {
+ name: 'i0',
+ type: 'var'
+ }
+ ],
+ variable: [
+ {
+ key: 'title',
+ name: 'legendTitle',
+ type: 'text'
+ },
+ {
+ key: 'label',
+ name: 'legendLabel',
+ type: 'var'
+ },
+ {
+ key: 'loc',
+ name: 'legendLoc',
+ type: 'text',
+ component: 'option_select',
+ default: 'best'
+ }
+ ]
+ },
+ 'savefig': {
+ code: "${i0}.savefig('${savefigpath}')",
+ code2: "plt.savefig('${savefigpath}')",
+ input: [
+ {
+ name: 'i0',
+ type: 'var'
+ },
+ {
+ name: 'savefigpath',
+ type: 'var'
+ }
+ ],
+ variable: []
+ }
+ };
+ this.addOption = [
+ { name: 'vp_userOption', required: false },
+ { name: 'title', required: false },
+ { name: 'xlabel', required: false },
+ { name: 'ylabel', required: false },
+ { name: 'xlim', required: false },
+ { name: 'ylim', required: false },
+ { name: 'legendTitle', required: false },
+ { name: 'legendLabel', required: false },
+ { name: 'legendLoc', required: false },
+ { name: 'savefigpath', required: false }
+ ];
+ // plot type
+ this.plotKind = [
+ 'plot', 'bar', 'barh', 'hist', 'boxplot', 'stackplot',
+ 'pie', 'scatter', 'hexbin', 'contour', 'imshow', 'errorbar'
+ ];
+ this.plotKindLang = {
+ 'plot': 'Line',
+ 'bar': 'Bar 1',
+ 'barh': 'Bar 2',
+ 'hist': 'Histogram',
+ 'boxplot': 'Box',
+ 'stackplot': 'Stack',
+ 'pie': 'Pie',
+ 'scatter': 'Scatter',
+ 'hexbin': 'Hexbin',
+ 'contour': 'Contour',
+ 'imshow': 'Image',
+ 'errorbar': 'Error Bar'
+ };
+ // cmap type
+ this.cmap = [
+ '', 'viridis', 'plasma', 'inferno', 'magma', 'cividis'
+ , 'Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c'
+ ];
+ // marker type
+ this.marker = {
+ // 'custom': { label: 'Custom', value: 'marker' },
+ 'point' : { label: '.', value: '.', img: 'm00.png' },
+ 'pixel' : { label: ',', value: ',', img: 'm01.png' },
+ 'circle' : { label: 'o', value: 'o', img: 'm02.png' },
+ 'triangle_down' : { label: '▼', value: 'v', img: 'm03.png' },
+ 'triangle_up' : { label: '▲', value: '^', img: 'm04.png' },
+ 'triangle_left' : { label: '◀', value: '<', img: 'm05.png' },
+ 'triangle_right' : { label: '▶', value: '>', img: 'm06.png' },
+ 'tri_down' : { label: '┬', value: '1', img: 'm07.png' },
+ 'tri_up' : { label: '┵', value: '2', img: 'm08.png' },
+ 'tri_left' : { label: '┤', value: '3', img: 'm09.png' },
+ 'tri_right' : { label: '├', value: '4', img: 'm10.png' },
+ 'octagon' : { label: 'octagon', value: '8', img: 'm11.png' },
+ 'square' : { label: 'square', value: 's', img: 'm12.png' },
+ 'pentagon' : { label: 'pentagon', value: 'p', img: 'm13.png' },
+ 'plus (filled)' : { label: 'filled plus', value: 'P', img: 'm23.png' },
+ 'star' : { label: 'star', value: '*', img: 'm14.png' },
+ 'hexagon1' : { label: 'hexagon1', value: 'h', img: 'm15.png' },
+ 'hexagon2' : { label: 'hexagon2', value: 'H', img: 'm16.png' },
+ 'plus' : { label: 'plus', value: '+', img: 'm17.png' },
+ 'x' : { label: 'x', value: 'x', img: 'm18.png' },
+ 'x (filled)' : { label: 'filled x', value: 'X', img: 'm24.png' },
+ 'diamond' : { label: 'diamond', value: 'D', img: 'm19.png' },
+ 'thin_diamond' : { label: 'thin diamond', value: 'd', img: 'm20.png' }
+ }
+ // legend position
+ this.legendPosition = [
+ 'best', 'upper right', 'upper left', 'lower left', 'lower right',
+ 'center left', 'center right', 'lower center', 'upper center', 'center'
+ ];
+ this.methodList = {
+ 'categorical': [
+ { label: 'count', method: 'count()' },
+ { label: 'unique count', method: 'unique()' }
+ ],
+ 'numerical': [
+ { label: 'count', method: 'count()' },
+ { label: 'unique count', method: 'unique()' },
+ { label: 'sum', method: 'sum(numeric_only=True)' },
+ { label: 'average', method: 'mean(numeric_only=True)' },
+ { label: 'min', method: 'min()' },
+ { label: 'max', method: 'max()' }
+ ]
+ }
+ }
+
+ }
+
+ return Chart;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_visualize/ChartSetting.js b/visualpython/js/m_visualize/ChartSetting.js
new file mode 100644
index 00000000..e1e49f63
--- /dev/null
+++ b/visualpython/js/m_visualize/ChartSetting.js
@@ -0,0 +1,168 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : ChartSetting.js
+ * Author : Black Logic
+ * Note : Visualization > Setting
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 03. 21
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Chart Setting
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_visualize/chartSetting.html'), // INTEGRATION: unified version of text loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput'
+], function(csHTML, com_String, com_util, PopupComponent, SuggestInput) {
+
+ class ChartSetting extends PopupComponent {
+ _init() {
+ super._init();
+
+ this.config.size = { width: 500, height: 400 };
+ this.config.importButton = true;
+ this.config.dataview = false;
+
+ this.state = {
+ figureWidth: '12',
+ figureHeight: '8',
+ styleSheet: '',
+ fontName: '',
+ fontSize: '10',
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+
+ let that = this;
+ // setting popup - set default
+ $(this.wrapSelector('#setDefault')).on('change', function() {
+ let checked = $(this).prop('checked');
+
+ if (checked) {
+ // disable input
+ $(that.wrapSelector('.vp-chart-setting-body input')).prop('disabled', true);
+ } else {
+ // enable input
+ $(that.wrapSelector('.vp-chart-setting-body input')).prop('disabled', false);
+ }
+ });
+ }
+
+ templateForBody() {
+ let page = $(csHTML);
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ let that = this;
+
+ //====================================================================
+ // Stylesheet suggestinput
+ //====================================================================
+ var stylesheetTag = $(this.wrapSelector('#styleSheet'));
+ // search available stylesheet list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('import json');
+ code.append(`print(json.dumps([{ 'label': s, 'value': s } for s in plt.style.available]))`);
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available stylesheet list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('styleSheet');
+ suggestInput.addClass('vp-input vp-state');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('style name');
+ suggestInput.setValue(that.state.styleSheet);
+ // suggestInput.setNormalFilter(false);
+ $(stylesheetTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ //====================================================================
+ // System font suggestinput
+ //====================================================================
+ var fontFamilyTag = $(this.wrapSelector('#fontName'));
+ // search system font list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import json');
+ code.appendLine("import matplotlib.font_manager as fm");
+ code.appendLine("_ttflist = fm.fontManager.ttflist");
+ code.append("print(json.dumps([{'label': f.name, 'value': f.name } for f in _ttflist]))");
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available font list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('fontName');
+ suggestInput.addClass('vp-input vp-state');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('font name');
+ suggestInput.setValue(that.state.fontName);
+ // suggestInput.setNormalFilter(false);
+ $(fontFamilyTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+ }
+
+ generateImportCode() {
+ var code = new com_String();
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('%matplotlib inline');
+ code.appendLine('import seaborn as sns');
+ return [code.toString()];
+ }
+
+ generateCode() {
+ var code = new com_String();
+
+ // get parameters
+ let setDefault = $(this.wrapSelector('#setDefault')).prop('checked');
+ if (setDefault == true) {
+ code.appendLine('from matplotlib import rcParams, rcParamsDefault');
+ code.append('rcParams.update(rcParamsDefault)');
+ } else {
+ // get parameters
+ let { figureWidth, figureHeight, styleSheet, fontName, fontSize } = this.state;
+
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('%matplotlib inline');
+ code.appendLine('import seaborn as sns');
+ if (styleSheet && styleSheet.length > 0) {
+ code.appendFormatLine("plt.style.use('{0}')", styleSheet);
+ }
+ code.appendFormatLine("plt.rc('figure', figsize=({0}, {1}))", figureWidth, figureHeight);
+ code.appendLine();
+
+ code.appendLine('from matplotlib import rcParams');
+ if (fontName && fontName.length > 0) {
+ code.appendFormatLine("rcParams['font.family'] = '{0}'", fontName);
+ }
+ if (fontSize && fontSize.length > 0) {
+ code.appendFormatLine("rcParams['font.size'] = {0}", fontSize);
+ }
+ code.append("rcParams['axes.unicode_minus'] = False");
+ }
+
+ return code.toString();
+ }
+ }
+
+ return ChartSetting;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_visualize/Plotly.js b/visualpython/js/m_visualize/Plotly.js
new file mode 100644
index 00000000..684840b3
--- /dev/null
+++ b/visualpython/js/m_visualize/Plotly.js
@@ -0,0 +1,579 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Plotly.js
+ * Author : Black Logic
+ * Note : Visualization > Plotly
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 05. 16
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Plotly
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_visualize/plotly.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_visualize/plotly'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/js/com/component/DataSelector',
+ 'vp_base/data/m_visualize/plotlyLibrary',
+], function(ptHTML, ptCss, com_String, com_generator, com_util, PopupComponent, SuggestInput, FileNavigation, DataSelector, PLOTLY_LIBRARIES) {
+
+ class Plotly extends PopupComponent {
+ _init() {
+ super._init();
+
+ this.config.size = { width: 1064, height: 550 };
+ this.config.installButton = true;
+ this.config.importButton = true;
+ this.config.dataview = false;
+ this.config.checkModules = ['px'];
+ this.config.docs = 'https://plotly.com/python-api-reference/index.html';
+
+ this.state = {
+ chartType: 'scatter',
+ data: '',
+ x: '', y: '', z: '',
+ x_start: '', x_end: '',
+ values: '', names: '', parents: '',
+ color: '',
+ sort: '',
+ userOption: '',
+ title: '',
+ x_label: '',
+ y_label: '',
+ userCode: '',
+ autoRefresh: true,
+ ...this.state
+ }
+
+ /**
+ * Plotly.express functions
+ * ---
+ * Basics: scatter, line, area, bar, funnel, timeline
+ * Part-of-Whole: pie, sunburst, treemap, icicle, funnel_area
+ * 1D Distributions: histogram, box, violin, strip, ecdf
+ * 2D Distributions: density_heatmap, density_contour
+ * Matrix or Image Input: imshow
+ * 3-Dimensional: scatter_3d, line_3d
+ * Multidimensional: scatter_matrix, parallel_coordinates, parallel_categories
+ * Tile Maps: scatter_mapbox, line_mapbox, choropleth_mapbox, density_mapbox
+ * Outline Maps: scatter_geo, line_geo, choropleth
+ * Polar Charts: scatter_polar, line_polar, bar_polar
+ * Ternary Charts: scatter_ternary, line_ternary
+ */
+ this.chartConfig = PLOTLY_LIBRARIES;
+ this.chartTypeList = {
+ 'Basics': [ 'scatter', 'line', 'area', 'bar', 'funnel', 'timeline' ],
+ 'Part-of-Whole': [ 'pie', 'sunburst', 'treemap', 'funnel_area' ], // 'icicle' removed
+ '1D Distributions': [ 'histogram', 'box', 'violin', 'strip' ], // 'ecdf' removed
+ '2D Distributions': [ 'density_heatmap', 'density_contour' ],
+ 'Matrix or Image Input': [ 'imshow' ],
+ // '3-Dimensional': [ 'scatter_3d', 'line_3d' ],
+ // 'Multidimensional': [ 'scatter_matrix', 'parallel_coordinates', 'parallel_categories' ],
+ // 'Tile Maps': [ 'scatter_mapbox', 'line_mapbox', 'choropleth_mapbox', 'density_mapbox' ],
+ // 'Outline Maps': [ 'scatter_geo', 'line_geo', 'choropleth' ],
+ // 'Polar Charts': [ 'scatter_polar', 'line_polar', 'bar_polar' ],
+ // 'Ternary Charts': [ 'scatter_ternary', 'line_ternary' ],
+ }
+
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+
+ let that = this;
+
+ // change tab
+ $(this.wrapSelector('.vp-tab-item')).on('click', function() {
+ let type = $(this).data('type'); // data / wordcloud / plot
+
+ $(that.wrapSelector('.vp-tab-bar .vp-tab-item')).removeClass('vp-focus');
+ $(this).addClass('vp-focus');
+
+ $(that.wrapSelector('.vp-tab-page-box > .vp-tab-page')).hide();
+ $(that.wrapSelector(com_util.formatString('.vp-tab-page[data-type="{0}"]', type))).show();
+ });
+
+ // change chart type
+ $(this.wrapSelector('#chartType')).on('change', function() {
+ let chartType = $(this).val();
+ $(that.wrapSelector('.pt-option')).hide();
+ if (chartType === 'density_heatmap' || chartType === 'density_contour') {
+ // show x, y, z
+ $(that.wrapSelector('#x')).closest('.pt-option').show();
+ $(that.wrapSelector('#y')).closest('.pt-option').show();
+ $(that.wrapSelector('#z')).closest('.pt-option').show();
+ if (chartType === 'density_contour') {
+ $(that.wrapSelector('#color')).closest('.pt-option').show();
+ }
+ }
+ else if (chartType === 'timeline') {
+ $(that.wrapSelector('#x_start')).closest('.pt-option').show();
+ $(that.wrapSelector('#x_end')).closest('.pt-option').show();
+ $(that.wrapSelector('#y')).closest('.pt-option').show();
+ $(that.wrapSelector('#color')).closest('.pt-option').show();
+ }
+ else if (chartType === 'pie' || chartType === 'funnel_area') {
+ // show values, names
+ $(that.wrapSelector('#values')).closest('.pt-option').show();
+ $(that.wrapSelector('#names')).closest('.pt-option').show();
+ $(that.wrapSelector('#color')).closest('.pt-option').show();
+ }
+ else if (chartType === 'sunburst' || chartType === 'treemap' || chartType === 'icicle') {
+ // show values, names, parents
+ $(that.wrapSelector('#values')).closest('.pt-option').show();
+ $(that.wrapSelector('#names')).closest('.pt-option').show();
+ $(that.wrapSelector('#color')).closest('.pt-option').show();
+ $(that.wrapSelector('#parents')).closest('.pt-option').show();
+ }
+ else {
+ // show x, y
+ $(that.wrapSelector('#x')).closest('.pt-option').show();
+ $(that.wrapSelector('#y')).closest('.pt-option').show();
+ $(that.wrapSelector('#color')).closest('.pt-option').show();
+ }
+ $(that.wrapSelector('#sort')).closest('.pt-option').show();
+ });
+
+ // use data or not
+ $(this.wrapSelector('#setXY')).on('change', function() {
+ let setXY = $(this).prop('checked');
+ if (setXY == false) {
+ // set Data
+ $(that.wrapSelector('#data')).prop('disabled', false);
+
+ $(that.wrapSelector('#x')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#x_start')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#x_end')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#y')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#z')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#values')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#names')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#parents')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#color')).closest('.vp-ds-box').replaceWith(' ');
+ } else {
+ // set X Y indivisually
+ // disable data selection
+ $(that.wrapSelector('#data')).prop('disabled', true);
+ $(that.wrapSelector('#data')).val('');
+ that.state.data = '';
+ that.state.x = '';
+ that.state.x_start = '';
+ that.state.x_end = '';
+ that.state.y = '';
+ that.state.z = '';
+ that.state.values = '';
+ that.state.names = '';
+ that.state.parents = '';
+ that.state.color = '';
+
+ let dataSelectorX = new DataSelector({ pageThis: that, id: 'x' });
+ $(that.wrapSelector('#x')).replaceWith(dataSelectorX.toTagString());
+
+ let dataSelectorXStart = new DataSelector({ pageThis: that, id: 'x_start' });
+ $(that.wrapSelector('#x_start')).replaceWith(dataSelectorXStart.toTagString());
+
+ let dataSelectorXEnd = new DataSelector({ pageThis: that, id: 'x_end' });
+ $(that.wrapSelector('#x_end')).replaceWith(dataSelectorXEnd.toTagString());
+
+ let dataSelectorY = new DataSelector({ pageThis: that, id: 'y' });
+ $(that.wrapSelector('#y')).replaceWith(dataSelectorY.toTagString());
+
+ let dataSelectorZ = new DataSelector({ pageThis: that, id: 'z' });
+ $(that.wrapSelector('#z')).replaceWith(dataSelectorZ.toTagString());
+
+ let dataSelectorValues = new DataSelector({ pageThis: that, id: 'values' });
+ $(that.wrapSelector('#values')).replaceWith(dataSelectorValues.toTagString());
+
+ let dataSelectorNames = new DataSelector({ pageThis: that, id: 'names' });
+ $(that.wrapSelector('#names')).replaceWith(dataSelectorNames.toTagString());
+
+ let dataSelectorParents = new DataSelector({ pageThis: that, id: 'parents' });
+ $(that.wrapSelector('#parents')).replaceWith(dataSelectorParents.toTagString());
+
+ let dataSelectorColor = new DataSelector({ pageThis: that, id: 'color' });
+ $(that.wrapSelector('#color')).replaceWith(dataSelectorColor.toTagString());
+
+ }
+ });
+
+ // load preview
+ // preview refresh
+ $(this.wrapSelector('#previewRefresh')).on('click', function() {
+ that.loadPreview();
+ });
+ $(document).off('change', this.wrapSelector('.vp-state'));
+ $(document).on('change', this.wrapSelector('.vp-state'), function(evt) {
+ that._saveSingleState($(this)[0]);
+ if (that.state.autoRefresh) {
+ that.loadPreview();
+ }
+ evt.stopPropagation();
+ });
+
+ }
+
+ templateForBody() {
+ let page = $(ptHTML);
+
+ let that = this;
+
+ // chart types
+ let chartTypeTag = new com_String();
+ Object.keys(this.chartTypeList).forEach(chartCategory => {
+ let chartOptionTag = new com_String();
+ that.chartTypeList[chartCategory].forEach(opt => {
+ let optConfig = that.chartConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.chartType) {
+ selectedFlag = 'selected';
+ }
+ chartOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, opt);
+ })
+ chartTypeTag.appendFormatLine('{1} ',
+ chartCategory, chartOptionTag.toString());
+ });
+ $(page).find('#chartType').html(chartTypeTag.toString());
+
+ // chart variable
+ let dataSelector = new DataSelector({
+ type: 'data',
+ pageThis: this,
+ id: 'data',
+ select: function(value, dtype) {
+ that.state.dtype = dtype;
+
+ if (dtype == 'DataFrame') {
+ $(that.wrapSelector('#x')).prop('disabled', false);
+ $(that.wrapSelector('#x_start')).prop('disabled', false);
+ $(that.wrapSelector('#x_end')).prop('disabled', false);
+ $(that.wrapSelector('#y')).prop('disabled', false);
+ $(that.wrapSelector('#z')).prop('disabled', false);
+ $(that.wrapSelector('#values')).prop('disabled', false);
+ $(that.wrapSelector('#names')).prop('disabled', false);
+ $(that.wrapSelector('#parents')).prop('disabled', false);
+ $(that.wrapSelector('#color')).prop('disabled', false);
+
+ // bind column source using selected dataframe
+ com_generator.vp_bindColumnSource(that, 'data', [
+ 'x', 'x_start', 'x_end', 'y', 'z', 'values', 'names', 'parents', 'color'
+ ], 'select', true, true);
+ } else {
+ $(that.wrapSelector('#x')).prop('disabled', true);
+ $(that.wrapSelector('#x_start')).prop('disabled', true);
+ $(that.wrapSelector('#x_end')).prop('disabled', true);
+ $(that.wrapSelector('#y')).prop('disabled', true);
+ $(that.wrapSelector('#z')).prop('disabled', true);
+ $(that.wrapSelector('#values')).prop('disabled', true);
+ $(that.wrapSelector('#names')).prop('disabled', true);
+ $(that.wrapSelector('#parents')).prop('disabled', true);
+ $(that.wrapSelector('#color')).prop('disabled', true);
+
+ }
+ },
+ finish: function(value, dtype) {
+ that.state.dtype = dtype;
+
+ if (dtype == 'DataFrame') {
+ $(that.wrapSelector('#x')).prop('disabled', false);
+ $(that.wrapSelector('#x_start')).prop('disabled', false);
+ $(that.wrapSelector('#x_end')).prop('disabled', false);
+ $(that.wrapSelector('#y')).prop('disabled', false);
+ $(that.wrapSelector('#z')).prop('disabled', false);
+ $(that.wrapSelector('#values')).prop('disabled', false);
+ $(that.wrapSelector('#names')).prop('disabled', false);
+ $(that.wrapSelector('#parents')).prop('disabled', false);
+ $(that.wrapSelector('#color')).prop('disabled', false);
+
+ // bind column source using selected dataframe
+ com_generator.vp_bindColumnSource(that, 'data', [
+ 'x', 'x_start', 'x_end', 'y', 'z', 'values', 'names', 'parents', 'color'
+ ], 'select', true, true);
+ } else {
+ $(that.wrapSelector('#x')).prop('disabled', true);
+ $(that.wrapSelector('#x_start')).prop('disabled', true);
+ $(that.wrapSelector('#x_end')).prop('disabled', true);
+ $(that.wrapSelector('#y')).prop('disabled', true);
+ $(that.wrapSelector('#z')).prop('disabled', true);
+ $(that.wrapSelector('#values')).prop('disabled', true);
+ $(that.wrapSelector('#names')).prop('disabled', true);
+ $(that.wrapSelector('#parents')).prop('disabled', true);
+ $(that.wrapSelector('#color')).prop('disabled', true);
+ }
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ $(page).find('.pt-option').hide();
+ if (this.state.chartType === 'density_heatmap'
+ || this.state.chartType === 'density_contour') {
+ // show x, y, z
+ $(page).find('#x').closest('.pt-option').show();
+ $(page).find('#y').closest('.pt-option').show();
+ $(page).find('#z').closest('.pt-option').show();
+ if (this.state.chartType === 'density_contour') {
+ $(page).find('#color').closest('.pt-option').show();
+ }
+ }
+ else if (this.state.chartType === 'timeline') {
+ // show x_start, x_end, y
+ $(page).find('#x_start').closest('.pt-option').show();
+ $(page).find('#x_end').closest('.pt-option').show();
+ $(page).find('#y').closest('.pt-option').show();
+ $(page).find('#color').closest('.pt-option').show();
+ }
+ else if (this.state.chartType === 'pie'
+ || this.state.chartType === 'funnel_area') {
+ // show values, names
+ $(page).find('#values').closest('.pt-option').show();
+ $(page).find('#names').closest('.pt-option').show();
+ $(page).find('#color').closest('.pt-option').show();
+ }
+ else if (this.state.chartType === 'sunburst'
+ || this.state.chartType === 'treemap'
+ || this.state.chartType === 'icicle') {
+ // show values, names, parents
+ $(page).find('#values').closest('.pt-option').show();
+ $(page).find('#names').closest('.pt-option').show();
+ $(page).find('#color').closest('.pt-option').show();
+ $(page).find('#parents').closest('.pt-option').show();
+ }
+ else {
+ // show x, y
+ $(page).find('#x').closest('.pt-option').show();
+ $(page).find('#y').closest('.pt-option').show();
+ $(page).find('#color').closest('.pt-option').show();
+ }
+ $(page).find('#sort').closest('.pt-option').show();
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ let that = this;
+
+ // Add style
+ $(this.wrapSelector('.vp-popup-body-top-bar')).css({
+ 'position': 'absolute',
+ 'left': 'calc(50% - 250px)'
+ });
+ $(this.wrapSelector('.vp-popup-codeview-box')).css({
+ 'height': '200px'
+ });
+
+ // load code tab - code mirror
+ let userCodeKey = 'userCode';
+ let userCodeTarget = this.wrapSelector('#' + userCodeKey);
+ this.codeArea = this.initCodemirror({
+ key: userCodeKey,
+ selector: userCodeTarget,
+ events: [{
+ key: 'blur',
+ callback: function(instance, evt) {
+ // save its state
+ instance.save();
+ that.state[userCodeKey] = $(userCodeTarget).val();
+ // refresh preview
+ that.loadPreview();
+ }
+ }]
+ });
+
+ this.loadPreview();
+ }
+
+ loadPreview() {
+ let that = this;
+ let code = this.generateCode(true);
+
+ that.checkAndRunModules(true).then(function() {
+ // show variable information on clicking variable
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (msg.content.data) {
+ var textResult = msg.content.data["text/plain"];
+ var htmlResult = msg.content.data["text/html"];
+ var imgResult = msg.content.data["image/png"];
+
+ $(that.wrapSelector('#vp_ptPreview')).html('');
+ if (htmlResult != undefined) {
+ // 1. HTML tag
+ $(that.wrapSelector('#vp_ptPreview')).append(htmlResult);
+ } else if (imgResult != undefined) {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $(that.wrapSelector('#vp_ptPreview')).append(imgTag);
+ } else if (textResult != undefined) {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(textResult);
+ $(that.wrapSelector('#vp_ptPreview')).html(preTag);
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ $(that.wrapSelector('#vp_ptPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ $(that.wrapSelector('#vp_ptPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ });
+ });
+ }
+
+ generateInstallCode() {
+ return ['!pip install plotly'];
+ }
+
+ generateImportCode() {
+ var code = new com_String();
+ code.appendLine('import plotly.express as px'); // need to be installed
+ code.appendLine('import plotly');
+ code.append('plotly.offline.init_notebook_mode(connected=True)');
+ return [code.toString()];
+ }
+
+ generateCode(preview=false) {
+ /**
+ * Plotly is not showing sometimes...
+ * import plotly
+ * plotly.offline.init_notebook_mode(connected=True)
+ */
+ let {
+ chartType,
+ data, x, y, color, setXY, sort,
+ userOption, userCode,
+ title, x_label, y_label
+ } = this.state;
+ let code = new com_String();
+ let config = this.chartConfig[chartType];
+
+ let etcOptionCode = [];
+ // add title
+ if (title != '') {
+ etcOptionCode.push(com_util.formatString("title='{0}'", title));
+ }
+ let labelOptions = [];
+ // add x_label
+ if (x_label != '') {
+ if (setXY === true) {
+ // replace 'x' to x_label
+ labelOptions.push(com_util.formatString("'x': '{0}'", x_label));
+ } else {
+ // if x is selected
+ if (x != '') {
+ // replace x column name to x_label
+ labelOptions.push(com_util.formatString("{0}: '{1}'", x, x_label));
+ } else {
+ // replace 'index' to x_label
+ labelOptions.push(com_util.formatString("'index': '{0}'", x_label));
+ }
+ }
+ }
+ // add y_label
+ if (y_label != '') {
+ if (setXY === true) {
+ // replace 'y' to y_label
+ labelOptions.push(com_util.formatString("'y': '{0}'", y_label));
+ } else {
+ // if y is selected
+ if (y != '') {
+ // replace y column name to y_label
+ labelOptions.push(com_util.formatString("{0}: '{1}'", y, y_label));
+ } else {
+ // replace 'index' to y_label
+ labelOptions.push(com_util.formatString("'index': '{0}'", y_label));
+ }
+ }
+ }
+ if (labelOptions.length > 0) {
+ etcOptionCode.push(com_util.formatString("labels={ {0} }", labelOptions.join(', ')));
+ }
+ // add user option
+ if (userOption != '') {
+ etcOptionCode.push(userOption);
+ }
+
+ if (preview === true) {
+ // set preview size
+ let width = 450;
+ let height = 400;
+ // let width = $(this.wrapSelector('#vp_ptPreview')).width();
+ // let height = $(this.wrapSelector('#vp_ptPreview')).height();
+ // console.log(width, height);
+ etcOptionCode.push(com_util.formatString('width={0}, height={1}', width, height));
+
+ // no auto-import for preview
+ this.config.checkModules = [];
+ } else {
+ this.config.checkModules = ['px'];
+ }
+
+ let generatedCode = com_generator.vp_codeGenerator(this, config, this.state
+ , etcOptionCode.length > 0? ', ' + etcOptionCode.join(', '): '');
+ code.appendFormatLine("fig = {0}", generatedCode);
+
+ // sort code
+ if (sort && sort != '') {
+ code.appendFormatLine("fig.update_xaxes(categoryorder='{0}')", sort);
+ }
+
+ if (userCode && userCode != '') {
+ code.appendLine(userCode);
+ }
+ code.append('fig.show()');
+
+ return code.toString();
+ }
+ }
+
+ return Plotly;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_visualize/Seaborn.js b/visualpython/js/m_visualize/Seaborn.js
new file mode 100644
index 00000000..bea6cfd1
--- /dev/null
+++ b/visualpython/js/m_visualize/Seaborn.js
@@ -0,0 +1,1128 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : Seaborn.js
+ * Author : Black Logic
+ * Note : Visualization > Seaborn
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 03. 21
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] Seaborn
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_visualize/seaborn.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_visualize/seaborn'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_generatorV2',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/com_interface',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/VarSelector2',
+ 'vp_base/data/m_visualize/seabornLibrary',
+ 'vp_base/js/com/component/DataSelector'
+], function(chartHTml, chartCss, com_String, com_generator, com_util, com_interface, PopupComponent, SuggestInput, VarSelector2, SEABORN_LIBRARIES, DataSelector) {
+
+ class Seaborn extends PopupComponent {
+ _init() {
+ super._init();
+
+ this.config.dataview = false;
+ this.config.size = { width: 1064, height: 550 };
+ this.config.autoScroll = false;
+ this.config.checkModules = ['plt', 'sns'];
+ this.config.docs = 'https://seaborn.pydata.org/index.html';
+
+ this.state = {
+ chartType: 'scatterplot',
+ figWidth: '',
+ figHeight: '',
+ figRow: 0,
+ figColumn: 0,
+ shareX: false,
+ shareY: false,
+ setXY: false,
+ data: '',
+ x: '',
+ y: '',
+ hue: '',
+ bins: '',
+ kde: '',
+ stat: '',
+ showValues: false,
+ showValuesPrecision: '',
+ errorbar: '',
+ sortBy: 'y',
+ sortType: '',
+ sortHue: '',
+ sortHueText: true,
+ // axes options
+ x_limit_from: '',
+ x_limit_to: '',
+ y_limit_from: '',
+ y_limit_to: '',
+ xticks: '',
+ xticks_label: '',
+ xticks_rotate: '',
+ removeXticks: false,
+ yticks: '',
+ yticks_label: '',
+ yticks_rotate: '',
+ removeYticks: false,
+ // info options
+ title: '',
+ x_label: '',
+ y_label: '',
+ legendPos: '',
+ // style options
+ useColor: false,
+ color: '#000000',
+ useGrid: '',
+ gridColor: '#000000',
+ markerStyle: '',
+ // code option
+ userCode: '',
+ // preview options
+ useSampling: true,
+ sampleCount: 30,
+ autoRefresh: true,
+ ...this.state
+ }
+
+ this.chartConfig = SEABORN_LIBRARIES;
+ this.chartTypeList = {
+ 'Relational': [ 'scatterplot', 'lineplot' ],
+ 'Distributions': [ 'histplot', 'kdeplot', 'rugplot' ],
+ 'Categorical': [ 'stripplot', 'swarmplot', 'boxplot', 'violinplot', 'pointplot', 'barplot', 'countplot' ],
+ 'Axes-level': [ 'heatmap' ],
+ }
+
+ this.legendPosList = [
+ {label: 'Select option...', value: ''},
+ {label: 'best', value: 'best'},
+ {label: 'upper right', value: 'upper right'},
+ {label: 'upper left', value: 'upper left'},
+ {label: 'lower left', value: 'lower left'},
+ {label: 'lower right', value: 'lower right'},
+ {label: 'center left', value: 'center left'},
+ {label: 'center right', value: 'center right'},
+ {label: 'lower center', value: 'lower center'},
+ {label: 'upper center', value: 'upper center'},
+ {label: 'center', value: 'center'},
+ ];
+
+ this.markerList = [
+ // 'custom': { label: 'Custom', value: 'marker' },
+ { label: 'Select option...', value: '', title: 'select marker style'},
+ { label: '.', value: '.', title: 'point' },
+ { label: ',', value: ',', title: 'pixel' },
+ { label: 'o', value: 'o', title: 'circle' },
+ { label: '▼', value: 'v', title: 'triangle_down' },
+ { label: '▲', value: '^', title: 'triangle_up' },
+ { label: '◀', value: '<', title: 'triangle_left' },
+ { label: '▶', value: '>', title: 'triangle_right' },
+ { label: '┬', value: '1', title: 'tri_down' },
+ { label: '┵', value: '2', title: 'tri_up' },
+ { label: '┤', value: '3', title: 'tri_left' },
+ { label: '├', value: '4', title: 'tri_right' },
+ { label: 'octagon', value: '8', title: 'octagon' },
+ { label: 'square', value: 's', title: 'square' },
+ { label: 'pentagon', value: 'p', title: 'pentagon' },
+ { label: 'filled plus', value: 'P', title: 'plus (filled)' },
+ { label: 'star', value: '*', title: 'star' },
+ { label: 'hexagon1', value: 'h', title: 'hexagon1' },
+ { label: 'hexagon2', value: 'H', title: 'hexagon2' },
+ { label: 'plus', value: '+', title: 'plus' },
+ { label: 'x', value: 'x', title: 'x' },
+ { label: 'filled x', value: 'X', title: 'x (filled)' },
+ { label: 'diamond', value: 'D', title: 'diamond' },
+ { label: 'thin diamond', value: 'd', title: 'thin_diamond' }
+ ]
+
+ this.statList = [
+ { label: 'Select option...', value: '' },
+ { label: 'count', value: "'count'" },
+ { label: 'frequency', value: "'frequency'" },
+ { label: 'density', value: "'density'" },
+ { label: 'probability', value: "'probability'" },
+ { label: 'proportion', value: "'proportion'" },
+ { label: 'percent', value: "'percent'" }
+ ];
+ }
+
+ _bindEvent() {
+ let that = this;
+
+ super._bindEvent();
+
+ // setting popup
+ $(this.wrapSelector('#chartSetting')).on('click', function() {
+ // show popup box
+ that.openInnerPopup('Chart Setting');
+ });
+
+ // check create subplots
+ $(this.wrapSelector('#createSubplots')).on('change', function() {
+ let checked = $(this).prop('checked');
+ // toggle figure option box
+ if (checked) {
+ $(that.wrapSelector('#subplotBox')).show();
+ } else {
+ $(that.wrapSelector('#subplotBox')).hide();
+ }
+ });
+
+ // create subplots
+ $(this.wrapSelector('#createSubplotsBtn')).on('click', function() {
+ // TODO:
+ });
+
+ // change tab
+ $(this.wrapSelector('.vp-tab-item')).on('click', function() {
+ let level = $(this).parent().data('level');
+ let type = $(this).data('type'); // data / info / element / figure
+
+ $(that.wrapSelector(com_util.formatString('.vp-tab-bar.{0} .vp-tab-item', level))).removeClass('vp-focus');
+ $(this).addClass('vp-focus');
+
+ $(that.wrapSelector(com_util.formatString('.vp-tab-page-box.{0} > .vp-tab-page', level))).hide();
+ $(that.wrapSelector(com_util.formatString('.vp-tab-page[data-type="{0}"]', type))).show();
+ });
+
+ // change chart type
+ $(this.wrapSelector('#chartType')).on('change', function() {
+ // add bins to histplot
+ let chartType = $(this).val();
+ $(that.wrapSelector('.sb-option')).hide();
+ if (chartType == 'histplot') {
+ $(that.wrapSelector('#bins')).closest('.sb-option').show();
+ $(that.wrapSelector('#kde')).closest('.sb-option').show();
+ $(that.wrapSelector('#stat')).closest('.sb-option').show();
+ } else if (chartType == 'barplot') {
+ $(that.wrapSelector('#orient')).closest('.sb-option').show();
+ $(that.wrapSelector('#showValues')).closest('.sb-option').show();
+ $(that.wrapSelector('#errorbar')).closest('.sb-option').show();
+ if (that.state.setXY === false) {
+ if (that.state.x !== '' && that.state.y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ }
+ if (that.state.hue !== '') {
+ $(that.wrapSelector('#sortHue')).closest('.sb-option').show();
+ }
+ }
+ } else if (chartType == 'countplot') {
+ $(that.wrapSelector('#showValues')).closest('.sb-option').show();
+ if (that.state.setXY === false) {
+ if (that.state.x !== '' || that.state.y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ }
+ if (that.state.hue !== '') {
+ $(that.wrapSelector('#sortHue')).closest('.sb-option').show();
+ }
+ }
+ } else if (chartType == 'heatmap') {
+ $(that.wrapSelector('#annot')).closest('.sb-option').show();
+ } else if (chartType === 'lineplot') {
+ $(that.wrapSelector('#errorbar')).closest('.sb-option').show();
+ }
+ });
+
+ // use data or not
+ $(this.wrapSelector('#setXY')).on('change', function() {
+ let setXY = $(this).prop('checked');
+ if (setXY == false) {
+ // set Data
+ $(that.wrapSelector('#data')).prop('disabled', false);
+
+ $(that.wrapSelector('#x')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#y')).closest('.vp-ds-box').replaceWith(' ');
+ $(that.wrapSelector('#hue')).closest('.vp-ds-box').replaceWith(' ');
+ } else {
+ // set X Y indivisually
+ // disable data selection
+ $(that.wrapSelector('#data')).prop('disabled', true);
+ $(that.wrapSelector('#data')).val('');
+ that.state.data = '';
+ that.state.x = '';
+ that.state.y = '';
+ that.state.hue = '';
+
+ let dataSelectorX = new DataSelector({ pageThis: that, id: 'x' });
+ $(that.wrapSelector('#x')).replaceWith(dataSelectorX.toTagString());
+
+ let dataSelectorY = new DataSelector({ pageThis: that, id: 'y' });
+ $(that.wrapSelector('#y')).replaceWith(dataSelectorY.toTagString());
+
+ let dataSelectorHue = new DataSelector({ pageThis: that, id: 'hue' });
+ $(that.wrapSelector('#hue')).replaceWith(dataSelectorHue.toTagString());
+
+ // FIXME: hide sort values for barplot/countplot
+ if (that.state.chartType == 'barplot' || that.state.chartType == 'countplot') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').hide();
+ $(that.wrapSelector('#sortHue')).closest('.sb-option').hide();
+ }
+
+ }
+ });
+
+ // change x, y
+ $(document).off('change', this.wrapSelector('#x'));
+ $(document).on('change', this.wrapSelector('#x'), function() {
+ let { chartType, y, setXY } = that.state;
+ let x = $(this).val();
+ if (setXY === false) {
+ if (chartType == 'barplot') {
+ if (x !== '' && y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ } else {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').hide();
+ }
+ } else if (chartType == 'countplot') {
+ if (x !== '' || y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ } else {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').hide();
+ }
+ }
+ }
+ });
+
+ $(document).off('change', this.wrapSelector('#y'));
+ $(document).on('change', this.wrapSelector('#y'), function() {
+ let { chartType, x, setXY } = that.state;
+ let y = $(this).val();
+ if (setXY === false) {
+ if (chartType == 'barplot') {
+ if (x !== '' && y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ } else {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').hide();
+ }
+ } else if (chartType == 'countplot') {
+ if (x !== '' || y !== '') {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').show();
+ } else {
+ $(that.wrapSelector('#sortBy')).closest('.sb-option').hide();
+ }
+ }
+ }
+ });
+
+ // change hue
+ $(document).off('change', this.wrapSelector('#hue'));
+ $(document).on('change', this.wrapSelector('#hue'), function() {
+ let { chartType, data } = that.state;
+ let hue = $(this).val();
+ if (hue !== '') {
+ if (chartType == 'barplot' || chartType == 'countplot') {
+ let colDtype = $(that.wrapSelector('#hue')).find('option:selected').data('type');
+ // get result and load column list
+ vpKernel.getColumnCategory(data, hue).then(function (resultObj) {
+ let { result } = resultObj;
+ try {
+ var category = JSON.parse(result);
+ if (category && category.length > 0 && colDtype == 'object') {
+ // if it's categorical column and its dtype is object, check 'Text' as default
+ $(that.wrapSelector('#sortHueText')).prop('checked', true);
+ that.state.sortHueText = true;
+ } else {
+ $(that.wrapSelector('#sortHueText')).prop('checked', false);
+ that.state.sortHueText = false;
+ }
+ $(that.wrapSelector('#sortHue')).replaceWith(that.templateForHueCondition(category, colDtype));
+ } catch {
+ $(that.wrapSelector('#sortHueText')).prop('checked', false);
+ that.state.sortHueText = false;
+
+ $(that.wrapSelector('#sortHue')).replaceWith(that.templateForHueCondition([], colDtype));
+ }
+ });
+ }
+ $(that.wrapSelector('#sortHue')).closest('.sb-option').show();
+ } else {
+ $(that.wrapSelector('#sortHue')).closest('.sb-option').hide();
+ }
+ });
+
+ // show values or not
+ $(this.wrapSelector('#showValues')).on('change', function() {
+ let checked = $(this).prop('checked');
+ if (checked === true) {
+ $(that.wrapSelector('#showValuesPrecision')).attr('disabled', false);
+ } else {
+ $(that.wrapSelector('#showValuesPrecision')).attr('disabled', true);
+ }
+ });
+
+ // use color or not
+ $(this.wrapSelector('#useColor')).on('change', function() {
+ that.state.useColor = $(this).prop('checked');
+ $(that.wrapSelector('#color')).prop('disabled', $(this).prop('checked') == false);
+ });
+
+ // axes - ticks location
+ $(this.wrapSelector('#xticks')).on('change', function() {
+ let val = $(this).val();
+ if (val !== '') {
+ // enable xticks_label
+ $(that.wrapSelector('#xticks_label')).attr('readonly', false);
+ } else {
+ // disable xticks_label
+ $(that.wrapSelector('#xticks_label')).attr('readonly', true);
+ }
+ });
+ $(this.wrapSelector('#yticks')).on('change', function() {
+ let val = $(this).val();
+ if (val !== '') {
+ // enable yticks_label
+ $(that.wrapSelector('#yticks_label')).attr('readonly', false);
+ } else {
+ // disable yticks_label
+ $(that.wrapSelector('#yticks_label')).attr('readonly', true);
+ }
+ });
+
+ // axes - ticks label: inform user to type location option to use label
+ $(this.wrapSelector('#xticks_label')).on('click', function() {
+ if ($(that.wrapSelector('#xticks')).val() === '') {
+ $(that.wrapSelector('#xticks')).focus();
+ }
+ });
+ $(this.wrapSelector('#yticks_label')).on('click', function() {
+ if ($(that.wrapSelector('#yticks')).val() === '') {
+ $(that.wrapSelector('#yticks')).focus();
+ }
+ });
+
+ // preview refresh
+ $(this.wrapSelector('#previewRefresh')).on('click', function() {
+ that.loadPreview();
+ });
+ // auto refresh
+ $(document).off('change', this.wrapSelector('.vp-state'));
+ $(document).on('change', this.wrapSelector('.vp-state'), function(evt) {
+ that._saveSingleState($(this)[0]);
+ if (that.state.autoRefresh) {
+ that.loadPreview();
+ }
+ evt.stopPropagation();
+ });
+ }
+
+ templateForBody() {
+ let page = $(chartHTml);
+
+ let that = this;
+
+ // chart types
+ let chartTypeTag = new com_String();
+ Object.keys(this.chartTypeList).forEach(chartCategory => {
+ let chartOptionTag = new com_String();
+ that.chartTypeList[chartCategory].forEach(opt => {
+ let optConfig = that.chartConfig[opt];
+ let selectedFlag = '';
+ if (opt == that.state.chartType) {
+ selectedFlag = 'selected';
+ }
+ chartOptionTag.appendFormatLine('{2} ',
+ opt, selectedFlag, opt);
+ })
+ chartTypeTag.appendFormatLine('{1} ',
+ chartCategory, chartOptionTag.toString());
+ });
+ $(page).find('#chartType').html(chartTypeTag.toString());
+
+ // chart variable
+ let dataSelector = new DataSelector({
+ type: 'data',
+ pageThis: this,
+ id: 'data',
+ select: function(value, dtype) {
+ that.state.data = value;
+ that.state.dtype = dtype;
+
+ if (dtype == 'DataFrame') {
+ $(that.wrapSelector('#x')).prop('disabled', false);
+ $(that.wrapSelector('#y')).prop('disabled', false);
+ $(that.wrapSelector('#hue')).prop('disabled', false);
+
+ // bind column source using selected dataframe
+ com_generator.vp_bindColumnSource(that, 'data', ['x', 'y', 'hue'], 'select', true, true);
+ } else {
+ $(that.wrapSelector('#x')).prop('disabled', true);
+ $(that.wrapSelector('#y')).prop('disabled', true);
+ $(that.wrapSelector('#hue')).prop('disabled', true);
+ }
+ },
+ finish: function(value, dtype) {
+ that.state.dtype = dtype;
+
+ if (dtype == 'DataFrame') {
+ $(that.wrapSelector('#x')).prop('disabled', false);
+ $(that.wrapSelector('#y')).prop('disabled', false);
+ $(that.wrapSelector('#hue')).prop('disabled', false);
+
+ // bind column source using selected dataframe
+ com_generator.vp_bindColumnSource(that, 'data', ['x', 'y', 'hue'], 'select', true, true);
+ } else {
+ $(that.wrapSelector('#x')).prop('disabled', true);
+ $(that.wrapSelector('#y')).prop('disabled', true);
+ $(that.wrapSelector('#hue')).prop('disabled', true);
+ }
+ }
+ });
+ $(page).find('#data').replaceWith(dataSelector.toTagString());
+
+ // legend position
+ let legendPosTag = new com_String();
+ this.legendPosList.forEach(pos => {
+ let selectedFlag = '';
+ if (pos.value == that.state.legendPos) {
+ selectedFlag = 'selected';
+ }
+ legendPosTag.appendFormatLine('{2}{3} ',
+ pos.value, selectedFlag, pos.label, pos.value == 'best'?' (default)':'');
+ });
+ $(page).find('#legendPos').html(legendPosTag.toString());
+
+ // marker style
+ let markerTag = new com_String();
+ this.markerList.forEach(marker => {
+ let selectedFlag = '';
+ if (marker.value == that.state.markerStyle) {
+ selectedFlag = 'selected';
+ }
+ markerTag.appendFormatLine('{3} ',
+ marker.value, marker.title, selectedFlag, marker.label);
+ });
+ $(page).find('#markerStyle').html(markerTag.toString());
+
+ // x, yticks label check
+ if (this.state.xticks && this.state.xticks !== '') {
+ $(page).find('#xticks_label').prop('readonly', false);
+ }
+ if (this.state.yticks && this.state.yticks !== '') {
+ $(page).find('#yticks_label').prop('readonly', false);
+ }
+
+ // stat options
+ let statTag = new com_String();
+ this.statList.forEach(stat => {
+ let selectedFlag = '';
+ if (stat.value == that.state.stat) {
+ selectedFlag = 'selected';
+ }
+ statTag.appendFormatLine('{2} ',
+ stat.value, selectedFlag, stat.label);
+ });
+ $(page).find('#stat').html(statTag.toString());
+
+ // preview sample count
+ let sampleCountList = [30, 50, 100, 300, 500, 700, 1000];
+ let sampleCountTag = new com_String();
+ sampleCountList.forEach(cnt => {
+ let selectedFlag = '';
+ if (cnt == that.state.sampleCount) {
+ selectedFlag = 'selected';
+ }
+ sampleCountTag.appendFormatLine('{2} ',
+ cnt, selectedFlag, cnt);
+ });
+ $(page).find('#sampleCount').html(sampleCountTag.toString());
+
+ // set errorbar list
+ var vpErrorbarSuggest = new SuggestInput();
+ vpErrorbarSuggest.setComponentID('errorbar');
+ vpErrorbarSuggest.addClass('vp-input vp-state');
+ vpErrorbarSuggest.setPlaceholder("('ci', 95)");
+ vpErrorbarSuggest.setValue(this.state.errorbar);
+ vpErrorbarSuggest.setSuggestList(["None", "'ci'", "'pi'", "'sd'", "'se'"]);
+ $(page).find('#errorbar').replaceWith(vpErrorbarSuggest.toTagString());
+
+ // data options depend on chart type
+ $(page).find('.sb-option').hide();
+ if (this.state.chartType == 'histplot') {
+ $(page).find('#bins').closest('.sb-option').show();
+ $(page).find('#kde').closest('.sb-option').show();
+ $(page).find('#stat').closest('.sb-option').show();
+ } else if (this.state.chartType == 'barplot') {
+ $(page).find('#orient').closest('.sb-option').show();
+ $(page).find('#showValues').closest('.sb-option').show();
+ $(page).find('#errorbar').closest('.sb-option').show();
+ if (this.state.setXY === false) {
+ if (this.state.x !== '' && this.state.y !== '') {
+ $(page).find('#sortBy').closest('.sb-option').show();
+ }
+ if (this.state.hue !== '') {
+ $(page).find('#sortHue').closest('.sb-option').show();
+ }
+ }
+ } else if (this.state.chartType == 'countplot') {
+ $(page).find('#showValues').closest('.sb-option').show();
+ if (this.state.setXY === false) {
+ if (this.state.x !== '' || this.state.y !== '') {
+ $(page).find('#sortBy').closest('.sb-option').show();
+ }
+ if (this.state.hue !== '') {
+ $(page).find('#sortHue').closest('.sb-option').show();
+ }
+ }
+ } else if (this.state.chartType == 'heatmap') {
+ $(page).find('#annot').closest('.sb-option').show();
+ } else if (this.state.chartType === 'lineplot') {
+ $(page).find('#errorbar').closest('.sb-option').show();
+ }
+
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ } else {
+ // if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ templateForSettingBox() {
+ return `
+
+ `;
+ }
+
+ render() {
+ super.render();
+
+ //================================================================
+ // Chart Setting Popup
+ //================================================================
+ // set inner popup content (chart setting)
+ $(this.wrapSelector('.vp-inner-popup-body')).html(this.templateForSettingBox());
+
+ // set inner button
+ $(this.wrapSelector('.vp-inner-popup-button[data-type="ok"]')).text('Run');
+
+ // set size
+ $(this.wrapSelector('.vp-inner-popup-box')).css({ width: 400, height: 260});
+
+ // set code view size
+ $(this.wrapSelector('.vp-popup-codeview-box')).css({
+ 'height': '200px'
+ });
+
+ this.bindSettingBox();
+
+ // Load chart options
+ if (this.state.setXY) {
+ // disable data selection
+ $(this.wrapSelector('#data')).prop('disabled', true);
+
+ let dataSelectorX = new DataSelector({ pageThis: this, id: 'x' });
+ $(this.wrapSelector('#x')).replaceWith(dataSelectorX.toTagString());
+
+ let dataSelectorY = new DataSelector({ pageThis: this, id: 'y' });
+ $(this.wrapSelector('#y')).replaceWith(dataSelectorY.toTagString());
+
+ let dataSelectorHue = new DataSelector({ pageThis: this, id: 'hue' });
+ $(this.wrapSelector('#hue')).replaceWith(dataSelectorHue.toTagString());
+ } else {
+ if (this.state.dtype == 'DataFrame') {
+ $(this.wrapSelector('#x')).prop('disabled', false);
+ $(this.wrapSelector('#y')).prop('disabled', false);
+ $(this.wrapSelector('#hue')).prop('disabled', false);
+
+ // bind column source using selected dataframe
+ com_generator.vp_bindColumnSource(this, 'data', ['x', 'y', 'hue'], 'select', true, true);
+ } else {
+ $(this.wrapSelector('#x')).prop('disabled', true);
+ $(this.wrapSelector('#y')).prop('disabled', true);
+ $(this.wrapSelector('#hue')).prop('disabled', true);
+ }
+ }
+
+ // load code tab - code mirror
+ let that = this;
+ let userCodeKey = 'userCode1';
+ let userCodeTarget = this.wrapSelector('#' + userCodeKey);
+ this.codeArea = this.initCodemirror({
+ key: userCodeKey,
+ selector: userCodeTarget,
+ events: [{
+ key: 'blur',
+ callback: function(instance, evt) {
+ // save its state
+ instance.save();
+ that.state[userCodeKey] = $(userCodeTarget).val();
+ // refresh preview
+ that.loadPreview();
+ }
+ }]
+ });
+
+ this.loadPreview();
+ }
+
+ templateForHueCondition(category, dtype='object') {
+ var vpCondSuggest = new SuggestInput();
+ vpCondSuggest.setComponentID('sortHue');
+ vpCondSuggest.addClass('vp-input vp-state');
+ vpCondSuggest.setPlaceholder('Type hue condition');
+ if (category && category.length > 0) {
+ vpCondSuggest.setPlaceholder((dtype=='object'?'Categorical':dtype) + " dtype");
+ vpCondSuggest.setSuggestList(function () { return category; });
+ vpCondSuggest.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ vpCondSuggest.setNormalFilter(false);
+ } else {
+ vpCondSuggest.setPlaceholder(dtype==''?'Value':(dtype + " dtype"));
+ }
+ return vpCondSuggest.toTagString();
+ }
+
+ bindSettingBox() {
+ //====================================================================
+ // Stylesheet suggestinput
+ //====================================================================
+ var stylesheetTag = $(this.wrapSelector('#styleSheet'));
+ // search available stylesheet list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('import json');
+ code.append(`print(json.dumps([{ 'label': s, 'value': s } for s in plt.style.available]))`);
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available stylesheet list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('styleSheet');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('style name');
+ // suggestInput.setValue('seaborn-darkgrid'); // set default (seaborn-darkgrid)
+ // suggestInput.setNormalFilter(false);
+ $(stylesheetTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ //====================================================================
+ // System font suggestinput
+ //====================================================================
+ var fontFamilyTag = $(this.wrapSelector('#fontName'));
+ // search system font list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import json');
+ code.appendLine("import matplotlib.font_manager as fm");
+ code.appendLine("_ttflist = fm.fontManager.ttflist");
+ code.append("print(json.dumps([{'label': f.name, 'value': f.name } for f in _ttflist]))");
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available font list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('fontName');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('font name');
+ // suggestInput.setNormalFilter(false);
+ $(fontFamilyTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ let that = this;
+ // setting popup - set default
+ $(this.wrapSelector('#setDefault')).on('change', function() {
+ let checked = $(this).prop('checked');
+
+ if (checked) {
+ // disable input
+ $(that.wrapSelector('.vp-chart-setting-body input')).prop('disabled', true);
+ } else {
+ // enable input
+ $(that.wrapSelector('.vp-chart-setting-body input')).prop('disabled', false);
+ }
+ });
+ }
+
+ handleInnerOk() {
+ // generateImportCode
+ var code = this.generateImportCode();
+ // DEPRECATED: no longer save to block as default
+ // create block and run it
+ // $('#vp_wrapper').trigger({
+ // type: 'create_option_page',
+ // blockType: 'block',
+ // menuId: 'lgExe_code',
+ // menuState: { taskState: { code: code } },
+ // afterAction: 'run'
+ // });
+ com_interface.insertCell('code', code, true, 'Visualization > Seaborn');
+
+ this.closeInnerPopup();
+
+ // load preview
+ this.loadPreview();
+ }
+
+ loadPreview() {
+ let that = this;
+ let code = this.generateCode(true);
+
+ that.checkAndRunModules(true).then(function() {
+ // show variable information on clicking variable
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (msg.content.data) {
+ var textResult = msg.content.data["text/plain"];
+ var htmlResult = msg.content.data["text/html"];
+ var imgResult = msg.content.data["image/png"];
+
+ $(that.wrapSelector('#chartPreview')).html('');
+ if (htmlResult != undefined) {
+ // 1. HTML tag
+ $(that.wrapSelector('#chartPreview')).append(htmlResult);
+ } else if (imgResult != undefined) {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $(that.wrapSelector('#chartPreview')).append(imgTag);
+ } else if (textResult != undefined) {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(textResult);
+ $(that.wrapSelector('#chartPreview')).html(preTag);
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ }
+ $(that.wrapSelector('#chartPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue, msg.content.detail);
+ }
+ $(that.wrapSelector('#chartPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ });
+ });
+ }
+
+ generateImportCode () {
+ var code = new com_String();
+
+ // get parameters
+ let setDefault = $(this.wrapSelector('#setDefault')).prop('checked');
+ if (setDefault == true) {
+ code.appendLine('from matplotlib import rcParams, rcParamsDefault');
+ code.append('rcParams.update(rcParamsDefault)');
+ } else {
+ var figWidth = $(this.wrapSelector('#figureWidth')).val();
+ var figHeight = $(this.wrapSelector('#figureHeight')).val();
+ var styleName = $(this.wrapSelector('#styleSheet')).val();
+ var fontName = $(this.wrapSelector('#fontName')).val();
+ var fontSize = $(this.wrapSelector('#fontSize')).val();
+
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.appendLine('%matplotlib inline');
+ code.appendLine('import seaborn as sns');
+ if (styleName && styleName.length > 0) {
+ code.appendFormatLine("plt.style.use('{0}')", styleName);
+ }
+ code.appendFormatLine("plt.rc('figure', figsize=({0}, {1}))", figWidth, figHeight);
+ code.appendLine();
+
+ code.appendLine('from matplotlib import rcParams');
+ if (fontName && fontName.length > 0) {
+ code.appendFormatLine("rcParams['font.family'] = '{0}'", fontName);
+ }
+ if (fontSize && fontSize.length > 0) {
+ code.appendFormatLine("rcParams['font.size'] = {0}", fontSize);
+ }
+ code.append("rcParams['axes.unicode_minus'] = False");
+ }
+
+ return [code.toString()];
+ }
+
+ generateCode(preview=false) {
+ let {
+ chartType, data, x, y, setXY, hue, orient, kde, stat,
+ showValues, showValuesPrecision, errorbar,
+ sortType, sortBy, sortHue, sortHueText,
+ userOption='',
+ x_limit_from, x_limit_to, y_limit_from, y_limit_to,
+ xticks, xticks_label, xticks_rotate, removeXticks,
+ yticks, yticks_label, yticks_rotate, removeYticks,
+ title, x_label, y_label, legendPos,
+ useColor, color, useGrid, gridColor, markerStyle,
+ userCode1,
+ useSampling, sampleCount
+ } = this.state;
+
+ let indent = '';
+ let code = new com_String();
+ let config = this.chartConfig[chartType];
+ let state = JSON.parse(JSON.stringify(this.state));
+
+ // set checkmodules
+ if (preview === true) {
+ // no auto-import for preview
+ this.config.checkModules = [];
+ } else {
+ if (showValues && showValues === true) {
+ this.config.checkModules = ['plt', 'sns', 'np', 'vp_seaborn_show_values'];
+ } else {
+ this.config.checkModules = ['plt', 'sns'];
+ }
+ }
+
+ if (preview === true && useSampling) {
+ // data sampling code for preview
+ // convertedData = data + '.sample(n=' + sampleCount + ', random_state=0)';
+ // convertedData = com_util.formatString('_vp_sample({0}, {1})', data, sampleCount);
+ // replace pre-defined options
+ // generatedCode = generatedCode.replaceAll(data, convertedData);
+ if (setXY) {
+ if (x && x != '') {
+ state.x = com_util.formatString('_vp_sample({0}, {1})', x, sampleCount);
+ }
+ if (y && y != '') {
+ state.y = com_util.formatString('_vp_sample({0}, {1})', y, sampleCount);
+ }
+ if (hue && hue != '') {
+ state.hue = com_util.formatString('_vp_sample({0}, {1})', hue, sampleCount);
+ }
+ } else {
+ if (data && data != '') {
+ state.data = com_util.formatString('_vp_sample({0}, {1})', data, sampleCount);
+ }
+ }
+ }
+
+ let chartCode = new com_String();
+
+ let etcOptionCode = []
+ if (useColor == true && color != '') {
+ etcOptionCode.push(com_util.formatString("color='{0}'", color));
+ }
+ if (markerStyle != '') {
+ // TODO: marker to seaborn argument (ex. marker='+' / markers={'Lunch':'s', 'Dinner':'X'})
+ etcOptionCode.push(com_util.formatString("marker='{0}'", markerStyle));
+ }
+ if (showValues === true && chartType === 'barplot') {
+ // etcOptionCode.push('ci=None'); // changed to errorbar after 0.12 version
+ etcOptionCode.push('errorbar=None');
+ } else {
+ if (chartType === 'barplot' || chartType === 'lineplot') {
+ if (errorbar !== '') {
+ etcOptionCode.push(com_util.formatString("errorbar={0}", errorbar));
+ }
+ }
+ }
+ if (setXY === false && sortType !== '') {
+ let sortCode = '';
+ let sortTypeStr = (sortType === 'descending'? 'ascending=False': 'ascending=True');
+ let sortX = state.x;
+ let sortY = state.y;
+ if (sortBy === 'x') {
+ sortX = state.y;
+ sortY = state.x;
+ }
+ if (chartType === 'barplot' && sortX !== '' && sortY !== '') {
+ if (hue !== '' && sortHue !== '') {
+ sortCode = com_util.formatString("{0}[{1}[{2}]=={3}].groupby({4})[{5}].mean(numeric_only=True).sort_values({6}).index"
+ , state.data, state.data, state.hue, com_util.convertToStr(sortHue, sortHueText), sortX, sortY, sortTypeStr);
+ } else {
+ sortCode = com_util.formatString("{0}.groupby({1})[{2}].mean(numeric_only=True).sort_values({3}).index", state.data, sortX, sortY, sortTypeStr);
+ }
+ } else if (chartType === 'countplot' && (sortX !== '' || sortY !== '')) {
+ let countVar = sortX === ''? sortY: sortX;
+ if (hue !== '' && sortHue !== '') {
+ sortCode = com_util.formatString("{0}[{1}[{2}]=={3}][{4}].value_counts({5}).index"
+ , state.data, state.data, state.hue, com_util.convertToStr(sortHue, sortHueText), countVar, sortTypeStr);
+ } else {
+ sortCode = com_util.formatString("{0}[{1}].value_counts({2}).index", state.data, countVar, sortTypeStr);
+ }
+ }
+
+ if (sortCode != '') {
+ etcOptionCode.push('order=' + sortCode);
+ }
+ }
+
+ // add user option
+ if (userOption != '') {
+ etcOptionCode.push(userOption);
+ }
+
+ let generatedCode = com_generator.vp_codeGenerator(this, config, state
+ , etcOptionCode.length > 0? ', ' + etcOptionCode.join(', '): '');
+
+ // Axes
+ if (x_limit_from != '' && x_limit_to != '') {
+ chartCode.appendFormatLine("plt.xlim(({0}, {1}))", x_limit_from, x_limit_to);
+ }
+ if (y_limit_from != '' && y_limit_to != '') {
+ chartCode.appendFormatLine("plt.ylim(({0}, {1}))", y_limit_from, y_limit_to);
+ }
+ if (legendPos != '') {
+ chartCode.appendFormatLine("plt.legend(loc='{0}')", legendPos);
+ }
+ if (removeXticks === true) {
+ // use empty list to disable xticks
+ chartCode.appendLine("plt.xticks([])");
+ } else {
+ let xticksOptList = [];
+ if (xticks && xticks !== '') {
+ xticksOptList.push('ticks=' + xticks);
+ // Not able to use xticks_label without xticks
+ if (xticks_label && xticks_label != '') {
+ xticksOptList.push('labels=' + xticks_label);
+ }
+ }
+ if (xticks_rotate && xticks_rotate !== '') {
+ xticksOptList.push('rotation=' + xticks_rotate)
+ }
+ // Add option to chart code if available
+ if (xticksOptList.length > 0) {
+ chartCode.appendFormatLine("plt.xticks({0})", xticksOptList.join(', '));
+ }
+ }
+ if (removeYticks === true) {
+ // use empty list to disable yticks
+ chartCode.appendLine("plt.yticks([])");
+ } else {
+ let yticksOptList = [];
+ if (yticks && yticks !== '') {
+ yticksOptList.push('ticks=' + yticks);
+ // Not able to use xticks_label without xticks
+ if (yticks_label && yticks_label != '') {
+ yticksOptList.push('labels=' + yticks_label);
+ }
+ }
+ if (yticks_rotate && yticks_rotate !== '') {
+ yticksOptList.push('rotation=' + yticks_rotate)
+ }
+ // Add option to chart code if available
+ if (yticksOptList.length > 0) {
+ chartCode.appendFormatLine("plt.yticks({0})", yticksOptList.join(', '));
+ }
+ }
+ // Info
+ if (title && title != '') {
+ chartCode.appendFormatLine("plt.title('{0}')", title);
+ }
+ if (x_label && x_label != '') {
+ chartCode.appendFormatLine("plt.xlabel('{0}')", x_label);
+ }
+ if (y_label && y_label != '') {
+ chartCode.appendFormatLine("plt.ylabel('{0}')", y_label);
+ }
+ // Style - Grid
+ // plt.grid(True, axis='x', color='red', alpha=0.5, linestyle='--')
+ let gridCodeList = [];
+ if (useGrid != '') {
+ gridCodeList.push(useGrid);
+ }
+ if (useGrid == 'True' && gridColor != '') {
+ gridCodeList.push(com_util.formatString("color='{0}'", gridColor));
+ }
+ if (gridCodeList.length > 0) {
+ chartCode.appendFormatLine("plt.grid({0})", gridCodeList.join(', '));
+ }
+
+ if (preview === true) {
+ // Ignore warning
+ code.appendLine('import warnings');
+ code.appendLine('with warnings.catch_warnings():');
+ code.appendLine(" warnings.simplefilter('ignore')");
+
+ // set figure size for preview chart
+ let defaultWidth = 8;
+ let defaultHeight = 6;
+ code.appendFormatLine('plt.figure(figsize=({0}, {1}))', defaultWidth, defaultHeight);
+
+ if (showValues && showValues === true) {
+ code.appendLine('ax = ' + generatedCode);
+ code.append("_vp_seaborn_show_values(ax");
+ if (showValuesPrecision !== '') {
+ code.appendFormat(", precision={0}", showValuesPrecision);
+ }
+ code.appendLine(")");
+ } else {
+ code.appendLine(generatedCode);
+ }
+ code.appendLine(chartCode.toString());
+ } else {
+ if (showValues && showValues === true) {
+ code.appendLine('ax = ' + generatedCode);
+ code.appendLine("vp_seaborn_show_values(ax)");
+ } else {
+ code.appendLine(generatedCode);
+ }
+ if (chartCode.length > 0) {
+ code.append(chartCode.toString());
+ }
+ }
+
+ if (userCode1 && userCode1 != '') {
+ code.appendLine(userCode1);
+ }
+
+ code.append('plt.show()');
+
+ // remove last Enter(\n) from code and then run it
+ return code.toString().replace(/\n+$/, "");
+ }
+
+ }
+
+ return Seaborn;
+});
\ No newline at end of file
diff --git a/visualpython/js/m_visualize/WordCloud.js b/visualpython/js/m_visualize/WordCloud.js
new file mode 100644
index 00000000..96ee22a1
--- /dev/null
+++ b/visualpython/js/m_visualize/WordCloud.js
@@ -0,0 +1,378 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : WordCloud.js
+ * Author : Black Logic
+ * Note : Visualization > WordCloud
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2022. 05. 16
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] WordCloud
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('vp_base/html/m_visualize/wordCloud.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/m_visualize/wordCloud'), // INTEGRATION: unified version of css loader
+ 'vp_base/js/com/com_String',
+ 'vp_base/js/com/com_util',
+ 'vp_base/js/com/component/PopupComponent',
+ 'vp_base/js/com/component/SuggestInput',
+ 'vp_base/js/com/component/FileNavigation',
+ 'vp_base/js/com/component/DataSelector'
+], function(wcHTML, wcCss, com_String, com_util, PopupComponent, SuggestInput, FileNavigation, DataSelector) {
+
+ class WordCloud extends PopupComponent {
+ _init() {
+ super._init();
+
+ this.config.size = { width: 1064, height: 550 };
+ this.config.installButton = true;
+ this.config.importButton = true;
+ this.config.dataview = false;
+ this.config.checkModules = ['Counter', 'plt', 'WordCloud'];
+ this.config.docs = 'https://amueller.github.io/word_cloud/references.html';
+
+ this.state = {
+ data: '',
+ useFile: false,
+ encoding: '',
+ wordCount: '200',
+ stopWords: '',
+ fontPath: '',
+ userOption: '',
+ figWidth: '8',
+ figHeight: '20',
+ autoRefresh: true,
+ ...this.state
+ }
+ }
+
+ _bindEvent() {
+ super._bindEvent();
+
+ let that = this;
+ // open file event for data
+ $(this.wrapSelector('#vp_wcOpenFile')).on('click', function() {
+ if (that.state.useFile === true) {
+ let fileNavi = new FileNavigation({
+ type: 'open',
+ extensions: [ 'txt' ],
+ finish: function(filesPath, status, error) {
+ let {file, path} = filesPath[0];
+ that.state.data = path;
+
+ that.state.useFile = true;
+ $(that.wrapSelector('.vp-wc-file-option')).show();
+ $(that.wrapSelector('#useFile')).prop('checked', true);
+ $(that.wrapSelector('#useFile')).trigger('change');
+
+ // set text
+ $(that.wrapSelector('#data')).val(path);
+ $(that.wrapSelector('#data')).trigger('change');
+ }
+ });
+ fileNavi.open();
+ }
+ });
+
+ // use file
+ $(this.wrapSelector('#useFile')).on('change', function() {
+ let checked = $(this).prop('checked');
+ if (checked === true) {
+ $(that.wrapSelector('.vp-wc-file-option')).show();
+ $(that.wrapSelector('#vp_wcOpenFile')).show();
+ } else {
+ $(that.wrapSelector('.vp-wc-file-option')).hide();
+ $(that.wrapSelector('#vp_wcOpenFile')).hide();
+ }
+ });
+
+ // change tab
+ $(this.wrapSelector('.vp-tab-item')).on('click', function() {
+ let type = $(this).data('type'); // data / wordcloud / plot
+
+ $(that.wrapSelector('.vp-tab-bar .vp-tab-item')).removeClass('vp-focus');
+ $(this).addClass('vp-focus');
+
+ $(that.wrapSelector('.vp-tab-page-box > .vp-tab-page')).hide();
+ $(that.wrapSelector(com_util.formatString('.vp-tab-page[data-type="{0}"]', type))).show();
+ });
+
+ // load preview
+ $(document).off('change', this.wrapSelector('.vp-state'));
+ $(document).on('change', this.wrapSelector('.vp-state'), function(evt) {
+ that._saveSingleState($(this)[0]);
+ if (that.state.autoRefresh) {
+ that.loadPreview();
+ }
+ evt.stopPropagation();
+ });
+
+ // preview refresh
+ $(this.wrapSelector('#previewRefresh')).on('click', function() {
+ that.loadPreview();
+ });
+
+ }
+
+ templateForBody() {
+ let page = $(wcHTML);
+
+ if (this.state.useFile == true) {
+ $(page).find('.vp-wc-file-option').show();
+ $(page).find('#vp_wcOpenFile').show();
+ } else {
+ $(page).find('.vp-wc-file-option').hide();
+ $(page).find('#vp_wcOpenFile').hide();
+ }
+
+ let that = this;
+ //================================================================
+ // Load state
+ //================================================================
+ Object.keys(this.state).forEach(key => {
+ let tag = $(page).find('#' + key);
+ let tagName = $(tag).prop('tagName'); // returns with UpperCase
+ let value = that.state[key];
+ if (value == undefined) {
+ return;
+ }
+ switch(tagName) {
+ case 'INPUT':
+ let inputType = $(tag).prop('type');
+ if (inputType == 'text' || inputType == 'number' || inputType == 'hidden') {
+ $(tag).val(value);
+ break;
+ }
+ if (inputType == 'checkbox') {
+ $(tag).prop('checked', value);
+ break;
+ }
+ break;
+ case 'TEXTAREA':
+ case 'SELECT':
+ default:
+ $(tag).val(value);
+ break;
+ }
+ });
+
+ return page;
+ }
+
+ render() {
+ super.render();
+
+ let that = this;
+
+ // Add style
+ $(this.wrapSelector('.vp-popup-body-top-bar')).css({
+ 'position': 'absolute',
+ 'left': 'calc(50% - 250px)'
+ });
+ $(this.wrapSelector('.vp-popup-codeview-box')).css({
+ 'height': '200px'
+ });
+
+ // bind dataSelector to #data
+ let dataSelector = new DataSelector({
+ type: 'data',
+ pageThis: this,
+ id: 'data',
+ required: true,
+ select: function() {
+ that.state.useFile = false;
+ $(that.wrapSelector('#useFile')).prop('checked', false);
+ $(that.wrapSelector('.vp-wc-file-option')).hide();
+ },
+ finish: function() {
+ that.state.useFile = false;
+ $(that.wrapSelector('#useFile')).prop('checked', false);
+ $(that.wrapSelector('.vp-wc-file-option')).hide();
+ }
+ });
+ $(this.wrapSelector('#data')).replaceWith(dataSelector.toTagString());
+
+ // System font suggestinput
+ var fontFamilyTag = $(this.wrapSelector('#fontPath'));
+ // search system font list
+ var code = new com_String();
+ // FIXME: convert it to kernelApi
+ code.appendLine('import json');
+ code.appendLine("import matplotlib.font_manager as fm");
+ code.appendLine("_ttflist = fm.fontManager.ttflist");
+ code.append("print(json.dumps([{'label': f.name, 'value': f.fname.replace('\\\\', '/') } for f in _ttflist]))");
+ vpKernel.execute(code.toString()).then(function(resultObj) {
+ let { result } = resultObj;
+ // get available font list
+ var varList = JSON.parse(result);
+ var suggestInput = new SuggestInput();
+ suggestInput.setComponentID('fontPath');
+ suggestInput.addClass('vp-input vp-state');
+ suggestInput.setSuggestList(function() { return varList; });
+ suggestInput.setPlaceholder('font path');
+ suggestInput.setValue(that.state.fontPath);
+ // suggestInput.setNormalFilter(false);
+ $(fontFamilyTag).replaceWith(function() {
+ return suggestInput.toTagString();
+ });
+ });
+
+ // 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');
+ suggestInput.setValue(that.state.encoding);
+ return suggestInput.toTagString();
+ });
+
+ this.loadPreview();
+ }
+
+ loadPreview() {
+ let that = this;
+ let code = this.generateCode(true);
+
+ that.checkAndRunModules(true).then(function() {
+ // show variable information on clicking variable
+ vpKernel.execute(code).then(function(resultObj) {
+ let { result, type, msg } = resultObj;
+ if (msg.content.data) {
+ var textResult = msg.content.data["text/plain"];
+ var htmlResult = msg.content.data["text/html"];
+ var imgResult = msg.content.data["image/png"];
+
+ $(that.wrapSelector('#vp_wcPreview')).html('');
+ if (htmlResult != undefined) {
+ // 1. HTML tag
+ $(that.wrapSelector('#vp_wcPreview')).append(htmlResult);
+ } else if (imgResult != undefined) {
+ // 2. Image data (base64)
+ var imgTag = ' ';
+ $(that.wrapSelector('#vp_wcPreview')).append(imgTag);
+ } else if (textResult != undefined) {
+ // 3. Text data
+ var preTag = document.createElement('pre');
+ $(preTag).text(textResult);
+ $(that.wrapSelector('#vp_wcPreview')).html(preTag);
+ }
+ } else {
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ $(that.wrapSelector('#vp_wcPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ }
+ }).catch(function(resultObj) {
+ let { msg } = resultObj;
+ var errorContent = '';
+ if (msg.content && msg.content.ename) {
+ errorContent = com_util.templateForErrorBox(msg.content.ename, msg.content.evalue);
+ }
+ $(that.wrapSelector('#vp_wcPreview')).html(errorContent);
+ vpLog.display(VP_LOG_TYPE.ERROR, msg.content?.ename, msg.content?.evalue, msg.content);
+ });
+ });
+ }
+
+ generateInstallCode() {
+ return ['!pip install wordcloud'];
+ }
+
+ generateImportCode() {
+ var code = new com_String();
+ code.appendLine('from wordcloud import WordCloud'); // need to be installed
+
+ code.appendLine('from collections import Counter');
+ code.appendLine('import matplotlib.pyplot as plt');
+ code.append('%matplotlib inline');
+ return [code.toString()];
+ }
+
+ generateCode(preview=false) {
+ let {
+ data, data_state, useFile, encoding, wordCount,
+ stopWords, fontPath, userOption, figWidth, figHeight
+ } = this.state;
+ let code = new com_String();
+
+ // preview option
+ if (preview === true) {
+ // Ignore warning
+ code.appendLine('import warnings');
+ code.appendLine('with warnings.catch_warnings():');
+ code.appendLine(" warnings.simplefilter('ignore')");
+
+ // no auto-import for preview
+ this.config.checkModules = [];
+ } else {
+ this.config.checkModules = ['Counter', 'plt', 'WordCloud'];
+ }
+
+ // counter for top limit
+ let dataVariable = data;
+ if (useFile) {
+ code.appendFormat("with open('{0}', 'rt'", data);
+ if (encoding && encoding != '') {
+ code.appendFormat(", encoding='{0}'", encoding);
+ }
+ code.appendLine(") as fp:");
+ code.appendLine(" word_cloud_text = fp.read()");
+ code.appendLine();
+ dataVariable = 'word_cloud_text';
+ } else {
+ // check data type and convert it to string
+ // let dataType = $(this.wrapSelector('#data')).data('type');
+ let dataType = '';
+ if (data_state) {
+ dataType = data_state['returnDataType'];
+ }
+ if (dataType == 'DataFrame' || dataType == 'Series') {
+ dataVariable = data + '.to_string()';
+ }
+ }
+ code.appendFormatLine("counts = Counter({0}.split())", dataVariable);
+ code.appendFormatLine("tags = counts.most_common({0})", wordCount);
+ code.appendLine();
+
+ // create wordcloud FIXME:
+ let options=[];
+ options.push("max_font_size=200");
+ options.push("background_color='white'");
+ options.push("width=1000, height=800");
+
+ if (stopWords && stopWords != '') {
+ options.push(com_util.formatString("stopwords=['{0}']", stopWords.split(',').join("','")));
+ }
+ if (fontPath && fontPath != '') {
+ options.push(com_util.formatString("font_path='{0}'", fontPath));
+ }
+ if (userOption && userOption != '') {
+ options.push(', ' + userOption);
+ }
+
+ code.appendFormatLine("wc = WordCloud({0})", options.join(', '));
+ code.appendLine("cloud = wc.generate_from_frequencies(dict(tags))");
+ code.appendLine();
+
+ // use plot to show
+ code.appendFormatLine("plt.figure(figsize=({0}, {1}))", figWidth, figHeight);
+ code.appendLine("plt.imshow(cloud)");
+ code.appendLine("plt.tight_layout(pad=0)");
+ code.appendLine("plt.axis('off')");
+ code.appendLine("plt.show()");
+
+ return code.toString();
+ }
+ }
+
+ return WordCloud;
+});
\ No newline at end of file
diff --git a/src/numpy/__init__.py b/visualpython/js/m_visualize/__init__.py
similarity index 100%
rename from src/numpy/__init__.py
rename to visualpython/js/m_visualize/__init__.py
diff --git a/visualpython/js/menu/MenuFrame.js b/visualpython/js/menu/MenuFrame.js
new file mode 100644
index 00000000..386916a3
--- /dev/null
+++ b/visualpython/js/menu/MenuFrame.js
@@ -0,0 +1,347 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : MenuFrame.js
+ * Author : Black Logic
+ * Note : Render and load menu frame
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 09. 13
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] MenuFrame
+//============================================================================
+define([
+ __VP_TEXT_LOADER__('../../html/menuFrame.html'), // INTEGRATION: unified version of text loader
+ __VP_CSS_LOADER__('vp_base/css/menuFrame'), // INTEGRATION: unified version of css loader
+
+ '../com/com_Config',
+ '../com/com_Const',
+ '../com/com_util',
+ '../com/com_interface',
+ '../com/component/Component',
+ '../com/component/SuggestInput',
+ '../com/component/InnerFuncViewer',
+ '../com/component/PackageManager',
+
+ __VP_RAW_LOADER__('../../data/libraries.json'), // INTEGRATION: text! to raw-loader
+
+ './MenuGroup',
+ './MenuItem',
+ './TaskBar'
+], function(menuFrameHtml, menuFrameCss, com_Config, com_Const, com_util, com_interface, Component, SuggestInput, InnerFuncViewer, PackageManager,
+ librariesJson,
+ MenuGroup, MenuItem, TaskBar) {
+ 'use strict';
+ //========================================================================
+ // Define Variable
+ //========================================================================
+ const {
+ VP_MIN_WIDTH,
+ MENU_MIN_WIDTH,
+ BOARD_MIN_WIDTH,
+ MENU_BOARD_SPACING
+ } = com_Config;
+
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * MenuFrame
+ */
+ class MenuFrame extends Component {
+ //========================================================================
+ // Constructor
+ //========================================================================
+ constructor($target, state, prop={}) {
+ super($target, state, prop);
+ /**
+ * state.vp_menu_width : menu width (metadata)
+ * prop.parent : MainFrame
+ */
+ }
+
+ //========================================================================
+ // Internal call function
+ //========================================================================
+ _init() {
+ // get json library list
+ this.menuLibrariesFlatten = []; // use it for searching
+ this.menuLibraries = this.getMenuLibraries();
+ }
+
+ /**
+ * Bind events on menuFrame
+ */
+ _bindEvent() {
+ var that = this;
+ // Click extra menu button
+ $(this.wrapSelector('#vp_headerExtraMenuBtn')).on('click', function(evt) {
+ $('#vp_headerExtraMenu').toggle();
+ evt.stopPropagation();
+ });
+ // Click toggle board icon
+ $(this.wrapSelector('#vp_toggleBoard')).on('click', function() {
+ that.prop.parent.toggleNote();
+ });
+ // Click extra menu item
+ $(this.wrapSelector('#vp_headerExtraMenu li')).on('click', function() {
+ let menu = $(this).data('menu');
+ switch(menu) {
+ case 'check-version':
+ // check vp version
+ vpConfig.checkVpVersion();
+ break;
+ case 'view-inner-func':
+ let viewer = new InnerFuncViewer();
+ viewer.open();
+ break;
+ case 'restart':
+ // restart vp
+ vpConfig.readKernelFunction().then(function() {
+ // successfully restarted
+ com_util.renderSuccessMessage('Successfully loaded inner functions for Visual Python');
+ }).catch(function() {
+ com_util.renderAlertModal('No connected runtime is detected. Please connect to runtime...');
+ });
+ break;
+ case 'about':
+ case 'vpnote':
+ break;
+ }
+ });
+ // Click version updater
+ $(this.wrapSelector('#vp_versionUpdater')).on('click', function() {
+ vpConfig.checkVpVersion();
+ });
+ // Click package manager
+ $(this.wrapSelector('#vp_packageManager')).on('click', function() {
+ let packageManager = new PackageManager();
+ packageManager.open();
+ });
+ }
+
+ _unbindResizable() {
+ $('#vp_menuFrame').resizable('destroy');
+ }
+
+ /**
+ * Bind resizable(jquery.ui)
+ */
+ _bindResizable() {
+ // resizable
+ $('#vp_menuFrame').resizable({
+ // containment: 'parent',
+ helper: 'vp-menuframe-resizer',
+ handles: 'e',
+ // resizeHeight: false,
+ minWidth: MENU_MIN_WIDTH,
+ // maxWidth: 0,
+ start: function(event, ui) {
+
+ },
+ resize: function(event, ui) {
+ var parentWidth = $('#vp_wrapper')[0].getBoundingClientRect().width;
+ var currentWidth = ui.size.width;
+ var newBoardWidth = 0;
+
+ var showBoard = $('#vp_boardFrame').is(':visible');
+ if (showBoard) {
+ newBoardWidth = parentWidth - currentWidth - MENU_BOARD_SPACING;
+
+ // check board minimum width
+ if (newBoardWidth < BOARD_MIN_WIDTH + MENU_BOARD_SPACING) {
+ newBoardWidth = BOARD_MIN_WIDTH;
+ currentWidth = parentWidth - (BOARD_MIN_WIDTH + MENU_BOARD_SPACING);
+ // change current width
+ ui.size.width = currentWidth;
+ }
+ }
+ // resize menu frame with current resized width
+ $('#vp_menuFrame').width(currentWidth);
+ // resize board frame with left space
+ $('#vp_boardFrame').width(newBoardWidth);
+
+ vpConfig.setMetadata({
+ vp_position: { width: parentWidth },
+ vp_menu_width: currentWidth,
+ vp_note_width: newBoardWidth
+ });
+
+ vpLog.display(VP_LOG_TYPE.DEVELOP, 'resizing menuFrame');
+ },
+ stop: function(event, ui) {
+
+ },
+ });
+ }
+
+
+ //========================================================================
+ // External call function
+ //========================================================================
+ /**
+ * Get menu object
+ * @returns library object
+ */
+ getMenuLibraries() {
+ var libraries = {};
+ // LAB: webpack5 load json object by default
+ if (vpConfig.extensionType === 'lab' || vpConfig.extensionType === 'lite') {
+ libraries = librariesJson;
+ } else {
+ libraries = JSON.parse(librariesJson);
+ }
+ if (!libraries || !libraries.library) {
+ vpLog.display(VP_LOG_TYPE.ERROR, 'vp menus are not avilable!');
+ return {};
+ }
+ vpLog.display(VP_LOG_TYPE.LOG, 'vp menus version : ', libraries.library.version);
+ if (libraries && libraries.library) {
+ return libraries.library.item;
+ }
+
+ return {};
+ }
+
+ getMenuLibrary(menuId, libraries=this.menuLibrariesFlatten) {
+ for (var i=0; i < libraries.length; i++) {
+ var item = libraries[i];
+ if (item) {
+ if (item.id === menuId) {
+ return item;
+ }
+ // if (item.type === 'package') {
+ // var result = this.getMenuLibrary(menuId, item.item);
+ // if (result) {
+ // return result;
+ // }
+ // }
+ }
+ }
+ return null;
+ }
+
+ template() {
+ this.$pageDom = $(menuFrameHtml.replaceAll('${vp_base}', com_Const.BASE_PATH));
+ // LAB: vp_base replacing test
+ // const regexp = /"\$\{vp_base\}(.+?)"/g;
+ // var replaceHtml = menuFrameHtml;
+
+ // const rep_list = [...replaceHtml.matchAll(regexp)];
+
+ // for (var i=0; i {
+ // remember parent to navigate its parent menu
+ var category = state.category?(state.category + ' > ' + state.name):state.name;
+ child['category'] = category;
+
+ if (child.type == 'package') {
+ // packages : MenuGroup
+ var menuGroup = new MenuGroup($(body), child);
+ if (child.item) {
+ that.renderMenuItem(menuGroup);
+ }
+ } else {
+ // functions : MenuItem
+ that.menuLibrariesFlatten.push(child);
+ if (!child.hide) {
+ var menuItem = new MenuItem($(body), child);
+ }
+ }
+ });
+ }
+
+ renderTaskBar(taskList) {
+ this.taskBar = new TaskBar($(this.wrapSelector('#vp_menuFooter')), { taskList: taskList });
+ }
+
+ render() {
+ super.render(true);
+ var that = this;
+
+ this._bindResizable();
+
+ // set width using metadata
+ $(this.wrapSelector()).width(this.state.vp_menu_width);
+
+ // render menuItem
+ var menuLibraries = this.menuLibraries;
+ vpLog.display(VP_LOG_TYPE.DEVELOP, menuLibraries);
+
+ this.menuLibrariesFlatten = [];
+ menuLibraries && menuLibraries.forEach(item => {
+ if (item.type == 'package') {
+ // packages : MenuGroup
+ var menuGroup = new MenuGroup($('.vp-menugroup-list'), item);
+ if (item.item) {
+ that.renderMenuItem(menuGroup);
+ }
+ }
+ });
+
+ let functionList = this.menuLibrariesFlatten.map(menu => {
+ return { label: menu.name, value: menu.name, dtype: menu.category, ...menu }
+ });
+ // render searchbox
+ let searchBox = new SuggestInput();
+ searchBox.setComponentID('vp_menuSearchBox');
+ searchBox.addClass('vp-input vp-menu-search-box');
+ searchBox.setPlaceholder('Search libraries');
+ searchBox.setMinSearchLength(2);
+ searchBox.setSuggestList(function () { return functionList; });
+ searchBox.setSelectEvent(function (value) {
+ $(this.wrapSelector()).val(value);
+ $(this.wrapSelector()).trigger('change');
+ });
+ searchBox.setSelectEvent(function(value, item) {
+ $(this.wrapSelector()).val(value);
+
+ $('#vp_wrapper').trigger({
+ type:"create_option_page",
+ blockType: 'task',
+ menuId: item.id,
+ menuState: {},
+ afterAction: 'open'
+ });
+ $(this.wrapSelector()).trigger('change');
+ // clear search box
+ $(that.wrapSelector('#vp_menuSearchBox')).val('');
+ return false;
+ });
+ searchBox.setNormalFilter(true);
+ // replace searchbox
+ $(this.wrapSelector('#vp_menuSearchBox')).replaceWith(searchBox.toTagString());
+
+ // render taskBar
+ this.renderTaskBar([]);
+ }
+ }
+
+ return MenuFrame;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/menu/MenuGroup.js b/visualpython/js/menu/MenuGroup.js
new file mode 100644
index 00000000..5f5f2f24
--- /dev/null
+++ b/visualpython/js/menu/MenuGroup.js
@@ -0,0 +1,108 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : MenuGroup.js
+ * Author : Black Logic
+ * Note : Render and load menu group
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 09. 13
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] MenuGroup
+//============================================================================
+define([
+ '../com/component/Component',
+ '../com/com_util',
+ '../com/com_String',
+], function(Component, com_util, com_String) {
+ 'use strict';
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * MenuGroup
+ */
+ class MenuGroup extends Component {
+ constructor($target, state) {
+ super($target, state);
+ }
+
+ _bindEvent() {
+ var that = this;
+ this.$target.on('click', function(evt) {
+ var target = evt.target;
+ if ($(target).parent().hasClass(that.uuid)) {
+ var bodyTag = $('.' + that.uuid).find('.vp-menugroup-box');
+ if (bodyTag.is(':visible')) {
+ bodyTag.hide();
+ } else {
+ bodyTag.show();
+ // scroll to view
+ $(target)[0].scrollIntoView({behavior: "smooth", block: "start"});
+ }
+ evt.stopPropagation();
+ }
+ });
+ }
+
+ template() {
+ var { id, name, desc, level, open, grid } = this.state;
+ // open menu group on default?
+ var openItemsAttribute = open && open==true? '': 'style="display:none;"'
+ var isGrid = (grid == true);
+
+ var page = new com_String();
+ page.appendFormatLine('', this.uuid, isGrid?'apps':'');
+ if (level == 0) {
+ // render root group
+ page.appendFormatLine('
{3}
'
+ , 'vp-menugroup-root vp-no-selection', id, desc, name);
+ page.appendFormatLine('
', 'vp-menugroup-box', openItemsAttribute);
+ if (isGrid) {
+ // add grid template if it's apps
+ page.appendFormatLine('
', 'vp-menugroup-grid');
+ }
+ // menu items here
+ page.appendLine('
');
+ } else {
+ // render normal group
+ page.appendFormatLine('
'
+ , 'vp-menugroup vp-no-selection vp-accordian'
+ , open && open==true?'vp-open':'vp-close', id, desc);
+ page.appendFormatLine(' ', 'vp-indicator');
+ page.appendFormatLine('{0} ', name)
+ page.appendLine('
');
+ page.appendFormatLine('
', 'vp-menugroup-box vp-accordian-box', openItemsAttribute);
+ }
+ page.appendLine('
');
+ return page.toString();
+ }
+
+ /**
+ * Get child items
+ * @returns object
+ */
+ getItem() {
+ return this.state.item;
+ }
+
+ /**
+ * Get body tag to append items
+ * @returns queryTag
+ */
+ getBody() {
+ var queryString = '.' + this.uuid;
+ if (this.state.grid == true) {
+ return this.$target.find(queryString + ' .vp-menugroup-grid');
+ }
+ return this.$target.find(queryString + ' .vp-menugroup-box');
+ }
+ }
+
+ return MenuGroup;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/menu/MenuItem.js b/visualpython/js/menu/MenuItem.js
new file mode 100644
index 00000000..8cebdd73
--- /dev/null
+++ b/visualpython/js/menu/MenuItem.js
@@ -0,0 +1,177 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : MenuItem.js
+ * Author : Black Logic
+ * Note : Render and load menu item
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 09. 13
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] MenuItem
+//============================================================================
+define([
+ '../com/com_Const',
+ '../com/com_String',
+ '../com/component/Component',
+ '../board/Block'
+], function(com_Const, com_String, Component, Block) {
+ 'use strict';
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * MenuItem
+ */
+ class MenuItem extends Component{
+ constructor($target, state) {
+ super($target, state);
+ }
+
+ _getMenuGroupRootType(idx=1) {
+ // ex) visualpython - apps - frame
+ let path = this.state.path;
+ let pathList = path.split(' - ');
+ return pathList[idx];
+ }
+
+ _getMenuGroupType() {
+ // ex) visualpython - apps - frame
+ let path = this.state.path;
+ let pathList = path.split(' - ');
+ return pathList.slice(1, pathList.length - 1).join('-');
+ }
+
+ /**
+ * Get menu item block's background color
+ * @param {*} isApps
+ * @returns
+ */
+ _getColorClass(isApps=false) {
+ if (isApps) {
+ // For Apps menu item
+ var color = this.state.apps.color;
+ switch(color) {
+ case 0:
+ return 'vp-color-preparing';
+ default:
+ return 'vp-color-apps' + color;
+ }
+ } else {
+ // return color class
+ // FIXME: set detailed labels
+ return this.getColorLabel();
+ }
+ }
+
+ getColorLabel() {
+ let root = this._getMenuGroupRootType();
+ let label = root;
+ switch(root) {
+ case 'logic':
+ let subRoot = this._getMenuGroupRootType(2);
+ label = 'logic-' + subRoot;
+ break;
+ case 'library':
+ break;
+ }
+
+ return label;
+ }
+
+ _bindEvent() {
+ var that = this;
+ $(this.wrapSelector()).on('click', function(evt) {
+ // click event
+ $('#vp_wrapper').trigger({
+ type: 'create_option_page',
+ blockType: 'task',
+ menuId: that.state.id,
+ menuState: {},
+ afterAction: 'open'
+ });
+ });
+ }
+
+ _bindDraggable() {
+ var that = this;
+ $(this.wrapSelector()).draggable({
+ containment: '#vp_wrapper',
+ appendTo: '.vp-board-body',
+ revert: true,
+ cursor: 'move',
+ connectToSortable: '.vp-board-body',
+ helper: function() {
+ let isApps = that.state.apps != undefined;
+ let helperTag = new com_String();
+ let colorClass = that.getColorLabel();
+ helperTag.appendFormatLine(''
+ , colorClass, colorClass, that.state.id);
+ helperTag.appendFormatLine('', that.state.name);
+ helperTag.appendLine('
');
+ return helperTag.toString();
+ },
+ start: function(event, ui) {
+ // ui.helper.hide();
+ $(ui.helper).css('z-index', 200);
+ },
+ stop: function(event, ui) {
+ let position = ui.helper.index();
+
+ let leftPosStr = $(ui.helper).css('left');
+ let leftPos = parseInt(leftPosStr.substr(0, leftPosStr.length - 2));
+ if (leftPos < 0) {
+ // out of board
+ return;
+ }
+
+ $('#vp_wrapper').trigger({
+ type: 'create_option_page',
+ blockType: 'block',
+ menuId: that.state.id,
+ menuState: {},
+ position: position
+ });
+ }
+ });
+ }
+
+ template() {
+ var page = new com_String();
+ var { id, name, desc, apps } = this.state;
+ if (apps) {
+ // render apps menu item
+ page.appendFormatLine('');
+ } else {
+ // render normal group
+ page.appendFormatLine('');
+ }
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+ this._bindDraggable();
+ }
+ }
+
+ return MenuItem;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/menu/TaskBar.js b/visualpython/js/menu/TaskBar.js
new file mode 100644
index 00000000..aa889141
--- /dev/null
+++ b/visualpython/js/menu/TaskBar.js
@@ -0,0 +1,78 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : TaskBar.js
+ * Author : Black Logic
+ * Note : Render and load task bar
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 09. 13
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] TaskBar
+//============================================================================
+define([
+ '../com/com_String',
+ '../com/component/Component',
+ './TaskItem'
+], function(com_String, Component, TaskItem) {
+ 'use strict';
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * TaskBar
+ */
+ class TaskBar extends Component{
+
+ _init() {
+ this._taskList = [];
+ }
+
+ _bindEvent() {
+ let that = this;
+
+ // Mousewheel horizontal scrolling event
+ $(this.wrapSelector()).on('mousewheel', function(evt) {
+ evt = window.event || evt;
+ var delta = Math.max(-1, Math.min(1, (evt.wheelDelta || -evt.detail)));
+ this.scrollLeft -= (delta * 30); // scroll speed : 30
+ evt.preventDefault();
+ });
+ }
+
+ template() {
+ return '';
+ }
+
+ render() {
+ super.render(true);
+
+ let taskList = this.state.taskList;
+ taskList && taskList.forEach(task => {
+ let taskItem = new TaskItem($(this.wrapSelector()), { task: task });
+ });
+ }
+
+ //====================================================================
+ // Handling task list
+ //====================================================================
+ get taskList() {
+ return this._taskList;
+ }
+
+ addTaskBlock(popup) {
+ // create TaskItem and add it
+ let taskItem = new TaskItem($(this.wrapSelector()), { popup: popup });
+ this.taskList.push(taskItem);
+ }
+
+
+ }
+
+ return TaskBar;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/visualpython/js/menu/TaskItem.js b/visualpython/js/menu/TaskItem.js
new file mode 100644
index 00000000..c8e2be64
--- /dev/null
+++ b/visualpython/js/menu/TaskItem.js
@@ -0,0 +1,123 @@
+/*
+ * Project Name : Visual Python
+ * Description : GUI-based Python code generator
+ * File Name : TaskItem.js
+ * Author : Black Logic
+ * Note : Render and load task item
+ * License : GNU GPLv3 with Visual Python special exception
+ * Date : 2021. 09. 13
+ * Change Date :
+ */
+
+//============================================================================
+// [CLASS] TaskItem
+//============================================================================
+define([
+ '../com/com_Const',
+ '../com/com_String',
+ '../com/component/Component',
+], function(com_Const, com_String, Component) {
+ 'use strict';
+ //========================================================================
+ // Declare class
+ //========================================================================
+ /**
+ * TaskItem
+ */
+ class TaskItem extends Component{
+
+ _init() {
+ // set taskitem to component
+ this.state.task.setTaskItem(this);
+ }
+
+ _bindEvent() {
+ let that = this;
+ // click event - emphasize TaskItem & open/hide PopupComponent
+ $(this.wrapSelector()).on('click', function(evt) {
+ let isOpen = $(that.wrapSelector()).hasClass('vp-focus');
+ if (isOpen) {
+ // hide task if it's already opened
+ // open task
+ that.state.task.hide();
+ } else {
+ // open task
+ $('#vp_wrapper').trigger({
+ type: 'open_option_page',
+ component: that.state.task
+ });
+ }
+ });
+
+ // remove click event
+ $(this.wrapSelector('.vp-menu-task-remove')).on('click', function(evt) {
+ $('#vp_wrapper').trigger({
+ type: 'remove_option_page',
+ component: that.state.task
+ });
+ });
+ }
+
+ _getOptionInfo() {
+ let task = this.state.task;
+ let info = {};
+ if (task && task.state && task.config) {
+ let { id, name } = task;
+ let { desc, apps }= task.config;
+ info = {
+ id: id,
+ title: name,
+ desc: desc,
+ icon: 'apps/apps_white.svg'
+ };
+
+ if (apps) {
+ info.icon = apps.icon;
+ }
+ }
+ return info;
+ }
+
+ template() {
+ let { title, icon, desc } = this._getOptionInfo();
+ let page = new com_String();
+ page.appendFormatLine('', 'vp-menu-task-item', desc);
+ // page.appendFormatLine('', icon);
+ page.appendFormatLine('{0} ', title);
+ // LAB: img to url
+ // page.appendFormatLine('', 'Close task', com_Const.IMAGE_PATH + 'close_small.svg');
+ page.appendFormatLine('', 'Close task');
+ page.appendLine('
');
+ return page.toString();
+ }
+
+ render() {
+ super.render();
+
+ // emphasize it if its task is visible
+ if (!this.state.task.isHidden()) {
+ this.$target.find('.vp-menu-task-item').removeClass('vp-focus');
+ $(this.wrapSelector()).addClass('vp-focus');
+ }
+ }
+
+ focusItem() {
+ this.$target.find('.vp-menu-task-item').removeClass('vp-focus');
+ $(this.wrapSelector()).addClass('vp-focus');
+ }
+
+ blurItem() {
+ // hide task if it's already opened
+ $(this.wrapSelector()).removeClass('vp-focus');
+ }
+
+ removeItem() {
+ $(this.wrapSelector()).remove();
+ }
+ }
+
+ return TaskItem;
+
+});
+
+/* End of file */
\ No newline at end of file
diff --git a/src/numpy/api/__init__.py b/visualpython/js/menu/__init__.py
similarity index 100%
rename from src/numpy/api/__init__.py
rename to visualpython/js/menu/__init__.py
diff --git a/src/numpy/common/NumpyPageRender/__init__.py b/visualpython/lib/__init__.py
similarity index 100%
rename from src/numpy/common/NumpyPageRender/__init__.py
rename to visualpython/lib/__init__.py
diff --git a/visualpython/lib/codemirror/addon/display/autorefresh.js b/visualpython/lib/codemirror/addon/display/autorefresh.js
new file mode 100644
index 00000000..b5e6ab0a
--- /dev/null
+++ b/visualpython/lib/codemirror/addon/display/autorefresh.js
@@ -0,0 +1,47 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/5/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"))
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod)
+ else // Plain browser env
+ mod(CodeMirror)
+})(function(CodeMirror) {
+ "use strict"
+
+ CodeMirror.defineOption("autoRefresh", false, function(cm, val) {
+ if (cm.state.autoRefresh) {
+ stopListening(cm, cm.state.autoRefresh)
+ cm.state.autoRefresh = null
+ }
+ if (val && cm.display.wrapper.offsetHeight == 0)
+ startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250})
+ })
+
+ function startListening(cm, state) {
+ function check() {
+ if (cm.display.wrapper.offsetHeight) {
+ stopListening(cm, state)
+ if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight)
+ cm.refresh()
+ } else {
+ state.timeout = setTimeout(check, state.delay)
+ }
+ }
+ state.timeout = setTimeout(check, state.delay)
+ state.hurry = function() {
+ clearTimeout(state.timeout)
+ state.timeout = setTimeout(check, 50)
+ }
+ CodeMirror.on(window, "mouseup", state.hurry)
+ CodeMirror.on(window, "keyup", state.hurry)
+ }
+
+ function stopListening(_cm, state) {
+ clearTimeout(state.timeout)
+ CodeMirror.off(window, "mouseup", state.hurry)
+ CodeMirror.off(window, "keyup", state.hurry)
+ }
+});
diff --git a/visualpython/lib/codemirror/addon/display/placeholder.js b/visualpython/lib/codemirror/addon/display/placeholder.js
new file mode 100644
index 00000000..7848f514
--- /dev/null
+++ b/visualpython/lib/codemirror/addon/display/placeholder.js
@@ -0,0 +1,78 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/5/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.on("blur", onBlur);
+ cm.on("change", onChange);
+ cm.on("swapDoc", onChange);
+ CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() { onComposition(cm) })
+ onChange(cm);
+ } else if (!val && prev) {
+ cm.off("blur", onBlur);
+ cm.off("change", onChange);
+ cm.off("swapDoc", onChange);
+ CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose)
+ clearPlaceholder(cm);
+ var wrapper = cm.getWrapperElement();
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
+ }
+
+ if (val && !cm.hasFocus()) onBlur(cm);
+ });
+
+ function clearPlaceholder(cm) {
+ if (cm.state.placeholder) {
+ cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
+ cm.state.placeholder = null;
+ }
+ }
+ function setPlaceholder(cm) {
+ clearPlaceholder(cm);
+ var elt = cm.state.placeholder = document.createElement("pre");
+ elt.style.cssText = "height: 0; overflow: visible";
+ elt.style.direction = cm.getOption("direction");
+ elt.className = "CodeMirror-placeholder CodeMirror-line-like";
+ var placeHolder = cm.getOption("placeholder")
+ if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
+ elt.appendChild(placeHolder)
+ cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
+ }
+
+ function onComposition(cm) {
+ setTimeout(function() {
+ var empty = false
+ if (cm.lineCount() == 1) {
+ var input = cm.getInputField()
+ empty = input.nodeName == "TEXTAREA" ? !cm.getLine(0).length
+ : !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent)
+ }
+ if (empty) setPlaceholder(cm)
+ else clearPlaceholder(cm)
+ }, 20)
+ }
+
+ function onBlur(cm) {
+ if (isEmpty(cm)) setPlaceholder(cm);
+ }
+ function onChange(cm) {
+ var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
+
+ if (empty) setPlaceholder(cm);
+ else clearPlaceholder(cm);
+ }
+
+ function isEmpty(cm) {
+ return (cm.lineCount() === 1) && (cm.getLine(0) === "");
+ }
+});
diff --git a/visualpython/lib/codemirror/lib/codemirror.css b/visualpython/lib/codemirror/lib/codemirror.css
new file mode 100644
index 00000000..0a80f68d
--- /dev/null
+++ b/visualpython/lib/codemirror/lib/codemirror.css
@@ -0,0 +1,344 @@
+/* BASICS */
+
+.CodeMirror {
+ /* Set height, width, borders, and global font properties here */
+ font-family: monospace;
+ /* height: 300px; */
+ color: black;
+ direction: ltr;
+}
+
+/* PADDING */
+
+.CodeMirror-lines {
+ padding: 4px 0; /* Vertical padding around content */
+}
+.CodeMirror pre.CodeMirror-line,
+.CodeMirror pre.CodeMirror-line-like {
+ padding: 0 4px; /* Horizontal padding of content */
+}
+
+.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+ background-color: white; /* The little square between H and V scrollbars */
+}
+
+/* GUTTER */
+
+.CodeMirror-gutters {
+ border-right: 1px solid #ddd;
+ background-color: #f7f7f7;
+ white-space: nowrap;
+}
+.CodeMirror-linenumbers {}
+.CodeMirror-linenumber {
+ padding: 0 3px 0 5px;
+ min-width: 20px;
+ text-align: right;
+ color: #999;
+ white-space: nowrap;
+}
+
+.CodeMirror-guttermarker { color: black; }
+.CodeMirror-guttermarker-subtle { color: #999; }
+
+/* CURSOR */
+
+.CodeMirror-cursor {
+ border-left: 1px solid black;
+ border-right: none;
+ width: 0;
+}
+/* Shown when moving in bi-directional text */
+.CodeMirror div.CodeMirror-secondarycursor {
+ border-left: 1px solid silver;
+}
+.cm-fat-cursor .CodeMirror-cursor {
+ width: auto;
+ border: 0 !important;
+ background: #7e7;
+}
+.cm-fat-cursor div.CodeMirror-cursors {
+ z-index: 1;
+}
+.cm-fat-cursor .CodeMirror-line::selection,
+.cm-fat-cursor .CodeMirror-line > span::selection,
+.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; }
+.cm-fat-cursor .CodeMirror-line::-moz-selection,
+.cm-fat-cursor .CodeMirror-line > span::-moz-selection,
+.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; }
+.cm-fat-cursor { caret-color: transparent; }
+@-moz-keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+@-webkit-keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+@keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+
+/* Can style cursor different in overwrite (non-insert) mode */
+.CodeMirror-overwrite .CodeMirror-cursor {}
+
+.cm-tab { display: inline-block; text-decoration: inherit; }
+
+.CodeMirror-rulers {
+ position: absolute;
+ left: 0; right: 0; top: -50px; bottom: 0;
+ overflow: hidden;
+}
+.CodeMirror-ruler {
+ border-left: 1px solid #ccc;
+ top: 0; bottom: 0;
+ position: absolute;
+}
+
+/* DEFAULT THEME */
+
+.cm-s-default .cm-header {color: blue;}
+.cm-s-default .cm-quote {color: #090;}
+.cm-negative {color: #d44;}
+.cm-positive {color: #292;}
+.cm-header, .cm-strong {font-weight: bold;}
+.cm-em {font-style: italic;}
+.cm-link {text-decoration: underline;}
+.cm-strikethrough {text-decoration: line-through;}
+
+.cm-s-default .cm-keyword {color: #708;}
+.cm-s-default .cm-atom {color: #219;}
+.cm-s-default .cm-number {color: #164;}
+.cm-s-default .cm-def {color: #00f;}
+.cm-s-default .cm-variable,
+.cm-s-default .cm-punctuation,
+.cm-s-default .cm-property,
+.cm-s-default .cm-operator {}
+.cm-s-default .cm-variable-2 {color: #05a;}
+.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
+.cm-s-default .cm-comment {color: #a50;}
+.cm-s-default .cm-string {color: #a11;}
+.cm-s-default .cm-string-2 {color: #f50;}
+.cm-s-default .cm-meta {color: #555;}
+.cm-s-default .cm-qualifier {color: #555;}
+.cm-s-default .cm-builtin {color: #30a;}
+.cm-s-default .cm-bracket {color: #997;}
+.cm-s-default .cm-tag {color: #170;}
+.cm-s-default .cm-attribute {color: #00c;}
+.cm-s-default .cm-hr {color: #999;}
+.cm-s-default .cm-link {color: #00c;}
+
+.cm-s-default .cm-error {color: #f00;}
+.cm-invalidchar {color: #f00;}
+
+.CodeMirror-composing { border-bottom: 2px solid; }
+
+/* Default styles for common addons */
+
+div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
+div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
+.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
+.CodeMirror-activeline-background {background: #e8f2ff;}
+
+/* STOP */
+
+/* The rest of this file contains styles related to the mechanics of
+ the editor. You probably shouldn't touch them. */
+
+.CodeMirror {
+ position: relative;
+ overflow: hidden;
+ background: white;
+}
+
+.CodeMirror-scroll {
+ overflow: scroll !important; /* Things will break if this is overridden */
+ /* 50px is the magic margin used to hide the element's real scrollbars */
+ /* See overflow: hidden in .CodeMirror */
+ margin-bottom: -50px; margin-right: -50px;
+ padding-bottom: 50px;
+ height: 100%;
+ outline: none; /* Prevent dragging from highlighting the element */
+ position: relative;
+ z-index: 0;
+}
+.CodeMirror-sizer {
+ position: relative;
+ border-right: 50px solid transparent;
+}
+
+/* The fake, visible scrollbars. Used to force redraw during scrolling
+ before actual scrolling happens, thus preventing shaking and
+ flickering artifacts. */
+.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+ position: absolute;
+ z-index: 6;
+ display: none;
+ outline: none;
+}
+.CodeMirror-vscrollbar {
+ right: 0; top: 0;
+ overflow-x: hidden;
+ overflow-y: scroll;
+}
+.CodeMirror-hscrollbar {
+ bottom: 0; left: 0;
+ overflow-y: hidden;
+ overflow-x: scroll;
+}
+.CodeMirror-scrollbar-filler {
+ right: 0; bottom: 0;
+}
+.CodeMirror-gutter-filler {
+ left: 0; bottom: 0;
+}
+
+.CodeMirror-gutters {
+ position: absolute; left: 0; top: 0;
+ min-height: 100%;
+ z-index: 3;
+}
+.CodeMirror-gutter {
+ white-space: normal;
+ height: 100%;
+ display: inline-block;
+ vertical-align: top;
+ margin-bottom: -50px;
+}
+.CodeMirror-gutter-wrapper {
+ position: absolute;
+ z-index: 4;
+ background: none !important;
+ border: none !important;
+}
+.CodeMirror-gutter-background {
+ position: absolute;
+ top: 0; bottom: 0;
+ z-index: 4;
+}
+.CodeMirror-gutter-elt {
+ position: absolute;
+ cursor: default;
+ z-index: 4;
+}
+.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
+.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
+
+.CodeMirror-lines {
+ cursor: text;
+ min-height: 1px; /* prevents collapsing before first draw */
+}
+.CodeMirror pre.CodeMirror-line,
+.CodeMirror pre.CodeMirror-line-like {
+ /* Reset some styles that the rest of the page might have set */
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
+ border-width: 0;
+ background: transparent;
+ font-family: inherit;
+ font-size: inherit;
+ margin: 0;
+ white-space: pre;
+ word-wrap: normal;
+ line-height: inherit;
+ color: inherit;
+ z-index: 2;
+ position: relative;
+ overflow: visible;
+ -webkit-tap-highlight-color: transparent;
+ -webkit-font-variant-ligatures: contextual;
+ font-variant-ligatures: contextual;
+}
+.CodeMirror-wrap pre.CodeMirror-line,
+.CodeMirror-wrap pre.CodeMirror-line-like {
+ word-wrap: break-word;
+ white-space: pre-wrap;
+ word-break: normal;
+}
+
+.CodeMirror-linebackground {
+ position: absolute;
+ left: 0; right: 0; top: 0; bottom: 0;
+ z-index: 0;
+}
+
+.CodeMirror-linewidget {
+ position: relative;
+ z-index: 2;
+ padding: 0.1px; /* Force widget margins to stay inside of the container */
+}
+
+.CodeMirror-widget {}
+
+.CodeMirror-rtl pre { direction: rtl; }
+
+.CodeMirror-code {
+ outline: none;
+}
+
+/* Force content-box sizing for the elements where we expect it */
+.CodeMirror-scroll,
+.CodeMirror-sizer,
+.CodeMirror-gutter,
+.CodeMirror-gutters,
+.CodeMirror-linenumber {
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+
+.CodeMirror-measure {
+ position: absolute;
+ width: 100%;
+ height: 0;
+ overflow: hidden;
+ visibility: hidden;
+}
+
+.CodeMirror-cursor {
+ position: absolute;
+ pointer-events: none;
+}
+.CodeMirror-measure pre { position: static; }
+
+div.CodeMirror-cursors {
+ visibility: hidden;
+ position: relative;
+ z-index: 3;
+}
+div.CodeMirror-dragcursors {
+ visibility: visible;
+}
+
+.CodeMirror-focused div.CodeMirror-cursors {
+ visibility: visible;
+}
+
+.CodeMirror-selected { background: #d9d9d9; }
+.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
+.CodeMirror-crosshair { cursor: crosshair; }
+.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
+.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
+
+.cm-searching {
+ background-color: #ffa;
+ background-color: rgba(255, 255, 0, .4);
+}
+
+/* Used to force a border model for a node */
+.cm-force-border { padding-right: .1px; }
+
+@media print {
+ /* Hide the cursor when printing */
+ .CodeMirror div.CodeMirror-cursors {
+ visibility: hidden;
+ }
+}
+
+/* See issue #2901 */
+.cm-tab-wrap-hack:after { content: ''; }
+
+/* Help users use markselection to safely style text background */
+span.CodeMirror-selectedtext { background: none; }
diff --git a/visualpython/lib/codemirror/lib/codemirror.js b/visualpython/lib/codemirror/lib/codemirror.js
new file mode 100644
index 00000000..5ff61d9e
--- /dev/null
+++ b/visualpython/lib/codemirror/lib/codemirror.js
@@ -0,0 +1,9867 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/5/LICENSE
+
+// This is CodeMirror (https://codemirror.net/5), a code editor
+// implemented in JavaScript on top of the browser's DOM.
+//
+// You can find some technical background for some of the code below
+// at http://marijnhaverbeke.nl/blog/#cm-internals .
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = global || self, global.CodeMirror = factory());
+}(this, (function () { 'use strict';
+
+ // Kludges for bugs and behavior differences that can't be feature
+ // detected are enabled based on userAgent etc sniffing.
+ var userAgent = navigator.userAgent;
+ var platform = navigator.platform;
+
+ var gecko = /gecko\/\d/i.test(userAgent);
+ var ie_upto10 = /MSIE \d/.test(userAgent);
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
+ var edge = /Edge\/(\d+)/.exec(userAgent);
+ var ie = ie_upto10 || ie_11up || edge;
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
+ var webkit = !edge && /WebKit\//.test(userAgent);
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
+ var chrome = !edge && /Chrome\/(\d+)/.exec(userAgent);
+ var chrome_version = chrome && +chrome[1];
+ var presto = /Opera\//.test(userAgent);
+ var safari = /Apple Computer/.test(navigator.vendor);
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
+ var phantom = /PhantomJS/.test(userAgent);
+
+ var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
+ var android = /Android/.test(userAgent);
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
+ var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
+ var mac = ios || /Mac/.test(platform);
+ var chromeOS = /\bCrOS\b/.test(userAgent);
+ var windows = /win/i.test(platform);
+
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
+ if (presto_version) { presto_version = Number(presto_version[1]); }
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
+ var captureRightClick = gecko || (ie && ie_version >= 9);
+
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+
+ var rmClass = function(node, cls) {
+ var current = node.className;
+ var match = classTest(cls).exec(current);
+ if (match) {
+ var after = current.slice(match.index + match[0].length);
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
+ }
+ };
+
+ function removeChildren(e) {
+ for (var count = e.childNodes.length; count > 0; --count)
+ { e.removeChild(e.firstChild); }
+ return e
+ }
+
+ function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e)
+ }
+
+ function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) { e.className = className; }
+ if (style) { e.style.cssText = style; }
+ if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
+ else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
+ return e
+ }
+ // wrapper for elt, which removes the elt from the accessibility tree
+ function eltP(tag, content, className, style) {
+ var e = elt(tag, content, className, style);
+ e.setAttribute("role", "presentation");
+ return e
+ }
+
+ var range;
+ if (document.createRange) { range = function(node, start, end, endNode) {
+ var r = document.createRange();
+ r.setEnd(endNode || node, end);
+ r.setStart(node, start);
+ return r
+ }; }
+ else { range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ try { r.moveToElementText(node.parentNode); }
+ catch(e) { return r }
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r
+ }; }
+
+ function contains(parent, child) {
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+ { child = child.parentNode; }
+ if (parent.contains)
+ { return parent.contains(child) }
+ do {
+ if (child.nodeType == 11) { child = child.host; }
+ if (child == parent) { return true }
+ } while (child = child.parentNode)
+ }
+
+ function activeElt(doc) {
+ // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
+ // IE < 10 will throw when accessed while the page is loading or in an iframe.
+ // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
+ var activeElement;
+ try {
+ activeElement = doc.activeElement;
+ } catch(e) {
+ activeElement = doc.body || null;
+ }
+ while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
+ { activeElement = activeElement.shadowRoot.activeElement; }
+ return activeElement
+ }
+
+ function addClass(node, cls) {
+ var current = node.className;
+ if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
+ }
+ function joinClasses(a, b) {
+ var as = a.split(" ");
+ for (var i = 0; i < as.length; i++)
+ { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
+ return b
+ }
+
+ var selectInput = function(node) { node.select(); };
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
+ { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
+ else if (ie) // Suppress mysterious IE10 errors
+ { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
+
+ function doc(cm) { return cm.display.wrapper.ownerDocument }
+
+ function win(cm) { return doc(cm).defaultView }
+
+ function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args)}
+ }
+
+ function copyObj(obj, target, overwrite) {
+ if (!target) { target = {}; }
+ for (var prop in obj)
+ { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+ { target[prop] = obj[prop]; } }
+ return target
+ }
+
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ function countColumn(string, end, tabSize, startIndex, startValue) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) { end = string.length; }
+ }
+ for (var i = startIndex || 0, n = startValue || 0;;) {
+ var nextTab = string.indexOf("\t", i);
+ if (nextTab < 0 || nextTab >= end)
+ { return n + (end - i) }
+ n += nextTab - i;
+ n += tabSize - (n % tabSize);
+ i = nextTab + 1;
+ }
+ }
+
+ var Delayed = function() {
+ this.id = null;
+ this.f = null;
+ this.time = 0;
+ this.handler = bind(this.onTimeout, this);
+ };
+ Delayed.prototype.onTimeout = function (self) {
+ self.id = 0;
+ if (self.time <= +new Date) {
+ self.f();
+ } else {
+ setTimeout(self.handler, self.time - +new Date);
+ }
+ };
+ Delayed.prototype.set = function (ms, f) {
+ this.f = f;
+ var time = +new Date + ms;
+ if (!this.id || time < this.time) {
+ clearTimeout(this.id);
+ this.id = setTimeout(this.handler, ms);
+ this.time = time;
+ }
+ };
+
+ function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ { if (array[i] == elt) { return i } }
+ return -1
+ }
+
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerGap = 50;
+
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var Pass = {toString: function(){return "CodeMirror.Pass"}};
+
+ // Reused option objects for setSelection & friends
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
+
+ // The inverse of countColumn -- find the offset that corresponds to
+ // a particular column.
+ function findColumn(string, goal, tabSize) {
+ for (var pos = 0, col = 0;;) {
+ var nextTab = string.indexOf("\t", pos);
+ if (nextTab == -1) { nextTab = string.length; }
+ var skipped = nextTab - pos;
+ if (nextTab == string.length || col + skipped >= goal)
+ { return pos + Math.min(skipped, goal - col) }
+ col += nextTab - pos;
+ col += tabSize - (col % tabSize);
+ pos = nextTab + 1;
+ if (col >= goal) { return pos }
+ }
+ }
+
+ var spaceStrs = [""];
+ function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ { spaceStrs.push(lst(spaceStrs) + " "); }
+ return spaceStrs[n]
+ }
+
+ function lst(arr) { return arr[arr.length-1] }
+
+ function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
+ return out
+ }
+
+ function insertSorted(array, value, score) {
+ var pos = 0, priority = score(value);
+ while (pos < array.length && score(array[pos]) <= priority) { pos++; }
+ array.splice(pos, 0, value);
+ }
+
+ function nothing() {}
+
+ function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ nothing.prototype = base;
+ inst = new nothing();
+ }
+ if (props) { copyObj(props, inst); }
+ return inst
+ }
+
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+ function isWordCharBasic(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
+ }
+ function isWordChar(ch, helper) {
+ if (!helper) { return isWordCharBasic(ch) }
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
+ return helper.test(ch)
+ }
+
+ function isEmpty(obj) {
+ for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
+ return true
+ }
+
+ // Extending unicode characters. A series of a non-extending char +
+ // any number of extending chars is treated as a single unit as far
+ // as editing and measuring is concerned. This is not fully correct,
+ // since some scripts/fonts/browsers also treat other configurations
+ // of code points as a group.
+ var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
+
+ // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
+ function skipExtendingChars(str, pos, dir) {
+ while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
+ return pos
+ }
+
+ // Returns the value from the range [`from`; `to`] that satisfies
+ // `pred` and is closest to `from`. Assumes that at least `to`
+ // satisfies `pred`. Supports `from` being greater than `to`.
+ function findFirst(pred, from, to) {
+ // At any point we are certain `to` satisfies `pred`, don't know
+ // whether `from` does.
+ var dir = from > to ? -1 : 1;
+ for (;;) {
+ if (from == to) { return from }
+ var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
+ if (mid == from) { return pred(mid) ? from : to }
+ if (pred(mid)) { to = mid; }
+ else { from = mid + dir; }
+ }
+ }
+
+ // BIDI HELPERS
+
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) { return f(from, to, "ltr", 0) }
+ var found = false;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from || from == to && part.to == from) {
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
+ found = true;
+ }
+ }
+ if (!found) { f(from, to, "ltr"); }
+ }
+
+ var bidiOther = null;
+ function getBidiPartAt(order, ch, sticky) {
+ var found;
+ bidiOther = null;
+ for (var i = 0; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < ch && cur.to > ch) { return i }
+ if (cur.to == ch) {
+ if (cur.from != cur.to && sticky == "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ if (cur.from == ch) {
+ if (cur.from != cur.to && sticky != "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ }
+ return found != null ? found : bidiOther
+ }
+
+ // Bidirectional ordering algorithm
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+ // that this (partially) implements.
+
+ // One-char codes used for character types:
+ // L (L): Left-to-Right
+ // R (R): Right-to-Left
+ // r (AL): Right-to-Left Arabic
+ // 1 (EN): European Number
+ // + (ES): European Number Separator
+ // % (ET): European Number Terminator
+ // n (AN): Arabic Number
+ // , (CS): Common Number Separator
+ // m (NSM): Non-Spacing Mark
+ // b (BN): Boundary Neutral
+ // s (B): Paragraph Separator
+ // t (S): Segment Separator
+ // w (WS): Whitespace
+ // N (ON): Other Neutrals
+
+ // Returns null if characters are ordered as they appear
+ // (left-to-right), or an array of sections ({from, to, level}
+ // objects) in the order in which they occur visually.
+ var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
+ // Character types for codepoints 0x600 to 0x6f9
+ var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
+ function charType(code) {
+ if (code <= 0xf7) { return lowTypes.charAt(code) }
+ else if (0x590 <= code && code <= 0x5f4) { return "R" }
+ else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
+ else if (0x6ee <= code && code <= 0x8ac) { return "r" }
+ else if (0x2000 <= code && code <= 0x200b) { return "w" }
+ else if (code == 0x200c) { return "b" }
+ else { return "L" }
+ }
+
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
+ }
+
+ return function(str, direction) {
+ var outerType = direction == "ltr" ? "L" : "R";
+
+ if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
+ var len = str.length, types = [];
+ for (var i = 0; i < len; ++i)
+ { types.push(charType(str.charCodeAt(i))); }
+
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
+ var type = types[i$1];
+ if (type == "m") { types[i$1] = prev; }
+ else { prev = type; }
+ }
+
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
+ var type$1 = types[i$2];
+ if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
+ else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
+ }
+
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
+ var type$2 = types[i$3];
+ if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
+ else if (type$2 == "," && prev$1 == types[i$3+1] &&
+ (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
+ prev$1 = type$2;
+ }
+
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i$4 = 0; i$4 < len; ++i$4) {
+ var type$3 = types[i$4];
+ if (type$3 == ",") { types[i$4] = "N"; }
+ else if (type$3 == "%") {
+ var end = (void 0);
+ for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i$4; j < end; ++j) { types[j] = replace; }
+ i$4 = end - 1;
+ }
+ }
+
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
+ var type$4 = types[i$5];
+ if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
+ else if (isStrong.test(type$4)) { cur$1 = type$4; }
+ }
+
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i$6 = 0; i$6 < len; ++i$6) {
+ if (isNeutral.test(types[i$6])) {
+ var end$1 = (void 0);
+ for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
+ var before = (i$6 ? types[i$6-1] : outerType) == "L";
+ var after = (end$1 < len ? types[end$1] : outerType) == "L";
+ var replace$1 = before == after ? (before ? "L" : "R") : outerType;
+ for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
+ i$6 = end$1 - 1;
+ }
+ }
+
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i$7 = 0; i$7 < len;) {
+ if (countsAsLeft.test(types[i$7])) {
+ var start = i$7;
+ for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
+ order.push(new BidiSpan(0, start, i$7));
+ } else {
+ var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
+ for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
+ for (var j$2 = pos; j$2 < i$7;) {
+ if (countsAsNum.test(types[j$2])) {
+ if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
+ var nstart = j$2;
+ for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j$2));
+ at += isRTL;
+ pos = j$2;
+ } else { ++j$2; }
+ }
+ if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
+ }
+ }
+ if (direction == "ltr") {
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift(new BidiSpan(0, 0, m[0].length));
+ }
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push(new BidiSpan(0, len - m[0].length, len));
+ }
+ }
+
+ return direction == "rtl" ? order.reverse() : order
+ }
+ })();
+
+ // Get the bidi ordering for the given line (and cache it). Returns
+ // false for lines that are fully left-to-right, and an array of
+ // BidiSpan objects otherwise.
+ function getOrder(line, direction) {
+ var order = line.order;
+ if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
+ return order
+ }
+
+ // EVENT HANDLING
+
+ // Lightweight event framework. on/off also work on DOM nodes,
+ // registering native DOM handlers.
+
+ var noHandlers = [];
+
+ var on = function(emitter, type, f) {
+ if (emitter.addEventListener) {
+ emitter.addEventListener(type, f, false);
+ } else if (emitter.attachEvent) {
+ emitter.attachEvent("on" + type, f);
+ } else {
+ var map = emitter._handlers || (emitter._handlers = {});
+ map[type] = (map[type] || noHandlers).concat(f);
+ }
+ };
+
+ function getHandlers(emitter, type) {
+ return emitter._handlers && emitter._handlers[type] || noHandlers
+ }
+
+ function off(emitter, type, f) {
+ if (emitter.removeEventListener) {
+ emitter.removeEventListener(type, f, false);
+ } else if (emitter.detachEvent) {
+ emitter.detachEvent("on" + type, f);
+ } else {
+ var map = emitter._handlers, arr = map && map[type];
+ if (arr) {
+ var index = indexOf(arr, f);
+ if (index > -1)
+ { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
+ }
+ }
+ }
+
+ function signal(emitter, type /*, values...*/) {
+ var handlers = getHandlers(emitter, type);
+ if (!handlers.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
+ }
+
+ // The DOM events that CodeMirror handles can be overridden by
+ // registering a (non-DOM) handler on the editor for the event name,
+ // and preventDefault-ing the event in that handler.
+ function signalDOMEvent(cm, e, override) {
+ if (typeof e == "string")
+ { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore
+ }
+
+ function signalCursorActivity(cm) {
+ var arr = cm._handlers && cm._handlers.cursorActivity;
+ if (!arr) { return }
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
+ for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+ { set.push(arr[i]); } }
+ }
+
+ function hasHandler(emitter, type) {
+ return getHandlers(emitter, type).length > 0
+ }
+
+ // Add on and off methods to a constructor's prototype, to make
+ // registering events on such objects more convenient.
+ function eventMixin(ctor) {
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
+ }
+
+ // Due to the fact that we still support jurassic IE versions, some
+ // compatibility wrappers are needed.
+
+ function e_preventDefault(e) {
+ if (e.preventDefault) { e.preventDefault(); }
+ else { e.returnValue = false; }
+ }
+ function e_stopPropagation(e) {
+ if (e.stopPropagation) { e.stopPropagation(); }
+ else { e.cancelBubble = true; }
+ }
+ function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+ }
+ function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
+
+ function e_target(e) {return e.target || e.srcElement}
+ function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) { b = 1; }
+ else if (e.button & 2) { b = 3; }
+ else if (e.button & 4) { b = 2; }
+ }
+ if (mac && e.ctrlKey && b == 1) { b = 3; }
+ return b
+ }
+
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie && ie_version < 9) { return false }
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div
+ }();
+
+ var zwspSupported;
+ function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
+ }
+ var node = zwspSupported ? elt("span", "\u200b") :
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ node.setAttribute("cm-text", "");
+ return node
+ }
+
+ // Feature-detect IE's crummy client rect reporting for bidi text
+ var badBidiRects;
+ function hasBadBidiRects(measure) {
+ if (badBidiRects != null) { return badBidiRects }
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ removeChildren(measure);
+ if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
+ return badBidiRects = (r1.right - r0.right < 3)
+ }
+
+ // See if "".split is the broken IE version, if so, provide an
+ // alternative way to split lines.
+ var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) { nl = string.length; }
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
+ }
+ }
+ return result
+ } : function (string) { return string.split(/\r\n?|\n/); };
+
+ var hasSelection = window.getSelection ? function (te) {
+ try { return te.selectionStart != te.selectionEnd }
+ catch(e) { return false }
+ } : function (te) {
+ var range;
+ try {range = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range || range.parentElement() != te) { return false }
+ return range.compareEndPoints("StartToEnd", range) != 0
+ };
+
+ var hasCopyEvent = (function () {
+ var e = elt("div");
+ if ("oncopy" in e) { return true }
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == "function"
+ })();
+
+ var badZoomedRects = null;
+ function hasBadZoomedRects(measure) {
+ if (badZoomedRects != null) { return badZoomedRects }
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
+ var normal = node.getBoundingClientRect();
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
+ }
+
+ // Known modes, by name and by MIME
+ var modes = {}, mimeModes = {};
+
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ function defineMode(name, mode) {
+ if (arguments.length > 2)
+ { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
+ modes[name] = mode;
+ }
+
+ function defineMIME(mime, spec) {
+ mimeModes[mime] = spec;
+ }
+
+ // Given a MIME type, a {name, ...options} config object, or a name
+ // string, return a mode config object.
+ function resolveMode(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ var found = mimeModes[spec.name];
+ if (typeof found == "string") { found = {name: found}; }
+ spec = createObj(found, spec);
+ spec.name = found.name;
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+ return resolveMode("application/xml")
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+ return resolveMode("application/json")
+ }
+ if (typeof spec == "string") { return {name: spec} }
+ else { return spec || {name: "null"} }
+ }
+
+ // Given a mode spec (anything that resolveMode accepts), find and
+ // initialize an actual mode object.
+ function getMode(options, spec) {
+ spec = resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) { return getMode(options, "text/plain") }
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) { continue }
+ if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ if (spec.helperType) { modeObj.helperType = spec.helperType; }
+ if (spec.modeProps) { for (var prop$1 in spec.modeProps)
+ { modeObj[prop$1] = spec.modeProps[prop$1]; } }
+
+ return modeObj
+ }
+
+ // This can be used to attach properties to mode objects from
+ // outside the actual mode definition.
+ var modeExtensions = {};
+ function extendMode(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+ }
+
+ function copyState(mode, state) {
+ if (state === true) { return state }
+ if (mode.copyState) { return mode.copyState(state) }
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) { val = val.concat([]); }
+ nstate[n] = val;
+ }
+ return nstate
+ }
+
+ // Given a mode and a state (for that mode), find the inner mode and
+ // state at the position that the state refers to.
+ function innerMode(mode, state) {
+ var info;
+ while (mode.innerMode) {
+ info = mode.innerMode(state);
+ if (!info || info.mode == mode) { break }
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state}
+ }
+
+ function startState(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true
+ }
+
+ // STRING STREAM
+
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
+
+ var StringStream = function(string, tabSize, lineOracle) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ this.lastColumnPos = this.lastColumnValue = 0;
+ this.lineStart = 0;
+ this.lineOracle = lineOracle;
+ };
+
+ StringStream.prototype.eol = function () {return this.pos >= this.string.length};
+ StringStream.prototype.sol = function () {return this.pos == this.lineStart};
+ StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
+ StringStream.prototype.next = function () {
+ if (this.pos < this.string.length)
+ { return this.string.charAt(this.pos++) }
+ };
+ StringStream.prototype.eat = function (match) {
+ var ch = this.string.charAt(this.pos);
+ var ok;
+ if (typeof match == "string") { ok = ch == match; }
+ else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
+ if (ok) {++this.pos; return ch}
+ };
+ StringStream.prototype.eatWhile = function (match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start
+ };
+ StringStream.prototype.eatSpace = function () {
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
+ return this.pos > start
+ };
+ StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
+ StringStream.prototype.skipTo = function (ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true}
+ };
+ StringStream.prototype.backUp = function (n) {this.pos -= n;};
+ StringStream.prototype.column = function () {
+ if (this.lastColumnPos < this.start) {
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+ this.lastColumnPos = this.start;
+ }
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+ };
+ StringStream.prototype.indentation = function () {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+ };
+ StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
+ if (typeof pattern == "string") {
+ var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
+ var substr = this.string.substr(this.pos, pattern.length);
+ if (cased(substr) == cased(pattern)) {
+ if (consume !== false) { this.pos += pattern.length; }
+ return true
+ }
+ } else {
+ var match = this.string.slice(this.pos).match(pattern);
+ if (match && match.index > 0) { return null }
+ if (match && consume !== false) { this.pos += match[0].length; }
+ return match
+ }
+ };
+ StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
+ StringStream.prototype.hideFirstChars = function (n, inner) {
+ this.lineStart += n;
+ try { return inner() }
+ finally { this.lineStart -= n; }
+ };
+ StringStream.prototype.lookAhead = function (n) {
+ var oracle = this.lineOracle;
+ return oracle && oracle.lookAhead(n)
+ };
+ StringStream.prototype.baseToken = function () {
+ var oracle = this.lineOracle;
+ return oracle && oracle.baseToken(this.pos)
+ };
+
+ // Find the line object corresponding to the given line number.
+ function getLine(doc, n) {
+ n -= doc.first;
+ if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
+ var chunk = doc;
+ while (!chunk.lines) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break }
+ n -= sz;
+ }
+ }
+ return chunk.lines[n]
+ }
+
+ // Get the part of a document between two positions, as an array of
+ // strings.
+ function getBetween(doc, start, end) {
+ var out = [], n = start.line;
+ doc.iter(start.line, end.line + 1, function (line) {
+ var text = line.text;
+ if (n == end.line) { text = text.slice(0, end.ch); }
+ if (n == start.line) { text = text.slice(start.ch); }
+ out.push(text);
+ ++n;
+ });
+ return out
+ }
+ // Get the lines between from and to, as array of strings.
+ function getLines(doc, from, to) {
+ var out = [];
+ doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
+ return out
+ }
+
+ // Update the height of a line, propagating the height change
+ // upwards to parent nodes.
+ function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
+ }
+
+ // Given a line object, find its line number by walking up through
+ // its parent links.
+ function lineNo(line) {
+ if (line.parent == null) { return null }
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) { break }
+ no += chunk.children[i].chunkSize();
+ }
+ }
+ return no + cur.first
+ }
+
+ // Find the line at the given vertical position, using the height
+ // information in the document tree.
+ function lineAtHeight(chunk, h) {
+ var n = chunk.first;
+ outer: do {
+ for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
+ var child = chunk.children[i$1], ch = child.height;
+ if (h < ch) { chunk = child; continue outer }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n
+ } while (!chunk.lines)
+ var i = 0;
+ for (; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) { break }
+ h -= lh;
+ }
+ return n + i
+ }
+
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
+
+ function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber))
+ }
+
+ // A Pos instance represents a position within the text.
+ function Pos(line, ch, sticky) {
+ if ( sticky === void 0 ) sticky = null;
+
+ if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
+ this.line = line;
+ this.ch = ch;
+ this.sticky = sticky;
+ }
+
+ // Compare two positions, return 0 if they are the same, a negative
+ // number when a is less, and a positive number otherwise.
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
+
+ function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
+
+ function copyPos(x) {return Pos(x.line, x.ch)}
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
+
+ // Most of the external API clips given positions to make sure they
+ // actually exist within the document.
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
+ function clipPos(doc, pos) {
+ if (pos.line < doc.first) { return Pos(doc.first, 0) }
+ var last = doc.first + doc.size - 1;
+ if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
+ return clipToLen(pos, getLine(doc, pos.line).text.length)
+ }
+ function clipToLen(pos, linelen) {
+ var ch = pos.ch;
+ if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
+ else if (ch < 0) { return Pos(pos.line, 0) }
+ else { return pos }
+ }
+ function clipPosArray(doc, array) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
+ return out
+ }
+
+ var SavedContext = function(state, lookAhead) {
+ this.state = state;
+ this.lookAhead = lookAhead;
+ };
+
+ var Context = function(doc, state, line, lookAhead) {
+ this.state = state;
+ this.doc = doc;
+ this.line = line;
+ this.maxLookAhead = lookAhead || 0;
+ this.baseTokens = null;
+ this.baseTokenPos = 1;
+ };
+
+ Context.prototype.lookAhead = function (n) {
+ var line = this.doc.getLine(this.line + n);
+ if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
+ return line
+ };
+
+ Context.prototype.baseToken = function (n) {
+ if (!this.baseTokens) { return null }
+ while (this.baseTokens[this.baseTokenPos] <= n)
+ { this.baseTokenPos += 2; }
+ var type = this.baseTokens[this.baseTokenPos + 1];
+ return {type: type && type.replace(/( |^)overlay .*/, ""),
+ size: this.baseTokens[this.baseTokenPos] - n}
+ };
+
+ Context.prototype.nextLine = function () {
+ this.line++;
+ if (this.maxLookAhead > 0) { this.maxLookAhead--; }
+ };
+
+ Context.fromSaved = function (doc, saved, line) {
+ if (saved instanceof SavedContext)
+ { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
+ else
+ { return new Context(doc, copyState(doc.mode, saved), line) }
+ };
+
+ Context.prototype.save = function (copy) {
+ var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
+ return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
+ };
+
+
+ // Compute a style array (an array starting with a mode generation
+ // -- for invalidation -- followed by pairs of end positions and
+ // style strings), which is used to highlight the tokens on the
+ // line.
+ function highlightLine(cm, line, context, forceToEnd) {
+ // A styles array always starts with a number identifying the
+ // mode/overlays that it is based on (for easy invalidation).
+ var st = [cm.state.modeGen], lineClasses = {};
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
+ lineClasses, forceToEnd);
+ var state = context.state;
+
+ // Run overlays, adjust style array.
+ var loop = function ( o ) {
+ context.baseTokens = st;
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ context.state = true;
+ runMode(cm, line.text, overlay.mode, context, function (end, style) {
+ var start = i;
+ // Ensure there's a token end at the current position, and that i points at it
+ while (at < end) {
+ var i_end = st[i];
+ if (i_end > end)
+ { st.splice(i, 1, end, st[i+1], i_end); }
+ i += 2;
+ at = Math.min(end, i_end);
+ }
+ if (!style) { return }
+ if (overlay.opaque) {
+ st.splice(start, i - start, end, "overlay " + style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
+ }
+ }
+ }, lineClasses);
+ context.state = state;
+ context.baseTokens = null;
+ context.baseTokenPos = 1;
+ };
+
+ for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
+
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+ }
+
+ function getLineStyles(cm, line, updateFrontier) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
+ var context = getContextBefore(cm, lineNo(line));
+ var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
+ var result = highlightLine(cm, line, context);
+ if (resetState) { context.state = resetState; }
+ line.stateAfter = context.save(!resetState);
+ line.styles = result.styles;
+ if (result.classes) { line.styleClasses = result.classes; }
+ else if (line.styleClasses) { line.styleClasses = null; }
+ if (updateFrontier === cm.doc.highlightFrontier)
+ { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
+ }
+ return line.styles
+ }
+
+ function getContextBefore(cm, n, precise) {
+ var doc = cm.doc, display = cm.display;
+ if (!doc.mode.startState) { return new Context(doc, true, n) }
+ var start = findStartLine(cm, n, precise);
+ var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
+ var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
+
+ doc.iter(start, n, function (line) {
+ processLine(cm, line.text, context);
+ var pos = context.line;
+ line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
+ context.nextLine();
+ });
+ if (precise) { doc.modeFrontier = context.line; }
+ return context
+ }
+
+ // Lightweight form of highlight -- proceed over this line and
+ // update state, but don't save a style array. Used for lines that
+ // aren't currently visible.
+ function processLine(cm, text, context, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize, context);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "") { callBlankLine(mode, context.state); }
+ while (!stream.eol()) {
+ readToken(mode, stream, context.state);
+ stream.start = stream.pos;
+ }
+ }
+
+ function callBlankLine(mode, state) {
+ if (mode.blankLine) { return mode.blankLine(state) }
+ if (!mode.innerMode) { return }
+ var inner = innerMode(mode, state);
+ if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
+ }
+
+ function readToken(mode, stream, state, inner) {
+ for (var i = 0; i < 10; i++) {
+ if (inner) { inner[0] = innerMode(mode, state).mode; }
+ var style = mode.token(stream, state);
+ if (stream.pos > stream.start) { return style }
+ }
+ throw new Error("Mode " + mode.name + " failed to advance stream.")
+ }
+
+ var Token = function(stream, type, state) {
+ this.start = stream.start; this.end = stream.pos;
+ this.string = stream.current();
+ this.type = type || null;
+ this.state = state;
+ };
+
+ // Utility for getTokenAt and getLineTokens
+ function takeToken(cm, pos, precise, asArray) {
+ var doc = cm.doc, mode = doc.mode, style;
+ pos = clipPos(doc, pos);
+ var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
+ var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
+ if (asArray) { tokens = []; }
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+ stream.start = stream.pos;
+ style = readToken(mode, stream, context.state);
+ if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
+ }
+ return asArray ? tokens : new Token(stream, style, context.state)
+ }
+
+ function extractLineClasses(type, output) {
+ if (type) { for (;;) {
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) { break }
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (output[prop] == null)
+ { output[prop] = lineClass[2]; }
+ else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
+ { output[prop] += " " + lineClass[2]; }
+ } }
+ return type
+ }
+
+ // Run the given mode's parser over a line, calling f for each token.
+ function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
+ var flattenSpans = mode.flattenSpans;
+ if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
+ var curStart = 0, curStyle = null;
+ var stream = new StringStream(text, cm.options.tabSize, context), style;
+ var inner = cm.options.addModeClass && [null];
+ if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) { processLine(cm, text, context, stream.pos); }
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
+ }
+ if (inner) {
+ var mName = inner[0].name;
+ if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
+ }
+ if (!flattenSpans || curStyle != style) {
+ while (curStart < stream.start) {
+ curStart = Math.min(stream.start, curStart + 5000);
+ f(curStart, curStyle);
+ }
+ curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444
+ // characters, and returns inaccurate measurements in nodes
+ // starting around 5000 chars.
+ var pos = Math.min(stream.pos, curStart + 5000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
+ }
+
+ // Finds the line to start with when starting a parse. Tries to
+ // find a line with a stateAfter, so that it can start with a
+ // valid state. If that fails, it returns the line with the
+ // smallest indentation, which tends to need the least context to
+ // parse correctly.
+ function findStartLine(cm, n, precise) {
+ var minindent, minline, doc = cm.doc;
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
+ for (var search = n; search > lim; --search) {
+ if (search <= doc.first) { return doc.first }
+ var line = getLine(doc, search - 1), after = line.stateAfter;
+ if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
+ { return search }
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline
+ }
+
+ function retreatFrontier(doc, n) {
+ doc.modeFrontier = Math.min(doc.modeFrontier, n);
+ if (doc.highlightFrontier < n - 10) { return }
+ var start = doc.first;
+ for (var line = n - 1; line > start; line--) {
+ var saved = getLine(doc, line).stateAfter;
+ // change is on 3
+ // state on line 1 looked ahead 2 -- so saw 3
+ // test 1 + 2 < 3 should cover this
+ if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
+ start = line + 1;
+ break
+ }
+ }
+ doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
+ }
+
+ // Optimize some code when these features are not used.
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
+
+ function seeReadOnlySpans() {
+ sawReadOnlySpans = true;
+ }
+
+ function seeCollapsedSpans() {
+ sawCollapsedSpans = true;
+ }
+
+ // TEXTMARKER SPANS
+
+ function MarkedSpan(marker, from, to) {
+ this.marker = marker;
+ this.from = from; this.to = to;
+ }
+
+ // Search an array of spans for a span matching the given marker.
+ function getMarkedSpanFor(spans, marker) {
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) { return span }
+ } }
+ }
+
+ // Remove a span from an array, returning undefined if no spans are
+ // left (we don't store arrays for lines without spans).
+ function removeMarkedSpan(spans, span) {
+ var r;
+ for (var i = 0; i < spans.length; ++i)
+ { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
+ return r
+ }
+
+ // Add a span to a line.
+ function addMarkedSpan(line, span, op) {
+ var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
+ if (inThisOp && line.markedSpans && inThisOp.has(line.markedSpans)) {
+ line.markedSpans.push(span);
+ } else {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ if (inThisOp) { inThisOp.add(line.markedSpans); }
+ }
+ span.marker.attachLine(line);
+ }
+
+ // Used for the algorithm that adjusts markers for a change in the
+ // document. These functions cut an array of spans at a given
+ // character position, returning an array of remaining chunks (or
+ // undefined if nothing remains).
+ function markedSpansBefore(old, startCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
+ ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
+ }
+ } }
+ return nw
+ }
+ function markedSpansAfter(old, endCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
+ ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+ span.to == null ? null : span.to - endCh));
+ }
+ } }
+ return nw
+ }
+
+ // Given a change object, compute the new set of marker spans that
+ // cover the line in which the change took place. Removes spans
+ // entirely within the change, reconnects spans belonging to the
+ // same marker that appear on both sides of the change, and cuts off
+ // spans partially within the change. Returns an array of span
+ // arrays with one element for each line in (after) the change.
+ function stretchSpansOverChange(doc, change) {
+ if (change.full) { return null }
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+ if (!oldFirst && !oldLast) { return null }
+
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+ // Next, merge those two ends
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) { span.to = startCh; }
+ else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
+ }
+ }
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i$1 = 0; i$1 < last.length; ++i$1) {
+ var span$1 = last[i$1];
+ if (span$1.to != null) { span$1.to += offset; }
+ if (span$1.from == null) {
+ var found$1 = getMarkedSpanFor(first, span$1.marker);
+ if (!found$1) {
+ span$1.from = offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ } else {
+ span$1.from += offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ }
+ }
+ // Make sure we didn't create any zero-length spans
+ if (first) { first = clearEmptySpans(first); }
+ if (last && last != first) { last = clearEmptySpans(last); }
+
+ var newMarkers = [first];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = change.text.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ { for (var i$2 = 0; i$2 < first.length; ++i$2)
+ { if (first[i$2].to == null)
+ { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
+ for (var i$3 = 0; i$3 < gap; ++i$3)
+ { newMarkers.push(gapMarkers); }
+ newMarkers.push(last);
+ }
+ return newMarkers
+ }
+
+ // Remove spans that are empty and don't have a clearWhenEmpty
+ // option of false.
+ function clearEmptySpans(spans) {
+ for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+ { spans.splice(i--, 1); }
+ }
+ if (!spans.length) { return null }
+ return spans
+ }
+
+ // Used to 'clip' out readOnly ranges when making a change.
+ function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function (line) {
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ { (markers || (markers = [])).push(mark); }
+ } }
+ });
+ if (!markers) { return null }
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var mk = markers[i], m = mk.find(0);
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+ { newParts.push({from: p.from, to: m.from}); }
+ if (dto > 0 || !mk.inclusiveRight && !dto)
+ { newParts.push({from: m.to, to: p.to}); }
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 3;
+ }
+ }
+ return parts
+ }
+
+ // Connect or disconnect spans from a line.
+ function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.detachLine(line); }
+ line.markedSpans = null;
+ }
+ function attachMarkedSpans(line, spans) {
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.attachLine(line); }
+ line.markedSpans = spans;
+ }
+
+ // Helpers used when computing which overlapping collapsed span
+ // counts as the larger one.
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
+
+ // Returns a number indicating which of two overlapping collapsed
+ // spans is larger (and thus includes the other). Falls back to
+ // comparing ids when the spans cover exactly the same range.
+ function compareCollapsedMarkers(a, b) {
+ var lenDiff = a.lines.length - b.lines.length;
+ if (lenDiff != 0) { return lenDiff }
+ var aPos = a.find(), bPos = b.find();
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
+ if (fromCmp) { return -fromCmp }
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
+ if (toCmp) { return toCmp }
+ return b.id - a.id
+ }
+
+ // Find out whether a line ends or starts in a collapsed span. If
+ // so, return the marker for that span.
+ function collapsedSpanAtSide(line, start) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+ { found = sp.marker; }
+ } }
+ return found
+ }
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
+
+ function collapsedSpanAround(line, ch) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) { for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
+ } }
+ return found
+ }
+
+ // Test whether there exists a collapsed span that partially
+ // overlaps (covers the start or end, but not both) of a new span.
+ // Such overlap is not allowed.
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
+ var line = getLine(doc, lineNo);
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ var found = sp.marker.find(0);
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
+ if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
+ fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
+ { return true }
+ } }
+ }
+
+ // A visual line is a line as drawn on the screen. Folding, for
+ // example, can cause multiple logical lines to appear on the same
+ // visual line. This finds the start of the visual line that the
+ // given line is part of (usually that is the line itself).
+ function visualLine(line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ { line = merged.find(-1, true).line; }
+ return line
+ }
+
+ function visualLineEnd(line) {
+ var merged;
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return line
+ }
+
+ // Returns an array of logical lines that continue the visual line
+ // started by the argument, or undefined if there are no such lines.
+ function visualLineContinued(line) {
+ var merged, lines;
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line
+ ;(lines || (lines = [])).push(line);
+ }
+ return lines
+ }
+
+ // Get the line number of the start of the visual line that the
+ // given line number is part of.
+ function visualLineNo(doc, lineN) {
+ var line = getLine(doc, lineN), vis = visualLine(line);
+ if (line == vis) { return lineN }
+ return lineNo(vis)
+ }
+
+ // Get the line number of the start of the next visual line after
+ // the given line.
+ function visualLineEndNo(doc, lineN) {
+ if (lineN > doc.lastLine()) { return lineN }
+ var line = getLine(doc, lineN), merged;
+ if (!lineIsHidden(doc, line)) { return lineN }
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return lineNo(line) + 1
+ }
+
+ // Compute whether a line is hidden. Lines count as hidden when they
+ // are part of a visual line that starts with another line, or when
+ // they are entirely covered by collapsed, non-widget span.
+ function lineIsHidden(doc, line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ if (sp.from == null) { return true }
+ if (sp.marker.widgetNode) { continue }
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+ { return true }
+ } }
+ }
+ function lineIsHiddenInner(doc, line, span) {
+ if (span.to == null) {
+ var end = span.marker.find(1, true);
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
+ }
+ if (span.marker.inclusiveRight && span.to == line.text.length)
+ { return true }
+ for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+ (sp.to == null || sp.to != span.from) &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(doc, line, sp)) { return true }
+ }
+ }
+
+ // Find the height above the given line.
+ function heightAtLine(lineObj) {
+ lineObj = visualLine(lineObj);
+
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) { break }
+ else { h += line.height; }
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
+ var cur = p.children[i$1];
+ if (cur == chunk) { break }
+ else { h += cur.height; }
+ }
+ }
+ return h
+ }
+
+ // Compute the character length of a line, taking into account
+ // collapsed ranges (see markText) that might hide parts, and join
+ // other lines onto it.
+ function lineLength(line) {
+ if (line.height == 0) { return 0 }
+ var len = line.text.length, merged, cur = line;
+ while (merged = collapsedSpanAtStart(cur)) {
+ var found = merged.find(0, true);
+ cur = found.from.line;
+ len += found.from.ch - found.to.ch;
+ }
+ cur = line;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found$1 = merged.find(0, true);
+ len -= cur.text.length - found$1.from.ch;
+ cur = found$1.to.line;
+ len += cur.text.length - found$1.to.ch;
+ }
+ return len
+ }
+
+ // Find the longest line in the document.
+ function findMaxLine(cm) {
+ var d = cm.display, doc = cm.doc;
+ d.maxLine = getLine(doc, doc.first);
+ d.maxLineLength = lineLength(d.maxLine);
+ d.maxLineChanged = true;
+ doc.iter(function (line) {
+ var len = lineLength(line);
+ if (len > d.maxLineLength) {
+ d.maxLineLength = len;
+ d.maxLine = line;
+ }
+ });
+ }
+
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ var Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
+ };
+
+ Line.prototype.lineNo = function () { return lineNo(this) };
+ eventMixin(Line);
+
+ // Change the content (text, markers) of a line. Automatically
+ // invalidates cached information and tries to re-estimate the
+ // line's height.
+ function updateLine(line, text, markedSpans, estimateHeight) {
+ line.text = text;
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ if (line.order != null) { line.order = null; }
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
+ }
+
+ // Detach a line from the document tree and its markers.
+ function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+ }
+
+ // Convert a style as returned by a mode (either null, or a string
+ // containing one or more styles) to a CSS style. This is cached,
+ // and also looks for line-wide styles.
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
+ function interpretTokenStyle(style, options) {
+ if (!style || /^\s*$/.test(style)) { return null }
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
+ return cache[style] ||
+ (cache[style] = style.replace(/\S+/g, "cm-$&"))
+ }
+
+ // Render the DOM representation of the text of a line. Also builds
+ // up a 'line map', which points at the DOM nodes that represent
+ // specific stretches of text, and is used by the measuring code.
+ // The returned object contains the DOM node, this map, and
+ // information about line-wide styles that were set by the mode.
+ function buildLineContent(cm, lineView) {
+ // The padding-right forces the element to have a 'border', which
+ // is needed on Webkit to be able to get line-level bounding
+ // rectangles for it (in measureChar).
+ var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
+ col: 0, pos: 0, cm: cm,
+ trailingSpace: false,
+ splitSpaces: cm.getOption("lineWrapping")};
+ lineView.measure = {};
+
+ // Iterate over the logical lines that make up this visual line.
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+ var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
+ { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
+ builder.map = [];
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
+ if (line.styleClasses) {
+ if (line.styleClasses.bgClass)
+ { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
+ if (line.styleClasses.textClass)
+ { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
+ }
+
+ // Ensure at least a single node is present, for measuring.
+ if (builder.map.length == 0)
+ { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
+
+ // Store the map and a cache object for the current logical line
+ if (i == 0) {
+ lineView.measure.map = builder.map;
+ lineView.measure.cache = {};
+ } else {
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
+ ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
+ }
+ }
+
+ // See issue #2901
+ if (webkit) {
+ var last = builder.content.lastChild;
+ if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
+ { builder.content.className = "cm-tab-wrap-hack"; }
+ }
+
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ if (builder.pre.className)
+ { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
+
+ return builder
+ }
+
+ function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ token.setAttribute("aria-label", token.title);
+ return token
+ }
+
+ // Build up the DOM representation for a single token, and add it to
+ // the line map. Takes care to render special characters separately.
+ function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
+ if (!text) { return }
+ var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
+ var special = builder.cm.state.specialChars, mustWrap = false;
+ var content;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ content = document.createTextNode(displayText);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie && ie_version < 9) { mustWrap = true; }
+ builder.pos += text.length;
+ } else {
+ content = document.createDocumentFragment();
+ var pos = 0;
+ while (true) {
+ special.lastIndex = pos;
+ var m = special.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
+ else { content.appendChild(txt); }
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
+ builder.col += skipped;
+ builder.pos += skipped;
+ }
+ if (!m) { break }
+ pos += skipped + 1;
+ var txt$1 = (void 0);
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ txt$1.setAttribute("role", "presentation");
+ txt$1.setAttribute("cm-text", "\t");
+ builder.col += tabWidth;
+ } else if (m[0] == "\r" || m[0] == "\n") {
+ txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
+ txt$1.setAttribute("cm-text", m[0]);
+ builder.col += 1;
+ } else {
+ txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
+ txt$1.setAttribute("cm-text", m[0]);
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
+ else { content.appendChild(txt$1); }
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt$1);
+ builder.pos++;
+ }
+ }
+ builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
+ if (style || startStyle || endStyle || mustWrap || css || attributes) {
+ var fullStyle = style || "";
+ if (startStyle) { fullStyle += startStyle; }
+ if (endStyle) { fullStyle += endStyle; }
+ var token = elt("span", [content], fullStyle, css);
+ if (attributes) {
+ for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
+ { token.setAttribute(attr, attributes[attr]); } }
+ }
+ return builder.content.appendChild(token)
+ }
+ builder.content.appendChild(content);
+ }
+
+ // Change some spaces to NBSP to prevent the browser from collapsing
+ // trailing spaces at the end of a line when rendering text (issue #1362).
+ function splitSpaces(text, trailingBefore) {
+ if (text.length > 1 && !/ /.test(text)) { return text }
+ var spaceBefore = trailingBefore, result = "";
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charAt(i);
+ if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+ { ch = "\u00a0"; }
+ result += ch;
+ spaceBefore = ch == " ";
+ }
+ return result
+ }
+
+ // Work around nonsense dimensions being reported for stretches of
+ // right-to-left text.
+ function buildTokenBadBidi(inner, order) {
+ return function (builder, text, style, startStyle, endStyle, css, attributes) {
+ style = style ? style + " cm-force-border" : "cm-force-border";
+ var start = builder.pos, end = start + text.length;
+ for (;;) {
+ // Find the part that overlaps with the start of this text
+ var part = (void 0);
+ for (var i = 0; i < order.length; i++) {
+ part = order[i];
+ if (part.to > start && part.from <= start) { break }
+ }
+ if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
+ startStyle = null;
+ text = text.slice(part.to - start);
+ start = part.to;
+ }
+ }
+ }
+
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+ var widget = !ignoreWidget && marker.widgetNode;
+ if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+ if (!widget)
+ { widget = builder.content.appendChild(document.createElement("span")); }
+ widget.setAttribute("cm-marker", marker.id);
+ }
+ if (widget) {
+ builder.cm.display.input.setUneditable(widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ builder.trailingSpace = false;
+ }
+
+ // Outputs a number of spans to make up a line, taking highlighting
+ // and marked text into account.
+ function insertLineContent(line, builder, styles) {
+ var spans = line.markedSpans, allText = line.text, at = 0;
+ if (!spans) {
+ for (var i$1 = 1; i$1 < styles.length; i$1+=2)
+ { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
+ return
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = css = "";
+ attributes = null;
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [], endStyles = (void 0);
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+ foundBookmarks.push(m);
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+ nextChange = sp.to;
+ spanEndStyle = "";
+ }
+ if (m.className) { spanStyle += " " + m.className; }
+ if (m.css) { css = (css ? css + ";" : "") + m.css; }
+ if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
+ if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
+ // support for the old title property
+ // https://github.com/codemirror/CodeMirror/pull/5673
+ if (m.title) { (attributes || (attributes = {})).title = m.title; }
+ if (m.attributes) {
+ for (var attr in m.attributes)
+ { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
+ }
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ { collapsed = sp; }
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ }
+ if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
+ { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
+
+ if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
+ { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+ collapsed.marker, collapsed.from == null);
+ if (collapsed.to == null) { return }
+ if (collapsed.to == pos) { collapsed = false; }
+ }
+ }
+ if (pos >= len) { break }
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = allText.slice(at, at = styles[i++]);
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
+ }
+ }
+ }
+
+
+ // These objects are used to represent the visible (currently drawn)
+ // part of the document. A LineView may correspond to multiple
+ // logical lines, if those are connected by collapsed ranges.
+ function LineView(doc, line, lineN) {
+ // The starting line
+ this.line = line;
+ // Continuing lines, if any
+ this.rest = visualLineContinued(line);
+ // Number of logical lines in this visual line
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
+ this.node = this.text = null;
+ this.hidden = lineIsHidden(doc, line);
+ }
+
+ // Create a range of LineView objects for the given lines.
+ function buildViewArray(cm, from, to) {
+ var array = [], nextPos;
+ for (var pos = from; pos < to; pos = nextPos) {
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
+ nextPos = pos + view.size;
+ array.push(view);
+ }
+ return array
+ }
+
+ var operationGroup = null;
+
+ function pushOperation(op) {
+ if (operationGroup) {
+ operationGroup.ops.push(op);
+ } else {
+ op.ownsGroup = operationGroup = {
+ ops: [op],
+ delayedCallbacks: []
+ };
+ }
+ }
+
+ function fireCallbacksForOps(group) {
+ // Calls delayed callbacks and cursorActivity handlers until no
+ // new ones appear
+ var callbacks = group.delayedCallbacks, i = 0;
+ do {
+ for (; i < callbacks.length; i++)
+ { callbacks[i].call(null); }
+ for (var j = 0; j < group.ops.length; j++) {
+ var op = group.ops[j];
+ if (op.cursorActivityHandlers)
+ { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
+ { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
+ }
+ } while (i < callbacks.length)
+ }
+
+ function finishOperation(op, endCb) {
+ var group = op.ownsGroup;
+ if (!group) { return }
+
+ try { fireCallbacksForOps(group); }
+ finally {
+ operationGroup = null;
+ endCb(group);
+ }
+ }
+
+ var orphanDelayedCallbacks = null;
+
+ // Often, we want to signal events at a point where we are in the
+ // middle of some work, but don't want the handler to start calling
+ // other methods on the editor, which might be in an inconsistent
+ // state or simply not expect any other events to happen.
+ // signalLater looks whether there are any handlers, and schedules
+ // them to be executed when the last operation ends, or, if no
+ // operation is active, when a timeout fires.
+ function signalLater(emitter, type /*, values...*/) {
+ var arr = getHandlers(emitter, type);
+ if (!arr.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2), list;
+ if (operationGroup) {
+ list = operationGroup.delayedCallbacks;
+ } else if (orphanDelayedCallbacks) {
+ list = orphanDelayedCallbacks;
+ } else {
+ list = orphanDelayedCallbacks = [];
+ setTimeout(fireOrphanDelayed, 0);
+ }
+ var loop = function ( i ) {
+ list.push(function () { return arr[i].apply(null, args); });
+ };
+
+ for (var i = 0; i < arr.length; ++i)
+ loop( i );
+ }
+
+ function fireOrphanDelayed() {
+ var delayed = orphanDelayedCallbacks;
+ orphanDelayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
+ }
+
+ // When an aspect of a line changes, a string is added to
+ // lineView.changes. This updates the relevant part of the line's
+ // DOM structure.
+ function updateLineForChanges(cm, lineView, lineN, dims) {
+ for (var j = 0; j < lineView.changes.length; j++) {
+ var type = lineView.changes[j];
+ if (type == "text") { updateLineText(cm, lineView); }
+ else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
+ else if (type == "class") { updateLineClasses(cm, lineView); }
+ else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
+ }
+ lineView.changes = null;
+ }
+
+ // Lines with gutter elements, widgets or a background class need to
+ // be wrapped, and have the extra elements added to the wrapper div
+ function ensureLineWrapped(lineView) {
+ if (lineView.node == lineView.text) {
+ lineView.node = elt("div", null, null, "position: relative");
+ if (lineView.text.parentNode)
+ { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
+ lineView.node.appendChild(lineView.text);
+ if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
+ }
+ return lineView.node
+ }
+
+ function updateLineBackground(cm, lineView) {
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
+ if (cls) { cls += " CodeMirror-linebackground"; }
+ if (lineView.background) {
+ if (cls) { lineView.background.className = cls; }
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
+ } else if (cls) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
+ cm.display.input.setUneditable(lineView.background);
+ }
+ }
+
+ // Wrapper around buildLineContent which will reuse the structure
+ // in display.externalMeasured when possible.
+ function getLineContent(cm, lineView) {
+ var ext = cm.display.externalMeasured;
+ if (ext && ext.line == lineView.line) {
+ cm.display.externalMeasured = null;
+ lineView.measure = ext.measure;
+ return ext.built
+ }
+ return buildLineContent(cm, lineView)
+ }
+
+ // Redraw the line's text. Interacts with the background and text
+ // classes because the mode may output tokens that influence these
+ // classes.
+ function updateLineText(cm, lineView) {
+ var cls = lineView.text.className;
+ var built = getLineContent(cm, lineView);
+ if (lineView.text == lineView.node) { lineView.node = built.pre; }
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
+ lineView.text = built.pre;
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
+ lineView.bgClass = built.bgClass;
+ lineView.textClass = built.textClass;
+ updateLineClasses(cm, lineView);
+ } else if (cls) {
+ lineView.text.className = cls;
+ }
+ }
+
+ function updateLineClasses(cm, lineView) {
+ updateLineBackground(cm, lineView);
+ if (lineView.line.wrapClass)
+ { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
+ else if (lineView.node != lineView.text)
+ { lineView.node.className = ""; }
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
+ lineView.text.className = textClass || "";
+ }
+
+ function updateLineGutter(cm, lineView, lineN, dims) {
+ if (lineView.gutter) {
+ lineView.node.removeChild(lineView.gutter);
+ lineView.gutter = null;
+ }
+ if (lineView.gutterBackground) {
+ lineView.node.removeChild(lineView.gutterBackground);
+ lineView.gutterBackground = null;
+ }
+ if (lineView.line.gutterClass) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
+ ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(lineView.gutterBackground);
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
+ }
+ var markers = lineView.line.gutterMarkers;
+ if (cm.options.lineNumbers || markers) {
+ var wrap$1 = ensureLineWrapped(lineView);
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
+ gutterWrap.setAttribute("aria-hidden", "true");
+ cm.display.input.setUneditable(gutterWrap);
+ wrap$1.insertBefore(gutterWrap, lineView.text);
+ if (lineView.line.gutterClass)
+ { gutterWrap.className += " " + lineView.line.gutterClass; }
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+ { lineView.lineNumber = gutterWrap.appendChild(
+ elt("div", lineNumberFor(cm.options, lineN),
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
+ if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
+ var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
+ if (found)
+ { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
+ } }
+ }
+ }
+
+ function updateLineWidgets(cm, lineView, dims) {
+ if (lineView.alignable) { lineView.alignable = null; }
+ var isWidget = classTest("CodeMirror-linewidget");
+ for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
+ next = node.nextSibling;
+ if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
+ }
+ insertLineWidgets(cm, lineView, dims);
+ }
+
+ // Build a line's DOM representation from scratch
+ function buildLineElement(cm, lineView, lineN, dims) {
+ var built = getLineContent(cm, lineView);
+ lineView.text = lineView.node = built.pre;
+ if (built.bgClass) { lineView.bgClass = built.bgClass; }
+ if (built.textClass) { lineView.textClass = built.textClass; }
+
+ updateLineClasses(cm, lineView);
+ updateLineGutter(cm, lineView, lineN, dims);
+ insertLineWidgets(cm, lineView, dims);
+ return lineView.node
+ }
+
+ // A lineView may contain multiple logical lines (when merged by
+ // collapsed spans). The widgets for all of them need to be drawn.
+ function insertLineWidgets(cm, lineView, dims) {
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
+ }
+
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
+ if (!line.widgets) { return }
+ var wrap = ensureLineWrapped(lineView);
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
+ if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
+ positionLineWidget(widget, node, lineView, dims);
+ cm.display.input.setUneditable(node);
+ if (allowAbove && widget.above)
+ { wrap.insertBefore(node, lineView.gutter || lineView.text); }
+ else
+ { wrap.appendChild(node); }
+ signalLater(widget, "redraw");
+ }
+ }
+
+ function positionLineWidget(widget, node, lineView, dims) {
+ if (widget.noHScroll) {
+ (lineView.alignable || (lineView.alignable = [])).push(node);
+ var width = dims.wrapperWidth;
+ node.style.left = dims.fixedPos + "px";
+ if (!widget.coverGutter) {
+ width -= dims.gutterTotalWidth;
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ }
+ node.style.width = width + "px";
+ }
+ if (widget.coverGutter) {
+ node.style.zIndex = 5;
+ node.style.position = "relative";
+ if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
+ }
+ }
+
+ function widgetHeight(widget) {
+ if (widget.height != null) { return widget.height }
+ var cm = widget.doc.cm;
+ if (!cm) { return 0 }
+ if (!contains(document.body, widget.node)) {
+ var parentStyle = "position: relative;";
+ if (widget.coverGutter)
+ { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
+ if (widget.noHScroll)
+ { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ }
+ return widget.height = widget.node.parentNode.offsetHeight
+ }
+
+ // Return true when the given mouse event happened in a widget
+ function eventInWidget(display, e) {
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
+ (n.parentNode == display.sizer && n != display.mover))
+ { return true }
+ }
+ }
+
+ // POSITION MEASUREMENT
+
+ function paddingTop(display) {return display.lineSpace.offsetTop}
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
+ function paddingH(display) {
+ if (display.cachedPaddingH) { return display.cachedPaddingH }
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
+ if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
+ return data
+ }
+
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
+ function displayWidth(cm) {
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
+ }
+ function displayHeight(cm) {
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
+ }
+
+ // Ensure the lineView.wrapping.heights array is populated. This is
+ // an array of bottom offsets for the lines that make up a drawn
+ // line. When lineWrapping is on, there might be more than one
+ // height.
+ function ensureLineHeights(cm, lineView, rect) {
+ var wrapping = cm.options.lineWrapping;
+ var curWidth = wrapping && displayWidth(cm);
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
+ var heights = lineView.measure.heights = [];
+ if (wrapping) {
+ lineView.measure.width = curWidth;
+ var rects = lineView.text.firstChild.getClientRects();
+ for (var i = 0; i < rects.length - 1; i++) {
+ var cur = rects[i], next = rects[i + 1];
+ if (Math.abs(cur.bottom - next.bottom) > 2)
+ { heights.push((cur.bottom + next.top) / 2 - rect.top); }
+ }
+ }
+ heights.push(rect.bottom - rect.top);
+ }
+ }
+
+ // Find a line map (mapping character offsets to text nodes) and a
+ // measurement cache for the given line number. (A line view might
+ // contain multiple lines when collapsed ranges are present.)
+ function mapFromLineView(lineView, line, lineN) {
+ if (lineView.line == line)
+ { return {map: lineView.measure.map, cache: lineView.measure.cache} }
+ if (lineView.rest) {
+ for (var i = 0; i < lineView.rest.length; i++)
+ { if (lineView.rest[i] == line)
+ { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
+ for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
+ { if (lineNo(lineView.rest[i$1]) > lineN)
+ { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
+ }
+ }
+
+ // Render a line into the hidden node display.externalMeasured. Used
+ // when measurement is needed for a line that's not in the viewport.
+ function updateExternalMeasurement(cm, line) {
+ line = visualLine(line);
+ var lineN = lineNo(line);
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
+ view.lineN = lineN;
+ var built = view.built = buildLineContent(cm, view);
+ view.text = built.pre;
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
+ return view
+ }
+
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
+ // for a given character.
+ function measureChar(cm, line, ch, bias) {
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
+ }
+
+ // Find a line view that corresponds to the given line number.
+ function findViewForLine(cm, lineN) {
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
+ { return cm.display.view[findViewIndex(cm, lineN)] }
+ var ext = cm.display.externalMeasured;
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
+ { return ext }
+ }
+
+ // Measurement can be split in two steps, the set-up work that
+ // applies to the whole line, and the measurement of the actual
+ // character. Functions like coordsChar, that need to do a lot of
+ // measurements in a row, can thus ensure that the set-up work is
+ // only done once.
+ function prepareMeasureForLine(cm, line) {
+ var lineN = lineNo(line);
+ var view = findViewForLine(cm, lineN);
+ if (view && !view.text) {
+ view = null;
+ } else if (view && view.changes) {
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
+ cm.curOp.forceUpdate = true;
+ }
+ if (!view)
+ { view = updateExternalMeasurement(cm, line); }
+
+ var info = mapFromLineView(view, line, lineN);
+ return {
+ line: line, view: view, rect: null,
+ map: info.map, cache: info.cache, before: info.before,
+ hasHeights: false
+ }
+ }
+
+ // Given a prepared measurement object, measures the position of an
+ // actual character (or fetches it from the cache).
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
+ if (prepared.before) { ch = -1; }
+ var key = ch + (bias || ""), found;
+ if (prepared.cache.hasOwnProperty(key)) {
+ found = prepared.cache[key];
+ } else {
+ if (!prepared.rect)
+ { prepared.rect = prepared.view.text.getBoundingClientRect(); }
+ if (!prepared.hasHeights) {
+ ensureLineHeights(cm, prepared.view, prepared.rect);
+ prepared.hasHeights = true;
+ }
+ found = measureCharInner(cm, prepared, ch, bias);
+ if (!found.bogus) { prepared.cache[key] = found; }
+ }
+ return {left: found.left, right: found.right,
+ top: varHeight ? found.rtop : found.top,
+ bottom: varHeight ? found.rbottom : found.bottom}
+ }
+
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
+
+ function nodeAndOffsetInLineMap(map, ch, bias) {
+ var node, start, end, collapse, mStart, mEnd;
+ // First, search the line map for the text node corresponding to,
+ // or closest to, the target character.
+ for (var i = 0; i < map.length; i += 3) {
+ mStart = map[i];
+ mEnd = map[i + 1];
+ if (ch < mStart) {
+ start = 0; end = 1;
+ collapse = "left";
+ } else if (ch < mEnd) {
+ start = ch - mStart;
+ end = start + 1;
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
+ end = mEnd - mStart;
+ start = end - 1;
+ if (ch >= mEnd) { collapse = "right"; }
+ }
+ if (start != null) {
+ node = map[i + 2];
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
+ { collapse = bias; }
+ if (bias == "left" && start == 0)
+ { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
+ node = map[(i -= 3) + 2];
+ collapse = "left";
+ } }
+ if (bias == "right" && start == mEnd - mStart)
+ { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
+ node = map[(i += 3) + 2];
+ collapse = "right";
+ } }
+ break
+ }
+ }
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
+ }
+
+ function getUsefulRect(rects, bias) {
+ var rect = nullRect;
+ if (bias == "left") { for (var i = 0; i < rects.length; i++) {
+ if ((rect = rects[i]).left != rect.right) { break }
+ } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
+ if ((rect = rects[i$1]).left != rect.right) { break }
+ } }
+ return rect
+ }
+
+ function measureCharInner(cm, prepared, ch, bias) {
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
+
+ var rect;
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+ for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
+ { rect = node.parentNode.getBoundingClientRect(); }
+ else
+ { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
+ if (rect.left || rect.right || start == 0) { break }
+ end = start;
+ start = start - 1;
+ collapse = "right";
+ }
+ if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
+ } else { // If it is a widget, simply get the box for the whole widget.
+ if (start > 0) { collapse = bias = "right"; }
+ var rects;
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
+ { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
+ else
+ { rect = node.getBoundingClientRect(); }
+ }
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
+ var rSpan = node.parentNode.getClientRects()[0];
+ if (rSpan)
+ { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
+ else
+ { rect = nullRect; }
+ }
+
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
+ var mid = (rtop + rbot) / 2;
+ var heights = prepared.view.measure.heights;
+ var i = 0;
+ for (; i < heights.length - 1; i++)
+ { if (mid < heights[i]) { break } }
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
+ top: top, bottom: bot};
+ if (!rect.left && !rect.right) { result.bogus = true; }
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
+
+ return result
+ }
+
+ // Work around problem with bounding client rects on ranges being
+ // returned incorrectly when zoomed on IE10 and below.
+ function maybeUpdateRectForZooming(measure, rect) {
+ if (!window.screen || screen.logicalXDPI == null ||
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
+ { return rect }
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY}
+ }
+
+ function clearLineMeasurementCacheFor(lineView) {
+ if (lineView.measure) {
+ lineView.measure.cache = {};
+ lineView.measure.heights = null;
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { lineView.measure.caches[i] = {}; } }
+ }
+ }
+
+ function clearLineMeasurementCache(cm) {
+ cm.display.externalMeasure = null;
+ removeChildren(cm.display.lineMeasure);
+ for (var i = 0; i < cm.display.view.length; i++)
+ { clearLineMeasurementCacheFor(cm.display.view[i]); }
+ }
+
+ function clearCaches(cm) {
+ clearLineMeasurementCache(cm);
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
+ if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
+ cm.display.lineNumChars = null;
+ }
+
+ function pageScrollX(doc) {
+ // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
+ // which causes page_Offset and bounding client rects to use
+ // different reference viewports and invalidate our calculations.
+ if (chrome && android) { return -(doc.body.getBoundingClientRect().left - parseInt(getComputedStyle(doc.body).marginLeft)) }
+ return doc.defaultView.pageXOffset || (doc.documentElement || doc.body).scrollLeft
+ }
+ function pageScrollY(doc) {
+ if (chrome && android) { return -(doc.body.getBoundingClientRect().top - parseInt(getComputedStyle(doc.body).marginTop)) }
+ return doc.defaultView.pageYOffset || (doc.documentElement || doc.body).scrollTop
+ }
+
+ function widgetTopHeight(lineObj) {
+ var ref = visualLine(lineObj);
+ var widgets = ref.widgets;
+ var height = 0;
+ if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
+ { height += widgetHeight(widgets[i]); } } }
+ return height
+ }
+
+ // Converts a {top, bottom, left, right} box from line-local
+ // coordinates into another coordinate system. Context may be one of
+ // "line", "div" (display.lineDiv), "local"./null (editor), "window",
+ // or "page".
+ function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+ if (!includeWidgets) {
+ var height = widgetTopHeight(lineObj);
+ rect.top += height; rect.bottom += height;
+ }
+ if (context == "line") { return rect }
+ if (!context) { context = "local"; }
+ var yOff = heightAtLine(lineObj);
+ if (context == "local") { yOff += paddingTop(cm.display); }
+ else { yOff -= cm.display.viewOffset; }
+ if (context == "page" || context == "window") {
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY(doc(cm)));
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX(doc(cm)));
+ rect.left += xOff; rect.right += xOff;
+ }
+ rect.top += yOff; rect.bottom += yOff;
+ return rect
+ }
+
+ // Coverts a box from "div" coords to another coordinate system.
+ // Context may be "window", "page", "div", or "local"./null.
+ function fromCoordSystem(cm, coords, context) {
+ if (context == "div") { return coords }
+ var left = coords.left, top = coords.top;
+ // First move into "page" coordinate system
+ if (context == "page") {
+ left -= pageScrollX(doc(cm));
+ top -= pageScrollY(doc(cm));
+ } else if (context == "local" || !context) {
+ var localBox = cm.display.sizer.getBoundingClientRect();
+ left += localBox.left;
+ top += localBox.top;
+ }
+
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
+ }
+
+ function charCoords(cm, pos, context, lineObj, bias) {
+ if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
+ }
+
+ // Returns a box for a given cursor position, which may have an
+ // 'other' property containing the position of the secondary cursor
+ // on a bidi boundary.
+ // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
+ // and after `char - 1` in writing order of `char - 1`
+ // A cursor Pos(line, char, "after") is on the same visual line as `char`
+ // and before `char` in writing order of `char`
+ // Examples (upper-case letters are RTL, lower-case are LTR):
+ // Pos(0, 1, ...)
+ // before after
+ // ab a|b a|b
+ // aB a|B aB|
+ // Ab |Ab A|b
+ // AB B|A B|A
+ // Every position after the last character on a line is considered to stick
+ // to the last character on the line.
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
+ lineObj = lineObj || getLine(cm.doc, pos.line);
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ function get(ch, right) {
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
+ if (right) { m.left = m.right; } else { m.right = m.left; }
+ return intoCoordSystem(cm, lineObj, m, context)
+ }
+ var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
+ if (ch >= lineObj.text.length) {
+ ch = lineObj.text.length;
+ sticky = "before";
+ } else if (ch <= 0) {
+ ch = 0;
+ sticky = "after";
+ }
+ if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
+
+ function getBidi(ch, partPos, invert) {
+ var part = order[partPos], right = part.level == 1;
+ return get(invert ? ch - 1 : ch, right != invert)
+ }
+ var partPos = getBidiPartAt(order, ch, sticky);
+ var other = bidiOther;
+ var val = getBidi(ch, partPos, sticky == "before");
+ if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
+ return val
+ }
+
+ // Used to cheaply estimate the coordinates for a position. Used for
+ // intermediate scroll updates.
+ function estimateCoords(cm, pos) {
+ var left = 0;
+ pos = clipPos(cm.doc, pos);
+ if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
+ var lineObj = getLine(cm.doc, pos.line);
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
+ return {left: left, right: left, top: top, bottom: top + lineObj.height}
+ }
+
+ // Positions returned by coordsChar contain some extra information.
+ // xRel is the relative x position of the input coordinates compared
+ // to the found position (so xRel > 0 means the coordinates are to
+ // the right of the character position, for example). When outside
+ // is true, that means the coordinates lie outside the line's
+ // vertical range.
+ function PosWithInfo(line, ch, sticky, outside, xRel) {
+ var pos = Pos(line, ch, sticky);
+ pos.xRel = xRel;
+ if (outside) { pos.outside = outside; }
+ return pos
+ }
+
+ // Compute the character position closest to the given coordinates.
+ // Input must be lineSpace-local ("div" coordinate system).
+ function coordsChar(cm, x, y) {
+ var doc = cm.doc;
+ y += cm.display.viewOffset;
+ if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
+ if (lineN > last)
+ { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
+ if (x < 0) { x = 0; }
+
+ var lineObj = getLine(doc, lineN);
+ for (;;) {
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
+ var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
+ if (!collapsed) { return found }
+ var rangeEnd = collapsed.find(1);
+ if (rangeEnd.line == lineN) { return rangeEnd }
+ lineObj = getLine(doc, lineN = rangeEnd.line);
+ }
+ }
+
+ function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
+ y -= widgetTopHeight(lineObj);
+ var end = lineObj.text.length;
+ var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
+ end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
+ return {begin: begin, end: end}
+ }
+
+ function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
+ return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
+ }
+
+ // Returns true if the given side of a box is after the given
+ // coordinates, in top-to-bottom, left-to-right order.
+ function boxIsAfter(box, x, y, left) {
+ return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
+ }
+
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
+ // Move y into line-local coordinate space
+ y -= heightAtLine(lineObj);
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
+ // When directly calling `measureCharPrepared`, we have to adjust
+ // for the widgets at this line.
+ var widgetHeight = widgetTopHeight(lineObj);
+ var begin = 0, end = lineObj.text.length, ltr = true;
+
+ var order = getOrder(lineObj, cm.doc.direction);
+ // If the line isn't plain left-to-right text, first figure out
+ // which bidi section the coordinates fall into.
+ if (order) {
+ var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
+ (cm, lineObj, lineNo, preparedMeasure, order, x, y);
+ ltr = part.level != 1;
+ // The awkward -1 offsets are needed because findFirst (called
+ // on these below) will treat its first bound as inclusive,
+ // second as exclusive, but we want to actually address the
+ // characters in the part's range
+ begin = ltr ? part.from : part.to - 1;
+ end = ltr ? part.to : part.from - 1;
+ }
+
+ // A binary search to find the first character whose bounding box
+ // starts after the coordinates. If we run across any whose box wrap
+ // the coordinates, store that.
+ var chAround = null, boxAround = null;
+ var ch = findFirst(function (ch) {
+ var box = measureCharPrepared(cm, preparedMeasure, ch);
+ box.top += widgetHeight; box.bottom += widgetHeight;
+ if (!boxIsAfter(box, x, y, false)) { return false }
+ if (box.top <= y && box.left <= x) {
+ chAround = ch;
+ boxAround = box;
+ }
+ return true
+ }, begin, end);
+
+ var baseX, sticky, outside = false;
+ // If a box around the coordinates was found, use that
+ if (boxAround) {
+ // Distinguish coordinates nearer to the left or right side of the box
+ var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
+ ch = chAround + (atStart ? 0 : 1);
+ sticky = atStart ? "after" : "before";
+ baseX = atLeft ? boxAround.left : boxAround.right;
+ } else {
+ // (Adjust for extended bound, if necessary.)
+ if (!ltr && (ch == end || ch == begin)) { ch++; }
+ // To determine which side to associate with, get the box to the
+ // left of the character and compare it's vertical position to the
+ // coordinates
+ sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
+ (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
+ "after" : "before";
+ // Now get accurate coordinates for this place, in order to get a
+ // base X position
+ var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
+ baseX = coords.left;
+ outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
+ }
+
+ ch = skipExtendingChars(lineObj.text, ch, 1);
+ return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
+ }
+
+ function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
+ // Bidi parts are sorted left-to-right, and in a non-line-wrapping
+ // situation, we can take this ordering to correspond to the visual
+ // ordering. This finds the first part whose end is after the given
+ // coordinates.
+ var index = findFirst(function (i) {
+ var part = order[i], ltr = part.level != 1;
+ return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
+ "line", lineObj, preparedMeasure), x, y, true)
+ }, 0, order.length - 1);
+ var part = order[index];
+ // If this isn't the first part, the part's start is also after
+ // the coordinates, and the coordinates aren't on the same line as
+ // that start, move one part back.
+ if (index > 0) {
+ var ltr = part.level != 1;
+ var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
+ "line", lineObj, preparedMeasure);
+ if (boxIsAfter(start, x, y, true) && start.top > y)
+ { part = order[index - 1]; }
+ }
+ return part
+ }
+
+ function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
+ // In a wrapped line, rtl text on wrapping boundaries can do things
+ // that don't correspond to the ordering in our `order` array at
+ // all, so a binary search doesn't work, and we want to return a
+ // part that only spans one line so that the binary search in
+ // coordsCharInner is safe. As such, we first find the extent of the
+ // wrapped line, and then do a flat search in which we discard any
+ // spans that aren't on the line.
+ var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
+ var begin = ref.begin;
+ var end = ref.end;
+ if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
+ var part = null, closestDist = null;
+ for (var i = 0; i < order.length; i++) {
+ var p = order[i];
+ if (p.from >= end || p.to <= begin) { continue }
+ var ltr = p.level != 1;
+ var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
+ // Weigh against spans ending before this, so that they are only
+ // picked if nothing ends after
+ var dist = endX < x ? x - endX + 1e9 : endX - x;
+ if (!part || closestDist > dist) {
+ part = p;
+ closestDist = dist;
+ }
+ }
+ if (!part) { part = order[order.length - 1]; }
+ // Clip the part to the wrapped line.
+ if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
+ if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
+ return part
+ }
+
+ var measureText;
+ // Compute the default text height.
+ function textHeight(display) {
+ if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+ if (measureText == null) {
+ measureText = elt("pre", null, "CodeMirror-line-like");
+ // Measure a bunch of lines, for browsers that compute
+ // fractional heights.
+ for (var i = 0; i < 49; ++i) {
+ measureText.appendChild(document.createTextNode("x"));
+ measureText.appendChild(elt("br"));
+ }
+ measureText.appendChild(document.createTextNode("x"));
+ }
+ removeChildrenAndAdd(display.measure, measureText);
+ var height = measureText.offsetHeight / 50;
+ if (height > 3) { display.cachedTextHeight = height; }
+ removeChildren(display.measure);
+ return height || 1
+ }
+
+ // Compute the default character width.
+ function charWidth(display) {
+ if (display.cachedCharWidth != null) { return display.cachedCharWidth }
+ var anchor = elt("span", "xxxxxxxxxx");
+ var pre = elt("pre", [anchor], "CodeMirror-line-like");
+ removeChildrenAndAdd(display.measure, pre);
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
+ if (width > 2) { display.cachedCharWidth = width; }
+ return width || 10
+ }
+
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
+ // view, so that we don't interleave reading and writing to the DOM.
+ function getDimensions(cm) {
+ var d = cm.display, left = {}, width = {};
+ var gutterLeft = d.gutters.clientLeft;
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ var id = cm.display.gutterSpecs[i].className;
+ left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
+ width[id] = n.clientWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth}
+ }
+
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
+ // but using getBoundingClientRect to get a sub-pixel-accurate
+ // result.
+ function compensateForHScroll(display) {
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
+ }
+
+ // Returns a function that estimates the height of a line, to use as
+ // first approximation until the line becomes visible (and is thus
+ // properly measurable).
+ function estimateHeight(cm) {
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
+ return function (line) {
+ if (lineIsHidden(cm.doc, line)) { return 0 }
+
+ var widgetsHeight = 0;
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
+ if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
+ } }
+
+ if (wrapping)
+ { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
+ else
+ { return widgetsHeight + th }
+ }
+ }
+
+ function estimateLineHeights(cm) {
+ var doc = cm.doc, est = estimateHeight(cm);
+ doc.iter(function (line) {
+ var estHeight = est(line);
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
+ });
+ }
+
+ // Given a mouse event, find the corresponding position. If liberal
+ // is false, it checks whether a gutter or scrollbar was clicked,
+ // and returns null if it was. forRect is used by rectangular
+ // selections, and tries to estimate a character position even for
+ // coordinates beyond the right of the text.
+ function posFromMouse(cm, e, liberal, forRect) {
+ var display = cm.display;
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
+
+ var x, y, space = display.lineSpace.getBoundingClientRect();
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
+ catch (e$1) { return null }
+ var coords = coordsChar(cm, x, y), line;
+ if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
+ }
+ return coords
+ }
+
+ // Find the view element corresponding to a given line. Return null
+ // when the line isn't visible.
+ function findViewIndex(cm, n) {
+ if (n >= cm.display.viewTo) { return null }
+ n -= cm.display.viewFrom;
+ if (n < 0) { return null }
+ var view = cm.display.view;
+ for (var i = 0; i < view.length; i++) {
+ n -= view[i].size;
+ if (n < 0) { return i }
+ }
+ }
+
+ // Updates the display.view data structure for a given change to the
+ // document. From and to are in pre-change coordinates. Lendiff is
+ // the amount of lines added or subtracted by the change. This is
+ // used for changes that span multiple lines, or change the way
+ // lines are divided into visual lines. regLineChange (below)
+ // registers single-line changes.
+ function regChange(cm, from, to, lendiff) {
+ if (from == null) { from = cm.doc.first; }
+ if (to == null) { to = cm.doc.first + cm.doc.size; }
+ if (!lendiff) { lendiff = 0; }
+
+ var display = cm.display;
+ if (lendiff && to < display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
+ { display.updateLineNumbers = from; }
+
+ cm.curOp.viewChanged = true;
+
+ if (from >= display.viewTo) { // Change after
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
+ { resetView(cm); }
+ } else if (to <= display.viewFrom) { // Change before
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
+ resetView(cm);
+ } else {
+ display.viewFrom += lendiff;
+ display.viewTo += lendiff;
+ }
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
+ resetView(cm);
+ } else if (from <= display.viewFrom) { // Top overlap
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cut) {
+ display.view = display.view.slice(cut.index);
+ display.viewFrom = cut.lineN;
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ } else if (to >= display.viewTo) { // Bottom overlap
+ var cut$1 = viewCuttingPoint(cm, from, from, -1);
+ if (cut$1) {
+ display.view = display.view.slice(0, cut$1.index);
+ display.viewTo = cut$1.lineN;
+ } else {
+ resetView(cm);
+ }
+ } else { // Gap in the middle
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cutTop && cutBot) {
+ display.view = display.view.slice(0, cutTop.index)
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
+ .concat(display.view.slice(cutBot.index));
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ }
+
+ var ext = display.externalMeasured;
+ if (ext) {
+ if (to < ext.lineN)
+ { ext.lineN += lendiff; }
+ else if (from < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
+ }
+ }
+
+ // Register a change to a single line. Type must be one of "text",
+ // "gutter", "class", "widget"
+ function regLineChange(cm, line, type) {
+ cm.curOp.viewChanged = true;
+ var display = cm.display, ext = cm.display.externalMeasured;
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
+
+ if (line < display.viewFrom || line >= display.viewTo) { return }
+ var lineView = display.view[findViewIndex(cm, line)];
+ if (lineView.node == null) { return }
+ var arr = lineView.changes || (lineView.changes = []);
+ if (indexOf(arr, type) == -1) { arr.push(type); }
+ }
+
+ // Clear the view.
+ function resetView(cm) {
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
+ cm.display.view = [];
+ cm.display.viewOffset = 0;
+ }
+
+ function viewCuttingPoint(cm, oldN, newN, dir) {
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
+ { return {index: index, lineN: newN} }
+ var n = cm.display.viewFrom;
+ for (var i = 0; i < index; i++)
+ { n += view[i].size; }
+ if (n != oldN) {
+ if (dir > 0) {
+ if (index == view.length - 1) { return null }
+ diff = (n + view[index].size) - oldN;
+ index++;
+ } else {
+ diff = n - oldN;
+ }
+ oldN += diff; newN += diff;
+ }
+ while (visualLineNo(cm.doc, newN) != newN) {
+ if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
+ index += dir;
+ }
+ return {index: index, lineN: newN}
+ }
+
+ // Force the view to cover a given range, adding empty view element
+ // or clipping off existing ones as needed.
+ function adjustView(cm, from, to) {
+ var display = cm.display, view = display.view;
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
+ display.view = buildViewArray(cm, from, to);
+ display.viewFrom = from;
+ } else {
+ if (display.viewFrom > from)
+ { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
+ else if (display.viewFrom < from)
+ { display.view = display.view.slice(findViewIndex(cm, from)); }
+ display.viewFrom = from;
+ if (display.viewTo < to)
+ { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
+ else if (display.viewTo > to)
+ { display.view = display.view.slice(0, findViewIndex(cm, to)); }
+ }
+ display.viewTo = to;
+ }
+
+ // Count the number of lines in the view whose DOM representation is
+ // out of date (or nonexistent).
+ function countDirtyView(cm) {
+ var view = cm.display.view, dirty = 0;
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
+ }
+ return dirty
+ }
+
+ function updateSelection(cm) {
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
+ }
+
+ function prepareSelection(cm, primary) {
+ if ( primary === void 0 ) primary = true;
+
+ var doc = cm.doc, result = {};
+ var curFragment = result.cursors = document.createDocumentFragment();
+ var selFragment = result.selection = document.createDocumentFragment();
+
+ var customCursor = cm.options.$customCursor;
+ if (customCursor) { primary = true; }
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ if (!primary && i == doc.sel.primIndex) { continue }
+ var range = doc.sel.ranges[i];
+ if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
+ var collapsed = range.empty();
+ if (customCursor) {
+ var head = customCursor(cm, range);
+ if (head) { drawSelectionCursor(cm, head, curFragment); }
+ } else if (collapsed || cm.options.showCursorWhenSelecting) {
+ drawSelectionCursor(cm, range.head, curFragment);
+ }
+ if (!collapsed)
+ { drawSelectionRange(cm, range, selFragment); }
+ }
+ return result
+ }
+
+ // Draws a cursor for the given range
+ function drawSelectionCursor(cm, head, output) {
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
+
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
+ cursor.style.left = pos.left + "px";
+ cursor.style.top = pos.top + "px";
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+
+ if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
+ var charPos = charCoords(cm, head, "div", null, null);
+ var width = charPos.right - charPos.left;
+ cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
+ }
+
+ if (pos.other) {
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
+ otherCursor.style.display = "";
+ otherCursor.style.left = pos.other.left + "px";
+ otherCursor.style.top = pos.other.top + "px";
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+ }
+ }
+
+ function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
+
+ // Draws the given range as a highlighted selection
+ function drawSelectionRange(cm, range, output) {
+ var display = cm.display, doc = cm.doc;
+ var fragment = document.createDocumentFragment();
+ var padding = paddingH(cm.display), leftSide = padding.left;
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
+ var docLTR = doc.direction == "ltr";
+
+ function add(left, top, width, bottom) {
+ if (top < 0) { top = 0; }
+ top = Math.round(top);
+ bottom = Math.round(bottom);
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
+ }
+
+ function drawForLine(line, fromArg, toArg) {
+ var lineObj = getLine(doc, line);
+ var lineLen = lineObj.text.length;
+ var start, end;
+ function coords(ch, bias) {
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
+ }
+
+ function wrapX(pos, dir, side) {
+ var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
+ var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
+ var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
+ return coords(ch, prop)[prop]
+ }
+
+ var order = getOrder(lineObj, doc.direction);
+ iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
+ var ltr = dir == "ltr";
+ var fromPos = coords(from, ltr ? "left" : "right");
+ var toPos = coords(to - 1, ltr ? "right" : "left");
+
+ var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
+ var first = i == 0, last = !order || i == order.length - 1;
+ if (toPos.top - fromPos.top <= 3) { // Single line
+ var openLeft = (docLTR ? openStart : openEnd) && first;
+ var openRight = (docLTR ? openEnd : openStart) && last;
+ var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
+ var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
+ add(left, fromPos.top, right - left, fromPos.bottom);
+ } else { // Multiple lines
+ var topLeft, topRight, botLeft, botRight;
+ if (ltr) {
+ topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
+ topRight = docLTR ? rightSide : wrapX(from, dir, "before");
+ botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
+ botRight = docLTR && openEnd && last ? rightSide : toPos.right;
+ } else {
+ topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
+ topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
+ botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
+ botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
+ }
+ add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
+ if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
+ add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
+ }
+
+ if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
+ if (cmpCoords(toPos, start) < 0) { start = toPos; }
+ if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
+ if (cmpCoords(toPos, end) < 0) { end = toPos; }
+ });
+ return {start: start, end: end}
+ }
+
+ var sFrom = range.from(), sTo = range.to();
+ if (sFrom.line == sTo.line) {
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
+ } else {
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
+ if (singleVLine) {
+ if (leftEnd.top < rightStart.top - 2) {
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
+ } else {
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
+ }
+ }
+ if (leftEnd.bottom < rightStart.top)
+ { add(leftSide, leftEnd.bottom, null, rightStart.top); }
+ }
+
+ output.appendChild(fragment);
+ }
+
+ // Cursor-blinking
+ function restartBlink(cm) {
+ if (!cm.state.focused) { return }
+ var display = cm.display;
+ clearInterval(display.blinker);
+ var on = true;
+ display.cursorDiv.style.visibility = "";
+ if (cm.options.cursorBlinkRate > 0)
+ { display.blinker = setInterval(function () {
+ if (!cm.hasFocus()) { onBlur(cm); }
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
+ }, cm.options.cursorBlinkRate); }
+ else if (cm.options.cursorBlinkRate < 0)
+ { display.cursorDiv.style.visibility = "hidden"; }
+ }
+
+ function ensureFocus(cm) {
+ if (!cm.hasFocus()) {
+ cm.display.input.focus();
+ if (!cm.state.focused) { onFocus(cm); }
+ }
+ }
+
+ function delayBlurEvent(cm) {
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function () { if (cm.state.delayingBlurEvent) {
+ cm.state.delayingBlurEvent = false;
+ if (cm.state.focused) { onBlur(cm); }
+ } }, 100);
+ }
+
+ function onFocus(cm, e) {
+ if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
+
+ if (cm.options.readOnly == "nocursor") { return }
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm, e);
+ cm.state.focused = true;
+ addClass(cm.display.wrapper, "CodeMirror-focused");
+ // This test prevents this from firing when a context
+ // menu is closed (since the input reset would kill the
+ // select-all detection hack)
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+ cm.display.input.reset();
+ if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
+ }
+ cm.display.input.receivedFocus();
+ }
+ restartBlink(cm);
+ }
+ function onBlur(cm, e) {
+ if (cm.state.delayingBlurEvent) { return }
+
+ if (cm.state.focused) {
+ signal(cm, "blur", cm, e);
+ cm.state.focused = false;
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
+ }
+
+ // Read the actual heights of the rendered lines, and update their
+ // stored heights to match.
+ function updateHeightsInViewport(cm) {
+ var display = cm.display;
+ var prevBottom = display.lineDiv.offsetTop;
+ var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
+ var oldHeight = display.lineDiv.getBoundingClientRect().top;
+ var mustScroll = 0;
+ for (var i = 0; i < display.view.length; i++) {
+ var cur = display.view[i], wrapping = cm.options.lineWrapping;
+ var height = (void 0), width = 0;
+ if (cur.hidden) { continue }
+ oldHeight += cur.line.height;
+ if (ie && ie_version < 8) {
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
+ } else {
+ var box = cur.node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ // Check that lines don't extend past the right of the current
+ // editor width
+ if (!wrapping && cur.text.firstChild)
+ { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
+ }
+ var diff = cur.line.height - height;
+ if (diff > .005 || diff < -.005) {
+ if (oldHeight < viewTop) { mustScroll -= diff; }
+ updateLineHeight(cur.line, height);
+ updateWidgetHeight(cur.line);
+ if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
+ { updateWidgetHeight(cur.rest[j]); } }
+ }
+ if (width > cm.display.sizerWidth) {
+ var chWidth = Math.ceil(width / charWidth(cm.display));
+ if (chWidth > cm.display.maxLineLength) {
+ cm.display.maxLineLength = chWidth;
+ cm.display.maxLine = cur.line;
+ cm.display.maxLineChanged = true;
+ }
+ }
+ }
+ if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
+ }
+
+ // Read and store the height of line widgets associated with the
+ // given line.
+ function updateWidgetHeight(line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
+ var w = line.widgets[i], parent = w.node.parentNode;
+ if (parent) { w.height = parent.offsetHeight; }
+ } }
+ }
+
+ // Compute the lines that are visible in a given viewport (defaults
+ // the the current scroll position). viewport may contain top,
+ // height, and ensure (see op.scrollToPos) properties.
+ function visibleLines(display, doc, viewport) {
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
+ top = Math.floor(top - paddingTop(display));
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
+
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
+ // forces those lines into the viewport (if possible).
+ if (viewport && viewport.ensure) {
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
+ if (ensureFrom < from) {
+ from = ensureFrom;
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
+ to = ensureTo;
+ }
+ }
+ return {from: from, to: Math.max(to, from + 1)}
+ }
+
+ // SCROLLING THINGS INTO VIEW
+
+ // If an editor sits on the top or bottom of the window, partially
+ // scrolled out of view, this ensures that the cursor is visible.
+ function maybeScrollWindow(cm, rect) {
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ var doc = display.wrapper.ownerDocument;
+ if (rect.top + box.top < 0) { doScroll = true; }
+ else if (rect.bottom + box.top > (doc.defaultView.innerHeight || doc.documentElement.clientHeight)) { doScroll = false; }
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
+ cm.display.lineSpace.appendChild(scrollNode);
+ scrollNode.scrollIntoView(doScroll);
+ cm.display.lineSpace.removeChild(scrollNode);
+ }
+ }
+
+ // Scroll a given position into view (immediately), verifying that
+ // it actually became visible (as line heights are accurately
+ // measured, the position of something may 'drift' during drawing).
+ function scrollPosIntoView(cm, pos, end, margin) {
+ if (margin == null) { margin = 0; }
+ var rect;
+ if (!cm.options.lineWrapping && pos == end) {
+ // Set pos and end to the cursor positions around the character pos sticks to
+ // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
+ // If pos == Pos(_, 0, "before"), pos and end are unchanged
+ end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
+ pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
+ }
+ for (var limit = 0; limit < 5; limit++) {
+ var changed = false;
+ var coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ rect = {left: Math.min(coords.left, endCoords.left),
+ top: Math.min(coords.top, endCoords.top) - margin,
+ right: Math.max(coords.left, endCoords.left),
+ bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
+ var scrollPos = calculateScrollPos(cm, rect);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ updateScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
+ }
+ if (!changed) { break }
+ }
+ return rect
+ }
+
+ // Scroll a given set of coordinates into view (immediately).
+ function scrollIntoView(cm, rect) {
+ var scrollPos = calculateScrollPos(cm, rect);
+ if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
+ if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
+ }
+
+ // Calculate a new scroll position needed to scroll the given
+ // rectangle into view. Returns an object with scrollTop and
+ // scrollLeft properties. When these are undefined, the
+ // vertical/horizontal position does not need to be adjusted.
+ function calculateScrollPos(cm, rect) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (rect.top < 0) { rect.top = 0; }
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = displayHeight(cm), result = {};
+ if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
+ if (rect.top < screentop) {
+ result.scrollTop = atTop ? 0 : rect.top;
+ } else if (rect.bottom > screentop + screen) {
+ var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
+ if (newTop != screentop) { result.scrollTop = newTop; }
+ }
+
+ var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
+ var screenw = displayWidth(cm) - display.gutters.offsetWidth;
+ var tooWide = rect.right - rect.left > screenw;
+ if (tooWide) { rect.right = rect.left + screenw; }
+ if (rect.left < 10)
+ { result.scrollLeft = 0; }
+ else if (rect.left < screenleft)
+ { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
+ else if (rect.right > screenw + screenleft - 3)
+ { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
+ return result
+ }
+
+ // Store a relative adjustment to the scroll position in the current
+ // operation (to be applied when the operation finishes).
+ function addToScrollTop(cm, top) {
+ if (top == null) { return }
+ resolveScrollToPos(cm);
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
+ }
+
+ // Make sure that at the end of the operation the current cursor is
+ // shown.
+ function ensureCursorVisible(cm) {
+ resolveScrollToPos(cm);
+ var cur = cm.getCursor();
+ cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
+ }
+
+ function scrollToCoords(cm, x, y) {
+ if (x != null || y != null) { resolveScrollToPos(cm); }
+ if (x != null) { cm.curOp.scrollLeft = x; }
+ if (y != null) { cm.curOp.scrollTop = y; }
+ }
+
+ function scrollToRange(cm, range) {
+ resolveScrollToPos(cm);
+ cm.curOp.scrollToPos = range;
+ }
+
+ // When an operation has its scrollToPos property set, and another
+ // scroll action is applied before the end of the operation, this
+ // 'simulates' scrolling that position into view in a cheap way, so
+ // that the effect of intermediate scroll commands is not ignored.
+ function resolveScrollToPos(cm) {
+ var range = cm.curOp.scrollToPos;
+ if (range) {
+ cm.curOp.scrollToPos = null;
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
+ scrollToCoordsRange(cm, from, to, range.margin);
+ }
+ }
+
+ function scrollToCoordsRange(cm, from, to, margin) {
+ var sPos = calculateScrollPos(cm, {
+ left: Math.min(from.left, to.left),
+ top: Math.min(from.top, to.top) - margin,
+ right: Math.max(from.right, to.right),
+ bottom: Math.max(from.bottom, to.bottom) + margin
+ });
+ scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
+ }
+
+ // Sync the scrollable area and scrollbars, ensure the viewport
+ // covers the visible area.
+ function updateScrollTop(cm, val) {
+ if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
+ if (!gecko) { updateDisplaySimple(cm, {top: val}); }
+ setScrollTop(cm, val, true);
+ if (gecko) { updateDisplaySimple(cm); }
+ startWorker(cm, 100);
+ }
+
+ function setScrollTop(cm, val, forceScroll) {
+ val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
+ if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
+ cm.doc.scrollTop = val;
+ cm.display.scrollbars.setScrollTop(val);
+ if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
+ }
+
+ // Sync scroller and scrollbar, ensure the gutter elements are
+ // aligned.
+ function setScrollLeft(cm, val, isScroller, forceScroll) {
+ val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
+ if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
+ cm.doc.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
+ cm.display.scrollbars.setScrollLeft(val);
+ }
+
+ // SCROLLBARS
+
+ // Prepare DOM reads needed to update the scrollbars. Done in one
+ // shot to minimize update/measure roundtrips.
+ function measureForScrollbars(cm) {
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
+ return {
+ clientHeight: d.scroller.clientHeight,
+ viewHeight: d.wrapper.clientHeight,
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
+ viewWidth: d.wrapper.clientWidth,
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
+ docHeight: docH,
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
+ nativeBarWidth: d.nativeBarWidth,
+ gutterWidth: gutterW
+ }
+ }
+
+ var NativeScrollbars = function(place, scroll, cm) {
+ this.cm = cm;
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
+ vert.tabIndex = horiz.tabIndex = -1;
+ place(vert); place(horiz);
+
+ on(vert, "scroll", function () {
+ if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
+ });
+ on(horiz, "scroll", function () {
+ if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
+ });
+
+ this.checkedZeroWidth = false;
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
+ };
+
+ NativeScrollbars.prototype.update = function (measure) {
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
+ var sWidth = measure.nativeBarWidth;
+
+ if (needsV) {
+ this.vert.style.display = "block";
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
+ // A bug in IE8 can cause this value to be negative, so guard it.
+ this.vert.firstChild.style.height =
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
+ } else {
+ this.vert.scrollTop = 0;
+ this.vert.style.display = "";
+ this.vert.firstChild.style.height = "0";
+ }
+
+ if (needsH) {
+ this.horiz.style.display = "block";
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
+ this.horiz.style.left = measure.barLeft + "px";
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
+ this.horiz.firstChild.style.width =
+ Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
+ } else {
+ this.horiz.style.display = "";
+ this.horiz.firstChild.style.width = "0";
+ }
+
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
+ if (sWidth == 0) { this.zeroWidthHack(); }
+ this.checkedZeroWidth = true;
+ }
+
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+ };
+
+ NativeScrollbars.prototype.setScrollLeft = function (pos) {
+ if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
+ if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
+ };
+
+ NativeScrollbars.prototype.setScrollTop = function (pos) {
+ if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
+ if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
+ };
+
+ NativeScrollbars.prototype.zeroWidthHack = function () {
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
+ this.horiz.style.height = this.vert.style.width = w;
+ this.horiz.style.visibility = this.vert.style.visibility = "hidden";
+ this.disableHoriz = new Delayed;
+ this.disableVert = new Delayed;
+ };
+
+ NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
+ bar.style.visibility = "";
+ function maybeDisable() {
+ // To find out whether the scrollbar is still visible, we
+ // check whether the element under the pixel in the bottom
+ // right corner of the scrollbar box is the scrollbar box
+ // itself (when the bar is still visible) or its filler child
+ // (when the bar is hidden). If it is still visible, we keep
+ // it enabled, if it's hidden, we disable pointer events.
+ var box = bar.getBoundingClientRect();
+ var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
+ : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
+ if (elt != bar) { bar.style.visibility = "hidden"; }
+ else { delay.set(1000, maybeDisable); }
+ }
+ delay.set(1000, maybeDisable);
+ };
+
+ NativeScrollbars.prototype.clear = function () {
+ var parent = this.horiz.parentNode;
+ parent.removeChild(this.horiz);
+ parent.removeChild(this.vert);
+ };
+
+ var NullScrollbars = function () {};
+
+ NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+ NullScrollbars.prototype.setScrollLeft = function () {};
+ NullScrollbars.prototype.setScrollTop = function () {};
+ NullScrollbars.prototype.clear = function () {};
+
+ function updateScrollbars(cm, measure) {
+ if (!measure) { measure = measureForScrollbars(cm); }
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
+ updateScrollbarsInner(cm, measure);
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
+ { updateHeightsInViewport(cm); }
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
+ }
+ }
+
+ // Re-synchronize the fake scrollbars with the actual size of the
+ // content.
+ function updateScrollbarsInner(cm, measure) {
+ var d = cm.display;
+ var sizes = d.scrollbars.update(measure);
+
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
+
+ if (sizes.right && sizes.bottom) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
+ d.scrollbarFiller.style.width = sizes.right + "px";
+ } else { d.scrollbarFiller.style.display = ""; }
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+ d.gutterFiller.style.display = "block";
+ d.gutterFiller.style.height = sizes.bottom + "px";
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
+ } else { d.gutterFiller.style.display = ""; }
+ }
+
+ var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
+
+ function initScrollbars(cm) {
+ if (cm.display.scrollbars) {
+ cm.display.scrollbars.clear();
+ if (cm.display.scrollbars.addClass)
+ { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ }
+
+ cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
+ // Prevent clicks in the scrollbars from killing focus
+ on(node, "mousedown", function () {
+ if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
+ });
+ node.setAttribute("cm-not-content", "true");
+ }, function (pos, axis) {
+ if (axis == "horizontal") { setScrollLeft(cm, pos); }
+ else { updateScrollTop(cm, pos); }
+ }, cm);
+ if (cm.display.scrollbars.addClass)
+ { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ }
+
+ // Operations are used to wrap a series of changes to the editor
+ // state in such a way that each change won't have to update the
+ // cursor and display (which would be awkward, slow, and
+ // error-prone). Instead, display updates are batched and then all
+ // combined and executed at once.
+
+ var nextOpId = 0;
+ // Start a new operation.
+ function startOperation(cm) {
+ cm.curOp = {
+ cm: cm,
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
+ forceUpdate: false, // Used to force a redraw
+ updateInput: 0, // Whether to reset the input textarea
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
+ changeObjs: null, // Accumulated changes, for firing change events
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
+ selectionChanged: false, // Whether the selection needs to be redrawn
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
+ scrollToPos: null, // Used to scroll to a specific position
+ focus: false,
+ id: ++nextOpId, // Unique ID
+ markArrays: null // Used by addMarkedSpan
+ };
+ pushOperation(cm.curOp);
+ }
+
+ // Finish an operation, updating the display and signalling delayed events
+ function endOperation(cm) {
+ var op = cm.curOp;
+ if (op) { finishOperation(op, function (group) {
+ for (var i = 0; i < group.ops.length; i++)
+ { group.ops[i].cm.curOp = null; }
+ endOperations(group);
+ }); }
+ }
+
+ // The DOM updates done when an operation finishes are batched so
+ // that the minimum number of relayouts are required.
+ function endOperations(group) {
+ var ops = group.ops;
+ for (var i = 0; i < ops.length; i++) // Read DOM
+ { endOperation_R1(ops[i]); }
+ for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
+ { endOperation_W1(ops[i$1]); }
+ for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
+ { endOperation_R2(ops[i$2]); }
+ for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
+ { endOperation_W2(ops[i$3]); }
+ for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
+ { endOperation_finish(ops[i$4]); }
+ }
+
+ function endOperation_R1(op) {
+ var cm = op.cm, display = cm.display;
+ maybeClipScrollbars(cm);
+ if (op.updateMaxLine) { findMaxLine(cm); }
+
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
+ op.scrollToPos.to.line >= display.viewTo) ||
+ display.maxLineChanged && cm.options.lineWrapping;
+ op.update = op.mustUpdate &&
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
+ }
+
+ function endOperation_W1(op) {
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
+ }
+
+ function endOperation_R2(op) {
+ var cm = op.cm, display = cm.display;
+ if (op.updatedDisplay) { updateHeightsInViewport(cm); }
+
+ op.barMeasure = measureForScrollbars(cm);
+
+ // If the max line changed since it was last measured, measure it,
+ // and ensure the document's width matches it.
+ // updateDisplay_W2 will use these properties to do the actual resizing
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
+ cm.display.sizerWidth = op.adjustWidthTo;
+ op.barMeasure.scrollWidth =
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
+ }
+
+ if (op.updatedDisplay || op.selectionChanged)
+ { op.preparedSelection = display.input.prepareSelection(); }
+ }
+
+ function endOperation_W2(op) {
+ var cm = op.cm;
+
+ if (op.adjustWidthTo != null) {
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
+ { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
+ cm.display.maxLineChanged = false;
+ }
+
+ var takeFocus = op.focus && op.focus == activeElt(doc(cm));
+ if (op.preparedSelection)
+ { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
+ { updateScrollbars(cm, op.barMeasure); }
+ if (op.updatedDisplay)
+ { setDocumentHeight(cm, op.barMeasure); }
+
+ if (op.selectionChanged) { restartBlink(cm); }
+
+ if (cm.state.focused && op.updateInput)
+ { cm.display.input.reset(op.typing); }
+ if (takeFocus) { ensureFocus(op.cm); }
+ }
+
+ function endOperation_finish(op) {
+ var cm = op.cm, display = cm.display, doc = cm.doc;
+
+ if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
+
+ // Abort mouse wheel delta measurement, when scrolling explicitly
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
+ { display.wheelStartX = display.wheelStartY = null; }
+
+ // Propagate the scroll position to the actual DOM scroller
+ if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
+
+ if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
+ // If we need to scroll a specific position into view, do so.
+ if (op.scrollToPos) {
+ var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
+ maybeScrollWindow(cm, rect);
+ }
+
+ // Fire events for markers that are hidden/unidden by editing or
+ // undoing
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
+ if (hidden) { for (var i = 0; i < hidden.length; ++i)
+ { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
+ if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
+ { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
+
+ if (display.wrapper.offsetHeight)
+ { doc.scrollTop = cm.display.scroller.scrollTop; }
+
+ // Fire change events, and delayed event handlers
+ if (op.changeObjs)
+ { signal(cm, "changes", cm, op.changeObjs); }
+ if (op.update)
+ { op.update.finish(); }
+ }
+
+ // Run the given function in an operation
+ function runInOp(cm, f) {
+ if (cm.curOp) { return f() }
+ startOperation(cm);
+ try { return f() }
+ finally { endOperation(cm); }
+ }
+ // Wraps a function in an operation. Returns the wrapped function.
+ function operation(cm, f) {
+ return function() {
+ if (cm.curOp) { return f.apply(cm, arguments) }
+ startOperation(cm);
+ try { return f.apply(cm, arguments) }
+ finally { endOperation(cm); }
+ }
+ }
+ // Used to add methods to editor and doc instances, wrapping them in
+ // operations.
+ function methodOp(f) {
+ return function() {
+ if (this.curOp) { return f.apply(this, arguments) }
+ startOperation(this);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(this); }
+ }
+ }
+ function docMethodOp(f) {
+ return function() {
+ var cm = this.cm;
+ if (!cm || cm.curOp) { return f.apply(this, arguments) }
+ startOperation(cm);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(cm); }
+ }
+ }
+
+ // HIGHLIGHT WORKER
+
+ function startWorker(cm, time) {
+ if (cm.doc.highlightFrontier < cm.display.viewTo)
+ { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
+ }
+
+ function highlightWorker(cm) {
+ var doc = cm.doc;
+ if (doc.highlightFrontier >= cm.display.viewTo) { return }
+ var end = +new Date + cm.options.workTime;
+ var context = getContextBefore(cm, doc.highlightFrontier);
+ var changedLines = [];
+
+ doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
+ if (context.line >= cm.display.viewFrom) { // Visible
+ var oldStyles = line.styles;
+ var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
+ var highlighted = highlightLine(cm, line, context, true);
+ if (resetState) { context.state = resetState; }
+ line.styles = highlighted.styles;
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
+ if (newCls) { line.styleClasses = newCls; }
+ else if (oldCls) { line.styleClasses = null; }
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
+ if (ischange) { changedLines.push(context.line); }
+ line.stateAfter = context.save();
+ context.nextLine();
+ } else {
+ if (line.text.length <= cm.options.maxHighlightLength)
+ { processLine(cm, line.text, context); }
+ line.stateAfter = context.line % 5 == 0 ? context.save() : null;
+ context.nextLine();
+ }
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true
+ }
+ });
+ doc.highlightFrontier = context.line;
+ doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
+ if (changedLines.length) { runInOp(cm, function () {
+ for (var i = 0; i < changedLines.length; i++)
+ { regLineChange(cm, changedLines[i], "text"); }
+ }); }
+ }
+
+ // DISPLAY DRAWING
+
+ var DisplayUpdate = function(cm, viewport, force) {
+ var display = cm.display;
+
+ this.viewport = viewport;
+ // Store some values that we'll need later (but don't want to force a relayout for)
+ this.visible = visibleLines(display, cm.doc, viewport);
+ this.editorIsHidden = !display.wrapper.offsetWidth;
+ this.wrapperHeight = display.wrapper.clientHeight;
+ this.wrapperWidth = display.wrapper.clientWidth;
+ this.oldDisplayWidth = displayWidth(cm);
+ this.force = force;
+ this.dims = getDimensions(cm);
+ this.events = [];
+ };
+
+ DisplayUpdate.prototype.signal = function (emitter, type) {
+ if (hasHandler(emitter, type))
+ { this.events.push(arguments); }
+ };
+ DisplayUpdate.prototype.finish = function () {
+ for (var i = 0; i < this.events.length; i++)
+ { signal.apply(null, this.events[i]); }
+ };
+
+ function maybeClipScrollbars(cm) {
+ var display = cm.display;
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
+ display.heightForcer.style.height = scrollGap(cm) + "px";
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
+ display.scrollbarsClipped = true;
+ }
+ }
+
+ function selectionSnapshot(cm) {
+ if (cm.hasFocus()) { return null }
+ var active = activeElt(doc(cm));
+ if (!active || !contains(cm.display.lineDiv, active)) { return null }
+ var result = {activeElt: active};
+ if (window.getSelection) {
+ var sel = win(cm).getSelection();
+ if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
+ result.anchorNode = sel.anchorNode;
+ result.anchorOffset = sel.anchorOffset;
+ result.focusNode = sel.focusNode;
+ result.focusOffset = sel.focusOffset;
+ }
+ }
+ return result
+ }
+
+ function restoreSelection(snapshot) {
+ if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt(snapshot.activeElt.ownerDocument)) { return }
+ snapshot.activeElt.focus();
+ if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
+ snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
+ var doc = snapshot.activeElt.ownerDocument;
+ var sel = doc.defaultView.getSelection(), range = doc.createRange();
+ range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
+ range.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ sel.extend(snapshot.focusNode, snapshot.focusOffset);
+ }
+ }
+
+ // Does the actual updating of the line display. Bails out
+ // (returning false) when there is nothing to be done and forced is
+ // false.
+ function updateDisplayIfNeeded(cm, update) {
+ var display = cm.display, doc = cm.doc;
+
+ if (update.editorIsHidden) {
+ resetView(cm);
+ return false
+ }
+
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (!update.force &&
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
+ display.renderedView == display.view && countDirtyView(cm) == 0)
+ { return false }
+
+ if (maybeUpdateLineNumberWidth(cm)) {
+ resetView(cm);
+ update.dims = getDimensions(cm);
+ }
+
+ // Compute a suitable new viewport (from & to)
+ var end = doc.first + doc.size;
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
+ if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
+ if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
+ if (sawCollapsedSpans) {
+ from = visualLineNo(cm.doc, from);
+ to = visualLineEndNo(cm.doc, to);
+ }
+
+ var different = from != display.viewFrom || to != display.viewTo ||
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
+ adjustView(cm, from, to);
+
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
+ // Position the mover div to align with the current scroll position
+ cm.display.mover.style.top = display.viewOffset + "px";
+
+ var toUpdate = countDirtyView(cm);
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
+ { return false }
+
+ // For big changes, we hide the enclosing element during the
+ // update, since that speeds up the operations on most browsers.
+ var selSnapshot = selectionSnapshot(cm);
+ if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
+ if (toUpdate > 4) { display.lineDiv.style.display = ""; }
+ display.renderedView = display.view;
+ // There might have been a widget with a focused element that got
+ // hidden or updated, if so re-focus it.
+ restoreSelection(selSnapshot);
+
+ // Prevent selection and cursors from interfering with the scroll
+ // width and height.
+ removeChildren(display.cursorDiv);
+ removeChildren(display.selectionDiv);
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
+
+ if (different) {
+ display.lastWrapHeight = update.wrapperHeight;
+ display.lastWrapWidth = update.wrapperWidth;
+ startWorker(cm, 400);
+ }
+
+ display.updateLineNumbers = null;
+
+ return true
+ }
+
+ function postUpdateDisplay(cm, update) {
+ var viewport = update.viewport;
+
+ for (var first = true;; first = false) {
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
+ // Clip forced viewport to actual scrollable area.
+ if (viewport && viewport.top != null)
+ { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
+ // Updated line heights might result in the drawn area not
+ // actually covering the viewport. Keep looping until it does.
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
+ { break }
+ } else if (first) {
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ }
+ if (!updateDisplayIfNeeded(cm, update)) { break }
+ updateHeightsInViewport(cm);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.force = false;
+ }
+
+ update.signal(cm, "update", cm);
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
+ }
+ }
+
+ function updateDisplaySimple(cm, viewport) {
+ var update = new DisplayUpdate(cm, viewport);
+ if (updateDisplayIfNeeded(cm, update)) {
+ updateHeightsInViewport(cm);
+ postUpdateDisplay(cm, update);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.finish();
+ }
+ }
+
+ // Sync the actual display DOM structure with display.view, removing
+ // nodes for lines that are no longer in view, and creating the ones
+ // that are not there yet, and updating the ones that are out of
+ // date.
+ function patchDisplay(cm, updateNumbersFrom, dims) {
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
+ var container = display.lineDiv, cur = container.firstChild;
+
+ function rm(node) {
+ var next = node.nextSibling;
+ // Works around a throw-scroll bug in OS X Webkit
+ if (webkit && mac && cm.display.currentWheelTarget == node)
+ { node.style.display = "none"; }
+ else
+ { node.parentNode.removeChild(node); }
+ return next
+ }
+
+ var view = display.view, lineN = display.viewFrom;
+ // Loop over the elements in the view, syncing cur (the DOM nodes
+ // in display.lineDiv) with the view as we go.
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
+ var node = buildLineElement(cm, lineView, lineN, dims);
+ container.insertBefore(node, cur);
+ } else { // Already drawn
+ while (cur != lineView.node) { cur = rm(cur); }
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
+ updateNumbersFrom <= lineN && lineView.lineNumber;
+ if (lineView.changes) {
+ if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
+ updateLineForChanges(cm, lineView, lineN, dims);
+ }
+ if (updateNumber) {
+ removeChildren(lineView.lineNumber);
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
+ }
+ cur = lineView.node.nextSibling;
+ }
+ lineN += lineView.size;
+ }
+ while (cur) { cur = rm(cur); }
+ }
+
+ function updateGutterSpace(display) {
+ var width = display.gutters.offsetWidth;
+ display.sizer.style.marginLeft = width + "px";
+ // Send an event to consumers responding to changes in gutter width.
+ signalLater(display, "gutterChanged", display);
+ }
+
+ function setDocumentHeight(cm, measure) {
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
+ }
+
+ // Re-align line numbers and gutter marks to compensate for
+ // horizontal scrolling.
+ function alignHorizontally(cm) {
+ var display = cm.display, view = display.view;
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
+ for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
+ if (cm.options.fixedGutter) {
+ if (view[i].gutter)
+ { view[i].gutter.style.left = left; }
+ if (view[i].gutterBackground)
+ { view[i].gutterBackground.style.left = left; }
+ }
+ var align = view[i].alignable;
+ if (align) { for (var j = 0; j < align.length; j++)
+ { align[j].style.left = left; } }
+ } }
+ if (cm.options.fixedGutter)
+ { display.gutters.style.left = (comp + gutterW) + "px"; }
+ }
+
+ // Used to ensure that the line number gutter is still the right
+ // size for the current document size. Returns true when an update
+ // is needed.
+ function maybeUpdateLineNumberWidth(cm) {
+ if (!cm.options.lineNumbers) { return false }
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
+ if (last.length != display.lineNumChars) {
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+ display.lineGutter.style.width = "";
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ updateGutterSpace(cm.display);
+ return true
+ }
+ return false
+ }
+
+ function getGutters(gutters, lineNumbers) {
+ var result = [], sawLineNumbers = false;
+ for (var i = 0; i < gutters.length; i++) {
+ var name = gutters[i], style = null;
+ if (typeof name != "string") { style = name.style; name = name.className; }
+ if (name == "CodeMirror-linenumbers") {
+ if (!lineNumbers) { continue }
+ else { sawLineNumbers = true; }
+ }
+ result.push({className: name, style: style});
+ }
+ if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
+ return result
+ }
+
+ // Rebuild the gutter elements, ensure the margin to the left of the
+ // code matches their width.
+ function renderGutters(display) {
+ var gutters = display.gutters, specs = display.gutterSpecs;
+ removeChildren(gutters);
+ display.lineGutter = null;
+ for (var i = 0; i < specs.length; ++i) {
+ var ref = specs[i];
+ var className = ref.className;
+ var style = ref.style;
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
+ if (style) { gElt.style.cssText = style; }
+ if (className == "CodeMirror-linenumbers") {
+ display.lineGutter = gElt;
+ gElt.style.width = (display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = specs.length ? "" : "none";
+ updateGutterSpace(display);
+ }
+
+ function updateGutters(cm) {
+ renderGutters(cm.display);
+ regChange(cm);
+ alignHorizontally(cm);
+ }
+
+ // The display handles the DOM integration, both for input reading
+ // and content drawing. It holds references to DOM nodes and
+ // display-related state.
+
+ function Display(place, doc, input, options) {
+ var d = this;
+ this.input = input;
+
+ // Covers bottom-right square when both scrollbars are present.
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
+ // and h scrollbar is present.
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+ d.gutterFiller.setAttribute("cm-not-content", "true");
+ // Will contain the actual code, positioned to cover the viewport.
+ d.lineDiv = eltP("div", null, "CodeMirror-code");
+ // Elements are added to these to represent selection and cursors.
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
+ // A visibility: hidden element used to find the size of things.
+ d.measure = elt("div", null, "CodeMirror-measure");
+ // When lines outside of the viewport are measured, they are drawn in this.
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
+ d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+ null, "position: relative; outline: none");
+ var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
+ // Moved around its parent to cover visible view.
+ d.mover = elt("div", [lines], null, "position: relative");
+ // Set to the height of the document, allowing scrolling.
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ d.sizerWidth = null;
+ // Behavior of elts with overflow: auto and padding is
+ // inconsistent across browsers. This is used to ensure the
+ // scrollable area is big enough.
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
+ // Will contain the gutters, if any.
+ d.gutters = elt("div", null, "CodeMirror-gutters");
+ d.lineGutter = null;
+ // Actual scrollable element.
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
+ d.scroller.setAttribute("tabIndex", "-1");
+ // The element in which the editor lives.
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
+
+ // This attribute is respected by automatic translation systems such as Google Translate,
+ // and may also be respected by tools used by human translators.
+ d.wrapper.setAttribute('translate', 'no');
+
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
+
+ if (place) {
+ if (place.appendChild) { place.appendChild(d.wrapper); }
+ else { place(d.wrapper); }
+ }
+
+ // Current rendered range (may be bigger than the view window).
+ d.viewFrom = d.viewTo = doc.first;
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
+ // Information about the rendered lines.
+ d.view = [];
+ d.renderedView = null;
+ // Holds info about a single rendered line when it was rendered
+ // for measurement, while not in view.
+ d.externalMeasured = null;
+ // Empty space (in pixels) above the view
+ d.viewOffset = 0;
+ d.lastWrapHeight = d.lastWrapWidth = 0;
+ d.updateLineNumbers = null;
+
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
+ d.scrollbarsClipped = false;
+
+ // Used to only resize the line number gutter when necessary (when
+ // the amount of lines crosses a boundary that makes its width change)
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+ // Set to true when a non-horizontal-scrolling line widget is
+ // added. As an optimization, line widget aligning is skipped when
+ // this is false.
+ d.alignWidgets = false;
+
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+
+ // Tracks the maximum line length so that the horizontal scrollbar
+ // can be kept static when scrolling.
+ d.maxLine = null;
+ d.maxLineLength = 0;
+ d.maxLineChanged = false;
+
+ // Used for measuring wheel scrolling granularity
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
+
+ // True when shift is held down.
+ d.shift = false;
+
+ // Used to track whether anything happened since the context menu
+ // was opened.
+ d.selForContextMenu = null;
+
+ d.activeTouch = null;
+
+ d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
+ renderGutters(d);
+
+ input.init(d);
+ }
+
+ // Since the delta values reported on mouse wheel events are
+ // unstandardized between browsers and even browser versions, and
+ // generally horribly unpredictable, this code starts by measuring
+ // the scroll effect that the first few mouse wheel events have,
+ // and, from that, detects the way it can convert deltas to pixel
+ // offsets afterwards.
+ //
+ // The reason we want to know the amount a wheel event will scroll
+ // is that it gives us a chance to update the display before the
+ // actual scrolling happens, reducing flickering.
+
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
+ // Fill in a browser-detected starting value on browsers where we
+ // know one. These don't have to be accurate -- the result of them
+ // being wrong would just be a slight flicker on the first wheel
+ // scroll (if it is large enough).
+ if (ie) { wheelPixelsPerUnit = -.53; }
+ else if (gecko) { wheelPixelsPerUnit = 15; }
+ else if (chrome) { wheelPixelsPerUnit = -.7; }
+ else if (safari) { wheelPixelsPerUnit = -1/3; }
+
+ function wheelEventDelta(e) {
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
+ else if (dy == null) { dy = e.wheelDelta; }
+ return {x: dx, y: dy}
+ }
+ function wheelEventPixels(e) {
+ var delta = wheelEventDelta(e);
+ delta.x *= wheelPixelsPerUnit;
+ delta.y *= wheelPixelsPerUnit;
+ return delta
+ }
+
+ function onScrollWheel(cm, e) {
+ // On Chrome 102, viewport updates somehow stop wheel-based
+ // scrolling. Turning off pointer events during the scroll seems
+ // to avoid the issue.
+ if (chrome && chrome_version == 102) {
+ if (cm.display.chromeScrollHack == null) { cm.display.sizer.style.pointerEvents = "none"; }
+ else { clearTimeout(cm.display.chromeScrollHack); }
+ cm.display.chromeScrollHack = setTimeout(function () {
+ cm.display.chromeScrollHack = null;
+ cm.display.sizer.style.pointerEvents = "";
+ }, 100);
+ }
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
+ var pixelsPerUnit = wheelPixelsPerUnit;
+ if (e.deltaMode === 0) {
+ dx = e.deltaX;
+ dy = e.deltaY;
+ pixelsPerUnit = 1;
+ }
+
+ var display = cm.display, scroll = display.scroller;
+ // Quit if there's nothing to scroll here
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
+ if (!(dx && canScrollX || dy && canScrollY)) { return }
+
+ // Webkit browsers on OS X abort momentum scrolls when the target
+ // of the scroll event is removed from the scrollable element.
+ // This hack (see related code in patchDisplay) makes sure the
+ // element is kept around.
+ if (dy && mac && webkit) {
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
+ for (var i = 0; i < view.length; i++) {
+ if (view[i].node == cur) {
+ cm.display.currentWheelTarget = cur;
+ break outer
+ }
+ }
+ }
+ }
+
+ // On some browsers, horizontal scrolling will cause redraws to
+ // happen before the gutter has been realigned, causing it to
+ // wriggle around in a most unseemly way. When we have an
+ // estimated pixels/delta value, we just handle horizontal
+ // scrolling entirely here. It'll be slightly off from native, but
+ // better than glitching out.
+ if (dx && !gecko && !presto && pixelsPerUnit != null) {
+ if (dy && canScrollY)
+ { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
+ setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
+ // Only prevent default scrolling if vertical scrolling is
+ // actually possible. Otherwise, it causes vertical scroll
+ // jitter on OSX trackpads when deltaX is small and deltaY
+ // is large (issue #3579)
+ if (!dy || (dy && canScrollY))
+ { e_preventDefault(e); }
+ display.wheelStartX = null; // Abort measurement, if in progress
+ return
+ }
+
+ // 'Project' the visible viewport to cover the area that is being
+ // scrolled into view (if we know enough to estimate it).
+ if (dy && pixelsPerUnit != null) {
+ var pixels = dy * pixelsPerUnit;
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
+ if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
+ else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
+ updateDisplaySimple(cm, {top: top, bottom: bot});
+ }
+
+ if (wheelSamples < 20 && e.deltaMode !== 0) {
+ if (display.wheelStartX == null) {
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
+ display.wheelDX = dx; display.wheelDY = dy;
+ setTimeout(function () {
+ if (display.wheelStartX == null) { return }
+ var movedX = scroll.scrollLeft - display.wheelStartX;
+ var movedY = scroll.scrollTop - display.wheelStartY;
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
+ (movedX && display.wheelDX && movedX / display.wheelDX);
+ display.wheelStartX = display.wheelStartY = null;
+ if (!sample) { return }
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+ ++wheelSamples;
+ }, 200);
+ } else {
+ display.wheelDX += dx; display.wheelDY += dy;
+ }
+ }
+ }
+
+ // Selection objects are immutable. A new one is created every time
+ // the selection changes. A selection is one or more non-overlapping
+ // (and non-touching) ranges, sorted, and an integer that indicates
+ // which one is the primary selection (the one that's scrolled into
+ // view, that getCursor returns, etc).
+ var Selection = function(ranges, primIndex) {
+ this.ranges = ranges;
+ this.primIndex = primIndex;
+ };
+
+ Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
+
+ Selection.prototype.equals = function (other) {
+ if (other == this) { return true }
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var here = this.ranges[i], there = other.ranges[i];
+ if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
+ }
+ return true
+ };
+
+ Selection.prototype.deepCopy = function () {
+ var out = [];
+ for (var i = 0; i < this.ranges.length; i++)
+ { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
+ return new Selection(out, this.primIndex)
+ };
+
+ Selection.prototype.somethingSelected = function () {
+ for (var i = 0; i < this.ranges.length; i++)
+ { if (!this.ranges[i].empty()) { return true } }
+ return false
+ };
+
+ Selection.prototype.contains = function (pos, end) {
+ if (!end) { end = pos; }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var range = this.ranges[i];
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
+ { return i }
+ }
+ return -1
+ };
+
+ var Range = function(anchor, head) {
+ this.anchor = anchor; this.head = head;
+ };
+
+ Range.prototype.from = function () { return minPos(this.anchor, this.head) };
+ Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
+ Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
+
+ // Take an unsorted, potentially overlapping set of ranges, and
+ // build a selection out of it. 'Consumes' ranges array (modifying
+ // it).
+ function normalizeSelection(cm, ranges, primIndex) {
+ var mayTouch = cm && cm.options.selectionsMayTouch;
+ var prim = ranges[primIndex];
+ ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
+ primIndex = indexOf(ranges, prim);
+ for (var i = 1; i < ranges.length; i++) {
+ var cur = ranges[i], prev = ranges[i - 1];
+ var diff = cmp(prev.to(), cur.from());
+ if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
+ if (i <= primIndex) { --primIndex; }
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
+ }
+ }
+ return new Selection(ranges, primIndex)
+ }
+
+ function simpleSelection(anchor, head) {
+ return new Selection([new Range(anchor, head || anchor)], 0)
+ }
+
+ // Compute the position of the end of a change (its 'to' property
+ // refers to the pre-change end).
+ function changeEnd(change) {
+ if (!change.text) { return change.to }
+ return Pos(change.from.line + change.text.length - 1,
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
+ }
+
+ // Adjust a position to refer to the post-change position of the
+ // same text, or the end of the change if the change covers it.
+ function adjustForChange(pos, change) {
+ if (cmp(pos, change.from) < 0) { return pos }
+ if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
+
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+ if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
+ return Pos(line, ch)
+ }
+
+ function computeSelAfterChange(doc, change) {
+ var out = [];
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ out.push(new Range(adjustForChange(range.anchor, change),
+ adjustForChange(range.head, change)));
+ }
+ return normalizeSelection(doc.cm, out, doc.sel.primIndex)
+ }
+
+ function offsetPos(pos, old, nw) {
+ if (pos.line == old.line)
+ { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
+ else
+ { return Pos(nw.line + (pos.line - old.line), pos.ch) }
+ }
+
+ // Used by replaceSelections to allow moving the selection to the
+ // start or around the replaced test. Hint may be "start" or "around".
+ function computeReplacedSel(doc, changes, hint) {
+ var out = [];
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ var from = offsetPos(change.from, oldPrev, newPrev);
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
+ oldPrev = change.to;
+ newPrev = to;
+ if (hint == "around") {
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
+ out[i] = new Range(inv ? to : from, inv ? from : to);
+ } else {
+ out[i] = new Range(from, from);
+ }
+ }
+ return new Selection(out, doc.sel.primIndex)
+ }
+
+ // Used to get the editor into a consistent state again when options change.
+
+ function loadMode(cm) {
+ cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
+ resetModeState(cm);
+ }
+
+ function resetModeState(cm) {
+ cm.doc.iter(function (line) {
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ });
+ cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
+ startWorker(cm, 100);
+ cm.state.modeGen++;
+ if (cm.curOp) { regChange(cm); }
+ }
+
+ // DOCUMENT DATA STRUCTURE
+
+ // By default, updates that start and end at the beginning of a line
+ // are treated specially, in order to make the association of line
+ // widgets and marker elements with the text behave more intuitive.
+ function isWholeLineUpdate(doc, change) {
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
+ }
+
+ // Perform a change on the document data structure.
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null}
+ function update(line, text, spans) {
+ updateLine(line, text, spans, estimateHeight);
+ signalLater(line, "change", line, change);
+ }
+ function linesFor(start, end) {
+ var result = [];
+ for (var i = start; i < end; ++i)
+ { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
+ return result
+ }
+
+ var from = change.from, to = change.to, text = change.text;
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+
+ // Adjust the line structure
+ if (change.full) {
+ doc.insert(0, linesFor(0, text.length));
+ doc.remove(text.length, doc.size - text.length);
+ } else if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = linesFor(0, text.length - 1);
+ update(lastLine, lastLine.text, lastSpans);
+ if (nlines) { doc.remove(from.line, nlines); }
+ if (added.length) { doc.insert(from.line, added); }
+ } else if (firstLine == lastLine) {
+ if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
+ } else {
+ var added$1 = linesFor(1, text.length - 1);
+ added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ doc.insert(from.line + 1, added$1);
+ }
+ } else if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+ doc.remove(from.line + 1, nlines);
+ } else {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+ var added$2 = linesFor(1, text.length - 1);
+ if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
+ doc.insert(from.line + 1, added$2);
+ }
+
+ signalLater(doc, "change", doc, change);
+ }
+
+ // Call f for all linked documents.
+ function linkedDocs(doc, f, sharedHistOnly) {
+ function propagate(doc, skip, sharedHist) {
+ if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
+ var rel = doc.linked[i];
+ if (rel.doc == skip) { continue }
+ var shared = sharedHist && rel.sharedHist;
+ if (sharedHistOnly && !shared) { continue }
+ f(rel.doc, shared);
+ propagate(rel.doc, doc, shared);
+ } }
+ }
+ propagate(doc, null, true);
+ }
+
+ // Attach a document to an editor.
+ function attachDoc(cm, doc) {
+ if (doc.cm) { throw new Error("This document is already in use.") }
+ cm.doc = doc;
+ doc.cm = cm;
+ estimateLineHeights(cm);
+ loadMode(cm);
+ setDirectionClass(cm);
+ cm.options.direction = doc.direction;
+ if (!cm.options.lineWrapping) { findMaxLine(cm); }
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+ }
+
+ function setDirectionClass(cm) {
+ (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
+ }
+
+ function directionChanged(cm) {
+ runInOp(cm, function () {
+ setDirectionClass(cm);
+ regChange(cm);
+ });
+ }
+
+ function History(prev) {
+ // Arrays of change events and selections. Doing something adds an
+ // event to done and clears undo. Undoing moves events from done
+ // to undone, redoing moves them in the other direction.
+ this.done = []; this.undone = [];
+ this.undoDepth = prev ? prev.undoDepth : Infinity;
+ // Used to track when changes can be merged into a single undo
+ // event
+ this.lastModTime = this.lastSelTime = 0;
+ this.lastOp = this.lastSelOp = null;
+ this.lastOrigin = this.lastSelOrigin = null;
+ // Used by the isClean() method
+ this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
+ }
+
+ // Create a history change event from an updateDoc-style change
+ // object.
+ function historyChangeFromChange(doc, change) {
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+ linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
+ return histChange
+ }
+
+ // Pop all selection events off the end of a history array. Stop at
+ // a change event.
+ function clearSelectionEvents(array) {
+ while (array.length) {
+ var last = lst(array);
+ if (last.ranges) { array.pop(); }
+ else { break }
+ }
+ }
+
+ // Find the top change event in the history. Pop off selection
+ // events that are in the way.
+ function lastChangeEvent(hist, force) {
+ if (force) {
+ clearSelectionEvents(hist.done);
+ return lst(hist.done)
+ } else if (hist.done.length && !lst(hist.done).ranges) {
+ return lst(hist.done)
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
+ hist.done.pop();
+ return lst(hist.done)
+ }
+ }
+
+ // Register a change in the history. Merges changes that are within
+ // a single operation, or are close together with an origin that
+ // allows merging (starting with "+") into a single event.
+ function addChangeToHistory(doc, change, selAfter, opId) {
+ var hist = doc.history;
+ hist.undone.length = 0;
+ var time = +new Date, cur;
+ var last;
+
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ last = lst(cur.changes);
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
+ // Optimized case for simple insertion -- don't want to add
+ // new changesets for every character typed
+ last.to = changeEnd(change);
+ } else {
+ // Add new sub-event
+ cur.changes.push(historyChangeFromChange(doc, change));
+ }
+ } else {
+ // Can not be merged, start a new event.
+ var before = lst(hist.done);
+ if (!before || !before.ranges)
+ { pushSelectionToHistory(doc.sel, hist.done); }
+ cur = {changes: [historyChangeFromChange(doc, change)],
+ generation: hist.generation};
+ hist.done.push(cur);
+ while (hist.done.length > hist.undoDepth) {
+ hist.done.shift();
+ if (!hist.done[0].ranges) { hist.done.shift(); }
+ }
+ }
+ hist.done.push(selAfter);
+ hist.generation = ++hist.maxGeneration;
+ hist.lastModTime = hist.lastSelTime = time;
+ hist.lastOp = hist.lastSelOp = opId;
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
+
+ if (!last) { signal(doc, "historyAdded"); }
+ }
+
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
+ var ch = origin.charAt(0);
+ return ch == "*" ||
+ ch == "+" &&
+ prev.ranges.length == sel.ranges.length &&
+ prev.somethingSelected() == sel.somethingSelected() &&
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
+ }
+
+ // Called whenever the selection changes, sets the new selection as
+ // the pending selection in the history, and pushes the old pending
+ // selection into the 'done' array when it was significantly
+ // different (in number of selected ranges, emptiness, or time).
+ function addSelectionToHistory(doc, sel, opId, options) {
+ var hist = doc.history, origin = options && options.origin;
+
+ // A new event is started when the previous origin does not match
+ // the current, or the origins don't allow matching. Origins
+ // starting with * are always merged, those starting with + are
+ // merged when similar and close together in time.
+ if (opId == hist.lastSelOp ||
+ (origin && hist.lastSelOrigin == origin &&
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+ { hist.done[hist.done.length - 1] = sel; }
+ else
+ { pushSelectionToHistory(sel, hist.done); }
+
+ hist.lastSelTime = +new Date;
+ hist.lastSelOrigin = origin;
+ hist.lastSelOp = opId;
+ if (options && options.clearRedo !== false)
+ { clearSelectionEvents(hist.undone); }
+ }
+
+ function pushSelectionToHistory(sel, dest) {
+ var top = lst(dest);
+ if (!(top && top.ranges && top.equals(sel)))
+ { dest.push(sel); }
+ }
+
+ // Used to store marked span information in the history.
+ function attachLocalSpans(doc, change, from, to) {
+ var existing = change["spans_" + doc.id], n = 0;
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
+ if (line.markedSpans)
+ { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
+ ++n;
+ });
+ }
+
+ // When un/re-doing restores text containing marked spans, those
+ // that have been explicitly cleared should not be restored.
+ function removeClearedSpans(spans) {
+ if (!spans) { return null }
+ var out;
+ for (var i = 0; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
+ else if (out) { out.push(spans[i]); }
+ }
+ return !out ? spans : out.length ? out : null
+ }
+
+ // Retrieve and filter the old marked spans stored in a change event.
+ function getOldSpans(doc, change) {
+ var found = change["spans_" + doc.id];
+ if (!found) { return null }
+ var nw = [];
+ for (var i = 0; i < change.text.length; ++i)
+ { nw.push(removeClearedSpans(found[i])); }
+ return nw
+ }
+
+ // Used for un/re-doing changes from the history. Combines the
+ // result of computing the existing spans with the set of spans that
+ // existed in the history (so that deleting around a span and then
+ // undoing brings back the span).
+ function mergeOldSpans(doc, change) {
+ var old = getOldSpans(doc, change);
+ var stretched = stretchSpansOverChange(doc, change);
+ if (!old) { return stretched }
+ if (!stretched) { return old }
+
+ for (var i = 0; i < old.length; ++i) {
+ var oldCur = old[i], stretchCur = stretched[i];
+ if (oldCur && stretchCur) {
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
+ var span = stretchCur[j];
+ for (var k = 0; k < oldCur.length; ++k)
+ { if (oldCur[k].marker == span.marker) { continue spans } }
+ oldCur.push(span);
+ }
+ } else if (stretchCur) {
+ old[i] = stretchCur;
+ }
+ }
+ return old
+ }
+
+ // Used both to provide a JSON-safe object in .getHistory, and, when
+ // detaching a document, to split the history in two
+ function copyHistoryArray(events, newGroup, instantiateSel) {
+ var copy = [];
+ for (var i = 0; i < events.length; ++i) {
+ var event = events[i];
+ if (event.ranges) {
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
+ continue
+ }
+ var changes = event.changes, newChanges = [];
+ copy.push({changes: newChanges});
+ for (var j = 0; j < changes.length; ++j) {
+ var change = changes[j], m = (void 0);
+ newChanges.push({from: change.from, to: change.to, text: change.text});
+ if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
+ if (indexOf(newGroup, Number(m[1])) > -1) {
+ lst(newChanges)[prop] = change[prop];
+ delete change[prop];
+ }
+ } } }
+ }
+ }
+ return copy
+ }
+
+ // The 'scroll' parameter given to many of these indicated whether
+ // the new cursor position should be scrolled into view after
+ // modifying the selection.
+
+ // If shift is held or the extend flag is set, extends a range to
+ // include a given position (and optionally a second position).
+ // Otherwise, simply returns the range between the given positions.
+ // Used for cursor motion and such.
+ function extendRange(range, head, other, extend) {
+ if (extend) {
+ var anchor = range.anchor;
+ if (other) {
+ var posBefore = cmp(head, anchor) < 0;
+ if (posBefore != (cmp(other, anchor) < 0)) {
+ anchor = head;
+ head = other;
+ } else if (posBefore != (cmp(head, other) < 0)) {
+ head = other;
+ }
+ }
+ return new Range(anchor, head)
+ } else {
+ return new Range(other || head, head)
+ }
+ }
+
+ // Extend the primary selection range, discard the rest.
+ function extendSelection(doc, head, other, options, extend) {
+ if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
+ setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
+ }
+
+ // Extend all selections (pos is an array of selections with length
+ // equal the number of selections)
+ function extendSelections(doc, heads, options) {
+ var out = [];
+ var extend = doc.cm && (doc.cm.display.shift || doc.extend);
+ for (var i = 0; i < doc.sel.ranges.length; i++)
+ { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
+ var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
+ setSelection(doc, newSel, options);
+ }
+
+ // Updates a single range in the selection.
+ function replaceOneSelection(doc, i, range, options) {
+ var ranges = doc.sel.ranges.slice(0);
+ ranges[i] = range;
+ setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
+ }
+
+ // Reset the selection to a single range.
+ function setSimpleSelection(doc, anchor, head, options) {
+ setSelection(doc, simpleSelection(anchor, head), options);
+ }
+
+ // Give beforeSelectionChange handlers a change to influence a
+ // selection update.
+ function filterSelectionChange(doc, sel, options) {
+ var obj = {
+ ranges: sel.ranges,
+ update: function(ranges) {
+ this.ranges = [];
+ for (var i = 0; i < ranges.length; i++)
+ { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
+ clipPos(doc, ranges[i].head)); }
+ },
+ origin: options && options.origin
+ };
+ signal(doc, "beforeSelectionChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
+ if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
+ else { return sel }
+ }
+
+ function setSelectionReplaceHistory(doc, sel, options) {
+ var done = doc.history.done, last = lst(done);
+ if (last && last.ranges) {
+ done[done.length - 1] = sel;
+ setSelectionNoUndo(doc, sel, options);
+ } else {
+ setSelection(doc, sel, options);
+ }
+ }
+
+ // Set a new selection.
+ function setSelection(doc, sel, options) {
+ setSelectionNoUndo(doc, sel, options);
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
+ }
+
+ function setSelectionNoUndo(doc, sel, options) {
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
+ { sel = filterSelectionChange(doc, sel, options); }
+
+ var bias = options && options.bias ||
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
+
+ if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
+ { ensureCursorVisible(doc.cm); }
+ }
+
+ function setSelectionInner(doc, sel) {
+ if (sel.equals(doc.sel)) { return }
+
+ doc.sel = sel;
+
+ if (doc.cm) {
+ doc.cm.curOp.updateInput = 1;
+ doc.cm.curOp.selectionChanged = true;
+ signalCursorActivity(doc.cm);
+ }
+ signalLater(doc, "cursorActivity", doc);
+ }
+
+ // Verify that the selection does not partially select any atomic
+ // marked ranges.
+ function reCheckSelection(doc) {
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
+ }
+
+ // Return a selection that does not partially select any atomic
+ // ranges.
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
+ var out;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
+ var newHead = range.head == range.anchor ? newAnchor : skipAtomic(doc, range.head, old && old.head, bias, mayClear);
+ if (out || newAnchor != range.anchor || newHead != range.head) {
+ if (!out) { out = sel.ranges.slice(0, i); }
+ out[i] = new Range(newAnchor, newHead);
+ }
+ }
+ return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
+ }
+
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+ var line = getLine(doc, pos.line);
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+
+ // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
+ // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
+ // is with selectLeft/Right
+ var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
+ var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
+
+ if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
+ (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) { break }
+ else {--i; continue}
+ }
+ }
+ if (!m.atomic) { continue }
+
+ if (oldPos) {
+ var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
+ if (dir < 0 ? preventCursorRight : preventCursorLeft)
+ { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
+ { return skipAtomicInner(doc, near, pos, dir, mayClear) }
+ }
+
+ var far = m.find(dir < 0 ? -1 : 1);
+ if (dir < 0 ? preventCursorLeft : preventCursorRight)
+ { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
+ }
+ } }
+ return pos
+ }
+
+ // Ensure a given position is not inside an atomic range.
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
+ var dir = bias || 1;
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
+ if (!found) {
+ doc.cantEdit = true;
+ return Pos(doc.first, 0)
+ }
+ return found
+ }
+
+ function movePos(doc, pos, dir, line) {
+ if (dir < 0 && pos.ch == 0) {
+ if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
+ else { return null }
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
+ if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
+ else { return null }
+ } else {
+ return new Pos(pos.line, pos.ch + dir)
+ }
+ }
+
+ function selectAll(cm) {
+ cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
+ }
+
+ // UPDATING
+
+ // Allow "beforeChange" event handlers to influence a change
+ function filterChange(doc, change, update) {
+ var obj = {
+ canceled: false,
+ from: change.from,
+ to: change.to,
+ text: change.text,
+ origin: change.origin,
+ cancel: function () { return obj.canceled = true; }
+ };
+ if (update) { obj.update = function (from, to, text, origin) {
+ if (from) { obj.from = clipPos(doc, from); }
+ if (to) { obj.to = clipPos(doc, to); }
+ if (text) { obj.text = text; }
+ if (origin !== undefined) { obj.origin = origin; }
+ }; }
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
+
+ if (obj.canceled) {
+ if (doc.cm) { doc.cm.curOp.updateInput = 2; }
+ return null
+ }
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
+ }
+
+ // Apply a change to a document, and add it to the document's
+ // history, and propagating it to all linked documents.
+ function makeChange(doc, change, ignoreReadOnly) {
+ if (doc.cm) {
+ if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
+ if (doc.cm.state.suppressEdits) { return }
+ }
+
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+ change = filterChange(doc, change, true);
+ if (!change) { return }
+ }
+
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+ if (split) {
+ for (var i = split.length - 1; i >= 0; --i)
+ { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
+ } else {
+ makeChangeInner(doc, change);
+ }
+ }
+
+ function makeChangeInner(doc, change) {
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
+ var selAfter = computeSelAfterChange(doc, change);
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
+
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+ var rebased = [];
+
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+ });
+ }
+
+ // Revert a change stored in a document's history.
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+ var suppress = doc.cm && doc.cm.state.suppressEdits;
+ if (suppress && !allowSelectionOnly) { return }
+
+ var hist = doc.history, event, selAfter = doc.sel;
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
+
+ // Verify that there is a useable event (so that ctrl-z won't
+ // needlessly clear selection events)
+ var i = 0;
+ for (; i < source.length; i++) {
+ event = source[i];
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
+ { break }
+ }
+ if (i == source.length) { return }
+ hist.lastOrigin = hist.lastSelOrigin = null;
+
+ for (;;) {
+ event = source.pop();
+ if (event.ranges) {
+ pushSelectionToHistory(event, dest);
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
+ setSelection(doc, event, {clearRedo: false});
+ return
+ }
+ selAfter = event;
+ } else if (suppress) {
+ source.push(event);
+ return
+ } else { break }
+ }
+
+ // Build up a reverse change object to add to the opposite history
+ // stack (redo when undoing, and vice versa).
+ var antiChanges = [];
+ pushSelectionToHistory(selAfter, dest);
+ dest.push({changes: antiChanges, generation: hist.generation});
+ hist.generation = event.generation || ++hist.maxGeneration;
+
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
+
+ var loop = function ( i ) {
+ var change = event.changes[i];
+ change.origin = type;
+ if (filter && !filterChange(doc, change, false)) {
+ source.length = 0;
+ return {}
+ }
+
+ antiChanges.push(historyChangeFromChange(doc, change));
+
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
+ var rebased = [];
+
+ // Propagate to the linked documents
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ });
+ };
+
+ for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
+ var returned = loop( i$1 );
+
+ if ( returned ) return returned.v;
+ }
+ }
+
+ // Sub-views need their line numbers shifted when text is added
+ // above or below them in the parent document.
+ function shiftDoc(doc, distance) {
+ if (distance == 0) { return }
+ doc.first += distance;
+ doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
+ Pos(range.anchor.line + distance, range.anchor.ch),
+ Pos(range.head.line + distance, range.head.ch)
+ ); }), doc.sel.primIndex);
+ if (doc.cm) {
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
+ { regLineChange(doc.cm, l, "gutter"); }
+ }
+ }
+
+ // More lower-level change function, handling only a single document
+ // (not linked ones).
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
+ if (doc.cm && !doc.cm.curOp)
+ { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
+
+ if (change.to.line < doc.first) {
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+ return
+ }
+ if (change.from.line > doc.lastLine()) { return }
+
+ // Clip the change to the size of this doc
+ if (change.from.line < doc.first) {
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
+ shiftDoc(doc, shift);
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+ text: [lst(change.text)], origin: change.origin};
+ }
+ var last = doc.lastLine();
+ if (change.to.line > last) {
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+ text: [change.text[0]], origin: change.origin};
+ }
+
+ change.removed = getBetween(doc, change.from, change.to);
+
+ if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
+ if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
+ else { updateDoc(doc, change, spans); }
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+
+ if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
+ { doc.cantEdit = false; }
+ }
+
+ // Handle the interaction of a change to a document with the editor
+ // that this document is part of.
+ function makeChangeSingleDocInEditor(cm, change, spans) {
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
+ doc.iter(checkWidthStart, to.line + 1, function (line) {
+ if (line == display.maxLine) {
+ recomputeMaxLength = true;
+ return true
+ }
+ });
+ }
+
+ if (doc.sel.contains(change.from, change.to) > -1)
+ { signalCursorActivity(cm); }
+
+ updateDoc(doc, change, spans, estimateHeight(cm));
+
+ if (!cm.options.lineWrapping) {
+ doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
+ var len = lineLength(line);
+ if (len > display.maxLineLength) {
+ display.maxLine = line;
+ display.maxLineLength = len;
+ display.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
+ }
+
+ retreatFrontier(doc, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = change.text.length - (to.line - from.line) - 1;
+ // Remember that these lines changed, for updating the display
+ if (change.full)
+ { regChange(cm); }
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
+ { regLineChange(cm, from.line, "text"); }
+ else
+ { regChange(cm, from.line, to.line + 1, lendiff); }
+
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
+ if (changeHandler || changesHandler) {
+ var obj = {
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ };
+ if (changeHandler) { signalLater(cm, "change", cm, obj); }
+ if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
+ }
+ cm.display.selForContextMenu = null;
+ }
+
+ function replaceRange(doc, code, from, to, origin) {
+ var assign;
+
+ if (!to) { to = from; }
+ if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
+ if (typeof code == "string") { code = doc.splitLines(code); }
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
+ }
+
+ // Rebasing/resetting history to deal with externally-sourced changes
+
+ function rebaseHistSelSingle(pos, from, to, diff) {
+ if (to < pos.line) {
+ pos.line += diff;
+ } else if (from < pos.line) {
+ pos.line = from;
+ pos.ch = 0;
+ }
+ }
+
+ // Tries to rebase an array of history events given a change in the
+ // document. If the change touches the same lines as the event, the
+ // event, and everything 'behind' it, is discarded. If the change is
+ // before the event, the event's positions are updated. Uses a
+ // copy-on-write scheme for the positions, to avoid having to
+ // reallocate them all on every rebase, but also avoid problems with
+ // shared position objects being unsafely updated.
+ function rebaseHistArray(array, from, to, diff) {
+ for (var i = 0; i < array.length; ++i) {
+ var sub = array[i], ok = true;
+ if (sub.ranges) {
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
+ for (var j = 0; j < sub.ranges.length; j++) {
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
+ }
+ continue
+ }
+ for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
+ var cur = sub.changes[j$1];
+ if (to < cur.from.line) {
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
+ } else if (from <= cur.to.line) {
+ ok = false;
+ break
+ }
+ }
+ if (!ok) {
+ array.splice(0, i + 1);
+ i = 0;
+ }
+ }
+ }
+
+ function rebaseHist(hist, change) {
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+ rebaseHistArray(hist.done, from, to, diff);
+ rebaseHistArray(hist.undone, from, to, diff);
+ }
+
+ // Utility for applying a change to a line by handle or number,
+ // returning the number and optionally registering the line as
+ // changed.
+ function changeLine(doc, handle, changeType, op) {
+ var no = handle, line = handle;
+ if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
+ else { no = lineNo(handle); }
+ if (no == null) { return null }
+ if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
+ return line
+ }
+
+ // The document is represented as a BTree consisting of leaves, with
+ // chunk of lines in them, and branches, with up to ten leaves or
+ // other branch nodes below them. The top node is always a branch
+ // node, and is the document object itself (meaning it has
+ // additional methods and properties).
+ //
+ // All nodes have parent links. The tree is used both to go from
+ // line numbers to line objects, and to go from objects to numbers.
+ // It also indexes by height, and is used to convert between height
+ // and line object, and to find the total height of the document.
+ //
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
+
+ function LeafChunk(lines) {
+ this.lines = lines;
+ this.parent = null;
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) {
+ lines[i].parent = this;
+ height += lines[i].height;
+ }
+ this.height = height;
+ }
+
+ LeafChunk.prototype = {
+ chunkSize: function() { return this.lines.length },
+
+ // Remove the n lines at offset 'at'.
+ removeInner: function(at, n) {
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this.lines[i];
+ this.height -= line.height;
+ cleanUpLine(line);
+ signalLater(line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
+
+ // Helper used to collapse a small branch into a single leaf.
+ collapse: function(lines) {
+ lines.push.apply(lines, this.lines);
+ },
+
+ // Insert the given array of lines at offset 'at', count them as
+ // having the given height.
+ insertInner: function(at, lines, height) {
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
+ },
+
+ // Used to iterate over a part of the tree.
+ iterN: function(at, n, op) {
+ for (var e = at + n; at < e; ++at)
+ { if (op(this.lines[at])) { return true } }
+ }
+ };
+
+ function BranchChunk(children) {
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0; i < children.length; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this;
+ }
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+ }
+
+ BranchChunk.prototype = {
+ chunkSize: function() { return this.size },
+
+ removeInner: function(at, n) {
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.removeInner(at, rm);
+ this.height -= oldHeight - child.height;
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
+ }
+ // If the result is smaller than 25 lines, ensure that it is a
+ // single leaf node.
+ if (this.size - n < 25 &&
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
+ }
+ },
+
+ collapse: function(lines) {
+ for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
+ },
+
+ insertInner: function(at, lines, height) {
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertInner(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
+ // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
+ var remaining = child.lines.length % 25 + 25;
+ for (var pos = remaining; pos < child.lines.length;) {
+ var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
+ child.height -= leaf.height;
+ this.children.splice(++i, 0, leaf);
+ leaf.parent = this;
+ }
+ child.lines = child.lines.slice(0, remaining);
+ this.maybeSpill();
+ }
+ break
+ }
+ at -= sz;
+ }
+ },
+
+ // When a node has grown, check whether it should be split.
+ maybeSpill: function() {
+ if (this.children.length <= 10) { return }
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10)
+ me.parent.maybeSpill();
+ },
+
+ iterN: function(at, n, op) {
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) { return true }
+ if ((n -= used) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
+ }
+ }
+ };
+
+ // Line widgets are block elements displayed above or below a line.
+
+ var LineWidget = function(doc, node, options) {
+ if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
+ { this[opt] = options[opt]; } } }
+ this.doc = doc;
+ this.node = node;
+ };
+
+ LineWidget.prototype.clear = function () {
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
+ if (no == null || !ws) { return }
+ for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
+ if (!ws.length) { line.widgets = null; }
+ var height = widgetHeight(this);
+ updateLineHeight(line, Math.max(0, line.height - height));
+ if (cm) {
+ runInOp(cm, function () {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ });
+ signalLater(cm, "lineWidgetCleared", cm, this, no);
+ }
+ };
+
+ LineWidget.prototype.changed = function () {
+ var this$1 = this;
+
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) { return }
+ if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
+ if (cm) {
+ runInOp(cm, function () {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
+ });
+ }
+ };
+ eventMixin(LineWidget);
+
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ { addToScrollTop(cm, diff); }
+ }
+
+ function addLineWidget(doc, handle, node, options) {
+ var widget = new LineWidget(doc, node, options);
+ var cm = doc.cm;
+ if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
+ changeLine(doc, handle, "widget", function (line) {
+ var widgets = line.widgets || (line.widgets = []);
+ if (widget.insertAt == null) { widgets.push(widget); }
+ else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
+ widget.line = line;
+ if (cm && !lineIsHidden(doc, line)) {
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) { addToScrollTop(cm, widget.height); }
+ cm.curOp.forceUpdate = true;
+ }
+ return true
+ });
+ if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
+ return widget
+ }
+
+ // TEXTMARKERS
+
+ // Created with markText and setBookmark methods. A TextMarker is a
+ // handle that can be used to clear or find a marked position in the
+ // document. Line objects hold arrays (markedSpans) containing
+ // {from, to, marker} object pointing to such marker objects, and
+ // indicating that such a marker is present on that line. Multiple
+ // lines may point to the same marker when it spans across lines.
+ // The spans will have null for their from/to properties when the
+ // marker continues beyond the start/end of the line. Markers have
+ // links back to the lines they currently touch.
+
+ // Collapsed markers have unique ids, in order to be able to order
+ // them, which is needed for uniquely determining an outer marker
+ // when they overlap (they may nest, but not partially overlap).
+ var nextMarkerId = 0;
+
+ var TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ this.id = ++nextMarkerId;
+ };
+
+ // Clear the marker.
+ TextMarker.prototype.clear = function () {
+ if (this.explicitlyCleared) { return }
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
+ if (withOp) { startOperation(cm); }
+ if (hasHandler(this, "clear")) {
+ var found = this.find();
+ if (found) { signalLater(this, "clear", found.from, found.to); }
+ }
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
+ else if (cm) {
+ if (span.to != null) { max = lineNo(line); }
+ if (span.from != null) { min = lineNo(line); }
+ }
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
+ { updateLineHeight(line, textHeight(cm.display)); }
+ }
+ if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
+ var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
+ if (len > cm.display.maxLineLength) {
+ cm.display.maxLine = visual;
+ cm.display.maxLineLength = len;
+ cm.display.maxLineChanged = true;
+ }
+ } }
+
+ if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.atomic && this.doc.cantEdit) {
+ this.doc.cantEdit = false;
+ if (cm) { reCheckSelection(cm.doc); }
+ }
+ if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
+ if (withOp) { endOperation(cm); }
+ if (this.parent) { this.parent.clear(); }
+ };
+
+ // Find the position of the marker in the document. Returns a {from,
+ // to} object by default. Side can be passed to get a specific side
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+ // Pos objects returned contain a line object, rather than a line
+ // number (used to prevent looking up the same line twice).
+ TextMarker.prototype.find = function (side, lineObj) {
+ if (side == null && this.type == "bookmark") { side = 1; }
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (span.from != null) {
+ from = Pos(lineObj ? line : lineNo(line), span.from);
+ if (side == -1) { return from }
+ }
+ if (span.to != null) {
+ to = Pos(lineObj ? line : lineNo(line), span.to);
+ if (side == 1) { return to }
+ }
+ }
+ return from && {from: from, to: to}
+ };
+
+ // Signals that the marker's widget changed, and surrounding layout
+ // should be recomputed.
+ TextMarker.prototype.changed = function () {
+ var this$1 = this;
+
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
+ if (!pos || !cm) { return }
+ runInOp(cm, function () {
+ var line = pos.line, lineN = lineNo(pos.line);
+ var view = findViewForLine(cm, lineN);
+ if (view) {
+ clearLineMeasurementCacheFor(view);
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
+ }
+ cm.curOp.updateMaxLine = true;
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
+ var oldHeight = widget.height;
+ widget.height = null;
+ var dHeight = widgetHeight(widget) - oldHeight;
+ if (dHeight)
+ { updateLineHeight(line, line.height + dHeight); }
+ }
+ signalLater(cm, "markerChanged", cm, this$1);
+ });
+ };
+
+ TextMarker.prototype.attachLine = function (line) {
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+ { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
+ }
+ this.lines.push(line);
+ };
+
+ TextMarker.prototype.detachLine = function (line) {
+ this.lines.splice(indexOf(this.lines, line), 1);
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp
+ ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+ }
+ };
+ eventMixin(TextMarker);
+
+ // Create a marker, wire it up to the right lines, and
+ function markText(doc, from, to, options, type) {
+ // Shared markers (across linked documents) are handled separately
+ // (markTextShared will call out to this again, once per
+ // document).
+ if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
+ // Ensure we are in an operation.
+ if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
+
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
+ if (options) { copyObj(options, marker, false); }
+ // Don't connect empty markers unless clearWhenEmpty is false
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
+ { return marker }
+ if (marker.replacedWith) {
+ // Showing up as a widget implies collapsed (widget replaces text)
+ marker.collapsed = true;
+ marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
+ if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
+ }
+ if (marker.collapsed) {
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
+ { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
+ seeCollapsedSpans();
+ }
+
+ if (marker.addToHistory)
+ { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
+
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
+ doc.iter(curLine, to.line + 1, function (line) {
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
+ { updateMaxLine = true; }
+ if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
+ addMarkedSpan(line, new MarkedSpan(marker,
+ curLine == from.line ? from.ch : null,
+ curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
+ ++curLine;
+ });
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
+ if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
+ if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
+ }); }
+
+ if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
+
+ if (marker.readOnly) {
+ seeReadOnlySpans();
+ if (doc.history.done.length || doc.history.undone.length)
+ { doc.clearHistory(); }
+ }
+ if (marker.collapsed) {
+ marker.id = ++nextMarkerId;
+ marker.atomic = true;
+ }
+ if (cm) {
+ // Sync editor state
+ if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
+ if (marker.collapsed)
+ { regChange(cm, from.line, to.line + 1); }
+ else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
+ marker.attributes || marker.title)
+ { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
+ if (marker.atomic) { reCheckSelection(cm.doc); }
+ signalLater(cm, "markerAdded", cm, marker);
+ }
+ return marker
+ }
+
+ // SHARED TEXTMARKERS
+
+ // A shared marker spans multiple linked documents. It is
+ // implemented as a meta-marker-object controlling multiple normal
+ // markers.
+ var SharedTextMarker = function(markers, primary) {
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0; i < markers.length; ++i)
+ { markers[i].parent = this; }
+ };
+
+ SharedTextMarker.prototype.clear = function () {
+ if (this.explicitlyCleared) { return }
+ this.explicitlyCleared = true;
+ for (var i = 0; i < this.markers.length; ++i)
+ { this.markers[i].clear(); }
+ signalLater(this, "clear");
+ };
+
+ SharedTextMarker.prototype.find = function (side, lineObj) {
+ return this.primary.find(side, lineObj)
+ };
+ eventMixin(SharedTextMarker);
+
+ function markTextShared(doc, from, to, options, type) {
+ options = copyObj(options);
+ options.shared = false;
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+ var widget = options.widgetNode;
+ linkedDocs(doc, function (doc) {
+ if (widget) { options.widgetNode = widget.cloneNode(true); }
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+ for (var i = 0; i < doc.linked.length; ++i)
+ { if (doc.linked[i].isParent) { return } }
+ primary = lst(markers);
+ });
+ return new SharedTextMarker(markers, primary)
+ }
+
+ function findSharedMarkers(doc) {
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
+ }
+
+ function copySharedMarkers(doc, markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], pos = marker.find();
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
+ if (cmp(mFrom, mTo)) {
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
+ marker.markers.push(subMark);
+ subMark.parent = marker;
+ }
+ }
+ }
+
+ function detachSharedMarkers(markers) {
+ var loop = function ( i ) {
+ var marker = markers[i], linked = [marker.primary.doc];
+ linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
+ for (var j = 0; j < marker.markers.length; j++) {
+ var subMarker = marker.markers[j];
+ if (indexOf(linked, subMarker.doc) == -1) {
+ subMarker.parent = null;
+ marker.markers.splice(j--, 1);
+ }
+ }
+ };
+
+ for (var i = 0; i < markers.length; i++) loop( i );
+ }
+
+ var nextDocId = 0;
+ var Doc = function(text, mode, firstLine, lineSep, direction) {
+ if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
+ if (firstLine == null) { firstLine = 0; }
+
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+ this.first = firstLine;
+ this.scrollTop = this.scrollLeft = 0;
+ this.cantEdit = false;
+ this.cleanGeneration = 1;
+ this.modeFrontier = this.highlightFrontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+ this.lineSep = lineSep;
+ this.direction = (direction == "rtl") ? "rtl" : "ltr";
+ this.extend = false;
+
+ if (typeof text == "string") { text = this.splitLines(text); }
+ updateDoc(this, {from: start, to: start, text: text});
+ setSelection(this, simpleSelection(start), sel_dontScroll);
+ };
+
+ Doc.prototype = createObj(BranchChunk.prototype, {
+ constructor: Doc,
+ // Iterate over the document. Supports two forms -- with only one
+ // argument, it calls that for each line in the document. With
+ // three, it iterates over the range given by the first two (with
+ // the second being non-inclusive).
+ iter: function(from, to, op) {
+ if (op) { this.iterN(from - this.first, to - from, op); }
+ else { this.iterN(this.first, this.first + this.size, from); }
+ },
+
+ // Non-public interface for adding and removing lines.
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
+ this.insertInner(at - this.first, lines, height);
+ },
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
+
+ // From here, the methods are part of the public interface. Most
+ // are also available from CodeMirror (editor) instances.
+
+ getValue: function(lineSep) {
+ var lines = getLines(this, this.first, this.first + this.size);
+ if (lineSep === false) { return lines }
+ return lines.join(lineSep || this.lineSeparator())
+ },
+ setValue: docMethodOp(function(code) {
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
+ if (this.cm) { scrollToCoords(this.cm, 0, 0); }
+ setSelection(this, simpleSelection(top), sel_dontScroll);
+ }),
+ replaceRange: function(code, from, to, origin) {
+ from = clipPos(this, from);
+ to = to ? clipPos(this, to) : from;
+ replaceRange(this, code, from, to, origin);
+ },
+ getRange: function(from, to, lineSep) {
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+ if (lineSep === false) { return lines }
+ if (lineSep === '') { return lines.join('') }
+ return lines.join(lineSep || this.lineSeparator())
+ },
+
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
+
+ getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
+ getLineNumber: function(line) {return lineNo(line)},
+
+ getLineHandleVisualStart: function(line) {
+ if (typeof line == "number") { line = getLine(this, line); }
+ return visualLine(line)
+ },
+
+ lineCount: function() {return this.size},
+ firstLine: function() {return this.first},
+ lastLine: function() {return this.first + this.size - 1},
+
+ clipPos: function(pos) {return clipPos(this, pos)},
+
+ getCursor: function(start) {
+ var range = this.sel.primary(), pos;
+ if (start == null || start == "head") { pos = range.head; }
+ else if (start == "anchor") { pos = range.anchor; }
+ else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
+ else { pos = range.from(); }
+ return pos
+ },
+ listSelections: function() { return this.sel.ranges },
+ somethingSelected: function() {return this.sel.somethingSelected()},
+
+ setCursor: docMethodOp(function(line, ch, options) {
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
+ }),
+ setSelection: docMethodOp(function(anchor, head, options) {
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
+ }),
+ extendSelection: docMethodOp(function(head, other, options) {
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
+ }),
+ extendSelections: docMethodOp(function(heads, options) {
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ extendSelectionsBy: docMethodOp(function(f, options) {
+ var heads = map(this.sel.ranges, f);
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ if (!ranges.length) { return }
+ var out = [];
+ for (var i = 0; i < ranges.length; i++)
+ { out[i] = new Range(clipPos(this, ranges[i].anchor),
+ clipPos(this, ranges[i].head || ranges[i].anchor)); }
+ if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
+ setSelection(this, normalizeSelection(this.cm, out, primary), options);
+ }),
+ addSelection: docMethodOp(function(anchor, head, options) {
+ var ranges = this.sel.ranges.slice(0);
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
+ setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
+ }),
+
+ getSelection: function(lineSep) {
+ var ranges = this.sel.ranges, lines;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ lines = lines ? lines.concat(sel) : sel;
+ }
+ if (lineSep === false) { return lines }
+ else { return lines.join(lineSep || this.lineSeparator()) }
+ },
+ getSelections: function(lineSep) {
+ var parts = [], ranges = this.sel.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
+ parts[i] = sel;
+ }
+ return parts
+ },
+ replaceSelection: function(code, collapse, origin) {
+ var dup = [];
+ for (var i = 0; i < this.sel.ranges.length; i++)
+ { dup[i] = code; }
+ this.replaceSelections(dup, collapse, origin || "+input");
+ },
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
+ var changes = [], sel = this.sel;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
+ { makeChange(this, changes[i$1]); }
+ if (newSel) { setSelectionReplaceHistory(this, newSel); }
+ else if (this.cm) { ensureCursorVisible(this.cm); }
+ }),
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
+
+ setExtending: function(val) {this.extend = val;},
+ getExtending: function() {return this.extend},
+
+ historySize: function() {
+ var hist = this.history, done = 0, undone = 0;
+ for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
+ for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
+ return {undo: done, redo: undone}
+ },
+ clearHistory: function() {
+ var this$1 = this;
+
+ this.history = new History(this.history);
+ linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
+ },
+
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
+ return this.history.generation
+ },
+ isClean: function (gen) {
+ return this.history.generation == (gen || this.cleanGeneration)
+ },
+
+ getHistory: function() {
+ return {done: copyHistoryArray(this.history.done),
+ undone: copyHistoryArray(this.history.undone)}
+ },
+ setHistory: function(histData) {
+ var hist = this.history = new History(this.history);
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
+ },
+
+ setGutterMarker: docMethodOp(function(line, gutterID, value) {
+ return changeLine(this, line, "gutter", function (line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
+ return true
+ })
+ }),
+
+ clearGutter: docMethodOp(function(gutterID) {
+ var this$1 = this;
+
+ this.iter(function (line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ changeLine(this$1, line, "gutter", function () {
+ line.gutterMarkers[gutterID] = null;
+ if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
+ return true
+ });
+ }
+ });
+ }),
+
+ lineInfo: function(line) {
+ var n;
+ if (typeof line == "number") {
+ if (!isLine(this, line)) { return null }
+ n = line;
+ line = getLine(this, line);
+ if (!line) { return null }
+ } else {
+ n = lineNo(line);
+ if (n == null) { return null }
+ }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets}
+ },
+
+ addLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ if (!line[prop]) { line[prop] = cls; }
+ else if (classTest(cls).test(line[prop])) { return false }
+ else { line[prop] += " " + cls; }
+ return true
+ })
+ }),
+ removeLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) { return false }
+ else if (cls == null) { line[prop] = null; }
+ else {
+ var found = cur.match(classTest(cls));
+ if (!found) { return false }
+ var end = found.index + found[0].length;
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ }
+ return true
+ })
+ }),
+
+ addLineWidget: docMethodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options)
+ }),
+ removeLineWidget: function(widget) { widget.clear(); },
+
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
+ },
+ setBookmark: function(pos, options) {
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+ insertLeft: options && options.insertLeft,
+ clearWhenEmpty: false, shared: options && options.shared,
+ handleMouseEvents: options && options.handleMouseEvents};
+ pos = clipPos(this, pos);
+ return markText(this, pos, pos, realOpts, "bookmark")
+ },
+ findMarksAt: function(pos) {
+ pos = clipPos(this, pos);
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ { markers.push(span.marker.parent || span.marker); }
+ } }
+ return markers
+ },
+ findMarks: function(from, to, filter) {
+ from = clipPos(this, from); to = clipPos(this, to);
+ var found = [], lineNo = from.line;
+ this.iter(from.line, to.line + 1, function (line) {
+ var spans = line.markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; i++) {
+ var span = spans[i];
+ if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
+ span.from == null && lineNo != from.line ||
+ span.from != null && lineNo == to.line && span.from >= to.ch) &&
+ (!filter || filter(span.marker)))
+ { found.push(span.marker.parent || span.marker); }
+ } }
+ ++lineNo;
+ });
+ return found
+ },
+ getAllMarks: function() {
+ var markers = [];
+ this.iter(function (line) {
+ var sps = line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i)
+ { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
+ });
+ return markers
+ },
+
+ posFromIndex: function(off) {
+ var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
+ this.iter(function (line) {
+ var sz = line.text.length + sepSize;
+ if (sz > off) { ch = off; return true }
+ off -= sz;
+ ++lineNo;
+ });
+ return clipPos(this, Pos(lineNo, ch))
+ },
+ indexFromPos: function (coords) {
+ coords = clipPos(this, coords);
+ var index = coords.ch;
+ if (coords.line < this.first || coords.ch < 0) { return 0 }
+ var sepSize = this.lineSeparator().length;
+ this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
+ index += line.text.length + sepSize;
+ });
+ return index
+ },
+
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
+ this.modeOption, this.first, this.lineSep, this.direction);
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+ doc.sel = this.sel;
+ doc.extend = false;
+ if (copyHistory) {
+ doc.history.undoDepth = this.history.undoDepth;
+ doc.setHistory(this.getHistory());
+ }
+ return doc
+ },
+
+ linkedDoc: function(options) {
+ if (!options) { options = {}; }
+ var from = this.first, to = this.first + this.size;
+ if (options.from != null && options.from > from) { from = options.from; }
+ if (options.to != null && options.to < to) { to = options.to; }
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
+ if (options.sharedHist) { copy.history = this.history
+ ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+ copySharedMarkers(copy, findSharedMarkers(this));
+ return copy
+ },
+ unlinkDoc: function(other) {
+ if (other instanceof CodeMirror) { other = other.doc; }
+ if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
+ var link = this.linked[i];
+ if (link.doc != other) { continue }
+ this.linked.splice(i, 1);
+ other.unlinkDoc(this);
+ detachSharedMarkers(findSharedMarkers(this));
+ break
+ } }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
+ other.history = new History(null);
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ }
+ },
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
+
+ getMode: function() {return this.mode},
+ getEditor: function() {return this.cm},
+
+ splitLines: function(str) {
+ if (this.lineSep) { return str.split(this.lineSep) }
+ return splitLinesAuto(str)
+ },
+ lineSeparator: function() { return this.lineSep || "\n" },
+
+ setDirection: docMethodOp(function (dir) {
+ if (dir != "rtl") { dir = "ltr"; }
+ if (dir == this.direction) { return }
+ this.direction = dir;
+ this.iter(function (line) { return line.order = null; });
+ if (this.cm) { directionChanged(this.cm); }
+ })
+ });
+
+ // Public alias.
+ Doc.prototype.eachLine = Doc.prototype.iter;
+
+ // Kludge to work around strange IE behavior where it'll sometimes
+ // re-fire a series of drag-related events right after the drop (#1551)
+ var lastDrop = 0;
+
+ function onDrop(e) {
+ var cm = this;
+ clearDragCursor(cm);
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+ { return }
+ e_preventDefault(e);
+ if (ie) { lastDrop = +new Date; }
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || cm.isReadOnly()) { return }
+ // Might be a file drop, in which case we simply extract the text
+ // and insert it.
+ if (files && files.length && window.FileReader && window.File) {
+ var n = files.length, text = Array(n), read = 0;
+ var markAsReadAndPasteIfAllFilesAreRead = function () {
+ if (++read == n) {
+ operation(cm, function () {
+ pos = clipPos(cm.doc, pos);
+ var change = {from: pos, to: pos,
+ text: cm.doc.splitLines(
+ text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
+ origin: "paste"};
+ makeChange(cm.doc, change);
+ setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
+ })();
+ }
+ };
+ var readTextFromFile = function (file, i) {
+ if (cm.options.allowDropFileTypes &&
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
+ markAsReadAndPasteIfAllFilesAreRead();
+ return
+ }
+ var reader = new FileReader;
+ reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
+ reader.onload = function () {
+ var content = reader.result;
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
+ markAsReadAndPasteIfAllFilesAreRead();
+ return
+ }
+ text[i] = content;
+ markAsReadAndPasteIfAllFilesAreRead();
+ };
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
+ } else { // Normal drop
+ // Don't do a replace if the drop happened inside of the selected text.
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
+ cm.state.draggingText(e);
+ // Ensure the editor is re-focused
+ setTimeout(function () { return cm.display.input.focus(); }, 20);
+ return
+ }
+ try {
+ var text$1 = e.dataTransfer.getData("Text");
+ if (text$1) {
+ var selected;
+ if (cm.state.draggingText && !cm.state.draggingText.copy)
+ { selected = cm.listSelections(); }
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
+ if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
+ { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
+ cm.replaceSelection(text$1, "around", "paste");
+ cm.display.input.focus();
+ }
+ }
+ catch(e$1){}
+ }
+ }
+
+ function onDragStart(cm, e) {
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
+
+ e.dataTransfer.setData("Text", cm.getSelection());
+ e.dataTransfer.effectAllowed = "copyMove";
+
+ // Use dummy image instead of default browsers image.
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+ if (e.dataTransfer.setDragImage && !safari) {
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
+ if (presto) {
+ img.width = img.height = 1;
+ cm.display.wrapper.appendChild(img);
+ // Force a relayout, or Opera won't use our image for some obscure reason
+ img._top = img.offsetTop;
+ }
+ e.dataTransfer.setDragImage(img, 0, 0);
+ if (presto) { img.parentNode.removeChild(img); }
+ }
+ }
+
+ function onDragOver(cm, e) {
+ var pos = posFromMouse(cm, e);
+ if (!pos) { return }
+ var frag = document.createDocumentFragment();
+ drawSelectionCursor(cm, pos, frag);
+ if (!cm.display.dragCursor) {
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
+ }
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
+ }
+
+ function clearDragCursor(cm) {
+ if (cm.display.dragCursor) {
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
+ cm.display.dragCursor = null;
+ }
+ }
+
+ // These must be handled carefully, because naively registering a
+ // handler for each editor will cause the editors to never be
+ // garbage collected.
+
+ function forEachCodeMirror(f) {
+ if (!document.getElementsByClassName) { return }
+ var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
+ for (var i = 0; i < byClass.length; i++) {
+ var cm = byClass[i].CodeMirror;
+ if (cm) { editors.push(cm); }
+ }
+ if (editors.length) { editors[0].operation(function () {
+ for (var i = 0; i < editors.length; i++) { f(editors[i]); }
+ }); }
+ }
+
+ var globalsRegistered = false;
+ function ensureGlobalHandlers() {
+ if (globalsRegistered) { return }
+ registerGlobalHandlers();
+ globalsRegistered = true;
+ }
+ function registerGlobalHandlers() {
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ on(window, "resize", function () {
+ if (resizeTimer == null) { resizeTimer = setTimeout(function () {
+ resizeTimer = null;
+ forEachCodeMirror(onResize);
+ }, 100); }
+ });
+ // When the window loses focus, we want to show the editor as blurred
+ on(window, "blur", function () { return forEachCodeMirror(onBlur); });
+ }
+ // Called when the window resizes
+ function onResize(cm) {
+ var d = cm.display;
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+ d.scrollbarsClipped = false;
+ cm.setSize();
+ }
+
+ var keyNames = {
+ 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
+ };
+
+ // Number keys
+ for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
+ // Alphabetic keys
+ for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
+ // Function keys
+ for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
+
+ var keyMap = {};
+
+ keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
+ "Esc": "singleSelection"
+ };
+ // Note that the save and find-related commands aren't defined by
+ // default. User code or addons can define them. Unknown commands
+ // are simply ignored.
+ keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
+ "fallthrough": "basic"
+ };
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
+ keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
+ "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
+ "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
+ };
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
+ "fallthrough": ["basic", "emacsy"]
+ };
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+
+ // KEYMAP DISPATCH
+
+ function normalizeKeyName(name) {
+ var parts = name.split(/-(?!$)/);
+ name = parts[parts.length - 1];
+ var alt, ctrl, shift, cmd;
+ for (var i = 0; i < parts.length - 1; i++) {
+ var mod = parts[i];
+ if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
+ else if (/^a(lt)?$/i.test(mod)) { alt = true; }
+ else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
+ else if (/^s(hift)?$/i.test(mod)) { shift = true; }
+ else { throw new Error("Unrecognized modifier name: " + mod) }
+ }
+ if (alt) { name = "Alt-" + name; }
+ if (ctrl) { name = "Ctrl-" + name; }
+ if (cmd) { name = "Cmd-" + name; }
+ if (shift) { name = "Shift-" + name; }
+ return name
+ }
+
+ // This is a kludge to keep keymaps mostly working as raw objects
+ // (backwards compatibility) while at the same time support features
+ // like normalization and multi-stroke key bindings. It compiles a
+ // new normalized keymap, and then updates the old object to reflect
+ // this.
+ function normalizeKeyMap(keymap) {
+ var copy = {};
+ for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
+ var value = keymap[keyname];
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
+ if (value == "...") { delete keymap[keyname]; continue }
+
+ var keys = map(keyname.split(" "), normalizeKeyName);
+ for (var i = 0; i < keys.length; i++) {
+ var val = (void 0), name = (void 0);
+ if (i == keys.length - 1) {
+ name = keys.join(" ");
+ val = value;
+ } else {
+ name = keys.slice(0, i + 1).join(" ");
+ val = "...";
+ }
+ var prev = copy[name];
+ if (!prev) { copy[name] = val; }
+ else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
+ }
+ delete keymap[keyname];
+ } }
+ for (var prop in copy) { keymap[prop] = copy[prop]; }
+ return keymap
+ }
+
+ function lookupKey(key, map, handle, context) {
+ map = getKeyMap(map);
+ var found = map.call ? map.call(key, context) : map[key];
+ if (found === false) { return "nothing" }
+ if (found === "...") { return "multi" }
+ if (found != null && handle(found)) { return "handled" }
+
+ if (map.fallthrough) {
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
+ { return lookupKey(key, map.fallthrough, handle, context) }
+ for (var i = 0; i < map.fallthrough.length; i++) {
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
+ if (result) { return result }
+ }
+ }
+ }
+
+ // Modifier key presses don't count as 'real' key presses for the
+ // purpose of keymap fallthrough.
+ function isModifierKey(value) {
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
+ }
+
+ function addModifierNames(name, event, noShift) {
+ var base = name;
+ if (event.altKey && base != "Alt") { name = "Alt-" + name; }
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
+ if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
+ return name
+ }
+
+ // Look up the name of a key as indicated by an event object.
+ function keyName(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) { return false }
+ var name = keyNames[event.keyCode];
+ if (name == null || event.altGraphKey) { return false }
+ // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
+ // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
+ if (event.keyCode == 3 && event.code) { name = event.code; }
+ return addModifierNames(name, event, noShift)
+ }
+
+ function getKeyMap(val) {
+ return typeof val == "string" ? keyMap[val] : val
+ }
+
+ // Helper for deleting text near the selection(s), used to implement
+ // backspace, delete, and similar functionality.
+ function deleteNearSelection(cm, compute) {
+ var ranges = cm.doc.sel.ranges, kill = [];
+ // Build up a set of ranges to kill first, merging overlapping
+ // ranges.
+ for (var i = 0; i < ranges.length; i++) {
+ var toKill = compute(ranges[i]);
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
+ var replaced = kill.pop();
+ if (cmp(replaced.from, toKill.from) < 0) {
+ toKill.from = replaced.from;
+ break
+ }
+ }
+ kill.push(toKill);
+ }
+ // Next, remove those actual ranges.
+ runInOp(cm, function () {
+ for (var i = kill.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
+ ensureCursorVisible(cm);
+ });
+ }
+
+ function moveCharLogically(line, ch, dir) {
+ var target = skipExtendingChars(line.text, ch + dir, dir);
+ return target < 0 || target > line.text.length ? null : target
+ }
+
+ function moveLogically(line, start, dir) {
+ var ch = moveCharLogically(line, start.ch, dir);
+ return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+ }
+
+ function endOfLine(visually, cm, lineObj, lineNo, dir) {
+ if (visually) {
+ if (cm.doc.direction == "rtl") { dir = -dir; }
+ var order = getOrder(lineObj, cm.doc.direction);
+ if (order) {
+ var part = dir < 0 ? lst(order) : order[0];
+ var moveInStorageOrder = (dir < 0) == (part.level == 1);
+ var sticky = moveInStorageOrder ? "after" : "before";
+ var ch;
+ // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
+ // it could be that the last bidi part is not on the last visual line,
+ // since visual lines contain content order-consecutive chunks.
+ // Thus, in rtl, we are looking for the first (content-order) character
+ // in the rtl chunk that is on the last line (that is, the same line
+ // as the last (content-order) character).
+ if (part.level > 0 || cm.doc.direction == "rtl") {
+ var prep = prepareMeasureForLine(cm, lineObj);
+ ch = dir < 0 ? lineObj.text.length - 1 : 0;
+ var targetTop = measureCharPrepared(cm, prep, ch).top;
+ ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
+ if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
+ } else { ch = dir < 0 ? part.to : part.from; }
+ return new Pos(lineNo, ch, sticky)
+ }
+ }
+ return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+ }
+
+ function moveVisually(cm, line, start, dir) {
+ var bidi = getOrder(line, cm.doc.direction);
+ if (!bidi) { return moveLogically(line, start, dir) }
+ if (start.ch >= line.text.length) {
+ start.ch = line.text.length;
+ start.sticky = "before";
+ } else if (start.ch <= 0) {
+ start.ch = 0;
+ start.sticky = "after";
+ }
+ var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
+ if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
+ // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
+ // nothing interesting happens.
+ return moveLogically(line, start, dir)
+ }
+
+ var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
+ var prep;
+ var getWrappedLineExtent = function (ch) {
+ if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
+ prep = prep || prepareMeasureForLine(cm, line);
+ return wrappedLineExtentChar(cm, line, prep, ch)
+ };
+ var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
+
+ if (cm.doc.direction == "rtl" || part.level == 1) {
+ var moveInStorageOrder = (part.level == 1) == (dir < 0);
+ var ch = mv(start, moveInStorageOrder ? 1 : -1);
+ if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
+ // Case 2: We move within an rtl part or in an rtl editor on the same visual line
+ var sticky = moveInStorageOrder ? "before" : "after";
+ return new Pos(start.line, ch, sticky)
+ }
+ }
+
+ // Case 3: Could not move within this bidi part in this visual line, so leave
+ // the current bidi part
+
+ var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
+ var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
+ ? new Pos(start.line, mv(ch, 1), "before")
+ : new Pos(start.line, ch, "after"); };
+
+ for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
+ var part = bidi[partPos];
+ var moveInStorageOrder = (dir > 0) == (part.level != 1);
+ var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
+ if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
+ ch = moveInStorageOrder ? part.from : mv(part.to, -1);
+ if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
+ }
+ };
+
+ // Case 3a: Look for other bidi parts on the same visual line
+ var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
+ if (res) { return res }
+
+ // Case 3b: Look for other bidi parts on the next visual line
+ var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
+ if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
+ res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
+ if (res) { return res }
+ }
+
+ // Case 4: Nowhere to move
+ return null
+ }
+
+ // Commands are parameter-less actions that can be performed on an
+ // editor, mostly used for keybindings.
+ var commands = {
+ selectAll: selectAll,
+ singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
+ killLine: function (cm) { return deleteNearSelection(cm, function (range) {
+ if (range.empty()) {
+ var len = getLine(cm.doc, range.head.line).text.length;
+ if (range.head.ch == len && range.head.line < cm.lastLine())
+ { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
+ else
+ { return {from: range.head, to: Pos(range.head.line, len)} }
+ } else {
+ return {from: range.from(), to: range.to()}
+ }
+ }); },
+ deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
+ }); }); },
+ delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0), to: range.from()
+ }); }); },
+ delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
+ return {from: leftPos, to: range.from()}
+ }); },
+ delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ return {from: range.from(), to: rightPos }
+ }); },
+ undo: function (cm) { return cm.undo(); },
+ redo: function (cm) { return cm.redo(); },
+ undoSelection: function (cm) { return cm.undoSelection(); },
+ redoSelection: function (cm) { return cm.redoSelection(); },
+ goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
+ goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
+ goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
+ {origin: "+move", bias: -1}
+ ); },
+ goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
+ }, sel_move); },
+ goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div")
+ }, sel_move); },
+ goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
+ return pos
+ }, sel_move); },
+ goLineUp: function (cm) { return cm.moveV(-1, "line"); },
+ goLineDown: function (cm) { return cm.moveV(1, "line"); },
+ goPageUp: function (cm) { return cm.moveV(-1, "page"); },
+ goPageDown: function (cm) { return cm.moveV(1, "page"); },
+ goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
+ goCharRight: function (cm) { return cm.moveH(1, "char"); },
+ goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
+ goColumnRight: function (cm) { return cm.moveH(1, "column"); },
+ goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
+ goGroupRight: function (cm) { return cm.moveH(1, "group"); },
+ goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
+ goWordRight: function (cm) { return cm.moveH(1, "word"); },
+ delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
+ delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
+ delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
+ delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
+ delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
+ delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
+ indentAuto: function (cm) { return cm.indentSelection("smart"); },
+ indentMore: function (cm) { return cm.indentSelection("add"); },
+ indentLess: function (cm) { return cm.indentSelection("subtract"); },
+ insertTab: function (cm) { return cm.replaceSelection("\t"); },
+ insertSoftTab: function (cm) {
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].from();
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
+ spaces.push(spaceStr(tabSize - col % tabSize));
+ }
+ cm.replaceSelections(spaces);
+ },
+ defaultTab: function (cm) {
+ if (cm.somethingSelected()) { cm.indentSelection("add"); }
+ else { cm.execCommand("insertTab"); }
+ },
+ // Swap the two chars left and right of each selection's head.
+ // Move cursor behind the two swapped characters afterwards.
+ //
+ // Doesn't consider line feeds a character.
+ // Doesn't scan more than one line above to find a character.
+ // Doesn't do anything on an empty line.
+ // Doesn't do anything with non-empty selections.
+ transposeChars: function (cm) { return runInOp(cm, function () {
+ var ranges = cm.listSelections(), newSel = [];
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) { continue }
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (line) {
+ if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
+ if (cur.ch > 0) {
+ cur = new Pos(cur.line, cur.ch + 1);
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
+ } else if (cur.line > cm.doc.first) {
+ var prev = getLine(cm.doc, cur.line - 1).text;
+ if (prev) {
+ cur = new Pos(cur.line, 1);
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
+ prev.charAt(prev.length - 1),
+ Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
+ }
+ }
+ }
+ newSel.push(new Range(cur, cur));
+ }
+ cm.setSelections(newSel);
+ }); },
+ newlineAndIndent: function (cm) { return runInOp(cm, function () {
+ var sels = cm.listSelections();
+ for (var i = sels.length - 1; i >= 0; i--)
+ { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
+ sels = cm.listSelections();
+ for (var i$1 = 0; i$1 < sels.length; i$1++)
+ { cm.indentLine(sels[i$1].from().line, null, true); }
+ ensureCursorVisible(cm);
+ }); },
+ openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
+ toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
+ };
+
+
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, visual, lineN, 1)
+ }
+ function lineEnd(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLineEnd(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, line, lineN, -1)
+ }
+ function lineStartSmart(cm, pos) {
+ var start = lineStart(cm, pos.line);
+ var line = getLine(cm.doc, start.line);
+ var order = getOrder(line, cm.doc.direction);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
+ }
+ return start
+ }
+
+ // Run a handler that was bound to a key.
+ function doHandleBinding(cm, bound, dropShift) {
+ if (typeof bound == "string") {
+ bound = commands[bound];
+ if (!bound) { return false }
+ }
+ // Ensure previous input has been read, so that the handler sees a
+ // consistent view of the document
+ cm.display.input.ensurePolled();
+ var prevShift = cm.display.shift, done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ if (dropShift) { cm.display.shift = false; }
+ done = bound(cm) != Pass;
+ } finally {
+ cm.display.shift = prevShift;
+ cm.state.suppressEdits = false;
+ }
+ return done
+ }
+
+ function lookupKeyForEditor(cm, name, handle) {
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
+ if (result) { return result }
+ }
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
+ || lookupKey(name, cm.options.keyMap, handle, cm)
+ }
+
+ // Note that, despite the name, this function is also used to check
+ // for bound mouse clicks.
+
+ var stopSeq = new Delayed;
+
+ function dispatchKey(cm, name, e, handle) {
+ var seq = cm.state.keySeq;
+ if (seq) {
+ if (isModifierKey(name)) { return "handled" }
+ if (/\'$/.test(name))
+ { cm.state.keySeq = null; }
+ else
+ { stopSeq.set(50, function () {
+ if (cm.state.keySeq == seq) {
+ cm.state.keySeq = null;
+ cm.display.input.reset();
+ }
+ }); }
+ if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
+ }
+ return dispatchKeyInner(cm, name, e, handle)
+ }
+
+ function dispatchKeyInner(cm, name, e, handle) {
+ var result = lookupKeyForEditor(cm, name, handle);
+
+ if (result == "multi")
+ { cm.state.keySeq = name; }
+ if (result == "handled")
+ { signalLater(cm, "keyHandled", cm, name, e); }
+
+ if (result == "handled" || result == "multi") {
+ e_preventDefault(e);
+ restartBlink(cm);
+ }
+
+ return !!result
+ }
+
+ // Handle a key from the keydown event.
+ function handleKeyBinding(cm, e) {
+ var name = keyName(e, true);
+ if (!name) { return false }
+
+ if (e.shiftKey && !cm.state.keySeq) {
+ // First try to resolve full name (including 'Shift-'). Failing
+ // that, see if there is a cursor-motion command (starting with
+ // 'go') bound to the keyname without 'Shift-'.
+ return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
+ || dispatchKey(cm, name, e, function (b) {
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+ { return doHandleBinding(cm, b) }
+ })
+ } else {
+ return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
+ }
+ }
+
+ // Handle a key from the keypress event
+ function handleCharBinding(cm, e, ch) {
+ return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
+ }
+
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ if (e.target && e.target != cm.display.input.getField()) { return }
+ cm.curOp.focus = activeElt(doc(cm));
+ if (signalDOMEvent(cm, e)) { return }
+ // IE does strange things with escape.
+ if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
+ var code = e.keyCode;
+ cm.display.shift = code == 16 || e.shiftKey;
+ var handled = handleKeyBinding(cm, e);
+ if (presto) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+ { cm.replaceSelection("", null, "cut"); }
+ }
+ if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
+ { document.execCommand("cut"); }
+
+ // Turn mouse into crosshair when Alt is held on Mac.
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+ { showCrossHair(cm); }
+ }
+
+ function showCrossHair(cm) {
+ var lineDiv = cm.display.lineDiv;
+ addClass(lineDiv, "CodeMirror-crosshair");
+
+ function up(e) {
+ if (e.keyCode == 18 || !e.altKey) {
+ rmClass(lineDiv, "CodeMirror-crosshair");
+ off(document, "keyup", up);
+ off(document, "mouseover", up);
+ }
+ }
+ on(document, "keyup", up);
+ on(document, "mouseover", up);
+ }
+
+ function onKeyUp(e) {
+ if (e.keyCode == 16) { this.doc.sel.shift = false; }
+ signalDOMEvent(this, e);
+ }
+
+ function onKeyPress(e) {
+ var cm = this;
+ if (e.target && e.target != cm.display.input.getField()) { return }
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
+ var keyCode = e.keyCode, charCode = e.charCode;
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ // Some browsers fire keypress events for backspace
+ if (ch == "\x08") { return }
+ if (handleCharBinding(cm, e, ch)) { return }
+ cm.display.input.onKeyPress(e);
+ }
+
+ var DOUBLECLICK_DELAY = 400;
+
+ var PastClick = function(time, pos, button) {
+ this.time = time;
+ this.pos = pos;
+ this.button = button;
+ };
+
+ PastClick.prototype.compare = function (time, pos, button) {
+ return this.time + DOUBLECLICK_DELAY > time &&
+ cmp(pos, this.pos) == 0 && button == this.button
+ };
+
+ var lastClick, lastDoubleClick;
+ function clickRepeat(pos, button) {
+ var now = +new Date;
+ if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
+ lastClick = lastDoubleClick = null;
+ return "triple"
+ } else if (lastClick && lastClick.compare(now, pos, button)) {
+ lastDoubleClick = new PastClick(now, pos, button);
+ lastClick = null;
+ return "double"
+ } else {
+ lastClick = new PastClick(now, pos, button);
+ lastDoubleClick = null;
+ return "single"
+ }
+ }
+
+ // A mouse down can be a single click, double click, triple click,
+ // start of selection drag, start of text drag, new cursor
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
+ // middle-click-paste. Or it might be a click on something we should
+ // not interfere with, such as a scrollbar or widget.
+ function onMouseDown(e) {
+ var cm = this, display = cm.display;
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
+ display.input.ensurePolled();
+ display.shift = e.shiftKey;
+
+ if (eventInWidget(display, e)) {
+ if (!webkit) {
+ // Briefly turn off draggability, to allow widgets to do
+ // normal dragging things.
+ display.scroller.draggable = false;
+ setTimeout(function () { return display.scroller.draggable = true; }, 100);
+ }
+ return
+ }
+ if (clickInGutter(cm, e)) { return }
+ var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
+ win(cm).focus();
+
+ // #3261: make sure, that we're not starting a second selection
+ if (button == 1 && cm.state.selectingText)
+ { cm.state.selectingText(e); }
+
+ if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
+
+ if (button == 1) {
+ if (pos) { leftButtonDown(cm, pos, repeat, e); }
+ else if (e_target(e) == display.scroller) { e_preventDefault(e); }
+ } else if (button == 2) {
+ if (pos) { extendSelection(cm.doc, pos); }
+ setTimeout(function () { return display.input.focus(); }, 20);
+ } else if (button == 3) {
+ if (captureRightClick) { cm.display.input.onContextMenu(e); }
+ else { delayBlurEvent(cm); }
+ }
+ }
+
+ function handleMappedButton(cm, button, pos, repeat, event) {
+ var name = "Click";
+ if (repeat == "double") { name = "Double" + name; }
+ else if (repeat == "triple") { name = "Triple" + name; }
+ name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
+
+ return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
+ if (typeof bound == "string") { bound = commands[bound]; }
+ if (!bound) { return false }
+ var done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ done = bound(cm, pos) != Pass;
+ } finally {
+ cm.state.suppressEdits = false;
+ }
+ return done
+ })
+ }
+
+ function configureMouse(cm, repeat, event) {
+ var option = cm.getOption("configureMouse");
+ var value = option ? option(cm, repeat, event) : {};
+ if (value.unit == null) {
+ var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
+ value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
+ }
+ if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
+ if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
+ if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
+ return value
+ }
+
+ function leftButtonDown(cm, pos, repeat, event) {
+ if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
+ else { cm.curOp.focus = activeElt(doc(cm)); }
+
+ var behavior = configureMouse(cm, repeat, event);
+
+ var sel = cm.doc.sel, contained;
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
+ repeat == "single" && (contained = sel.contains(pos)) > -1 &&
+ (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
+ (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
+ { leftButtonStartDrag(cm, event, pos, behavior); }
+ else
+ { leftButtonSelect(cm, event, pos, behavior); }
+ }
+
+ // Start a text drag. When it ends, see if any dragging actually
+ // happen, and treat as a click if it didn't.
+ function leftButtonStartDrag(cm, event, pos, behavior) {
+ var display = cm.display, moved = false;
+ var dragEnd = operation(cm, function (e) {
+ if (webkit) { display.scroller.draggable = false; }
+ cm.state.draggingText = false;
+ if (cm.state.delayingBlurEvent) {
+ if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
+ else { delayBlurEvent(cm); }
+ }
+ off(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ off(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ off(display.scroller, "dragstart", dragStart);
+ off(display.scroller, "drop", dragEnd);
+ if (!moved) {
+ e_preventDefault(e);
+ if (!behavior.addNew)
+ { extendSelection(cm.doc, pos, null, null, behavior.extend); }
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
+ if ((webkit && !safari) || ie && ie_version == 9)
+ { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
+ else
+ { display.input.focus(); }
+ }
+ });
+ var mouseMove = function(e2) {
+ moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
+ };
+ var dragStart = function () { return moved = true; };
+ // Let the drag handler handle this.
+ if (webkit) { display.scroller.draggable = true; }
+ cm.state.draggingText = dragEnd;
+ dragEnd.copy = !behavior.moveOnDrag;
+ on(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ on(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ on(display.scroller, "dragstart", dragStart);
+ on(display.scroller, "drop", dragEnd);
+
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function () { return display.input.focus(); }, 20);
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
+ }
+
+ function rangeForUnit(cm, pos, unit) {
+ if (unit == "char") { return new Range(pos, pos) }
+ if (unit == "word") { return cm.findWordAt(pos) }
+ if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
+ var result = unit(cm, pos);
+ return new Range(result.from, result.to)
+ }
+
+ // Normal selection, as opposed to text dragging.
+ function leftButtonSelect(cm, event, start, behavior) {
+ if (ie) { delayBlurEvent(cm); }
+ var display = cm.display, doc$1 = cm.doc;
+ e_preventDefault(event);
+
+ var ourRange, ourIndex, startSel = doc$1.sel, ranges = startSel.ranges;
+ if (behavior.addNew && !behavior.extend) {
+ ourIndex = doc$1.sel.contains(start);
+ if (ourIndex > -1)
+ { ourRange = ranges[ourIndex]; }
+ else
+ { ourRange = new Range(start, start); }
+ } else {
+ ourRange = doc$1.sel.primary();
+ ourIndex = doc$1.sel.primIndex;
+ }
+
+ if (behavior.unit == "rectangle") {
+ if (!behavior.addNew) { ourRange = new Range(start, start); }
+ start = posFromMouse(cm, event, true, true);
+ ourIndex = -1;
+ } else {
+ var range = rangeForUnit(cm, start, behavior.unit);
+ if (behavior.extend)
+ { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
+ else
+ { ourRange = range; }
+ }
+
+ if (!behavior.addNew) {
+ ourIndex = 0;
+ setSelection(doc$1, new Selection([ourRange], 0), sel_mouse);
+ startSel = doc$1.sel;
+ } else if (ourIndex == -1) {
+ ourIndex = ranges.length;
+ setSelection(doc$1, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
+ {scroll: false, origin: "*mouse"});
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
+ setSelection(doc$1, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
+ {scroll: false, origin: "*mouse"});
+ startSel = doc$1.sel;
+ } else {
+ replaceOneSelection(doc$1, ourIndex, ourRange, sel_mouse);
+ }
+
+ var lastPos = start;
+ function extendTo(pos) {
+ if (cmp(lastPos, pos) == 0) { return }
+ lastPos = pos;
+
+ if (behavior.unit == "rectangle") {
+ var ranges = [], tabSize = cm.options.tabSize;
+ var startCol = countColumn(getLine(doc$1, start.line).text, start.ch, tabSize);
+ var posCol = countColumn(getLine(doc$1, pos.line).text, pos.ch, tabSize);
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
+ line <= end; line++) {
+ var text = getLine(doc$1, line).text, leftPos = findColumn(text, left, tabSize);
+ if (left == right)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
+ else if (text.length > leftPos)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
+ }
+ if (!ranges.length) { ranges.push(new Range(start, start)); }
+ setSelection(doc$1, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
+ {origin: "*mouse", scroll: false});
+ cm.scrollIntoView(pos);
+ } else {
+ var oldRange = ourRange;
+ var range = rangeForUnit(cm, pos, behavior.unit);
+ var anchor = oldRange.anchor, head;
+ if (cmp(range.anchor, anchor) > 0) {
+ head = range.head;
+ anchor = minPos(oldRange.from(), range.anchor);
+ } else {
+ head = range.anchor;
+ anchor = maxPos(oldRange.to(), range.head);
+ }
+ var ranges$1 = startSel.ranges.slice(0);
+ ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc$1, anchor), head));
+ setSelection(doc$1, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
+ }
+ }
+
+ var editorSize = display.wrapper.getBoundingClientRect();
+ // Used to ensure timeout re-tries don't fire when another extend
+ // happened in the meantime (clearTimeout isn't reliable -- at
+ // least on Chrome, the timeouts still happen even when cleared,
+ // if the clear happens after their scheduled firing time).
+ var counter = 0;
+
+ function extend(e) {
+ var curCount = ++counter;
+ var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
+ if (!cur) { return }
+ if (cmp(cur, lastPos) != 0) {
+ cm.curOp.focus = activeElt(doc(cm));
+ extendTo(cur);
+ var visible = visibleLines(display, doc$1);
+ if (cur.line >= visible.to || cur.line < visible.from)
+ { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
+ } else {
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+ if (outside) { setTimeout(operation(cm, function () {
+ if (counter != curCount) { return }
+ display.scroller.scrollTop += outside;
+ extend(e);
+ }), 50); }
+ }
+ }
+
+ function done(e) {
+ cm.state.selectingText = false;
+ counter = Infinity;
+ // If e is null or undefined we interpret this as someone trying
+ // to explicitly cancel the selection rather than the user
+ // letting go of the mouse button.
+ if (e) {
+ e_preventDefault(e);
+ display.input.focus();
+ }
+ off(display.wrapper.ownerDocument, "mousemove", move);
+ off(display.wrapper.ownerDocument, "mouseup", up);
+ doc$1.history.lastSelOrigin = null;
+ }
+
+ var move = operation(cm, function (e) {
+ if (e.buttons === 0 || !e_button(e)) { done(e); }
+ else { extend(e); }
+ });
+ var up = operation(cm, done);
+ cm.state.selectingText = up;
+ on(display.wrapper.ownerDocument, "mousemove", move);
+ on(display.wrapper.ownerDocument, "mouseup", up);
+ }
+
+ // Used when mouse-selecting to adjust the anchor to the proper side
+ // of a bidi jump depending on the visual position of the head.
+ function bidiSimplify(cm, range) {
+ var anchor = range.anchor;
+ var head = range.head;
+ var anchorLine = getLine(cm.doc, anchor.line);
+ if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
+ var order = getOrder(anchorLine);
+ if (!order) { return range }
+ var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
+ if (part.from != anchor.ch && part.to != anchor.ch) { return range }
+ var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
+ if (boundary == 0 || boundary == order.length) { return range }
+
+ // Compute the relative visual position of the head compared to the
+ // anchor (<0 is to the left, >0 to the right)
+ var leftSide;
+ if (head.line != anchor.line) {
+ leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
+ } else {
+ var headIndex = getBidiPartAt(order, head.ch, head.sticky);
+ var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
+ if (headIndex == boundary - 1 || headIndex == boundary)
+ { leftSide = dir < 0; }
+ else
+ { leftSide = dir > 0; }
+ }
+
+ var usePart = order[boundary + (leftSide ? -1 : 0)];
+ var from = leftSide == (usePart.level == 1);
+ var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
+ return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
+ }
+
+
+ // Determines whether an event happened in the gutter, and fires the
+ // handlers for the corresponding event.
+ function gutterEvent(cm, e, type, prevent) {
+ var mX, mY;
+ if (e.touches) {
+ mX = e.touches[0].clientX;
+ mY = e.touches[0].clientY;
+ } else {
+ try { mX = e.clientX; mY = e.clientY; }
+ catch(e$1) { return false }
+ }
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
+ if (prevent) { e_preventDefault(e); }
+
+ var display = cm.display;
+ var lineBox = display.lineDiv.getBoundingClientRect();
+
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
+ mY -= lineBox.top - display.viewOffset;
+
+ for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.doc, mY);
+ var gutter = cm.display.gutterSpecs[i];
+ signal(cm, type, cm, line, gutter.className, e);
+ return e_defaultPrevented(e)
+ }
+ }
+ }
+
+ function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true)
+ }
+
+ // CONTEXT MENU HANDLING
+
+ // To make the context menu work, we need to briefly unhide the
+ // textarea (making it as unobtrusive as possible) to let the
+ // right-click take effect on it.
+ function onContextMenu(cm, e) {
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
+ if (signalDOMEvent(cm, e, "contextmenu")) { return }
+ if (!captureRightClick) { cm.display.input.onContextMenu(e); }
+ }
+
+ function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) { return false }
+ return gutterEvent(cm, e, "gutterContextMenu", false)
+ }
+
+ function themeChanged(cm) {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+ clearCaches(cm);
+ }
+
+ var Init = {toString: function(){return "CodeMirror.Init"}};
+
+ var defaults = {};
+ var optionHandlers = {};
+
+ function defineOptions(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
+
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) { optionHandlers[name] =
+ notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
+ }
+
+ CodeMirror.defineOption = option;
+
+ // Passed to option handlers when there is no old value.
+ CodeMirror.Init = Init;
+
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function (cm, val) { return cm.setValue(val); }, true);
+ option("mode", null, function (cm, val) {
+ cm.doc.modeOption = val;
+ loadMode(cm);
+ }, true);
+
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function (cm) {
+ resetModeState(cm);
+ clearCaches(cm);
+ regChange(cm);
+ }, true);
+
+ option("lineSeparator", null, function (cm, val) {
+ cm.doc.lineSep = val;
+ if (!val) { return }
+ var newBreaks = [], lineNo = cm.doc.first;
+ cm.doc.iter(function (line) {
+ for (var pos = 0;;) {
+ var found = line.text.indexOf(val, pos);
+ if (found == -1) { break }
+ pos = found + val.length;
+ newBreaks.push(Pos(lineNo, found));
+ }
+ lineNo++;
+ });
+ for (var i = newBreaks.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
+ });
+ option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ if (old != Init) { cm.refresh(); }
+ });
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
+ option("electricChars", true);
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
+ throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
+ }, true);
+ option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
+ option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
+ option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function (cm) {
+ themeChanged(cm);
+ updateGutters(cm);
+ }, true);
+ option("keyMap", "default", function (cm, val, old) {
+ var next = getKeyMap(val);
+ var prev = old != Init && getKeyMap(old);
+ if (prev && prev.detach) { prev.detach(cm, next); }
+ if (next.attach) { next.attach(cm, prev || null); }
+ });
+ option("extraKeys", null);
+ option("configureMouse", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function (cm, val) {
+ cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
+ updateGutters(cm);
+ }, true);
+ option("fixedGutter", true, function (cm, val) {
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+ cm.refresh();
+ }, true);
+ option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
+ option("scrollbarStyle", "native", function (cm) {
+ initScrollbars(cm);
+ updateScrollbars(cm);
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
+ }, true);
+ option("lineNumbers", false, function (cm, val) {
+ cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
+ updateGutters(cm);
+ }, true);
+ option("firstLineNumber", 1, updateGutters, true);
+ option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+ option("lineWiseCopyCut", true);
+ option("pasteLinesPerSelection", true);
+ option("selectionsMayTouch", false);
+
+ option("readOnly", false, function (cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
+ }
+ cm.display.input.readOnlyChanged(val);
+ });
+
+ option("screenReaderLabel", null, function (cm, val) {
+ val = (val === '') ? null : val;
+ cm.display.input.screenReaderLabelChanged(val);
+ });
+
+ option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
+ option("dragDrop", true, dragDropChanged);
+ option("allowDropFileTypes", null);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1, updateSelection, true);
+ option("singleCursorHeightPerLine", true, updateSelection, true);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true, resetModeState, true);
+ option("addModeClass", false, resetModeState, true);
+ option("pollInterval", 100);
+ option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function (cm, val) {
+ if (!val) { cm.display.input.resetPosition(); }
+ });
+
+ option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
+ option("autofocus", null);
+ option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
+ option("phrases", null);
+ }
+
+ function dragDropChanged(cm, value, old) {
+ var wasOn = old && old != Init;
+ if (!value != !wasOn) {
+ var funcs = cm.display.dragFunctions;
+ var toggle = value ? on : off;
+ toggle(cm.display.scroller, "dragstart", funcs.start);
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
+ toggle(cm.display.scroller, "dragover", funcs.over);
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
+ toggle(cm.display.scroller, "drop", funcs.drop);
+ }
+ }
+
+ function wrappingChanged(cm) {
+ if (cm.options.lineWrapping) {
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
+ cm.display.sizer.style.minWidth = "";
+ cm.display.sizerWidth = null;
+ } else {
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
+ findMaxLine(cm);
+ }
+ estimateLineHeights(cm);
+ regChange(cm);
+ clearCaches(cm);
+ setTimeout(function () { return updateScrollbars(cm); }, 100);
+ }
+
+ // A CodeMirror instance represents an editor. This is the object
+ // that user code is usually dealing with.
+
+ function CodeMirror(place, options) {
+ var this$1 = this;
+
+ if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
+
+ this.options = options = options ? copyObj(options) : {};
+ // Determine effective options based on given values and defaults.
+ copyObj(defaults, options, false);
+
+ var doc = options.value;
+ if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
+ else if (options.mode) { doc.modeOption = options.mode; }
+ this.doc = doc;
+
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
+ var display = this.display = new Display(place, doc, input, options);
+ display.wrapper.CodeMirror = this;
+ themeChanged(this);
+ if (options.lineWrapping)
+ { this.display.wrapper.className += " CodeMirror-wrap"; }
+ initScrollbars(this);
+
+ this.state = {
+ keyMaps: [], // stores maps added by addKeyMap
+ overlays: [], // highlighting overlays, as added by addOverlay
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
+ overwrite: false,
+ delayingBlurEvent: false,
+ focused: false,
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
+ pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
+ selectingText: false,
+ draggingText: false,
+ highlight: new Delayed(), // stores highlight worker timeout
+ keySeq: null, // Unfinished key sequence
+ specialChars: null
+ };
+
+ if (options.autofocus && !mobile) { display.input.focus(); }
+
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
+
+ registerEventHandlers(this);
+ ensureGlobalHandlers();
+
+ startOperation(this);
+ this.curOp.forceUpdate = true;
+ attachDoc(this, doc);
+
+ if ((options.autofocus && !mobile) || this.hasFocus())
+ { setTimeout(function () {
+ if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
+ }, 20); }
+ else
+ { onBlur(this); }
+
+ for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
+ { optionHandlers[opt](this, options[opt], Init); } }
+ maybeUpdateLineNumberWidth(this);
+ if (options.finishInit) { options.finishInit(this); }
+ for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
+ endOperation(this);
+ // Suppress optimizelegibility in Webkit, since it breaks text
+ // measuring on line wrapping boundaries.
+ if (webkit && options.lineWrapping &&
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
+ { display.lineDiv.style.textRendering = "auto"; }
+ }
+
+ // The default configuration options.
+ CodeMirror.defaults = defaults;
+ // Functions to run when options are changed.
+ CodeMirror.optionHandlers = optionHandlers;
+
+ // Attach the necessary event handlers when initializing the editor
+ function registerEventHandlers(cm) {
+ var d = cm.display;
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
+ // Older IE's will not fire a second mousedown for a double click
+ if (ie && ie_version < 11)
+ { on(d.scroller, "dblclick", operation(cm, function (e) {
+ if (signalDOMEvent(cm, e)) { return }
+ var pos = posFromMouse(cm, e);
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
+ e_preventDefault(e);
+ var word = cm.findWordAt(pos);
+ extendSelection(cm.doc, word.anchor, word.head);
+ })); }
+ else
+ { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
+ // Some browsers fire contextmenu *after* opening the menu, at
+ // which point we can't mess with it anymore. Context menu is
+ // handled in onMouseDown for these browsers.
+ on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
+ on(d.input.getField(), "contextmenu", function (e) {
+ if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
+ });
+
+ // Used to suppress mouse event handling when a touch happens
+ var touchFinished, prevTouch = {end: 0};
+ function finishTouch() {
+ if (d.activeTouch) {
+ touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
+ prevTouch = d.activeTouch;
+ prevTouch.end = +new Date;
+ }
+ }
+ function isMouseLikeTouchEvent(e) {
+ if (e.touches.length != 1) { return false }
+ var touch = e.touches[0];
+ return touch.radiusX <= 1 && touch.radiusY <= 1
+ }
+ function farAway(touch, other) {
+ if (other.left == null) { return true }
+ var dx = other.left - touch.left, dy = other.top - touch.top;
+ return dx * dx + dy * dy > 20 * 20
+ }
+ on(d.scroller, "touchstart", function (e) {
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
+ d.input.ensurePolled();
+ clearTimeout(touchFinished);
+ var now = +new Date;
+ d.activeTouch = {start: now, moved: false,
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
+ if (e.touches.length == 1) {
+ d.activeTouch.left = e.touches[0].pageX;
+ d.activeTouch.top = e.touches[0].pageY;
+ }
+ }
+ });
+ on(d.scroller, "touchmove", function () {
+ if (d.activeTouch) { d.activeTouch.moved = true; }
+ });
+ on(d.scroller, "touchend", function (e) {
+ var touch = d.activeTouch;
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
+ !touch.moved && new Date - touch.start < 300) {
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
+ { range = new Range(pos, pos); }
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
+ { range = cm.findWordAt(pos); }
+ else // Triple tap
+ { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
+ cm.setSelection(range.anchor, range.head);
+ cm.focus();
+ e_preventDefault(e);
+ }
+ finishTouch();
+ });
+ on(d.scroller, "touchcancel", finishTouch);
+
+ // Sync scrolling between fake scrollbars and real scrollable
+ // area, ensure viewport is updated when scrolling.
+ on(d.scroller, "scroll", function () {
+ if (d.scroller.clientHeight) {
+ updateScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
+ }
+ });
+
+ // Listen to wheel events in order to try and update the viewport on time.
+ on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
+ on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
+
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+ d.dragFunctions = {
+ enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
+ over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
+ start: function (e) { return onDragStart(cm, e); },
+ drop: operation(cm, onDrop),
+ leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
+ };
+
+ var inp = d.input.getField();
+ on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
+ on(inp, "keydown", operation(cm, onKeyDown));
+ on(inp, "keypress", operation(cm, onKeyPress));
+ on(inp, "focus", function (e) { return onFocus(cm, e); });
+ on(inp, "blur", function (e) { return onBlur(cm, e); });
+ }
+
+ var initHooks = [];
+ CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
+
+ // Indent the given line. The how parameter can be "smart",
+ // "add"/null, "subtract", or "prev". When aggressive is false
+ // (typically set to true for forced single-line indents), empty
+ // lines are not indented, and places where the mode returns Pass
+ // are left alone.
+ function indentLine(cm, n, how, aggressive) {
+ var doc = cm.doc, state;
+ if (how == null) { how = "add"; }
+ if (how == "smart") {
+ // Fall back to "prev" when the mode doesn't have an indentation
+ // method.
+ if (!doc.mode.indent) { how = "prev"; }
+ else { state = getContextBefore(cm, n).state; }
+ }
+
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ if (line.stateAfter) { line.stateAfter = null; }
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (!aggressive && !/\S/.test(line.text)) {
+ indentation = 0;
+ how = "not";
+ } else if (how == "smart") {
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass || indentation > 150) {
+ if (!aggressive) { return }
+ how = "prev";
+ }
+ }
+ if (how == "prev") {
+ if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
+ else { indentation = 0; }
+ } else if (how == "add") {
+ indentation = curSpace + cm.options.indentUnit;
+ } else if (how == "subtract") {
+ indentation = curSpace - cm.options.indentUnit;
+ } else if (typeof how == "number") {
+ indentation = curSpace + how;
+ }
+ indentation = Math.max(0, indentation);
+
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
+ if (pos < indentation) { indentString += spaceStr(indentation - pos); }
+
+ if (indentString != curSpaceString) {
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ line.stateAfter = null;
+ return true
+ } else {
+ // Ensure that, if the cursor was in the whitespace at the start
+ // of the line, it is moved to the end of that space.
+ for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
+ var range = doc.sel.ranges[i$1];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos$1 = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
+ break
+ }
+ }
+ }
+ }
+
+ // This will be set to a {lineWise: bool, text: [string]} object, so
+ // that, when pasting, we know what kind of selections the copied
+ // text was made out of.
+ var lastCopied = null;
+
+ function setLastCopied(newLastCopied) {
+ lastCopied = newLastCopied;
+ }
+
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
+ var doc = cm.doc;
+ cm.display.shift = false;
+ if (!sel) { sel = doc.sel; }
+
+ var recent = +new Date - 200;
+ var paste = origin == "paste" || cm.state.pasteIncoming > recent;
+ var textLines = splitLinesAuto(inserted), multiPaste = null;
+ // When pasting N lines into N selections, insert one line per selection
+ if (paste && sel.ranges.length > 1) {
+ if (lastCopied && lastCopied.text.join("\n") == inserted) {
+ if (sel.ranges.length % lastCopied.text.length == 0) {
+ multiPaste = [];
+ for (var i = 0; i < lastCopied.text.length; i++)
+ { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
+ }
+ } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
+ multiPaste = map(textLines, function (l) { return [l]; });
+ }
+ }
+
+ var updateInput = cm.curOp.updateInput;
+ // Normal behavior is to insert the new text into every selection
+ for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
+ var range = sel.ranges[i$1];
+ var from = range.from(), to = range.to();
+ if (range.empty()) {
+ if (deleted && deleted > 0) // Handle deletion
+ { from = Pos(from.line, from.ch - deleted); }
+ else if (cm.state.overwrite && !paste) // Handle overwrite
+ { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
+ else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
+ { from = to = Pos(from.line, 0); }
+ }
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
+ makeChange(cm.doc, changeEvent);
+ signalLater(cm, "inputRead", cm, changeEvent);
+ }
+ if (inserted && !paste)
+ { triggerElectric(cm, inserted); }
+
+ ensureCursorVisible(cm);
+ if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
+ cm.curOp.typing = true;
+ cm.state.pasteIncoming = cm.state.cutIncoming = -1;
+ }
+
+ function handlePaste(e, cm) {
+ var pasted = e.clipboardData && e.clipboardData.getData("Text");
+ if (pasted) {
+ e.preventDefault();
+ if (!cm.isReadOnly() && !cm.options.disableInput && cm.hasFocus())
+ { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
+ return true
+ }
+ }
+
+ function triggerElectric(cm, inserted) {
+ // When an 'electric' character is inserted, immediately trigger a reindent
+ if (!cm.options.electricChars || !cm.options.smartIndent) { return }
+ var sel = cm.doc.sel;
+
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
+ var range = sel.ranges[i];
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
+ var mode = cm.getModeAt(range.head);
+ var indented = false;
+ if (mode.electricChars) {
+ for (var j = 0; j < mode.electricChars.length; j++)
+ { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
+ indented = indentLine(cm, range.head.line, "smart");
+ break
+ } }
+ } else if (mode.electricInput) {
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
+ { indented = indentLine(cm, range.head.line, "smart"); }
+ }
+ if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
+ }
+ }
+
+ function copyableRanges(cm) {
+ var text = [], ranges = [];
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
+ var line = cm.doc.sel.ranges[i].head.line;
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
+ ranges.push(lineRange);
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
+ }
+ return {text: text, ranges: ranges}
+ }
+
+ function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
+ field.setAttribute("autocorrect", autocorrect ? "" : "off");
+ field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
+ field.setAttribute("spellcheck", !!spellcheck);
+ }
+
+ function hiddenTextarea() {
+ var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // The textarea is kept positioned near the cursor to prevent the
+ // fact that it'll be scrolled into view on input from scrolling
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
+ // very slow. So make the area wide instead.
+ if (webkit) { te.style.width = "1000px"; }
+ else { te.setAttribute("wrap", "off"); }
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
+ if (ios) { te.style.border = "1px solid black"; }
+ disableBrowserMagic(te);
+ return div
+ }
+
+ // The publicly visible API. Note that methodOp(f) means
+ // 'wrap f in an operation, performed on its `this` parameter'.
+
+ // This is not the complete set of editor methods. Most of the
+ // methods defined on the Doc type are also injected into
+ // CodeMirror.prototype, for backwards compatibility and
+ // convenience.
+
+ function addEditorMethods(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
+
+ var helpers = CodeMirror.helpers = {};
+
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){win(this).focus(); this.display.input.focus();},
+
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") { return }
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ { operation(this, optionHandlers[option])(this, value, old); }
+ signal(this, "optionChange", this, option);
+ },
+
+ getOption: function(option) {return this.options[option]},
+ getDoc: function() {return this.doc},
+
+ addKeyMap: function(map, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
+ },
+ removeKeyMap: function(map) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ { if (maps[i] == map || maps[i].name == map) {
+ maps.splice(i, 1);
+ return true
+ } }
+ },
+
+ addOverlay: methodOp(function(spec, options) {
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+ if (mode.startState) { throw new Error("Overlays may not be stateful.") }
+ insertSorted(this.state.overlays,
+ {mode: mode, modeSpec: spec, opaque: options && options.opaque,
+ priority: (options && options.priority) || 0},
+ function (overlay) { return overlay.priority; });
+ this.state.modeGen++;
+ regChange(this);
+ }),
+ removeOverlay: methodOp(function(spec) {
+ var overlays = this.state.overlays;
+ for (var i = 0; i < overlays.length; ++i) {
+ var cur = overlays[i].modeSpec;
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
+ overlays.splice(i, 1);
+ this.state.modeGen++;
+ regChange(this);
+ return
+ }
+ }
+ }),
+
+ indentLine: methodOp(function(n, dir, aggressive) {
+ if (typeof dir != "string" && typeof dir != "number") {
+ if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
+ else { dir = dir ? "add" : "subtract"; }
+ }
+ if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
+ }),
+ indentSelection: methodOp(function(how) {
+ var ranges = this.doc.sel.ranges, end = -1;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (!range.empty()) {
+ var from = range.from(), to = range.to();
+ var start = Math.max(end, from.line);
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ { indentLine(this, j, how); }
+ var newRanges = this.doc.sel.ranges;
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
+ { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
+ } else if (range.head.line > end) {
+ indentLine(this, range.head.line, how, true);
+ end = range.head.line;
+ if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
+ }
+ }
+ }),
+
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos, precise) {
+ return takeToken(this, pos, precise)
+ },
+
+ getLineTokens: function(line, precise) {
+ return takeToken(this, Pos(line), precise, true)
+ },
+
+ getTokenTypeAt: function(pos) {
+ pos = clipPos(this.doc, pos);
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+ var type;
+ if (ch == 0) { type = styles[2]; }
+ else { for (;;) {
+ var mid = (before + after) >> 1;
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
+ else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
+ else { type = styles[mid * 2 + 2]; break }
+ } }
+ var cut = type ? type.indexOf("overlay ") : -1;
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
+ },
+
+ getModeAt: function(pos) {
+ var mode = this.doc.mode;
+ if (!mode.innerMode) { return mode }
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
+ },
+
+ getHelper: function(pos, type) {
+ return this.getHelpers(pos, type)[0]
+ },
+
+ getHelpers: function(pos, type) {
+ var found = [];
+ if (!helpers.hasOwnProperty(type)) { return found }
+ var help = helpers[type], mode = this.getModeAt(pos);
+ if (typeof mode[type] == "string") {
+ if (help[mode[type]]) { found.push(help[mode[type]]); }
+ } else if (mode[type]) {
+ for (var i = 0; i < mode[type].length; i++) {
+ var val = help[mode[type][i]];
+ if (val) { found.push(val); }
+ }
+ } else if (mode.helperType && help[mode.helperType]) {
+ found.push(help[mode.helperType]);
+ } else if (help[mode.name]) {
+ found.push(help[mode.name]);
+ }
+ for (var i$1 = 0; i$1 < help._global.length; i$1++) {
+ var cur = help._global[i$1];
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
+ { found.push(cur.val); }
+ }
+ return found
+ },
+
+ getStateAfter: function(line, precise) {
+ var doc = this.doc;
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+ return getContextBefore(this, line + 1, precise).state
+ },
+
+ cursorCoords: function(start, mode) {
+ var pos, range = this.doc.sel.primary();
+ if (start == null) { pos = range.head; }
+ else if (typeof start == "object") { pos = clipPos(this.doc, start); }
+ else { pos = start ? range.from() : range.to(); }
+ return cursorCoords(this, pos, mode || "page")
+ },
+
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.doc, pos), mode || "page")
+ },
+
+ coordsChar: function(coords, mode) {
+ coords = fromCoordSystem(this, coords, mode || "page");
+ return coordsChar(this, coords.left, coords.top)
+ },
+
+ lineAtHeight: function(height, mode) {
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+ return lineAtHeight(this.doc, height + this.display.viewOffset)
+ },
+ heightAtLine: function(line, mode, includeWidgets) {
+ var end = false, lineObj;
+ if (typeof line == "number") {
+ var last = this.doc.first + this.doc.size - 1;
+ if (line < this.doc.first) { line = this.doc.first; }
+ else if (line > last) { line = last; end = true; }
+ lineObj = getLine(this.doc, line);
+ } else {
+ lineObj = line;
+ }
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0)
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display) },
+ defaultCharWidth: function() { return charWidth(this.display) },
+
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
+
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.doc, pos));
+ var top = pos.bottom, left = pos.left;
+ node.style.position = "absolute";
+ node.setAttribute("cm-ignore-events", "true");
+ this.display.input.setUneditable(node);
+ display.sizer.appendChild(node);
+ if (vert == "over") {
+ top = pos.top;
+ } else if (vert == "above" || vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+ { top = pos.top - node.offsetHeight; }
+ else if (pos.bottom + node.offsetHeight <= vspace)
+ { top = pos.bottom; }
+ if (left + node.offsetWidth > hspace)
+ { left = hspace - node.offsetWidth; }
+ }
+ node.style.top = top + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") { left = 0; }
+ else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
+ },
+
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: onKeyUp,
+ triggerOnMouseDown: methodOp(onMouseDown),
+
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ { return commands[cmd].call(null, this) }
+ },
+
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
+
+ findPosH: function(from, amount, unit, visually) {
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ cur = findPosH(this.doc, cur, dir, unit, visually);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
+
+ moveH: methodOp(function(dir, unit) {
+ var this$1 = this;
+
+ this.extendSelectionsBy(function (range) {
+ if (this$1.display.shift || this$1.doc.extend || range.empty())
+ { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
+ else
+ { return dir < 0 ? range.from() : range.to() }
+ }, sel_move);
+ }),
+
+ deleteH: methodOp(function(dir, unit) {
+ var sel = this.doc.sel, doc = this.doc;
+ if (sel.somethingSelected())
+ { doc.replaceSelection("", null, "+delete"); }
+ else
+ { deleteNearSelection(this, function (range) {
+ var other = findPosH(doc, range.head, dir, unit, false);
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
+ }); }
+ }),
+
+ findPosV: function(from, amount, unit, goalColumn) {
+ var dir = 1, x = goalColumn;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ var coords = cursorCoords(this, cur, "div");
+ if (x == null) { x = coords.left; }
+ else { coords.left = x; }
+ cur = findPosV(this, coords, dir, unit);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
+
+ moveV: methodOp(function(dir, unit) {
+ var this$1 = this;
+
+ var doc = this.doc, goals = [];
+ var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function (range) {
+ if (collapse)
+ { return dir < 0 ? range.from() : range.to() }
+ var headPos = cursorCoords(this$1, range.head, "div");
+ if (range.goalColumn != null) { headPos.left = range.goalColumn; }
+ goals.push(headPos.left);
+ var pos = findPosV(this$1, headPos, dir, unit);
+ if (unit == "page" && range == doc.sel.primary())
+ { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
+ return pos
+ }, sel_move);
+ if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
+ { doc.sel.ranges[i].goalColumn = goals[i]; } }
+ }),
+
+ // Find the word at the given position (as returned by coordsChar).
+ findWordAt: function(pos) {
+ var doc = this.doc, line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ var helper = this.getHelper(pos, "wordChars");
+ if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar, helper)
+ ? function (ch) { return isWordChar(ch, helper); }
+ : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
+ : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
+ while (start > 0 && check(line.charAt(start - 1))) { --start; }
+ while (end < line.length && check(line.charAt(end))) { ++end; }
+ }
+ return new Range(Pos(pos.line, start), Pos(pos.line, end))
+ },
+
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) { return }
+ if (this.state.overwrite = !this.state.overwrite)
+ { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+ else
+ { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return this.display.input.getField() == activeElt(doc(this)) },
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
+
+ scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
+ },
+
+ scrollIntoView: methodOp(function(range, margin) {
+ if (range == null) {
+ range = {from: this.doc.sel.primary().head, to: null};
+ if (margin == null) { margin = this.options.cursorScrollMargin; }
+ } else if (typeof range == "number") {
+ range = {from: Pos(range, 0), to: null};
+ } else if (range.from == null) {
+ range = {from: range, to: null};
+ }
+ if (!range.to) { range.to = range.from; }
+ range.margin = margin || 0;
+
+ if (range.from.line != null) {
+ scrollToRange(this, range);
+ } else {
+ scrollToCoordsRange(this, range.from, range.to, range.margin);
+ }
+ }),
+
+ setSize: methodOp(function(width, height) {
+ var this$1 = this;
+
+ var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
+ if (width != null) { this.display.wrapper.style.width = interpret(width); }
+ if (height != null) { this.display.wrapper.style.height = interpret(height); }
+ if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
+ var lineNo = this.display.viewFrom;
+ this.doc.iter(lineNo, this.display.viewTo, function (line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
+ { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
+ ++lineNo;
+ });
+ this.curOp.forceUpdate = true;
+ signal(this, "refresh", this);
+ }),
+
+ operation: function(f){return runInOp(this, f)},
+ startOperation: function(){return startOperation(this)},
+ endOperation: function(){return endOperation(this)},
+
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ this.curOp.forceUpdate = true;
+ clearCaches(this);
+ scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
+ updateGutterSpace(this.display);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
+ { estimateLineHeights(this); }
+ signal(this, "refresh", this);
+ }),
+
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ // Cancel the current text selection if any (#5821)
+ if (this.state.selectingText) { this.state.selectingText(); }
+ attachDoc(this, doc);
+ clearCaches(this);
+ this.display.input.reset();
+ scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
+ this.curOp.forceScroll = true;
+ signalLater(this, "swapDoc", this, old);
+ return old
+ }),
+
+ phrase: function(phraseText) {
+ var phrases = this.options.phrases;
+ return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
+ },
+
+ getInputField: function(){return this.display.input.getField()},
+ getWrapperElement: function(){return this.display.wrapper},
+ getScrollerElement: function(){return this.display.scroller},
+ getGutterElement: function(){return this.display.gutters}
+ };
+ eventMixin(CodeMirror);
+
+ CodeMirror.registerHelper = function(type, name, value) {
+ if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
+ helpers[type][name] = value;
+ };
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
+ CodeMirror.registerHelper(type, name, value);
+ helpers[type]._global.push({pred: predicate, val: value});
+ };
+ }
+
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
+ // right), unit can be "codepoint", "char", "column" (like char, but
+ // doesn't cross line boundaries), "word" (across next word), or
+ // "group" (to the start of next group of word or
+ // non-word-non-whitespace chars). The visually param controls
+ // whether, in right-to-left text, direction 1 means to move towards
+ // the next index in the string, or towards the character to the right
+ // of the current position. The resulting position will have a
+ // hitSide=true property if it reached the end of the document.
+ function findPosH(doc, pos, dir, unit, visually) {
+ var oldPos = pos;
+ var origDir = dir;
+ var lineObj = getLine(doc, pos.line);
+ var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
+ function findNextLine() {
+ var l = pos.line + lineDir;
+ if (l < doc.first || l >= doc.first + doc.size) { return false }
+ pos = new Pos(l, pos.ch, pos.sticky);
+ return lineObj = getLine(doc, l)
+ }
+ function moveOnce(boundToLine) {
+ var next;
+ if (unit == "codepoint") {
+ var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
+ if (isNaN(ch)) {
+ next = null;
+ } else {
+ var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
+ next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
+ }
+ } else if (visually) {
+ next = moveVisually(doc.cm, lineObj, pos, dir);
+ } else {
+ next = moveLogically(lineObj, pos, dir);
+ }
+ if (next == null) {
+ if (!boundToLine && findNextLine())
+ { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
+ else
+ { return false }
+ } else {
+ pos = next;
+ }
+ return true
+ }
+
+ if (unit == "char" || unit == "codepoint") {
+ moveOnce();
+ } else if (unit == "column") {
+ moveOnce(true);
+ } else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) { break }
+ var cur = lineObj.text.charAt(pos.ch) || "\n";
+ var type = isWordChar(cur, helper) ? "w"
+ : group && cur == "\n" ? "n"
+ : !group || /\s/.test(cur) ? null
+ : "p";
+ if (group && !first && !type) { type = "s"; }
+ if (sawType && sawType != type) {
+ if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
+ break
+ }
+
+ if (type) { sawType = type; }
+ if (dir > 0 && !moveOnce(!first)) { break }
+ }
+ }
+ var result = skipAtomic(doc, pos, oldPos, origDir, true);
+ if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
+ return result
+ }
+
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
+ // "page" or "line". The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosV(cm, pos, dir, unit) {
+ var doc = cm.doc, x = pos.left, y;
+ if (unit == "page") {
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, win(cm).innerHeight || doc(cm).documentElement.clientHeight);
+ var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
+ y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
+
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ var target;
+ for (;;) {
+ target = coordsChar(cm, x, y);
+ if (!target.outside) { break }
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
+ y += dir * 5;
+ }
+ return target
+ }
+
+ // CONTENTEDITABLE INPUT STYLE
+
+ var ContentEditableInput = function(cm) {
+ this.cm = cm;
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
+ this.polling = new Delayed();
+ this.composing = null;
+ this.gracePeriod = false;
+ this.readDOMTimeout = null;
+ };
+
+ ContentEditableInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = input.cm;
+ var div = input.div = display.lineDiv;
+ div.contentEditable = true;
+ disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
+
+ function belongsToInput(e) {
+ for (var t = e.target; t; t = t.parentNode) {
+ if (t == div) { return true }
+ if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
+ }
+ return false
+ }
+
+ on(div, "paste", function (e) {
+ if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+ // IE doesn't fire input events, so we schedule a read for the pasted content in this way
+ if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
+ });
+
+ on(div, "compositionstart", function (e) {
+ this$1.composing = {data: e.data, done: false};
+ });
+ on(div, "compositionupdate", function (e) {
+ if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
+ });
+ on(div, "compositionend", function (e) {
+ if (this$1.composing) {
+ if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
+ this$1.composing.done = true;
+ }
+ });
+
+ on(div, "touchstart", function () { return input.forceCompositionEnd(); });
+
+ on(div, "input", function () {
+ if (!this$1.composing) { this$1.readFromDOMSoon(); }
+ });
+
+ function onCopyCut(e) {
+ if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.operation(function () {
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
+ cm.replaceSelection("", null, "cut");
+ });
+ }
+ }
+ if (e.clipboardData) {
+ e.clipboardData.clearData();
+ var content = lastCopied.text.join("\n");
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
+ e.clipboardData.setData("Text", content);
+ if (e.clipboardData.getData("Text") == content) {
+ e.preventDefault();
+ return
+ }
+ }
+ // Old-fashioned briefly-focus-a-textarea hack
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
+ te.value = lastCopied.text.join("\n");
+ var hadFocus = activeElt(div.ownerDocument);
+ selectInput(te);
+ setTimeout(function () {
+ cm.display.lineSpace.removeChild(kludge);
+ hadFocus.focus();
+ if (hadFocus == div) { input.showPrimarySelection(); }
+ }, 50);
+ }
+ on(div, "copy", onCopyCut);
+ on(div, "cut", onCopyCut);
+ };
+
+ ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
+ // Label for screenreaders, accessibility
+ if(label) {
+ this.div.setAttribute('aria-label', label);
+ } else {
+ this.div.removeAttribute('aria-label');
+ }
+ };
+
+ ContentEditableInput.prototype.prepareSelection = function () {
+ var result = prepareSelection(this.cm, false);
+ result.focus = activeElt(this.div.ownerDocument) == this.div;
+ return result
+ };
+
+ ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
+ if (!info || !this.cm.display.view.length) { return }
+ if (info.focus || takeFocus) { this.showPrimarySelection(); }
+ this.showMultipleSelections(info);
+ };
+
+ ContentEditableInput.prototype.getSelection = function () {
+ return this.cm.display.wrapper.ownerDocument.getSelection()
+ };
+
+ ContentEditableInput.prototype.showPrimarySelection = function () {
+ var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
+ var from = prim.from(), to = prim.to();
+
+ if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
+ cmp(minPos(curAnchor, curFocus), from) == 0 &&
+ cmp(maxPos(curAnchor, curFocus), to) == 0)
+ { return }
+
+ var view = cm.display.view;
+ var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
+ {node: view[0].measure.map[2], offset: 0};
+ var end = to.line < cm.display.viewTo && posToDOM(cm, to);
+ if (!end) {
+ var measure = view[view.length - 1].measure;
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
+ }
+
+ if (!start || !end) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var old = sel.rangeCount && sel.getRangeAt(0), rng;
+ try { rng = range(start.node, start.offset, end.offset, end.node); }
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
+ if (rng) {
+ if (!gecko && cm.state.focused) {
+ sel.collapse(start.node, start.offset);
+ if (!rng.collapsed) {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ } else {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ if (old && sel.anchorNode == null) { sel.addRange(old); }
+ else if (gecko) { this.startGracePeriod(); }
+ }
+ this.rememberSelection();
+ };
+
+ ContentEditableInput.prototype.startGracePeriod = function () {
+ var this$1 = this;
+
+ clearTimeout(this.gracePeriod);
+ this.gracePeriod = setTimeout(function () {
+ this$1.gracePeriod = false;
+ if (this$1.selectionChanged())
+ { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
+ }, 20);
+ };
+
+ ContentEditableInput.prototype.showMultipleSelections = function (info) {
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
+ };
+
+ ContentEditableInput.prototype.rememberSelection = function () {
+ var sel = this.getSelection();
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
+ };
+
+ ContentEditableInput.prototype.selectionInEditor = function () {
+ var sel = this.getSelection();
+ if (!sel.rangeCount) { return false }
+ var node = sel.getRangeAt(0).commonAncestorContainer;
+ return contains(this.div, node)
+ };
+
+ ContentEditableInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor") {
+ if (!this.selectionInEditor() || activeElt(this.div.ownerDocument) != this.div)
+ { this.showSelection(this.prepareSelection(), true); }
+ this.div.focus();
+ }
+ };
+ ContentEditableInput.prototype.blur = function () { this.div.blur(); };
+ ContentEditableInput.prototype.getField = function () { return this.div };
+
+ ContentEditableInput.prototype.supportsTouch = function () { return true };
+
+ ContentEditableInput.prototype.receivedFocus = function () {
+ var this$1 = this;
+
+ var input = this;
+ if (this.selectionInEditor())
+ { setTimeout(function () { return this$1.pollSelection(); }, 20); }
+ else
+ { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
+
+ function poll() {
+ if (input.cm.state.focused) {
+ input.pollSelection();
+ input.polling.set(input.cm.options.pollInterval, poll);
+ }
+ }
+ this.polling.set(this.cm.options.pollInterval, poll);
+ };
+
+ ContentEditableInput.prototype.selectionChanged = function () {
+ var sel = this.getSelection();
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
+ };
+
+ ContentEditableInput.prototype.pollSelection = function () {
+ if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
+ var sel = this.getSelection(), cm = this.cm;
+ // On Android Chrome (version 56, at least), backspacing into an
+ // uneditable block element will put the cursor in that element,
+ // and then, because it's not editable, hide the virtual keyboard.
+ // Because Android doesn't allow us to actually detect backspace
+ // presses in a sane way, this code checks for when that happens
+ // and simulates a backspace press in this case.
+ if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
+ this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
+ this.blur();
+ this.focus();
+ return
+ }
+ if (this.composing) { return }
+ this.rememberSelection();
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (anchor && head) { runInOp(cm, function () {
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
+ if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
+ }); }
+ };
+
+ ContentEditableInput.prototype.pollContent = function () {
+ if (this.readDOMTimeout != null) {
+ clearTimeout(this.readDOMTimeout);
+ this.readDOMTimeout = null;
+ }
+
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
+ var from = sel.from(), to = sel.to();
+ if (from.ch == 0 && from.line > cm.firstLine())
+ { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
+ if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
+ { to = Pos(to.line + 1, 0); }
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
+
+ var fromIndex, fromLine, fromNode;
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
+ fromLine = lineNo(display.view[0].line);
+ fromNode = display.view[0].node;
+ } else {
+ fromLine = lineNo(display.view[fromIndex].line);
+ fromNode = display.view[fromIndex - 1].node.nextSibling;
+ }
+ var toIndex = findViewIndex(cm, to.line);
+ var toLine, toNode;
+ if (toIndex == display.view.length - 1) {
+ toLine = display.viewTo - 1;
+ toNode = display.lineDiv.lastChild;
+ } else {
+ toLine = lineNo(display.view[toIndex + 1].line) - 1;
+ toNode = display.view[toIndex + 1].node.previousSibling;
+ }
+
+ if (!fromNode) { return false }
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
+ while (newText.length > 1 && oldText.length > 1) {
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
+ else { break }
+ }
+
+ var cutFront = 0, cutEnd = 0;
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
+ { ++cutFront; }
+ var newBot = lst(newText), oldBot = lst(oldText);
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
+ while (cutEnd < maxCutEnd &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
+ { ++cutEnd; }
+ // Try to move start of change to start of selection if ambiguous
+ if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
+ while (cutFront && cutFront > from.ch &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
+ cutFront--;
+ cutEnd++;
+ }
+ }
+
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
+ newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
+
+ var chFrom = Pos(fromLine, cutFront);
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
+ return true
+ }
+ };
+
+ ContentEditableInput.prototype.ensurePolled = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.reset = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.forceCompositionEnd = function () {
+ if (!this.composing) { return }
+ clearTimeout(this.readDOMTimeout);
+ this.composing = null;
+ this.updateFromDOM();
+ this.div.blur();
+ this.div.focus();
+ };
+ ContentEditableInput.prototype.readFromDOMSoon = function () {
+ var this$1 = this;
+
+ if (this.readDOMTimeout != null) { return }
+ this.readDOMTimeout = setTimeout(function () {
+ this$1.readDOMTimeout = null;
+ if (this$1.composing) {
+ if (this$1.composing.done) { this$1.composing = null; }
+ else { return }
+ }
+ this$1.updateFromDOM();
+ }, 80);
+ };
+
+ ContentEditableInput.prototype.updateFromDOM = function () {
+ var this$1 = this;
+
+ if (this.cm.isReadOnly() || !this.pollContent())
+ { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
+ };
+
+ ContentEditableInput.prototype.setUneditable = function (node) {
+ node.contentEditable = "false";
+ };
+
+ ContentEditableInput.prototype.onKeyPress = function (e) {
+ if (e.charCode == 0 || this.composing) { return }
+ e.preventDefault();
+ if (!this.cm.isReadOnly())
+ { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
+ };
+
+ ContentEditableInput.prototype.readOnlyChanged = function (val) {
+ this.div.contentEditable = String(val != "nocursor");
+ };
+
+ ContentEditableInput.prototype.onContextMenu = function () {};
+ ContentEditableInput.prototype.resetPosition = function () {};
+
+ ContentEditableInput.prototype.needsContentAttribute = true;
+
+ function posToDOM(cm, pos) {
+ var view = findViewForLine(cm, pos.line);
+ if (!view || view.hidden) { return null }
+ var line = getLine(cm.doc, pos.line);
+ var info = mapFromLineView(view, line, pos.line);
+
+ var order = getOrder(line, cm.doc.direction), side = "left";
+ if (order) {
+ var partPos = getBidiPartAt(order, pos.ch);
+ side = partPos % 2 ? "right" : "left";
+ }
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
+ result.offset = result.collapse == "right" ? result.end : result.start;
+ return result
+ }
+
+ function isInGutter(node) {
+ for (var scan = node; scan; scan = scan.parentNode)
+ { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
+ return false
+ }
+
+ function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
+
+ function domTextBetween(cm, from, to, fromLine, toLine) {
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
+ function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
+ function close() {
+ if (closing) {
+ text += lineSep;
+ if (extraLinebreak) { text += lineSep; }
+ closing = extraLinebreak = false;
+ }
+ }
+ function addText(str) {
+ if (str) {
+ close();
+ text += str;
+ }
+ }
+ function walk(node) {
+ if (node.nodeType == 1) {
+ var cmText = node.getAttribute("cm-text");
+ if (cmText) {
+ addText(cmText);
+ return
+ }
+ var markerID = node.getAttribute("cm-marker"), range;
+ if (markerID) {
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
+ if (found.length && (range = found[0].find(0)))
+ { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
+ return
+ }
+ if (node.getAttribute("contenteditable") == "false") { return }
+ var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
+ if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
+
+ if (isBlock) { close(); }
+ for (var i = 0; i < node.childNodes.length; i++)
+ { walk(node.childNodes[i]); }
+
+ if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
+ if (isBlock) { closing = true; }
+ } else if (node.nodeType == 3) {
+ addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
+ }
+ }
+ for (;;) {
+ walk(from);
+ if (from == to) { break }
+ from = from.nextSibling;
+ extraLinebreak = false;
+ }
+ return text
+ }
+
+ function domToPos(cm, node, offset) {
+ var lineNode;
+ if (node == cm.display.lineDiv) {
+ lineNode = cm.display.lineDiv.childNodes[offset];
+ if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
+ node = null; offset = 0;
+ } else {
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
+ if (!lineNode || lineNode == cm.display.lineDiv) { return null }
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
+ }
+ }
+ for (var i = 0; i < cm.display.view.length; i++) {
+ var lineView = cm.display.view[i];
+ if (lineView.node == lineNode)
+ { return locateNodeInLineView(lineView, node, offset) }
+ }
+ }
+
+ function locateNodeInLineView(lineView, node, offset) {
+ var wrapper = lineView.text.firstChild, bad = false;
+ if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
+ if (node == wrapper) {
+ bad = true;
+ node = wrapper.childNodes[offset];
+ offset = 0;
+ if (!node) {
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
+ return badPos(Pos(lineNo(line), line.text.length), bad)
+ }
+ }
+
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
+ textNode = node.firstChild;
+ if (offset) { offset = textNode.nodeValue.length; }
+ }
+ while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
+ var measure = lineView.measure, maps = measure.maps;
+
+ function find(textNode, topNode, offset) {
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
+ var map = i < 0 ? measure.map : maps[i];
+ for (var j = 0; j < map.length; j += 3) {
+ var curNode = map[j + 2];
+ if (curNode == textNode || curNode == topNode) {
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
+ var ch = map[j] + offset;
+ if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
+ return Pos(line, ch)
+ }
+ }
+ }
+ }
+ var found = find(textNode, topNode, offset);
+ if (found) { return badPos(found, bad) }
+
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
+ found = find(after, after.firstChild, 0);
+ if (found)
+ { return badPos(Pos(found.line, found.ch - dist), bad) }
+ else
+ { dist += after.textContent.length; }
+ }
+ for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
+ found = find(before, before.firstChild, -1);
+ if (found)
+ { return badPos(Pos(found.line, found.ch + dist$1), bad) }
+ else
+ { dist$1 += before.textContent.length; }
+ }
+ }
+
+ // TEXTAREA INPUT STYLE
+
+ var TextareaInput = function(cm) {
+ this.cm = cm;
+ // See input.poll and input.reset
+ this.prevInput = "";
+
+ // Flag that indicates whether we expect input to appear real soon
+ // now (after some event like 'keypress' or 'input') and are
+ // polling intensively.
+ this.pollingFast = false;
+ // Self-resetting timeout for the poller
+ this.polling = new Delayed();
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
+ this.hasSelection = false;
+ this.composing = null;
+ };
+
+ TextareaInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = this.cm;
+ this.createField(display);
+ var te = this.textarea;
+
+ display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
+
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
+ if (ios) { te.style.width = "0px"; }
+
+ on(te, "input", function () {
+ if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
+ input.poll();
+ });
+
+ on(te, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+
+ cm.state.pasteIncoming = +new Date;
+ input.fastPoll();
+ });
+
+ function prepareCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
+ } else {
+ input.prevInput = "";
+ te.value = ranges.text.join("\n");
+ selectInput(te);
+ }
+ }
+ if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
+ }
+ on(te, "cut", prepareCopyCut);
+ on(te, "copy", prepareCopyCut);
+
+ on(display.scroller, "paste", function (e) {
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
+ if (!te.dispatchEvent) {
+ cm.state.pasteIncoming = +new Date;
+ input.focus();
+ return
+ }
+
+ // Pass the `paste` event to the textarea so it's handled by its event listener.
+ var event = new Event("paste");
+ event.clipboardData = e.clipboardData;
+ te.dispatchEvent(event);
+ });
+
+ // Prevent normal selection in the editor (we handle our own)
+ on(display.lineSpace, "selectstart", function (e) {
+ if (!eventInWidget(display, e)) { e_preventDefault(e); }
+ });
+
+ on(te, "compositionstart", function () {
+ var start = cm.getCursor("from");
+ if (input.composing) { input.composing.range.clear(); }
+ input.composing = {
+ start: start,
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
+ };
+ });
+ on(te, "compositionend", function () {
+ if (input.composing) {
+ input.poll();
+ input.composing.range.clear();
+ input.composing = null;
+ }
+ });
+ };
+
+ TextareaInput.prototype.createField = function (_display) {
+ // Wraps and hides input textarea
+ this.wrapper = hiddenTextarea();
+ // The semihidden textarea that is focused when the editor is
+ // focused, and receives input.
+ this.textarea = this.wrapper.firstChild;
+ };
+
+ TextareaInput.prototype.screenReaderLabelChanged = function (label) {
+ // Label for screenreaders, accessibility
+ if(label) {
+ this.textarea.setAttribute('aria-label', label);
+ } else {
+ this.textarea.removeAttribute('aria-label');
+ }
+ };
+
+ TextareaInput.prototype.prepareSelection = function () {
+ // Redraw the selection and/or cursor
+ var cm = this.cm, display = cm.display, doc = cm.doc;
+ var result = prepareSelection(cm);
+
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
+ if (cm.options.moveInputWithCursor) {
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top));
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left));
+ }
+
+ return result
+ };
+
+ TextareaInput.prototype.showSelection = function (drawn) {
+ var cm = this.cm, display = cm.display;
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
+ if (drawn.teTop != null) {
+ this.wrapper.style.top = drawn.teTop + "px";
+ this.wrapper.style.left = drawn.teLeft + "px";
+ }
+ };
+
+ // Reset the input to correspond to the selection (or to be empty,
+ // when not typing and nothing is selected)
+ TextareaInput.prototype.reset = function (typing) {
+ if (this.contextMenuPending || this.composing) { return }
+ var cm = this.cm;
+ if (cm.somethingSelected()) {
+ this.prevInput = "";
+ var content = cm.getSelection();
+ this.textarea.value = content;
+ if (cm.state.focused) { selectInput(this.textarea); }
+ if (ie && ie_version >= 9) { this.hasSelection = content; }
+ } else if (!typing) {
+ this.prevInput = this.textarea.value = "";
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ }
+ };
+
+ TextareaInput.prototype.getField = function () { return this.textarea };
+
+ TextareaInput.prototype.supportsTouch = function () { return false };
+
+ TextareaInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt(this.textarea.ownerDocument) != this.textarea)) {
+ try { this.textarea.focus(); }
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
+ }
+ };
+
+ TextareaInput.prototype.blur = function () { this.textarea.blur(); };
+
+ TextareaInput.prototype.resetPosition = function () {
+ this.wrapper.style.top = this.wrapper.style.left = 0;
+ };
+
+ TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
+
+ // Poll for input changes, using the normal rate of polling. This
+ // runs as long as the editor is focused.
+ TextareaInput.prototype.slowPoll = function () {
+ var this$1 = this;
+
+ if (this.pollingFast) { return }
+ this.polling.set(this.cm.options.pollInterval, function () {
+ this$1.poll();
+ if (this$1.cm.state.focused) { this$1.slowPoll(); }
+ });
+ };
+
+ // When an event has just come in that is likely to add or change
+ // something in the input textarea, we poll faster, to ensure that
+ // the change appears on the screen quickly.
+ TextareaInput.prototype.fastPoll = function () {
+ var missed = false, input = this;
+ input.pollingFast = true;
+ function p() {
+ var changed = input.poll();
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
+ else {input.pollingFast = false; input.slowPoll();}
+ }
+ input.polling.set(20, p);
+ };
+
+ // Read input from the textarea, and update the document to match.
+ // When something is selected, it is present in the textarea, and
+ // selected (unless it is huge, in which case a placeholder is
+ // used). When nothing is selected, the cursor sits after previously
+ // seen text (can be empty), which is stored in prevInput (we must
+ // not reset the textarea when typing, because that breaks IME).
+ TextareaInput.prototype.poll = function () {
+ var this$1 = this;
+
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
+ // Since this is called a *lot*, try to bail out as cheaply as
+ // possible when it is clear that nothing happened. hasSelection
+ // will be the case when there is a lot of text in the textarea,
+ // in which case reading its value would be expensive.
+ if (this.contextMenuPending || !cm.state.focused ||
+ (hasSelection(input) && !prevInput && !this.composing) ||
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
+ { return false }
+
+ var text = input.value;
+ // If nothing changed, bail.
+ if (text == prevInput && !cm.somethingSelected()) { return false }
+ // Work around nonsensical selection resetting in IE9/10, and
+ // inexplicable appearance of private area unicode characters on
+ // some key combos in Mac (#2689).
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
+ mac && /[\uf700-\uf7ff]/.test(text)) {
+ cm.display.input.reset();
+ return false
+ }
+
+ if (cm.doc.sel == cm.display.selForContextMenu) {
+ var first = text.charCodeAt(0);
+ if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
+ }
+ // Find the part of the input that is actually new
+ var same = 0, l = Math.min(prevInput.length, text.length);
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
+
+ runInOp(cm, function () {
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
+ null, this$1.composing ? "*compose" : null);
+
+ // Don't leave long text in the textarea, since it makes further polling slow
+ if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
+ else { this$1.prevInput = text; }
+
+ if (this$1.composing) {
+ this$1.composing.range.clear();
+ this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
+ {className: "CodeMirror-composing"});
+ }
+ });
+ return true
+ };
+
+ TextareaInput.prototype.ensurePolled = function () {
+ if (this.pollingFast && this.poll()) { this.pollingFast = false; }
+ };
+
+ TextareaInput.prototype.onKeyPress = function () {
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ this.fastPoll();
+ };
+
+ TextareaInput.prototype.onContextMenu = function (e) {
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
+ if (input.contextMenuPending) { input.contextMenuPending(); }
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+ if (!pos || presto) { return } // Opera is difficult.
+
+ // Reset the current text selection only if the click is done outside of the selection
+ // and 'resetSelectionOnContextMenu' option is true.
+ var reset = cm.options.resetSelectionOnContextMenu;
+ if (reset && cm.doc.sel.contains(pos) == -1)
+ { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
+
+ var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
+ var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
+ input.wrapper.style.cssText = "position: static";
+ te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ var oldScrollY;
+ if (webkit) { oldScrollY = te.ownerDocument.defaultView.scrollY; } // Work around Chrome issue (#2712)
+ display.input.focus();
+ if (webkit) { te.ownerDocument.defaultView.scrollTo(null, oldScrollY); }
+ display.input.reset();
+ // Adds "Select all" to context menu in FF
+ if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
+ input.contextMenuPending = rehide;
+ display.selForContextMenu = cm.doc.sel;
+ clearTimeout(display.detectingSelectAll);
+
+ // Select-all will be greyed out if there's nothing to select, so
+ // this adds a zero-width space so that we can later check whether
+ // it got selected.
+ function prepareSelectAllHack() {
+ if (te.selectionStart != null) {
+ var selected = cm.somethingSelected();
+ var extval = "\u200b" + (selected ? te.value : "");
+ te.value = "\u21da"; // Used to catch context-menu undo
+ te.value = extval;
+ input.prevInput = selected ? "" : "\u200b";
+ te.selectionStart = 1; te.selectionEnd = extval.length;
+ // Re-set this, in case some other handler touched the
+ // selection in the meantime.
+ display.selForContextMenu = cm.doc.sel;
+ }
+ }
+ function rehide() {
+ if (input.contextMenuPending != rehide) { return }
+ input.contextMenuPending = false;
+ input.wrapper.style.cssText = oldWrapperCSS;
+ te.style.cssText = oldCSS;
+ if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
+
+ // Try to detect the user choosing select-all
+ if (te.selectionStart != null) {
+ if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
+ var i = 0, poll = function () {
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
+ te.selectionEnd > 0 && input.prevInput == "\u200b") {
+ operation(cm, selectAll)(cm);
+ } else if (i++ < 10) {
+ display.detectingSelectAll = setTimeout(poll, 500);
+ } else {
+ display.selForContextMenu = null;
+ display.input.reset();
+ }
+ };
+ display.detectingSelectAll = setTimeout(poll, 200);
+ }
+ }
+
+ if (ie && ie_version >= 9) { prepareSelectAllHack(); }
+ if (captureRightClick) {
+ e_stop(e);
+ var mouseup = function () {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ };
+ on(window, "mouseup", mouseup);
+ } else {
+ setTimeout(rehide, 50);
+ }
+ };
+
+ TextareaInput.prototype.readOnlyChanged = function (val) {
+ if (!val) { this.reset(); }
+ this.textarea.disabled = val == "nocursor";
+ this.textarea.readOnly = !!val;
+ };
+
+ TextareaInput.prototype.setUneditable = function () {};
+
+ TextareaInput.prototype.needsContentAttribute = false;
+
+ function fromTextArea(textarea, options) {
+ options = options ? copyObj(options) : {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabIndex)
+ { options.tabindex = textarea.tabIndex; }
+ if (!options.placeholder && textarea.placeholder)
+ { options.placeholder = textarea.placeholder; }
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = activeElt(textarea.ownerDocument);
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+ }
+
+ function save() {textarea.value = cm.getValue();}
+
+ var realSubmit;
+ if (textarea.form) {
+ on(textarea.form, "submit", save);
+ // Deplorable hack to make the submit method do the right thing.
+ if (!options.leaveSubmitMethodAlone) {
+ var form = textarea.form;
+ realSubmit = form.submit;
+ try {
+ var wrappedSubmit = form.submit = function () {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
+ }
+ }
+
+ options.finishInit = function (cm) {
+ cm.save = save;
+ cm.getTextArea = function () { return textarea; };
+ cm.toTextArea = function () {
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
+ { textarea.form.submit = realSubmit; }
+ }
+ };
+ };
+
+ textarea.style.display = "none";
+ var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
+ options);
+ return cm
+ }
+
+ function addLegacyProps(CodeMirror) {
+ CodeMirror.off = off;
+ CodeMirror.on = on;
+ CodeMirror.wheelEventPixels = wheelEventPixels;
+ CodeMirror.Doc = Doc;
+ CodeMirror.splitLines = splitLinesAuto;
+ CodeMirror.countColumn = countColumn;
+ CodeMirror.findColumn = findColumn;
+ CodeMirror.isWordChar = isWordCharBasic;
+ CodeMirror.Pass = Pass;
+ CodeMirror.signal = signal;
+ CodeMirror.Line = Line;
+ CodeMirror.changeEnd = changeEnd;
+ CodeMirror.scrollbarModel = scrollbarModel;
+ CodeMirror.Pos = Pos;
+ CodeMirror.cmpPos = cmp;
+ CodeMirror.modes = modes;
+ CodeMirror.mimeModes = mimeModes;
+ CodeMirror.resolveMode = resolveMode;
+ CodeMirror.getMode = getMode;
+ CodeMirror.modeExtensions = modeExtensions;
+ CodeMirror.extendMode = extendMode;
+ CodeMirror.copyState = copyState;
+ CodeMirror.startState = startState;
+ CodeMirror.innerMode = innerMode;
+ CodeMirror.commands = commands;
+ CodeMirror.keyMap = keyMap;
+ CodeMirror.keyName = keyName;
+ CodeMirror.isModifierKey = isModifierKey;
+ CodeMirror.lookupKey = lookupKey;
+ CodeMirror.normalizeKeyMap = normalizeKeyMap;
+ CodeMirror.StringStream = StringStream;
+ CodeMirror.SharedTextMarker = SharedTextMarker;
+ CodeMirror.TextMarker = TextMarker;
+ CodeMirror.LineWidget = LineWidget;
+ CodeMirror.e_preventDefault = e_preventDefault;
+ CodeMirror.e_stopPropagation = e_stopPropagation;
+ CodeMirror.e_stop = e_stop;
+ CodeMirror.addClass = addClass;
+ CodeMirror.contains = contains;
+ CodeMirror.rmClass = rmClass;
+ CodeMirror.keyNames = keyNames;
+ }
+
+ // EDITOR CONSTRUCTOR
+
+ defineOptions(CodeMirror);
+
+ addEditorMethods(CodeMirror);
+
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
+ for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+ { CodeMirror.prototype[prop] = (function(method) {
+ return function() {return method.apply(this.doc, arguments)}
+ })(Doc.prototype[prop]); } }
+
+ eventMixin(Doc);
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
+
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ CodeMirror.defineMode = function(name/*, mode, …*/) {
+ if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
+ defineMode.apply(this, arguments);
+ };
+
+ CodeMirror.defineMIME = defineMIME;
+
+ // Minimal default mode.
+ CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
+ CodeMirror.defineMIME("text/plain", "null");
+
+ // EXTENSIONS
+
+ CodeMirror.defineExtension = function (name, func) {
+ CodeMirror.prototype[name] = func;
+ };
+ CodeMirror.defineDocExtension = function (name, func) {
+ Doc.prototype[name] = func;
+ };
+
+ CodeMirror.fromTextArea = fromTextArea;
+
+ addLegacyProps(CodeMirror);
+
+ CodeMirror.version = "5.65.7";
+
+ return CodeMirror;
+
+})));
diff --git a/visualpython/lib/codemirror/mode/python/index.html b/visualpython/lib/codemirror/mode/python/index.html
new file mode 100644
index 00000000..edf958f8
--- /dev/null
+++ b/visualpython/lib/codemirror/mode/python/index.html
@@ -0,0 +1,207 @@
+
+
+CodeMirror: Python mode
+
+
+
+
+
+
+
+
+
+
+
+Python mode
+
+
+
+
+Cython mode
+
+
+
+
+ Configuration Options for Python mode:
+
+ version - 2/3 - The version of Python to recognize. Default is 3.
+ singleLineStringErrors - true/false - If you have a single-line string that is not terminated at the end of the line, this will show subsequent lines as errors if true, otherwise it will consider the newline as the end of the string. Default is false.
+ hangingIndent - int - If you want to write long arguments to a function starting on a new line, how much that line should be indented. Defaults to one normal indentation unit.
+
+ Advanced Configuration Options:
+ Useful for superset of python syntax like Enthought enaml, IPython magics and questionmark help
+
+ singleOperators - RegEx - Regular Expression for single operator matching, default : ^[\\+\\-\\*/%&|\\^~<>!] including @ on Python 3
+ singleDelimiters - RegEx - Regular Expression for single delimiter matching, default : ^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]
+ doubleOperators - RegEx - Regular Expression for double operators matching, default : ^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))
+ doubleDelimiters - RegEx - Regular Expression for double delimiters matching, default : ^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))
+ tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default : ^((//=)|(>>=)|(<<=)|(\\*\\*=))
+ identifiers - RegEx - Regular Expression for identifier, default : ^[_A-Za-z][_A-Za-z0-9]* on Python 2 and ^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]* on Python 3.
+ extra_keywords - list of string - List of extra words ton consider as keywords
+ extra_builtins - list of string - List of extra words ton consider as builtins
+
+
+
+ MIME types defined: text/x-python and text/x-cython.
+
diff --git a/visualpython/lib/codemirror/mode/python/python.js b/visualpython/lib/codemirror/mode/python/python.js
new file mode 100644
index 00000000..1cec2de8
--- /dev/null
+++ b/visualpython/lib/codemirror/mode/python/python.js
@@ -0,0 +1,402 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/5/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ function wordRegexp(words) {
+ return new RegExp("^((" + words.join(")|(") + "))\\b");
+ }
+
+ var wordOperators = wordRegexp(["and", "or", "not", "is"]);
+ var commonKeywords = ["as", "assert", "break", "class", "continue",
+ "def", "del", "elif", "else", "except", "finally",
+ "for", "from", "global", "if", "import",
+ "lambda", "pass", "raise", "return",
+ "try", "while", "with", "yield", "in"];
+ var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
+ "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
+ "enumerate", "eval", "filter", "float", "format", "frozenset",
+ "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
+ "input", "int", "isinstance", "issubclass", "iter", "len",
+ "list", "locals", "map", "max", "memoryview", "min", "next",
+ "object", "oct", "open", "ord", "pow", "property", "range",
+ "repr", "reversed", "round", "set", "setattr", "slice",
+ "sorted", "staticmethod", "str", "sum", "super", "tuple",
+ "type", "vars", "zip", "__import__", "NotImplemented",
+ "Ellipsis", "__debug__"];
+ CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
+
+ function top(state) {
+ return state.scopes[state.scopes.length - 1];
+ }
+
+ CodeMirror.defineMode("python", function(conf, parserConf) {
+ var ERRORCLASS = "error";
+
+ var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/;
+ // (Backwards-compatibility with old, cumbersome config system)
+ var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters,
+ parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/]
+ for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1)
+
+ var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
+
+ var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
+ if (parserConf.extra_keywords != undefined)
+ myKeywords = myKeywords.concat(parserConf.extra_keywords);
+
+ if (parserConf.extra_builtins != undefined)
+ myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
+
+ var py3 = !(parserConf.version && Number(parserConf.version) < 3)
+ if (py3) {
+ // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
+ var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;
+ myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]);
+ myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]);
+ var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i");
+ } else {
+ var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/;
+ myKeywords = myKeywords.concat(["exec", "print"]);
+ myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
+ "file", "intern", "long", "raw_input", "reduce", "reload",
+ "unichr", "unicode", "xrange", "False", "True", "None"]);
+ var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
+ }
+ var keywords = wordRegexp(myKeywords);
+ var builtins = wordRegexp(myBuiltins);
+
+ // tokenizers
+ function tokenBase(stream, state) {
+ var sol = stream.sol() && state.lastToken != "\\"
+ if (sol) state.indent = stream.indentation()
+ // Handle scope changes
+ if (sol && top(state).type == "py") {
+ var scopeOffset = top(state).offset;
+ if (stream.eatSpace()) {
+ var lineOffset = stream.indentation();
+ if (lineOffset > scopeOffset)
+ pushPyScope(state);
+ else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#")
+ state.errorToken = true;
+ return null;
+ } else {
+ var style = tokenBaseInner(stream, state);
+ if (scopeOffset > 0 && dedent(stream, state))
+ style += " " + ERRORCLASS;
+ return style;
+ }
+ }
+ return tokenBaseInner(stream, state);
+ }
+
+ function tokenBaseInner(stream, state, inFormat) {
+ if (stream.eatSpace()) return null;
+
+ // Handle Comments
+ if (!inFormat && stream.match(/^#.*/)) return "comment";
+
+ // Handle Number Literals
+ if (stream.match(/^[0-9\.]/, false)) {
+ var floatLiteral = false;
+ // Floats
+ if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
+ if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; }
+ if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+ if (floatLiteral) {
+ // Float literals may be "imaginary"
+ stream.eat(/J/i);
+ return "number";
+ }
+ // Integers
+ var intLiteral = false;
+ // Hex
+ if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true;
+ // Binary
+ if (stream.match(/^0b[01_]+/i)) intLiteral = true;
+ // Octal
+ if (stream.match(/^0o[0-7_]+/i)) intLiteral = true;
+ // Decimal
+ if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) {
+ // Decimal literals may be "imaginary"
+ stream.eat(/J/i);
+ // TODO - Can you have imaginary longs?
+ intLiteral = true;
+ }
+ // Zero by itself with no other piece of number.
+ if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
+ if (intLiteral) {
+ // Integer literals may be "long"
+ stream.eat(/L/i);
+ return "number";
+ }
+ }
+
+ // Handle Strings
+ if (stream.match(stringPrefixes)) {
+ var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1;
+ if (!isFmtString) {
+ state.tokenize = tokenStringFactory(stream.current(), state.tokenize);
+ return state.tokenize(stream, state);
+ } else {
+ state.tokenize = formatStringFactory(stream.current(), state.tokenize);
+ return state.tokenize(stream, state);
+ }
+ }
+
+ for (var i = 0; i < operators.length; i++)
+ if (stream.match(operators[i])) return "operator"
+
+ if (stream.match(delimiters)) return "punctuation";
+
+ if (state.lastToken == "." && stream.match(identifiers))
+ return "property";
+
+ if (stream.match(keywords) || stream.match(wordOperators))
+ return "keyword";
+
+ if (stream.match(builtins))
+ return "builtin";
+
+ if (stream.match(/^(self|cls)\b/))
+ return "variable-2";
+
+ if (stream.match(identifiers)) {
+ if (state.lastToken == "def" || state.lastToken == "class")
+ return "def";
+ return "variable";
+ }
+
+ // Handle non-detected items
+ stream.next();
+ return inFormat ? null :ERRORCLASS;
+ }
+
+ function formatStringFactory(delimiter, tokenOuter) {
+ while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
+ delimiter = delimiter.substr(1);
+
+ var singleline = delimiter.length == 1;
+ var OUTCLASS = "string";
+
+ function tokenNestedExpr(depth) {
+ return function(stream, state) {
+ var inner = tokenBaseInner(stream, state, true)
+ if (inner == "punctuation") {
+ if (stream.current() == "{") {
+ state.tokenize = tokenNestedExpr(depth + 1)
+ } else if (stream.current() == "}") {
+ if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1)
+ else state.tokenize = tokenString
+ }
+ }
+ return inner
+ }
+ }
+
+ function tokenString(stream, state) {
+ while (!stream.eol()) {
+ stream.eatWhile(/[^'"\{\}\\]/);
+ if (stream.eat("\\")) {
+ stream.next();
+ if (singleline && stream.eol())
+ return OUTCLASS;
+ } else if (stream.match(delimiter)) {
+ state.tokenize = tokenOuter;
+ return OUTCLASS;
+ } else if (stream.match('{{')) {
+ // ignore {{ in f-str
+ return OUTCLASS;
+ } else if (stream.match('{', false)) {
+ // switch to nested mode
+ state.tokenize = tokenNestedExpr(0)
+ if (stream.current()) return OUTCLASS;
+ else return state.tokenize(stream, state)
+ } else if (stream.match('}}')) {
+ return OUTCLASS;
+ } else if (stream.match('}')) {
+ // single } in f-string is an error
+ return ERRORCLASS;
+ } else {
+ stream.eat(/['"]/);
+ }
+ }
+ if (singleline) {
+ if (parserConf.singleLineStringErrors)
+ return ERRORCLASS;
+ else
+ state.tokenize = tokenOuter;
+ }
+ return OUTCLASS;
+ }
+ tokenString.isString = true;
+ return tokenString;
+ }
+
+ function tokenStringFactory(delimiter, tokenOuter) {
+ while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
+ delimiter = delimiter.substr(1);
+
+ var singleline = delimiter.length == 1;
+ var OUTCLASS = "string";
+
+ function tokenString(stream, state) {
+ while (!stream.eol()) {
+ stream.eatWhile(/[^'"\\]/);
+ if (stream.eat("\\")) {
+ stream.next();
+ if (singleline && stream.eol())
+ return OUTCLASS;
+ } else if (stream.match(delimiter)) {
+ state.tokenize = tokenOuter;
+ return OUTCLASS;
+ } else {
+ stream.eat(/['"]/);
+ }
+ }
+ if (singleline) {
+ if (parserConf.singleLineStringErrors)
+ return ERRORCLASS;
+ else
+ state.tokenize = tokenOuter;
+ }
+ return OUTCLASS;
+ }
+ tokenString.isString = true;
+ return tokenString;
+ }
+
+ function pushPyScope(state) {
+ while (top(state).type != "py") state.scopes.pop()
+ state.scopes.push({offset: top(state).offset + conf.indentUnit,
+ type: "py",
+ align: null})
+ }
+
+ function pushBracketScope(stream, state, type) {
+ var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1
+ state.scopes.push({offset: state.indent + hangingIndent,
+ type: type,
+ align: align})
+ }
+
+ function dedent(stream, state) {
+ var indented = stream.indentation();
+ while (state.scopes.length > 1 && top(state).offset > indented) {
+ if (top(state).type != "py") return true;
+ state.scopes.pop();
+ }
+ return top(state).offset != indented;
+ }
+
+ function tokenLexer(stream, state) {
+ if (stream.sol()) {
+ state.beginningOfLine = true;
+ state.dedent = false;
+ }
+
+ var style = state.tokenize(stream, state);
+ var current = stream.current();
+
+ // Handle decorators
+ if (state.beginningOfLine && current == "@")
+ return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS;
+
+ if (/\S/.test(current)) state.beginningOfLine = false;
+
+ if ((style == "variable" || style == "builtin")
+ && state.lastToken == "meta")
+ style = "meta";
+
+ // Handle scope changes.
+ if (current == "pass" || current == "return")
+ state.dedent = true;
+
+ if (current == "lambda") state.lambda = true;
+ if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false))
+ pushPyScope(state);
+
+ if (current.length == 1 && !/string|comment/.test(style)) {
+ var delimiter_index = "[({".indexOf(current);
+ if (delimiter_index != -1)
+ pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
+
+ delimiter_index = "])}".indexOf(current);
+ if (delimiter_index != -1) {
+ if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent
+ else return ERRORCLASS;
+ }
+ }
+ if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1)
+ state.scopes.pop();
+
+ return style;
+ }
+
+ var external = {
+ startState: function(basecolumn) {
+ return {
+ tokenize: tokenBase,
+ scopes: [{offset: basecolumn || 0, type: "py", align: null}],
+ indent: basecolumn || 0,
+ lastToken: null,
+ lambda: false,
+ dedent: 0
+ };
+ },
+
+ token: function(stream, state) {
+ var addErr = state.errorToken;
+ if (addErr) state.errorToken = false;
+ var style = tokenLexer(stream, state);
+
+ if (style && style != "comment")
+ state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style;
+ if (style == "punctuation") style = null;
+
+ if (stream.eol() && state.lambda)
+ state.lambda = false;
+ return addErr ? style + " " + ERRORCLASS : style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase)
+ return state.tokenize.isString ? CodeMirror.Pass : 0;
+
+ var scope = top(state)
+ var closing = scope.type == textAfter.charAt(0) ||
+ scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter)
+ if (scope.align != null)
+ return scope.align - (closing ? 1 : 0)
+ else
+ return scope.offset - (closing ? hangingIndent : 0)
+ },
+
+ electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/,
+ closeBrackets: {triples: "'\""},
+ lineComment: "#",
+ fold: "indent"
+ };
+ return external;
+ });
+
+ CodeMirror.defineMIME("text/x-python", "python");
+
+ var words = function(str) { return str.split(" "); };
+
+ CodeMirror.defineMIME("text/x-cython", {
+ name: "python",
+ extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+
+ "extern gil include nogil property public "+
+ "readonly struct union DEF IF ELIF ELSE")
+ });
+
+});
diff --git a/visualpython/lib/codemirror/mode/python/test.js b/visualpython/lib/codemirror/mode/python/test.js
new file mode 100644
index 00000000..ca5da153
--- /dev/null
+++ b/visualpython/lib/codemirror/mode/python/test.js
@@ -0,0 +1,74 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/5/LICENSE
+
+(function() {
+ var mode = CodeMirror.getMode({indentUnit: 4},
+ {name: "python",
+ version: 3,
+ singleLineStringErrors: false});
+ function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+ // Error, because "foobarhello" is neither a known type or property, but
+ // property was expected (after "and"), and it should be in parentheses.
+ MT("decoratorStartOfLine",
+ "[meta @dec]",
+ "[keyword def] [def function]():",
+ " [keyword pass]");
+
+ MT("decoratorIndented",
+ "[keyword class] [def Foo]:",
+ " [meta @dec]",
+ " [keyword def] [def function]():",
+ " [keyword pass]");
+
+ MT("matmulWithSpace:", "[variable a] [operator @] [variable b]");
+ MT("matmulWithoutSpace:", "[variable a][operator @][variable b]");
+ MT("matmulSpaceBefore:", "[variable a] [operator @][variable b]");
+ var before_equal_sign = ["+", "-", "*", "/", "=", "!", ">", "<"];
+ for (var i = 0; i < before_equal_sign.length; ++i) {
+ var c = before_equal_sign[i]
+ MT("before_equal_sign_" + c, "[variable a] [operator " + c + "=] [variable b]");
+ }
+
+ MT("fValidStringPrefix", "[string f'this is a]{[variable formatted]}[string string']");
+ MT("fValidExpressionInFString", "[string f'expression ]{[number 100][operator *][number 5]}[string string']");
+ MT("fInvalidFString", "[error f'this is wrong}]");
+ MT("fNestedFString", "[string f'expression ]{[number 100] [operator +] [string f'inner]{[number 5]}[string ']}[string string']");
+ MT("uValidStringPrefix", "[string u'this is an unicode string']");
+
+ MT("nestedString", "[string f']{[variable b][[ [string \"c\"] ]]}[string f'] [comment # oops]")
+
+ MT("bracesInFString", "[string f']{[variable x] [operator +] {}}[string !']")
+
+ MT("nestedFString", "[string f']{[variable b][[ [string f\"c\"] ]]}[string f'] [comment # oops]")
+
+ MT("dontIndentTypeDecl",
+ "[variable i]: [builtin int] [operator =] [number 32]",
+ "[builtin print]([variable i])")
+
+ MT("dedentElse",
+ "[keyword if] [variable x]:",
+ " [variable foo]()",
+ "[keyword elif] [variable y]:",
+ " [variable bar]()",
+ "[keyword else]:",
+ " [variable baz]()")
+
+ MT("dedentElsePass",
+ "[keyword if] [variable x]:",
+ " [keyword pass]",
+ "[keyword elif] [variable y]:",
+ " [keyword pass]",
+ "[keyword else]:",
+ " [keyword pass]")
+
+ MT("dedentElseInFunction",
+ "[keyword def] [def foo]():",
+ " [keyword if] [variable x]:",
+ " [variable foo]()",
+ " [keyword elif] [variable y]:",
+ " [variable bar]()",
+ " [keyword pass]",
+ " [keyword else]:",
+ " [variable baz]()")
+})();
diff --git a/visualpython/lib/jquery/images/ui-bg_glass_65_ffffff_1x400.png b/visualpython/lib/jquery/images/ui-bg_glass_65_ffffff_1x400.png
new file mode 100644
index 00000000..3d53f770
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-bg_glass_65_ffffff_1x400.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_444444_256x240.png b/visualpython/lib/jquery/images/ui-icons_444444_256x240.png
new file mode 100644
index 00000000..c2daae16
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_444444_256x240.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_555555_256x240.png b/visualpython/lib/jquery/images/ui-icons_555555_256x240.png
new file mode 100644
index 00000000..47849283
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_555555_256x240.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_777620_256x240.png b/visualpython/lib/jquery/images/ui-icons_777620_256x240.png
new file mode 100644
index 00000000..d2f58d25
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_777620_256x240.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_777777_256x240.png b/visualpython/lib/jquery/images/ui-icons_777777_256x240.png
new file mode 100644
index 00000000..1d532588
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_777777_256x240.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_cc0000_256x240.png b/visualpython/lib/jquery/images/ui-icons_cc0000_256x240.png
new file mode 100644
index 00000000..2825f200
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_cc0000_256x240.png differ
diff --git a/visualpython/lib/jquery/images/ui-icons_ffffff_256x240.png b/visualpython/lib/jquery/images/ui-icons_ffffff_256x240.png
new file mode 100644
index 00000000..136a4f97
Binary files /dev/null and b/visualpython/lib/jquery/images/ui-icons_ffffff_256x240.png differ
diff --git a/visualpython/lib/jquery/jquery-3.6.0.min.js b/visualpython/lib/jquery/jquery-3.6.0.min.js
new file mode 100644
index 00000000..c4c6022f
--- /dev/null
+++ b/visualpython/lib/jquery/jquery-3.6.0.min.js
@@ -0,0 +1,2 @@
+/*! jQuery v3.6.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */
+!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.0",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML=" ",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML=" ";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML=" ",y.option=!!ce.lastChild;var ge={thead:[1,""],col:[2,""],tr:[2,""],td:[3,""],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var _t,zt=[],Ut=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=zt.pop()||S.expando+"_"+wt.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Ut.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ut.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Ut,"$1"+r):!1!==e.jsonp&&(e.url+=(Tt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,zt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((_t=E.implementation.createHTMLDocument("").body).innerHTML="",2===_t.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Fe(y.pixelPosition,function(e,t){if(t)return t=We(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0 .ui-controlgroup-item{float:left;margin-left:0;margin-right:0}.ui-controlgroup > .ui-controlgroup-item:focus,.ui-controlgroup > .ui-controlgroup-item.ui-visual-focus{z-index:9999}.ui-controlgroup-vertical > .ui-controlgroup-item{display:block;float:none;width:100%;margin-top:0;margin-bottom:0;text-align:left}.ui-controlgroup-vertical .ui-controlgroup-item{box-sizing:border-box}.ui-controlgroup .ui-controlgroup-label{padding:.4em 1em}.ui-controlgroup .ui-controlgroup-label span{font-size:80%}.ui-controlgroup-horizontal .ui-controlgroup-label + .ui-controlgroup-item{border-left:none}.ui-controlgroup-vertical .ui-controlgroup-label + .ui-controlgroup-item{border-top:none}.ui-controlgroup-horizontal .ui-controlgroup-label.ui-widget-content{border-right:none}.ui-controlgroup-vertical .ui-controlgroup-label.ui-widget-content{border-bottom:none}.ui-controlgroup-vertical .ui-spinner-input{width:75%;width:calc( 100% - 2.4em )}.ui-controlgroup-vertical .ui-spinner .ui-spinner-up{border-top-style:solid}.ui-checkboxradio-label .ui-icon-background{box-shadow:inset 1px 1px 1px #ccc;border-radius:.12em;border:none}.ui-checkboxradio-radio-label .ui-icon-background{width:16px;height:16px;border-radius:1em;overflow:visible;border:none}.ui-checkboxradio-radio-label.ui-checkboxradio-checked .ui-icon,.ui-checkboxradio-radio-label.ui-checkboxradio-checked:hover .ui-icon{background-image:none;width:8px;height:8px;border-width:4px;border-style:solid}.ui-checkboxradio-disabled{pointer-events:none}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:45%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker .ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat;left:.5em;top:.3em}.ui-dialog{position:absolute;top:0;left:0;padding:.2em;outline:0}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 0;white-space:nowrap;width:90%;overflow:hidden;text-overflow:ellipsis}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:20px;margin:-10px 0 0 0;padding:1px;height:20px}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin-top:.5em;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-n{height:2px;top:0}.ui-dialog .ui-resizable-e{width:2px;right:0}.ui-dialog .ui-resizable-s{height:2px;bottom:0}.ui-dialog .ui-resizable-w{width:2px;left:0}.ui-dialog .ui-resizable-se,.ui-dialog .ui-resizable-sw,.ui-dialog .ui-resizable-ne,.ui-dialog .ui-resizable-nw{width:7px;height:7px}.ui-dialog .ui-resizable-se{right:0;bottom:0}.ui-dialog .ui-resizable-sw{left:0;bottom:0}.ui-dialog .ui-resizable-ne{right:0;top:0}.ui-dialog .ui-resizable-nw{left:0;top:0}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-draggable-handle{-ms-touch-action:none;touch-action:none}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block;-ms-touch-action:none;touch-action:none}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-progressbar .ui-progressbar-overlay{background:url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");height:100%;filter:alpha(opacity=25);opacity:0.25}.ui-progressbar-indeterminate .ui-progressbar-value{background-image:none}.ui-selectable{-ms-touch-action:none;touch-action:none}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-selectmenu-menu{padding:0;margin:0;position:absolute;top:0;left:0;display:none}.ui-selectmenu-menu .ui-menu{overflow:auto;overflow-x:hidden;padding-bottom:1px}.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup{font-size:1em;font-weight:bold;line-height:1.5;padding:2px 0.4em;margin:0.5em 0 0 0;height:auto;border:0}.ui-selectmenu-open{display:block}.ui-selectmenu-text{display:block;margin-right:20px;overflow:hidden;text-overflow:ellipsis}.ui-selectmenu-button.ui-button{text-align:left;white-space:nowrap;width:14em}.ui-selectmenu-icon.ui-icon{float:right;margin-top:0}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default;-ms-touch-action:none;touch-action:none}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider.ui-state-disabled .ui-slider-handle,.ui-slider.ui-state-disabled .ui-slider-range{filter:inherit}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-sortable-handle{-ms-touch-action:none;touch-action:none}.ui-spinner{position:relative;display:inline-block;overflow:hidden;padding:0;vertical-align:middle}.ui-spinner-input{border:none;background:none;color:inherit;padding:.222em 0;margin:.2em 0;vertical-align:middle;margin-left:.4em;margin-right:2em}.ui-spinner-button{width:1.6em;height:50%;font-size:.5em;padding:0;margin:0;text-align:center;position:absolute;cursor:default;display:block;overflow:hidden;right:0}.ui-spinner a.ui-spinner-button{border-top-style:none;border-bottom-style:none;border-right-style:none}.ui-spinner-up{top:0}.ui-spinner-down{bottom:0}.ui-tabs{position:relative;padding:.2em}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:0;margin:1px .2em 0 0;border-bottom-width:0;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav .ui-tabs-anchor{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-active{margin-bottom:-1px;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor{cursor:text}.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tooltip{padding:8px;position:absolute;z-index:9999;max-width:300px}body .ui-tooltip{border-width:2px}.ui-widget{font-family:Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Verdana,Arial,sans-serif;font-size:1em}.ui-widget.ui-widget-content{border:1px solid #d3d3d3}.ui-widget-content{border:1px solid #aaa;background:#fff;color:#222}.ui-widget-content a{color:#222}.ui-widget-header{border:1px solid #aaa;background:#ccc url("images/ui-bg_highlight-soft_75_cccccc_1x100.png") 50% 50% repeat-x;color:#222;font-weight:bold}.ui-widget-header a{color:#222}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default,.ui-button,html .ui-button.ui-state-disabled:hover,html .ui-button.ui-state-disabled:active{border:1px solid #d3d3d3;background:#e6e6e6 url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x;font-weight:normal;color:#555}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited,a.ui-button,a:link.ui-button,a:visited.ui-button,.ui-button{color:#555;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus,.ui-button:hover,.ui-button:focus{border:1px solid #999;background:#dadada url("images/ui-bg_glass_75_dadada_1x400.png") 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-hover a,.ui-state-hover a:hover,.ui-state-hover a:link,.ui-state-hover a:visited,.ui-state-focus a,.ui-state-focus a:hover,.ui-state-focus a:link,.ui-state-focus a:visited,a.ui-button:hover,a.ui-button:focus{color:#212121;text-decoration:none}.ui-visual-focus{box-shadow:0 0 3px 1px rgb(94,158,214)}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active,a.ui-button:active,.ui-button:active,.ui-button.ui-state-active:hover{border:1px solid #aaa;background:#fff url("images/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-icon-background,.ui-state-active .ui-icon-background{border:#aaa;background-color:#212121}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#212121;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fcefa1;background:#fbf9ee url("images/ui-bg_glass_55_fbf9ee_1x400.png") 50% 50% repeat-x;color:#363636}.ui-state-checked{border:1px solid #fcefa1;background:#fbf9ee}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#fef1ec url("images/ui-bg_glass_95_fef1ec_1x400.png") 50% 50% repeat-x;color:#cd0a0a}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#cd0a0a}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#cd0a0a}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-state-disabled .ui-icon{filter:Alpha(Opacity=35)}.ui-icon{width:16px;height:16px}.ui-icon,.ui-widget-content .ui-icon{background-image:url("images/ui-icons_222222_256x240.png")}.ui-widget-header .ui-icon{background-image:url("images/ui-icons_222222_256x240.png")}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon,.ui-button:hover .ui-icon,.ui-button:focus .ui-icon{background-image:url("images/ui-icons_454545_256x240.png")}.ui-state-active .ui-icon,.ui-button:active .ui-icon{background-image:url("images/ui-icons_454545_256x240.png")}.ui-state-highlight .ui-icon,.ui-button .ui-state-highlight.ui-icon{background-image:url("images/ui-icons_2e83ff_256x240.png")}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url("images/ui-icons_cd0a0a_256x240.png")}.ui-button .ui-icon{background-image:url("images/ui-icons_888888_256x240.png")}.ui-icon-blank{background-position:16px 16px}.ui-icon-caret-1-n{background-position:0 0}.ui-icon-caret-1-ne{background-position:-16px 0}.ui-icon-caret-1-e{background-position:-32px 0}.ui-icon-caret-1-se{background-position:-48px 0}.ui-icon-caret-1-s{background-position:-65px 0}.ui-icon-caret-1-sw{background-position:-80px 0}.ui-icon-caret-1-w{background-position:-96px 0}.ui-icon-caret-1-nw{background-position:-112px 0}.ui-icon-caret-2-n-s{background-position:-128px 0}.ui-icon-caret-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-65px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-65px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:1px -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:4px}.ui-widget-overlay{background:#aaa;opacity:.3;filter:Alpha(Opacity=30)}.ui-widget-shadow{-webkit-box-shadow:-8px -8px 8px #aaa;box-shadow:-8px -8px 8px #aaa}
\ No newline at end of file
diff --git a/visualpython/lib/jquery/jquery-ui.min.js b/visualpython/lib/jquery/jquery-ui.min.js
new file mode 100644
index 00000000..939e88da
--- /dev/null
+++ b/visualpython/lib/jquery/jquery-ui.min.js
@@ -0,0 +1,6 @@
+/*! jQuery UI - v1.12.1 - 2021-09-12
+* http://jqueryui.com
+* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/draggable.js, widgets/droppable.js, widgets/resizable.js, widgets/selectable.js, widgets/sortable.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/selectmenu.js, widgets/slider.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
+* Copyright jQuery Foundation and other contributors; Licensed MIT */
+
+!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(k){k.ui=k.ui||{};k.ui.version="1.12.1";var n,i=0,r=Array.prototype.slice;k.cleanData=(n=k.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)try{(e=k._data(i,"events"))&&e.remove&&k(i).triggerHandler("remove")}catch(t){}n(t)}),k.widget=function(t,i,e){var s,n,o,a={},r=t.split(".")[0],h=r+"-"+(t=t.split(".")[1]);return e||(e=i,i=k.Widget),k.isArray(e)&&(e=k.extend.apply(null,[{}].concat(e))),k.expr[":"][h.toLowerCase()]=function(t){return!!k.data(t,h)},k[r]=k[r]||{},s=k[r][t],n=k[r][t]=function(t,e){if(!this._createWidget)return new n(t,e);arguments.length&&this._createWidget(t,e)},k.extend(n,s,{version:e.version,_proto:k.extend({},e),_childConstructors:[]}),(o=new i).options=k.widget.extend({},o.options),k.each(e,function(e,s){function n(){return i.prototype[e].apply(this,arguments)}function o(t){return i.prototype[e].apply(this,t)}k.isFunction(s)?a[e]=function(){var t,e=this._super,i=this._superApply;return this._super=n,this._superApply=o,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}:a[e]=s}),n.prototype=k.widget.extend(o,{widgetEventPrefix:s&&o.widgetEventPrefix||t},a,{constructor:n,namespace:r,widgetName:t,widgetFullName:h}),s?(k.each(s._childConstructors,function(t,e){var i=e.prototype;k.widget(i.namespace+"."+i.widgetName,n,e._proto)}),delete s._childConstructors):i._childConstructors.push(n),k.widget.bridge(t,n),n},k.widget.extend=function(t){for(var e,i,s=r.call(arguments,1),n=0,o=s.length;n",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=k(e||this.defaultElement||this)[0],this.element=k(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=k(),this.hoverable=k(),this.focusable=k(),this.classesElementLookup={},e!==this&&(k.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=k(e.style?e.ownerDocument:e.document||e),this.window=k(this.document[0].defaultView||this.document[0].parentWindow)),this.options=k.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:k.noop,_create:k.noop,_init:k.noop,destroy:function(){var i=this;this._destroy(),k.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:k.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return k.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=k.widget.extend({},this.options[t]),n=0;n
"),i=e.children()[0];return k("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.widthx(C(s),C(n))?o.important="horizontal":o.important="vertical",u.using.call(this,t,o)}),a.offset(k.extend(l,{using:t}))})},k.ui.position={fit:{left:function(t,e){var i=e.within,s=i.isWindow?i.scrollLeft:i.offset.left,n=i.width,o=t.left-e.collisionPosition.marginLeft,a=s-o,r=o+e.collisionWidth-n-s;e.collisionWidth>n?0n?0 ?@[\]^`{|}~])/g,function(t){return t.replace(e,"\\$1")}),k.fn.labels=function(){var t,e,i;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+k.ui.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e))},k.fn.scrollParent=function(t){var e=this.css("position"),i="absolute"===e,s=t?/(auto|scroll|hidden)/:/(auto|scroll)/,t=this.parents().filter(function(){var t=k(this);return(!i||"static"!==t.css("position"))&&s.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==e&&t.length?t:k(this[0].ownerDocument||document)},k.extend(k.expr[":"],{tabbable:function(t){var e=k.attr(t,"tabindex"),i=null!=e;return(!i||0<=e)&&k.ui.focusable(t,i)}}),k.fn.extend({uniqueId:(u=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++u)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&k(this).removeAttr("id")})}}),k.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var e,u,d=!1;k(document).on("mouseup",function(){d=!1});k.widget("ui.mouse",{version:"1.12.1",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(t){if(!0===k.data(t.target,e.widgetName+".preventClickEvent"))return k.removeData(t.target,e.widgetName+".preventClickEvent"),t.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!d){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var e=this,i=1===t.which,s=!("string"!=typeof this.options.cancel||!t.target.nodeName)&&k(t.target).closest(this.options.cancel).length;return i&&!s&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(t),!this._mouseStarted)?(t.preventDefault(),!0):(!0===k.data(t.target,this.widgetName+".preventClickEvent")&&k.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return e._mouseMove(t)},this._mouseUpDelegate=function(t){return e._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),d=!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(k.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button)return this._mouseUp(t);if(!t.which)if(t.originalEvent.altKey||t.originalEvent.ctrlKey||t.originalEvent.metaKey||t.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(this._mouseDownEvent,t),this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&k.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,d=!1,t.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),k.ui.plugin={add:function(t,e,i){var s,n=k.ui[t].prototype;for(s in i)n.plugins[s]=n.plugins[s]||[],n.plugins[s].push([e,i[s]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;n").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var e=k.ui.safeActiveElement(this.document[0]);k(t.target).closest(e).length||k.ui.safeBlur(e)},_mouseStart:function(t){var e=this.options;return this.helper=this._createHelper(t),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),k.ui.ddmanager&&(k.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=0i[2]&&(o=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(a=i[3]+this.offset.click.top)),s.grid&&(t=s.grid[1]?this.originalPageY+Math.round((a-this.originalPageY)/s.grid[1])*s.grid[1]:this.originalPageY,a=!i||t-this.offset.click.top>=i[1]||t-this.offset.click.top>i[3]?t:t-this.offset.click.top>=i[1]?t-s.grid[1]:t+s.grid[1],t=s.grid[0]?this.originalPageX+Math.round((o-this.originalPageX)/s.grid[0])*s.grid[0]:this.originalPageX,o=!i||t-this.offset.click.left>=i[0]||t-this.offset.click.left>i[2]?t:t-this.offset.click.left>=i[0]?t-s.grid[0]:t+s.grid[0]),"y"===s.axis&&(o=this.originalPageX),"x"===s.axis&&(a=this.originalPageY)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:n?0:this.offset.scroll.top),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:n?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(t,e,i){return i=i||this._uiHash(),k.ui.plugin.call(this,t,[e,i,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),i.offset=this.positionAbs),k.Widget.prototype._trigger.call(this,t,e,i)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),k.ui.plugin.add("draggable","connectToSortable",{start:function(e,t,i){var s=k.extend({},t,{item:i.element});i.sortables=[],k(i.options.connectToSortable).each(function(){var t=k(this).sortable("instance");t&&!t.options.disabled&&(i.sortables.push(t),t.refreshPositions(),t._trigger("activate",e,s))})},stop:function(e,t,i){var s=k.extend({},t,{item:i.element});i.cancelHelperRemoval=!1,k.each(i.sortables,function(){var t=this;t.isOver?(t.isOver=0,i.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,s))})},drag:function(i,s,n){k.each(n.sortables,function(){var t=!1,e=this;e.positionAbs=n.positionAbs,e.helperProportions=n.helperProportions,e.offset.click=n.offset.click,e._intersectsWith(e.containerCache)&&(t=!0,k.each(n.sortables,function(){return this.positionAbs=n.positionAbs,this.helperProportions=n.helperProportions,this.offset.click=n.offset.click,t=this!==e&&this._intersectsWith(this.containerCache)&&k.contains(e.element[0],this.element[0])?!1:t})),t?(e.isOver||(e.isOver=1,n._parent=s.helper.parent(),e.currentItem=s.helper.appendTo(e.element).data("ui-sortable-item",!0),e.options._helper=e.options.helper,e.options.helper=function(){return s.helper[0]},i.target=e.currentItem[0],e._mouseCapture(i,!0),e._mouseStart(i,!0,!0),e.offset.click.top=n.offset.click.top,e.offset.click.left=n.offset.click.left,e.offset.parent.left-=n.offset.parent.left-e.offset.parent.left,e.offset.parent.top-=n.offset.parent.top-e.offset.parent.top,n._trigger("toSortable",i),n.dropped=e.element,k.each(n.sortables,function(){this.refreshPositions()}),n.currentItem=n.element,e.fromOutside=n),e.currentItem&&(e._mouseDrag(i),s.position=e.position)):e.isOver&&(e.isOver=0,e.cancelHelperRemoval=!0,e.options._revert=e.options.revert,e.options.revert=!1,e._trigger("out",i,e._uiHash(e)),e._mouseStop(i,!0),e.options.revert=e.options._revert,e.options.helper=e.options._helper,e.placeholder&&e.placeholder.remove(),s.helper.appendTo(n._parent),n._refreshOffsets(i),s.position=n._generatePosition(i,!0),n._trigger("fromSortable",i),n.dropped=!1,k.each(n.sortables,function(){this.refreshPositions()}))})}}),k.ui.plugin.add("draggable","cursor",{start:function(t,e,i){var s=k("body"),i=i.options;s.css("cursor")&&(i._cursor=s.css("cursor")),s.css("cursor",i.cursor)},stop:function(t,e,i){i=i.options;i._cursor&&k("body").css("cursor",i._cursor)}}),k.ui.plugin.add("draggable","opacity",{start:function(t,e,i){e=k(e.helper),i=i.options;e.css("opacity")&&(i._opacity=e.css("opacity")),e.css("opacity",i.opacity)},stop:function(t,e,i){i=i.options;i._opacity&&k(e.helper).css("opacity",i._opacity)}}),k.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,e,i){var s=i.options,n=!1,o=i.scrollParentNotHidden[0],a=i.document[0];o!==a&&"HTML"!==o.tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+o.offsetHeight-t.pageY").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,t={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(t),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(t),this._proportionallyResize()),this._setupHandles(),e.autoHide&&k(this.element).on("mouseenter",function(){e.disabled||(i._removeClass("ui-resizable-autohide"),i._handles.show())}).on("mouseleave",function(){e.disabled||i.resizing||(i._addClass("ui-resizable-autohide"),i._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();function t(t){k(t).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()}var e;return this.elementIsWrapper&&(t(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_setOption:function(t,e){this._super(t,e),"handles"===t&&(this._removeHandles(),this._setupHandles())},_setupHandles:function(){var t,e,i,s,n,o=this.options,a=this;if(this.handles=o.handles||(k(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=k(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),i=this.handles.split(","),this.handles={},e=0;e"),this._addClass(n,"ui-resizable-handle "+s),n.css({zIndex:o.zIndex}),this.handles[t]=".ui-resizable-"+t,this.element.append(n);this._renderAxis=function(t){var e,i,s;for(e in t=t||this.element,this.handles)this.handles[e].constructor===String?this.handles[e]=this.element.children(this.handles[e]).first().show():(this.handles[e].jquery||this.handles[e].nodeType)&&(this.handles[e]=k(this.handles[e]),this._on(this.handles[e],{mousedown:a._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(i=k(this.handles[e],this.element),s=/sw|ne|nw|se|n|s/.test(e)?i.outerHeight():i.outerWidth(),i=["padding",/ne|nw|n/.test(e)?"Top":/se|sw|s/.test(e)?"Bottom":/^e$/.test(e)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize()),this._handles=this._handles.add(this.handles[e])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){a.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),a.axis=n&&n[1]?n[1]:"se")}),o.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(t){var e,i,s=!1;for(e in this.handles)(i=k(this.handles[e])[0])!==t.target&&!k.contains(i,t.target)||(s=!0);return!this.options.disabled&&s},_mouseStart:function(t){var e,i,s=this.options,n=this.element;return this.resizing=!0,this._renderProxy(),e=this._num(this.helper.css("left")),i=this._num(this.helper.css("top")),s.containment&&(e+=k(s.containment).scrollLeft()||0,i+=k(s.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:e,top:i},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:n.width(),height:n.height()},this.originalSize=this._helper?{width:n.outerWidth(),height:n.outerHeight()}:{width:n.width(),height:n.height()},this.sizeDiff={width:n.outerWidth()-n.width(),height:n.outerHeight()-n.height()},this.originalPosition={left:e,top:i},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof s.aspectRatio?s.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=k(".ui-resizable-"+this.axis).css("cursor"),k("body").css("cursor","auto"===s?this.axis+"-resize":s),this._addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var e=this.originalMousePosition,i=this.axis,s=t.pageX-e.left||0,e=t.pageY-e.top||0,i=this._change[i];return this._updatePrevProperties(),i&&(e=i.apply(this,[t,s,e]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(e=this._updateRatio(e,t)),e=this._respectSize(e,t),this._updateCache(e),this._propagate("resize",t),e=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),k.isEmptyObject(e)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges())),!1},_mouseStop:function(t){this.resizing=!1;var e,i,s,n=this.options,o=this;return this._helper&&(s=(e=(i=this._proportionallyResizeElements).length&&/textarea/i.test(i[0].nodeName))&&this._hasScroll(i[0],"left")?0:o.sizeDiff.height,i=e?0:o.sizeDiff.width,e={width:o.helper.width()-i,height:o.helper.height()-s},i=parseFloat(o.element.css("left"))+(o.position.left-o.originalPosition.left)||null,s=parseFloat(o.element.css("top"))+(o.position.top-o.originalPosition.top)||null,n.animate||this.element.css(k.extend(e,{top:s,left:i})),o.helper.height(o.size.height),o.helper.width(o.size.width),this._helper&&!n.animate&&this._proportionallyResize()),k("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s=this.options,n={minWidth:this._isNumber(s.minWidth)?s.minWidth:0,maxWidth:this._isNumber(s.maxWidth)?s.maxWidth:1/0,minHeight:this._isNumber(s.minHeight)?s.minHeight:0,maxHeight:this._isNumber(s.maxHeight)?s.maxHeight:1/0};(this._aspectRatio||t)&&(e=n.minHeight*this.aspectRatio,i=n.minWidth/this.aspectRatio,s=n.maxHeight*this.aspectRatio,t=n.maxWidth/this.aspectRatio,e>n.minWidth&&(n.minWidth=e),i>n.minHeight&&(n.minHeight=i),st.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),i=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&i&&(t.top=h-e.minHeight),n&&i&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];e<4;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;e"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++e.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize;return{left:this.originalPosition.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize;return{top:this.originalPosition.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(t,e,i){return k.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},sw:function(t,e,i){return k.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,e,i]))},ne:function(t,e,i){return k.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},nw:function(t,e,i){return k.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,e,i]))}},_propagate:function(t,e){k.ui.plugin.call(this,t,[e,this.ui()]),"resize"!==t&&this._trigger(t,e,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),k.ui.plugin.add("resizable","animate",{stop:function(e){var i=k(this).resizable("instance"),t=i.options,s=i._proportionallyResizeElements,n=s.length&&/textarea/i.test(s[0].nodeName),o=n&&i._hasScroll(s[0],"left")?0:i.sizeDiff.height,a=n?0:i.sizeDiff.width,n={width:i.size.width-a,height:i.size.height-o},a=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,o=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(k.extend(n,o&&a?{top:o,left:a}:{}),{duration:t.animateDuration,easing:t.animateEasing,step:function(){var t={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};s&&s.length&&k(s[0]).css({width:t.width,height:t.height}),i._updateCache(t),i._propagate("resize",e)}})}}),k.ui.plugin.add("resizable","containment",{start:function(){var i,s,n=k(this).resizable("instance"),t=n.options,e=n.element,o=t.containment,a=o instanceof k?o.get(0):/parent/.test(o)?e.parent().get(0):o;a&&(n.containerElement=k(a),/document/.test(o)||o===document?(n.containerOffset={left:0,top:0},n.containerPosition={left:0,top:0},n.parentData={element:k(document),left:0,top:0,width:k(document).width(),height:k(document).height()||document.body.parentNode.scrollHeight}):(i=k(a),s=[],k(["Top","Right","Left","Bottom"]).each(function(t,e){s[t]=n._num(i.css("padding"+e))}),n.containerOffset=i.offset(),n.containerPosition=i.position(),n.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},t=n.containerOffset,e=n.containerSize.height,o=n.containerSize.width,o=n._hasScroll(a,"left")?a.scrollWidth:o,e=n._hasScroll(a)?a.scrollHeight:e,n.parentData={element:a,left:t.left,top:t.top,width:o,height:e}))},resize:function(t){var e=k(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.position,o=e._aspectRatio||t.shiftKey,a={top:0,left:0},r=e.containerElement,t=!0;r[0]!==document&&/static/.test(r.css("position"))&&(a=s),n.left<(e._helper?s.left:0)&&(e.size.width=e.size.width+(e._helper?e.position.left-s.left:e.position.left-a.left),o&&(e.size.height=e.size.width/e.aspectRatio,t=!1),e.position.left=i.helper?s.left:0),n.top<(e._helper?s.top:0)&&(e.size.height=e.size.height+(e._helper?e.position.top-s.top:e.position.top),o&&(e.size.width=e.size.height*e.aspectRatio,t=!1),e.position.top=e._helper?s.top:0),i=e.containerElement.get(0)===e.element.parent().get(0),n=/relative|absolute/.test(e.containerElement.css("position")),i&&n?(e.offset.left=e.parentData.left+e.position.left,e.offset.top=e.parentData.top+e.position.top):(e.offset.left=e.element.offset().left,e.offset.top=e.element.offset().top),n=Math.abs(e.sizeDiff.width+(e._helper?e.offset.left-a.left:e.offset.left-s.left)),s=Math.abs(e.sizeDiff.height+(e._helper?e.offset.top-a.top:e.offset.top-s.top)),n+e.size.width>=e.parentData.width&&(e.size.width=e.parentData.width-n,o&&(e.size.height=e.size.width/e.aspectRatio,t=!1)),s+e.size.height>=e.parentData.height&&(e.size.height=e.parentData.height-s,o&&(e.size.width=e.size.height*e.aspectRatio,t=!1)),t||(e.position.left=e.prevPosition.left,e.position.top=e.prevPosition.top,e.size.width=e.prevSize.width,e.size.height=e.prevSize.height)},stop:function(){var t=k(this).resizable("instance"),e=t.options,i=t.containerOffset,s=t.containerPosition,n=t.containerElement,o=k(t.helper),a=o.offset(),r=o.outerWidth()-t.sizeDiff.width,o=o.outerHeight()-t.sizeDiff.height;t._helper&&!e.animate&&/relative/.test(n.css("position"))&&k(this).css({left:a.left-s.left-i.left,width:r,height:o}),t._helper&&!e.animate&&/static/.test(n.css("position"))&&k(this).css({left:a.left-s.left-i.left,width:r,height:o})}}),k.ui.plugin.add("resizable","alsoResize",{start:function(){var t=k(this).resizable("instance").options;k(t.alsoResize).each(function(){var t=k(this);t.data("ui-resizable-alsoresize",{width:parseFloat(t.width()),height:parseFloat(t.height()),left:parseFloat(t.css("left")),top:parseFloat(t.css("top"))})})},resize:function(t,i){var e=k(this).resizable("instance"),s=e.options,n=e.originalSize,o=e.originalPosition,a={height:e.size.height-n.height||0,width:e.size.width-n.width||0,top:e.position.top-o.top||0,left:e.position.left-o.left||0};k(s.alsoResize).each(function(){var t=k(this),s=k(this).data("ui-resizable-alsoresize"),n={},e=t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];k.each(e,function(t,e){var i=(s[e]||0)+(a[e]||0);i&&0<=i&&(n[e]=i||null)}),t.css(n)})},stop:function(){k(this).removeData("ui-resizable-alsoresize")}}),k.ui.plugin.add("resizable","ghost",{start:function(){var t=k(this).resizable("instance"),e=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}),t._addClass(t.ghost,"ui-resizable-ghost"),!1!==k.uiBackCompat&&"string"==typeof t.options.ghost&&t.ghost.addClass(this.options.ghost),t.ghost.appendTo(t.helper)},resize:function(){var t=k(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=k(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),k.ui.plugin.add("resizable","grid",{resize:function(){var t,e=k(this).resizable("instance"),i=e.options,s=e.size,n=e.originalSize,o=e.originalPosition,a=e.axis,r="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=r[0]||1,l=r[1]||1,c=Math.round((s.width-n.width)/h)*h,u=Math.round((s.height-n.height)/l)*l,d=n.width+c,p=n.height+u,f=i.maxWidth&&i.maxWidthd,s=i.minHeight&&i.minHeight>p;i.grid=r,m&&(d+=h),s&&(p+=l),f&&(d-=h),g&&(p-=l),/^(se|s|e)$/.test(a)?(e.size.width=d,e.size.height=p):/^(ne)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.top=o.top-u):/^(sw)$/.test(a)?(e.size.width=d,e.size.height=p,e.position.left=o.left-c):((p-l<=0||d-h<=0)&&(t=e._getPaddingPlusBorderDimensions(this)),0"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(i){var s=this,t=this.options;this.opos=[i.pageX,i.pageY],this.elementPos=k(this.element[0]).offset(),this.options.disabled||(this.selectees=k(t.filter,this.element[0]),this._trigger("start",i),k(t.appendTo).append(this.helper),this.helper.css({left:i.pageX,top:i.pageY,width:0,height:0}),t.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var t=k.data(this,"selectable-item");t.startselected=!0,i.metaKey||i.ctrlKey||(s._removeClass(t.$element,"ui-selected"),t.selected=!1,s._addClass(t.$element,"ui-unselecting"),t.unselecting=!0,s._trigger("unselecting",i,{unselecting:t.element}))}),k(i.target).parents().addBack().each(function(){var t,e=k.data(this,"selectable-item");if(e)return t=!i.metaKey&&!i.ctrlKey||!e.$element.hasClass("ui-selected"),s._removeClass(e.$element,t?"ui-unselecting":"ui-selected")._addClass(e.$element,t?"ui-selecting":"ui-unselecting"),e.unselecting=!t,e.selecting=t,(e.selected=t)?s._trigger("selecting",i,{selecting:e.element}):s._trigger("unselecting",i,{unselecting:e.element}),!1}))},_mouseDrag:function(s){if(this.dragged=!0,!this.options.disabled){var t,n=this,o=this.options,a=this.opos[0],r=this.opos[1],h=s.pageX,l=s.pageY;return hh||i.right l||i.bottoma&&i.rightr&&i.bottom *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return e<=t&&t*{ cursor: "+o.cursor+" !important; }").appendTo(n)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!i)for(s=this.containers.length-1;0<=s;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return k.ui.ddmanager&&(k.ui.ddmanager.current=this),k.ui.ddmanager&&!o.dropBehaviour&&k.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var e,i,s,n,o=this.options,a=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageYt[this.floating?"width":"height"]?l&&c:o",i.document[0]);return i._addClass(e,"ui-sortable-placeholder",s||i.currentItem[0].className)._removeClass(e,"ui-sortable-helper"),"tbody"===t?i._createTrPlaceholder(i.currentItem.find("tr").eq(0),k("",i.document[0]).appendTo(e)):"tr"===t?i._createTrPlaceholder(i.currentItem,e):"img"===t&&e.attr("src",i.currentItem.attr("src")),s||e.css("visibility","hidden"),e},update:function(t,e){s&&!n.forcePlaceholderSize||(e.height()||e.height(i.currentItem.innerHeight()-parseInt(i.currentItem.css("paddingTop")||0,10)-parseInt(i.currentItem.css("paddingBottom")||0,10)),e.width()||e.width(i.currentItem.innerWidth()-parseInt(i.currentItem.css("paddingLeft")||0,10)-parseInt(i.currentItem.css("paddingRight")||0,10)))}}),i.placeholder=k(n.placeholder.element.call(i.element,i.currentItem)),i.currentItem.after(i.placeholder),n.placeholder.update(i,i.placeholder)},_createTrPlaceholder:function(t,e){var i=this;t.children().each(function(){k(" ",i.document[0]).attr("colspan",k(this).attr("colspan")||1).appendTo(e)})},_contactContainers:function(t){for(var e,i,s,n,o,a,r,h,l,c=null,u=null,d=this.containers.length-1;0<=d;d--)k.contains(this.currentItem[0],this.containers[d].element[0])||(this._intersectsWith(this.containers[d].containerCache)?c&&k.contains(this.containers[d].element[0],c.element[0])||(c=this.containers[d],u=d):this.containers[d].containerCache.over&&(this.containers[d]._trigger("out",t,this._uiHash(this)),this.containers[d].containerCache.over=0));if(c)if(1===this.containers.length)this.containers[u].containerCache.over||(this.containers[u]._trigger("over",t,this._uiHash(this)),this.containers[u].containerCache.over=1);else{for(i=1e4,s=null,n=(h=c.floating||this._isFloating(this.currentItem))?"left":"top",o=h?"width":"height",l=h?"pageX":"pageY",e=this.items.length-1;0<=e;e--)k.contains(this.containers[u].element[0],this.items[e].item[0])&&this.items[e].item[0]!==this.currentItem[0]&&(a=this.items[e].item.offset()[n],r=!1,t[l]-a>this.items[e][o]/2&&(r=!0),Math.abs(t[l]-a)this.containment[2]&&(i=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(s=this.containment[3]+this.offset.click.top)),e.grid&&(t=this.originalPageY+Math.round((s-this.originalPageY)/e.grid[1])*e.grid[1],s=!this.containment||t-this.offset.click.top>=this.containment[1]&&t-this.offset.click.top<=this.containment[3]?t:t-this.offset.click.top>=this.containment[1]?t-e.grid[1]:t+e.grid[1],t=this.originalPageX+Math.round((i-this.originalPageX)/e.grid[0])*e.grid[0],i=!this.containment||t-this.offset.click.left>=this.containment[0]&&t-this.offset.click.left<=this.containment[2]?t:t-this.offset.click.left>=this.containment[0]?t-e.grid[0]:t+e.grid[0])),{top:s-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop()),left:i-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)"auto"!==this._storedCSS[i]&&"static"!==this._storedCSS[i]||(this._storedCSS[i]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();function n(e,i,s){return function(t){s._trigger(e,t,i._uiHash(i))}}for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||s.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;0<=i;i--)e||s.push(n("deactivate",this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(n("out",this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(i=0;i li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var t=this.options;this.prevShow=this.prevHide=k(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),t.collapsible||!1!==t.active&&null!=t.active||(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():k()}},_createIcons:function(){var t,e=this.options.icons;e&&(t=k(""),this._addClass(t,"ui-accordion-header-icon","ui-icon "+e.header),t.prependTo(this.headers),t=this.active.children(".ui-accordion-header-icon"),this._removeClass(t,e.header)._addClass(t,null,e.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){"active"!==t?("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||!1!==this.options.active||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons())):this._activate(e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var e=k.ui.keyCode,i=this.headers.length,s=this.headers.index(t.target),n=!1;switch(t.keyCode){case e.RIGHT:case e.DOWN:n=this.headers[(s+1)%i];break;case e.LEFT:case e.UP:n=this.headers[(s-1+i)%i];break;case e.SPACE:case e.ENTER:this._eventHandler(t);break;case e.HOME:n=this.headers[0];break;case e.END:n=this.headers[i-1]}n&&(k(t.target).attr("tabIndex",-1),k(n).attr("tabIndex",0),k(n).trigger("focus"),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===k.ui.keyCode.UP&&t.ctrlKey&&k(t.currentTarget).prev().trigger("focus")},refresh:function(){var t=this.options;this._processPanels(),!1===t.active&&!0===t.collapsible||!this.headers.length?(t.active=!1,this.active=k()):!1===t.active?this._activate(0):this.active.length&&!k.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=k()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var i,t=this.options,e=t.heightStyle,s=this.element.parent();this.active=this._findActive(t.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var t=k(this),e=t.uniqueId().attr("id"),i=t.next(),s=i.uniqueId().attr("id");t.attr("aria-controls",s),i.attr("aria-labelledby",e)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(t.event),"fill"===e?(i=s.height(),this.element.siblings(":visible").each(function(){var t=k(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.headers.each(function(){i-=k(this).outerHeight(!0)}),this.headers.next().each(function(){k(this).height(Math.max(0,i-k(this).innerHeight()+k(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.headers.next().each(function(){var t=k(this).is(":visible");t||k(this).show(),i=Math.max(i,k(this).css("height","").height()),t||k(this).hide()}).height(i))},_activate:function(t){t=this._findActive(t)[0];t!==this.active[0]&&(t=t||this.active[0],this._eventHandler({target:t,currentTarget:t,preventDefault:k.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):k()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&k.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var e=this.options,i=this.active,s=k(t.currentTarget),n=s[0]===i[0],o=n&&e.collapsible,a=o?k():s.next(),r=i.next(),a={oldHeader:i,oldPanel:r,newHeader:o?k():s,newPanel:a};t.preventDefault(),n&&!e.collapsible||!1===this._trigger("beforeActivate",t,a)||(e.active=!o&&this.headers.index(s),this.active=n?k():s,this._toggle(a),this._removeClass(i,"ui-accordion-header-active","ui-state-active"),e.icons&&(i=i.children(".ui-accordion-header-icon"),this._removeClass(i,null,e.icons.activeHeader)._addClass(i,null,e.icons.header)),n||(this._removeClass(s,"ui-accordion-header-collapsed")._addClass(s,"ui-accordion-header-active","ui-state-active"),e.icons&&(n=s.children(".ui-accordion-header-icon"),this._removeClass(n,null,e.icons.header)._addClass(n,null,e.icons.activeHeader)),this._addClass(s.next(),"ui-accordion-content-active")))},_toggle:function(t){var e=t.newPanel,i=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=e,this.prevHide=i,this.options.animate?this._animate(e,i,t):(i.hide(),e.show(),this._toggleComplete(t)),i.attr({"aria-hidden":"true"}),i.prev().attr({"aria-selected":"false","aria-expanded":"false"}),e.length&&i.length?i.prev().attr({tabIndex:-1,"aria-expanded":"false"}):e.length&&this.headers.filter(function(){return 0===parseInt(k(this).attr("tabIndex"),10)}).attr("tabIndex",-1),e.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,i,e){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!i.length||t.index()",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(t){var e=k(t.target),i=k(k.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var e,i;this.previousFilter||(e=k(t.target).closest(".ui-menu-item"),i=k(t.currentTarget),e[0]===i[0]&&(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i)))},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(t){this._delay(function(){k.contains(this.element[0],k.ui.safeActiveElement(this.document[0]))||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=k(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case k.ui.keyCode.PAGE_UP:this.previousPage(t);break;case k.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case k.ui.keyCode.HOME:this._move("first","first",t);break;case k.ui.keyCode.END:this._move("last","last",t);break;case k.ui.keyCode.UP:this.previous(t);break;case k.ui.keyCode.DOWN:this.next(t);break;case k.ui.keyCode.LEFT:this.collapse(t);break;case k.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case k.ui.keyCode.ENTER:case k.ui.keyCode.SPACE:this._activate(t);break;case k.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=k(this),e=t.prev(),i=k("").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=k(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),i=(e=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(e,"ui-menu-item")._addClass(i,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!k.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(i=parseFloat(k.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(k.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-i-s,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&this._isContentEditable(this.element),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=k.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)return i=!1,void(this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault());if(!s){var e=k.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){if(n)return n=!1,void t.preventDefault();this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){this.cancelBlur?delete this.cancelBlur:(clearTimeout(this.searching),this.close(t),this._change(t))}}),this._initSource(),this.menu=k("