Your IP : 216.73.216.79


Current Path : /var/www/html/brspace/backend/modules/uiuxBuilder/widgets/
Upload File :
Current File : /var/www/html/brspace/backend/modules/uiuxBuilder/widgets/AdvanceContentEditor.php

<?php

namespace backend\modules\uiuxBuilder\widgets;

use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

class AdvanceContentEditor extends Widget
{
    public $containerId;

    public $field;

    public $is_update;

    public $content;

    public array $modules = ['grapejs', 'keditor', 'ace', 'ai-article'];

    public static $assetInit = true;

    public function init()
    {
        parent::init();
        if ($this->containerId === null) {
            $this->containerId = 'content-main';
        }
    }

    public function run()
    {   
        /** url **/
        $urlgettoken = Url::to(['/aidynaweb/ai-dynaweb/get-bearer']);

        /** request **/
        $request = \Yii::$app->request;

        /** render once **/
        $render_once = null;

        if(self::$assetInit) {
            /**extra asset **/

            /** loading spinner **/
            $this->view->params['extra-asset']['JS'][]  = 'plugins/ladda/spin.min.js';
            $this->view->params['extra-asset']['JS'][]  = 'plugins/ladda/ladda.min.js';
            $this->view->params['extra-asset']['JS'][]  = 'plugins/ladda/ladda.jquery.min.js';
            $this->view->params['extra-asset']['CSS'][] = 'plugins/ladda/ladda-themeless.min.css';

            /** url **/
            $urlgettoken = Url::to(['/aidynaweb/ai-dynaweb/get-bearer']);

            /** request **/
            $request = \Yii::$app->request;

            $this->view->registerCssFile('@web/plugins/summernote/summernote.min.css');
            $this->view->registerJsFile('@web/plugins/summernote/summernote.min.js', ['depends' => [\yii\web\JqueryAsset::className()]]);
        
            /** javascript **/
            $this->view->registerJs(
            <<<JS
                $('.btn-code-editor-ai-assistant').click(function(e){
                    $('.ai-assist-modal').modal('show');

                    $('.send-to-api-ai').click(async function() {
                        try {
                            console.log(e)
                            /** validate form **/
                            if(!document.querySelector('#get-ai-article-{$this->getId()}').reportValidity()) {
                                return;
                            }
                            
                            /** data **/
                            const nonce = Math.floor(new Date().getTime() / 1000);

                            const data  = {
                                topic: $('#topic').val(),
                                style: $('#style').val(),
                                language: $('#language').val(),
                                nonce: nonce
                            }

                            /** loading start **/
                            loading_start()
                            
                            /** get token **/
                            const token = await getToken(data)

                            /** get response **/
                            const resp  = await getAiArticle(token, data)

                            /** parse **/
                            const content = parseResponse(resp)
                            setContent(content, e.currentTarget.dataset.containerId)

                            /** loading stop **/
                            loading_stop()
                            $('.ai-assist-modal').modal('hide');
                        
                        } catch(e) {
                            console.log(e)
                            alert(e)
                        }
                    }.bind(e));
                });

                function loading_start() {
                    const l = Ladda.create(document.querySelector('.ladda-button'));
                    l.start();
                }

                function loading_stop() {
                    const l = Ladda.create(document.querySelector('.ladda-button'));
                    l.stop();
                }

                function parseResponse(response) {
                    if(!response.success) { 
                        throw new Error("Error Processing Request");
                    }
                    
                    answer = response.answer.replace(/(?:\\r\\n|\\r|\\n)/g, '<br>');
                    const wrap = '<p>' + answer + '</p>'
                    return wrap;
                }

                async function getAiArticle(token, {topic, style, language, nonce}) {
                    if(!token.success) {
                        throw new Error("Error Getting Token");
                    }
                        
                    const url = `https://ai.dynaweb4.work/api/json/query_article`;
                    // const url = `http://father-mediawiki.gl.at.ply.gg:6625/api/json/query_article`;
                    const resp = await fetch(url, {
                        method: 'post',
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": "Bearer " + token.token
                        },
                        body: JSON.stringify({
                            topic: topic,
                            style: style,
                            language: language,
                            nonce: nonce
                        })
                    });
                    return await resp.json();
                }

                function setContent(content, container_id) {

                    var textEditorVisible = $('#btn-code-editor-' + container_id).is(":visible");
                    var codeEditorVisible = $('#btn-text-editor-' + container_id).is(":visible");
                    if (textEditorVisible === true) {
                        $('#' + container_id).summernote("code", content);
                    } else if(codeEditorVisible === true) {
                        var editor = ace.edit('ace-editor-' + container_id);
                        editor.setValue(content);
                    } else {
                        $('#' + container_id).summernote("code", content); //default
                    }

                }

                async function getToken({token, topic, style, language, nonce}) {

                    payload = topic + style + language

                    const formData = new FormData();

                    formData.append('payload', payload);
                    formData.append('nonce', nonce);
                    formData.append('$request->csrfParam', '$request->csrfToken');

                    const urltoken = `$urlgettoken`;
                    const resp = await fetch(urltoken, {
                        method: 'post',
                        body: formData
                    });

                    return await resp.json()
                }

                window.usetexteditor = function usetexteditor(id) {

                    var editor = ace.edit('ace-editor-' + id);
                    var currentContent = editor.getValue();
                    editor.destroy();
                    $('#ace-editor-' + id).css({"min-height": "0px", "height": "0px"});

                    $('#' + id).summernote({
                        height: 300,
                        toolbar: [
                            ['style', ['style']],
                            ['font', ['bold', 'italic', 'underline', 'clear']],
                            ['fontname', ['fontname']],
                            ['fontsize', ['fontsize']],
                            ['color', ['color']],
                            ['para', ['ul', 'ol', 'paragraph']],
                            ['height', ['height']],
                            ['table', ['table']],
                            ['insert', ['link', 'picture', 'hr']],
                            ['view', ['fullscreen', 'codeview']],
                            ['help', ['help']]
                        ],
                    });
                    $('#' + id).summernote("code", currentContent);

                    $('#btn-code-editor-' + id).show();
                    $('#btn-text-editor-' + id).hide();
                }

                window.usecodeeditor = function usecodeeditor(id) {

                    var currentContent = $('#' + id).summernote('code');
                    $('#' + id).summernote('destroy');

                    var textarea = $('#' + id).hide();
                    var editor = ace.edit('ace-editor-' + id);
                    editor.setValue(currentContent);
                    editor.setOptions({maxLines: Infinity});
                    editor.setTheme("ace/theme/monokai");
                    editor.getSession().setMode("ace/mode/php");
                    //editor.getSession().setValue(textarea.val());
                    editor.getSession().on('change', function () {
                        textarea.val(editor.getSession().getValue());
                    });
                    $('#ace-editor-' + id).css({"min-height": "360px"});

                    $('#btn-code-editor-' + id).hide();
                    $('#btn-text-editor-' + id).show();
                }

                window.changecategory = function changecategory(parent_code) {
                    $.ajax({
                        url: "getsubcategory?parent_code=" + parent_code,
                        method: "GET",
                        success: function (response) {
                            $('#contentarticle-article_subcategory').html(response);
                        },
                    });
                }

                window.openbuilder = function openbuilder(contentID) {
                    $('#input-hidden-{$this->containerId}').val(contentID);
                    var textEditorVisible = $('#btn-code-editor-' + contentID).is(":visible");
                    var codeEditorVisible = $('#btn-text-editor-' + contentID).is(":visible");
                    var content = '';
                    if (textEditorVisible === true) {
                        content = $('#' + contentID).summernote('code');
                    }
                    if (codeEditorVisible === true) {
                        var editor = ace.edit('ace-editor-' + contentID);
                        content = editor.getValue();
                    }

                    var url = '/admin/uiuxBuilder/uiux-templates/design';
                    params = 'width=' + screen.width;
                    params += ', height=' + screen.height;
                    params += ', top=0, left=0'
                    params += ', fullscreen=yes';
                    params += ', directories=no';
                    params += ', location=no';
                    params += ', menubar=no';
                    params += ', resizable=no';
                    params += ', scrollbars=no';
                    params += ', status=no';
                    params += ', toolbar=no';
                    newwin = window.open(url, 'FullWindowAll', params);

                    newwin.addEventListener("load", function () {
                        newwin.$('#content-area').keditor('setContent', `
                            <div class="row"><div class="col-sm-12" data-type="container-content">\${content}</div></div>
                            <div class="keditor-ui keditor-toolbar keditor-toolbar-bottom keditor-toolbar-bottom-container">
                                <a href="javascript:void(0)" class="keditor-ui btn-add-content" title="Add content below"><i class="fa fa-plus"></i></a>
                                <a href="javascript:void(0)" class="keditor-ui btn-paste-content" title="Paste content below"><i class="fa fa-paste"></i></a>
                            </div>
                        `);
                    });

                    if (window.focus) {
                        newwin.focus();
                    }
                    return false;
                }

                window.openbuilderGrapeJs = function openbuilderGrapeJs(contentID) {
                    $('#input-hidden-{$this->containerId}').val(contentID);
                    var textEditorVisible = $('#btn-code-editor-' + contentID).is(":visible");
                    var codeEditorVisible = $('#btn-text-editor-' + contentID).is(":visible");
                    var content = '';
                    if (textEditorVisible === true) {
                        content = $('#' + contentID).summernote('code');
                    }
                    if (codeEditorVisible === true) {
                        var editor = ace.edit('ace-editor-' + contentID);
                        content = editor.getValue();
                    }

                    console.log(textEditorVisible, codeEditorVisible, content)

                    var url = '/admin/uiuxBuilder/uiux-templates/design-grape';
                    params = 'width=' + screen.width;
                    params += ', height=' + screen.height;
                    params += ', top=0, left=0'
                    params += ', fullscreen=yes';
                    params += ', directories=no';
                    params += ', location=no';
                    params += ', menubar=no';
                    params += ', resizable=no';
                    params += ', scrollbars=no';
                    params += ', status=no';
                    params += ', toolbar=no';
                    newwin = window.open(url, 'FullWindowAll', params);

                    newwin.addEventListener("load", function () {
                        console.log(newwin);
                        newwin.$('#gjs').html(content);
                        newwin.run();
                    });

                    if (window.focus) {
                        newwin.focus();
                    }
                    return false;
                }

                window.HandlePopupResult = function HandlePopupResult(result) {
                    var contentID = $('#input-hidden-{$this->containerId}').val();
                    var textEditorVisible = $('#btn-code-editor-' + contentID).is(":visible");
                    var codeEditorVisible = $('#btn-text-editor-' + contentID).is(":visible");
                    if (textEditorVisible === true) {
                        $('#' + contentID).summernote("code", result);
                    }
                    if (codeEditorVisible === true) {
                        var editor = ace.edit('ace-editor-' + contentID);
                        editor.setValue(result);
                    }
                }

            JS
            );
            self::$assetInit = false;

            $render_once = $this->render('modal', [
                'container_id' =>  $this->containerId,
                'widget_id' => $this->getId(),
                'field' => $this->field
            ]);
        }

        ///////////////MULTIPLE RENDERING BASED ON NUMBER OF WIDGET///////////////
        
        /** javascript **/
        $this->view->registerJs(
        <<<JS
                
            $('.{$this->field['class']}').summernote({
            height: 300,
            toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'clear']],
                    ['fontname', ['fontname']],
                    ['fontsize', ['fontsize']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['height', ['height']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'hr']],
                    ['view', ['fullscreen', 'codeview']],
                    ['help', ['help']]
            ],
            });
        JS
        );
        return 
            $render_once //only render once, for reusable element
            . 
            $this->render('main', [ // multiple based on widget count
            'container_id' =>  $this->containerId,
            'widget_id' => $this->getId(),
            'field' => $this->field,
            'is_update' => $this->is_update,
            'content' => $this->content,
            'modules' => $this->modules
        ]);
    }
}