Source: tool/MarkdownEditor.js

/**
 * Created by seeker910 on 2022/4/22.
 * @description markdown 文件编辑器
 */ 
 Rsd.define('Rsd.tool.MarkdownEditor', {
    extend: 'Rsd.container.Dialog',
    requires: [
        'Rsd.form.Button',
        'Rsd.form.Label',
        'Rsd.form.Link',
        'Rsd.form.CheckBox',
        'Rsd.control.IframeBox',
        'Rsd.control.ListView'
    ],
    editorHeight:'100%',
    /**
     * 是否显示目录栏
     */
    showIndex:true,
    /**
     * 是阅读模式
     */
    isView:false,
    /**
     * 文档索引编辑函数
     */
    indexEditServiceName:null,
    /**
     * 文档索引加载函数
     */
    indexLoadServiceName:'global.merch.doc.GetDocPageList',
    /**
     * 文件下载服务名称
     */
    fileDownloadServiceName:'aliyun.merch.oss.cms.download',
    /**
     * 上传
     */
    fileUploadServiceName:'aliyun.merch.oss.cms.upload',
    /**
     * 
     */
    layout:'hbox',
    /**
     * 
     */
    items:[
        {
            xtype:'list-view',
            itemXtype:'link',
            itemKeyMember:'key',
            label:{
                xtype:'link', 
                text:'[刷 新]',
                width:'100%',
                height:'40px',
                margin:'3px 0 3px 0',
                label:{
                    width:120,
                    content:'页面列表',
                    align:'center',
                    style:{
                            color:'#000', 
                            cursor: 'default',
                            textAlign:'left',
                            //fontWeight:'Bold',
                            fontSize:'130%',  
                            borderBottom: '1px darkgrey dotted'
                        }
                },
                ctrl:{
                    style:{
                        //element:'ctrl', 
                        color: '#fff',  
                        backgroundColor: '#b92525f0',
                        cursor: 'pointer',
                        lineHeight:'40px', 
                        borderRadius: '4px'
                    }     
                }
                   
            },
            margin:'0 0 0 10',
            width:200,
            height:'100%',
            layout:'vbox',
            itemClick:'pageIndexChanged',
            dataSource:null

        },
        {
            xtype:'iframe', 
            flex:1,
            //width:'100%',
            height:'100%', 
            src:'javascript:void(0)',
            ctrl:{style:{boder:'1px red solid'}},
            onload:'iframe_load',
            label:{
                position:'bottom',
                space:0,
                xtype:'container',
                header:false,
                height:60,
                style:{lineHeight:60},
                items:[
                    {
                        xtype:'checkbox',
                        width:120,
                        height:30,
                        checked:true,
                        margin:'5 0 0 60',
                        label:{
                            position:'right',
                            width:90,
                            content:'自动保存',
                            style:{color:'#000',fontSize:'120%'}
                        },
                        tip:'勾选后,每5分钟自动保存',
                        onchange:'on_checked'
                    },
                    {
                        xtype:'button',
                        height:40,
                        width:120,
                        text:'保存文件(S)',
                        handler:'btn_save'
                    },
                    {
                        xtype:'label',
                        text:'按 ctrl+s 保存文件',
                        style:{color:'#000',fontSize:'120%'},
                        height:40,
                        width:160,
                    },
                    {
                        xtype:'label',
                        text:'上次保存时间:',
                        style:{color: '#999289',textAlign:'left'},
                        height:40,
                        width:200,
                    },
                    {
                        xtype:'button',
                        height:40,
                        width:100,
                        margin:'0 10',
                        style:{
                            float: 'right', 
                            backgroundColor:'#7d4f0cd1'
                        },
                        text:'发 布',
                        handler:'btn_publish'
                    },
                    {
                        xtype:'button',
                        height:40,
                        width:100,
                        margin:'0 10',
                        style:{
                            float: 'right', 
                            backgroundColor:'#034e09bd'
                        },
                        text:'分 享',
                        handler:'btn_share'
                    },
                    {
                        xtype:'button',
                        height:40,
                        width:100,
                        margin:'0 10',
                        style:{
                            float: 'right', 
                            backgroundColor:'#7a013dcc'
                        },
                        text:'预 览',
                        handler:'btn_preview'
                    }
                ]
            }
        } 
    ],
    /**
     * 文档信息
     */
    doc:{Id:null,Key:null,Name:''},
    /**
     * 
     * @param {*} config 
     */
    constructor: function MarkdownEditor(config) {

        config = config || {};
        this.apply(config);
        var me = this;

        me.items[1].src = Rsd.getRedjsHost()+'plugin/editormd/app/'+ (me.isView?'view':'edit') +'.html?h='+me.editorHeight;

        if(!this.showIndex)
        {
            this.items[0].hidden = true;
        }
        if(this.isView)
        {
            this.items[0].label = {
                content:'页 面 列 表  ', 
                style:{
                    borderBottom: '1px darkgrey dotted',
                    color:'#000',
                    fontSize:'130%'
                }
            };
            this.items[1].label =false;
        }
        else
        {
            this.items[0].label.handler = function(){
                me.loadIndex();
            };
        }
        Rsd.app.mdEditorContainer = me;
    },
    /** 
     * @param {*} key 
     */
    load:function load()
    {
        this.callParent();
    },
    /**
     * 
     */
    loadIndex:function loadIndex()
    {
        var me = this;
        
        me.loadDocPages(function(indexList){
                 
            for(var i in indexList)
            { 
                var item = indexList[i];
                if(item.key)
                {
                    item.style = item.style || {fontSize:'120%',overflow:'hidden'};
                    //章节 页面加载 
                    item.handler = function(){ 
                        //console.log(this);
                        me.selectPage(this.key);
                   }; 
                }
                
            }

            me.items[0].loadData(indexList);
        });
    },
     /**
     * 
     * @param {*} row 
     * @param {*} callback 
     */
     loadDocPages:function loadDocPages(callback)
     {
         var me = this;
         var isView = me.isView;
         var docId = me.doc.Id;
         var docKey = me.doc.Key;
         var docName = me.doc.Name;
 
         var list = [{text:' 首 页 ', width:'100%',key:docKey}];
             //获取索引
             Rsd.app.requestService(me.indexLoadServiceName,{key:docKey},function(resp){
                 
                 if(resp.success)
                 {
                     for(var i in resp.data)
                     {
                         var no = Number(i) + 1;
                          //{text:'第一章:xxxxxxxx',width:'100%',handler:function(){alert(this.text);}},
                         list.push({
                             key:resp.data[i].Key,
                             label:'第'+ no +'章:' + resp.data[i].Title,
                             width:'100%',
                             tip: resp.data[i].Title + ':' + resp.data[i].Description
                         });
                     }
                     
                 }
 
                 if(isView)
                 {}
                 else
                 {
                     list.push({
                         xtype:'container',
                         width:'100%',
                         items:[
                                 {
                                     xtype:'link',
                                     text:' 添加新页面 ',
                                     width:'50%',
                                     height:40, 
                                     style:{
                                         element:'ctrl',
                                         textDecoration:'underline',
                                         textAlign:'right',
                                         //fontWeight:'Bold',
                                         fontSize:'130%',
                                         //backgroundColor: '#03127eb5',
                                         color:'#f70000d9' 
                                     },
                                     handler:function() {
                         
                                         Rsd.create('Rsd.zen.dialog.FormDialog',{
                                             style:{maxHeight:'100%'},
                                             docKey:docKey,
                                             readOnly: false, 
                                             height:'100%',
                                             width:500,
                                             delayShow:50,
                                             header:{content:'添加新页面'},
                                             style:{borderRadius:0,maxHeight:'100%'},
                                             formFields:[
                                                {
                                                    xtype:'text',
                                                    label:'名称',
                                                    width:'80%'
                                                },
                                                {
                                                    xtype:'text',
                                                    label:'描述',
                                                    width:'80%'
                                                }
                                             ],
                                             labelWidth:100,
                                             buttons:['save','delete'],
                                             saveHandler:function(data){
                                                alert('save');
                                             },
                                             afterNewHandler:function(newObj)
                                             {
                                                 me.loadDocPages(isView,row,callback);
                                             }
                                         }).showDialog(document.body,{left:-550,top:0},{left:0,top:0},500);
                                     
                                     }
                                 },
                                 {
                                     xtype:'link',
                                     text:' 查看详情 ',
                                     width:'50%',
                                     height:40, 
                                     style:{
                                         element:'ctrl',
                                         textDecoration:'underline',
                                         textAlign:'right',
                                         //fontWeight:'Bold',
                                         fontSize:'110%',
                                         //backgroundColor: '#03127eb5',
                                         color:'#160404ba', 
                                     },
                                     handler:function() {
                         
                                         var mdEditor = this.parent.parent;
                                         Rsd.create('Rsd.CMS.pages.DocPageListDialog',{
                                             parent:mdEditor,
                                             //autoLoad:true,
                                             title:docName +' - 目录编辑', 
                                             formTitle:'目录', 
                                             where:[{name:'DocId',op:'equals',value:docId}],
                                             sort:[{name:'IndexCode',direction:'asc'}], 
                                         
                                         }).showDialog(mdEditor).load();
                                             
                                 }
                             }
                         ]
                      });
  
                 }
                  
                 callback(list);
             });
     },
    /**
     * 
     * @param {*} key 
     */
    selectPage:function selectPage(key)
    { 
        var me = this;
        
        var _fn_relocate = function(){

            me.download(key);
        }

        var c_win = me.items[1].ctrl.element.contentWindow;

        var _fn  = function(){
            
            if(c_win.isChanged)
            {
                Rsd.showMessage('文档已修改,是否保存?',[
                    {
                        text:'保 存',
                        fn:function(){ me.upload(false,_fn_relocate);  }
                    },
                    {text:'不保存',fn:_fn_relocate}
                ]);
            }
            else
            {
                _fn_relocate();
            }
        }
         
        if(c_win)
        {
            _fn();
        }
        else
        {
            var _id = setInterval(function(){

                c_win = me.items[1].ctrl.element.contentWindow;
                if(c_win)
                {
                    clearInterval(_id);
                    _fn();
                }
               
            },100);
        }
        
        //
    },
    /**
     * 
     * @param {*} key 
     */
    download:function download(key)
    {
        if(Rsd.isEmpty(key))
        { 
            return;
        }
        var me = this;
        Rsd.app.requestService(this.fileDownloadServiceName,{filename:key+".md"}, function(resp) {
                    
            if(!resp.success)
            {
                return;
            }
            //更新当前key
            me.key = key;
            
            //清除自动保存
            if(me.__interval_id)
            {
                window.clearInterval(me.__interval_id);
            }

            me.render_html(resp.data,function(){
                //在成功渲染后 开启自动保存 放在在未加载前 触发保存 污染数据
                me.__interval_id = setInterval(function(){me.upload(true,null);},5*1000*60);
            });

            var c_win = me.items[1].ctrl.element.contentWindow; 

            //绑定预览事件
            if(me.items[1].label 
                && me.items[1].label.content 
                && c_win.bindPreviewEvent)
            {
                c_win.bindPreviewEvent(function(isPreview){
                        var btn = me.items[1].label.content.items[6].ctrl.element;
                        btn.innerHTML = isPreview?'关闭预览':'预 览';
                    });
            }
            //设置保存方法
            if(c_win.bindSaveFunction)
            {
                c_win.bindSaveFunction(function(){me.upload(false,null);});
            }
            
        });
                
               
    },
    /**
     * 上传文件
     * @param {*} autoSave 是否是自动保存
     * @param {*} callback 保存后回调方法
     */
     upload:function upload(autoSave,callback)
     {
         var me = this;
         var key = me.key;
         if(Rsd.isEmpty(key))
         {
            Rsd.alert('无法保存文件。');
            return;
         }
         if(!me.items[1])
         {
            window.clearInterval(me.__interval_id);
            return;
         }
         var c_win = me.items[1].ctrl.element.contentWindow;
         var code = c_win.getFileCode();
         var file = new File([new Blob([code])], key+'.md', {type: 'text/x-markdown'});
         var data = {}; 
         data['files'] = file;
         data['desc'] = '这是来自CMS的MD文件内容';
 
         var service = top.Rsd.app.getService(me.fileUploadServiceName);
         
        
         //application/x-www-form-urlencoded =》 未找到上传文件 
         //application/form-data    => Incorrect Content-Type: application/form-data 
         //text/plain               => Incorrect Content-Type: text/plain  
         //multipart/form-data      => Missing Content-Type Broundary=XXXX 
         service.server.contentType = "multipart/form-data";// 该设置 让ajax 将 data 转化为FormData
         service.server.accept="application/json, text/javascript, */*; q=0.01";   
         service.request(data,function(resp){
             if(resp.success)
             {
                  if(autoSave)
                  {
                     Rsd.popup('已自动保存');
                  }
                  else
                  {
                     Rsd.popup('保存成功');
                  }
 
                 var time =  Rsd.formatTimestamp(Date.now(),"yyyy-MM-dd hh:mm:ss");
                 c_win.changeTime = time;
                 c_win.isChanged = false;
                 //更新 页面提示时间
                  me.items[1].label.content.items[3].setValue(time);
                 if(callback)
                 {
                     callback();
                 }
             }
         });
 
     },
    /**
     * 
     * @param {*} listItem 
     */
    pageIndexChanged:function pageIndexChanged(listItem)
    {
        if(listItem.key && listItem.key != this.key)
        {
           this.selectPage(listItem.key);
        }
         
    },
    /**
     * 
     * @param {*} evt 
     * @returns 
     */
    iframe_load:function iframe_load(evt)
    {
        var me = this;
        if(evt.target.src !== me.items[1].src)
        {
            return;
        }
        var c_win = me.items[1].ctrl.element.contentWindow;
        if(c_win.document.readyState !== "complete")
        {
            return;
        } 
        if(me.data)
        {
            me.render_html(me.data,null);
            
        } 
        if(me.key)
        {
            //
            me.selectPage(me.key); 
            //目录信息
            me.loadIndex(); 
        } 
    },
    /**
     * 
     * @param {*} data 
     * @param {*} callback 
     * @returns 
     */
    render_html:function render_html(data,callback)
    {
        var me = this;
        var c_win = me.items[1].ctrl.element.contentWindow;
         if(c_win.render)
         {
             c_win.render(data,callback);

             return;
         }
           
         console.error(c_win.location.href + "未实现接口:render");
    },
    /**
     *  
     */
    on_checked:function(sender,evt)
    { 
        var me = this;
        if(sender.isChecked())
        {
                clearInterval(me.__interval_id);
                me.__interval_id = setInterval(function(){me.upload(true,null);},5*1000*60);
                Rsd.popup('自动保存已开启');
        }
        else
        {
                clearInterval( me.__interval_id);
                Rsd.popup('自动保存已关闭');
        }    
    },
    /**
     * 
     */
    btn_save:function btn_save()
    {
        this.upload(false,null);
    },
    /**
     * 
     */
    btn_preview:function btn_preview()
    {
        var me = this;
        var c_win = me.items[1].ctrl.element.contentWindow;
        c_win && c_win.previewFile();
    },
    /**
     * 
     */
    btn_share:function btn_share()
    {
        Rsd.popup('扫码 或 复制 连接 分享');
    },
    /**
     * 
     */
    btn_publish:function btn_publish()
    {
        Rsd.popup('发布html到网站');
    },
    /**
     * 
     */
    beforeClose:function beforeClose()
    {
        var me = this;
        if(me.closeWithoutSaving===true)
        {
            delete me.closeWithoutSaving;
            return;
        }
        //通过dialog.closeCancel 进行关闭拦截: 如果修改后未保存,阻止窗体关闭
        var c_win = me.items[1].ctrl.element.contentWindow;
        me.closeCancel = c_win.isChanged;

        if(me.closeCancel)
        {
            Rsd.showMessage('文档已修改,是否保存?',[
                {
                    text:'保存并关闭',
                    width:85,
                    height:32,
                    style:{
                        element:'ctrl',
                        color:'#fff',
                        backgroundColor: '#1744a9bd'
                    },
                    fn:function(){ 
                        me.upload(false,function(){me.close();}); 
                    }
                },
                {
                    text:'关闭(不保存)',
                    width:95,
                    height:32,
                    style:{
                        element:'ctrl',
                        color:'#fff',
                        backgroundColor: '#9a1204e6'
                    },
                    fn:function(){ 
                        me.closeWithoutSaving = true;
                        me.closeCancel =false;
                        me.close();
                        
                    }
                },
                {
                    text:'取消(继续编辑)',
                    width:105,
                    height:32,
                }
                ]);
        }
    }

},function(type){

  
      
});