"use strict";
(self["webpackChunk_xavier_idgxavier"] = self["webpackChunk_xavier_idgxavier"] || []).push([["lib_index_js"],{

/***/ "./lib/assets/AddContextIcon.js":
/*!**************************************!*\
  !*** ./lib/assets/AddContextIcon.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   AddContextIcon: () => (/* binding */ AddContextIcon)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

;
;
class AddContextIcon extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.onIconClick = this.onIconClick.bind(this);
    }
    onIconClick(e) {
        e.stopPropagation();
        this.props.handleIconClick(e);
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-icon-wrapper", onClick: this.onIconClick }, this.props.sign === "+" ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M6.41665 6.41659V2.33325H7.58331V6.41659H11.6666V7.58325H7.58331V11.6666H6.41665V7.58325H2.33331V6.41659H6.41665Z", fill: "#444444" }))) : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { viewBox: "0 0 1024 1024", version: "1.1", xmlns: "http://www.w3.org/2000/svg", "p-id": "1437", width: "14", height: "14" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M170.666667 469.333333h682.666666v85.333334H170.666667z", fill: "#444444", "p-id": "1438" })))));
    }
}


/***/ }),

/***/ "./lib/assets/MultiSelectIcon.js":
/*!***************************************!*\
  !*** ./lib/assets/MultiSelectIcon.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   MultiSelectIcon: () => (/* binding */ MultiSelectIcon)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

;
;
class MultiSelectIcon extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.defaultWidth = 14;
        this.defaultHeight = 14;
        this.handleIconClick = this.handleIconClick.bind(this);
    }
    handleIconClick(e) {
        this.props.handleIconClick(e);
    }
    render() {
        const width = this.props.width === undefined ? this.defaultWidth : this.props.width;
        const height = this.props.height === undefined ? this.defaultHeight : this.props.height;
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-icon-wrapper", onClick: this.handleIconClick }, this.props.status === "full" ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { viewBox: "0 0 1024 1024", version: "1.1", xmlns: "http://www.w3.org/2000/svg", "p-id": "6496", width: width, height: height },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M863.8 127.7c17.6 0 32 14.4 32 32v704c0 17.6-14.4 32-32 32h-704c-17.6 0-32-14.4-32-32v-704c0-17.6 14.4-32 32-32h704m0-64h-704c-53 0-96 43-96 96v704c0 53 43 96 96 96h704c53 0 96-43 96-96v-704c0-53-42.9-96-96-96z", "p-id": "6497", fill: "#444444" }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M435 737.1c-1.7 0-3.4-0.1-5.1-0.2-17-1.3-32.5-9.2-43.6-22.2L208.8 507c-11.5-13.4-9.9-33.6 3.5-45.1s33.6-9.9 45.1 3.5L434.8 673l332.4-284c13.4-11.5 33.6-9.9 45.1 3.5s9.9 33.6-3.5 45.1l-332.4 284c-11.6 10.2-26.2 15.5-41.4 15.5z", "p-id": "6498", fill: "#444444" }))) : this.props.status === "empty" ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { viewBox: "0 0 1024 1024", version: "1.1", xmlns: "http://www.w3.org/2000/svg", "p-id": "6755", width: width, height: height },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M873.59 960H150.41C102.73 960 64 921.27 64 873.59V150.41C64 102.73 102.73 64 150.41 64h723.18c47.68 0 86.41 38.73 86.41 86.41v723.17c0 47.69-38.73 86.42-86.41 86.42zM150.68 116.95c-18.44 0-33.72 15.02-33.72 33.72v723.17c0 18.44 15.02 33.72 33.72 33.72h723.18c18.44 0 33.72-15.02 33.72-33.72V150.68c0-18.44-15.02-33.72-33.72-33.72H150.68z", "p-id": "6756", fill: "#444444" }))) : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { viewBox: "0 0 1024 1024", version: "1.1", xmlns: "http://www.w3.org/2000/svg", "p-id": "5800", width: width, height: height },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M152.251317 1023.000976h718.498342c83.918049 0 152.251317-68.333268 152.251317-152.251317V152.251317C1023.000976 68.333268 954.667707 0 870.749659 0H152.251317C68.333268 0 0 68.333268 0 152.251317v718.498342c0 83.918049 68.333268 152.251317 152.251317 152.251317zM56.834498 883.996722V139.044215a82.429502 82.429502 0 0 1 82.149775-82.239688h745.04242a82.279649 82.279649 0 0 1 82.149775 82.139785v745.05241a82.279649 82.279649 0 0 1-82.149775 82.139785H138.984273a82.279649 82.279649 0 0 1-82.149775-82.139785z", fill: "#444444", "p-id": "5801", "data-spm-anchor-id": "a313x.search_index.0.i11.290c3a81HmaRUN" }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M227.328 227.34798m73.068644 0l422.197697 0q73.068644 0 73.068644 73.068644l0 422.197698q0 73.068644-73.068644 73.068644l-422.197697 0q-73.068644 0-73.068644-73.068644l0-422.197698q0-73.068644 73.068644-73.068644Z", fill: "#8a8a8a", "p-id": "5802", "data-spm-anchor-id": "a313x.search_index.0.i7.290c3a81HmaRUN" })))));
    }
}
;


/***/ }),

/***/ "./lib/assets/SvgCollection.js":
/*!*************************************!*\
  !*** ./lib/assets/SvgCollection.js ***!
  \*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   MetaDataIcon: () => (/* binding */ MetaDataIcon)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constant */ "./lib/constant.js");


const MetaDataIcon = () => {
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("svg", { viewBox: "0 0 1024 1024", version: "1.1", xmlns: "http://www.w3.org/2000/svg", "p-id": "4953", width: "20", height: "20" },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("path", { d: "M922.688 64H101.312A37.312 37.312 0 0 0 64 101.312V776.32c0 20.608 16.704 37.312 37.312 37.312h821.376A37.312 37.312 0 0 0 960 776.32V101.312A37.312 37.312 0 0 0 922.688 64z m-37.376 675.008H138.688v-600.32h746.624v600.32z m-123.264 146.304a37.312 37.312 0 0 1 0 74.688H261.952a37.312 37.312 0 1 1 0-74.688h500.096z m-518.4-288v-1.024a52.672 52.672 0 0 1 0-105.216 47.808 47.808 0 0 1 13.44 2.176L376.32 366.912a49.728 49.728 0 1 1 95.552 0l117.12 123.968a42.688 42.688 0 0 1 31.36 0l113.536-119.872a52.672 52.672 0 1 1 46.528 34.368 48.64 48.64 0 0 1-9.6 0l-117.76 125.44c0.896 3.84 1.408 7.68 1.472 11.712a49.92 49.92 0 1 1-99.648 0c0.128-3.968 0.512-7.872 1.28-11.776l-118.592-125.44a42.688 42.688 0 0 1-26.88 0L291.2 530.56a52.032 52.032 0 0 1-47.552 66.752z", fill: _constant__WEBPACK_IMPORTED_MODULE_1__.ViewIconStyle.fill, "p-id": "4954" })));
};


/***/ }),

/***/ "./lib/codePanelLink/highlightSidePanel.js":
/*!*************************************************!*\
  !*** ./lib/codePanelLink/highlightSidePanel.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   resetAllColumnHighlight: () => (/* binding */ resetAllColumnHighlight),
/* harmony export */   resetAllDfFold: () => (/* binding */ resetAllDfFold)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);

function resetAllColumnHighlight(allDfStyle) {
    for (const key in allDfStyle) {
        for (const colKey in allDfStyle[key].columns) {
            allDfStyle[key].columns[colKey].isHighlight = false;
        }
    }
}
function resetAllDfFold(tableColumnsLL, newAllDfStyle) {
    if (!lodash__WEBPACK_IMPORTED_MODULE_0___default().isEmpty(tableColumnsLL)) {
        for (const t in newAllDfStyle) {
            if (!(t in tableColumnsLL)) {
                newAllDfStyle[t].isFold = true;
            }
        }
    }
}


/***/ }),

/***/ "./lib/constant.js":
/*!*************************!*\
  !*** ./lib/constant.js ***!
  \*************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SSAlternateColor: () => (/* binding */ SSAlternateColor),
/* harmony export */   SSCellMaxWidth: () => (/* binding */ SSCellMaxWidth),
/* harmony export */   SSColumnHLColor: () => (/* binding */ SSColumnHLColor),
/* harmony export */   SSColumnPreColor: () => (/* binding */ SSColumnPreColor),
/* harmony export */   SSMaxHeight: () => (/* binding */ SSMaxHeight),
/* harmony export */   SSRowDelColor: () => (/* binding */ SSRowDelColor),
/* harmony export */   SSRowHLDelColor: () => (/* binding */ SSRowHLDelColor),
/* harmony export */   SSTableRowHeight: () => (/* binding */ SSTableRowHeight),
/* harmony export */   ViewIconStyle: () => (/* binding */ ViewIconStyle),
/* harmony export */   ViewMode: () => (/* binding */ ViewMode)
/* harmony export */ });
const ViewMode = {
    INIT: 0,
    FILTER_COLUMN: 1,
    FILTER_VALUE: 2
};
const ViewIconStyle = {
    fill: "#777777",
};
// SpreadSheet column Highlight color
const SSRowHLDelColor = "#f5eef7";
const SSColumnHLColor = "#e9e9ff"; //"#dfdfff" //"#d5d4ff";
const SSColumnPreColor = "#fffcee";
const SSRowDelColor = "#fff2f0";
const SSAlternateColor = ["#f1f1f1", "#ffffff"]; // "#eaebee"
const SSCellMaxWidth = 75;
const SSTableRowHeight = 30;
const SSMaxHeight = 8.5 * SSTableRowHeight;


/***/ }),

/***/ "./lib/dataApi/nbApi.js":
/*!******************************!*\
  !*** ./lib/dataApi/nbApi.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NBApi: () => (/* binding */ NBApi)
/* harmony export */ });
/* harmony import */ var _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/notebook */ "webpack/sharing/consume/default/@jupyterlab/notebook");
/* harmony import */ var _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _nbcell__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./nbcell */ "./lib/dataApi/nbcell.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils */ "./lib/utils.js");


// import { IKernelConnection } from '@jupyterlab/services/lib/kernel/kernel';



function _getKernel(panel) {
    const s = panel.sessionContext.session;
    if (s === null) {
        throw new Error("[_getKernel] No session found.");
    }
    if (s.kernel === null) {
        throw new Error("[_getKernel] No kernel found.");
    }
    return s.kernel;
}
class NBApi {
    constructor(notebookPanel) {
        this._changed = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_1__.Signal(this);
        this._hasConnection = false;
        this._dfList = [];
        this._panel = notebookPanel;
        this._ready = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_2__.PromiseDelegate();
        this.cells = [];
        this.mostRecentExecutionCount = -1;
        if (this._panel) {
            // this.listenToSession();
            this._panel.revealed.then(() => {
                this.listenToCells();
                this._hasConnection = true;
                this._ready.resolve();
            });
        }
        else {
            this._ready.resolve();
        }
    }
    // saveToNotebookMetadata(key: string, value: any) {
    //     this.panel.model.metadata.set(key, value);
    // }
    // ready is a Promise that resolves once the notebook is done loading
    get ready() {
        return this._ready.promise;
    }
    get panel() {
        if (!this._panel) {
            throw Error("[NBApi] Notebook panel is not defined.");
        }
        return this._panel;
    }
    get dfList() {
        return this._dfList;
    }
    get hasConnection() {
        return this._hasConnection;
    }
    // changed is a signal emitted when various things in this notebook change
    get changed() {
        return this._changed;
    }
    get notebook() {
        var _a;
        return (_a = this.panel) === null || _a === void 0 ? void 0 : _a.content;
    }
    // get path(): string | undefined {
    //     return this.panel?.sessionContext?.path;
    // }
    // get name(): string | undefined {
    //     return this.path ? PathExt.basename(this.path) : undefined;
    // }
    // get activeCell(): CellAPI | undefined {
    //     if (this.notebook && this.cells) {
    //         const active = this.notebook.activeCell;
    //         return this.cells.find(c => c.model.id === active.model.id);
    //     }
    //     return undefined;
    // }
    // Various notebook level events you can listen to
    listenToCells() {
        this.loadCells();
        if (this.notebook === undefined || this.notebook.model === null) {
            console.warn("[listenToCells] notebook is undefined");
            return;
        }
        // event fires when cells are added, deleted, or moved
        this.notebook.model.cells.changed.connect(() => {
            this.loadCells();
            this._changed.emit('cells');
        });
        // // event fires when the user selects a cell
        this.notebook.activeCellChanged.connect((_, cell) => {
            this._changed.emit('activeCell');
        });
        // event fires when any cell is run
        _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_0__.NotebookActions.executed.connect(async (_, args) => {
            // can get execution signals from other notebooks
            if (this.notebook === undefined) {
                console.warn("[listenToCells] notebook is undefined");
                return;
            }
            if (args.notebook.id === this.notebook.id) {
                const cell = this.cells.find(c => c.model.id === args.cell.model.id);
                if (cell !== undefined) {
                    const exCount = cell.getExecutionCount();
                    this.mostRecentExecutionCount = (exCount !== null) ? exCount : this.mostRecentExecutionCount;
                    cell._runSignal.emit();
                    this._changed.emit('cellRun');
                    const k = _getKernel(this.panel);
                    const dfList = await (0,_utils__WEBPACK_IMPORTED_MODULE_3__.getActiveDataFrames)(k);
                    this._dfList = dfList;
                    // this._allDfInfo = await _getallDfInfo(k, dfList);
                    // console.log("[listenToCells] allDfInfo", this._allDfInfo);
                }
            }
        });
        // this.notebook.model.metadata.changed.connect((_, args) => {
        //     this._changed.emit('language changed');
        // })
    }
    loadCells() {
        this.cells = [];
        if (this.notebook == undefined || this.notebook.model == undefined) {
            console.warn("[loadCells] notebook or notebook model is undefined");
            return;
        }
        for (let i = 0; i < this.notebook.model.cells.length; i++) {
            this.cells.push(new _nbcell__WEBPACK_IMPORTED_MODULE_4__["default"](this.notebook.model.cells.get(i), i));
        }
    }
}


/***/ }),

/***/ "./lib/dataApi/nbExe.js":
/*!******************************!*\
  !*** ./lib/dataApi/nbExe.js ***!
  \******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NBExe: () => (/* binding */ NBExe)
/* harmony export */ });
function replaceSpecial(input_str) {
    /*Format strings when writing code, need to escape double quotes (")
    since the code uses same character, single quotes are fine (') */
    const res = input_str
        .replace(/\\/g, '\\\\') // escape backslashes
        .replace(/"/g, '\\"'); // escape double quotes
    return res;
}
class NBExe {
    constructor(session) {
        this._sessionContext = session; // starts null
    }
    setSession(new_session) {
        this._sessionContext = new_session;
    }
    get session() {
        if (!this._sessionContext) {
            throw new Error('[NBExe] Session context is null');
        }
        return this._sessionContext;
    }
    // ################################## Code execution helpers ###########################################
    sendCodeToKernel(code, onReply, onDone) {
        if (!(this.session == undefined)) {
            const ss = this.session.session;
            if (!ss) {
                throw new Error('[NBExe] Session is undefined');
            }
            const knl = ss.kernel;
            if (!knl) {
                throw new Error('[NBExe] Kernel is undefined');
            }
            const future = knl.requestExecute({
                code,
                stop_on_error: true,
                store_history: false // prevents incrementing execution count for extension code
            });
            // this is the output of the execution, may return things multiple times as code runs
            future.onIOPub = (msg) => {
                const msg_type = msg.header.msg_type;
                if ((msg_type === 'execute_result' || msg_type === 'display_data' || msg_type === 'update_display_data' || msg_type === 'stream') && onReply) {
                    onReply(msg_type + '', msg.content);
                }
            };
            // when execution is done
            future.done.then(reply => {
                if (onDone) {
                    onDone(reply.content.status);
                }
                // reply.content.execution_count // time this code was run
            }, error => {
                console.warn('Code run failed: ', error);
                if (onDone) {
                    onDone();
                }
            });
        }
    }
    async executeCode(code) {
        return new Promise(resolve => {
            const response = {
                content: [],
                exec_count: -1
            };
            const contentMatrix = [];
            const onReply = (type, content) => {
                if (type === 'execute_result' || type === 'display_data' || type === 'update_display_data') {
                    const cont = content.data['text/plain'].split('\n');
                    response.exec_count = content.execution_count; // does not exist on message for streams
                    contentMatrix.push(cont);
                }
                else if (type === 'stream') {
                    const cont = content.text.split('\n');
                    contentMatrix.push(cont);
                }
            };
            const onDone = (status) => {
                let flat_array = Array.prototype.concat(...contentMatrix);
                /* prevent empty strings that happen from extra returns at end of print(),
                        this causes big issues if onReply() returns multiple times and the order
                        of code results gets thrown off. If future code intentionally prints blank
                        lines this will cause other issues. */
                flat_array = flat_array.filter(item => item !== '');
                response['content'] = flat_array;
                // console.log(`[executeCode] ${code} finished with status [${status}]. Response: `, response)
                resolve(response);
            };
            this.sendCodeToKernel(code, onReply, onDone);
        });
    }
    /**
     * If using the python package xavier, then it needs to be imported every time
     * so this appends the import and then executes the code
     * @param code the code string
     */
    executePythonXavier(code) {
        const importCode = 'import idgxavier as idg_xavier\n';
        const deleteCode = '\ndel idg_xavier\n';
        return this.executeCode(importCode + code + deleteCode);
    }
    // ############################# Python kernel functions ################################################
    async getAllDataFrames(currentOutputName) {
        try {
            const pandasImported = await this.checkIfPandasInModules();
            if (!pandasImported) {
                console.warn("[getAllDataFrames] Pandas is not imported");
                return {};
            }
            const var_names = await this.getVariableNames(currentOutputName);
            const isDF = await this.getIsDFVars(var_names);
            const vars_DF = var_names.filter((d, idx) => isDF[idx] === 'True');
            const dfColMap = {};
            const python_ids = await this.getObjectIds(vars_DF);
            for (let index = 0; index < vars_DF.length; index++) {
                const dfName = vars_DF[index];
                const [num_rows, num_cols] = await this.getShape(dfName);
                const { columns, columnNameList } = await this.getColumns(dfName);
                dfColMap[dfName] = {
                    tableName: dfName,
                    numRows: num_rows,
                    numCols: num_cols,
                    python_id: python_ids[index],
                    columns: columns,
                    columnNameList: columnNameList,
                };
            }
            return dfColMap;
        }
        catch (error) {
            console.warn('[getAllDataFrames]', error);
            return {};
        }
    }
    async getCateValueCounts(dfName, colName) {
        const code = `idg_xavier.getCateValueCounts(${dfName}, "${replaceSpecial(colName)}")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            return json_res;
        }
        catch (error) {
            console.warn(`[Error caught] in getCateValueCounts executing code: ${code}`, error);
            return [];
        }
    }
    async getNumColumnSample(dfName, colName) {
        const code = `idg_xavier.getNumColumnSample(${dfName}, "${replaceSpecial(colName)}")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const sample = json_res["sample"];
            return sample;
        }
        catch (error) {
            console.warn(`[Error caught] in getNumColumnSample executing code: ${code}`, error);
            return [];
        }
    }
    async getRowSampleOfOneDf(dfName, condition) {
        const code = `idg_xavier.getRowSampleOfOneDf(${dfName}, """${JSON.stringify(condition)}""")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            return json_res;
        }
        catch (error) {
            console.warn(`[Error caught] in getRowSampleOfOneDf executing code: ${code}`, error);
            return [];
        }
    }
    async getVariableNames(currentOutputName) {
        try {
            // const code = `print([x for x in dir() if x == "${currentOutputName}" or x[0] != "_"])`
            const code = `print([x for x in dir() if x[0] != "_"])`;
            const res = await this.executeCode(code);
            const content = res['content'];
            const data = content.join("").replace(/'/g, '"');
            if (data) {
                const names = JSON.parse(data);
                return names;
            }
            return [];
        }
        catch (error) {
            return [];
        }
    }
    async checkIfPandasInModules() {
        try {
            const code_lines = [
                "import sys as __xavier_sys",
                "print('pandas' in __xavier_sys.modules)",
                "del __xavier_sys"
            ];
            const res = await this.executeCode(code_lines.join('\n'));
            const content = res['content'].join("").trim();
            if (content === 'True') {
                return true;
            }
            return false;
        }
        catch (error) {
            return false;
        }
    }
    /**
     * NOTE: this function cannot be put in xavier python because evaluting the variable names
     * does not work from a separate module
     * @returns array of "True" or "False" if that variable is a pandas dataframe
     */
    async getIsDFVars(varNames) {
        try {
            const code_lines = ['import pandas as __xavier_pandas'];
            varNames.forEach(name => code_lines.push(`print(type(${name}) == __xavier_pandas.DataFrame)`));
            code_lines.push('del __xavier_pandas');
            const res = await this.executeCode(code_lines.join('\n'));
            const content = res['content'];
            return content;
        }
        catch (error) {
            console.warn('[getIsDFVars]', error);
            return [];
        }
    }
    /**
     * Used to see if id has changed and update interface.
     * NOTE: this function cannot be put in xavier python because evaluting the variable names
     * does not work from a separate module
     * @returns array of python object ids for varNames
     */
    async getObjectIds(varNames) {
        try {
            const code_lines = [];
            varNames.forEach(name => code_lines.push(`print(id(${name}))`));
            const res = await this.executeCode(code_lines.join('\n'));
            const content = res['content'];
            return content;
        }
        catch (error) {
            console.warn('[Error caught] in getObjectIds', error);
            return [];
        }
    }
    async getColumns(dfName) {
        const code = `idg_xavier.getColumns(${dfName})`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const columnNameList = [];
            const columns = {};
            for (const item of json_res) {
                columnNameList.push(item["colName"]);
                if (item["colName"] in columns) {
                    console.warn(`[getColumns] Column name ${item["colName"]} is duplicated in dataframe ${dfName}`);
                }
                columns[item["colName"]] = {
                    colName: item["colName"],
                    dtype: item["dtype"],
                    nullCount: item["nullCount"],
                    cardinality: item["cardinality"],
                    sortedness: item["sortedness"],
                    minValue: item["minValue"],
                    maxValue: item["maxValue"],
                };
            }
            return { columns, columnNameList };
        }
        catch (error) {
            console.warn(`[Error caught] in getColumns executing code: ${code}`, error);
            return { columns: {}, columnNameList: [] };
        }
    }
    async getShape(dfName) {
        /*
        returns tuple array [length, width]
        */
        const code = `idg_xavier.getShape(${dfName})`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content'];
            const shapeString = content.join("");
            const [length, width] = shapeString.substring(1, shapeString.length - 1).split(',').map(x => parseFloat(x));
            return [length, width];
        }
        catch (error) {
            console.warn(`[Error caught] in getShape executing: ${code}`, error);
            return [0, 0];
        }
    }
    async getHeadTail(dfName) {
        const code = `idg_xavier.getHeadTail(${dfName})`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content'];
            const json_res = JSON.parse(content.join(""));
            return json_res;
        }
        catch (error) {
            console.warn(`[Error caught] in getHeadTail executing: ${code}`, error);
            return [];
        }
    }
    async getNumHistogram(dfName, colName) {
        const code = `idg_xavier.getNumHistogram(${dfName}, "${replaceSpecial(colName)}")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content === null || content === void 0 ? void 0 : content.join(""));
            return json_res["histogram"];
        }
        catch (error) {
            console.warn(`[Error caught] in getNumHistogram executing: ${code}`, error);
            return [];
        }
    }
    async exeFillna(table, column, fillValue) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeFillna(${table}, "${replaceSpecial(column)}", ${fillValue})`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const meta = JSON.parse(json_res["meta"]);
            return {
                newList: json_res["newList"],
                meta: meta[0]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeFillna executing: ${code}`, error);
            return {
                newList: [],
                meta: {
                    colName: column,
                    dtype: "object",
                    nullCount: 0,
                    cardinality: 0,
                    sortedness: "no",
                    minValue: null,
                    maxValue: null
                }
            };
        }
    }
    async exeColumnRename(table, oldColName, newColName) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeColumnRename(${table}, "${replaceSpecial(oldColName)}","${replaceSpecial(newColName)}")`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const meta = JSON.parse(json_res["meta"]);
            return {
                newList: json_res["newList"],
                meta: meta[0]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in newColName executing: ${code}`, error);
            return {
                newList: [],
                meta: {
                    colName: newColName,
                    dtype: "object",
                    nullCount: 0,
                    cardinality: 0,
                    sortedness: "no",
                    minValue: null,
                    maxValue: null
                }
            };
        }
    }
    async exeColumnAdd(table, column, operator, addedColumns) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeColumnAdd(${table}, "${column}", "${operator}", """ ${JSON.stringify(addedColumns)} """)`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const meta = JSON.parse(json_res["meta"]);
            return {
                newList: json_res["newList"],
                meta: meta[0]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeColumnAdd executing: ${code}`, error);
            return {
                newList: [],
                meta: {
                    colName: column,
                    dtype: "object",
                    nullCount: 0,
                    cardinality: 0,
                    sortedness: "no",
                    minValue: null,
                    maxValue: null
                }
            };
        }
    }
    async exeStrReplace(series, old, newStr) {
        const code = `idg_xavier.exeStrReplace(${JSON.stringify(series)}, ${old}, ${newStr})`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            return json_res;
        }
        catch (error) {
            console.warn(`[Error caught] in exeStrReplace executing: ${code}`, error);
            return [];
        }
    }
    async exeStrReplaceMeta(table, column, old, newStr) {
        const code = `idg_xavier.exeStrReplaceMeta(${table}, "${replaceSpecial(column)}", ${old}, ${newStr})`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null            
            const json_res = JSON.parse(content.join(""));
            const item = json_res[0];
            return {
                colName: item["colName"],
                dtype: item["dtype"],
                nullCount: item["nullCount"],
                cardinality: item["cardinality"],
                sortedness: item["sortedness"],
                minValue: item["minValue"],
                maxValue: item["maxValue"],
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeStrReplaceMeta executing: ${code}`, error);
            return {
                colName: column,
                dtype: "object",
                nullCount: 0,
                cardinality: 0,
                sortedness: "no",
                minValue: null,
                maxValue: null
            };
        }
    }
    async exeTableFilter(table, cond, newTable) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeTableFilter(${table}, "${table}", """ ${cond} """)`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const resRows = JSON.parse(json_res["rows"]);
            const jcolumns = JSON.parse(json_res["columns"]);
            const columns = {};
            for (const item of jcolumns) {
                columns[item["colName"]] = {
                    colName: item["colName"],
                    dtype: item["dtype"],
                    nullCount: item["nullCount"],
                    cardinality: item["cardinality"],
                    sortedness: item["sortedness"],
                    minValue: item["minValue"],
                    maxValue: item["maxValue"],
                };
            }
            return {
                success: true,
                resRows,
                resMeta: {
                    tableName: newTable,
                    python_id: "",
                    numRows: json_res["numRows"],
                    numCols: json_res["numCols"],
                    columns: columns,
                    columnNameList: json_res["columnNameList"]
                },
                histograms: json_res["histograms"]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeTableFilter executing: ${code}`, error);
            return {
                success: false,
                resRows: [],
                resMeta: {
                    tableName: table,
                    python_id: "",
                    numRows: 0,
                    numCols: 0,
                    columns: {},
                    columnNameList: []
                },
                histograms: {}
            };
        }
    }
    async exeTableSort(table, sortCols, ascending, newTable) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeTableSort(${table}, """ ${JSON.stringify(sortCols)} """, """ ${JSON.stringify(ascending)} """)`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const resRows = JSON.parse(json_res["rows"]);
            const jcolumns = JSON.parse(json_res["columns"]);
            const columns = {};
            for (const item of jcolumns) {
                columns[item["colName"]] = {
                    colName: item["colName"],
                    dtype: item["dtype"],
                    nullCount: item["nullCount"],
                    cardinality: item["cardinality"],
                    sortedness: item["sortedness"],
                    minValue: item["minValue"],
                    maxValue: item["maxValue"],
                };
            }
            return {
                success: true,
                resRows,
                resMeta: {
                    tableName: newTable,
                    python_id: "",
                    numRows: json_res["numRows"],
                    numCols: json_res["numCols"],
                    columns: columns,
                    columnNameList: json_res["columnNameList"]
                },
                histograms: json_res["histograms"]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeTableSort executing: ${code}`, error);
            return {
                success: false,
                resRows: [],
                resMeta: {
                    tableName: table,
                    python_id: "",
                    numRows: 0,
                    numCols: 0,
                    columns: {},
                    columnNameList: []
                },
                histograms: {}
            };
        }
    }
    async exeGroupby(table, groupbyCols, selectCols, aggFunc, newTable) {
        const saveDf = `__xavier_save_${table} = ${table}.copy()`;
        const code = `idg_xavier.exeGroupby(${table}, """ ${JSON.stringify(groupbyCols)} """, """ ${JSON.stringify(selectCols)} """, "${aggFunc}")`;
        const restoreDf = `${table} = __xavier_save_${table}`;
        const deleteDf = `del __xavier_save_${table}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            const resRows = JSON.parse(json_res["rows"]);
            const jcolumns = JSON.parse(json_res["columns"]);
            const columns = {};
            for (const item of jcolumns) {
                columns[item["colName"]] = {
                    colName: item["colName"],
                    dtype: item["dtype"],
                    nullCount: item["nullCount"],
                    cardinality: item["cardinality"],
                    sortedness: item["sortedness"],
                    minValue: item["minValue"],
                    maxValue: item["maxValue"],
                };
            }
            return {
                success: true,
                resRows,
                resMeta: {
                    tableName: newTable,
                    python_id: "",
                    numRows: json_res["numRows"],
                    numCols: json_res["numCols"],
                    columns: columns,
                    columnNameList: json_res["columnNameList"]
                },
                histograms: json_res["histograms"]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeGroupby executing: ${code}`, error);
            return {
                success: false,
                resRows: [],
                resMeta: {
                    tableName: table,
                    python_id: "",
                    numRows: 0,
                    numCols: 0,
                    columns: {},
                    columnNameList: []
                },
                histograms: {}
            };
        }
    }
    async exeTableMerge(leftTable, rightTable, leftCol, rightCol, how, newTable) {
        const saveDf = `__xavier_save_${leftTable} = ${leftTable}.copy()`;
        const code1 = `idg_xavier.exeTableMerge(${leftTable}, ${rightTable}, "${leftCol}", "${rightCol}", "${how}")`;
        const code2 = `idg_xavier.exeTableMerge(${leftTable}, ${rightTable}, None, None, "${how}")`;
        const code3 = `idg_xavier.exeTableMerge(${leftTable}, ${rightTable}, "${leftCol}", "${rightCol}", None)`;
        const code4 = `idg_xavier.exeTableMerge(${leftTable}, ${rightTable}, None, None, None)`;
        const code = (how !== null) ? (leftCol !== null ? code1 : code2) : (leftCol !== null ? code3 : code4); // We have ensure that leftCol and rightCol will both be null or not null
        const restoreDf = `${leftTable} = __xavier_save_${leftTable}`;
        const deleteDf = `del __xavier_save_${leftTable}`;
        const allCode = [saveDf, code, restoreDf, deleteDf].join('\n');
        try {
            const res = await this.executePythonXavier(allCode);
            const content = res['content']; // might be null
            console.log("content", content);
            const json_res = JSON.parse(content.join(""));
            const resRows = JSON.parse(json_res["rows"]);
            const jcolumns = JSON.parse(json_res["columns"]);
            const columns = {};
            for (const item of jcolumns) {
                columns[item["colName"]] = {
                    colName: item["colName"],
                    dtype: item["dtype"],
                    nullCount: item["nullCount"],
                    cardinality: item["cardinality"],
                    sortedness: item["sortedness"],
                    minValue: item["minValue"],
                    maxValue: item["maxValue"],
                };
            }
            return {
                success: true,
                resRows,
                resMeta: {
                    tableName: newTable,
                    python_id: "",
                    numRows: json_res["numRows"],
                    numCols: json_res["numCols"],
                    columns: columns,
                    columnNameList: json_res["columnNameList"]
                },
                histograms: json_res["histograms"]
            };
        }
        catch (error) {
            console.warn(`[Error caught] in exeTableMerge executing: ${code}`, error);
            return {
                success: false,
                resRows: [],
                resMeta: {
                    tableName: newTable,
                    python_id: "",
                    numRows: 0,
                    numCols: 0,
                    columns: {},
                    columnNameList: []
                },
                histograms: {}
            };
        }
    }
    async exeCompleteCode(previousCode2D, token, tableLvInfo, rowLvInfo, colLvInfo) {
        const q = JSON.stringify({
            "previousCode2D": previousCode2D,
            "token": {
                ...token,
                "type": token.type === undefined ? null : token.type,
            },
            "tableLvInfo": tableLvInfo,
            "rowLvInfo": rowLvInfo,
            "colLvInfo": colLvInfo
        });
        const code = `idg_xavier.complete("""${replaceSpecial(q)}""")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            const json_res = JSON.parse(content.join(""));
            return json_res;
        }
        catch (error) {
            console.warn(`[Error caught] in exeCompleteCode executing: ${code}`, error);
            return {
                tokenList: [],
                analyzeResp: null,
            };
        }
    }
    async exeSetGroqAPIKey(apiKey) {
        const code = `idg_xavier.setGroqAPIKey("${replaceSpecial(apiKey)}")`;
        try {
            const res = await this.executePythonXavier(code);
            const content = res['content']; // might be null
            console.log("[exeSetGroqAPIKey] response: ", content);
            const json_res = JSON.parse(content.join(""));
            if (json_res.status) {
                console.log("[exeSetGroqAPIKey] API Key set successfully");
            }
            else {
                console.warn("[exeSetGroqAPIKey] API Key set failed");
            }
        }
        catch (error) {
            console.warn(`[Error caught] in exeSetGroqAPIKey executing: ${code}`, error);
        }
    }
}


/***/ }),

/***/ "./lib/dataApi/nbcell.js":
/*!*******************************!*\
  !*** ./lib/dataApi/nbcell.js ***!
  \*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ CellAPI)
/* harmony export */ });
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_0__);

class CellAPI {
    constructor(model, index) {
        this._runSignal = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_0__.Signal(this);
        this.model = model;
        this.index = index;
    }
    // set text(text: string) {
    //     this.model.value.text = text;
    // }
    // get text() {
    //     return this.model.value.text;
    // }
    get type() {
        return this.model.type;
    }
    // an event emitted when the code/markdown changes
    // edited() {
    //     return this.model.value.changed;
    // }
    // an event emitted when this cell is run
    run() {
        return this._runSignal;
    }
    getExecutionCount() {
        if (this.type === "code") {
            return this.model.executionCount;
        }
        return null;
    }
}


/***/ }),

/***/ "./lib/dataApi/sidePanelModel.js":
/*!***************************************!*\
  !*** ./lib/dataApi/sidePanelModel.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SidePanelModel: () => (/* binding */ SidePanelModel)
/* harmony export */ });
/* harmony import */ var _nbExe__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nbExe */ "./lib/dataApi/nbExe.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils */ "./lib/utils.js");



class SidePanelModel {
    // private _language: Writable<string> = writable(undefined)
    // private _widgetIsVisible = () => false
    constructor(session) {
        this._api_key = "";
        this._observers = new Set();
        this._ready = false;
        // Style
        this._allDfSeq = [];
        this._allDfStyle = {};
        // private _selectedDFName: null | string = null;
        this._previewItems = {
            newColumns: {},
            newTables: {},
            op: null
        };
        // Data context
        this._allDfInfo = {};
        this._valueCountsCache = {};
        this._histogramBinCache = {};
        this._numColumnSampleCache = {};
        this._rowSampleCache = {};
        // private _name: Writable<string> = writable(undefined)
        this._varsInCurrentCell = []; //Writable<string[]> = writable([])
        this._executor = new _nbExe__WEBPACK_IMPORTED_MODULE_1__.NBExe(session);
        this.getCateValueCounts = this.getCateValueCounts.bind(this);
        this.getRowSampleOfOneDf = this.getRowSampleOfOneDf.bind(this);
        this.setAllDfStyle = this.setAllDfStyle.bind(this);
        this.setAllDfSeq = this.setAllDfSeq.bind(this);
        this.setAllDfInfo = this.setAllDfInfo.bind(this);
        // this.setSelectedDFName = this.setSelectedDFName.bind(this);
        this.setPreviewItems = this.setPreviewItems.bind(this);
        this.resetPreviewItems = this.resetPreviewItems.bind(this);
        this.setAPIKey = this.setAPIKey.bind(this);
    }
    get api_key() {
        return this._api_key;
    }
    get ready() {
        return this._ready;
    }
    // get loading(): Writable<boolean> {
    //     return this._loadingNewData;
    // }
    get executor() {
        return this._executor;
    }
    // Style
    get allDfStyle() {
        return this._allDfStyle;
    }
    get allDfSeq() {
        return this._allDfSeq;
    }
    // get selectedDFName(): null | string {
    //     return this._selectedDFName;
    // }
    get previewItems() {
        return this._previewItems;
    }
    // Output table, column, row level information
    // Must include all active dataframes
    get tableLvInfo() {
        const ks = Object.keys(this._allDfInfo);
        const res = {};
        ks.forEach(k => {
            res[k] = {
                numRows: this._allDfInfo[k].numRows,
                numCols: this._allDfInfo[k].numCols,
                columnNameList: this._allDfInfo[k].columnNameList
            };
        });
        return res;
    }
    // Must include all active dataframes, all columns
    get colLvInfo() {
        const res = {};
        for (const [dfName, dfInfo] of Object.entries(this._allDfInfo)) {
            res[dfName] = {};
            for (const col of dfInfo.columnNameList) {
                const dtype = dfInfo.columns[col].dtype;
                let uniqueValues = null;
                let uvCounts = null;
                let minValue = null;
                let maxValue = null;
                let sample = null;
                if (_utils__WEBPACK_IMPORTED_MODULE_2__.isCateColumn(dtype) && this._valueCountsCache[dfName] !== undefined && this._valueCountsCache[dfName][col] !== undefined) {
                    uniqueValues = this._valueCountsCache[dfName][col].map(item => item.value);
                    uvCounts = this._valueCountsCache[dfName][col].map(item => item.count);
                }
                if (_utils__WEBPACK_IMPORTED_MODULE_2__.isNumColumn(dtype)) {
                    minValue = dfInfo.columns[col].minValue;
                    maxValue = dfInfo.columns[col].maxValue;
                    if (this._numColumnSampleCache[dfName] !== undefined && this._numColumnSampleCache[dfName][col] !== undefined) {
                        sample = this._numColumnSampleCache[dfName][col];
                    }
                }
                res[dfName][col] = {
                    dtype: dtype,
                    nullCount: dfInfo.columns[col].nullCount,
                    sortedness: dfInfo.columns[col].sortedness,
                    uniqueValues: uniqueValues,
                    uvCounts: uvCounts,
                    cardinality: dfInfo.columns[col].cardinality,
                    minValue: minValue,
                    maxValue: maxValue,
                    sample: sample
                };
            }
        }
        return res;
    }
    // May not include all active dataframes
    get rowLvInfo() {
        const ks = Object.keys(this._allDfInfo);
        const res = {};
        ks.forEach(k => {
            res[k] = {
                columnNameList: this._allDfInfo[k].columnNameList,
                sampleRows: this.rowSampleCache[k] !== undefined ? this._rowSampleCache[k].rows.slice(0, 5) : null
            };
        });
        return res;
    }
    // Programming language
    // get language(): Writable<string> {
    //     return this._language
    // }
    // Session name (i.e. File name)
    // get name(): Writable<string> {
    //     return this._name
    // }
    get allDfInfo() {
        return this._allDfInfo;
    }
    get variablesInCurrentCell() {
        return this._varsInCurrentCell;
    }
    get notebook() {
        if (this._notebook === undefined) {
            throw new Error("[ProfileModel] Notebook not connected");
        }
        return this._notebook;
    }
    get currentOutputName() {
        return `_${this.notebook.mostRecentExecutionCount}`;
    }
    get valueCountsCache() {
        return this._valueCountsCache;
    }
    get histogramBinCache() {
        return this._histogramBinCache;
    }
    get numColumnSampleCache() {
        return this._numColumnSampleCache;
    }
    get rowSampleCache() {
        return this._rowSampleCache;
    }
    // private notebookIsPython(): boolean {
    //     let currentLang = get(this.language)
    //     return (currentLang === 'python' || currentLang === 'python3')
    // }
    notifyObservers() {
        this._observers.forEach(callback => callback());
    }
    addObserver(callback) {
        this._observers.add(callback);
    }
    removeObserver(callback) {
        this._observers.delete(callback);
    }
    setAllDfInfo(newInfo) {
        // Note that the style is also set.
        // 1. set style
        this._allDfStyle = _utils__WEBPACK_IMPORTED_MODULE_2__.initAllDfStyle(newInfo, this._allDfStyle, this._previewItems.newTables, this._allDfInfo);
        // 2. set seq
        this._allDfSeq = _utils__WEBPACK_IMPORTED_MODULE_2__.initAllDfSeq(newInfo, this._allDfSeq);
        // 3. set info
        this._allDfInfo = newInfo;
        this.notifyObservers();
    }
    setAllDfStyle(newStyle) {
        this._allDfStyle = newStyle;
        this.notifyObservers();
    }
    setAllDfSeq(newSeq) {
        this._allDfSeq = newSeq;
        this.notifyObservers();
    }
    // public setSelectedDFName(dfName: string) {
    //     this._selectedDFName = dfName;
    //     this.notifyObservers();
    // }
    setPreviewItems(newItems) {
        this._previewItems = newItems;
        this.notifyObservers();
    }
    resetPreviewItems() {
        this.setPreviewItems({
            newColumns: {},
            newTables: {},
            op: null
        });
    }
    setAPIKey(apiKey) {
        this._api_key = apiKey;
        this._executor.exeSetGroqAPIKey(apiKey);
        this.notifyObservers();
    }
    /**
     * connectNotebook: connect to a notebook, assumes the notebook connection is ready but might not have valid connection
     * @param notebook notebook connection
     * @param widgetIsVisible function that says if AP is visible to user
     */
    async connectNotebook(notebook, widgetIsVisible) {
        var _a;
        this._notebook = notebook;
        // this._widgetIsVisible = widgetIsVisible
        // this.resetData();
        this.executor.setSession((_a = notebook.panel) === null || _a === void 0 ? void 0 : _a.sessionContext);
        if (this.notebook.hasConnection) {
            await this.executor.session.ready;
            // this._name.set(this.executor.session.name)
            // this._language.set(this.notebook.language)
            // have to do this as arrow function or else this doesnt work
            this._notebook.changed.connect((sender, value) => {
                // when cell is run, update data
                if (value === 'cellRun') {
                    // if (this._widgetIsVisible()) {
                    this.updateRootData();
                    // }
                }
                // else if (value === "name") {
                //     this.name.set(this._notebook.name)
                // } 
                else if (value === "activeCell") {
                    // if (this._widgetIsVisible()) {
                    this.handleCellSelect();
                    // }
                }
                // else if (value === "language changed") {
                //     // e.g. kernel changes from Julia to Python
                //     this.language.set(this._notebook.language)
                //     this.resetData();
                //     if (this._widgetIsVisible()) {
                //         this.updateRootData();
                //     }
                // }
            });
            this.listenForRestart();
            this._ready = true; // this.ready.set(true);
            // if (this._widgetIsVisible()) {
            this.updateRootData();
            // }
        }
        else {
            this._ready = false; // this.ready.set(false);
            // this.name.set(undefined)
        }
    }
    async listenForRestart() {
        const scon = this.executor.session.session;
        if (!scon) {
            throw new Error("[ProfileModel] Session not connected");
        }
        const knl = scon.kernel;
        if (!knl) {
            throw new Error("[ProfileModel] Kernel not connected");
        }
        knl.statusChanged.connect((_, status) => {
            if (status.endsWith('restarting')) {
                // console.log("[ProfileModel] Kernel restarting");
                // this.resetData();
            }
        });
    }
    // public resetData() {
    //     this._columnProfiles.set(undefined);
    // }
    // public addCell(kind: 'code' | 'markdown', text: string) {
    //     if (this.notebook) {
    //         this.notebook.addCell(kind, text);
    //     }
    // }
    /**
     * Called when widget is shown.
     * Does not check if notebook is visible because visible flag set after update happens
    **/
    updateAll() {
        this.updateRootData();
        this.handleCellSelect();
    }
    /**
     * Fetch all data for UI, requires notebook to be python
    **/
    async updateRootData() {
        if (this.notebook /*&& this.notebookIsPython()*/) {
            // this._loadingNewData.set(true)
            let alldf = await this.executor.getAllDataFrames(this.currentOutputName);
            this.setAllDfInfo(alldf); // Must call before reset preview items
            // Reset the cache
            this._valueCountsCache = {};
            this._histogramBinCache = {};
            this._rowSampleCache = {};
            this.resetPreviewItems();
            const promises = [];
            for (const dfName of Object.keys(alldf)) {
                this._valueCountsCache[dfName] = {};
                this._histogramBinCache[dfName] = {};
                this._numColumnSampleCache[dfName] = {};
                const cInfo = alldf[dfName].columns;
                promises.push(this.executor.getHeadTail(dfName).then((v) => {
                    this._rowSampleCache[dfName] = {
                        condition: null,
                        rows: v
                    };
                    // this.notifyObservers();
                }));
                for (const colName of Object.keys(cInfo)) {
                    if (_utils__WEBPACK_IMPORTED_MODULE_2__.isCateColumn(cInfo[colName].dtype)) {
                        promises.push(this.executor.getCateValueCounts(dfName, colName).then((v) => {
                            this._valueCountsCache[dfName][colName] = v;
                            // this.notifyObservers();
                        }));
                    }
                    else if (_utils__WEBPACK_IMPORTED_MODULE_2__.isNumColumn(cInfo[colName].dtype)) {
                        promises.push(this.executor.getNumHistogram(dfName, colName).then((v) => {
                            this._histogramBinCache[dfName][colName] = v;
                            // this.notifyObservers();
                        }));
                        promises.push(this.executor.getNumColumnSample(dfName, colName).then((v) => {
                            this._numColumnSampleCache[dfName][colName] = v;
                            // this.notifyObservers();
                        }));
                    }
                    else {
                        console.warn(`[updateRootData] Unsupported column type ${cInfo[colName].dtype} for column ${colName}`);
                    }
                }
            }
            Promise.all(promises).then(() => {
                this.notifyObservers();
            });
        }
        else {
            // this._loadingNewData.set(false);
        }
    }
    async handleCellSelect() {
        //   console.log("[ProfileModel] handleCellSelect");
        // if (this.notebookIsPython()) {
        //     const cellCode = this._notebook?.activeCell?.text
        //     let variablesInCell: string[] = []
        //     if (!(cellCode == undefined)) {
        //         variablesInCell = await this._executor.getVariableNamesInPythonStr(cellCode)
        //     }
        //     // determine which ones are actual dataframes
        //     const profiles = get(this.columnProfiles)
        //     if (profiles) {
        //         const dfNames = Object.keys(profiles)
        //         const dfNamesInSelection = variablesInCell.filter(value => dfNames.includes(value));
        //         this.variablesInCurrentCell.set(dfNamesInSelection)
        //     }
        // }
    }
    async getCateValueCounts(dfName, colName) {
        let res = null;
        if ((this._valueCountsCache[dfName] !== undefined) && (this._valueCountsCache[dfName][colName] !== undefined)) {
            res = this._valueCountsCache[dfName][colName];
        }
        else {
            res = await this.executor.getCateValueCounts(dfName, colName);
            if (this._valueCountsCache[dfName] === undefined) {
                this._valueCountsCache[dfName] = {};
            }
            this._valueCountsCache[dfName][colName] = res;
        }
        this.notifyObservers();
        return res;
    }
    async getRowSampleOfOneDf(dfName, condition) {
        if (condition === null) {
            const rows = await this.executor.getHeadTail(dfName);
            this.rowSampleCache[dfName] = { condition, rows };
        }
        else {
            const rows = await this.executor.getRowSampleOfOneDf(dfName, condition);
            this.rowSampleCache[dfName] = { condition, rows };
        }
        this.notifyObservers();
    }
    async previewColumnFillna(fillnaTemp) {
        const { table, column, fillValue, newColumn } = fillnaTemp;
        const { newList, meta } = await this.executor.exeFillna(table, column, fillValue);
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "column_fillna"
        };
        newPreviewItems.newColumns[table] = {};
        newPreviewItems.newColumns[table][column] = {
            newColumn: newColumn,
            colMeta: meta,
            sample: newList
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewColumnRename(columnRenameTemp) {
        const { table, oldColName, newColName } = columnRenameTemp;
        const { newList, meta } = await this.executor.exeColumnRename(table, oldColName, newColName);
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "column_rename"
        };
        newPreviewItems.newColumns[table] = {};
        newPreviewItems.newColumns[table][oldColName] = {
            newColumn: newColName,
            colMeta: meta,
            sample: newList
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewStrReplace(strReplaceTemp) {
        const { table, column, oldPattern, newValue, newColumn } = strReplaceTemp;
        const rows = this._rowSampleCache[table].rows;
        const columnCells = rows.map(row => row[column]);
        const newList = await this.executor.exeStrReplace(columnCells, oldPattern, newValue);
        const meta = await this.executor.exeStrReplaceMeta(table, column, oldPattern, newValue);
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "str_replace"
        }; // @TODO: init or clone old?
        if (newPreviewItems.newColumns[table] === undefined) {
            newPreviewItems.newColumns[table] = {};
        }
        newPreviewItems.newColumns[table][column] = {
            newColumn: newColumn,
            colMeta: meta,
            sample: newList
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewTableConcat(tableConcatParam) {
        const { tables, newTable } = tableConcatParam;
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "table_concat"
        };
        tables.forEach(table => {
            newPreviewItems.newTables[table] = {
                newTable: newTable,
                dfMeta: lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(this._allDfInfo[table]),
                rows: [],
                isInSituIfSameTable: true,
                histograms: lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(this._histogramBinCache[table]),
                condValues: null
            };
        });
        this.setPreviewItems(newPreviewItems);
    }
    async previewColumnSelect(columnSelectTemp) {
        const { table, columns, newTable } = columnSelectTemp;
        if (table === newTable) {
            this.resetPreviewItems();
            return;
        }
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "column_select"
        };
        // filter dfMeta
        const oriDfMeta = this._allDfInfo[table];
        const newDfMeta = {
            tableName: newTable,
            python_id: "",
            numRows: oriDfMeta.numRows,
            numCols: columns.length,
            columnNameList: columns,
            columns: {}
        };
        columns.forEach(col => {
            newDfMeta.columns[col] = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(oriDfMeta.columns[col]);
        });
        // filter rows
        const oriRows = this._rowSampleCache[table].rows;
        const newRows = oriRows.map(row => {
            const newRow = {};
            columns.forEach(col => {
                newRow[col] = row[col];
            });
            return newRow;
        });
        // filter histograms
        const oriHistograms = this._histogramBinCache[table];
        const newHistograms = {};
        columns.forEach(col => {
            const colType = newDfMeta.columns[col].dtype;
            if (_utils__WEBPACK_IMPORTED_MODULE_2__.isNumColumn(colType)) {
                newHistograms[col] = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(oriHistograms[col]);
            }
        });
        newPreviewItems.newTables[table] = {
            newTable: newTable,
            dfMeta: newDfMeta,
            rows: newRows,
            isInSituIfSameTable: true,
            histograms: newHistograms,
            condValues: null
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewTableFilter(tableFilterParam) {
        const { table, newTable, cond, condValues } = tableFilterParam;
        const { success, resRows, resMeta, histograms } = await this.executor.exeTableFilter(table, cond, newTable);
        if (!success) {
            return;
        }
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "table_filter"
        };
        newPreviewItems.newTables[table] = {
            newTable: newTable,
            dfMeta: resMeta,
            rows: resRows,
            isInSituIfSameTable: true,
            histograms: histograms,
            condValues: condValues
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewTableSort(tableSortParam) {
        const { table, newTable, sortCols, asc } = tableSortParam;
        // broadcast asc
        const realAsc = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(asc);
        if (sortCols.length !== asc.length) {
            if (realAsc.length === 0) {
                for (let i = 0; i < sortCols.length; i++) {
                    realAsc.push(true);
                }
            }
            else if (realAsc.length === 1) {
                for (let i = 1; i < sortCols.length; i++) {
                    realAsc.push(realAsc[0]);
                }
            }
            else {
                console.warn("[previewTableSort] Length of asc does not match length of sortCols");
                return;
            }
        }
        const { success, resRows, resMeta, histograms } = await this.executor.exeTableSort(table, sortCols, asc, newTable);
        if (!success) {
            return;
        }
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "table_sort"
        };
        newPreviewItems.newTables[table] = {
            newTable: newTable,
            dfMeta: resMeta,
            rows: resRows,
            isInSituIfSameTable: false,
            histograms: histograms,
            condValues: null
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewTableMerge(tableMergeParam, allTableColumns) {
        const { leftTable, rightTable, newTable, leftCol, rightCol, how } = tableMergeParam;
        // Check if the column are null
        if ((leftCol === null && rightCol !== null) || (leftCol !== null && rightCol === null)) {
            console.warn("[previewTableMerge] One of the columns is null");
            return;
        }
        // Check if the column exists
        if (leftCol !== null && !allTableColumns[leftTable].includes(leftCol)) {
            console.warn(`[previewTableMerge] Column ${leftCol} does not exist in table ${leftTable}`);
            return;
        }
        if (rightCol !== null && !allTableColumns[rightTable].includes(rightCol)) {
            console.warn(`[previewTableMerge] Column ${rightCol} does not exist in table ${rightTable}`);
            return;
        }
        const { success, resRows, resMeta, histograms } = await this.executor.exeTableMerge(leftTable, rightTable, leftCol, rightCol, how, newTable);
        if (!success) {
            return;
        }
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "table_merge"
        };
        const realTable = rightTable === newTable ? rightTable : leftTable;
        newPreviewItems.newTables[realTable] = {
            newTable: newTable,
            dfMeta: resMeta,
            rows: resRows,
            isInSituIfSameTable: false,
            histograms: histograms,
            condValues: null
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewGroupby(groupbyParam) {
        const { tableName, newTableName, groupbyCols, selectCols, aggFunc } = groupbyParam;
        const { success, resRows, resMeta, histograms } = await this.executor.exeGroupby(tableName, groupbyCols, selectCols, aggFunc, newTableName);
        if (!success) {
            return;
        }
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "groupby"
        };
        newPreviewItems.newTables[tableName] = {
            newTable: newTableName,
            dfMeta: resMeta,
            rows: resRows,
            isInSituIfSameTable: false,
            histograms: histograms,
            condValues: null
        };
        this.setPreviewItems(newPreviewItems);
    }
    async previewColumnAdd(columnAddParam) {
        const { table, column, operator, addedColumns } = columnAddParam;
        if (addedColumns.length === 0) {
            return;
        }
        const lastAddedColumn = addedColumns[addedColumns.length - 1];
        const { newList, meta } = await this.executor.exeColumnAdd(table, column, operator, addedColumns);
        const newPreviewItems = {
            newColumns: {},
            newTables: {},
            op: "column_add"
        };
        newPreviewItems.newColumns[table] = {};
        newPreviewItems.newColumns[table][lastAddedColumn] = {
            newColumn: column,
            colMeta: meta,
            sample: newList
        };
        this.setPreviewItems(newPreviewItems);
    }
}


/***/ }),

/***/ "./lib/index.js":
/*!**********************!*\
  !*** ./lib/index.js ***!
  \**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/completer */ "webpack/sharing/consume/default/@jupyterlab/completer");
/* harmony import */ var _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_completer__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/notebook */ "webpack/sharing/consume/default/@jupyterlab/notebook");
/* harmony import */ var _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _sidePanel_Wrapper_SidePanel__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sidePanel/Wrapper/SidePanel */ "./lib/sidePanel/Wrapper/SidePanel.js");
/* harmony import */ var _xavierCompleter_customconnector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./xavierCompleter/customconnector */ "./lib/xavierCompleter/customconnector.js");
/* harmony import */ var _dataApi_nbApi__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./dataApi/nbApi */ "./lib/dataApi/nbApi.js");
/* harmony import */ var _dataApi_sidePanelModel__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dataApi/sidePanelModel */ "./lib/dataApi/sidePanelModel.js");






/**
 * Initialization data for the extension.
 */
const extension = {
    id: '@xavier/idgxavier:completion',
    description: 'Minimal JupyterLab extension setting up the completion.',
    autoStart: true,
    requires: [_jupyterlab_completer__WEBPACK_IMPORTED_MODULE_0__.ICompletionProviderManager, _jupyterlab_notebook__WEBPACK_IMPORTED_MODULE_1__.INotebookTracker],
    activate: async (app, completionManager, notebooks) => {
        const dataModel = new _dataApi_sidePanelModel__WEBPACK_IMPORTED_MODULE_2__.SidePanelModel(null); // Null session. The session will be set when a notebook is connected. See `SidePanel.connectNotebook()`
        const panel = new _sidePanel_Wrapper_SidePanel__WEBPACK_IMPORTED_MODULE_3__.SidePanel(dataModel);
        app.shell.add(panel, 'right', { rank: 1000 });
        // emitted when the user's notebook changes, null if all notebooks close
        // Note: SidePanel contains NBApi contains NotebookPanel. NotebookTracker contains NotebookPanel
        notebooks.currentChanged.connect((_, widget) => {
            const na = new _dataApi_nbApi__WEBPACK_IMPORTED_MODULE_4__.NBApi(widget);
            na.ready.then(async () => {
                await panel.connectNotebook(na);
            });
        });
        // @TODO
        const allProviders = completionManager.getProviders();
        const contextProvider = allProviders.get("CompletionProvider:context");
        const kernelProvider = allProviders.get("CompletionProvider:kernel");
        const ccp = new _xavierCompleter_customconnector__WEBPACK_IMPORTED_MODULE_5__.XavierCompleterProvider(notebooks, dataModel, contextProvider, kernelProvider);
        completionManager.registerProvider(ccp);
        console.log('@idgxavier: JupyterLab custom completer extension is activated!', ccp, app, completionManager, notebooks);
    }
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (extension);


/***/ }),

/***/ "./lib/sidePanel/Metadata/CateColTitle.js":
/*!************************************************!*\
  !*** ./lib/sidePanel/Metadata/CateColTitle.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CateColTitle: () => (/* binding */ CateColTitle)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

class CateColTitle extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
    }
    get realBasicPx() {
        return this.props.basicPx === undefined ? 2 : this.props.basicPx;
    }
    render() {
        // const isShowSelectIcon = this.props.dfMode === ViewMode.FILTER_COLUMN;
        // // const nullPercent = this.props.nullCount / this.props.numRows * 100;
        // // let percentage_str = `${nullPercent.toFixed(1)}%`;
        // const dfName = this.props.dfName;
        // const colName = this.props.colName;
        // const multiSelectIconDiv = isShowSelectIcon ? (
        //   <MultiSelectIcon  status={this.props.isColSelect ? "full" : "empty"}
        //                     handleIconClick={(e) => this.props.onColSelectIconClick(e, dfName, colName) } />
        // ) : null;
        // let iconWidthUnit = 1;
        // iconWidthUnit += multiSelectIconDiv === null ? 0 : 1;
        // iconWidthUnit += filterValueIconDiv === null ? 0 : 1;
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-histogram", style: { width: '100%' } },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-histogram-rect", style: {
                        width: `${100 * this.props.cardinality / this.props.numRows}%`,
                        minWidth: `${this.props.cardinality === 0 ? 0 : this.realBasicPx}px`,
                    } }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-histogram-text" },
                    "|",
                    this.props.cardinality,
                    "|")))
        // </div>
        );
    }
}
;


/***/ }),

/***/ "./lib/sidePanel/Metadata/CateItem.js":
/*!********************************************!*\
  !*** ./lib/sidePanel/Metadata/CateItem.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CateItem: () => (/* binding */ CateItem)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _assets_MultiSelectIcon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../assets/MultiSelectIcon */ "./lib/assets/MultiSelectIcon.js");


class CateItem extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
    }
    render() {
        const dfName = this.props.dfName;
        const colName = this.props.colName;
        // const cnt = this.props.vc.count;
        const val = this.props.vc.value;
        // const ratio = 100 * cnt / this.props.numRows;
        // const ratioStr = ratio < 0.1 ? `${cnt} (< 0.1%)` : `${cnt} (${ratio.toFixed(1)}%)`;
        const multiSelectIconDiv = this.props.isFilterValue ? (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_assets_MultiSelectIcon__WEBPACK_IMPORTED_MODULE_1__.MultiSelectIcon, { status: this.props.isSelect ? "full" : "empty", handleIconClick: (e) => this.props.onCateSelectIconClick(e, dfName, colName, val) })) : null;
        let iconWidthUnit = 0;
        iconWidthUnit += multiSelectIconDiv !== null ? 1 : 0;
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-cate", key: `xavier-${dfName}-${colName}-${val}` },
            multiSelectIconDiv,
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-name xavier-mv-cate-value", style: {
                    width: `calc(70% - 5px - ${iconWidthUnit} * var(--xavier-icon-width))`
                } }, val)));
    }
}


/***/ }),

/***/ "./lib/sidePanel/Metadata/DFTitle.js":
/*!*******************************************!*\
  !*** ./lib/sidePanel/Metadata/DFTitle.js ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   DFTitle: () => (/* binding */ DFTitle)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _assets_AddContextIcon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../assets/AddContextIcon */ "./lib/assets/AddContextIcon.js");


class DFTitle extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.iconClickHandler = this.iconClickHandler.bind(this);
        this.titleClickHandler = this.titleClickHandler.bind(this);
    }
    iconClickHandler(e) {
        if (this.props.onUpdateDCIconClick === undefined) {
            return;
        }
        this.props.onUpdateDCIconClick(e, "table", "toggle", { dfName: this.props.dfName });
    }
    titleClickHandler(e) {
        if (this.props.onTitleClick === undefined) {
            return;
        }
        this.props.onTitleClick(e, this.props.dfName);
    }
    render() {
        const oldShapeStr = `${this.props.oldNumRows} × ${this.props.oldNumCols}`;
        const curShapeStr = `${this.props.numRows} × ${this.props.numCols}`;
        const shapeStr = (this.props.oldNumRows === undefined || this.props.oldNumCols === undefined) ? curShapeStr : `${oldShapeStr} -> ${curShapeStr}`;
        const addSign = this.props.isFold ? "+" : "-";
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_assets_AddContextIcon__WEBPACK_IMPORTED_MODULE_1__.AddContextIcon, { handleIconClick: this.iconClickHandler, sign: addSign }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-name-wrapper", style: { width: `calc(100% - var(--xavier-icon-width))` }, onClick: this.titleClickHandler },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-name" }, this.props.dfName),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mdt-shape", style: {
                        color: shapeStr.includes("NaN") ? "red" : "#000"
                    } }, shapeStr))));
    }
}


/***/ }),

/***/ "./lib/sidePanel/Metadata/MetadataView.js":
/*!************************************************!*\
  !*** ./lib/sidePanel/Metadata/MetadataView.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   MetadataView: () => (/* binding */ MetadataView)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Wrapper/SidePanelReactStore */ "./lib/sidePanel/Wrapper/SidePanelReactStore.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _DFTitle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DFTitle */ "./lib/sidePanel/Metadata/DFTitle.js");
/* harmony import */ var _SpreadSheet_SSRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../SpreadSheet/SSRenderer */ "./lib/sidePanel/SpreadSheet/SSRenderer.js");
/* harmony import */ var _SpreadSheet_SpreadSheet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../SpreadSheet/SpreadSheet */ "./lib/sidePanel/SpreadSheet/SpreadSheet.js");








class MetadataView extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {
            _allDfStyle: initAllDfStyleForMV(props),
            // _allDfMode: initAllDfMode(props.allDfInfo),
            _allColMode: initAllColMode(props.allDfInfo),
            _canShowFloatSS: false,
        };
        this.onTitleClick = this.onTitleClick.bind(this);
        this.onUpdateDCIconClick = this.onUpdateDCIconClick.bind(this);
        // this.onFilterValueIconClick = this.onFilterValueIconClick.bind(this);
        this.dfFoldToggle = this.dfFoldToggle.bind(this);
        // this.columnFoldToggle = this.columnFoldToggle.bind(this);
        this.renderDfList = this.renderDfList.bind(this);
        this.onSampleBtnClick = this.onSampleBtnClick.bind(this);
    }
    get realAllDfStyle() {
        const s1 = this.props.allDfStyle;
        const s2 = this.state._allDfStyle;
        if (this.props.isLive && s1 === null) {
            console.warn("[realAllDfStyle] allDfStyle is null.");
            return s2;
        }
        else if (this.props.isLive && s1 !== null) {
            return s1;
        }
        else {
            return s2;
        }
    }
    get realAllDfSeq() {
        return this.props.isLive ? this.props.allDfSeq : Object.keys(this.props.allDfInfo);
    }
    onTitleClick(e, dfName) {
        e.stopPropagation();
        // this.props.setSelectedDFName(dfName);
    }
    // columnFoldToggle(dfName: string, colName: string) {
    //   const newAllDfStyle = {...this.state._allDfStyle};
    //   const colObj = newAllDfStyle[dfName].columns[colName];
    //   colObj.isFold = !colObj.isFold;
    //   if (this.props.isLive) {
    //     this.props.setAllDfStyle(newAllDfStyle);
    //   } else {
    //     this.setState({
    //       _allDfStyle: newAllDfStyle
    //     });
    //   }
    // }
    dfFoldToggle(dfName) {
        const allDfStyle = { ...this.state._allDfStyle }; // Create a shallow copy
        allDfStyle[dfName].isFold = !allDfStyle[dfName].isFold;
        if (this.props.isLive) {
            this.props.setAllDfStyle(allDfStyle);
        }
        else {
            this.setState({
                _allDfStyle: allDfStyle
            });
        }
    }
    async onUpdateDCIconClick(e, channel, op, ctx) {
        e.stopPropagation();
        if (op !== "toggle") {
            console.error("[onUpdateDCIconClick] Unsupported operation.");
            return;
        }
        if (channel === "table") {
            if (ctx.dfName === undefined) {
                console.error("[onUpdateDCIconClick] DataFrame name is not provided.");
                return;
            }
            this.dfFoldToggle(ctx.dfName);
        }
        else {
            // channel is column
            console.warn("[onUpdateDCIconClick] Column operation is not supported yet.");
            // if (ctx.dfName === undefined || ctx.colName === undefined) {
            //   console.error("[onUpdateDCIconClick] DataFrame name / Column name is not provided.");
            //   return;
            // }
            // const allDfInfo = this.props.allDfInfo;
            // const dtype = allDfInfo[ctx.dfName].columns[ctx.colName].dtype;
            // if (utils.isCateColumn(dtype)) {
            //   await this.props.getCateValueCounts(ctx.dfName, ctx.colName);
            // }
            // this.columnFoldToggle(ctx.dfName, ctx.colName);
        }
    }
    // onFilterValueIconClick(e: React.MouseEvent, dfName: string, colName: string) {
    //   e.stopPropagation();
    //   const colObj = this.state._allColMode[dfName][colName];
    //   const newAllColMode = {...this.state._allColMode};
    //   newAllColMode[dfName][colName] = (colObj === constant.ViewMode.INIT ? constant.ViewMode.FILTER_VALUE : constant.ViewMode.INIT);
    //   this.setState({
    //     _allColMode: newAllColMode
    //   });
    // }
    onSampleBtnClick(dfName) {
        const newAllDfStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(this.realAllDfStyle);
        newAllDfStyle[dfName].isShowRows = !newAllDfStyle[dfName].isShowRows;
        this.props.setAllDfStyle(newAllDfStyle);
    }
    canRenderExtraTablePreview() {
        // Must support multi schema
        const cond1 = _utils__WEBPACK_IMPORTED_MODULE_2__.isSupportMultiSchemaOp(this.props.previewItems.op);
        if (!cond1) {
            return { yes: false, newDfName: null };
        }
        // Must exist new tables
        const nt = this.props.previewItems.newTables;
        const tbs = Object.keys(nt);
        if (tbs.length === 0) {
            return { yes: false, newDfName: null };
        }
        // Must have new table
        const newTableName = nt[tbs[0]].newTable; // @TODO: we assume that there is only one new table
        const allDfInfo = this.props.allDfInfo;
        if (!(newTableName in allDfInfo)) {
            return { yes: true, newDfName: newTableName };
        }
        return { yes: false, newDfName: null };
    }
    renderExtraTablePreview() {
        const { yes, newDfName } = this.canRenderExtraTablePreview();
        if (!yes || !newDfName) {
            return null;
        }
        const { num_rows, num_cols } = _utils__WEBPACK_IMPORTED_MODULE_2__.calcPreviewRowsCols(this.props.previewItems.newTables);
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-df" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_DFTitle__WEBPACK_IMPORTED_MODULE_3__.DFTitle, { dfName: newDfName, numRows: num_rows, numCols: num_cols, isFold: false }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SpreadSheet_SpreadSheet__WEBPACK_IMPORTED_MODULE_4__["default"], { name: "table-view-ss-preview-" + newDfName, header: [], table: [], maxHeight: _constant__WEBPACK_IMPORTED_MODULE_5__.SSMaxHeight, alternateColor: _constant__WEBPACK_IMPORTED_MODULE_5__.SSAlternateColor, cellMaxWidth: _constant__WEBPACK_IMPORTED_MODULE_5__.SSCellMaxWidth, cellMinWidth: _constant__WEBPACK_IMPORTED_MODULE_5__.SSCellMaxWidth, tableRowHeight: _constant__WEBPACK_IMPORTED_MODULE_5__.SSTableRowHeight, headerFontSize: 12, tableFontSize: 12, overflowOption: "hidden", onlyPreviewSchema: true, dfName: newDfName, selectCond: null, valueCounts: this.props.valueCounts, rowSampleCache: this.props.rowSampleCache, setAllDfStyle: this.props.setAllDfStyle, getRowSampleOfOneDf: this.props.getRowSampleOfOneDf, previewItems: this.props.previewItems })));
    }
    renderDfList() {
        const allDfInfo = this.props.allDfInfo;
        const allDfStyle = this.realAllDfStyle;
        const dfNameList = this.realAllDfSeq;
        const op = this.props.previewItems.op;
        const nt = this.props.previewItems.newTables;
        const extraPreview = this.renderExtraTablePreview();
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-df-list" },
            dfNameList.map((v) => {
                let num_rows = allDfInfo[v].numRows;
                let num_cols = allDfInfo[v].numCols;
                const yes_fold = this.realAllDfStyle[v].isFold;
                let oldNumRows = undefined;
                let oldNumCols = undefined;
                const tables = Object.keys(nt);
                if (_utils__WEBPACK_IMPORTED_MODULE_2__.isSupportMultiSchemaOp(op) && tables.length > 0 && tables.every(t => nt[t].isInSituIfSameTable) && nt[tables[0]].newTable === v) {
                    // Four conditions:
                    // 1. Support multi schema operation
                    // 2. There are new tables
                    // 3. All new tables are in situ
                    // 4. The new table is the current table (We assume that there is only one new table)
                    oldNumRows = num_rows;
                    oldNumCols = num_cols;
                    const cprc = _utils__WEBPACK_IMPORTED_MODULE_2__.calcPreviewRowsCols(nt);
                    num_rows = cprc.num_rows;
                    num_cols = cprc.num_cols;
                }
                const SSRenderDiv = (allDfStyle[v].isFold ? null :
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SpreadSheet_SSRenderer__WEBPACK_IMPORTED_MODULE_6__.SSRenderer, { dfName: v, allDfInfo: allDfInfo, allDfStyle: this.realAllDfStyle, allColMode: this.state._allColMode, histogramBin: this.props.histogramBin, valueCounts: this.props.valueCounts, rowSampleCache: this.props.rowSampleCache, previewItems: this.props.previewItems, setAllDfStyle: this.props.setAllDfStyle, getRowSampleOfOneDf: this.props.getRowSampleOfOneDf, onSampleBtnClick: this.onSampleBtnClick }));
                return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-df", key: "xavier-df-" + v },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_DFTitle__WEBPACK_IMPORTED_MODULE_3__.DFTitle, { dfName: v, numRows: num_rows, numCols: num_cols, oldNumRows: oldNumRows, oldNumCols: oldNumCols, isFold: yes_fold, onUpdateDCIconClick: this.onUpdateDCIconClick, onTitleClick: this.onTitleClick }),
                    SSRenderDiv);
            }),
            extraPreview));
    }
    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.allDfInfo !== this.props.allDfInfo) {
            const newDfStyle = initAllDfStyleForMV(nextProps, this.state._allDfStyle);
            // const newDfMode = initAllDfMode(nextProps.allDfInfo);
            const newColMode = initAllColMode(nextProps.allDfInfo);
            const newDfColSelect = initAllDfColSelect(nextProps.allDfInfo);
            this.setState({
                _allDfStyle: newDfStyle,
                // _allDfMode: newDfMode,
                _allColMode: newColMode
            });
            this.context.setAllDfColSelect(newDfColSelect);
            this.context.setAllDfCateColItemSearch({});
        }
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-metadata-view" }, this.renderDfList()));
    }
}
MetadataView.contextType = _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_7__.ReactStore;

;
// function initAllDfMode(allDfInfo: IDFInfoAll) {
//   const res: IDfMode = {};
//   for (const dfName in allDfInfo) {
//     res[dfName] = constant.ViewMode.INIT;
//   }
//   return res;
// }
function initAllColMode(allDfInfo) {
    const res = {};
    for (const dfName in allDfInfo) {
        res[dfName] = {};
        for (const colName of allDfInfo[dfName].columnNameList) {
            res[dfName][colName] = _constant__WEBPACK_IMPORTED_MODULE_5__.ViewMode.INIT;
        }
    }
    return res;
}
function initAllDfColSelect(allDfInfo) {
    const res = {};
    for (const dfName in allDfInfo) {
        res[dfName] = {};
        for (const colName of allDfInfo[dfName].columnNameList) {
            res[dfName][colName] = true;
        }
    }
    return res;
}
function initAllDfStyleForMV(nextProps, oldAllDfStyle = undefined) {
    return (nextProps.isLive && nextProps.allDfStyle !== null) ? nextProps.allDfStyle : _utils__WEBPACK_IMPORTED_MODULE_2__.initAllDfStyle(nextProps.allDfInfo, oldAllDfStyle);
}


/***/ }),

/***/ "./lib/sidePanel/Metadata/NumColTitle.js":
/*!***********************************************!*\
  !*** ./lib/sidePanel/Metadata/NumColTitle.js ***!
  \***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NumColTitle: () => (/* binding */ NumColTitle)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");



class NumColTitle extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.renderHistBars = this.renderHistBars.bind(this);
    }
    get realBasicPercent() {
        return this.props.basicPercent === undefined ? 0.05 : this.props.basicPercent;
    }
    renderHistBars() {
        const dfName = this.props.dfName;
        const colName = this.props.colName;
        const _maxCount = lodash__WEBPACK_IMPORTED_MODULE_1___default().max(this.props.bins.map(bin => bin.count));
        const maxCount = _maxCount === undefined ? 1 : _maxCount;
        const width = `${1 / this.props.bins.length * 100}%`;
        return this.props.bins.map((bin) => {
            const height = this.realBasicPercent + (1 - this.realBasicPercent) * (bin.count / maxCount);
            const heightStr = `${(height) * 100}%`;
            return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: `xavier-${dfName}-${colName}-hist-bar-${bin.low}-${bin.high}`, className: "xavier-mct-histogram-bar", style: {
                    width: width,
                    height: heightStr,
                    backgroundColor: '#fca5a5', //highLight === false? '#FCF2F2' : '#ffcccc', between FCF2FC and FFCCCC
                } }));
        });
    }
    render() {
        // const isShowSelectIcon = this.props.dfMode === ViewMode.FILTER_COLUMN;
        const minValueStr = this.props.minValue === null ? "NaN" : typeof this.props.minValue === "string" ? this.props.minValue : _utils__WEBPACK_IMPORTED_MODULE_2__.formatNumber(this.props.minValue);
        const maxValueStr = this.props.maxValue === null ? "NaN" : typeof this.props.maxValue === "string" ? this.props.maxValue : _utils__WEBPACK_IMPORTED_MODULE_2__.formatNumber(this.props.maxValue);
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-histogram", style: { width: "100%" } },
                this.renderHistBars(),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-histogram-text" },
                    minValueStr,
                    " ~ ",
                    maxValueStr)))
        // </div>
        );
    }
}


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/Cell.js":
/*!*******************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/Cell.js ***!
  \*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");


const realValueHandler = (cv) => {
    if (cv === undefined || cv === null) {
        return "NaN";
    }
    else if (cv === "") {
        return "<Empty String>";
    }
    if (cv.value != undefined) {
        if (!cv.value.lower) {
            return String((0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv.value));
        }
        else if (cv.value.isRightOpen == true) {
            return `[${(0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv.value.lower)}, ${(0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv.value.upper)})`;
        }
        else {
            return `[${(0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv.value.lower)}, ${(0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv.value.upper)}]`;
        }
    }
    else if (typeof cv === "string" || typeof cv === "number") {
        return String((0,_utils__WEBPACK_IMPORTED_MODULE_1__.toFix)(cv));
    }
    // Can add more cases here for other types of cell values
    return String(cv);
};
const SpreadsheetCell = (props) => {
    const p_cellBold = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (props.cellBold !== undefined ? props.cellBold : false), [props.cellBold]);
    const p_contenteditable = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (props.contenteditable !== undefined ? props.contenteditable : false), [props.contenteditable]);
    const [editEn, setEditEn] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [e_target, setE_target] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null);
    const [storedStyle, setStoredStyle] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({});
    const realValue = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => realValueHandler(props.cellValue), [props.cellValue]);
    const givenIdRef = react__WEBPACK_IMPORTED_MODULE_0___default().createRef();
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        if (editEn && e_target) {
            e_target.focus();
        }
    }, [editEn, e_target]);
    const commitEdit = (e) => {
        setEditEn(false);
        let splitres = props.givenId.split("_");
        if (splitres[splitres.length - 3] !== "cell" ||
            !(0,_utils__WEBPACK_IMPORTED_MODULE_1__.isNumeric)(splitres[splitres.length - 1]) ||
            !(0,_utils__WEBPACK_IMPORTED_MODULE_1__.isNumeric)(splitres[splitres.length - 2])) {
            console.error("commitEdit: Invalid cell ID!");
            return;
        }
        let col = Number(splitres[splitres.length - 1]);
        let row = Number(splitres[splitres.length - 2]);
        let tableName = splitres.slice(0, splitres.length - 3).join("_");
        if (props.cellChange) {
            props.cellChange({
                oldValue: realValue,
                newValue: e.target.innerText,
                tableName, row, col
            });
        }
        if (!givenIdRef.current) {
            console.warn("[commitEdit] givenIdRef is null");
            return;
        }
        const s = givenIdRef.current.style;
        if (storedStyle.overflow !== undefined) {
            s.overflow = storedStyle.overflow;
        }
        if (storedStyle.textOverflow !== undefined) {
            s.textOverflow = storedStyle.textOverflow;
        }
        if (storedStyle.overflowX !== undefined) {
            s.overflowX = storedStyle.overflowX;
        }
        if (storedStyle.overflowY !== undefined) {
            s.overflowY = storedStyle.overflowY;
        }
    };
    const enableEdit = (e) => {
        e.stopPropagation();
        if (p_contenteditable) {
            setEditEn(true);
            setE_target(e.target);
            if (!givenIdRef.current) {
                console.warn("[enableEdit] givenIdRef is null");
                return;
            }
            const s = givenIdRef.current.style;
            setStoredStyle({
                overflow: s.overflow,
                textOverflow: s.textOverflow,
                overflowX: s.overflowX,
                overflowY: s.overflowY,
            });
            s.overflow = "";
            s.textOverflow = "";
            s.overflowX = "overlay";
            s.overflowY = "hidden";
        }
        else if (props.onDblclick) {
            props.onDblclick();
        }
    };
    const cellClassName = `cell ${p_cellBold ? 'text-bold' : ''} ${((props.cellValue === undefined || props.cellValue === null || props.cellValue === '') && !(props.cellStyle && props.cellStyle.color === "transparent")) ? 'xavier-cell-empty' : ''}`;
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { id: props.givenId, ref: givenIdRef, className: cellClassName, style: props.cellStyle, contentEditable: p_contenteditable && editEn, onMouseDown: e => e.stopPropagation(), 
        // onClick={e => e.stopPropagation()}
        onDoubleClick: enableEdit, onBlur: commitEdit }, realValue));
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SpreadsheetCell);


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/FilterListRenderer.js":
/*!*********************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/FilterListRenderer.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FilterListRenderer: () => (/* binding */ FilterListRenderer)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Wrapper/SidePanelReactStore */ "./lib/sidePanel/Wrapper/SidePanelReactStore.js");
/* harmony import */ var _assets_MultiSelectIcon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../assets/MultiSelectIcon */ "./lib/assets/MultiSelectIcon.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Metadata_CateItem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Metadata/CateItem */ "./lib/sidePanel/Metadata/CateItem.js");
/* harmony import */ var _RangeFilter__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./RangeFilter */ "./lib/sidePanel/SpreadSheet/RangeFilter.js");








class FilterListRenderer extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {};
        this.onsearchCateItem = this.onsearchCateItem.bind(this);
        this.onCateSelectIconClick = this.onCateSelectIconClick.bind(this);
        this.onMultiSelectIconClick = this.onMultiSelectIconClick.bind(this);
        this.renderMutilFilter = this.renderMutilFilter.bind(this);
        this.renderCateItemList = this.renderCateItemList.bind(this);
        this.onNumRangeSelectIconClick = this.onNumRangeSelectIconClick.bind(this);
    }
    onsearchCateItem(e, dfName, colName) {
        // Read input value
        e.stopPropagation();
        const inputText = e.currentTarget.value;
        const newAllDfCateColItemSearch = { ...this.context.allDfCateColItemSearch };
        if (newAllDfCateColItemSearch[dfName] === undefined) {
            newAllDfCateColItemSearch[dfName] = {};
        }
        newAllDfCateColItemSearch[dfName][colName] = inputText;
        this.context.setAllDfCateColItemSearch(newAllDfCateColItemSearch);
    }
    async onMultiSelectIconClick(e, dfName, colName) {
        e.stopPropagation();
        const dfCache = this.props.rowSampleCache[dfName];
        const vc = this.props.valueCounts[dfName];
        if (dfCache === undefined || vc === undefined) {
            console.warn("[onMultiSelectIconClick] rowSampleCache is undefined or valueCounts is undefined.");
            return;
        }
        let newCond = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(dfCache.condition);
        if (newCond === null) { // previously, full table is selected
            newCond = {
                [colName]: {
                    dfName, colName,
                    cateSelect: [],
                    rangeSelect: null // don't care
                }
            };
            await this.props.getRowSampleOfOneDf(dfName, newCond);
            return;
        }
        else if (newCond[colName] === undefined) { // previously, we select all values of this column
            newCond[colName] = {
                dfName, colName,
                cateSelect: [],
                rangeSelect: null // don't care
            };
            await this.props.getRowSampleOfOneDf(dfName, newCond);
            return;
        }
        const newCondCol = newCond[colName];
        if (newCondCol.cateSelect === null || newCondCol.cateSelect.length === vc[colName].length) { // previously, we select all values of this column
            newCond[colName].cateSelect = []; // empty array means select nothing      
        }
        else { // previously, we select some values of this column
            newCond[colName].cateSelect = null;
        }
        console.log("[onCateSelectIconClick] newAllDfRowSelect:", newCond);
        await this.props.getRowSampleOfOneDf(dfName, newCond);
    }
    async onNumRangeSelectIconClick(e, dfName, colName, lowerBundle, upperBundle) {
        e.stopPropagation();
        const startOpen = false; //闭区间
        const endOpen = false; //闭区间 
        const dfCache = this.props.rowSampleCache[dfName];
        const vc = this.props.valueCounts[dfName];
        if (dfCache === undefined || vc === undefined) {
            console.warn("[onNumRangeSelectIconClick] rowSampleCache is undefined or valueCounts is undefined.");
            return;
        }
        let newCond = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(dfCache.condition);
        if (newCond === null) { // previously, full table is selected
            newCond = {
                [colName]: {
                    dfName, colName,
                    cateSelect: null,
                    rangeSelect: [{ startOpen: startOpen, endOpen: endOpen, start: lowerBundle, end: upperBundle }]
                }
            };
        }
        else if (newCond[colName] === undefined) { // previously, we select all values of this column
            newCond[colName] = {
                dfName, colName,
                cateSelect: null,
                rangeSelect: [{ startOpen: startOpen, endOpen: endOpen, start: lowerBundle, end: upperBundle }]
            };
        }
        const newCondCol = newCond[colName];
        if (newCondCol.rangeSelect === null) { // previously, we select all values of this column
            newCondCol.rangeSelect = [{ startOpen: startOpen, endOpen: endOpen, start: lowerBundle, end: upperBundle }];
        }
        else { // previously, we select some values of this column
            newCondCol.rangeSelect = [{ startOpen: startOpen, endOpen: endOpen, start: lowerBundle, end: upperBundle }];
        }
        console.log("[onNumRangeSelectIconClick] newAllDfRowSelect:", newCond);
        await this.props.getRowSampleOfOneDf(dfName, newCond);
    }
    async onCateSelectIconClick(e, dfName, colName, cate) {
        e.stopPropagation();
        const dfCache = this.props.rowSampleCache[dfName];
        const vc = this.props.valueCounts[dfName];
        if (dfCache === undefined || vc === undefined) {
            console.warn("[onCateSelectIconClick] rowSampleCache is undefined or valueCounts is undefined.");
            return;
        }
        let newCond = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(dfCache.condition);
        if (newCond === null) { // previously, full table is selected
            newCond = {
                [colName]: {
                    dfName, colName,
                    cateSelect: vc[colName].map(v => v.value).filter(v => v !== cate),
                    rangeSelect: null // don't care
                }
            };
        }
        else if (newCond[colName] === undefined) { // previously, we select all values of this column
            newCond[colName] = {
                dfName, colName,
                cateSelect: vc[colName].map(v => v.value).filter(v => v !== cate),
                rangeSelect: null // don't care
            };
        }
        const newCondCol = newCond[colName];
        if (newCondCol.cateSelect === null) { // previously, we select all values of this column
            newCondCol.cateSelect = vc[colName].map(v => v.value).filter(v => v !== cate); // exclude the selected value
        }
        else { // previously, we select some values of this column
            newCondCol.cateSelect = newCondCol.cateSelect.filter((v) => v !== cate); // exclude the selected value
        }
        console.log("[onCateSelectIconClick] newAllDfRowSelect:", newCond);
        await this.props.getRowSampleOfOneDf(dfName, newCond);
    }
    renderMutilFilter(dfName, colName) {
        var _a;
        let allSelect = false;
        const rc = this.props.rowSampleCache[dfName];
        const vc = this.props.valueCounts[dfName];
        if (rc === undefined || vc === undefined) {
            console.warn("[renderMutilFilter] valueCounts is undefined.");
            allSelect = true;
        }
        else if (rc.condition === null) {
            allSelect = true;
        }
        else if (rc.condition[colName] === undefined) {
            allSelect = true;
        }
        else if (rc.condition[colName].cateSelect === null) {
            allSelect = true;
        }
        else if (((_a = rc.condition[colName].cateSelect) === null || _a === void 0 ? void 0 : _a.length) === vc[colName].length) {
            allSelect = true;
        }
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-col" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-wrapper" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_assets_MultiSelectIcon__WEBPACK_IMPORTED_MODULE_2__.MultiSelectIcon, { status: allSelect ? "full" : "empty", handleIconClick: (e) => this.onMultiSelectIconClick(e, dfName, colName) }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-name-wrapper", style: { width: "calc(100% - 2 * var(--xavier-icon-width))" } },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mct-name" }, "Select all columns")))));
    }
    renderCateItemList(dfName, colName, itemList, cateSearch, cateSelect, isFilterValue) {
        if (cateSearch !== undefined) {
            itemList = itemList.filter((v) => {
                const itemV = String(v.value).toLowerCase();
                const searchV = cateSearch.toLowerCase();
                return itemV.includes(searchV);
            });
        }
        // console.log('cateSelect:',cateSelect);
        const cateItemDivList = itemList.map((v) => {
            const isSelect = cateSelect === null ? true : cateSelect.includes(String(v.value));
            return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Metadata_CateItem__WEBPACK_IMPORTED_MODULE_3__.CateItem, { dfName: dfName, colName: colName, vc: v, onCateSelectIconClick: this.onCateSelectIconClick, 
                // cateSearch={cateSearch}
                // 默认显示
                isFilterValue:  true || 0, isSelect: isSelect }));
        });
        return cateItemDivList;
    }
    render() {
        const dfName = this.props.dfName;
        const colName = this.props.colName;
        // const numRows = this.props.allDfInfo[dfName].numRows;
        // console.log('dfName:',dfName,'colName:',colName);
        // console.log(`allDfRowSelect[dfName] :${allDfRowSelect[dfName]}`);
        const cateSelect = (this.props.selectCond !== null) && (this.props.selectCond[colName] !== undefined) ? this.props.selectCond[colName].cateSelect : null;
        // console.log(`allDfRowSelect[dfName] :${allDfRowSelect[dfName]}. allDfRowSelect[dfName][colName] :${allDfRowSelect[dfName][colName]}. cateSelect :${cateSelect}`);
        const isFilterValue = this.props.allColMode[dfName][colName] === _constant__WEBPACK_IMPORTED_MODULE_4__.ViewMode.FILTER_VALUE;
        const colInfoObj = this.props.allDfInfo[dfName].columns[colName];
        const isNumColumn = _utils__WEBPACK_IMPORTED_MODULE_5__.isNumColumn(colInfoObj.dtype);
        const dfObj = this.props.valueCounts[dfName];
        const colObj = dfObj !== undefined ? dfObj[colName] : undefined;
        let itemList = colObj !== undefined ? colObj : [];
        const cateSearchDf = this.context.allDfCateColItemSearch[dfName];
        const cateSearch = cateSearchDf !== undefined ? cateSearchDf[colName] : undefined;
        // const isShowSelectIcon = _allDfMode[dfName] === constant.ViewMode.FILTER_COLUMN;
        //渲染数字列的过滤器
        let minValue = this.props.allDfInfo[dfName].columns[colName].minValue;
        let maxValue = this.props.allDfInfo[dfName].columns[colName].maxValue;
        const dfCache = this.props.rowSampleCache[dfName];
        if (dfCache !== undefined) {
            let cond = dfCache.condition;
            if (cond !== null) {
                const colCond = cond[colName];
                if (colCond !== null && colCond !== undefined) {
                    if (colCond.rangeSelect !== null) {
                        const rangeSelect = colCond.rangeSelect;
                        minValue = rangeSelect[0].start;
                        maxValue = rangeSelect[0].end;
                    }
                }
            }
        }
        return (
        // onMouseLeave={() => setSearchInputActive(null)}
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-itemlist-wrapper" },
            !isNumColumn &&
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-search-bar" },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "text", className: "xavier-mv-search-input", value: cateSearch, placeholder: "Search values...", onInput: (e) => this.onsearchCateItem(e, dfName, colName) })),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-cate-list" },
                !isNumColumn && true ? this.renderMutilFilter(dfName, colName) : null,
                isNumColumn ? react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_RangeFilter__WEBPACK_IMPORTED_MODULE_6__["default"], { dfName: dfName, colName: colName, minValue: Number(minValue), maxValue: Number(maxValue), onNumRangeSelectIconClick: this.onNumRangeSelectIconClick })
                    : this.renderCateItemList(dfName, colName, itemList, cateSearch, cateSelect, isFilterValue))));
    }
}
FilterListRenderer.contextType = _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_7__.ReactStore;



/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/HeaderRenderer.js":
/*!*****************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/HeaderRenderer.js ***!
  \*****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   HeaderRenderer: () => (/* binding */ HeaderRenderer)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Cell */ "./lib/sidePanel/SpreadSheet/Cell.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");
/* harmony import */ var _SSStyle__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SSStyle */ "./lib/sidePanel/SpreadSheet/SSStyle.js");
/* harmony import */ var _FilterListRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./FilterListRenderer */ "./lib/sidePanel/SpreadSheet/FilterListRenderer.js");







class HeaderRenderer extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {};
        this.onCellDoubleClick = this.onCellDoubleClick.bind(this);
    }
    onCellDoubleClick(colNum) {
        return () => {
            if (this.props.mood && this.props.setSearchInputActive) {
                this.props.setSearchInputActive(colNum);
            }
        };
    }
    render() {
        return this.props.header && react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "row", style: this.props.headerRowStyle }, this.props.header.map((headerValue, j) => {
            var _a, _b;
            if (j === this.props.header.length - 1) {
                const realHeaderCellStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(this.props.headerCellStyle);
                realHeaderCellStyle.color = "transparent";
                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "cell-container", key: `_dummy_${this.props.spreadsheetName}_header_${j}`, style: this.props.headerContainerStyle, id: `_dummy_${this.props.spreadsheetName}_headerContainer_${j}` },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Cell__WEBPACK_IMPORTED_MODULE_2__["default"], { givenId: `_dummy_${this.props.spreadsheetName}_header_${j}`, cellValue: headerValue, cellStyle: realHeaderCellStyle, contenteditable: false, cellBold: true })));
            }
            const colName = this.props.header[j];
            const pn = (_a = this.props.previewItems) === null || _a === void 0 ? void 0 : _a.newColumns;
            const previewDetail = (pn !== undefined && this.props.tableName in pn && j > 1) ? pn[this.props.tableName][this.props.header[j - 1]] : undefined;
            const isPreviewColumn = this.props.previewItems !== undefined && this.props.previewItems.op !== null && _utils__WEBPACK_IMPORTED_MODULE_3__.isSupportPreviewOp(this.props.previewItems.op) && previewDetail !== undefined && previewDetail.newColumn === colName;
            const isHighlight = isPreviewColumn ? false : this.props.dfColsStyle[colName].isHighlight;
            const refFn = this.props.floatColumnRefFunc ? this.props.floatColumnRefFunc(j, isPreviewColumn || isHighlight) : undefined;
            const cellCtnSpecialStyle = _utils__WEBPACK_IMPORTED_MODULE_3__.calCellCtnSpecialStyle(false, isPreviewColumn, false, isHighlight, (_b = this.props.previewItems) === null || _b === void 0 ? void 0 : _b.op);
            const realHeaderCtnStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(this.props.headerContainerStyle);
            if (cellCtnSpecialStyle === "highlight") {
                realHeaderCtnStyle.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_4__.SSColumnHLColor;
            }
            else if (cellCtnSpecialStyle === "preview") {
                realHeaderCtnStyle.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_4__.SSColumnPreColor;
            }
            return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "cell-container cell-container-header", key: `${this.props.spreadsheetName}_header_${j}`, style: realHeaderCtnStyle, id: `${this.props.spreadsheetName}_headerContainer_${j}`, ref: refFn },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: 'xavier-mv-header-cell', onMouseEnter: (e) => { (0,_SSStyle__WEBPACK_IMPORTED_MODULE_5__.zoomTitle)(e, true, true); }, onMouseLeave: (e) => { (0,_SSStyle__WEBPACK_IMPORTED_MODULE_5__.zoomTitle)(e, false, true); } },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Cell__WEBPACK_IMPORTED_MODULE_2__["default"], { onDblclick: this.onCellDoubleClick(j), givenId: `${this.props.spreadsheetName}_header_${j}`, cellValue: headerValue, cellStyle: this.props.headerCellStyle, contenteditable: false, cellBold: true })),
                this.props.searchInputActive === j && this.props.filterListRendererParam &&
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: 'xavier-mv-search-container' },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_FilterListRenderer__WEBPACK_IMPORTED_MODULE_6__.FilterListRenderer, { dfName: this.props.tableName, colName: String(headerValue), ...this.props.filterListRendererParam }))));
        }));
    }
}


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/RangeFilter.js":
/*!**************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/RangeFilter.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ RangeFilter)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

class RangeFilter extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.handleInputChange = (e) => {
            const { name, value } = e.currentTarget;
            if (name === 'lowerBundle') {
                this.setState({ lowerBundle: Number(value) });
            }
            else if (name === 'upperBundle') {
                this.setState({ upperBundle: Number(value) });
            }
        };
        this.state = {
            lowerBundle: this.props.minValue,
            upperBundle: this.props.maxValue,
            //    isInit: false,
        };
        this.handleInputChange = this.handleInputChange.bind(this);
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-itemlist-wrapper" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-search-bar" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "number", className: "xavier-mv-search-input xavier-mv-num-search-input", value: this.state.lowerBundle || 0, name: "lowerBundle", onChange: this.handleInputChange }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-mv-num-search-mid" }, "~"),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "number", className: "xavier-mv-search-input xavier-mv-num-search-input", value: this.state.upperBundle || 0, min: this.state.lowerBundle, name: "upperBundle", onChange: this.handleInputChange }),
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", { className: "xavier-mv-confirm-btn", onClick: (e) => { this.props.onNumRangeSelectIconClick(e, this.props.dfName, this.props.colName, this.state.lowerBundle, this.state.upperBundle); } }, "Confirm"))));
    }
}


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/SGRowRenderer.js":
/*!****************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/SGRowRenderer.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SGRowRenderer: () => (/* binding */ SGRowRenderer)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _SSStyle__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./SSStyle */ "./lib/sidePanel/SpreadSheet/SSStyle.js");
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Cell */ "./lib/sidePanel/SpreadSheet/Cell.js");
/* harmony import */ var _Metadata_CateColTitle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Metadata/CateColTitle */ "./lib/sidePanel/Metadata/CateColTitle.js");
/* harmony import */ var _Metadata_NumColTitle__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Metadata/NumColTitle */ "./lib/sidePanel/Metadata/NumColTitle.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");








class SGRowRenderer extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {};
    }
    renderSummaryGraph(colName, colNum) {
        const p_dfName = this.props.tableName;
        const p_header = this.props.header;
        const p_previewItems = this.props.previewItems;
        const p_dfInfo = this.props.dfInfo;
        const p_histogramBin = this.props.histogramBin;
        const pn = p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.newColumns;
        const previewDetail = (pn !== undefined && p_dfName in pn && colNum > 1) ? pn[p_dfName][p_header[colNum - 1]] : undefined;
        const isPreviewColumn = _utils__WEBPACK_IMPORTED_MODULE_2__.isSupportPreviewOp(p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.op) && previewDetail !== undefined && previewDetail.newColumn === colName;
        const colMeta = isPreviewColumn ? previewDetail.colMeta : p_dfInfo.columns[colName];
        const colHist = p_histogramBin[colName];
        // if (utils.isCateColumn(colMeta.dtype) && colMeta.cardinality === null) {
        //   console.error(`[renderCol] Cardinality is null for column ${colName} in DataFrame ${p_dfName}.`);
        // } else if (utils.isNumColumn(colMeta.dtype) && colHist === undefined) {
        //   console.error(`[renderCol] Histogram is not found for column ${colName} in DataFrame ${p_dfName}.`);
        // }
        const cardinality = colMeta.cardinality === null ? 0 : colMeta.cardinality;
        const histItems = colHist !== undefined ? colHist : [];
        const cateColTitleDiv = (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Metadata_CateColTitle__WEBPACK_IMPORTED_MODULE_3__.CateColTitle, { dfName: p_dfName, colName: colName, nullCount: colMeta.nullCount, cardinality: cardinality, numRows: p_dfInfo.numRows }));
        const numColTitleDiv = (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Metadata_NumColTitle__WEBPACK_IMPORTED_MODULE_4__.NumColTitle, { dfName: p_dfName, colName: colName, nullCount: colMeta.nullCount, numRows: p_dfInfo.numRows, bins: histItems, minValue: colMeta.minValue, maxValue: colMeta.maxValue }));
        return (
        // <div className="xavier-mv-col" key={`xavier-table-${p_dfName}-col-${colName}`}>
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, _utils__WEBPACK_IMPORTED_MODULE_2__.isNumColumn(colMeta.dtype) ? numColTitleDiv : cateColTitleDiv)
        // </div>
        );
    }
    ;
    render() {
        const p_header = this.props.header;
        const p_name = this.props.spreadsheetName;
        const p_previewItems = this.props.previewItems;
        const p_dfName = this.props.tableName;
        return p_header && react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "row", style: this.props.headerRowStyle }, p_header.map((headerValue, j) => {
            var _a;
            if (j === p_header.length - 1) {
                const realHeaderCellStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(this.props.headerCellStyle);
                realHeaderCellStyle.color = "transparent";
                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "cell-container", key: `_dummy_${p_name}_summary_${j}`, style: this.props.headerContainerStyle, id: `_dummy_${p_name}_summary_${j}` },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Cell__WEBPACK_IMPORTED_MODULE_5__["default"], { givenId: `_dummy_${p_name}_summary_${j}`, cellValue: headerValue, cellStyle: realHeaderCellStyle, contenteditable: false, cellBold: true })));
            }
            const colName = p_header[j];
            const pn = p_previewItems !== undefined ? p_previewItems.newColumns : undefined;
            const previewDetail = (pn !== undefined && p_dfName in pn && j > 1) ? pn[p_dfName][p_header[j - 1]] : undefined;
            const isPreviewColumn = p_previewItems !== undefined && p_previewItems.op !== null && _utils__WEBPACK_IMPORTED_MODULE_2__.isSupportPreviewOp(p_previewItems.op) && previewDetail !== undefined && previewDetail.newColumn === colName;
            const isHighlight = isPreviewColumn ? false : this.props.dfColsStyle[colName].isHighlight;
            const refFn = this.props.floatColumnRefFunc ? this.props.floatColumnRefFunc(j, isPreviewColumn || isHighlight) : undefined;
            const cellCtnSpecialStyle = _utils__WEBPACK_IMPORTED_MODULE_2__.calCellCtnSpecialStyle(false, isPreviewColumn, false, isHighlight, (_a = this.props.previewItems) === null || _a === void 0 ? void 0 : _a.op);
            const realHeaderCtnStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(this.props.headerContainerStyle);
            if (cellCtnSpecialStyle === "highlight") {
                realHeaderCtnStyle.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_6__.SSColumnHLColor;
            }
            else if (cellCtnSpecialStyle === "preview") {
                realHeaderCtnStyle.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_6__.SSColumnPreColor;
            }
            return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "cell-container", key: `${p_name}_summary_${j}`, style: realHeaderCtnStyle, ref: refFn },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: 'xavier-mv-header-cell', onMouseEnter: (e) => { (0,_SSStyle__WEBPACK_IMPORTED_MODULE_7__.zoomTitle)(e, true, false); }, onMouseLeave: (e) => { (0,_SSStyle__WEBPACK_IMPORTED_MODULE_7__.zoomTitle)(e, false, false); } }, this.renderSummaryGraph(headerValue, j))));
        }));
    }
}


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/SSRenderer.js":
/*!*************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/SSRenderer.js ***!
  \*************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SSRenderer: () => (/* binding */ SSRenderer)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _SpreadSheet__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SpreadSheet */ "./lib/sidePanel/SpreadSheet/SpreadSheet.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");
/* harmony import */ var _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Wrapper/SidePanelReactStore */ "./lib/sidePanel/Wrapper/SidePanelReactStore.js");
/* harmony import */ var _Metadata_DFTitle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Metadata/DFTitle */ "./lib/sidePanel/Metadata/DFTitle.js");






class SSRenderer extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {};
        // this.onColSelectIconClick = this.onColSelectIconClick.bind(this);
        this.arrJsonTo2DArray = this.arrJsonTo2DArray.bind(this);
        this.needRenderNewTable = this.needRenderNewTable.bind(this);
        this.renderPreviewNewTable = this.renderPreviewNewTable.bind(this);
    }
    arrJsonTo2DArray(dfName, arr, header) {
        let res = [];
        for (let i = 0; i < arr.length; i++) {
            let row = arr[i];
            let rowArr = [];
            for (let j = 0; j < header.length; j++) {
                let colName = header[j];
                if (this.context.allDfColSelect[dfName][colName] === false) {
                    continue;
                }
                rowArr.push(row[colName]);
            }
            res.push(rowArr);
        }
        return res;
    }
    // onColSelectIconClick(e: React.MouseEvent, dfName: string, colName: string) {
    //   e.stopPropagation();
    //   const newAllDfColSelect = {...this.context.allDfColSelect};
    //   newAllDfColSelect[dfName][colName] = !newAllDfColSelect[dfName][colName];
    //   this.context.setAllDfColSelect(newAllDfColSelect);    
    // }
    needRenderNewTable() {
        const dfName = this.props.dfName;
        const nt = this.props.previewItems.newTables;
        const op = this.props.previewItems.op;
        if ([null, "str_replace", "table_concat", "column_fillna", "column_add", "column_rename"].includes(op)) {
            return false;
        }
        return (nt[dfName] !== undefined) && ((nt[dfName].isInSituIfSameTable && nt[dfName].newTable !== dfName) ||
            (!nt[dfName].isInSituIfSameTable));
    }
    renderPreviewNewTable() {
        const shouldRender = this.needRenderNewTable();
        if (!shouldRender) {
            return null;
        }
        const dfName = this.props.dfName;
        const nt = this.props.previewItems.newTables;
        const newDfName = nt[dfName].newTable;
        const newDfHeader = nt[dfName].dfMeta.columnNameList;
        const newDfTable = _utils__WEBPACK_IMPORTED_MODULE_1__.dfRows2SSRows(nt[dfName].rows, newDfHeader, false);
        const newAllDfInfo = {
            [newDfName]: nt[dfName].dfMeta
        };
        const dfStyleColumns = {};
        newDfHeader.forEach((colName) => {
            dfStyleColumns[colName] = {
                colName: colName,
                isHighlight: false
            };
        });
        const newDfStyle = {
            tableName: newDfName,
            isFold: false,
            isShowRows: true,
            columns: dfStyleColumns
        };
        const newColModes = {};
        newDfHeader.forEach((colName) => {
            newColModes[colName] = _constant__WEBPACK_IMPORTED_MODULE_2__.ViewMode.INIT;
        });
        const newAllColMode = {
            [newDfName]: newColModes
        };
        const newAllDfColSelect = {
            [newDfName]: {}
        };
        newDfHeader.forEach((colName) => {
            newAllDfColSelect[newDfName][colName] = true;
        });
        const newHistogramBin = {
            [newDfName]: nt[dfName].histograms
        };
        const newDfTitle = (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Metadata_DFTitle__WEBPACK_IMPORTED_MODULE_3__.DFTitle, { dfName: `Preview: ${newDfName}`, numRows: nt[dfName].dfMeta.numRows, numCols: nt[dfName].dfMeta.numCols, isFold: false }));
        const newTableDiv = (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SpreadSheet__WEBPACK_IMPORTED_MODULE_4__["default"], { name: "ss-renderer-preview-" + newDfName, header: newDfHeader, table: newDfTable, maxHeight: _constant__WEBPACK_IMPORTED_MODULE_2__.SSMaxHeight, alternateColor: _constant__WEBPACK_IMPORTED_MODULE_2__.SSAlternateColor, cellMaxWidth: _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth, cellMinWidth: _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth, tableRowHeight: _constant__WEBPACK_IMPORTED_MODULE_2__.SSTableRowHeight, headerFontSize: 12, tableFontSize: 12, overflowOption: "hidden", rowSampleCache: this.props.rowSampleCache, allDfInfo: newAllDfInfo, dfName: newDfName, selectCond: null, dfStyle: newDfStyle, histogramBin: newHistogramBin, _allColMode: newAllColMode, valueCounts: this.props.valueCounts, setAllDfStyle: this.props.setAllDfStyle, getRowSampleOfOneDf: this.props.getRowSampleOfOneDf }));
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
            newDfTitle,
            newTableDiv));
    }
    render() {
        const dfName = this.props.dfName;
        const shownDF = this.props.allDfInfo[dfName];
        const header1D = shownDF.columnNameList;
        const rows = this.props.rowSampleCache[dfName] !== undefined ? this.props.rowSampleCache[dfName].rows : [];
        const selectedCond = this.props.rowSampleCache[dfName] !== undefined ? this.props.rowSampleCache[dfName].condition : null;
        const table2D = this.arrJsonTo2DArray(dfName, rows, header1D);
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-ss-wrapper", id: `xavier-ss-wrapper-${dfName}` },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SpreadSheet__WEBPACK_IMPORTED_MODULE_4__["default"], { name: "ss-renderer" + dfName, header: header1D, table: table2D, maxHeight: _constant__WEBPACK_IMPORTED_MODULE_2__.SSMaxHeight, alternateColor: _constant__WEBPACK_IMPORTED_MODULE_2__.SSAlternateColor, cellMaxWidth: _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth, cellMinWidth: _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth, tableRowHeight: _constant__WEBPACK_IMPORTED_MODULE_2__.SSTableRowHeight, headerFontSize: 12, tableFontSize: 12, overflowOption: "hidden", rowSampleCache: this.props.rowSampleCache, allDfInfo: this.props.allDfInfo, dfName: dfName, selectCond: selectedCond, dfStyle: this.props.allDfStyle[dfName], histogramBin: this.props.histogramBin, _allColMode: this.props.allColMode, valueCounts: this.props.valueCounts, setAllDfStyle: this.props.setAllDfStyle, getRowSampleOfOneDf: this.props.getRowSampleOfOneDf, previewItems: this.props.previewItems, onSampleBtnClick: this.props.onSampleBtnClick }),
            this.renderPreviewNewTable()));
    }
}
SSRenderer.contextType = _Wrapper_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_5__.ReactStore;



/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/SSStyle.js":
/*!**********************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/SSStyle.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   addDummyValue: () => (/* binding */ addDummyValue),
/* harmony export */   attachScrollHandlerFac: () => (/* binding */ attachScrollHandlerFac),
/* harmony export */   calCellCtnAltColor: () => (/* binding */ calCellCtnAltColor),
/* harmony export */   commonTableCellStyleHandler: () => (/* binding */ commonTableCellStyleHandler),
/* harmony export */   contenteditableHandler: () => (/* binding */ contenteditableHandler),
/* harmony export */   fcRefFuncFac: () => (/* binding */ fcRefFuncFac),
/* harmony export */   fixFloatColumn: () => (/* binding */ fixFloatColumn),
/* harmony export */   headerCellStyleHandler: () => (/* binding */ headerCellStyleHandler),
/* harmony export */   headerContainerStyleHandler: () => (/* binding */ headerContainerStyleHandler),
/* harmony export */   headerHandler: () => (/* binding */ headerHandler),
/* harmony export */   headerRowStyleHandler: () => (/* binding */ headerRowStyleHandler),
/* harmony export */   moodHandler: () => (/* binding */ moodHandler),
/* harmony export */   scrollHandlerFac: () => (/* binding */ scrollHandlerFac),
/* harmony export */   spreadsheetStyleHandler: () => (/* binding */ spreadsheetStyleHandler),
/* harmony export */   tableCellStyleColPre: () => (/* binding */ tableCellStyleColPre),
/* harmony export */   tableCellStyleHandler: () => (/* binding */ tableCellStyleHandler),
/* harmony export */   tableContainerStyle: () => (/* binding */ tableContainerStyle),
/* harmony export */   tableHandler: () => (/* binding */ tableHandler),
/* harmony export */   tableRowStyleHandler: () => (/* binding */ tableRowStyleHandler),
/* harmony export */   zoomTitle: () => (/* binding */ zoomTitle)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _constant__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../constant */ "./lib/constant.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");



const contenteditableHandler = (editMode) => {
    return editMode === "rw";
};
const spreadsheetStyleHandler = (maxHeight) => {
    if (maxHeight !== undefined) {
        return {
            overflowY: "auto",
            maxHeight: `${maxHeight}px`,
        };
    }
    else {
        return {};
    }
};
const headerRowStyleHandler = (headerRowHeight) => {
    return {
        height: `${headerRowHeight}px`
    };
};
const tableRowStyleHandler = (tableRowHeight) => {
    return {
        height: `${tableRowHeight}px`
    };
};
const headerContainerStyleHandler = (headerColor, cellMinWidth, cellMaxWidth) => {
    let res = {};
    if (headerColor !== undefined) {
        res.backgroundColor = headerColor;
    }
    if (cellMinWidth !== undefined) {
        res.minWidth = `${cellMinWidth}px`;
    }
    if (cellMaxWidth !== undefined) {
        res.maxWidth = `${cellMaxWidth}px`;
    }
    return res;
};
const headerCellStyleHandler = (headerRowHeight, headerFontColor, cellTextAlign, headerFontSize, overflowOption) => {
    let s = {
        lineHeight: `${headerRowHeight}px`,
        color: headerFontColor,
        textAlign: cellTextAlign,
    };
    if (headerFontSize < 12) {
        s.fontSize = "12px";
        s.transform = `scale(${headerFontSize / 12})`;
    }
    else {
        s.fontSize = `${headerFontSize}px`;
    }
    if (overflowOption === "auto") {
        s.overflow = "auto";
    }
    else if (overflowOption === "scrollX") {
        s.overflowX = "auto"; // @TODO cannot use "overlay"
        s.overflowY = "hidden";
    }
    else if (overflowOption === "hidden") {
        s.overflow = "hidden";
        s.textOverflow = "ellipsis";
        s.whiteSpace = "nowrap";
    }
    // Add more overflow options here...
    return s;
};
const commonTableCellStyleHandler = (tableRowHeight, tableFontColor, cellTextAlign, tableFontSize) => {
    let s = {
        height: `${tableRowHeight}px`,
        lineHeight: `${tableRowHeight}px`,
        color: tableFontColor,
        textAlign: cellTextAlign,
    };
    if (tableFontSize < 12) {
        s.fontSize = "12px";
        s.transform = `scale(${tableFontSize / 12})`;
    }
    else {
        s.fontSize = `${tableFontSize}px`;
    }
    return s;
};
const tableCellStyleHandler = (commonTableCellStyle, overflowOption) => {
    let s = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(commonTableCellStyle);
    if (overflowOption === "auto") {
        s.overflow = "auto";
    }
    else if (overflowOption === "hidden") {
        s.overflow = "hidden";
        s.textOverflow = "ellipsis";
        s.whiteSpace = "nowrap";
    }
    else if (overflowOption === "scrollX") {
        console.warn("[tableCellStyleHandler]Warning: style for scrollX is not implemented yet. Using hidden style instead.");
        s.overflow = "hidden";
        s.textOverflow = "ellipsis";
        s.whiteSpace = "nowrap";
    }
    return s;
};
const tableCellStyleColPre = (tableCellStyle, header, row, curColNum, dfName, previewItem, isPreviewColumn) => {
    var _a;
    if (previewItem === undefined) {
        return tableCellStyle;
    }
    if (isPreviewColumn) { // For preview column
        const cond = curColNum >= 1 && row[curColNum - 1] !== row[curColNum] && _utils__WEBPACK_IMPORTED_MODULE_1__.isSingleColumnOp(previewItem.op);
        if (cond) {
            const realTableCellStyle = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(tableCellStyle);
            realTableCellStyle.fontWeight = "bold";
            return realTableCellStyle;
        }
        else {
            return tableCellStyle;
        }
    }
    // For adjacent column
    const pn = previewItem.newColumns;
    const cond2 = dfName in pn && header[curColNum] in pn[dfName] && curColNum < row.length - 1 && row[curColNum + 1] !== row[curColNum] && _utils__WEBPACK_IMPORTED_MODULE_1__.isSingleColumnOp(previewItem.op);
    // Another case is when it is a filtered value
    const pnt = previewItem.newTables;
    const cond3 = previewItem.op === "table_filter" && dfName in pnt && ["string", "number"].includes(typeof row[curColNum]) && ((_a = pnt[dfName].condValues) === null || _a === void 0 ? void 0 : _a.includes(String(row[curColNum])));
    if (cond2 || cond3) {
        const realTableCellStyle = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(tableCellStyle);
        realTableCellStyle.fontWeight = "bold";
        return realTableCellStyle;
    }
    else {
        return tableCellStyle;
    }
};
const tableContainerStyle = (rowNum, cellss, alternateColor, InnerBorderStyle, cellMinWidth, cellMaxWidth) => {
    let s = {};
    if (cellss === "highlightAndDelete") {
        s.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_2__.SSRowHLDelColor;
    }
    else if (cellss === "preview") {
        s.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_2__.SSColumnPreColor;
    }
    else if (cellss === "deleted") {
        s.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_2__.SSRowDelColor;
    }
    else if (cellss === "highlight") {
        s.backgroundColor = _constant__WEBPACK_IMPORTED_MODULE_2__.SSColumnHLColor;
    }
    else if (alternateColor !== undefined) {
        s.backgroundColor = /*"#eaebee"*/ alternateColor[rowNum % alternateColor.length];
    }
    if (InnerBorderStyle !== undefined) {
        s.border = InnerBorderStyle;
    }
    if (cellMinWidth !== undefined) {
        s.minWidth = `${cellMinWidth}px`;
    }
    if (cellMaxWidth !== undefined) {
        s.maxWidth = `${cellMaxWidth}px`;
    }
    return s;
};
const moodHandler = (realAllDfStyle) => {
    return realAllDfStyle.isShowRows;
};
const addDummyValue = (row) => {
    row.push("---");
};
const tableHandler = (previewItems, header, table, dfName) => {
    let headerCopy = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(header);
    let tableCopy = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(table);
    if (previewItems !== undefined) {
        _utils__WEBPACK_IMPORTED_MODULE_1__.tableAddPreviewColumn(headerCopy, tableCopy, previewItems, dfName);
    }
    tableCopy.forEach((row) => {
        addDummyValue(row); // Add a dummy column because we need to correctly scroll the table
    });
    return tableCopy;
};
const headerHandler = (previewItems, header, table, dfName) => {
    let headerCopy = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(header);
    let tableCopy = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(table);
    if (previewItems !== undefined) {
        _utils__WEBPACK_IMPORTED_MODULE_1__.tableAddPreviewColumn(headerCopy, tableCopy, previewItems, dfName);
    }
    addDummyValue(headerCopy); // Add a dummy column because we need to correctly scroll the table
    return headerCopy;
};
const scrollHandlerFac = (parentElement, floatColumnRefs) => {
    return () => {
        if (parentElement) {
            const ctnWidth = _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth + 10; // 10 means padding
            const parentRect = parentElement.getBoundingClientRect();
            const pScrollL = parentElement.scrollLeft;
            const isVisibleRef = [];
            const isNotVisibleRef = [];
            const allFloatRef = [];
            floatColumnRefs.current.forEach((fref) => {
                const cOriginRightRe = ctnWidth * (fref.colNum + 1);
                if (pScrollL + parentRect.width >= cOriginRightRe) {
                    isVisibleRef.push(fref);
                }
                else {
                    isNotVisibleRef.push(fref);
                }
            });
            isVisibleRef.forEach((fref) => {
                fref.el.classList.remove('xavier-cc-float-right');
                fref.el.style.right = "";
            });
            // First we put the invisible element to the right
            let allColNumNotVis = lodash__WEBPACK_IMPORTED_MODULE_0___default().uniq(isNotVisibleRef.map((fref) => fref.colNum));
            allColNumNotVis.sort((a, b) => b - a); // Sort in descending order
            isNotVisibleRef.forEach((fref) => {
                fref.el.classList.add('xavier-cc-float-right');
                const rank = allColNumNotVis.indexOf(fref.colNum);
                fref.el.style.right = `${10 + ctnWidth * rank}px`;
                allFloatRef.push(fref);
            });
            // Then if the originally visible columns become invisible, we need to adjust the position
            const curNumOfFloatCol = allColNumNotVis.length;
            let allColNumVis = lodash__WEBPACK_IMPORTED_MODULE_0___default().uniq(isVisibleRef.map((fref) => fref.colNum));
            allColNumVis.sort((a, b) => b - a); // Sort in descending order
            isVisibleRef.forEach((fref) => {
                const cOriginRightRe = ctnWidth * (fref.colNum + 1);
                if (pScrollL + parentRect.width < cOriginRightRe + ctnWidth * curNumOfFloatCol) {
                    fref.el.classList.add('xavier-cc-float-right');
                    const rank = allColNumVis.indexOf(fref.colNum);
                    fref.el.style.right = `${10 + ctnWidth * (curNumOfFloatCol + rank)}px`;
                    allFloatRef.push(fref);
                }
            });
            // Only let the first fref and the last fref to have shadows
            let allFloatNum = lodash__WEBPACK_IMPORTED_MODULE_0___default().uniq(allFloatRef.map((fref) => fref.colNum));
            allFloatNum.sort((a, b) => a - b);
            allFloatRef.forEach((fref) => {
                const rank = allFloatNum.indexOf(fref.colNum);
                if (rank === 0 && rank === allFloatNum.length - 1) {
                    fref.el.style.boxShadow = "-4px 4px 8px rgba(0, 0, 0, 0.1), 6px 4px 8px rgba(0, 0, 0, 0.1)";
                }
                else if (rank === 0) {
                    fref.el.style.boxShadow = "-4px 4px 8px rgba(0, 0, 0, 0.1)";
                }
                else if (rank === allFloatNum.length - 1) {
                    fref.el.style.boxShadow = "6px 4px 8px rgba(0, 0, 0, 0.1)";
                }
            });
        }
    };
};
const fixFloatColumn = (rootRef, floatColumnRefs) => {
    return () => {
        var _a;
        const parentElement = (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.parentElement;
        scrollHandlerFac(parentElement, floatColumnRefs)();
    };
};
const attachScrollHandlerFac = (rootRef, floatColumnRefs) => {
    return () => {
        var _a;
        const parentElement = (_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.parentElement;
        if (parentElement) {
            parentElement.addEventListener('scroll', scrollHandlerFac(parentElement, floatColumnRefs));
        }
        return () => {
            if (parentElement) {
                parentElement.removeEventListener('scroll', scrollHandlerFac(parentElement, floatColumnRefs));
            }
        };
    };
};
function calCellCtnAltColor(p_alternateColor, deletedRowsFound, op) {
    return _utils__WEBPACK_IMPORTED_MODULE_1__.isSupportDeleteRowOp(op) && deletedRowsFound ? undefined : p_alternateColor;
}
const fcRefFuncFac = (floatColumnRefs) => {
    return (colNum, enable) => {
        return (el) => {
            if (el && enable) {
                floatColumnRefs.current.push({ el, colNum });
            }
        };
    };
};
const zoomTitle = (e, isZoomIn, type) => {
    // isZoomIn = true;
    let zoomIndex = 0.6;
    // if(type) { //如果是text，那么按照文本长度进行缩放
    let textWidth = e.currentTarget.innerText.length * 3.2;
    zoomIndex = textWidth / _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth;
    // }
    let width = _constant__WEBPACK_IMPORTED_MODULE_2__.SSCellMaxWidth;
    e.currentTarget.style.marginLeft = isZoomIn ? -width * zoomIndex / 2 + 'px' : '0px';
    e.currentTarget.style.width = isZoomIn ? width * (1 + zoomIndex) + 'px' : width + 'px';
    e.currentTarget.style.boxShadow = isZoomIn ? '10px 0 15px rgba(0, 0, 0, 0.1), -10px 0 15px rgba(0, 0, 0, 0.1)' : 'none';
    e.currentTarget.style.transition = 'all 0.3s'; //坑的一批，加了动画再动态获取宽度会导致获取宽度异常
    const firstChild = e.currentTarget.children[0];
    firstChild.style.zIndex = isZoomIn ? '2' : '';
    firstChild.style.backgroundColor = 'white';
    // if(!type) {//如果是图形那就也放大height
    //   e.currentTarget.style.marginTop = isZoomIn ? -p_headerRowHeight * zoomIndex / 2 + 'px' : '0px';
    //   e.currentTarget.style.height = isZoomIn? p_headerRowHeight * (1 + zoomIndex) + 'px' : p_headerRowHeight +  'px';  
    //   firstChild.style.height = isZoomIn? p_headerRowHeight * (1 + zoomIndex) + 'px' : p_headerRowHeight +  'px';
    //   e.currentTarget.style.transition = 'all 1s';
    // }
};


/***/ }),

/***/ "./lib/sidePanel/SpreadSheet/SpreadSheet.js":
/*!**************************************************!*\
  !*** ./lib/sidePanel/SpreadSheet/SpreadSheet.js ***!
  \**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Cell */ "./lib/sidePanel/SpreadSheet/Cell.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils */ "./lib/utils.js");
/* harmony import */ var _SSStyle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SSStyle */ "./lib/sidePanel/SpreadSheet/SSStyle.js");
/* harmony import */ var _HeaderRenderer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./HeaderRenderer */ "./lib/sidePanel/SpreadSheet/HeaderRenderer.js");
/* harmony import */ var _SGRowRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./SGRowRenderer */ "./lib/sidePanel/SpreadSheet/SGRowRenderer.js");







const exactProps = (props) => {
    const p_name = props.name;
    const p_editMode = (props.editMode !== undefined) ? props.editMode : "r";
    const p_initRowNum = (props.initRowNum !== undefined) ? props.initRowNum : 0;
    const p_initColNum = (props.initColNum !== undefined) ? props.initColNum : 0;
    const p_fixedRowNum = (props.fixedRowNum !== undefined) ? props.fixedRowNum : 0;
    const p_fixedColNum = (props.fixedColNum !== undefined) ? props.fixedColNum : 0;
    const p_minRowNum = (props.minRowNum !== undefined) ? props.minRowNum : 0;
    const p_minColNum = (props.minColNum !== undefined) ? props.minColNum : 0;
    const p_headerRowHeight = (props.headerRowHeight !== undefined) ? props.headerRowHeight : 32;
    const p_tableRowHeight = (props.tableRowHeight !== undefined) ? props.tableRowHeight : 26;
    const p_cellMinWidth = props.cellMinWidth;
    const p_cellMaxWidth = props.cellMaxWidth;
    const p_overflowOption = (props.overflowOption !== undefined) ? props.overflowOption : "auto";
    const p_cellTextAlign = (props.cellTextAlign !== undefined) ? props.cellTextAlign : "center";
    const p_headerColor = props.headerColor;
    const p_alternateColor = props.alternateColor;
    const p_InnerBorderStyle = props.InnerBorderStyle;
    const p_headerFontColor = (props.headerFontColor !== undefined) ? props.headerFontColor : "#000";
    const p_headerFontSize = (props.headerFontSize !== undefined) ? props.headerFontSize : 14;
    const p_tableFontSize = (props.tableFontSize !== undefined) ? props.tableFontSize : 10;
    const p_tableFontColor = (props.tableFontColor !== undefined) ? props.tableFontColor : "#000";
    const p_height = props.maxHeight;
    const p_onlyPreviewSchema = props.onlyPreviewSchema === undefined ? false : props.onlyPreviewSchema;
    const p_allDfInfo = (!p_onlyPreviewSchema && props.allDfInfo !== undefined) ? props.allDfInfo : {};
    const p_dfName = props.dfName;
    const p_dfStyle = props.dfStyle === undefined ? {
        tableName: p_dfName,
        isFold: true,
        isShowRows: false,
        columns: {}
    } : props.dfStyle;
    const histogramBin = props.histogramBin === undefined ? {} : props.histogramBin;
    const _allColMode = props._allColMode === undefined ? {} : props._allColMode;
    const valueCounts = props.valueCounts;
    const p_selectCond = props.selectCond;
    const p_previewItems = props.previewItems;
    return { p_name, p_editMode, p_initRowNum, p_initColNum, p_fixedRowNum, p_fixedColNum, p_minRowNum,
        p_minColNum, p_headerRowHeight, p_tableRowHeight, p_cellMinWidth, p_cellMaxWidth, p_overflowOption,
        p_cellTextAlign, p_headerColor, p_alternateColor, p_InnerBorderStyle, p_headerFontColor, p_headerFontSize,
        p_tableFontSize, p_tableFontColor, p_height,
        p_onlyPreviewSchema, p_allDfInfo, p_dfName, p_dfStyle, histogramBin, _allColMode, valueCounts, p_selectCond, p_previewItems };
};
const SpreadSheet = (props) => {
    // @TODO: I don't know whether or not it can react to props change
    const { p_name, p_editMode, p_headerRowHeight, p_tableRowHeight, p_cellMinWidth, p_cellMaxWidth, p_overflowOption, p_cellTextAlign, p_headerColor, p_alternateColor, p_InnerBorderStyle, p_headerFontColor, p_headerFontSize, p_tableFontSize, p_tableFontColor, p_height, p_onlyPreviewSchema, p_allDfInfo, p_dfName, p_dfStyle, histogramBin, _allColMode, valueCounts, p_selectCond, p_previewItems } = exactProps(props);
    const p_table = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableHandler)(props.previewItems, props.header, props.table, props.dfName), [props.previewItems, props.table, props.header, props.dfName]);
    const p_header = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.headerHandler)(props.previewItems, props.header, props.table, props.dfName), [props.previewItems, props.table, props.header, props.dfName]);
    const mood = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.moodHandler)(p_dfStyle), [p_dfStyle]);
    const [searchInputActive, setSearchInputActive] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(null); // 用来记录当前激活的input的索引，null表示没有激活
    // const [editingCellInfo, setEditingCellInfo] = useState<IEditingCellInfo>({ exist: false, row: -1, col: -1 })
    const contenteditable = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.contenteditableHandler)(p_editMode), [p_editMode]);
    const spreadsheetStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.spreadsheetStyleHandler)(p_height), [p_height]);
    const headerRowStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.headerRowStyleHandler)(p_headerRowHeight), [p_headerRowHeight]);
    const tableRowStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableRowStyleHandler)(p_tableRowHeight), [p_tableRowHeight]);
    const headerContainerStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.headerContainerStyleHandler)(p_headerColor, p_cellMinWidth, p_cellMaxWidth), [p_headerColor, p_cellMinWidth, p_cellMaxWidth]);
    const headerCellStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.headerCellStyleHandler)(p_headerRowHeight, p_headerFontColor, p_cellTextAlign, p_headerFontSize, p_overflowOption), [p_headerRowHeight, p_headerFontColor, p_cellTextAlign, p_headerFontSize, p_overflowOption]);
    const commonTableCellStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.commonTableCellStyleHandler)(p_tableRowHeight, p_tableFontColor, p_cellTextAlign, p_tableFontSize), [p_tableRowHeight, p_tableFontColor, p_cellTextAlign, p_tableFontSize]);
    const tableCellStyle = (0,react__WEBPACK_IMPORTED_MODULE_0__.useMemo)(() => (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableCellStyleHandler)(commonTableCellStyle, p_overflowOption), [commonTableCellStyle, p_overflowOption]);
    const floatColumnRefs = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)([]);
    const rootRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)((0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.attachScrollHandlerFac)(rootRef, floatColumnRefs), []); // Empty dependency array means this effect will only run once after the initial render
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)((0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.fixFloatColumn)(rootRef, floatColumnRefs)); // No dependencies means this effect will run after every render
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        floatColumnRefs.current = [];
    });
    const [updateKey, setUpdateKey] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(0);
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        // Increment the updateKey to force a re-render
        // The reason for re-render is the bug of the float column header style. @TODO
        setUpdateKey(prevKey => prevKey + 1);
    }, [props.header, props.table]); // Dependency array includes props that should trigger a re-render
    const renderTable = () => {
        if (p_table.length === 0) { //筛选为空表时，渲染10行空表
            return ([...Array(10)].map((_, i) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20) + String(i), className: "row", style: tableRowStyle }, [...Array(p_header.length)].map((_, j) => (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20) + String(i + j), className: "cell-container", style: (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableContainerStyle)(i, "normal", p_alternateColor, p_InnerBorderStyle, p_cellMinWidth, p_cellMaxWidth) })))))));
        }
        const isTableInSituPreview = _utils__WEBPACK_IMPORTED_MODULE_3__.tableShouldInSituPreview(p_dfName, p_previewItems);
        const previewRows = isTableInSituPreview && p_previewItems !== undefined ? p_previewItems.newTables[p_dfName] : undefined;
        const deletedRowsFound = isTableInSituPreview &&
            previewRows !== undefined &&
            p_table.some((row, i) => !_utils__WEBPACK_IMPORTED_MODULE_3__.canFindRows(row, _utils__WEBPACK_IMPORTED_MODULE_3__.dfRows2SSRows(previewRows.rows, p_header)));
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null, p_table.map((row, i) => {
            const isDeletedRows = isTableInSituPreview && previewRows !== undefined && !_utils__WEBPACK_IMPORTED_MODULE_3__.canFindRows(row, _utils__WEBPACK_IMPORTED_MODULE_3__.dfRows2SSRows(previewRows.rows, p_header));
            return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20) + String(i), className: "row", style: tableRowStyle }, row.map((rowValue, j) => {
                if (j === row.length - 1) {
                    const realTableCellStyle = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(tableCellStyle);
                    realTableCellStyle.color = "transparent";
                    const realTableCtnStyle = (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableContainerStyle)(i, "normal", p_alternateColor, p_InnerBorderStyle, p_cellMinWidth, p_cellMaxWidth);
                    realTableCtnStyle.backgroundColor = undefined;
                    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20) + String(i + j), className: "cell-container", style: realTableCtnStyle },
                        react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Cell__WEBPACK_IMPORTED_MODULE_4__["default"], { givenId: `_dummy_${p_name}_cell_${i}_${j}`, cellValue: rowValue, row: i, col: 1 + j, contenteditable: contenteditable, cellStyle: realTableCellStyle })));
                }
                const colName = p_header[j];
                const pn = p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.newColumns;
                const op = p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.op;
                const previewDetail = (pn !== undefined && p_dfName in pn && j > 1) ? pn[p_dfName][p_header[j - 1]] : undefined;
                const isPreviewColumn = _utils__WEBPACK_IMPORTED_MODULE_3__.isSupportPreviewOp(op) && previewDetail !== undefined && previewDetail.newColumn === colName;
                const isHighlight = colName in p_dfStyle.columns ? p_dfStyle.columns[colName].isHighlight : false;
                const realTableCellStyle = (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableCellStyleColPre)(tableCellStyle, p_header, row, j, p_dfName, p_previewItems, isPreviewColumn);
                const cellCtnSpecialStyle = _utils__WEBPACK_IMPORTED_MODULE_3__.calCellCtnSpecialStyle(deletedRowsFound, isPreviewColumn, isDeletedRows, isHighlight, op);
                const altColor = (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.calCellCtnAltColor)(p_alternateColor, deletedRowsFound, op);
                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { key: _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20) + String(i + j), ref: (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.fcRefFuncFac)(floatColumnRefs)(j, isPreviewColumn || isHighlight), className: "cell-container", style: (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.tableContainerStyle)(i, cellCtnSpecialStyle, altColor, p_InnerBorderStyle, p_cellMinWidth, p_cellMaxWidth) },
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Cell__WEBPACK_IMPORTED_MODULE_4__["default"], { givenId: `${p_name}_cell_${i}_${j}`, cellValue: rowValue, row: i, col: 1 + j, contenteditable: contenteditable, cellStyle: realTableCellStyle })));
            })));
        })));
    };
    const renderOtherSchemas = () => {
        const nt = p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.newTables;
        if (nt === undefined || !_utils__WEBPACK_IMPORTED_MODULE_3__.isSupportMultiSchemaOp(p_previewItems === null || p_previewItems === void 0 ? void 0 : p_previewItems.op)) {
            return null;
        }
        const tables = Object.keys(nt);
        if (tables.length === 0) {
            return null;
        }
        const allInSitu = tables.every(t => nt[t].isInSituIfSameTable);
        if (!allInSitu) {
            return null;
        }
        const newTableName = nt[tables[0]].newTable; // @TODO: We assume that all tables have the same new table name    
        if (p_name.startsWith("table-view-ss-preview-")) { // Is preview table
            return tables.map((t, i) => {
                const key = _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20);
                const dfMeta = nt[t].dfMeta;
                // columns style
                const dfColsStyle = {};
                dfMeta.columnNameList.forEach(col => {
                    dfColsStyle[col] = {
                        colName: col,
                        isHighlight: false
                    };
                });
                const realHeader = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(dfMeta.columnNameList);
                (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.addDummyValue)(realHeader);
                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_HeaderRenderer__WEBPACK_IMPORTED_MODULE_5__.HeaderRenderer, { key: key, tableName: dfMeta.tableName, spreadsheetName: p_name + "---" + key, header: realHeader, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: dfColsStyle, mood: false, searchInputActive: null }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SGRowRenderer__WEBPACK_IMPORTED_MODULE_6__.SGRowRenderer, { key: key, tableName: dfMeta.tableName, spreadsheetName: p_name + "---" + key, header: realHeader, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: dfColsStyle, dfInfo: dfMeta, histogramBin: nt[t].histograms })));
            });
        }
        else if (newTableName === p_dfName) {
            // If the table is not a preview table, insert other schemas
            return tables.map((t, i) => {
                if (t === p_dfName) {
                    return null;
                }
                const key = _utils__WEBPACK_IMPORTED_MODULE_3__.myNanoid(20);
                const dfMeta = nt[t].dfMeta;
                // columns style
                const dfColsStyle = {};
                dfMeta.columnNameList.forEach(col => {
                    dfColsStyle[col] = {
                        colName: col,
                        isHighlight: false
                    };
                });
                const realHeader = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(dfMeta.columnNameList);
                (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.addDummyValue)(realHeader);
                return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement((react__WEBPACK_IMPORTED_MODULE_0___default().Fragment), null,
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_HeaderRenderer__WEBPACK_IMPORTED_MODULE_5__.HeaderRenderer, { key: key, tableName: dfMeta.tableName, spreadsheetName: p_name + "-header-" + key, header: realHeader, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: dfColsStyle, mood: false, searchInputActive: null }),
                    react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SGRowRenderer__WEBPACK_IMPORTED_MODULE_6__.SGRowRenderer, { key: key, tableName: dfMeta.tableName, spreadsheetName: p_name + "-sg-" + key, header: realHeader, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: dfColsStyle, dfInfo: dfMeta, histogramBin: nt[t].histograms })));
            });
        }
        return null;
    };
    const headerRendererDiv = p_onlyPreviewSchema ? null : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_HeaderRenderer__WEBPACK_IMPORTED_MODULE_5__.HeaderRenderer, { tableName: p_dfName, spreadsheetName: p_name, header: p_header, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: p_dfStyle.columns, mood: mood, searchInputActive: searchInputActive, previewItems: p_previewItems, floatColumnRefFunc: (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.fcRefFuncFac)(floatColumnRefs), setSearchInputActive: setSearchInputActive, filterListRendererParam: {
            selectCond: p_selectCond,
            allColMode: _allColMode,
            allDfInfo: p_allDfInfo,
            valueCounts: valueCounts,
            rowSampleCache: props.rowSampleCache,
            getRowSampleOfOneDf: props.getRowSampleOfOneDf,
        } }));
    const sgRowRendererDiv = p_onlyPreviewSchema ? null : (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_SGRowRenderer__WEBPACK_IMPORTED_MODULE_6__.SGRowRenderer, { tableName: p_dfName, spreadsheetName: p_name, header: p_header, headerRowStyle: headerRowStyle, headerContainerStyle: headerContainerStyle, headerCellStyle: headerCellStyle, dfColsStyle: p_dfStyle.columns, dfInfo: p_allDfInfo[p_dfName], histogramBin: histogramBin[p_dfName], previewItems: p_previewItems, floatColumnRefFunc: (0,_SSStyle__WEBPACK_IMPORTED_MODULE_2__.fcRefFuncFac)(floatColumnRefs) }));
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "spreadsheet xavier-mv-table-wrapper", id: p_name, style: spreadsheetStyle, onClick: (e) => { if (e.target.className.includes('cell')) {
            setSearchInputActive(null);
        } }, ref: rootRef, key: updateKey },
        headerRendererDiv,
        sgRowRendererDiv,
        renderOtherSchemas(),
        !mood && !p_onlyPreviewSchema && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", { className: 'xavier-sample-row-btn', onClick: () => { if (props.onSampleBtnClick)
                props.onSampleBtnClick(p_dfName); } }, "Show sample rows...")),
        mood && !p_onlyPreviewSchema && renderTable()));
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SpreadSheet);


/***/ }),

/***/ "./lib/sidePanel/Wrapper/SidePanel.js":
/*!********************************************!*\
  !*** ./lib/sidePanel/Wrapper/SidePanel.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SidePanel: () => (/* binding */ SidePanel)
/* harmony export */ });
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lumino/widgets */ "webpack/sharing/consume/default/@lumino/widgets");
/* harmony import */ var _lumino_widgets__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_lumino_widgets__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _SidePanelReactWidget__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SidePanelReactWidget */ "./lib/sidePanel/Wrapper/SidePanelReactWidget.js");


// import { LabIcon } from '@jupyterlab/ui-components';
// import appIconStr from '../style/logo.svg';
class SidePanel extends _lumino_widgets__WEBPACK_IMPORTED_MODULE_0__.StackedPanel {
    constructor(model) {
        super();
        // ~~~~~~~~~ Variables, getters, setters ~~~~~~~~~
        this._sessionContext = null;
        this.addClass('xavier-sidepanel');
        this.id = 'xavier-sidepanel-app';
        this.title.caption = 'Xavier'; // shown on hover the tab icon
        this.title.iconClass = 'autoprofile-logo';
        // ICON in the side panel tab
        // const icon = new LabIcon({
        //     name: 'auto-profile-app:app-icon',
        //     svgstr: appIconStr
        // });
        // this.title.icon = icon;
        // MODEL init
        this._model = model;
        // VIEW init
        this._sidePanelFullView = new _SidePanelReactWidget__WEBPACK_IMPORTED_MODULE_1__.SidePanelReactWidget(this._model);
        this.addWidget(this._sidePanelFullView);
    }
    // get session(): ISessionContext {
    //     return this._sessionContext;
    // }
    // set session(session: ISessionContext) {
    //     this._sessionContext = session;
    // }
    async connectNotebook(na) {
        if (na.hasConnection) {
            this._sessionContext = na.panel.sessionContext;
        }
        await this._model.connectNotebook(na, () => { return this.isVisible; });
    }
    // ~~~~~~~~~ Lifecycle methods for closing panel ~~~~~~~~~
    dispose() {
        if (this._sessionContext) {
            this._sessionContext.dispose();
        }
        super.dispose();
    }
    onCloseRequest(msg) {
        super.onCloseRequest(msg);
        this.dispose();
    }
    /**
     * Called before the widget is made visible.
     * NOTE: when using beforeShow, this.isVisible is false during update.
     *
     * other useful state messages are onAfterShow,
     * onBeforeHide, onAfterHide.
     * @param msg
     */
    onBeforeShow(msg) {
        this._model.updateAll();
    }
}


/***/ }),

/***/ "./lib/sidePanel/Wrapper/SidePanelFullView.js":
/*!****************************************************!*\
  !*** ./lib/sidePanel/Wrapper/SidePanelFullView.js ***!
  \****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SidePanelFullView: () => (/* binding */ SidePanelFullView)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _style_base_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../style/base.css */ "./style/base.css");
/* harmony import */ var _Metadata_MetadataView__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Metadata/MetadataView */ "./lib/sidePanel/Metadata/MetadataView.js");
/* harmony import */ var _assets_SvgCollection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../assets/SvgCollection */ "./lib/assets/SvgCollection.js");




class SidePanelFullView extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this._model = props.model;
        this.state = {
            _modelAllDfStyle: this._model.allDfStyle,
            _modelAllDfSeq: this._model.allDfSeq,
            // _modelSelectedDFName: this._model.selectedDFName,
            _modelPreviewItems: this._model.previewItems,
            _modelRowSampleCache: this._model.rowSampleCache,
            _allDfInfo: this._model.allDfInfo,
            _histogramBinCache: this._model.histogramBinCache,
            _valueCountsCache: this._model.valueCountsCache,
            _isLive: true,
        };
        this.handleModelChange = this.handleModelChange.bind(this);
        this.renderTitle = this.renderTitle.bind(this);
        this.onAPIBtnClick = this.onAPIBtnClick.bind(this);
    }
    componentDidMount() {
        this._model.addObserver(this.handleModelChange);
    }
    componentWillUnmount() {
        this._model.removeObserver(this.handleModelChange);
    }
    handleModelChange() {
        this.setState({
            _allDfInfo: this._model.allDfInfo,
            _histogramBinCache: this._model.histogramBinCache,
            _valueCountsCache: this._model.valueCountsCache,
            _modelAllDfStyle: this._model.allDfStyle,
            _modelAllDfSeq: this._model.allDfSeq,
            // _modelSelectedDFName: this._model.selectedDFName,
            _modelPreviewItems: this._model.previewItems,
            _modelRowSampleCache: this._model.rowSampleCache,
        });
    }
    onAPIBtnClick() {
        const apiKey = prompt("Please enter your API Key:");
        if (!apiKey) {
            return;
        }
        this._model.setAPIKey(apiKey);
    }
    renderTitle() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-sidepanel-view-title" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-sti-wrapper" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_assets_SvgCollection__WEBPACK_IMPORTED_MODULE_2__.MetaDataIcon, null)),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-st-text" }, "Table View"),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-st-btn", style: {
                    borderColor: this.state._isLive ? "#1890ff" : "#d9d9d9",
                    color: this.state._isLive ? "#1890ff" : undefined,
                    boxShadow: this.state._isLive ? "inset 0 1px 1px rgba(0,0,0,.075), 0 0 4px rgba(102, 175, 233, .6)" : undefined,
                }, onClick: this.onAPIBtnClick }, "Enter API Key")));
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "xavier-sidepanel-fullview" },
            this.renderTitle(),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_Metadata_MetadataView__WEBPACK_IMPORTED_MODULE_3__.MetadataView, { isLive: this.state._isLive, rowSampleCache: this._model.rowSampleCache, allDfStyle: this.state._modelAllDfStyle, allDfSeq: this.state._modelAllDfSeq, previewItems: this.state._modelPreviewItems, allDfInfo: this.state._allDfInfo, valueCounts: this.state._valueCountsCache, histogramBin: this.state._histogramBinCache, getCateValueCounts: this._model.getCateValueCounts, getRowSampleOfOneDf: this._model.getRowSampleOfOneDf, setAllDfStyle: this._model.setAllDfStyle })));
    }
}


/***/ }),

/***/ "./lib/sidePanel/Wrapper/SidePanelReactStore.js":
/*!******************************************************!*\
  !*** ./lib/sidePanel/Wrapper/SidePanelReactStore.js ***!
  \******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ReactStore: () => (/* binding */ ReactStore),
/* harmony export */   SidePanelReactStore: () => (/* binding */ SidePanelReactStore)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);

const ReactStore = react__WEBPACK_IMPORTED_MODULE_0___default().createContext({
    allDfColSelect: {},
    setAllDfColSelect: () => { },
    allDfCateColItemSearch: {},
    setAllDfCateColItemSearch: () => { },
});
// Create a provider component
class SidePanelReactStore extends (react__WEBPACK_IMPORTED_MODULE_0___default().Component) {
    constructor(props) {
        super(props);
        this.state = {
            _allDfColSelect: {},
            _allDfCateColItemSearch: {},
        };
        this.setAllDfColSelect = this.setAllDfColSelect.bind(this);
        this.setAllDfCateColItemSearch = this.setAllDfCateColItemSearch.bind(this);
    }
    setAllDfColSelect(newAllDfColSelect) {
        this.setState({ _allDfColSelect: newAllDfColSelect });
    }
    setAllDfCateColItemSearch(newAllDfCateColItemSearch) {
        this.setState({ _allDfCateColItemSearch: newAllDfCateColItemSearch });
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement(ReactStore.Provider, { value: {
                allDfColSelect: this.state._allDfColSelect,
                setAllDfColSelect: this.setAllDfColSelect,
                allDfCateColItemSearch: this.state._allDfCateColItemSearch,
                setAllDfCateColItemSearch: this.setAllDfCateColItemSearch,
            } }, this.props.children));
    }
}


/***/ }),

/***/ "./lib/sidePanel/Wrapper/SidePanelReactWidget.js":
/*!*******************************************************!*\
  !*** ./lib/sidePanel/Wrapper/SidePanelReactWidget.js ***!
  \*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   SidePanelReactWidget: () => (/* binding */ SidePanelReactWidget)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _SidePanelFullView__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./SidePanelFullView */ "./lib/sidePanel/Wrapper/SidePanelFullView.js");
/* harmony import */ var _SidePanelReactStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SidePanelReactStore */ "./lib/sidePanel/Wrapper/SidePanelReactStore.js");




class SidePanelReactWidget extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.ReactWidget {
    constructor(model) {
        super();
        this.addClass('xavier-sidepanel-react');
        this._model = model;
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_0__.createElement(_SidePanelReactStore__WEBPACK_IMPORTED_MODULE_2__.SidePanelReactStore, null,
            react__WEBPACK_IMPORTED_MODULE_0__.createElement(_SidePanelFullView__WEBPACK_IMPORTED_MODULE_3__.SidePanelFullView, { model: this._model })));
    }
}
;


/***/ }),

/***/ "./lib/utils.js":
/*!**********************!*\
  !*** ./lib/utils.js ***!
  \**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   calCellCtnSpecialStyle: () => (/* binding */ calCellCtnSpecialStyle),
/* harmony export */   calcPreviewRowsCols: () => (/* binding */ calcPreviewRowsCols),
/* harmony export */   canFindRows: () => (/* binding */ canFindRows),
/* harmony export */   countLetterInStr: () => (/* binding */ countLetterInStr),
/* harmony export */   deDuplicateCompletionItems: () => (/* binding */ deDuplicateCompletionItems),
/* harmony export */   dfRows2SSRows: () => (/* binding */ dfRows2SSRows),
/* harmony export */   fillNull: () => (/* binding */ fillNull),
/* harmony export */   findPositionedAncestor: () => (/* binding */ findPositionedAncestor),
/* harmony export */   formatNumber: () => (/* binding */ formatNumber),
/* harmony export */   getActiveDataFrames: () => (/* binding */ getActiveDataFrames),
/* harmony export */   getAllNewTablesFromPI: () => (/* binding */ getAllNewTablesFromPI),
/* harmony export */   getLastLine: () => (/* binding */ getLastLine),
/* harmony export */   getPreviousText: () => (/* binding */ getPreviousText),
/* harmony export */   getValidFilterCond: () => (/* binding */ getValidFilterCond),
/* harmony export */   initAllDfSeq: () => (/* binding */ initAllDfSeq),
/* harmony export */   initAllDfStyle: () => (/* binding */ initAllDfStyle),
/* harmony export */   isCateColumn: () => (/* binding */ isCateColumn),
/* harmony export */   isNumColumn: () => (/* binding */ isNumColumn),
/* harmony export */   isNumeric: () => (/* binding */ isNumeric),
/* harmony export */   isSingleColumnOp: () => (/* binding */ isSingleColumnOp),
/* harmony export */   isSupportDeleteRowOp: () => (/* binding */ isSupportDeleteRowOp),
/* harmony export */   isSupportMultiSchemaOp: () => (/* binding */ isSupportMultiSchemaOp),
/* harmony export */   isSupportPreviewOp: () => (/* binding */ isSupportPreviewOp),
/* harmony export */   isTimeColumn: () => (/* binding */ isTimeColumn),
/* harmony export */   myNanoid: () => (/* binding */ myNanoid),
/* harmony export */   removeBrackets: () => (/* binding */ removeBrackets),
/* harmony export */   removeQuotes: () => (/* binding */ removeQuotes),
/* harmony export */   removeSuffix: () => (/* binding */ removeSuffix),
/* harmony export */   tableAddPreviewColumn: () => (/* binding */ tableAddPreviewColumn),
/* harmony export */   tableShouldInSituPreview: () => (/* binding */ tableShouldInSituPreview),
/* harmony export */   toFix: () => (/* binding */ toFix)
/* harmony export */ });
/* harmony import */ var nanoid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! nanoid */ "webpack/sharing/consume/default/nanoid/nanoid");
/* harmony import */ var nanoid__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(nanoid__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_1__);


// 保留两位小数
const toFix = (s) => {
    if (typeof s !== "number")
        return s;
    let t = Number(s);
    if (t % 1 != 0) {
        return t.toFixed(2);
    }
    else {
        return t;
    }
};
const isNumeric = (value) => {
    const value_n = parseFloat(value);
    const cond1 = !isNaN(value_n);
    const cond2 = isFinite(value_n);
    return cond1 && cond2;
};
const _nanoid = (0,nanoid__WEBPACK_IMPORTED_MODULE_0__.customAlphabet)("abcdefghijklmnopqrstuvwxyz", 30);
function myNanoid(len) {
    return _nanoid(len);
}
;
function fillNull(arr, num) {
    for (let i = 0; i < num; i++) {
        arr.push(null);
    }
    return arr;
}
function tableAddPreviewColumn(header, table, previewItem, dfName) {
    const piOfDfName = previewItem.newColumns[dfName];
    if (piOfDfName === undefined) {
        return;
    }
    for (const colName in piOfDfName) {
        const idx = header.indexOf(colName);
        // Insert to the right
        header.splice(idx + 1, 0, piOfDfName[colName].newColumn); // @TODO to make the column unique
        table.forEach((row, numRow) => {
            row.splice(idx + 1, 0, piOfDfName[colName].sample[numRow]);
        });
    }
}
function _getCellTextLines(cells, i) {
    const _s = cells.get(i).toJSON().source;
    let sListComplete;
    if (_s instanceof Array) {
        sListComplete = _s;
    }
    else {
        sListComplete = _s.split("\n");
    }
    return sListComplete;
}
function _getCellTextLineBeforeCursor(sListComplete, cursorPos) {
    const sListPartial = sListComplete.slice(0, cursorPos.line);
    sListPartial.push(sListComplete[cursorPos.line].slice(0, cursorPos.column));
    return sListPartial;
}
async function getActiveDataFrames(kernel) {
    let dfList = [];
    try {
        //I don't know the seq
        const result = await kernel.requestDebug({ seq: 2, command: "inspectVariables", type: "request" }).done;
        const body = result.content.body;
        if (body && body.variables) {
            const v = body.variables;
            dfList = v.filter(v => v.type === "DataFrame");
        }
        else {
            console.warn("[getActiveDataFrames] No body or body.variables found");
        }
    }
    catch (error) {
        console.error("[getActiveDataFrames] Error fetching variable value:", error);
    }
    return dfList;
}
function getPreviousText(notebooks, cursorPos) {
    const sources = []; // every element source codes from a single cell
    const cw = notebooks.currentWidget;
    if (!cw || !cw.model) {
        console.warn("[getPreviousText] Warning: No current notebook or model");
        return sources;
    }
    const aci = cw.content.activeCellIndex;
    const cells = cw.model.cells;
    // We only consider code before cursor
    for (let i = 0; i <= aci; i++) {
        let s = _getCellTextLines(cells, i);
        if (i === aci) {
            s = _getCellTextLineBeforeCursor(s, cursorPos);
        }
        sources.push(s);
    }
    return sources;
}
function getLastLine(notebooks, cursorPos) {
    const pCode2D = getPreviousText(notebooks, cursorPos);
    if (pCode2D.length === 0) {
        console.warn("[getLastLine] no pCode2D found.");
        return null;
    }
    const lastCell = pCode2D[pCode2D.length - 1];
    if (lastCell.length === 0) {
        console.warn("[getLastLine] no lastCell found.");
        return null;
    }
    const lastLine = lastCell[lastCell.length - 1];
    return lastLine;
}
function deDuplicateCompletionItems(items) {
    const seen = {};
    return items.filter(item => {
        if (seen[item.value]) {
            return false;
        }
        seen[item.value] = true;
        return true;
    }).map(item => {
        return {
            label: item.value,
            type: item.type,
        };
    });
}
function getAllNewTablesFromPI(oldNewTables, oldAllDfInfo) {
    if (oldNewTables === undefined || oldAllDfInfo === undefined) {
        return [];
    }
    const res = [];
    for (const dfName in oldNewTables) {
        const maybeNewTable = oldNewTables[dfName].newTable;
        if (!(maybeNewTable in oldAllDfInfo)) {
            res.push(maybeNewTable);
        }
    }
    return res;
}
function initAllDfStyle(allDfInfo, oldDfStyle = undefined, oldNewTables = undefined, oldAllDfInfo = undefined) {
    const allDfStyle = {};
    const allNewTable = getAllNewTablesFromPI(oldNewTables, oldAllDfInfo);
    for (const dfName in allDfInfo) {
        const colsStyle = {};
        if (dfName in allDfStyle) {
            console.error(`[initialDfStyle] DataFrame name ${dfName} already exists in the allDfStyle object.`);
            continue;
        }
        // 1. init column style
        allDfInfo[dfName].columnNameList.forEach((col, i) => {
            if (col in colsStyle) {
                console.error(`[initialDfStyle] Column name ${col} already exists in the columns object.`);
                return;
            }
            if (oldDfStyle !== undefined && dfName in oldDfStyle && col in oldDfStyle[dfName].columns) {
                colsStyle[col] = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(oldDfStyle[dfName].columns[col]);
            }
            else {
                colsStyle[col] = {
                    colName: col,
                    isHighlight: false
                };
            }
        });
        // 2. init DataFrame style
        if (oldDfStyle !== undefined && dfName in oldDfStyle) { // For existing DataFrame
            allDfStyle[dfName] = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(oldDfStyle[dfName]);
            allDfStyle[dfName].columns = colsStyle;
        }
        else if (allNewTable.includes(dfName)) { // For the DataFrame previewed before
            allDfStyle[dfName] = {
                tableName: dfName,
                isFold: false,
                columns: colsStyle,
                isShowRows: true
            };
        }
        else { // For other cases
            allDfStyle[dfName] = {
                tableName: dfName,
                isFold: false,
                columns: colsStyle,
                isShowRows: false
            };
        }
    }
    return allDfStyle;
}
function initAllDfSeq(allDfInfo, oldAllDfSeq = undefined) {
    if (oldAllDfSeq === undefined) {
        return Object.keys(allDfInfo);
    }
    const newAllDfSeq = [];
    oldAllDfSeq.forEach((d) => {
        if (d in allDfInfo) {
            newAllDfSeq.push(d);
        }
    });
    for (const d in allDfInfo) {
        if (!newAllDfSeq.includes(d)) {
            newAllDfSeq.push(d);
        }
    }
    return newAllDfSeq;
}
function isCateColumn(dtype) {
    if (["string", "str", 'bool', '_bool'].includes(dtype)) {
        console.warn("[isCateColumn] Column type is string or boolean, which may not be supported.");
    }
    return ["object", "string", "str", "category", 'bool', '_bool'].includes(dtype);
}
function isTimeColumn(dtype) {
    return ["datetime64", "datetime64[ns]"].includes(dtype);
}
function isNumColumn(dtype) {
    const INT_TYPE = ['int', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64'];
    const FLOAT_TYPE = ['float', 'float_', 'float16', 'float32', 'float64'];
    const NUM_TYPE = [...INT_TYPE, ...FLOAT_TYPE];
    return NUM_TYPE.includes(dtype) || isTimeColumn(dtype);
}
function formatNumber(num, maxDecimalPlaces = 3, maxDecimalPlacesExp = 1, veryLargeThreshold = 1e5, verySmallThreshold = 1e-3) {
    let numStr = num.toString();
    // Special case
    if (numStr === "0" || numStr === "NaN") {
        return numStr;
    }
    // If the number is very large or very small, use exponential notation
    if (Math.abs(num) >= veryLargeThreshold || Math.abs(num) <= verySmallThreshold) {
        numStr = num.toExponential();
    }
    // Exponential
    const numStrSplit = numStr.split("e");
    if (numStrSplit.length > 2) {
        console.error("[formatNumber] Invalid number format:", numStr);
        return "NaN";
    }
    else if (numStrSplit.length === 2) {
        return `${formatNumber(parseFloat(numStrSplit[0]), maxDecimalPlaces - 2, maxDecimalPlacesExp)}e${numStrSplit[1]}`;
    }
    // Common case
    const decimalPlaces = getDecimalPlaces(num);
    if (decimalPlaces > maxDecimalPlaces) {
        return num.toFixed(maxDecimalPlaces);
    }
    else {
        return num.toString();
    }
}
// 辅助函数，用于获取数字的小数位数
function getDecimalPlaces(num) {
    const match = /\.(\d+)/.exec(num.toString());
    if (match) {
        return match[1].length;
    }
    return 0;
}
function removeQuotes(s) {
    if (s.startsWith("'''") && s.endsWith("'''")) {
        return s.slice(3, -3);
    }
    else if (s.startsWith('"""') && s.endsWith('"""')) {
        return s.slice(3, -3);
    }
    else if (s.startsWith('"') && s.endsWith('"')) {
        return s.slice(1, -1);
    }
    else if (s.startsWith("'") && s.endsWith("'")) {
        return s.slice(1, -1);
    }
    else {
        return s;
    }
}
function removeSuffix(str, suffix) {
    if (suffix.length === 0) {
        return str;
    }
    if (str.endsWith(suffix)) {
        return str.slice(0, -suffix.length);
    }
    return str;
}
function removeBrackets(s) {
    let res = s;
    if (res.startsWith("[")) {
        res = res.slice(1);
    }
    if (res.endsWith("]")) {
        res = res.slice(0, -1);
    }
    return res;
}
function findPositionedAncestor(element) {
    element = element === null ? element : element.parentElement;
    while (element) {
        var position = window.getComputedStyle(element).getPropertyValue('position');
        if (position !== 'static') {
            return element;
        }
        element = element.parentElement;
    }
    return null; // 如果没有找到定位祖先，返回null
}
function isSupportPreviewOp(op) {
    if (op === null || op === undefined) {
        return false;
    }
    return ["str_replace", "column_fillna", "column_add", "column_rename"].includes(op);
}
function isSingleColumnOp(op) {
    if (op === null || op === undefined) {
        return false;
    }
    return ["str_replace", "column_fillna"].includes(op);
}
function isSupportDeleteRowOp(op) {
    if (op === null || op === undefined) {
        return false;
    }
    return ["table_filter"].includes(op);
}
function isSupportMultiSchemaOp(op) {
    if (op === null || op === undefined) {
        return false;
    }
    return ["table_concat"].includes(op);
}
function tableShouldInSituPreview(dfName, previewItems) {
    if (previewItems === undefined) {
        return false;
    }
    return dfName in previewItems.newTables && previewItems.newTables[dfName].isInSituIfSameTable;
}
function calCellCtnSpecialStyle(deletedRowsFound, isPreview, isDeleted, isHighlight, op) {
    if (op === null || op === undefined) {
        return isHighlight ? "highlight" : "normal";
    }
    else if (isSupportDeleteRowOp(op)) {
        const deleteLogic = isDeleted && deletedRowsFound;
        return (isHighlight && deleteLogic) ? "highlightAndDelete" : (isHighlight && !deleteLogic) ? "highlight" : (!isHighlight && deleteLogic) ? "deleted" : "normal";
    }
    else if (isSupportPreviewOp(op)) {
        return isPreview ? "preview" : isHighlight ? "highlight" : "normal";
    }
    return isHighlight ? "highlight" : "normal";
}
function countLetterInStr(str, letter) {
    return str.split('').filter(char => char === letter).length;
}
function dfRows2SSRows(arr, header, removeDummy = true) {
    // Remove dummy element of header
    const headerWithoutDummy = removeDummy ? header.slice(0, -1) : header;
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        let row = arr[i];
        let rowArr = [];
        for (let j = 0; j < headerWithoutDummy.length; j++) {
            let colName = headerWithoutDummy[j];
            rowArr.push(row[colName]);
        }
        res.push(rowArr);
    }
    return res;
}
function canFindRows(row, sourceRows) {
    const clearDummyR = lodash__WEBPACK_IMPORTED_MODULE_1___default().cloneDeep(row);
    clearDummyR.pop(); // remove the last dummy element
    for (const sourceRow of sourceRows) {
        if (lodash__WEBPACK_IMPORTED_MODULE_1___default().isEqual(clearDummyR, sourceRow)) {
            return true;
        }
    }
    return false;
}
function getValidFilterCond(filterCond) {
    let cond = filterCond;
    const signStack = ["["];
    for (let i = 0; i < cond.length; i++) {
        if (cond[i] === "[") {
            signStack.push("[");
        }
        else if (cond[i] === "]") {
            if (signStack.length > 0) {
                signStack.pop();
            }
            else {
                return null; // invalid
            }
        }
        if (signStack.length === 0) { // find the end of the filter condition
            cond = cond.slice(0, i + 1);
            break;
        }
    }
    // returned cond may end with ']' or not
    return cond;
}
function calcPreviewRowsCols(pnt) {
    const tables = Object.keys(pnt);
    if (tables.length === 0) {
        return { num_rows: NaN, num_cols: NaN };
    }
    const firstTable = pnt[tables[0]];
    const firstTableColList = [...firstTable.dfMeta.columnNameList].sort();
    let num_rows = firstTable.dfMeta.numRows;
    let num_cols = firstTable.dfMeta.numCols;
    for (let i = 1; i < tables.length; i++) {
        const curTableColList = [...pnt[tables[i]].dfMeta.columnNameList].sort();
        if (pnt[tables[i]].dfMeta.numCols !== num_cols || !lodash__WEBPACK_IMPORTED_MODULE_1___default().isEqual(firstTableColList, curTableColList)) {
            console.warn("[calcPreviewRowsCols] Number of columns not consistent.");
            num_rows = NaN;
            num_cols = NaN;
            break;
        }
        num_rows += pnt[tables[i]].dfMeta.numRows;
    }
    return { num_rows, num_cols };
}


/***/ }),

/***/ "./lib/xavierCompleter/customModel.js":
/*!********************************************!*\
  !*** ./lib/xavierCompleter/customModel.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   CustomModel: () => (/* binding */ CustomModel)
/* harmony export */ });
/* harmony import */ var _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lumino/algorithm */ "webpack/sharing/consume/default/@lumino/algorithm");
/* harmony import */ var _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_2__);
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// @xavier: we only change one line. Tagged as "@xavier"



/**
 * Escape HTML by native means of the browser.
 */
function escapeHTML(text) {
    const node = document.createElement('span');
    node.textContent = text;
    return node.innerHTML;
}
/**
 * An implementation of a completer model.
 */
class CustomModel {
    constructor() {
        this.processedItemsCache = null;
        this._current = null;
        this._cursor = null;
        this._isDisposed = false;
        this._completionItems = [];
        this._original = null;
        this._query = '';
        this._subsetMatch = false;
        this._typeMap = {};
        this._orderedTypes = [];
        this._stateChanged = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__.Signal(this);
        this._queryChanged = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__.Signal(this);
        /**
         * The weak map between a processed completion item with the original item.
         * It's used to keep track of original completion item in case of displaying
         * the completer with query.
         */
        this._processedToOriginalItem = null;
        /**
         * A counter to cancel ongoing `resolveItem` call.
         */
        this._resolvingItem = 0;
    }
    /**
     * A signal emitted when state of the completer menu changes.
     */
    get stateChanged() {
        return this._stateChanged;
    }
    /**
     * A signal emitted when query string changes (at invocation, or as user types).
     */
    get queryChanged() {
        return this._queryChanged;
    }
    /**
     * The original completion request details.
     */
    get original() {
        return this._original;
    }
    set original(newValue) {
        const unchanged = this._original === newValue ||
            (this._original &&
                newValue &&
                _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.JSONExt.deepEqual(newValue, this._original));
        if (unchanged) {
            return;
        }
        this._reset();
        // Set both the current and original to the same value when original is set.
        this._current = this._original = newValue;
        this._stateChanged.emit(undefined);
    }
    /**
     * The current text change details.
     */
    get current() {
        return this._current;
    }
    set current(newValue) {
        const unchanged = this._current === newValue ||
            (this._current && newValue && _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.JSONExt.deepEqual(newValue, this._current));
        if (unchanged) {
            return;
        }
        const original = this._original;
        // Original request must always be set before a text change. If it isn't
        // the model fails silently.
        if (!original) {
            return;
        }
        const cursor = this._cursor;
        // Cursor must always be set before a text change. This happens
        // automatically in the completer handler, but since `current` is a public
        // attribute, this defensive check is necessary.
        if (!cursor) {
            return;
        }
        const current = (this._current = newValue);
        if (!current) {
            this._stateChanged.emit(undefined);
            return;
        }
        const originalLine = original.text.split('\n')[original.line];
        const currentLine = current.text.split('\n')[current.line];
        // If the text change means that the original start point has been preceded,
        // then the completion is no longer valid and should be reset.
        if (!this._subsetMatch && currentLine.length < originalLine.length) {
            this.reset(true);
            return;
        }
        const { start, end } = cursor;
        // Clip the front of the current line.
        let query = current.text.substring(start);
        // Clip the back of the current line by calculating the end of the original.
        const ending = original.text.substring(end);
        query = query.substring(0, query.lastIndexOf(ending));
        this._query = query;
        this.processedItemsCache = null;
        this._processedToOriginalItem = null;
        this._queryChanged.emit({ newValue: this._query, origin: 'editorUpdate' });
        this._stateChanged.emit(undefined);
    }
    /**
     * The cursor details that the API has used to return matching options.
     */
    get cursor() {
        return this._cursor;
    }
    set cursor(newValue) {
        // Original request must always be set before a cursor change. If it isn't
        // the model fails silently.
        if (!this.original) {
            return;
        }
        this._cursor = newValue;
    }
    /**
     * The query against which items are filtered.
     */
    get query() {
        return this._query;
    }
    set query(newValue) {
        this._query = newValue;
        this.processedItemsCache = null;
        this._processedToOriginalItem = null;
        this._queryChanged.emit({ newValue: this._query, origin: 'setter' });
    }
    /**
     * A flag that is true when the model value was modified by a subset match.
     */
    get subsetMatch() {
        return this._subsetMatch;
    }
    set subsetMatch(newValue) {
        this._subsetMatch = newValue;
    }
    /**
     * Get whether the model is disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * Dispose of the resources held by the model.
     */
    dispose() {
        // Do nothing if already disposed.
        if (this._isDisposed) {
            return;
        }
        this._isDisposed = true;
        _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__.Signal.clearData(this);
    }
    /**
     * The list of visible items in the completer menu.
     *
     * #### Notes
     * This is a read-only property.
     * When overriding it is recommended to cache results in `processedItemsCache`
     * property which will be automatically nullified when needed.
     */
    completionItems() {
        if (!this.processedItemsCache) {
            let query = this._query;
            if (query) {
                const markedItems = this._markup(query);
                this.processedItemsCache = markedItems.map(it => it.processedItem);
                this._processedToOriginalItem = new WeakMap(markedItems.map(it => [it.processedItem, it.originalItem]));
            }
            else {
                this.processedItemsCache = this._completionItems.map(item => {
                    return this._escapeItemLabel(item);
                });
                this._processedToOriginalItem = null;
            }
        }
        return this.processedItemsCache;
    }
    /**
     * Set the list of visible items in the completer menu, and append any
     * new types to KNOWN_TYPES.
     */
    setCompletionItems(newValue) {
        if (_lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.JSONExt.deepEqual(newValue, this._completionItems)) {
            return;
        }
        this._completionItems = newValue;
        this._orderedTypes = Private.findOrderedCompletionItemTypes(this._completionItems);
        this.processedItemsCache = null;
        this._processedToOriginalItem = null;
        this._stateChanged.emit(undefined);
    }
    /**
     * The map from identifiers (a.b) to types (function, module, class, instance,
     * etc.).
     *
     * #### Notes
     * A type map is currently only provided by the latest IPython kernel using
     * the completer reply metadata field `_jupyter_types_experimental`. The
     * values are completely up to the kernel.
     *
     */
    typeMap() {
        return this._typeMap;
    }
    /**
     * An ordered list of all the known types in the typeMap.
     *
     * #### Notes
     * To visually encode the types of the completer matches, we assemble an
     * ordered list. This list begins with:
     * ```
     * ['function', 'instance', 'class', 'module', 'keyword']
     * ```
     * and then has any remaining types listed alphabetically. This will give
     * reliable visual encoding for these known types, but allow kernels to
     * provide new types.
     */
    orderedTypes() {
        return this._orderedTypes;
    }
    /**
     * Handle a cursor change.
     */
    handleCursorChange(change) {
        // If there is no active completion, return.
        if (!this._original) {
            return;
        }
        const { column, line } = change;
        const { current, original } = this;
        if (!original) {
            return;
        }
        // If a cursor change results in a the cursor being on a different line
        // than the original request, cancel.
        if (line !== original.line) {
            this.reset(true);
            return;
        }
        // If a cursor change results in the cursor being set to a position that
        // precedes the original column, cancel.
        if (column < original.column) {
            this.reset(true);
            return;
        }
        const { cursor } = this;
        if (!cursor || !current) {
            return;
        }
        // If a cursor change results in the cursor being set to a position beyond
        // the end of the area that would be affected by completion, cancel.
        const cursorDelta = cursor.end - cursor.start;
        const originalLine = original.text.split('\n')[original.line];
        const currentLine = current.text.split('\n')[current.line];
        const inputDelta = currentLine.length - originalLine.length;
        if (column > original.column + cursorDelta + inputDelta) {
            this.reset(true);
            return;
        }
    }
    /**
     * Handle a text change.
     */
    handleTextChange(change) {
        const original = this._original;
        // If there is no active completion, return.
        if (!original) {
            return;
        }
        const { text, column, line } = change;
        const last = text.split('\n')[line][column - 1];
        // If last character entered is not whitespace or if the change column is
        // greater than or equal to the original column, update completion.
        if ((last && last.match(/\S/)) || change.column >= original.column) {
            this.current = change;
            return;
        }
        // If final character is whitespace, reset completion.
        this.reset(false);
    }
    /**
     * Create a resolved patch between the original state and a patch string.
     *
     * @param patch - The patch string to apply to the original value.
     *
     * @returns A patched text change or undefined if original value did not exist.
     */
    createPatch(patch) {
        const original = this._original;
        const cursor = this._cursor;
        const current = this._current;
        if (!original || !cursor || !current) {
            return undefined;
        }
        let { start, end } = cursor;
        // Also include any filtering/additional-typing that has occurred
        // since the completion request in the patched length.
        end = end + (current.text.length - original.text.length);
        return { start, end, value: patch };
    }
    /**
     * Reset the state of the model and emit a state change signal.
     *
     * @param hard - Reset even if a subset match is in progress.
     */
    reset(hard = false) {
        // When the completer detects a common subset prefix for all options,
        // it updates the model and sets the model source to that value, triggering
        // a reset. Unless explicitly a hard reset, this should be ignored.
        if (!hard && this._subsetMatch) {
            return;
        }
        this._reset();
        this._stateChanged.emit(undefined);
    }
    /**
     * Check if CompletionItem matches against query.
     * Highlight matching prefix by adding <mark> tags.
     */
    _markup(query) {
        var _a;
        const items = this._completionItems;
        let results = [];
        for (const originalItem of items) {
            // See if label matches query string
            // With ICompletionItems, the label may include parameters,
            // so we exclude them from the matcher.
            // e.g. Given label `foo(b, a, r)` and query `bar`,
            // don't count parameters, `b`, `a`, and `r` as matches.
            const index = originalItem.label.indexOf('(');
            const text = index > -1
                ? originalItem.label.substring(0, index)
                : originalItem.label;
            const match = _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__.StringExt.matchSumOfSquares(escapeHTML(text), query);
            // Filter non-matching items.
            if (match) {
                // Highlight label text if there's a match
                let marked = _lumino_algorithm__WEBPACK_IMPORTED_MODULE_0__.StringExt.highlight(escapeHTML(originalItem.label), match.indices, Private.mark);
                // Use `Object.assign` to evaluate getters.
                const highlightedItem = Object.assign({}, originalItem);
                highlightedItem.label = marked.join('');
                highlightedItem.insertText =
                    (_a = originalItem.insertText) !== null && _a !== void 0 ? _a : originalItem.label;
            }
            // @TODO: @xavier: Not filter anything
            results.push({
                item: originalItem,
                score: match ? match.score : 0,
                originalItem
            });
        }
        // @xavier: We don't sort completion items.
        // results.sort(Private.scoreCmp);
        // console.log("results:", results);    
        // Extract only the item (dropping the extra score attribute to not leak
        // implementation details to JavaScript callers.
        return results.map(match => ({
            processedItem: match.item,
            originalItem: match.originalItem
        }));
    }
    /**
     * Lazy load missing data of an item.
     * @param indexOrValue - the item or its index
     * @remarks
     * Resolving item by index will be deprecated in
     * the JupyterLab 5.0 and removed in JupyterLab 6.0.
     *
     * @return Return `undefined` if the completion item with `activeIndex` index can not be found.
     *  Return a promise of `null` if another `resolveItem` is called. Otherwise return the
     * promise of resolved completion item.
     */
    resolveItem(indexOrValue) {
        let processedItem;
        if (typeof indexOrValue === 'number') {
            const completionItems = this.completionItems();
            if (!completionItems || !completionItems[indexOrValue]) {
                return undefined;
            }
            processedItem = completionItems[indexOrValue];
        }
        else {
            processedItem = indexOrValue;
        }
        if (!processedItem) {
            return undefined;
        }
        let originalItem;
        if (this._processedToOriginalItem) {
            originalItem = this._processedToOriginalItem.get(processedItem);
        }
        else {
            originalItem = processedItem;
        }
        if (!originalItem) {
            return undefined;
        }
        return this._resolveItemByValue(originalItem);
    }
    /**
     * Lazy load missing data of a completion item.
     *
     * @param  completionItem - the item to be resolved
     * @return See `resolveItem` method
     */
    _resolveItemByValue(completionItem) {
        const current = ++this._resolvingItem;
        let resolvedItem;
        if (completionItem.resolve) {
            let patch;
            if (completionItem.insertText) {
                patch = this.createPatch(completionItem.insertText);
            }
            resolvedItem = completionItem.resolve(patch);
        }
        else {
            resolvedItem = Promise.resolve(completionItem);
        }
        return resolvedItem
            .then(activeItem => {
            // Escape the label it in place
            this._escapeItemLabel(activeItem, true);
            Object.keys(activeItem).forEach((key) => {
                completionItem[key] = activeItem[key];
            });
            completionItem.resolve = undefined;
            if (current !== this._resolvingItem) {
                return Promise.resolve(null);
            }
            return activeItem;
        })
            .catch(e => {
            console.error(e);
            // Failed to resolve missing data, return the original item.
            return Promise.resolve(completionItem);
        });
    }
    /**
     * Escape item label, storing the original label and adding `insertText` if needed.
     * If escaping changes label creates a new item unless `inplace` is true.
     */
    _escapeItemLabel(item, inplace = false) {
        var _a;
        const escapedLabel = escapeHTML(item.label);
        // If there was no insert text, use the original (unescaped) label.
        if (escapedLabel !== item.label) {
            const newItem = inplace ? item : Object.assign({}, item);
            newItem.insertText = (_a = item.insertText) !== null && _a !== void 0 ? _a : item.label;
            newItem.label = escapedLabel;
            return newItem;
        }
        return item;
    }
    /**
     * Reset the state of the model.
     */
    _reset() {
        const hadQuery = this._query;
        this._current = null;
        this._cursor = null;
        this._completionItems = [];
        this._original = null;
        this._query = '';
        this.processedItemsCache = null;
        this._processedToOriginalItem = null;
        this._subsetMatch = false;
        this._typeMap = {};
        this._orderedTypes = [];
        if (hadQuery) {
            this._queryChanged.emit({ newValue: this._query, origin: 'reset' });
        }
    }
}
/**
 * A namespace for completer model private data.
 */
var Private;
(function (Private) {
    /**
     * The list of known type annotations of completer matches.
     */
    const KNOWN_TYPES = ['function', 'instance', 'class', 'module', 'keyword'];
    /**
     * The map of known type annotations of completer matches.
     */
    const KNOWN_MAP = KNOWN_TYPES.reduce((acc, type) => {
        acc[type] = null;
        return acc;
    }, {});
    /**
     * Mark a highlighted chunk of text.
     */
    function mark(value) {
        return `<mark>${value}</mark>`;
    }
    Private.mark = mark;
    /**
     * A sort comparison function for item match scores.
     *
     * #### Notes
     * This orders the items first based on score (lower is better), then
     * by locale order of the item text.
     */
    function scoreCmp(a, b) {
        var _a, _b, _c;
        const delta = a.score - b.score;
        if (delta !== 0) {
            return delta;
        }
        return (_c = (_a = a.item.insertText) === null || _a === void 0 ? void 0 : _a.localeCompare((_b = b.item.insertText) !== null && _b !== void 0 ? _b : '')) !== null && _c !== void 0 ? _c : 0;
    }
    Private.scoreCmp = scoreCmp;
    /**
     * Compute a reliably ordered list of types for ICompletionItems.
     *
     * #### Notes
     * The resulting list always begins with the known types:
     * ```
     * ['function', 'instance', 'class', 'module', 'keyword']
     * ```
     * followed by other types in alphabetical order.
     *
     */
    function findOrderedCompletionItemTypes(items) {
        const newTypeSet = new Set();
        items.forEach(item => {
            if (item.type &&
                !KNOWN_TYPES.includes(item.type) &&
                !newTypeSet.has(item.type)) {
                newTypeSet.add(item.type);
            }
        });
        const newTypes = Array.from(newTypeSet);
        newTypes.sort((a, b) => a.localeCompare(b));
        return KNOWN_TYPES.concat(newTypes);
    }
    Private.findOrderedCompletionItemTypes = findOrderedCompletionItemTypes;
    /**
     * Compute a reliably ordered list of types.
     *
     * #### Notes
     * The resulting list always begins with the known types:
     * ```
     * ['function', 'instance', 'class', 'module', 'keyword']
     * ```
     * followed by other types in alphabetical order.
     */
    function findOrderedTypes(typeMap) {
        const filtered = Object.keys(typeMap)
            .map(key => typeMap[key])
            .filter((value) => !!value && !(value in KNOWN_MAP))
            .sort((a, b) => a.localeCompare(b));
        return KNOWN_TYPES.concat(filtered);
    }
    Private.findOrderedTypes = findOrderedTypes;
})(Private || (Private = {}));


/***/ }),

/***/ "./lib/xavierCompleter/customconnector.js":
/*!************************************************!*\
  !*** ./lib/xavierCompleter/customconnector.js ***!
  \************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   XavierCompleterProvider: () => (/* binding */ XavierCompleterProvider)
/* harmony export */ });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "webpack/sharing/consume/default/lodash/lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/completer */ "webpack/sharing/consume/default/@jupyterlab/completer");
/* harmony import */ var _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_completer__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils */ "./lib/utils.js");
/* harmony import */ var _customModel__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./customModel */ "./lib/xavierCompleter/customModel.js");
/* harmony import */ var _pyTokenizer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pyTokenizer */ "./lib/xavierCompleter/pyTokenizer.js");
/* harmony import */ var _codePanelLink_highlightSidePanel__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../codePanelLink/highlightSidePanel */ "./lib/codePanelLink/highlightSidePanel.js");
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// Modified from jupyterlab/packages/completer/src/contextconnector.ts






function findCompletionLiCode() {
    let liCode = null;
    const allLI = [...document.querySelectorAll(".jp-Completer-item.jp-mod-active")];
    const findres = allLI.find((v) => {
        const childres = v.querySelector(".jp-Completer-match");
        const parent = v.parentElement;
        const pp = parent === null ? null : parent.parentElement;
        const isHidden = pp !== null && pp.classList.contains("lm-mod-hidden");
        return childres !== null && childres.textContent !== "Loading..." && !isHidden;
    });
    if (findres !== undefined) {
        liCode = findres.querySelector(".jp-Completer-match");
    }
    return liCode;
}
function insertText(editor, text, offset, yesNew) {
    // 1. add text
    let realText = text;
    const cursorTok = editor.getTokenAtCursor();
    if (yesNew && realText.startsWith(cursorTok.value)) {
        realText = realText.slice(cursorTok.value.length);
    }
    editor.model.sharedModel.updateSource(offset, offset, realText);
    // 2. modify style
    const newOffset = offset + realText.length;
    const newCursorPos = editor.getPositionAt(newOffset);
    if (newCursorPos !== undefined) {
        editor.setCursorPosition(newCursorPos);
    }
    else {
        console.error("[insertText] newCursorPos is undefined.");
    }
    return realText;
}
/**
 * A custom connector for completion handlers.
 */
class XavierCompleterProvider {
    constructor(_notebooks, _dataModel, _contextProvider, _kernelProvider) {
        this.rank = 5000; // Higher than the default provider means the priority is higher.
        this.identifier = 'CompletionProvider:custom';
        this.notebooks = undefined;
        this.contextProvider = undefined;
        this.kernelProvider = undefined;
        this.tempCompleter = undefined;
        this._fetchTimeout = null;
        // Variables for partial accept of completion items
        this.bufferTokens = [];
        this.currentEditor = null;
        this.addedBufferTokens = [];
        this.pCodeForLastTokenAccept = [];
        // Variables for side panel highlight
        // private lastAnalyze: AnalyzeCodeResp | null = null;
        this.currentCompItems = [];
        this.currentCompItemsIdx = -1;
        this.notebooks = _notebooks;
        this.contextProvider = _contextProvider;
        this.kernelProvider = _kernelProvider;
        this.dataModel = _dataModel;
        // Variables for partial accept of completion items
        this.addedBufferTokens = [];
        this.bufferTokens = [];
        this.currentEditor = null;
        this.pCodeForLastTokenAccept = [];
        // Variables for side panel highlight
        // this.lastAnalyze = null;
        this.currentCompItems = [];
        this.currentCompItemsIdx = -1;
        _notebooks.currentChanged.connect((_, widget) => {
            if (widget === null) {
                console.warn("[XavierCompleterProvider] no widget");
                return;
            }
        });
        this.tokenAcceptListener = this.tokenAcceptListener.bind(this);
        this.resetCurrentEditor = this.resetCurrentEditor.bind(this);
        this.tryGetNewBufferTokens = this.tryGetNewBufferTokens.bind(this);
        document.removeEventListener("keydown", this.tokenAcceptListener, true); // "true" means useCapture
        document.addEventListener("keydown", this.tokenAcceptListener, true);
    }
    resetCurrentEditor() {
        if (this.currentEditor !== null && !this.currentEditor.hasFocus()) {
            this.currentEditor = null;
            this.bufferTokens = [];
            this.addedBufferTokens = [];
        }
    }
    tryGetNewBufferTokens(nb) {
        let yesNew = false;
        if (this.bufferTokens.length === 0) {
            // try to fill the buffer
            const liCode = findCompletionLiCode();
            if (liCode !== null && liCode.textContent) {
                const newText = liCode.textContent;
                const txtTokens = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.tokenizePythonScript)(newText);
                this.bufferTokens = txtTokens;
                this.addedBufferTokens = [];
                if (this.currentEditor !== null) {
                    this.pCodeForLastTokenAccept = _utils__WEBPACK_IMPORTED_MODULE_3__.getPreviousText(nb, this.currentEditor.getCursorPosition());
                }
                yesNew = true;
            }
        }
        return yesNew;
    }
    canStillAddTokens(nb, edt) {
        const newPreviousCode2D = _utils__WEBPACK_IMPORTED_MODULE_3__.getPreviousText(nb, edt.getCursorPosition());
        const oldPreviousCode2D = this.pCodeForLastTokenAccept;
        // different number of cell
        if (newPreviousCode2D.length !== oldPreviousCode2D.length) {
            // console.log("not equal", newPreviousCode2D.length, oldPreviousCode2D.length);
            return false;
        }
        // different number of line
        for (let i = 0; i < newPreviousCode2D.length; i++) {
            if (newPreviousCode2D[i].length !== oldPreviousCode2D[i].length) {
                // console.log("not euql 2", newPreviousCode2D[i].length, oldPreviousCode2D[i].length);
                return false;
            }
        }
        // For old, must have at least one line
        if (oldPreviousCode2D.length === 0 || oldPreviousCode2D[oldPreviousCode2D.length - 1].length === 0) {
            // console.log("must one line", oldPreviousCode2D.length, oldPreviousCode2D[oldPreviousCode2D.length-1].length);
            return false;
        }
        // Whole comparison
        const buffStr = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.concatTokens)(this.addedBufferTokens);
        for (let i = 0; i < newPreviousCode2D.length; i++) {
            for (let j = 0; j < newPreviousCode2D[i].length; j++) {
                if (i === newPreviousCode2D.length - 1 && j === newPreviousCode2D[i].length - 1) {
                    if (newPreviousCode2D[i][j] !== oldPreviousCode2D[i][j] + buffStr) {
                        // console.log("not equal 4", newPreviousCode2D[i][j], "$$$", oldPreviousCode2D[i][j]+ buffStr);
                        return false;
                    }
                }
                else if (newPreviousCode2D[i][j] !== oldPreviousCode2D[i][j]) {
                    // console.log("not equal 3", newPreviousCode2D[i][j], "$$$", oldPreviousCode2D[i][j]);
                    return false;
                }
            }
        }
        return true;
    }
    tokenAcceptListener(e) {
        if (e.key === "ArrowRight" && e.ctrlKey && e.altKey && this.notebooks !== undefined) {
            this.resetCurrentEditor();
            const yesNew = this.tryGetNewBufferTokens(this.notebooks);
            if (this.bufferTokens.length !== 0 && this.currentEditor !== null && this.canStillAddTokens(this.notebooks, this.currentEditor)) {
                const cursorPos = this.currentEditor.getCursorPosition();
                const cursorOffset = this.currentEditor.getOffsetAt(cursorPos);
                const nextToken = this.bufferTokens.shift();
                if (nextToken === undefined) {
                    console.error("[tokenAcceptListener] no next token found.");
                    return;
                }
                const realInsert = insertText(this.currentEditor, nextToken.value, cursorOffset, yesNew);
                this.addedBufferTokens.push({
                    type: nextToken.type,
                    value: realInsert
                });
            }
        }
        else if ((e.key === "ArrowDown" || e.key === "ArrowUp") && this.notebooks !== undefined) {
            const liCode = findCompletionLiCode(); // Just to determine whether the completion menu is shown
            if (liCode !== null && liCode.textContent !== null && this.currentEditor !== null) {
                if (e.key === "ArrowDown") {
                    this.currentCompItemsIdx = (this.currentCompItemsIdx + 1) % this.currentCompItems.length;
                }
                else {
                    this.currentCompItemsIdx = (this.currentCompItemsIdx - 1 + this.currentCompItems.length) % this.currentCompItems.length;
                }
                const token = this.currentEditor.getTokenAtCursor();
                let lastLine = _utils__WEBPACK_IMPORTED_MODULE_3__.getLastLine(this.notebooks, this.currentEditor.getCursorPosition());
                lastLine = lastLine !== null ? _utils__WEBPACK_IMPORTED_MODULE_3__.removeSuffix(lastLine, token.value) : null;
                this.highlightInSidePanel(lastLine, this.currentCompItems[this.currentCompItemsIdx] === undefined ? null : this.currentCompItems[this.currentCompItemsIdx]);
            }
        }
    }
    modelFactory(context) {
        const m = new _customModel__WEBPACK_IMPORTED_MODULE_4__.CustomModel();
        return Promise.resolve(m);
    }
    shouldShowContinuousHint(completerIsVisible, changed, context) {
        if (!context || !context.editor) {
            // waiting for https://github.com/jupyterlab/jupyterlab/pull/15015 due to
            // https://github.com/jupyterlab/jupyterlab/issues/15014
            console.log("[shouldShowContinuousHint] no context");
            return false;
        }
        const editor = context.editor;
        const token = editor.getTokenAtCursor();
        // if (token.value === ")") {
        //   return false;
        // }
        // @TODO
        const triggerCharacters = [".", "'", '"'];
        const sourceChange = changed.sourceChange;
        if (sourceChange === undefined) {
            console.log("[shouldShowContinuousHint] no sourceChange");
            return false;
        }
        // if (sourceChange.some(delta => delta.delete != null)) {
        //   console.log("[shouldShowContinuousHint] delete", sourceChange);    
        //   return false;
        // }
        //@TODO by default
        const thisOptions = {
            settings: {
                composite: {
                    continuousHinting: true,
                    suppressContinuousHintingIn: [/*"Comment",*/ "BlockComment", "LineComment", /*"String"*/],
                    suppressTriggerCharacterIn: [/*"Comment",*/ "BlockComment", "LineComment", /*"String"*/]
                }
            }
        };
        if (thisOptions.settings.composite.continuousHinting) {
            // if token type is known and not ignored token type is ignored - show completer
            if (token.type && !thisOptions.settings.composite.suppressContinuousHintingIn.includes(token.type)) {
                return true;
            }
            // otherwise show it may still be shown due to trigger character
        }
        if (!token.type || thisOptions.settings.composite.suppressTriggerCharacterIn.includes(token.type)) {
            return false;
        }
        const yesShould = sourceChange.some(delta => (delta.insert != null) &&
            (triggerCharacters.includes(delta.insert) || (!completerIsVisible && delta.insert.trim().length > 0)));
        return yesShould;
    }
    /**
     * The context completion provider is applicable on all cases.
     * @param context - additional information about context of completion request
     */
    async isApplicable(context) {
        const widget = context.widget;
        if (typeof widget.context === 'undefined') {
            // there is no path for Console as it is not a DocumentWidget
            console.log("[isApplicable]: no context");
            return false;
        }
        return true;
    }
    /**
     * Fetch completion requests.
     *
     * @param request - The completion request text and details.
     * @returns Completion reply
     */
    async _fetch(request, context, trigger) {
        const editor = context.editor;
        if (!editor) {
            console.error("No editor found.");
            return Promise.reject('No editor');
        }
        const originItems = await Private.getOriginItems(request, context, editor, trigger, this.contextProvider, this.kernelProvider);
        const reply = await this._completionHint(editor, originItems, request, context.sanitizer);
        this.currentCompItems = reply.items.map((v) => v.label);
        this.currentCompItemsIdx = reply.items.length > 0 ? 0 : -1;
        return reply;
    }
    async fetch(request, context, trigger, delay = 500) {
        return new Promise((resolve, reject) => {
            if (this._fetchTimeout) {
                clearTimeout(this._fetchTimeout);
            }
            this._fetchTimeout = setTimeout(async () => {
                try {
                    const result = await this._fetch(request, context, trigger);
                    resolve(result);
                }
                catch (error) {
                    reject(error);
                }
            }, this.bufferTokens.length !== 0 ? 0 : delay);
        });
    }
    highlightInSidePanel(lastLine, compText) {
        if (this.dataModel === undefined || lastLine === null) {
            console.warn("[highlightInSidePanel] no dataModel or analyzeRes or lastLine found.");
            return;
        }
        const lastAndComp = lastLine + (compText === null ? "" : compText);
        const allTableColumns = {};
        Object.keys(this.dataModel.allDfInfo).forEach((k) => {
            allTableColumns[k] = this.dataModel.allDfInfo[k].columnNameList;
        });
        let newAllDfStyle = lodash__WEBPACK_IMPORTED_MODULE_0___default().cloneDeep(this.dataModel.allDfStyle);
        // 1. handle fold and unfold of dataframe
        (0,_codePanelLink_highlightSidePanel__WEBPACK_IMPORTED_MODULE_5__.resetAllColumnHighlight)(newAllDfStyle);
        const tableColumnsLL = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findAllTableColumn)(lastAndComp, allTableColumns);
        for (const t in tableColumnsLL) {
            newAllDfStyle[t].isFold = false;
        }
        (0,_codePanelLink_highlightSidePanel__WEBPACK_IMPORTED_MODULE_5__.resetAllDfFold)(tableColumnsLL, newAllDfStyle);
        // 3. handle show or hidden of columns
        // We only consider table mentioned in the code line. For table not mentioned, the column will always be shown
        for (const t in tableColumnsLL) {
            const cols = tableColumnsLL[t];
            newAllDfStyle[t].isShowRows = (cols.length > 0);
            for (const c in newAllDfStyle[t].columns) {
                // If cols is empty, show all columns
                newAllDfStyle[t].columns[c].isHighlight = (cols.includes(c));
            }
        }
        // 4. Preview format transformation of single column
        const fillnaTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findColumnFillnaTemp)(lastAndComp, allTableColumns);
        const strReplaceTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findColumnStrReplaceTemp)(lastAndComp, allTableColumns);
        const columnSelectTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findColumnSelectTemp)(lastAndComp, allTableColumns);
        const tableFilterTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findTableFilterTemp)(lastAndComp, allTableColumns);
        const tableConcatTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findTableConcatTemp)(lastAndComp, allTableColumns);
        const tableSortTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findTableSortTemp)(lastAndComp, allTableColumns);
        const pdMergeTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findPdMergeTemp)(lastAndComp, allTableColumns);
        const tableMergeTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findTableMergeTemp)(lastAndComp, allTableColumns);
        const groupbyTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findGroupby)(lastAndComp, allTableColumns);
        const columnAddTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findColumnAddTemp)(lastAndComp, allTableColumns);
        const columnRenameTemp = (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.findColumnRenameTemp)(lastAndComp, allTableColumns);
        if (fillnaTemp !== null) {
            this.dataModel.previewColumnFillna(fillnaTemp);
        }
        else if (strReplaceTemp !== null) {
            this.dataModel.previewStrReplace(strReplaceTemp);
        }
        else if (tableConcatTemp !== null) {
            this.dataModel.previewTableConcat(tableConcatTemp);
        }
        else if (pdMergeTemp !== null) {
            this.dataModel.previewTableMerge(pdMergeTemp, allTableColumns);
        }
        else if (tableMergeTemp !== null) {
            this.dataModel.previewTableMerge(tableMergeTemp, allTableColumns);
        }
        else if (tableSortTemp !== null) {
            this.dataModel.previewTableSort(tableSortTemp);
        }
        else if (columnSelectTemp !== null) {
            this.dataModel.previewColumnSelect(columnSelectTemp);
        }
        else if (tableFilterTemp !== null) {
            this.dataModel.previewTableFilter(tableFilterTemp);
        }
        else if (groupbyTemp !== null) {
            this.dataModel.previewGroupby(groupbyTemp);
        }
        else if (columnAddTemp !== null) {
            this.dataModel.previewColumnAdd(columnAddTemp);
        }
        else if (columnRenameTemp !== null) {
            this.dataModel.previewColumnRename(columnRenameTemp);
        }
        else {
            this.dataModel.resetPreviewItems();
        }
        console.log(`lastline: ${lastLine}, firstItem: ${compText}, pattern: ${lastAndComp}`, "strReplaceTemp", strReplaceTemp, "columnSelectTemp", columnSelectTemp, "tableFilterTemp", tableFilterTemp, "tableConcatTemp", tableConcatTemp, "tableSortTemp", tableSortTemp, "groupbyTemp", groupbyTemp, 'columnAddTemp', columnAddTemp, "fillnaTemp", fillnaTemp, "pdMergeTemp", pdMergeTemp, "tableMergeTemp", tableMergeTemp);
        this.dataModel.setAllDfStyle(newAllDfStyle);
    }
    async _completionHint(editor, originItems, request, sanitizer) {
        const token = editor.getTokenAtCursor();
        const res = {
            start: token.offset,
            end: token.offset + token.value.length,
            items: []
        };
        // vefify the parameters
        if (this.notebooks === undefined /*|| _.isEmpty(this.dataModel.allDfInfo)*/) {
            console.warn("[completionHint] no notebook tracker or no dfInfo found.");
            res.items = originItems;
            return res;
        }
        if (this.bufferTokens.length !== 0) {
            if (this.canStillAddTokens(this.notebooks, editor)) {
                res.items = [{
                        label: (0,_pyTokenizer__WEBPACK_IMPORTED_MODULE_2__.concatTokens)(this.bufferTokens),
                        type: "code"
                    }];
                return res;
            }
            else {
                this.bufferTokens = [];
                this.currentEditor = null;
                this.addedBufferTokens = [];
                this.pCodeForLastTokenAccept = [];
            }
        }
        // get previous code
        const previousCode2D = _utils__WEBPACK_IMPORTED_MODULE_3__.getPreviousText(this.notebooks, editor.getCursorPosition());
        let lastLine = _utils__WEBPACK_IMPORTED_MODULE_3__.getLastLine(this.notebooks, editor.getCursorPosition());
        lastLine = lastLine !== null ? _utils__WEBPACK_IMPORTED_MODULE_3__.removeSuffix(lastLine, token.value) : null;
        // get completer
        if (this.tempCompleter === undefined) {
            this.tempCompleter = Private.createTempCompleter(editor, originItems, request, sanitizer);
        }
        else {
            Private.updatePosOfTempCompleter(editor, this.tempCompleter);
        }
        this.tempCompleter.show();
        const queryRes = await this.dataModel.executor.exeCompleteCode(previousCode2D, token, this.dataModel.tableLvInfo, this.dataModel.rowLvInfo, this.dataModel.colLvInfo);
        // const queryRes: CompResult = await completeQuery(previousCode2D, token, this.dataModel.tableLvInfo, this.dataModel.rowLvInfo, this.dataModel.colLvInfo);
        this.tempCompleter.hide();
        // this.lastAnalyze = queryRes.analyzeResp;
        let items = _utils__WEBPACK_IMPORTED_MODULE_3__.deDuplicateCompletionItems(queryRes.tokenList);
        if (items.length === 0 && (token.value === "]" || token.value === ")")) {
            this.highlightInSidePanel(lastLine, null);
            return res;
        }
        // No need to concat originItems since the token start and end are different
        res.items = items.length > 0 ? items : originItems;
        const firstItem = res.items.length > 0 ? res.items[0].label : null;
        this.highlightInSidePanel(lastLine, firstItem);
        if (res.items.length !== 0) {
            this.currentEditor = editor;
        }
        console.log("[_completionHint] res:", res.items);
        return res;
    }
}
/**
 * A namespace for Private functionality.
 */
var Private;
(function (Private) {
    /**
     * Get a list of mocked completion hints.
     *
     * @param editor Editor
     * @returns Completion reply
     */
    async function getOriginItems(request, context, editor, trigger, contextProvider, kernelProvider) {
        const allItems = [];
        if (contextProvider && kernelProvider) {
            const f1 = await contextProvider.fetch(request, context, trigger);
            const f2 = await kernelProvider.fetch(request, context, trigger);
            allItems.push(...f1.items, ...f2.items);
        }
        return allItems.filter((v) => !v.label.startsWith("%"));
    }
    Private.getOriginItems = getOriginItems;
    function updatePosOfTempCompleter(editor, tempCompleter) {
        const cursorPos = editor.getCursorPosition();
        const cor = editor.getCoordinateForPosition(cursorPos);
        if (cor) {
            tempCompleter.node.style.top = cor.top + editor.lineHeight + "px";
            tempCompleter.node.style.left = cor.left + "px";
        }
        tempCompleter.node.classList.add("jp-HoverBox");
        return tempCompleter;
    }
    Private.updatePosOfTempCompleter = updatePosOfTempCompleter;
    function createTempCompleter(editor, originItems, request, sanitizer) {
        const cursorPos = editor.getCursorPosition();
        const fakeitems = new Array();
        fakeitems.push({ label: "Loading..." });
        fakeitems.push(...originItems);
        const tempCompleterModel = new _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_1__.CompleterModel();
        tempCompleterModel.setCompletionItems(fakeitems);
        tempCompleterModel.cursor = {
            start: request.offset,
            end: request.offset + request.text.length
        };
        // tempCompleterModel.current = {
        //   text: request.text,
        //   line: cursorPos.line + 200,
        //   column: cursorPos.column + 200
        // };
        // tempCompleterModel.original = {
        //   text: request.text,
        //   line: cursorPos.line + 400,
        //   column: cursorPos.column + 400
        // }
        const cor = editor.getCoordinateForPosition(cursorPos);
        const tempCompleter = new _jupyterlab_completer__WEBPACK_IMPORTED_MODULE_1__.Completer({
            editor: editor,
            model: tempCompleterModel,
            showDoc: true,
            sanitizer: sanitizer,
        });
        tempCompleter.onUpdateRequest("update-request"); // @TODO
        document.body.appendChild(tempCompleter.node);
        tempCompleter.node.style.position = "absolute";
        if (cor) {
            tempCompleter.node.style.top = cor.top + editor.lineHeight + "px";
            tempCompleter.node.style.left = cor.left + "px";
        }
        tempCompleter.node.style.height = "240px";
        tempCompleter.node.style.width = "200px";
        // tempCompleter.show();
        return tempCompleter;
    }
    Private.createTempCompleter = createTempCompleter;
    function hideTempCompleter(tempCompleter) {
        tempCompleter.hide();
        tempCompleter.node.remove();
        tempCompleter.dispose();
    }
    Private.hideTempCompleter = hideTempCompleter;
})(Private || (Private = {}));


/***/ }),

/***/ "./lib/xavierCompleter/pyTokenizer.js":
/*!********************************************!*\
  !*** ./lib/xavierCompleter/pyTokenizer.js ***!
  \********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   concatTokens: () => (/* binding */ concatTokens),
/* harmony export */   findAllTableColumn: () => (/* binding */ findAllTableColumn),
/* harmony export */   findColumnAddTemp: () => (/* binding */ findColumnAddTemp),
/* harmony export */   findColumnFillnaTemp: () => (/* binding */ findColumnFillnaTemp),
/* harmony export */   findColumnRenameTemp: () => (/* binding */ findColumnRenameTemp),
/* harmony export */   findColumnSelectTemp: () => (/* binding */ findColumnSelectTemp),
/* harmony export */   findColumnStrReplaceTemp: () => (/* binding */ findColumnStrReplaceTemp),
/* harmony export */   findGroupby: () => (/* binding */ findGroupby),
/* harmony export */   findPdMergeTemp: () => (/* binding */ findPdMergeTemp),
/* harmony export */   findTableConcatTemp: () => (/* binding */ findTableConcatTemp),
/* harmony export */   findTableFilterTemp: () => (/* binding */ findTableFilterTemp),
/* harmony export */   findTableMergeTemp: () => (/* binding */ findTableMergeTemp),
/* harmony export */   findTableSortTemp: () => (/* binding */ findTableSortTemp),
/* harmony export */   tokenizePythonScript: () => (/* binding */ tokenizePythonScript)
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./lib/utils.js");

function tokenizePythonScript(script) {
    const tokens = [];
    const keywords = new Set([
        'def', 'return', 'if', 'else', 'elif', 'while', 'for', 'in', 'break', 'continue',
        'pass', 'import', 'from', 'as', 'class', 'try', 'except', 'finally', 'with', 'assert',
        'yield', 'lambda', 'print', 'True', 'False', 'None'
    ]);
    const tokenPatterns = [
        [/\s+/, 'WHITESPACE'],
        [/[a-zA-Z_]\w*/, 'IDENTIFIER'],
        [/\d+(\.\d+)?/, 'NUMBER'],
        [/#[^\n]*/, 'COMMENT'],
        [/[+\-*/%=<>!]=?/, 'OPERATOR'],
        [/[{}()\[\],.:;]/, 'PUNCTUATION'],
        [/["'][^"']*["']/, 'STRING']
    ];
    let i = 0;
    while (i < script.length) {
        let matched = false;
        for (const [pattern, type] of tokenPatterns) {
            const regex = new RegExp(`^${pattern.source}`);
            const match = script.slice(i).match(regex);
            if (match) {
                matched = true;
                const value = match[0];
                if (type !== 'WHITESPACE' && type !== 'COMMENT') {
                    tokens.push({
                        type: keywords.has(value) ? 'KEYWORD' : type,
                        value
                    });
                }
                i += value.length;
                break;
            }
        }
        if (!matched) {
            console.error(`Unexpected token at index ${i}: ${script[i]}`);
            i++;
        }
    }
    return tokens;
}
function concatTokens(tokens) {
    return tokens.map(token => token.value).join('');
}
function findAllTableColumn(code, tablesColumns) {
    const tokens = tokenizePythonScript(code);
    const res = {};
    // Find all tables first
    tokens.forEach((t) => {
        if (t.type === "IDENTIFIER" && t.value in tablesColumns) {
            res[t.value] = [];
        }
    });
    // Find all columns
    const resKeys = Object.keys(res);
    const colPos = {};
    tokens.forEach((t, i) => {
        if (t.type === "STRING") {
            const colName = _utils__WEBPACK_IMPORTED_MODULE_0__.removeQuotes(t.value); //Remove quotes
            for (const table of resKeys) {
                if (tablesColumns[table].includes(colName)) {
                    if (colName in colPos) {
                        colPos[colName].tokPos.push(i);
                        colPos[colName].belongTable.push(table);
                    }
                    else {
                        colPos[colName] = { tokPos: [i], belongTable: [table] };
                    }
                }
            }
        }
    });
    // @TODO: may add rules to remove same column name in different tables
    // Construct result
    for (const colName in colPos) {
        const tableNames = colPos[colName].belongTable;
        for (const tableName of tableNames) {
            res[tableName].push(colName);
        }
    }
    // remove duplicated columns
    for (const tableName in res) {
        res[tableName] = Array.from(new Set(res[tableName]));
    }
    return res;
}
function findColumnFillnaTemp(code, tablesColumns) {
    // Example: df['A'] = df['A'].fillna("Unknown")
    // Example: df['A'] = df['A'].fillna(0)
    const regex = /(\w+)\[['"]([^'"]+)['"]\]\s*=\s*(\w+)\[['"]([^'"]+)['"]\]\.fillna\(\s*(["'][^'"]*["']|\d+)/;
    const match = code.match(regex);
    if (!(match && match.length === 6)) {
        return null;
    }
    const [_, newTableName, newColumnName, tableName, columnName, fillValue] = match;
    if (newTableName !== tableName || !(tableName in tablesColumns && tablesColumns[tableName].includes(columnName))) {
        return null;
    }
    return {
        table: tableName,
        column: columnName,
        fillValue: fillValue,
        newColumn: newColumnName // no quote
    };
}
function findColumnStrReplaceTemp(code, tablesColumns) {
    // Example: df1['B'] = df1['A'].str.replace('a', 'b'
    const regex = /(\w+)\[['"]([^'"]+)['"]\]\s*=\s*(\w+)\[['"]([^'"]+)['"]\]\.str\.replace\(\s*r?(['"])([^'"]+)\5,\s*r?(['"])([^'"]*)\7/;
    const match = code.match(regex);
    if (!(match && match.length === 9)) {
        return null;
    }
    const [_, newTableName, newColumnName, tableName, columnName, searchQuote, searchValue, replaceQuote, replaceValue] = match;
    if (newTableName !== tableName || !(tableName in tablesColumns && tablesColumns[tableName].includes(columnName))) {
        return null;
    }
    return {
        table: tableName,
        column: columnName,
        newColumn: newColumnName,
        oldPattern: searchQuote + searchValue + searchQuote,
        newValue: replaceQuote + replaceValue + replaceQuote // has quote
    };
}
;
function findColumnSelectTemp(code, tablesColumns) {
    // Example: df = df[['A', 'B', 'C'
    const regex = /(\w+)\s*=\s*(\w+)\[\[(.*)/;
    const match = code.match(regex);
    if (!(match && match.length === 4)) {
        return null;
    }
    const [_, newTable, table, columnsStr] = match;
    if (!(table in tablesColumns)) {
        return null;
    }
    let filterCond = _utils__WEBPACK_IMPORTED_MODULE_0__.getValidFilterCond(columnsStr);
    if (filterCond === null) {
        return null;
    }
    const columnsAndOccur = [];
    tablesColumns[table].forEach((col) => {
        const idx1 = filterCond === null || filterCond === void 0 ? void 0 : filterCond.indexOf(`"${col}"`);
        const idx2 = filterCond === null || filterCond === void 0 ? void 0 : filterCond.indexOf(`'${col}'`);
        if (idx1 !== undefined && idx1 !== -1) {
            columnsAndOccur.push({ name: col, occur: idx1 });
        }
        else if (idx2 !== undefined && idx2 !== -1) {
            columnsAndOccur.push({ name: col, occur: idx2 });
        }
        else {
            return;
        }
    });
    columnsAndOccur.sort((a, b) => a.occur - b.occur);
    const columns = columnsAndOccur.map((c) => c.name);
    return { table, newTable, columns };
}
function findTableFilterTemp(code, tablesColumns) {
    // Example: df2 = df1[df1["A"] > 0 && df1["B"] < 0 
    const regex = /(\w+)\s*=\s*(\w+)\[(.*)/;
    const match = code.match(regex);
    if (!(match && match.length === 4)) {
        return null;
    }
    const [_, newTableName, tableName, filterStr] = match;
    if (!(tableName in tablesColumns)) {
        return null;
    }
    if (filterStr.startsWith("[")) { // means column selection, not filter
        return null;
    }
    const leftPNum = _utils__WEBPACK_IMPORTED_MODULE_0__.countLetterInStr(filterStr, "[");
    const rightPNum = _utils__WEBPACK_IMPORTED_MODULE_0__.countLetterInStr(filterStr, "]");
    // Exclude such case: df = df["A"] + df["B"]. Should not let cond = `"A"] + df["B``
    let filterCond = _utils__WEBPACK_IMPORTED_MODULE_0__.getValidFilterCond(filterStr);
    if (filterCond === null) {
        return null;
    }
    if (filterCond.endsWith("]")) { // remove the last ']'
        if (leftPNum + 1 === rightPNum) {
            filterCond = filterCond.slice(0, -1);
        }
        else if (leftPNum + 1 < rightPNum) { // invalid
            return null;
        }
    }
    // Find filter values
    filterCond = filterCond.trim();
    let filterCondCopy = filterCond;
    const condValues = [];
    const regexCond = /(>=|<=|>|<|==|!=)\s*(['"][^'"]*['"]|\d+)/;
    let condMatch = filterCondCopy.match(regexCond);
    while (condMatch) {
        const [matchedStr, _op, value] = condMatch;
        const v = _utils__WEBPACK_IMPORTED_MODULE_0__.removeQuotes(value);
        condValues.push(v);
        filterCondCopy = filterCondCopy.replace(matchedStr, '');
        condMatch = filterCondCopy.match(regexCond);
    }
    return {
        newTable: newTableName,
        table: tableName,
        cond: filterCond,
        condValues: condValues
    };
}
function findTableConcatTemp(code, tablesColumns) {
    // Example: df = pd.concat([df1, df2, df3, 
    const concatRegex = /(\w+)\s*=\s*\w+\.concat\(\[([^\]]+)/;
    const match = code.match(concatRegex);
    if (match) {
        // Extract the new table name and the table names from the match
        const newTable = match[1].trim();
        const tables = match[2].split(',').map(table => table.trim());
        // Verify that each table name exists in the tablesColumns object
        const validTables = tables.filter(table => tablesColumns.hasOwnProperty(table));
        if (validTables.length === tables.length) {
            // Construct and return the ITableConcatParam object
            return { tables: validTables, newTable };
        }
    }
    // Return null if no valid concatenation is found
    return null;
}
function findTableSortTemp(code, tablesColumns) {
    // Example: df = df.sort_values(by=['A', 'B'], ascending=[True, False])
    // Example: df = df.sort_values(['A', 'B'], ascending=[True, False])
    // Example: df = df.sort_values(by='A', ascending=False)
    // Example: df2 = df.sort_values('A', ascending=False)
    // Example: df = df.sort_values('A')
    const regex = /(\w+)\s*=\s*(\w+)\.sort_values\s*\(\s*(?:by\s*=\s*)?(\[.*?\]|'.*?'|".*?")(?:\s*,\s*ascending\s*=\s*(\[.*?\]|True|False))?/;
    const match = code.match(regex);
    // console.log("match", match);
    // TODO: covid_19_data.sort_values(["Country / Region",
    // TODO: covid_19_data.sort_values(["Country / Region", "Province / State"], ascending=[True, 
    if (match) {
        const newTable = match[1].trim();
        const table = match[2].trim();
        let match3 = match[3].replace(/'/g, '"').replace(/"/g, '');
        match3 = _utils__WEBPACK_IMPORTED_MODULE_0__.removeBrackets(match3);
        const sortCols = match3.split(',').map(col => col.trim());
        let ascStr = match[4] ? match[4].replace(/'/g, '"').replace(/"/g, '') : 'True';
        ascStr = _utils__WEBPACK_IMPORTED_MODULE_0__.removeBrackets(ascStr);
        const asc = ascStr === 'True' ? [true] : ascStr === 'False' ? [false] : ascStr.split(',').map(a => a.trim() === 'True');
        if (tablesColumns.hasOwnProperty(table) && sortCols.every(col => tablesColumns[table].includes(col))) {
            return { table, newTable, sortCols, asc };
        }
    }
    return null;
}
function findPdMergeTemp(code, tablesColumns) {
    // Example: df = pd.merge(df1, df2, on='A', how='inner')
    // @TODO: aquire alias of pandas
    const regexPd = /(\w+)\s*=\s*pd\.merge\s*\(\s*(\w+)\s*,\s*(\w+)/;
    const matchPd = code.match(regexPd);
    if ((matchPd === null || matchPd === void 0 ? void 0 : matchPd.index) !== undefined) {
        // Find tables
        const newTable = matchPd[1].trim();
        const leftTable = matchPd[2].trim();
        const rightTable = matchPd[3].trim();
        // Find columns
        let leftCol = null;
        let rightCol = null;
        const optionStr = code.slice(matchPd.index + matchPd[0].length);
        // Find the pattern `on='A'`
        const onRegex = /on\s*=\s*['"]([^'"]+)['"]/;
        const onMatch = optionStr.match(onRegex);
        // Find the pattern `left_on='A'`
        const leftOnRegex = /left_on\s*=\s*['"]([^'"]+)['"]/;
        const leftOnMatch = optionStr.match(leftOnRegex);
        // Find the pattern `right_on='A'`
        const rightOnRegex = /right_on\s*=\s*['"]([^'"]+)['"]/;
        const rightOnMatch = optionStr.match(rightOnRegex);
        if (leftOnMatch || rightOnMatch) {
            if (leftOnMatch) {
                leftCol = leftOnMatch[1];
            }
            if (rightOnMatch) {
                rightCol = rightOnMatch[1];
            }
        }
        else if (onMatch) {
            leftCol = onMatch[1];
            rightCol = onMatch[1];
        }
        // Find how
        let how = null;
        // Find the pattern `how='inner'`
        const howRegex = /how\s*=\s*['"]([^'"]+)['"]/;
        const howMatch = optionStr.match(howRegex);
        if (howMatch) {
            how = howMatch[1];
        }
        // Roughly check
        if (tablesColumns.hasOwnProperty(leftTable) && tablesColumns.hasOwnProperty(rightTable)) {
            return { newTable, leftTable, rightTable, leftCol, rightCol, how };
        }
    }
    return null;
}
function findTableMergeTemp(code, tablesColumns) {
    // Example: df = df1.merge(df2, on='A', how='inner')
    const regex = /(\w+)\s*=\s*(\w+)\.merge\s*\(\s*(\w+)\s*/;
    const match = code.match(regex);
    if ((match === null || match === void 0 ? void 0 : match.index) !== undefined) {
        // Find tables
        const newTable = match[1].trim();
        const leftTable = match[2].trim();
        const rightTable = match[3].trim();
        // Find columns
        let leftCol = null;
        let rightCol = null;
        const optionStr = code.slice(match.index + match[0].length);
        // Find the pattern `on='A'`
        const onRegex = /on\s*=\s*['"]([^'"]+)['"]/;
        const onMatch = optionStr.match(onRegex);
        // Find the pattern `left_on='A'`
        const leftOnRegex = /left_on\s*=\s*['"]([^'"]+)['"]/;
        const leftOnMatch = optionStr.match(leftOnRegex);
        // Find the pattern `right_on='A'`
        const rightOnRegex = /right_on\s*=\s*['"]([^'"]+)['"]/;
        const rightOnMatch = optionStr.match(rightOnRegex);
        if (leftOnMatch || rightOnMatch) {
            if (leftOnMatch) {
                leftCol = leftOnMatch[1];
            }
            if (rightOnMatch) {
                rightCol = rightOnMatch[1];
            }
        }
        else if (onMatch) {
            leftCol = onMatch[1];
            rightCol = onMatch[1];
        }
        // Find how
        let how = null;
        // Find the pattern `how='inner'`
        const howRegex = /how\s*=\s*['"]([^'"]+)['"]/;
        const howMatch = optionStr.match(howRegex);
        if (howMatch) {
            how = howMatch[1];
        }
        // Roughly check
        if (tablesColumns.hasOwnProperty(leftTable) && tablesColumns.hasOwnProperty(rightTable)) {
            return { newTable, leftTable, rightTable, leftCol, rightCol, how };
        }
    }
    return null;
}
function findGroupby(code, tablesColumns) {
    //example: df2 = df.groupby("col1")[["col2", "col3", ...]].sum()
    //example: df = df.groupby(["col1", "col2"])[["col3"]].avg()
    //example: df2 = df1.groupby("col1").sum()
    // const regex = /(\w+)\s*=\s*(\w+)\.groupby\((.*?)\)\s*\[?\[?(.*?)?\]?\]?\.(\w+)\(\)/;
    const regex = /(\w+)\s*=\s*(\w+)\.groupby\((.*?)\)\s*\[?\[?(.*?)?\]?\]?\.(\w+)/;
    const match = code.match(regex);
    // console.log('[groupby match]', match);
    if (match) {
        const newTableName = match[1].trim();
        const tableName = match[2].trim();
        let match3 = match[3].replace(/'/g, '"').replace(/"/g, '');
        match3 = _utils__WEBPACK_IMPORTED_MODULE_0__.removeBrackets(match3);
        const groupbyCols = match3.split(',').map(col => col.trim()); // groupby里的所有列
        let selectCols = null;
        if (match[4] !== undefined) {
            let match4 = match[4].replace(/'/g, '"').replace(/"/g, '');
            match4 = _utils__WEBPACK_IMPORTED_MODULE_0__.removeBrackets(match4);
            selectCols = match4.split(',').map(col => col.trim()); // groupby之后选择了哪些列
        }
        const aggFunc = match[5]; // 聚合函数名
        // console.log('[groupby match] code:',code, match, 'newTableName:', newTableName, 'tableName:', tableName, 'groupbyCols:', groupbyCols,'selectCols:', selectCols, 'aggFunc:', aggFunc);
        if (!(tableName in tablesColumns)) {
            return null;
        }
        if (groupbyCols) {
            groupbyCols.forEach(col => {
                if (!tablesColumns[tableName].includes(col)) {
                    return null;
                }
            });
        }
        if (selectCols) {
            selectCols.forEach(col => {
                if (!tablesColumns[tableName].includes(col)) {
                    return null;
                }
            });
        }
        return {
            newTableName,
            tableName,
            groupbyCols,
            selectCols,
            aggFunc
        };
    }
    return null;
}
function findColumnAddTemp(code, tablesColumns) {
    const addregex = /(\w+)\[['"]([^'"]+)['"]\]\s*=\s*((?:\w+\[['"]\w+['"]\]?\s*(?:\+\s*)?)*)/;
    const divRegex = /(\w+)\[['"]([^'"]+)['"]\]\s*=\s*((?:\w+\[['"]\w+['"]\]?\s*(?:\/\s*)?)*)/;
    let operator = '';
    const addMatch = code.match(addregex);
    const divMatch = code.match(divRegex);
    let match = null;
    if (addMatch && divMatch) {
        if (addMatch[3].length > divMatch[3].length) {
            operator = '+';
            match = addMatch;
        }
        else if (divMatch) {
            operator = '/';
            match = divMatch;
        }
    }
    if (match) {
        // console.log('[add && div match]', match)
        // 提取DataFrame名称、被赋值的列名
        const tableName = match[1].trim(); // DataFrame的名称
        const assignedColumn = match[2].trim(); // 被赋值的列名
        const expressions = match[3]; // 剩余的表达式部分（相加的列）
        if (!(tableName in tablesColumns)) {
            return null;
        }
        // 使用正则表达式提取相加的所有列
        const columnRegex = /(\w+)\[['"]([^'"]+)['"]\]?/g;
        let columnMatch;
        let addedColumns = [];
        let addedTable = [];
        while ((columnMatch = columnRegex.exec(expressions)) !== null) {
            addedTable.push(columnMatch[1]); // 相加的表名
            addedColumns.push(columnMatch[2]); // 相加的列名
        }
        // 检查所有表是否一致
        for (let table of addedTable) {
            if (table !== tableName) {
                return null;
            }
        }
        if (divMatch) { //必须大于两列才能做除法
            if (addedColumns.length < 2) {
                return null;
            }
        }
        // 检查所有列名是否在指定的表中
        for (let col of addedColumns) {
            if (!tablesColumns[tableName].includes(col)) {
                return null;
            }
        }
        console.log('[column add match]', "code:", code, "tableName:", "match:", match, tableName, "assignedColumn:", assignedColumn, "addedColumns:", addedColumns);
        return {
            table: tableName,
            column: assignedColumn,
            addedColumns: addedColumns,
            operator: operator
        };
    }
    return null;
}
function findColumnRenameTemp(code, tablesColumns) {
    // Example: df_renamed = df.rename(columns={'A': 'Column1', 'B': 'Column2'})
    const regex = /(\w+)\s*=\s*(\w+)\.rename\((.*)\)?/;
    const match = code.match(regex);
    console.log('[column rename match]', code, match);
    if (match) {
        const tableName = match[2].trim();
        //解析columns中的值
        let columnRegex = /columns\s*=\s*\{\s*['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/;
        let columns = match[3];
        let columnsMatch = columns.match(columnRegex);
        if (columnsMatch === null)
            return null;
        const [_, oldColName, newColName] = columnsMatch;
        // console.log('[column rename match columns]', match[3], columnsMatch, oldColName, newColName);
        if (!(tableName in tablesColumns && tablesColumns[tableName].includes(oldColName))) {
            return null;
        }
        return {
            table: tableName,
            oldColName: oldColName,
            newColName: newColName,
        };
    }
    return null;
}


/***/ })

}]);
//# sourceMappingURL=lib_index_js.7af5bdf42aad82443824.js.map