Newer
Older
ournorth2021 / views / chat.php
LuisOlaya on 17 Apr 2021 6 KB juego
<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-firestore.js"></script>

<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
        apiKey: "AIzaSyDr7eBZj0fa9Yu61aEPpHRVfVSfcf9qeuw",
        authDomain: "chathtml-87108.firebaseapp.com",
        projectId: "chathtml-87108",
        storageBucket: "chathtml-87108.appspot.com",
        messagingSenderId: "408063657727",
        appId: "1:408063657727:web:a2f1ae56ff9c8fcbce2eca"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    var db = firebase.firestore();
</script>
<style>
    .message {
        padding: -10px;
        border-radius: 25px;
        margin-bottom: 4px;
    }

    .other-message {
        background: red;
        color: aliceblue;
    }

    .my-message {
        background: blue;
        color: aliceblue;
    }

    .time {
        color: aliceblue;
        float: right;
        font-size: small;
    }

    .header1 {
        background: gray;
        padding-right: 0;
        position: sticky;
        top: 0;
        left: 0;
        width: 100%;
        z-index: 10;
    }

    .footer {
        background: gray;
        color: #ffffff;
        font-size: 13px;
        bottom: 0px;
        position: sticky;
        left: 0px;
        width: 100%;
        z-index: 10;
        border-top: 3px solid #ffffff;
    }
</style>
<script>
    var input = document.getElementById("text");
    /* input.addEventListener("keyup", function (event) {
      if (event.keyCode === 13) {
        event.preventDefault();
        document.getElementById("btn_send").click();
      }
    }); */
    var myName = '';


    var nameGroup = '';


    function init() {
        myName = "<?php echo $data['nombre'] . ' ' . $data['apellidos']; ?>";
        nameGroup = "<?php echo $data['equipo']; ?>";
        messages = [];




        db.collection('chat').where('id', '==', nameGroup).onSnapshot((snap1) => {

            messages = null;
            snap1.forEach(child => {
                messages = {
                    id: child.id,
                    data: child.data()
                };
            });

            if (messages == null) {
                db.collection("chat").add({
                    id: nameGroup,
                    messages: []
                });
            } else {
                var html = "";
                inicio = `
                    <div style="height: 200px;">
                        <div class="text-center" style="margin-top: 30%; ">
                            <h4>Bienvenido a al chat grupal del equipo `+nameGroup+`</h4>
                        </div>
                    </div>
                    `;
                    html+=inicio;
                messages.data.messages.forEach(msj => {
                    var fecha = (new Date(msj.date));
                    var fechaOld = (new Date(msj.dateOld));
                    var item = "";
                    var item1 = "";
                    if (fecha.toDateString() != fechaOld.toDateString()) {
                        item1 = `
              <div class="row">
                <div class="col-12">
                  <p class="text-center">` + fecha.toLocaleDateString() + `</p>
                </div>
              </div>
              `;

                    }

                    if (msj.name != myName) {
                        item +=
                            `
                <div class="col-9 message other-message">
                  <b>` + msj.name + `</b><br>
                  <span>` + msj.content + `</span>
                  <div class="time" text-right>
                    ` + fecha.toLocaleTimeString() + `
                  </div>
                </div>
                <div class="col-3"></div>`;
                    } else {
                        item +=
                            `
                <div class="col-3"></div>
                <div class="col-9 message my-message "">
                  <b>T&uacute;</b><br>
                  <span>` + msj.content + `</span>
                  <div class="time" text-right>
                    ` + fecha.toLocaleTimeString() + `
                  </div>
                </div>`;
                    }
                    var msjHtml =
                        `
        <div class="row">
      <div class="col-12">
      
        ` + item1 + `

        <div class="row">
          ` + item + `

        </div>
      </div>
    </div>
        `;
                    
                    html += msjHtml;
                });
                document.getElementById('titulo').innerText = "Equipo " + nameGroup;
                document.getElementById('contenedor').innerHTML = html;
                setTimeout(() => {
                    console.log(document.getElementById('contenedor'));
                    //document.getElementById('contenedor').animate({ scrollTop: 3000 }, 400);
                    document.getElementById('main').scrollIntoView(0, document.getElementById('main').scrollHeight);
                }, 300);

            }


        });

    }

    function sendMsj() {
        var text = document.getElementById('text').value;
        if (text != '') {
            var date = new Date().toISOString();
            var s = this.messages.data.messages.length;
            db.collection('chat').doc(messages.id).update({
                messages: firebase.firestore.FieldValue.arrayUnion({
                    content: text,
                    type: 'text',
                    name: myName,
                    date,
                    dateOld: s === 0 ? null : messages.data.messages[s - 1].date,
                })
            }).then(() => {
                document.getElementById('text').value = '';
                setTimeout(() => {
                    document.getElementById('main').scrollIntoView(0, document.getElementById('main').scrollHeight);
                }, 300);
            })
        }
    }
    init();
</script>

<div id="main">
    <div class="header1">
    <h1  id="titulo"></h1>
    </div>
    
    <div id="contenedor"></div>
    

    <div class="footer" id="footer">
        <div class="input-group">
            <input class="form-control" type="text" placeholder="Escribe el mensaje aquĆ­ ..." id="text" value="">
            <button class="btn btn-info" id="btn_send" onclick="sendMsj()">Enviar</button>
        </div>

    </div>
</div>