2023-11-09 13:42:40 -05:00

81 lines
2.3 KiB
Vue

<script setup>
import { ref, onMounted } from 'vue'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const input = ref('')
const msgs = ref([{ username: 'Server', message: 'Welcome to Chat App' }, { username: 'Server', message: 'This is an example message' }])
let ws;
async function sendMsg(ev) {
ev.preventDefault()
let msg = input.value
input.value = ''
ws.send(msg)
}
onMounted(async () => {
let proto = window.location.protocol == 'https:' ? 'wss://' : 'ws://'
let host = window.location.host
ws = new WebSocket(proto + host + "/api/ws")
ws.onerror = function (event) {
console.log('WebSocket connection failed:', event);
emit('update:modelValue', '')
//alert("Not logged in!")
window.location.hash = "/login"
};
ws.onmessage = async function (event) {
console.log("event data: " + event.data)
msgs.value.push(JSON.parse(event.data))
console.log("msgs:" + msgs.value)
};
console.log(ws)
})
</script>
<template>
<main>
<div class="overflow-auto position-relative pb-5">
<!--
<div v-for="msg in msgs" class="card m-3 text-bg-secondary">
<div class="card-body">{{ msg.username }}: {{ msg.message }}</div>
</div>
<div v-for="msg in msgs" class="input-group">
<div class="alert alert-primary">{{ msg.username }}</div>
<div class="alert alert-secondary">{{ msg.message }}</div>
</div>
-->
<div v-for="msg in msgs" class="d-flex text-body-secondary pt-2 px-3 border-bottom">
<p class="pb-2 mb-0 small lh-sm word-wrap">
<div class="d-flex justify-content-between">
<strong class="d-block text-gray-dark">{{ msg.username }}</strong>
<div>{{ msg.timestamp }}</div>
</div>
{{ msg.message }}
</p>
</div>
<form onsubmit="event.preventDefault();" class="container-fluid fixed-bottom mb-3">
<div class="input-group">
<input v-model="input" type="text" class="form-control text-bg-secondary" placeholder="Type message here"
aria-label="Chat message" aria-describedby="button-submit">
<button @click="sendMsg" class="btn btn-primary" id="button-submit">Send</button>
</div>
</form>
</div>
</main>
</template>
<style scoped>
.word-wrap {
word-break: break-all;
width: 100vw;
}
</style>