waffle/frontend/src/components/MessageInput.svelte

103 lines
2.8 KiB
Svelte
Raw Normal View History

<script>
import { SendIcon } from "svelte-feather-icons";
2022-04-28 18:48:44 +03:00
import request from "../request";
2022-04-26 03:09:16 +03:00
import { apiRoute } from "../storage";
import { messagesStoreProvider, overlayStore, smallViewport, userInfoStore } from "../stores";
export let channel;
let messageInput = "";
$: messages = messagesStoreProvider.getStore(channel.id);
const sendMessage = async () => {
if (messageInput.trim() === "" || !$userInfoStore)
return;
// optimistically add message to store
const optimisticMessageId = Math.floor(Math.random() * 999999);
const optimisticMessage = {
id: optimisticMessageId,
content: messageInput,
channel_id: channel.id,
author_id: $userInfoStore.id,
author_username: $userInfoStore.username,
created_at: Date.now().toString(),
_isPending: true
};
messages.addMessage(optimisticMessage);
messageInput = "";
const res = await request("POST", apiRoute(`channels/${channel.id}/messages`), true, {
content: optimisticMessage.content
});
if (res.success && res.ok) {
messages.setMessage(optimisticMessageId, res.json);
} else {
messages.deleteMessage({
id: optimisticMessageId
});
overlayStore.open("toast", {
message: "Couldn't send message"
});
}
};
const onKeydown = async (e) => {
2022-05-07 16:50:04 +03:00
if (e.code === "Enter") {
if (e.shiftKey) {
return;
} else {
e.preventDefault();
await sendMessage();
}
}
};
</script>
<style>
.message-input-container {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
padding: var(--space-norm);
}
.message-input {
width: 100%;
background-color : var(--background-color-2);
border: none;
color: currentColor;
border-radius: var(--radius-md);
padding: var(--space-sm);
font-size: inherit;
line-height: inherit;
2022-08-03 04:49:03 +03:00
resize: none;
}
.message-input::placeholder {
color: var(--foreground-color-3);
}
.send-button {
margin-left: var(--space-sm);
}
</style>
<div class="message-input-container">
2022-05-07 16:50:04 +03:00
<textarea
2022-08-03 04:49:03 +03:00
placeholder={$smallViewport ? `Message #${channel.name}` : `Send something interesting to #${channel.name}`}
type="text"
class="message-input"
2022-08-03 04:49:03 +03:00
rows="1"
on:keydown={ onKeydown }
bind:value={ messageInput }
2022-05-07 16:50:04 +03:00
/>
{#if $smallViewport}
<button class="icon-button send-button" on:click="{ sendMessage }">
<SendIcon />
</button>
{/if}
</div>