淺嘗MUI-詳解im-chat源碼

寫在前面

因最近項(xiàng)目需要制作一個(gè)聊天界面,對(duì)比后感覺MUI源碼內(nèi)的im-chat.html文件對(duì)各種情況的處理比較的全面,因此,將整個(gè)頁面的邏輯從頭到尾理了一遍,希望有需求的小伙伴可以少走彎路,通過這個(gè)模板,可以根據(jù)我們自己需要的功能進(jìn)行定制,如果不是很清楚(用詞不當(dāng))的地方,還請(qǐng)小伙伴們提出來,做相關(guān)修改,謝謝!
ps:理這種邏輯性的東西需要耐心,所以希望小伙伴能夠靜下心來慢慢理,任何代碼都是根據(jù)需求實(shí)現(xiàn)。所以,可以結(jié)合實(shí)際操作來看相關(guān)模塊。最后,求一波關(guān)注,哈哈!

相關(guān)引用

這個(gè)聊天框架基于MUI開發(fā),正常引入相關(guān)文件后,還需引入如下文件:

  1. 圖片預(yù)覽的mui.imageviewer.css樣式文件,
  2. 處理圖片瀏覽的mui.imageViewer.js文件,
  3. 模板渲染的arttmpl.js文件;

代碼詳解

<body contextmenu="return false;">
<header class="mui-bar mui-bar-nav">
    <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
    <h1 class="mui-title">chat (聊天窗口)</h1>
</header>
<pre id='h'></pre>
<script id='msg-template' type="text/template">
    <% for(var i in record){ var item=record[i]; %>
        <div class="msg-item <%= (item.sender=='self'?' msg-item-self':'') %>" msg-type='<%=(item.type)%>' msg-content='<%=(item.content)%>'>
            <% if(item.sender=='self' ) { %>
                <i class="msg-user mui-icon mui-icon-person"></i>
            <% } else { %>
                <img class="msg-user-img" src="../images/logo.png" alt="" />
            <% } %>
            <div class="msg-content">
                <div class="msg-content-inner">
                    <% if(item.type=='text' ) { %>
                        <%=( item.content|| '&nbsp;&nbsp;') %>
                    <% } else if(item.type=='image' ) { %>
                        <img class="msg-content-image" src="<%=(item.content)%>" style="max-width: 100px;" />
                    <% } else if(item.type=='sound' ) { %>
                        <span class="mui-icon mui-icon-mic" style="font-size: 18px;font-weight: bold;"></span>
                        <span class="play-state">點(diǎn)擊播放</span>
                    <% } %>
                </div>
                <div class="msg-content-arrow"></div>
            </div>
            <div class="mui-item-clear"></div>
        </div>
    <% } %>
</script>
<div class="mui-content">
    <div id='msg-list'>
    </div>
</div>
<footer>
    <div class="footer-left">
        <i id='msg-image' class="mui-icon mui-icon-camera" style="font-size: 28px;"></i>
    </div>
    <div class="footer-center">
        <textarea id='msg-text' type="text" class='input-text'></textarea>
        <button id='msg-sound' type="button" class='input-sound' style="display: none;">按住說話</button>
    </div>
    <label for="" class="footer-right">
        <i id='msg-type' class="mui-icon mui-icon-mic"></i>
    </label>
</footer>
<div id='sound-alert' class="rprogress">
    <div class="rschedule"></div>
    <div class="r-sigh">!</div>
    <div id="audio_tips" class="rsalert">手指上滑,取消發(fā)送</div>
</div>
<script src="../js/mui.min.js"></script>
<script src="../js/mui.imageViewer.js"></script>
<script src="../js/arttmpl.js"></script>
<script type="text/javascript" charset="utf-8">
(function($, doc) {
    var MIN_SOUND_TIME = 800;
    $.init({
        gestureConfig: {
            tap: true, //默認(rèn)為true
        doubletap: true, //默認(rèn)為false
        longtap: true, //默認(rèn)為false
        swipe: true, //默認(rèn)為true
        drag: true, //默認(rèn)為true
        hold: true, //默認(rèn)為false,不監(jiān)聽
        release: true //默認(rèn)為false,不監(jiān)聽
    }
});
template.config('escape', false);
//$.plusReady=function(fn){fn();};
$.plusReady(function() {
    plus.webview.currentWebview().setStyle({
        softinputMode: "adjustResize"
    });
    //強(qiáng)制彈出鍵盤
    var showKeyboard = function() {
        if ($.os.ios) {
            var webView = plus.webview.currentWebview().nativeInstanceObject();
            webView.plusCallMethod({
                "setKeyboardDisplayRequiresUserAction": false
            });
        } else {
            var Context = plus.android.importClass("android.content.Context");
            var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
            var main = plus.android.runtimeMainActivity();
            var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
            //var view = ((ViewGroup)main.findViewById(android.R.id.content)).getChildAt(0);
            imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT);
            //alert("ll");
        }
    };
    var record = [{
        sender: 'zs',
        type: 'text',
        content: 'Hi,我是 MUI 小管家!'
    }];
    var ui = {
        body: doc.querySelector('body'),
        footer: doc.querySelector('footer'),
        footerRight: doc.querySelector('.footer-right'),
        footerLeft: doc.querySelector('.footer-left'),
        btnMsgType: doc.querySelector('#msg-type'),
        boxMsgText: doc.querySelector('#msg-text'),
        boxMsgSound: doc.querySelector('#msg-sound'),
        btnMsgImage: doc.querySelector('#msg-image'),
        areaMsgList: doc.querySelector('#msg-list'),
        boxSoundAlert: doc.querySelector('#sound-alert'),
        h: doc.querySelector('#h'),
        content: doc.querySelector('.mui-content')
    };
    //將文本框?qū)挾荣x值給h
    ui.h.style.width = ui.boxMsgText.offsetWidth + 'px';
    //alert(ui.boxMsgText.offsetWidth );
    //讓文本框居中
    var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
    //語音輸入相關(guān)操作
    var msgItemTap = function(msgItem, event) {
        var msgType = msgItem.getAttribute('msg-type');
        var msgContent = msgItem.getAttribute('msg-content')
        if (msgType == 'sound') {
            player = plus.audio.createPlayer(msgContent);
            var playState = msgItem.querySelector('.play-state');
            playState.innerText = '正在播放...';
            player.play(function() {
                playState.innerText = '點(diǎn)擊播放';
            }, function(e) {
                playState.innerText = '點(diǎn)擊播放';
            });
        }
    };
    //圖片預(yù)覽組件
    var imageViewer = new $.ImageViewer('.msg-content-image', {
        dbl: false
    });
    //綁定消息節(jié)點(diǎn)
    var bindMsgList = function() {
        //綁定數(shù)據(jù):
        /*tp.bind({
            template: 'msg-template',
            element: 'msg-list',
            model: record
        });*/
        //將數(shù)據(jù)綁定到界面上
        ui.areaMsgList.innerHTML = template('msg-template', {
            "record": record
        });
        //拿到所有的聊天節(jié)點(diǎn)
        var msgItems = ui.areaMsgList.querySelectorAll('.msg-item');
        //因?yàn)閐ocument.querySelectorAll()返回的并不是我們想當(dāng)然的數(shù)組,而是NodeList,對(duì)NodeList,它里面沒有.forEach方法,我們使用了這樣的方法進(jìn)行循環(huán):
        //通過call將this綁定到msgItems(以[]下標(biāo)的方式去遍歷msgItems)
        [].forEach.call(msgItems, function(item, index) {
            item.addEventListener('tap', function(event) {
                //處理語音消息播放
                msgItemTap(item, event);
            }, false);
        });
        //查找所有符合條件的圖片
        imageViewer.findAllImage();
        //聊天界面的高度修改
        ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
    };
    bindMsgList();
    //平滑高度過渡
    window.addEventListener('resize', function() {
        ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight;
    }, false);
    //發(fā)送對(duì)象聲明
    var send = function(msg) {
        //將消息內(nèi)容體push進(jìn)record
        record.push(msg);
        //綁定消息節(jié)點(diǎn)
        bindMsgList();
        toRobot(msg.content);
    };
    var toRobot = function(info) {
        var apiUrl = 'http://www.tuling123.com/openapi/api';
        $.getJSON(apiUrl, {
            "key": 'acfbca724ea1b5db96d2eef88ce677dc',
            "info": info,
            "userid": plus.device.uuid
        }, function(data) {
            //alert(JSON.stringify(data));
            record.push({
                sender: 'zs',
                type: 'text',
                content: data.text
            });
            bindMsgList();
        });
    };
    
    //讓輸入框獲取焦點(diǎn)
    function msgTextFocus() {
            ui.boxMsgText.focus();
            setTimeout(function() {
                ui.boxMsgText.focus();
            }, 150);
        }
        //解決長按“發(fā)送”按鈕,導(dǎo)致鍵盤關(guān)閉的問題;
    ui.footerRight.addEventListener('touchstart', function(event) {
        if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
            msgTextFocus();
            event.preventDefault();
        }
    });
    //解決長按“發(fā)送”按鈕,導(dǎo)致鍵盤關(guān)閉的問題;
    ui.footerRight.addEventListener('touchmove', function(event) {
        if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
            msgTextFocus();
            event.preventDefault();
        }
    });
    //                  ui.footerRight.addEventListener('touchcancel', function(event) {
    //                      if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
    //                          msgTextFocus();
    //                          event.preventDefault();
    //                      }
    //                  });
    //                  ui.footerRight.addEventListener('touchend', function(event) {
    //                      if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
    //                          msgTextFocus();
    //                          event.preventDefault();
    //                      }
    //                  });
    //長按離開屏幕時(shí)觸發(fā)
    ui.footerRight.addEventListener('release', function(event) {
        //當(dāng)是文字時(shí)
        if (ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
            //showKeyboard();
            ui.boxMsgText.focus();
            setTimeout(function() {
                ui.boxMsgText.focus();
            }, 150);
            //                          event.detail.gesture.preventDefault();
            send({
                sender: 'self',
                type: 'text',
                content: ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '<br/>')
            });
            ui.boxMsgText.value = '';
            $.trigger(ui.boxMsgText, 'input', null);
        } 
        //當(dāng)是語音時(shí)
        else if (ui.btnMsgType.classList.contains('mui-icon-mic')) {
            ui.btnMsgType.classList.add('mui-icon-compose');
            ui.btnMsgType.classList.remove('mui-icon-mic');
            ui.boxMsgText.style.display = 'none';
            ui.boxMsgSound.style.display = 'block';
            ui.boxMsgText.blur();
            document.body.focus();
        }
        //當(dāng)是文本狀態(tài)時(shí)
        else if (ui.btnMsgType.classList.contains('mui-icon-compose')) {
            ui.btnMsgType.classList.add('mui-icon-mic');
            ui.btnMsgType.classList.remove('mui-icon-compose');
            ui.boxMsgSound.style.display = 'none';
            ui.boxMsgText.style.display = 'block';
            //--
            //showKeyboard();
            ui.boxMsgText.focus();
            setTimeout(function() {
                ui.boxMsgText.focus();
            }, 150);
        }
    }, false);
    
    //點(diǎn)擊左邊按鈕時(shí)
    ui.footerLeft.addEventListener('tap', function(event) {
        var btnArray = [{
            title: "拍照"
        }, {
            title: "從相冊(cè)選擇"
        }];
        plus.nativeUI.actionSheet({
            title: "選擇照片",
            cancel: "取消",
            buttons: btnArray
        }, function(e) {
            var index = e.index;
            switch (index) {
                case 0:
                    break;
                case 1:
                    var cmr = plus.camera.getCamera();
                    cmr.captureImage(function(path) {
                        send({
                            sender: 'self',
                            type: 'image',
                            content: "file://" + plus.io.convertLocalFileSystemURL(path)
                        });
                    }, function(err) {});
                    break;
                case 2:
                    plus.gallery.pick(function(path) {
                        send({
                            sender: 'self',
                            type: 'image',
                            content: path
                        });
                    }, function(err) {}, null);
                    break;
            }
        });
    }, false); 
    //控制按住語音時(shí)的顯示與隱藏
    var setSoundAlertVisable=function(show){
        if(show){
            ui.boxSoundAlert.style.display = 'block';
            ui.boxSoundAlert.style.opacity = 1;
        }else{
            ui.boxSoundAlert.style.opacity = 0;
            //fadeOut 完成再真正隱藏
            setTimeout(function(){
                ui.boxSoundAlert.style.display = 'none';
            },200);
        }
    };
    var recordCancel = false;
    var recorder = null;
    var audio_tips = document.getElementById("audio_tips");
    var startTimestamp = null;
    var stopTimestamp = null;
    var stopTimer = null;
    //按住說話時(shí)候觸發(fā)
    ui.boxMsgSound.addEventListener('hold', function(event) {
        recordCancel = false;
        //如果有結(jié)束時(shí)間,清除定時(shí)器
        if(stopTimer)clearTimeout(stopTimer);
        //修改顯示文字
        audio_tips.innerHTML = "手指上劃,取消發(fā)送";
        //移除rprogress-sigh
        ui.boxSoundAlert.classList.remove('rprogress-sigh');
        //顯示樣式
        setSoundAlertVisable(true);
        //獲取錄音對(duì)象  5+模塊
        recorder = plus.audio.getRecorder();
        if (recorder == null) {
            plus.nativeUI.toast("不能獲取錄音對(duì)象");
            return;
        }
        //記錄當(dāng)前錄音時(shí)間
        startTimestamp = (new Date()).getTime();
        //保存錄音http://www.html5plus.org/doc/zh_cn/audio.html#plus.audio.RecordOption
        recorder.record({
            filename: "_doc/audio/"
        }, function(path) {
            if (recordCancel) return;
            send({
                sender: 'self',
                type: 'sound',
                content: path
            });
        }, function(e) {
            plus.nativeUI.toast("錄音時(shí)出現(xiàn)異常: " + e.message);
        });
    }, false);
    
    //監(jiān)聽drag(拖動(dòng)中)事件 上滑;下滑事件
    ui.body.addEventListener('drag', function(event) {
        //console.log('drag');
        if (Math.abs(event.detail.deltaY) > 50) {
            //此時(shí)沒有錄音操作執(zhí)行 檢查recordCancel狀態(tài)
            if (!recordCancel) {
                recordCancel = true;
                if (!audio_tips.classList.contains("cancel")) {
                    audio_tips.classList.add("cancel");
                }
                audio_tips.innerHTML = "松開手指,取消發(fā)送";
            }
        } else {
            if (recordCancel) {
                recordCancel = false;
                if (audio_tips.classList.contains("cancel")) {
                    audio_tips.classList.remove("cancel");
                }
                audio_tips.innerHTML = "手指上劃,取消發(fā)送";
            }
        }
    }, false);
    //長按離開錄音節(jié)點(diǎn)時(shí)執(zhí)行
    ui.boxMsgSound.addEventListener('release', function(event) {
        //console.log('release');
        //初始化
        if (audio_tips.classList.contains("cancel")) {
            audio_tips.classList.remove("cancel");
            audio_tips.innerHTML = "手指上劃,取消發(fā)送";
        }
        //判斷錄音是否小于800毫秒,若小于,則廢棄
        stopTimestamp = (new Date()).getTime();
        if (stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
            audio_tips.innerHTML = "錄音時(shí)間太短";
            ui.boxSoundAlert.classList.add('rprogress-sigh');
            recordCancel = true;
            stopTimer=setTimeout(function(){
                setSoundAlertVisable(false);
            },800);
        }else{
            setSoundAlertVisable(false);
        }
        //停止錄音模塊
        recorder.stop();
    }, false);
    
    //阻止瀏覽器默認(rèn)的事件冒泡
    ui.boxMsgSound.addEventListener("touchstart", function(e) {
        //console.log("start....");
        e.preventDefault();
    });
    //監(jiān)聽用戶輸入時(shí)觸發(fā)
    ui.boxMsgText.addEventListener('input', function(event) {
        //當(dāng)輸入為空時(shí)去掉發(fā)送文字,當(dāng)不為空時(shí),顯示發(fā)送文字
        ui.btnMsgType.classList[ui.boxMsgText.value == '' ? 'remove' : 'add']('mui-icon-paperplane');
        //當(dāng)用戶輸入值不為空時(shí),設(shè)置自定義屬性for 賦值msg-text
        ui.btnMsgType.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
        //替換與正則表達(dá)式相匹配的值(轉(zhuǎn)義)
        ui.h.innerText = ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '\n-') || '-';
        //動(dòng)態(tài)調(diào)整輸入框高度
        ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
        //調(diào)整顯示信息高度
        ui.content.style.paddingBottom = ui.footer.style.height;
    });
    var focus = false;
    //監(jiān)聽用戶點(diǎn)擊發(fā)送時(shí)觸發(fā)
    ui.boxMsgText.addEventListener('tap', function(event) {
        //得到焦點(diǎn)
        ui.boxMsgText.focus();
        setTimeout(function() {
            ui.boxMsgText.focus();
        }, 0);
        focus = true;
        setTimeout(function () {
            focus = false;
        },1000);
        //阻止iOS2.0中的手勢事件:gesture事件 
        event.detail.gesture.preventDefault();
    }, false);
    //點(diǎn)擊消息列表,關(guān)閉鍵盤
    ui.areaMsgList.addEventListener('click',function (event) {
        if(!focus){
            ui.boxMsgText.blur();
        }
    })  
});
}(mui, document));
    </script>
</body>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容