<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {html, LitElement} from "lit";
import {JSONEditor} from "vanilla-jsoneditor";
import NotificationUtils from "./utils/notification-utils.js";
import UtilsNew from "../../core/utils-new.js";
import LitUtils from "./utils/lit-utils.js";
import "../download-button.js";

export default class JsonEditor extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            data: {
                type: Object
            },
            active: {
                type: Boolean
            },
            config: {
                type: Object
            }
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);
        this.jsonEditor = null;
        this.jsonEditorId = this._prefix + "jsoneditor";
        this._config = this.getDefaultConfig();
    }

    update(changedProperties) {
        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }

        super.update(changedProperties);
    }

    updated(changedProperties) {
        if (changedProperties.has("data")) {
            // If element exist and the jsonEditor Obj not exist
            if (document.getElementById(this.jsonEditorId) && !this.jsonEditor) {
                this.initJsonEditor();
            }

            if (this.jsonEditor) {
                this.jsonEditor.update({json: this.data});
            }

            // this.disabledTransformContextMenu();

        }
    }

    initJsonEditor() {
        const content = {
            json: this.data ? this.data : {}
        };

        const editorElm = document.getElementById(this.jsonEditorId);
        // Create Editor
        this.jsonEditor = new JSONEditor({
            target: editorElm,
            props: {
                content,
                mode: this._config?.mode || "text",
                indentation: this._config?.indentation || 4,
                readOnly: this._config?.readOnly ?? false,
                onChange: (updatedContent, previousContent, {contentErrors, patchResult}) =>
                    this.onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}),
                onError: err => {
                    NotificationUtils.dispatch(this, NotificationUtils.NOTIFY_ERROR, {
                        message: err
                    });
                },
                onRenderMenu: (mode, items) => {
                    // Remove transforms we don't need for the moment
                    console.log("test items", items);
                    return items.filter(item => item.className !== "jse-transform");
                },
            }
        });
    }

    disabledTransformContextMenu() {
        console.log("context", this);
        const btnsElements = this.querySelectorAll(".jse-contextmenu button");
        const transformBtn = Array.from(btnsElements).filter(btn => btn?.innerText === " Transform");
        transformBtn[0].disabled = true;
    }

    onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}) {
        console.log("onChange", {updatedContent, previousContent, contentErrors, patchResult});
        // updatedContent is a object which content 2 props (text & json)
        this.data = updatedContent.text ? JSON.parse(updatedContent.text) : updatedContent.json;
        LitUtils.dispatchCustomEvent(this, "fieldChange", {
            json: {...this.data},
            text: updatedContent?.text
        }, null);
    }

    render() {
        if (!this.data && !this.jsonEditor) {
            return html`<h4>No valid data found</h4>`;
        }

        return html`
            ${this._config.showDownloadButton ? html`
                <div class="text-right">
                    <download-button
                        .json="${this.data}"
                        class="btn-sm">
                    </download-button>
                </div>
            ` : null
            }

            <div style="padding-top: 10px" id="${this.jsonEditorId}"></div>
        `;
    }<commit_msg>wc: minor improvement json-editor #TASK-2217<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {html, LitElement} from "lit";
import {JSONEditor} from "vanilla-jsoneditor";
import NotificationUtils from "./utils/notification-utils.js";
import UtilsNew from "../../core/utils-new.js";
import LitUtils from "./utils/lit-utils.js";
import "../download-button.js";

export default class JsonEditor extends LitElement {

    constructor() {
        super();
        this.#init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            data: {
                type: Object
            },
            active: {
                type: Boolean
            },
            config: {
                type: Object
            }
        };
    }

    #init() {
        this._prefix = UtilsNew.randomString(8);
        this.jsonEditor = null;
        this.jsonEditorId = this._prefix + "jsoneditor";
        this._config = this.getDefaultConfig();
        this._data = "";
    }

    update(changedProperties) {
        if (changedProperties.has("config")) {
            this._config = {...this.getDefaultConfig(), ...this.config};
        }

        super.update(changedProperties);
    }

    updated(changedProperties) {
        if (changedProperties.has("data")) {
            // If element exist and the jsonEditor Obj not exist
            if (document.getElementById(this.jsonEditorId) && !this.jsonEditor) {
                this.initJsonEditor();
            }

            if (this.jsonEditor && !UtilsNew.isEqual(JSON.stringify(this._data), JSON.stringify(this.data))) {
                // It is updated twice, to avoid the need to compare data.
                this.jsonEditor.update({json: this.data});
            }

            // this.disabledTransformContextMenu();

        }
    }


    initJsonEditor() {
        const content = {
            json: this.data ? this.data : {}
        };

        const editorElm = document.getElementById(this.jsonEditorId);
        // Create Editor
        this.jsonEditor = new JSONEditor({
            target: editorElm,
            props: {
                content,
                mode: this._config?.mode || "text",
                indentation: this._config?.indentation || 4,
                readOnly: this._config?.readOnly ?? false,
                onChange: (updatedContent, previousContent, {contentErrors, patchResult}) =>
                    this.onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}),
                onError: err => {
                    NotificationUtils.dispatch(this, NotificationUtils.NOTIFY_ERROR, {
                        message: err
                    });
                },
                onRenderMenu: (mode, items) => {
                    // Remove transforms we don't need for the moment
                    return items.filter(item => item.className !== "jse-transform");
                },
            }
        });
    }

    disabledTransformContextMenu() {
        console.log("context", this);
        const btnsElements = this.querySelectorAll(".jse-contextmenu button");
        const transformBtn = Array.from(btnsElements).filter(btn => btn?.innerText === " Transform");
        transformBtn[0].disabled = true;
    }

    onFilterChange(updatedContent, previousContent, {contentErrors, patchResult}) {
        console.log("onChange", {updatedContent, previousContent, contentErrors, patchResult});
        // updatedContent is a object which content 2 props (text & json)
        this.data = updatedContent.text ? JSON.parse(updatedContent.text) : updatedContent.json;
        // Copy the updated content
        this._data = updatedContent.text ? JSON.parse(updatedContent.text) : updatedContent.json;
        LitUtils.dispatchCustomEvent(this, "fieldChange", {
            json: {...this.data},
            text: updatedContent?.text
        }, null);
    }

    render() {
        if (!this.data && !this.jsonEditor) {
            return html`<h4>No valid data found</h4>`;
        }

        return html`
            ${this._config.showDownloadButton ? html`
                <div class="text-right">
                    <download-button
                        .json="${this.data}"
                        class="btn-sm">
                    </download-button>
                </div>
            ` : null
            }

            <div style="padding-top: 10px" id="${this.jsonEditorId}"></div>
        `;
    }
{'fraction_non_alphanumeric': 0.11504065040650406, 'fraction_numerical': 0.004471544715447155, 'mean_word_length': 1.8458646616541354, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5312306', 'n_tokens_mistral': 2540, 'n_tokens_neox': 2419, 'n_words': 617}