keanu-weblite/src/components/Chat.vue

1641 lines
58 KiB
Vue
Raw Normal View History

2020-11-09 10:26:56 +01:00
<template>
2021-11-24 00:27:09 +02:00
<div class="chat-root fill-height d-flex flex-column">
2023-06-28 12:14:44 +00:00
<ChatHeader class="chat-header flex-grow-0 flex-shrink-0" v-on:header-click="onHeaderClick" v-on:view-room-details="viewRoomDetails" v-if="!useFileModeNonAdmin" />
<AudioLayout ref="chatContainer" class="auto-audio-player-root" v-if="useVoiceMode" :room="room"
:events="events" :autoplay="!showRecorder"
2023-01-30 08:36:02 +00:00
:timelineSet="timelineSet"
:readMarker="readMarker"
:recordingMembers="typingMembers"
2023-03-16 15:23:26 +01:00
v-on:start-recording="setShowRecorder()"
2023-01-30 08:36:02 +00:00
v-on:loadnext="handleScrolledToBottom(false)"
v-on:loadprevious="handleScrolledToTop()"
v-on:mark-read="sendRR"
v-on:sendclap="sendClapReactionAtTime"
2023-01-30 08:36:02 +00:00
/>
<VoiceRecorder class="audio-layout" v-if="useVoiceMode" :micButtonRef="$refs.mic_button" :ptt="showRecorderPTT" :show="showRecorder"
v-on:close="showRecorder = false" v-on:file="onVoiceRecording" :sendTypingIndicators="useVoiceMode" />
2023-01-30 08:36:02 +00:00
2023-06-28 12:14:44 +00:00
<FileDropLayout class="file-drop-root" v-if="useFileModeNonAdmin" :room="room"
v-on:pick-file="showAttachmentPicker()"
v-on:add-file="addAttachment($event)"
2023-06-28 12:14:44 +00:00
v-on:remove-file="currentFileInputs.splice($event, 1)"
v-on:reset="resetAttachments"
:attachments="currentFileInputs"
/>
2023-01-30 08:36:02 +00:00
2023-06-28 12:14:44 +00:00
<div v-if="!useVoiceMode && !useFileModeNonAdmin" class="chat-content flex-grow-1 flex-shrink-1" ref="chatContainer"
2023-01-30 08:36:02 +00:00
v-on:scroll="onScroll" @click="closeContextMenusIfOpen">
2021-01-11 17:42:58 +01:00
<div ref="messageOperationsStrut" class="message-operations-strut">
2023-01-30 08:36:02 +00:00
<message-operations ref="messageOperations" :style="opStyle" :emojis="recentEmojis" v-on:close="
showContextMenu = false;
showContextMenuAnchor = null;
" v-if="showMessageOperations" v-on:addreaction="addReaction" v-on:addquickreaction="addQuickReaction"
v-on:addreply="addReply(selectedEvent)" v-on:edit="edit(selectedEvent)" v-on:redact="redact(selectedEvent)"
v-on:download="download(selectedEvent)" v-on:more="
2022-06-11 12:30:50 +03:00
isEmojiQuickReaction= true
showMoreMessageOperations($event)
2023-01-30 08:36:02 +00:00
" :originalEvent="selectedEvent" />
</div>
2020-12-14 16:11:45 +01:00
<div ref="avatarOperationsStrut" class="avatar-operations-strut">
2023-01-30 08:36:02 +00:00
<avatar-operations ref="avatarOperations" :style="avatarOpStyle" v-on:close="
showAvatarMenu = false;
showAvatarMenuAnchor = null;
" v-on:start-private-chat="startPrivateChat($event)" v-if="selectedEvent && showAvatarMenu" :room="room"
:originalEvent="selectedEvent" />
</div>
<!-- Handle resizes, e.g. when soft keyboard is shown/hidden -->
2022-05-17 15:16:53 +00:00
<resize-observer ref="chatContainerResizer" @notify="handleChatContainerResize" />
<CreatedRoomWelcomeHeader v-if="showCreatedRoomWelcomeHeader" v-on:close="closeCreateRoomWelcomeHeader" />
<div v-for="(event, index) in filteredEvents" :key="event.getId()" :eventId="event.getId()">
<!-- DAY Marker, shown for every new day in the timeline -->
<div v-if="showDayMarkerBeforeEvent(event) && !!componentForEvent(event, isForExport = false)" class="day-marker" :title="dayForEvent(event)" />
2022-11-30 08:16:23 +00:00
<div v-if="!event.isRelation() && !event.isRedaction()" :ref="event.getId()">
2023-01-30 08:36:02 +00:00
<div class="message-wrapper" v-on:touchstart="
(e) => {
touchStart(e, event);
}
" v-on:touchend="touchEnd" v-on:touchcancel="touchCancel" v-on:touchmove="touchMove">
<component :is="componentForEvent(event)" :room="room" :originalEvent="event" :nextEvent="filteredEvents[index + 1]"
:timelineSet="timelineSet" v-on:send-quick-reaction.stop="sendQuickReaction"
2023-01-30 08:36:02 +00:00
v-on:context-menu="showContextMenuForEvent($event)" v-on:own-avatar-clicked="viewProfile"
v-on:other-avatar-clicked="showAvatarMenuForEvent($event)" v-on:download="download(event)"
2023-04-16 13:45:35 +03:00
v-on:poll-closed="pollWasClosed(event)"
v-on:more="
isEmojiQuickReaction = true
showMoreMessageOperations($event)
"
/>
<!-- <div v-if="debugging" style="user-select:text">EventID: {{ event.getId() }}</div> -->
<!-- <div v-if="debugging" style="user-select:text">Event: {{ JSON.stringify(event) }}</div> -->
<div v-if="event.getId() == readMarker && index < filteredEvents.length - 1" class="read-marker"
2023-01-30 08:36:02 +00:00
:title="$t('message.unread_messages')" />
2020-11-25 14:42:50 +01:00
</div>
</div>
2020-11-09 10:26:56 +01:00
</div>
<NoHistoryRoomWelcomeHeader v-if="showNoHistoryRoomWelcomeHeader" />
2020-11-09 10:26:56 +01:00
</div>
<!-- Input area -->
2023-06-28 12:14:44 +00:00
<v-container v-if="!useVoiceMode && !useFileModeNonAdmin && room" fluid :class="['input-area-outer', replyToEvent ? 'reply-to' : '']">
2022-05-17 15:16:53 +00:00
<div :class="[replyToEvent ? 'iput-area-inner-box' : '']">
<!-- "Scroll to end"-button -->
<v-btn v-if="!useVoiceMode" class="scroll-to-end" v-show="showScrollToEnd" fab x-small elevation="0" color="black"
2023-01-30 08:36:02 +00:00
@click.stop="scrollToEndOfTimeline">
<v-icon color="white">arrow_downward</v-icon>
</v-btn>
<v-row class="ma-0 pa-0">
<div v-if="replyToEvent" class="row">
<div class="col">
2022-11-20 13:39:20 +02:00
<div class="font-weight-medium">{{ $t("message.replying_to", { user: senderDisplayName }) }}</div>
2022-05-17 15:16:53 +00:00
<div v-if="replyToContentType === 'm.text'" class="reply-text" :title="replyToEvent.getContent().body">
{{ replyToEvent.getContent().body | latestReply }}
</div>
<div v-if="replyToContentType === 'm.image'">{{ $t("message.reply_image") }}</div>
<div v-if="replyToContentType === 'm.audio'">{{ $t("message.reply_audio_message") }}</div>
<div v-if="replyToContentType === 'm.video'">{{ $t("message.reply_video") }}</div>
2023-01-30 08:36:02 +00:00
<div v-if="replyToContentType === 'm.poll'">{{ $t("message.reply_poll") }}</div>
</div>
<div class="col col-auto" v-if="replyToContentType !== 'm.text'">
2023-01-30 08:36:02 +00:00
<img v-if="replyToContentType === 'm.image'" width="50px" height="50px" :src="replyToImg"
class="rounded" />
2022-05-17 15:16:53 +00:00
<v-img v-if="replyToContentType === 'm.audio'" src="@/assets/icons/audio_message.svg" />
<v-img v-if="replyToContentType === 'm.video'" src="@/assets/icons/video_message.svg" />
<v-icon v-if="replyToContentType === 'm.poll'" light>$vuetify.icons.poll</v-icon>
</div>
2022-03-06 14:28:16 +02:00
<div class="col col-auto">
2022-05-17 15:16:53 +00:00
<v-btn fab x-small elevation="0" color="black" @click.stop="cancelEditReply">
2022-03-06 14:28:16 +02:00
<v-icon color="white">cancel</v-icon>
</v-btn>
</div>
</div>
2020-12-15 17:06:26 +01:00
<!-- CONTACT IS TYPING -->
<div class="typing">
{{ typingMembersString }}
</div>
</v-row>
<v-row class="input-area-inner align-center" v-if="!showRecorder && !$matrix.currentRoomIsReadOnlyForUser">
<v-col class="flex-grow-1 flex-shrink-1 ma-0 pa-0">
2023-01-30 08:36:02 +00:00
<v-textarea height="undefined" ref="messageInput" full-width auto-grow rows="1" v-model="currentInput"
no-resize class="input-area-text" :placeholder="$t('message.your_message')" hide-details
background-color="white" v-on:keydown.enter.prevent="
() => {
sendCurrentTextMessage();
}
2023-01-30 08:36:02 +00:00
" />
</v-col>
2020-12-04 12:15:47 +01:00
2022-05-17 15:16:53 +00:00
<v-col class="input-area-button text-center flex-grow-0 flex-shrink-1" v-if="editedEvent">
<v-btn fab small elevation="0" color="black" @click.stop="cancelEditReply">
<v-icon color="white">cancel</v-icon>
</v-btn>
</v-col>
2021-02-23 22:07:57 +01:00
2023-04-10 08:38:04 +00:00
<v-col v-if="(!currentInput || currentInput.length == 0) && canCreatePoll && !replyToEvent"
2023-01-30 08:36:02 +00:00
class="input-area-button text-center flex-grow-0 flex-shrink-1">
<v-btn icon large color="black" @click="showCreatePollDialog = true">
2023-01-05 09:35:47 +00:00
<v-icon dark>$vuetify.icons.poll</v-icon>
</v-btn>
</v-col>
2023-01-30 08:36:02 +00:00
<v-col class="input-area-button text-center flex-grow-0 flex-shrink-1"
v-if="!currentInput || currentInput.length == 0 || showRecorder">
<v-btn v-if="canRecordAudio" class="mic-button" ref="mic_button" fab small elevation="0" v-blur
v-longTap:250="[showRecordingUI, startRecording]">
<v-icon :color="showRecorder ? 'white' : 'black'">mic</v-icon>
</v-btn>
2023-01-30 08:36:02 +00:00
<v-btn v-else class="mic-button" ref="mic_button" fab small elevation="0" v-blur
@click.stop="showNoRecordingAvailableDialog = true">
<v-icon :color="showRecorder ? 'white' : 'black'">mic</v-icon>
</v-btn>
</v-col>
2021-02-23 22:07:57 +01:00
2022-05-17 15:16:53 +00:00
<v-col class="input-area-button text-center flex-grow-0 flex-shrink-1" v-else>
2023-01-30 08:36:02 +00:00
<v-btn fab small elevation="0" color="black" @click.stop="sendCurrentTextMessage"
:disabled="sendButtonDisabled">
2022-05-17 15:16:53 +00:00
<v-icon color="white">{{ editedEvent ? "save" : "arrow_upward" }}</v-icon>
</v-btn>
</v-col>
2021-02-23 22:07:57 +01:00
2023-01-30 08:36:02 +00:00
<v-col class="input-area-button text-center flex-grow-0 flex-shrink-1 input-more-icon">
<v-btn fab small elevation="0" v-blur @click.stop="
isEmojiQuickReaction = false
showMoreMessageOperations($event)
">
2022-06-11 12:30:50 +03:00
<v-icon>$vuetify.icons.addReaction</v-icon>
</v-btn>
</v-col>
2022-05-17 15:16:53 +00:00
<v-col v-if="$config.shortCodeStickers" class="input-area-button text-center flex-grow-0 flex-shrink-1">
<v-btn id="btn-attach" icon large color="black" @click="showStickerPicker"
2023-01-30 08:36:02 +00:00
:disabled="attachButtonDisabled">
<v-icon large>face</v-icon>
2021-02-23 22:07:57 +01:00
</v-btn>
</v-col>
<v-col class="input-area-button text-center flex-grow-0 flex-shrink-1">
<label icon flat ref="attachmentLabel">
<v-btn icon large color="black" @click="showAttachmentPicker"
2023-01-30 08:36:02 +00:00
:disabled="attachButtonDisabled">
<v-icon x-large>add_circle_outline</v-icon>
</v-btn>
</label>
</v-col>
</v-row>
2023-01-30 08:36:02 +00:00
<VoiceRecorder :micButtonRef="$refs.mic_button" :ptt="showRecorderPTT" :show="showRecorder"
v-on:close="showRecorder = false" v-on:file="onVoiceRecording" />
</div>
2023-03-16 15:23:26 +01:00
<div v-if="!useVoiceMode && room && $matrix.currentRoomIsReadOnlyForUser" class="input-area-read-only">{{ $t("message.not_allowed_to_send") }}</div>
2020-12-04 12:15:47 +01:00
</v-container>
2020-11-17 20:02:42 +01:00
2023-01-30 08:36:02 +00:00
<input ref="attachment" type="file" name="attachment" @change="handlePickedAttachment($event)"
2023-05-06 14:03:15 +03:00
accept="image/*, audio/*, video/*, .pdf" class="d-none" multiple/>
2023-01-30 08:36:02 +00:00
2023-06-28 12:14:44 +00:00
<div v-if="currentFileInputsDialog && !useFileModeNonAdmin">
<v-dialog v-model="currentFileInputsDialog" class="ma-0 pa-0" :width="$vuetify.breakpoint.smAndUp ? '50%' : '85%'" persistent scrollable>
2020-11-17 20:02:42 +01:00
<v-card class="ma-0 pa-0">
<v-card-title>{{ $t('message.send_attachements_dialog_title') }}</v-card-title>
<v-divider></v-divider>
2023-06-28 12:14:44 +00:00
<template v-if="imageFiles && imageFiles.length">
<v-card-title v-if="imageFiles.length > 1"> {{ $t('message.images') }} </v-card-title>
<v-card-text :class="{'ma-0 pa-2' : true, 'd-flex flex-wrap justify-center': imageFiles.length > 1}">
<div :class="{'col-4': imageFiles.length > 1}" v-for="(currentImageInput, id) in imageFiles" :key="id">
2023-05-06 14:03:15 +03:00
<v-img v-if="currentImageInput && currentImageInput.image" :aspect-ratio="1" :src="currentImageInput.image"
contain class="current-image-input-path" />
<div>
<span v-if="currentImageInput && currentImageInput.scaled && currentImageInput.useScaled">
{{ currentImageInput.scaledDimensions.width }} x {{ currentImageInput.scaledDimensions.height }}</span>
<span v-else-if="currentImageInput && currentImageInput.dimensions">
{{ currentImageInput.dimensions.width }} x {{ currentImageInput.dimensions.height }}</span>
<span v-if="currentImageInput && currentImageInput.scaled && currentImageInput.useScaled">
({{ formatBytes(currentImageInput.scaledSize) }})</span>
<v-switch v-if="currentImageInput && currentImageInput.scaled" :label="$t('message.scale_image')"
v-model="currentImageInput.useScaled" />
</div>
</div>
</v-card-text>
</template>
<template v-if="Array.isArray(currentFileInputs) && currentFileInputs.length">
<v-card-title v-if="nonImageFiles.length > 1">{{ $t('message.files') }}</v-card-title>
2023-05-06 14:03:15 +03:00
<v-card-text>
<div v-for="(currentImageInputPath, id) in currentFileInputs" :key="id">
<div v-if="!currentImageInputPath.type.includes('image/')">
<span> {{ $t('message.file') }}: {{ currentImageInputPath.name }}</span>
<span> ({{ formatBytes(currentImageInputPath.size) }})</span>
</div>
2023-05-06 14:03:15 +03:00
</div>
</v-card-text>
</template>
2020-11-17 20:02:42 +01:00
<v-divider></v-divider>
<v-card-actions>
<v-spacer>
<div v-if="currentSendError">{{ currentSendError }}</div>
<div v-else>{{ currentSendProgress }}</div>
</v-spacer>
<v-btn color="primary" text @click="cancelSendAttachment" id="btn-attachment-cancel">
{{ $t("menu.cancel") }}
</v-btn>
2023-01-30 08:36:02 +00:00
<v-btn id="btn-attachment-send" color="primary" text @click="sendAttachment"
v-if="currentSendShowSendButton" :disabled="currentSendOperation != null">{{ $t("menu.send") }}</v-btn>
2020-11-17 20:02:42 +01:00
</v-card-actions>
</v-card>
</v-dialog>
</div>
2020-11-25 14:42:50 +01:00
2022-05-17 15:16:53 +00:00
<MessageOperationsBottomSheet ref="messageOperationsSheet">
<VEmojiPicker ref="emojiPicker" @select="emojiSelected" :i18n="i18nEmoji"/>
</MessageOperationsBottomSheet>
2020-12-10 12:37:06 +01:00
2022-05-17 15:16:53 +00:00
<StickerPickerBottomSheet ref="stickerPickerSheet" v-on:selectSticker="sendSticker" />
2021-02-17 17:12:16 +01:00
<!-- Loading indicator -->
2022-05-17 15:16:53 +00:00
<v-container fluid class="loading-indicator" fill-height v-if="!initialLoadDone || loading">
2021-02-17 17:12:16 +01:00
<v-row align="center" justify="center">
<v-col class="text-center">
2022-05-17 15:16:53 +00:00
<v-progress-circular indeterminate color="primary"></v-progress-circular>
2021-02-17 17:12:16 +01:00
</v-col>
</v-row>
</v-container>
2021-03-11 13:55:10 +01:00
<RoomInfoBottomSheet ref="roomInfoSheet" />
<!-- Dialog for audio recording not supported! -->
2022-05-17 15:16:53 +00:00
<v-dialog v-model="showNoRecordingAvailableDialog" class="ma-0 pa-0" width="80%">
<v-card>
2022-05-17 15:16:53 +00:00
<v-card-title>{{ $t("voice_recorder.not_supported_title") }}</v-card-title>
<v-card-text>{{ $t("voice_recorder.not_supported_text") }} </v-card-text>
<v-divider></v-divider>
<v-card-actions>
<v-spacer></v-spacer>
2022-05-17 15:16:53 +00:00
<v-btn id="btn-ok" color="primary" text @click="showNoRecordingAvailableDialog = false">{{
2023-01-30 08:36:02 +00:00
$t("menu.ok")
2022-05-17 15:16:53 +00:00
}}</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
2022-05-17 15:16:53 +00:00
<CreatePollDialog :show="showCreatePollDialog" @close="showCreatePollDialog = false" />
2020-11-09 10:26:56 +01:00
</div>
</template>
<script>
import Vue from "vue";
import { TimelineWindow, EventTimeline } from "matrix-js-sdk";
2023-06-28 12:14:44 +00:00
import util, { ROOM_TYPE_VOICE_MODE, ROOM_TYPE_FILE_MODE } from "../plugins/utils";
2020-11-25 14:42:50 +01:00
import MessageOperations from "./messages/MessageOperations.vue";
import AvatarOperations from "./messages/AvatarOperations.vue";
2020-12-04 17:15:18 +01:00
import ChatHeader from "./ChatHeader";
2021-02-22 16:34:19 +01:00
import VoiceRecorder from "./VoiceRecorder";
2021-03-11 13:55:10 +01:00
import RoomInfoBottomSheet from "./RoomInfoBottomSheet";
import CreatedRoomWelcomeHeader from "./CreatedRoomWelcomeHeader";
import NoHistoryRoomWelcomeHeader from "./NoHistoryRoomWelcomeHeader.vue";
import MessageOperationsBottomSheet from "./MessageOperationsBottomSheet";
import StickerPickerBottomSheet from "./StickerPickerBottomSheet";
import BottomSheet from "./BottomSheet.vue";
import ImageResize from "image-resize";
import CreatePollDialog from "./CreatePollDialog.vue";
2022-05-23 15:19:55 +00:00
import chatMixin from "./chatMixin";
2023-01-30 08:36:02 +00:00
import AudioLayout from "./AudioLayout.vue";
2023-06-28 12:14:44 +00:00
import FileDropLayout from "./file_mode/FileDropLayout";
const sizeOf = require("image-size");
const dataUriToBuffer = require("data-uri-to-buffer");
const prettyBytes = require("pretty-bytes");
const READ_RECEIPT_TIMEOUT = 5000; /* How long a message must have been visible before the read marker is updated */
const WINDOW_BUFFER_SIZE = 0.3; /** Relative window height of when we start paginating. Always keep this much loaded before and after our scroll position! */
// from https://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html
function ScrollPosition(node) {
this.node = node;
this.previousScrollHeightMinusTop = 0;
2020-11-17 20:02:42 +01:00
this.previousScrollTop = 0;
this.readyFor = "up";
}
2023-01-30 08:36:02 +00:00
ScrollPosition.prototype.restore = function () {
if (this.readyFor === "up") {
2022-05-17 15:16:53 +00:00
this.node.scrollTop = this.node.scrollHeight - this.previousScrollHeightMinusTop;
2020-11-17 20:02:42 +01:00
} else {
this.node.scrollTop = this.previousScrollTop;
}
};
2023-01-30 08:36:02 +00:00
ScrollPosition.prototype.prepareFor = function (direction) {
this.readyFor = direction || "up";
2020-11-17 20:02:42 +01:00
if (this.readyFor === "up") {
2022-05-17 15:16:53 +00:00
this.previousScrollHeightMinusTop = this.node.scrollHeight - this.node.scrollTop;
2020-11-17 20:02:42 +01:00
} else {
this.previousScrollTop = this.node.scrollTop;
}
};
2020-11-09 10:26:56 +01:00
export default {
name: "Chat",
2022-05-23 15:19:55 +00:00
mixins: [chatMixin],
components: {
2020-12-04 17:15:18 +01:00
ChatHeader,
2020-11-25 14:42:50 +01:00
MessageOperations,
2021-03-04 12:48:32 +01:00
VoiceRecorder,
RoomInfoBottomSheet,
CreatedRoomWelcomeHeader,
NoHistoryRoomWelcomeHeader,
MessageOperationsBottomSheet,
StickerPickerBottomSheet,
BottomSheet,
AvatarOperations,
2022-05-17 15:16:53 +00:00
CreatePollDialog,
2023-06-28 12:14:44 +00:00
AudioLayout,
FileDropLayout
},
2020-11-19 22:48:08 +01:00
data() {
return {
waitingForRoomObject: false,
2020-11-19 22:48:08 +01:00
events: [],
currentInput: "",
typingMembers: [],
timelineSet: null,
2020-11-19 22:48:08 +01:00
timelineWindow: null,
/** true if we are currently paginating */
timelineWindowPaginating: false,
2020-11-19 22:48:08 +01:00
scrollPosition: null,
currentFileInputs: null,
2020-11-19 22:48:08 +01:00
currentSendOperation: null,
currentSendProgress: null,
2021-03-10 17:24:48 +01:00
currentSendShowSendButton: true,
2020-11-19 22:48:08 +01:00
currentSendError: null,
2020-11-25 14:42:50 +01:00
showEmojiPicker: false,
selectedEvent: null,
2020-12-14 16:11:45 +01:00
editedEvent: null,
2020-12-15 17:06:26 +01:00
replyToEvent: null,
replyToImg: null,
replyToContentType: null,
showCreatePollDialog: false,
showNoRecordingAvailableDialog: false,
2020-12-04 10:44:46 +01:00
showContextMenu: false,
2021-01-11 17:42:58 +01:00
showContextMenuAnchor: null,
showAvatarMenu: false,
showAvatarMenuAnchor: null,
initialLoadDone: false,
2021-04-09 16:20:57 +02:00
loading: false, // Set this to true during long operations to show a "spinner" overlay
2021-02-22 16:34:19 +01:00
showRecorder: false,
2021-03-05 22:34:00 +01:00
showRecorderPTT: false, // True to open the voice recorder in push-to-talk mode.
2021-01-11 17:42:58 +01:00
2020-12-04 10:44:46 +01:00
/**
* Current chat container size. We need to keep track of this so that if and when
* a soft keyboard is shown/hidden we can restore the scroll position correctly.
* If we don't, the keyboard will simply overflow the message we are answering to etc.
*/
chatContainerSize: 0,
2020-12-10 12:37:06 +01:00
/**
* True if we should show the "scroll to end" marker in the chat. For now at least, we use a simple
* method here, basically just "if we can scroll, show it".
*/
showScrollToEnd: false,
/** A timer for read receipts. */
rrTimer: null,
/** Last event we sent a Read Receipt/Read Marker for */
lastRR: null,
/** If we just created this room, show a small welcome header with info */
showCreatedRoomWelcomeHeader: false,
/** An array of recent emojis. Used in the "message operations" popup. */
recentEmojis: [],
/** Calculated style for message operations. We position the "popup" at the selected message. */
opStyle: "",
2022-06-11 12:30:50 +03:00
isEmojiQuickReaction: true,
i18nEmoji: {
search: this.$t("emoji.search"),
categories: {
Activity: this.$t("emoji.categories.activity"),
Flags: this.$t("emoji.categories.flags"),
Foods: this.$t("emoji.categories.foods"),
Frequently: this.$t("emoji.categories.frequently"),
Objects: this.$t("emoji.categories.objects"),
Nature: this.$t("emoji.categories.nature"),
Peoples: this.$t("emoji.categories.peoples"),
Symbols: this.$t("emoji.categories.symbols"),
Places: this.$t("emoji.categories.places")
}
}
2020-11-19 22:48:08 +01:00
};
},
2020-11-09 10:26:56 +01:00
filters: {
latestReply(contents) {
2022-05-17 15:16:53 +00:00
const contentArr = contents.split("\n").reverse();
if (contentArr[0] === "") {
contentArr.shift();
}
2022-05-17 15:16:53 +00:00
return contentArr[0].replace(/^> (<.*> )?/g, "");
},
},
mounted() {
this.$root.$on('audio-playback-ended', this.audioPlaybackEnded);
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
if (container) {
this.scrollPosition = new ScrollPosition(container);
if (this.$refs.chatContainerResizer) {
this.chatContainerSize = this.$refs.chatContainerResizer.$el.clientHeight;
}
}
},
beforeDestroy() {
this.$root.$off('audio-playback-ended', this.audioPlaybackEnded);
this.$audioPlayer.pause();
this.stopRRTimer();
},
destroyed() {
this.$matrix.off("Room.timeline", this.onEvent);
this.$matrix.off("RoomMember.typing", this.onUserTyping);
},
2020-11-09 10:26:56 +01:00
computed: {
nonImageFiles() {
return this.isCurrentFileInputsAnArray && this.currentFileInputs.filter(file => !file.type.includes("image/"))
2023-05-06 14:03:15 +03:00
},
2023-06-28 12:14:44 +00:00
imageFiles() {
return this.isCurrentFileInputsAnArray && this.currentFileInputs.filter(file => file.type.includes("image/"))
},
isCurrentFileInputsAnArray() {
return Array.isArray(this.currentFileInputs)
},
currentFileInputsDialog: {
2023-05-06 14:03:15 +03:00
get() {
return this.isCurrentFileInputsAnArray
2023-05-06 14:03:15 +03:00
},
set() {
this.currentFileInputs = null
2023-05-06 14:03:15 +03:00
}
},
2023-01-30 08:36:02 +00:00
chatContainer() {
const container = this.$refs.chatContainer;
if (this.useVoiceMode) {
2023-01-30 08:36:02 +00:00
return container.$el;
}
return container;
},
2022-11-20 13:39:20 +02:00
senderDisplayName() {
return this.room.getMember(this.replyToEvent.sender.userId).name;
},
2021-01-11 17:42:58 +01:00
currentUser() {
return this.$store.state.auth.user;
},
2020-12-09 15:20:50 +01:00
room() {
return this.$matrix.currentRoom;
},
2020-11-09 10:26:56 +01:00
roomId() {
if (!this.$matrix.ready && this.currentUser) {
// If we have a user already, wait for ready state. If not, we
// dont want to return here, because we want to redirect to "join".
2021-02-17 17:12:16 +01:00
return null; // Not ready yet...
}
if (this.room) {
return this.room.roomId;
}
2021-01-11 17:42:58 +01:00
return this.$matrix.currentRoomId;
2020-11-09 10:26:56 +01:00
},
2021-01-28 22:13:08 +01:00
roomAliasOrId() {
if (this.room) {
return this.room.getCanonicalAlias() || this.room.roomId;
}
return this.$matrix.currentRoomId;
},
readMarker() {
if (this.lastRR) {
// If we have sent a RR, use that as read marker (so we don't have to wait for server round trip)
return this.lastRR.getId();
}
2022-05-17 15:16:53 +00:00
return this.fullyReadMarker || this.room.getEventReadUpTo(this.$matrix.currentUserId, false);
},
fullyReadMarker() {
2023-03-16 08:17:29 +00:00
const readEvent = this.room && this.room.getAccountData("m.fully_read");
if (readEvent) {
return readEvent.getContent().event_id;
}
return null;
},
2020-12-14 17:12:29 +01:00
attachButtonDisabled() {
2022-05-17 15:16:53 +00:00
return this.editedEvent != null || this.replyToEvent != null || this.currentInput.length > 0;
2020-12-14 17:12:29 +01:00
},
2020-11-09 10:26:56 +01:00
sendButtonDisabled() {
return this.currentInput.length == 0;
},
typingMembersString() {
const count = this.typingMembers.length;
if (count > 1) {
return this.$t("message.users_are_typing", { count: count });
} else if (count > 0) {
return this.$t("message.user_is_typing", {
user: this.typingMembers[0].name,
});
} else {
return "";
}
2020-12-14 16:11:45 +01:00
},
showMessageOperations() {
return this.selectedEvent && this.showContextMenu;
},
avatarOpStyle() {
// Calculate where to show the context menu.
//
const ref = this.selectedEvent && this.$refs[this.selectedEvent.getId()];
var top = 0;
2023-05-23 10:20:42 +02:00
var left = "unset";
var right = "unset";
if (ref && ref[0]) {
if (this.showAvatarMenuAnchor) {
var rectAnchor = this.showAvatarMenuAnchor.getBoundingClientRect();
2022-05-17 15:16:53 +00:00
var rectChat = this.$refs.avatarOperationsStrut.getBoundingClientRect();
top = rectAnchor.top - rectChat.top;
2023-05-23 10:20:42 +02:00
if (this.$vuetify.rtl) {
right = (rectAnchor.right - rectChat.right)+ "px";
} else {
left = (rectAnchor.left - rectChat.left) + "px";
}
// if (left + 250 > rectChat.right) {
// left = rectChat.right - 250; // Pretty ugly, but we want to make sure it does not escape the screen, and we don't have the exakt width of it (yet)!
// }
}
}
2023-05-23 10:20:42 +02:00
return "top:" + top + "px;left:" + left + ";right:" + right;
},
canRecordAudio() {
return util.browserCanRecordAudio();
},
debugging() {
return false; //(window.location.host || "").startsWith("localhost");
},
canCreatePoll() {
// We say that if you can redact events, you are allowed to create polls.
const me = this.room && this.room.getMember(this.$matrix.currentUserId);
2022-05-17 15:16:53 +00:00
let isAdmin =
me && this.room.currentState && this.room.currentState.hasSufficientPowerLevelFor("redact", me.powerLevel);
return isAdmin;
2022-05-17 15:16:53 +00:00
},
useVoiceMode: {
2023-01-30 08:36:02 +00:00
get: function () {
if (!this.$config.experimental_voice_mode) return false;
2023-06-28 12:14:44 +00:00
return util.roomDisplayType(this.room) === ROOM_TYPE_VOICE_MODE;
2023-01-30 08:36:02 +00:00
},
},
2023-06-28 12:14:44 +00:00
useFileModeNonAdmin: {
get: function() {
if (!this.$config.experimental_file_mode) return false;
return util.roomDisplayType(this.room) === ROOM_TYPE_FILE_MODE && !this.canCreatePoll; // TODO - Check user or admin
}
},
/**
* If we have no events and the room is encrypted, show info about this
* to the user.
*/
showNoHistoryRoomWelcomeHeader() {
return this.filteredEvents.length == 0 && this.room && this.$matrix.matrixClient.isRoomEncrypted(this.room.roomId);
},
filteredEvents() {
if (this.room && this.$matrix.matrixClient.isRoomEncrypted(this.room.roomId)) {
if (this.room.getHistoryVisibility() == "joined") {
// For encrypted rooms where history is set to "joined" we can't read old events.
// We might, however, have old status events from room creation etc.
// We filter out anything that happened before our own join event.
for (let idx = this.events.length - 1; idx >= 0; idx--) {
const e = this.events[idx];
if (e.getType() == "m.room.member" &&
e.getContent().membership == "join" &&
(!e.getPrevContent() || e.getPrevContent().membership != "join") &&
e.getStateKey() == this.$matrix.currentUserId) {
// Our own join event.
return this.events.slice(idx + 1);
}
}
}
}
return this.events;
}
2020-11-09 10:26:56 +01:00
},
watch: {
2023-01-30 08:36:02 +00:00
initialLoadDone: {
immediate: true,
handler(value, oldValue) {
if (value && !oldValue) {
console.log("Loading finished!");
}
}
},
2021-01-28 22:13:08 +01:00
roomId: {
2020-12-15 17:06:26 +01:00
immediate: true,
2021-01-28 22:13:08 +01:00
handler(value, oldValue) {
if (value && value == oldValue) {
return; // No change.
}
2022-05-17 15:16:53 +00:00
console.log("Chat: Current room changed to " + (value ? value : "null"));
2020-11-09 10:26:56 +01:00
2020-11-25 14:42:50 +01:00
// Clear old events
this.$matrix.off("Room.timeline", this.onEvent);
this.$matrix.off("RoomMember.typing", this.onUserTyping);
this.waitingForRoomObject = false;
2020-11-25 14:42:50 +01:00
this.events = [];
this.timelineWindow = null;
this.typingMembers = [];
this.initialLoadDone = false;
2022-04-21 09:41:52 +00:00
this.showCreatedRoomWelcomeHeader = false;
// Stop RR timer
this.stopRRTimer();
this.lastRR = null;
if (this.roomId) {
this.$matrix.isJoinedToRoom(this.roomId).then(joined => {
if (!joined) {
this.onRoomNotJoined();
} else {
if (this.room) {
this.onRoomJoined(this.readMarker);
} else {
this.waitingForRoomObject = true;
return; // no room, wait for it (we know we are joined so need to wait for sync to complete)
}
}
});
} else {
this.initialLoadDone = true;
2020-11-25 14:42:50 +01:00
return; // no room
}
},
2021-01-11 17:42:58 +01:00
},
room() {
// Were we waiting?
if (this.room && this.room.roomId == this.roomId && this.waitingForRoomObject) {
this.waitingForRoomObject = false;
this.onRoomJoined(this.readMarker);
}
},
showMessageOperations() {
if (this.showMessageOperations) {
this.$nextTick(() => {
// Calculate where to show the context menu.
//
2022-05-17 15:16:53 +00:00
const ref = this.selectedEvent && this.$refs[this.selectedEvent.getId()];
var top = 0;
var left = 0;
if (ref && ref[0]) {
if (this.showContextMenuAnchor) {
2022-05-17 15:16:53 +00:00
var rectAnchor = this.showContextMenuAnchor.getBoundingClientRect();
var rectChat = this.$refs.messageOperationsStrut.getBoundingClientRect();
var rectOps = this.$refs.messageOperations.$el.getBoundingClientRect();
top = rectAnchor.top - rectChat.top - 50;
2023-04-10 10:05:46 +03:00
left = rectAnchor.left - rectChat.left - 75;
if (left + rectOps.width >= rectChat.right) {
left = rectChat.right - rectOps.width - 10; // No overflow
}
}
}
this.opStyle = "top:" + top + "px;left:" + left + "px";
});
}
},
showRecorder(show) {
if (this.useVoiceMode) {
// Send typing indicators when recorder UI is opened/closed
this.$matrix.matrixClient.sendTyping(this.roomId, show, 10 * 60 * 1000);
}
}
2021-01-11 17:42:58 +01:00
},
methods: {
onRoomJoined(initialEventId) {
// Was this room just created (by you)? Show a small info header in
// that case!
2022-05-17 15:16:53 +00:00
const createEvent = this.room.currentState.getStateEvents("m.room.create", "");
if (createEvent) {
const creatorId = createEvent.getContent().creator;
2022-05-17 15:16:53 +00:00
if (creatorId == this.$matrix.currentUserId && createEvent.getLocalAge() < 5 * 60000 /* 5 minutes */) {
this.showCreatedRoomWelcomeHeader = true;
}
}
// Listen to events
this.$matrix.on("Room.timeline", this.onEvent);
this.$matrix.on("RoomMember.typing", this.onUserTyping);
console.log("Read up to " + initialEventId);
//initialEventId = null;
this.timelineSet = this.room.getUnfilteredTimelineSet();
2022-05-17 15:16:53 +00:00
this.timelineWindow = new TimelineWindow(this.$matrix.matrixClient, this.timelineSet, {});
2021-01-28 22:13:08 +01:00
const self = this;
2021-03-04 12:48:32 +01:00
this.timelineWindow
.load(initialEventId, 20)
.then(() => {
self.events = self.timelineWindow.getEvents();
const getMoreIfNeeded = function _getMoreIfNeeded() {
const container = self.$refs.chatContainer;
if (
2023-01-30 08:36:02 +00:00
container &&
2022-05-17 15:16:53 +00:00
container.scrollHeight <= (1 + 2 * WINDOW_BUFFER_SIZE) * container.clientHeight &&
2021-03-04 12:48:32 +01:00
self.timelineWindow &&
self.timelineWindow.canPaginate(EventTimeline.BACKWARDS)
) {
2022-05-17 15:16:53 +00:00
return self.timelineWindow.paginate(EventTimeline.BACKWARDS, 10, true, 5).then((success) => {
self.events = self.timelineWindow.getEvents();
if (success) {
return _getMoreIfNeeded.call(self);
} else {
return Promise.reject("Failed to paginate");
}
});
2021-03-04 12:48:32 +01:00
} else {
return Promise.resolve("Done");
}
}.bind(self);
getMoreIfNeeded()
.catch((err) => {
console.log("ERROR " + err);
})
.finally(() => {
self.initialLoadDone = true;
if (initialEventId && !this.showCreatedRoomWelcomeHeader) {
2021-03-04 12:48:32 +01:00
self.scrollToEvent(initialEventId);
} else if (this.showCreatedRoomWelcomeHeader) {
self.onScroll();
2021-03-04 12:48:32 +01:00
}
self.restartRRTimer();
});
})
.catch((err) => {
console.log("Error fetching events!", err, this);
if (err.errcode == "M_UNKNOWN" && initialEventId) {
// Try again without initial event!
this.onRoomJoined(null);
} else {
2021-03-04 12:48:32 +01:00
// Error. Done loading.
this.events = this.timelineWindow.getEvents();
this.initialLoadDone = true;
}
2022-03-23 14:11:50 +01:00
})
.finally(() => {
for (var event of this.events) {
this.$matrix.matrixClient.decryptEventIfNeeded(event, {});
}
2021-03-04 12:48:32 +01:00
});
2020-11-09 10:26:56 +01:00
},
2021-01-11 17:42:58 +01:00
onRoomNotJoined() {
this.$navigation.push(
{
name: "Join",
params: { roomId: util.sanitizeRoomId(this.roomAliasOrId) },
},
0
);
2021-01-11 17:42:58 +01:00
},
2021-04-09 16:20:57 +02:00
scrollToEndOfTimeline() {
2022-05-17 15:16:53 +00:00
if (this.timelineWindow && this.timelineWindow.canPaginate(EventTimeline.FORWARDS)) {
2021-04-09 16:20:57 +02:00
this.loading = true;
// Instead of paging though ALL history, just reload a timeline at the live marker...
var timelineSet = this.room.getUnfilteredTimelineSet();
2022-05-17 15:16:53 +00:00
var timelineWindow = new TimelineWindow(this.$matrix.matrixClient, timelineSet, {});
const self = this;
timelineWindow
.load(null, 20)
.then(() => {
self.timelineSet = timelineSet;
self.timelineWindow = timelineWindow;
self.events = self.timelineWindow.getEvents();
})
.finally(() => {
this.loading = false;
});
2021-04-09 16:20:57 +02:00
} else {
// Can't paginate, just scroll to bottom of window!
this.smoothScrollToEnd();
}
},
2020-12-03 22:12:50 +01:00
touchX(event) {
2020-12-04 10:44:46 +01:00
if (event.type.indexOf("mouse") !== -1) {
2020-12-03 22:12:50 +01:00
return event.clientX;
}
2020-12-03 22:12:50 +01:00
return event.touches[0].clientX;
},
2020-12-03 22:12:50 +01:00
touchY(event) {
2020-12-04 10:44:46 +01:00
if (event.type.indexOf("mouse") !== -1) {
2020-12-03 22:12:50 +01:00
return event.clientY;
}
return event.touches[0].clientY;
},
touchStart(e, event) {
if (this.selectedEvent != event) {
this.showContextMenu = false;
}
this.selectedEvent = event;
2020-12-03 22:12:50 +01:00
this.touchStartX = this.touchX(e);
this.touchStartY = this.touchY(e);
this.touchTimer = setTimeout(this.touchTimerElapsed, 500);
},
touchEnd() {
this.touchTimer && clearTimeout(this.touchTimer);
},
touchCancel() {
this.touchTimer && clearTimeout(this.touchTimer);
},
touchMove(e) {
this.touchCurrentX = this.touchX(e);
this.touchCurrentY = this.touchY(e);
var tapTolerance = 4;
2020-12-04 10:44:46 +01:00
var touchMoved =
Math.abs(this.touchStartX - this.touchCurrentX) > tapTolerance ||
Math.abs(this.touchStartY - this.touchCurrentY) > tapTolerance;
if (touchMoved) {
2020-12-03 22:12:50 +01:00
this.touchTimer && clearTimeout(this.touchTimer);
}
},
2020-12-04 10:44:46 +01:00
/**
2021-03-05 22:34:00 +01:00
* Triggered when our "long tap" timer hits.
2020-12-04 10:44:46 +01:00
*/
2020-12-03 22:12:50 +01:00
touchTimerElapsed() {
this.updateRecentEmojis();
this.showContextMenu = true;
},
2020-12-04 10:44:46 +01:00
/**
* If chat container is shrunk (probably because soft keyboard is shown) adjust
* the scroll position so that e.g. if we were looking at the last message when
* moving focus to the input field, we would still see the last message. Otherwise
* if would be hidden behind the keyboard.
*/
2020-12-04 12:15:47 +01:00
handleChatContainerResize({ ignoredWidth, height }) {
2020-12-04 10:44:46 +01:00
const delta = height - this.chatContainerSize;
this.chatContainerSize = height;
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
if (container && delta < 0) {
2020-12-04 10:44:46 +01:00
container.scrollTop -= delta;
}
},
paginateBackIfNeeded() {
2020-11-17 20:02:42 +01:00
this.$nextTick(() => {
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
if (container && container.scrollHeight <= container.clientHeight) {
2020-11-17 20:02:42 +01:00
this.handleScrolledToTop();
}
});
},
onScroll(ignoredevent) {
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
if (!container) {
return;
}
const bufferHeight = container.clientHeight * WINDOW_BUFFER_SIZE;
if (container.scrollTop <= bufferHeight) {
// Scrolled to top
this.handleScrolledToTop();
2022-05-17 15:16:53 +00:00
} else if (container.scrollHeight - container.scrollTop.toFixed(0) - container.clientHeight <= bufferHeight) {
2020-11-17 20:02:42 +01:00
this.handleScrolledToBottom(false);
}
2022-05-23 14:24:43 +00:00
this.showScrollToEnd =
container.scrollHeight === container.clientHeight
? false
: container.scrollHeight - container.scrollTop.toFixed(0) > container.clientHeight ||
2023-01-30 08:36:02 +00:00
(this.timelineWindow && this.timelineWindow.canPaginate(EventTimeline.FORWARDS));
this.restartRRTimer();
},
onEvent(event) {
//console.log("OnEvent", JSON.stringify(event));
if (event.getRoomId() !== this.roomId) {
return; // Not for this room
}
2023-01-30 08:36:02 +00:00
const loadingDone = this.initialLoadDone;
2022-03-23 14:11:50 +01:00
this.$matrix.matrixClient.decryptEventIfNeeded(event, {});
if (this.initialLoadDone && !this.useVoiceMode) {
this.paginateBackIfNeeded();
}
2020-11-17 20:02:42 +01:00
2023-01-30 08:36:02 +00:00
if (loadingDone && event.forwardLooking && !event.isRelation()) {
// If we are at bottom, scroll to see new events...
var scrollToSeeNew = event.getSender() == this.$matrix.currentUserId; // When we sent, scroll
const container = this.chatContainer;
2023-06-28 12:14:44 +00:00
if (container) {
if (container.scrollHeight - container.scrollTop.toFixed(0) == container.clientHeight) {
scrollToSeeNew = true;
}
2023-01-30 08:36:02 +00:00
}
2020-12-03 22:12:50 +01:00
this.handleScrolledToBottom(scrollToSeeNew);
2023-06-08 13:25:02 +00:00
// If kick or ban event, redirect to "goodbye"...
if (event.getType() === "m.room.member" &&
event.getStateKey() == this.$matrix.currentUserId &&
(event.getPrevContent() || {}).membership == "join" &&
(
(event.getContent().membership == "leave" && event.getSender() != this.currentUserId) ||
(event.getContent().membership == "ban" ))
) {
this.$store.commit("setCurrentRoomId", null);
const wasPurged = event.getContent().reason == "Room Deleted";
this.$navigation.push({ name: "Goodbye", params: { roomWasPurged: wasPurged } }, -1);
}
}
},
onUserTyping(event, member) {
if (member.roomId !== this.roomId) {
return; // Not for this room
2020-11-09 10:26:56 +01:00
}
if (member.typing) {
if (!this.typingMembers.includes(member)) {
this.typingMembers.push(member);
}
} else {
const index = this.typingMembers.indexOf(member);
if (index > -1) {
this.typingMembers.splice(index, 1);
}
}
//console.log("Typing: ", this.typingMembers);
2020-11-09 10:26:56 +01:00
},
2021-03-10 17:24:48 +01:00
sendCurrentTextMessage() {
// DOn't have "enter" send messages while in recorder.
if (this.currentInput.length > 0 && !this.showRecorder) {
this.sendMessage(this.currentInput);
this.currentInput = "";
this.editedEvent = null; //TODO - Is this a good place to reset this?
this.replyToEvent = null;
}
},
sendMessage(text) {
if (text && text.length > 0) {
2020-11-25 14:42:50 +01:00
util
2022-05-17 15:16:53 +00:00
.sendTextMessage(this.$matrix.matrixClient, this.roomId, text, this.editedEvent, this.replyToEvent)
2020-11-25 14:42:50 +01:00
.then(() => {
console.log("Sent message");
})
.catch((err) => {
console.log("Failed to send:", err);
});
2020-11-09 10:26:56 +01:00
}
},
2020-11-17 20:02:42 +01:00
/**
2020-12-10 12:37:06 +01:00
* Show attachment picker to select file
*/
showAttachmentPicker() {
this.$refs.attachment.click();
2020-12-10 12:37:06 +01:00
},
2023-05-06 14:03:15 +03:00
optimizeImage(e,event,file) {
2023-06-28 12:14:44 +00:00
file.image = e.target.result;
file.dimensions = null;
2023-05-06 14:03:15 +03:00
try {
2023-06-28 12:14:44 +00:00
file.dimensions = sizeOf(dataUriToBuffer(e.target.result));
2023-05-06 14:03:15 +03:00
// Need to resize?
2023-06-28 12:14:44 +00:00
const w = file.dimensions.width;
const h = file.dimensions.height;
2023-05-06 14:03:15 +03:00
if (w > 640 || h > 640) {
var aspect = w / h;
var newWidth = parseInt((w > h ? 640 : 640 * aspect).toFixed());
var newHeight = parseInt((w > h ? 640 / aspect : 640).toFixed());
var imageResize = new ImageResize({
format: "png",
width: newWidth,
height: newHeight,
outputType: "blob",
});
imageResize
.play(event.target)
.then((img) => {
Vue.set(
2023-06-28 12:14:44 +00:00
file,
2023-05-06 14:03:15 +03:00
"scaled",
new File([img], file.name, {
type: img.type,
lastModified: Date.now(),
})
);
2023-06-28 12:14:44 +00:00
Vue.set(file, "useScaled", true);
Vue.set(file, "scaledSize", img.size);
Vue.set(file, "scaledDimensions", {
2023-05-06 14:03:15 +03:00
width: newWidth,
height: newHeight,
});
})
.catch((err) => {
console.error("Resize failed:", err);
});
}
} catch (error) {
console.error("Failed to get image dimensions: " + error);
}
2023-06-28 12:14:44 +00:00
return file
2023-05-06 14:03:15 +03:00
},
handleFileReader(event, file) {
if (file) {
2020-11-17 20:02:42 +01:00
var reader = new FileReader();
reader.onload = (e) => {
if (file.type.startsWith("image/")) {
2023-06-28 12:14:44 +00:00
this.optimizeImage(e, event, file)
}
this.$matrix.matrixClient.getMediaConfig().then((config) => {
this.currentFileInputs = Array.isArray(this.currentFileInputs) ? [...this.currentFileInputs, file] : [file];
if (config["m.upload.size"] && file.size > config["m.upload.size"]) {
this.currentSendError = this.$t("message.upload_file_too_large");
this.currentSendShowSendButton = false;
} else {
this.currentSendShowSendButton = true;
}
});
2020-11-17 20:02:42 +01:00
};
2023-05-06 14:03:15 +03:00
reader.readAsDataURL(file);
2020-11-17 20:02:42 +01:00
}
},
2023-05-06 14:03:15 +03:00
/**
* Handle picked attachment
*/
handlePickedAttachment(event) {
Object.values(event.target.files).forEach(file => this.handleFileReader(event, file));
},
2020-11-17 20:02:42 +01:00
showStickerPicker() {
this.$refs.stickerPickerSheet.open();
},
2020-11-17 20:02:42 +01:00
onUploadProgress(p) {
if (p.total) {
2022-05-17 15:16:53 +00:00
this.currentSendProgress = this.$t("message.upload_progress_with_total", {
count: p.loaded || 0,
total: p.total,
});
2020-11-17 20:02:42 +01:00
} else {
this.currentSendProgress = this.$t("message.upload_progress", {
count: p.loaded || 0,
});
2020-11-17 20:02:42 +01:00
}
},
2021-03-10 17:24:48 +01:00
sendAttachment(withText) {
this.$refs.attachment.value = null;
if (this.isCurrentFileInputsAnArray) {
2023-06-28 12:14:44 +00:00
let inputFiles = this.currentFileInputs.map(entry => {
if (entry.scaled && entry.useScaled) {
// Send scaled version of image instead!
return entry.scaled;
}
return entry;
})
const promises = inputFiles.map(inputFile => util.sendImage(this.$matrix.matrixClient, this.roomId, inputFile, this.onUploadProgress));
Promise.all(promises).then(() => {
this.currentSendOperation = null;
this.currentFileInputs = null;
2021-03-10 13:40:32 +01:00
this.currentSendProgress = null;
if (withText) {
this.sendMessage(withText);
}
})
.catch((err) => {
if (err.name === "AbortError" || err === "Abort") {
this.currentSendError = null;
} else {
this.currentSendError = err.LocaleString();
}
this.currentSendOperation = null;
this.currentSendProgress = null;
});
2020-11-17 20:02:42 +01:00
}
},
2020-11-21 14:57:43 +01:00
cancelSendAttachment() {
this.$refs.attachment.value = null;
2020-11-21 14:57:43 +01:00
if (this.currentSendOperation) {
2023-01-09 21:12:17 +01:00
this.currentSendOperation.abort();
2020-11-21 14:57:43 +01:00
}
this.currentSendOperation = null;
this.currentFileInputs = null;
2021-03-10 13:40:32 +01:00
this.currentSendProgress = null;
this.currentSendError = null;
2020-11-09 10:26:56 +01:00
},
addAttachment(file) {
this.handleFileReader(null, file);
},
2023-06-28 12:14:44 +00:00
resetAttachments() {
this.cancelSendAttachment();
},
handleScrolledToTop() {
if (
this.timelineWindow &&
this.timelineWindow.canPaginate(EventTimeline.BACKWARDS) &&
!this.timelineWindowPaginating
) {
this.timelineWindowPaginating = true;
this.timelineWindow
.paginate(EventTimeline.BACKWARDS, 10, true)
.then((success) => {
if (success) {
this.scrollPosition.prepareFor("up");
this.events = this.timelineWindow.getEvents();
this.$nextTick(() => {
// restore scroll position!
console.log("Restore scroll!");
this.scrollPosition.restore();
});
}
})
.finally(() => {
this.timelineWindowPaginating = false;
});
}
},
2020-11-17 20:02:42 +01:00
handleScrolledToBottom(scrollToEnd) {
if (
this.timelineWindow &&
this.timelineWindow.canPaginate(EventTimeline.FORWARDS) &&
!this.timelineWindowPaginating
2020-11-17 20:02:42 +01:00
) {
this.timelineWindowPaginating = true;
2020-11-17 20:02:42 +01:00
this.timelineWindow
.paginate(EventTimeline.FORWARDS, 10, true)
.then((success) => {
if (success) {
this.events = this.timelineWindow.getEvents();
if (!this.useVoiceMode) {
2023-01-30 08:36:02 +00:00
this.scrollPosition.prepareFor("down");
this.$nextTick(() => {
// restore scroll position!
console.log("Restore scroll!");
this.scrollPosition.restore();
if (scrollToEnd) {
this.smoothScrollToEnd();
}
});
}
2020-11-17 20:02:42 +01:00
}
})
.finally(() => {
this.timelineWindowPaginating = false;
2020-11-17 20:02:42 +01:00
});
}
},
/**
* Scroll so that the given event is at the middle of the chat view (if more events) or else at the bottom.
*/
scrollToEvent(eventId) {
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
const ref = this.$refs[eventId];
if (container && ref) {
const targetY = container.clientHeight / 2;
const sourceY = ref[0].offsetTop;
container.scrollTo(0, sourceY - targetY);
}
},
2020-11-17 20:02:42 +01:00
smoothScrollToEnd() {
2023-01-30 08:36:02 +00:00
this.$nextTick(function () {
const container = this.chatContainer;
if (container && container.children.length > 0) {
2020-11-17 20:02:42 +01:00
const lastChild = container.children[container.children.length - 1];
console.log("Scroll into view", lastChild);
window.requestAnimationFrame(() => {
lastChild.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest",
});
});
}
});
},
2020-11-25 14:42:50 +01:00
showMoreMessageOperations(e) {
this.addReaction(e);
},
2020-11-25 14:42:50 +01:00
addReaction(e) {
const event = e.event;
// Store the event we are reacting to, so that we know where to
// send when the picker closes.
this.selectedEvent = event;
this.$refs.messageOperationsSheet.open();
2020-11-25 14:42:50 +01:00
this.showEmojiPicker = true;
},
addQuickReaction(e) {
this.sendQuickReaction({ reaction: e.emoji, event: e.event });
},
setReplyToImage(event) {
util
2022-05-17 15:16:53 +00:00
.getThumbnail(this.$matrix.matrixClient, event)
.then((url) => {
this.replyToImg = url;
})
.catch((err) => {
console.log("Failed to fetch thumbnail: ", err);
});
},
2020-12-15 17:06:26 +01:00
addReply(event) {
this.replyToEvent = event;
this.$refs.messageInput.focus();
this.replyToContentType = event.getContent().msgtype || 'm.poll';
this.setReplyToImage(event);
2020-12-15 17:06:26 +01:00
},
2020-12-14 16:11:45 +01:00
edit(event) {
this.editedEvent = event;
this.currentInput = event.getContent().body;
2020-12-14 16:30:27 +01:00
this.$refs.messageInput.focus();
2020-12-14 16:11:45 +01:00
},
redact(event) {
this.$matrix.matrixClient
.redactEvent(event.getRoomId(), event.getId())
.then(() => {
console.log("Message redacted");
})
.catch((err) => {
console.log("Redaction failed: ", err);
});
},
download(event) {
util
.getAttachment(this.$matrix.matrixClient, event)
.then((url) => {
const link = document.createElement("a");
link.href = url;
2021-01-28 22:13:08 +01:00
link.target = "_blank";
2022-02-13 11:31:41 +02:00
link.download = event.getContent().body || this.$t("fallbacks.download_name");
document.body.appendChild(link);
link.click();
2022-02-13 11:31:41 +02:00
2023-01-30 08:36:02 +00:00
setTimeout(function () {
2022-02-13 11:31:41 +02:00
document.body.removeChild(link);
URL.revokeObjectURL(url);
2022-05-17 15:16:53 +00:00
}, 200);
})
.catch((err) => {
console.log("Failed to fetch attachment: ", err);
});
},
2020-12-15 17:06:26 +01:00
cancelEditReply() {
2020-12-14 17:12:29 +01:00
this.currentInput = "";
this.editedEvent = null;
2020-12-15 17:06:26 +01:00
this.replyToEvent = null;
2020-12-14 17:12:29 +01:00
},
2020-11-25 14:42:50 +01:00
emojiSelected(e) {
2023-01-30 08:36:02 +00:00
if (this.isEmojiQuickReaction) {
// When quick emoji picker is clicked
2022-06-11 12:30:50 +03:00
if (this.selectedEvent) {
const event = this.selectedEvent;
this.selectedEvent = null;
this.sendQuickReaction({ reaction: e.data, event: event });
}
} else {
// When text input emoji picker is clicked
2023-01-07 11:04:07 +02:00
this.currentInput = `${this.currentInput} ${e.data}`;
2022-06-11 12:30:50 +03:00
this.$refs.messageInput.focus();
}
2020-11-25 14:42:50 +01:00
this.showEmojiPicker = false;
2022-03-21 07:50:31 +00:00
this.$refs.messageOperationsSheet.close();
2020-11-25 14:42:50 +01:00
},
sendClapReactionAtTime(e) {
util
.sendQuickReaction(this.$matrix.matrixClient, this.roomId, "👏", e.event, { timeOffset: e.timeOffset.toFixed(0)})
.then(() => {
console.log("Send clap reaction at time", e.timeOffset);
})
.catch((err) => {
console.log("Failed to send clap reaction:", err);
});
},
2020-11-25 14:42:50 +01:00
sendQuickReaction(e) {
let previousReaction = null;
// Figure out if we have already sent this emoji, in that case redact it again (toggle)
//
const reactions = this.timelineSet.relations.getChildEventsForEvent(e.event.getId(), 'm.annotation', 'm.reaction');
if (reactions && reactions._eventsCount > 0) {
const relations = reactions.getRelations();
for (const r of relations) {
const emoji = r.getRelation().key;
const sender = r.getSender();
if (emoji == e.reaction && sender == this.$matrix.currentUserId) {
previousReaction = r.isRedacted() ? null : r;
}
}
}
if (previousReaction) {
this.redact(previousReaction);
} else {
2020-11-25 14:42:50 +01:00
util
2022-05-17 15:16:53 +00:00
.sendQuickReaction(this.$matrix.matrixClient, this.roomId, e.reaction, e.event)
2020-12-04 10:44:46 +01:00
.then(() => {
console.log("Quick reaction message");
})
.catch((err) => {
console.log("Failed to send quick reaction:", err);
});
}
2020-12-04 10:44:46 +01:00
},
2020-12-14 16:11:45 +01:00
sendSticker(stickerShortCode) {
this.sendMessage(stickerShortCode);
},
2021-01-11 17:42:58 +01:00
showContextMenuForEvent(e) {
const event = e.event;
2020-12-14 16:11:45 +01:00
this.selectedEvent = event;
this.updateRecentEmojis();
this.showContextMenu = !this.showContextMenu;
2021-01-11 17:42:58 +01:00
this.showContextMenuAnchor = e.anchor;
2020-12-14 16:11:45 +01:00
},
showAvatarMenuForEvent(e) {
const event = e.event;
this.selectedEvent = event;
this.showAvatarMenu = true;
this.showAvatarMenuAnchor = e.anchor;
},
viewProfile() {
this.$navigation.push({ name: "Profile" }, 1);
},
startPrivateChat(e) {
this.loading = true;
this.$matrix
.getOrCreatePrivateChat(e.event.getSender())
.then((room) => {
this.$nextTick(() => {
this.$navigation.push(
{
name: "Chat",
params: {
2022-05-17 15:16:53 +00:00
roomId: util.sanitizeRoomId(room.getCanonicalAlias() || room.roomId),
},
},
-1
);
});
})
.catch((err) => {
console.error(err);
})
.finally(() => {
this.loading = false;
});
},
closeContextMenusIfOpen(e) {
2020-12-14 16:11:45 +01:00
if (this.showContextMenu) {
this.showContextMenu = false;
this.showContextMenuAnchor = null;
e.preventDefault();
}
if (this.showAvatarMenu) {
this.showAvatarMenu = false;
this.showAvatarMenuAnchor = null;
2020-12-14 16:11:45 +01:00
e.preventDefault();
}
},
/** Stop Read Receipt timer */
stopRRTimer() {
if (this.rrTimer) {
clearTimeout(this.rrTimer);
this.rrTimer = null;
}
},
/**
* Start/restart the timer to Read Receipts.
*/
restartRRTimer() {
this.stopRRTimer();
2023-01-30 08:36:02 +00:00
if (this.$matrix.currentRoomBeingPurged) {
return;
}
2023-01-30 08:36:02 +00:00
let eventIdFirst = null;
let eventIdLast = null;
2023-06-28 12:14:44 +00:00
if (!this.useVoiceMode && !this.useFileModeNonAdmin) {
2023-01-30 08:36:02 +00:00
const container = this.chatContainer;
const elFirst = util.getFirstVisibleElement(container, (item) => item.hasAttribute("eventId"));
const elLast = util.getLastVisibleElement(container, (item) => item.hasAttribute("eventId"));
2023-01-30 08:36:02 +00:00
if (elFirst && elLast) {
eventIdFirst = elFirst.getAttribute("eventId");
eventIdLast = elLast.getAttribute("eventId");
}
}
if (eventIdFirst && eventIdLast) {
this.rrTimer = setTimeout(() => { this.rrTimerElapsed(eventIdFirst, eventIdLast) }, READ_RECEIPT_TIMEOUT);
}
},
2023-01-30 08:36:02 +00:00
rrTimerElapsed(eventIdFirst, eventIdLast) {
this.rrTimer = null;
2023-01-30 08:36:02 +00:00
this.sendRR(eventIdFirst, eventIdLast);
this.restartRRTimer();
},
2023-01-30 08:36:02 +00:00
sendRR(eventIdFirst, eventIdLast) {
console.log("SEND RR", eventIdFirst, eventIdLast);
if (eventIdLast && this.room) {
var event = this.room.findEventById(eventIdLast);
const index = this.events.indexOf(event);
2023-01-30 08:36:02 +00:00
// Walk backwards through visible events to the first one that is incoming
//
var lastTimestamp = 0;
if (this.lastRR) {
lastTimestamp = this.lastRR.getTs();
}
2023-01-30 08:36:02 +00:00
for (var i = index; i >= 0; i--) {
event = this.events[i];
if (event == this.lastRR || event.getTs() <= lastTimestamp) {
// Already sent this or too old...
break;
}
// Make sure it's not a local echo event...
if (!event.getId().startsWith("~")) {
// Send read receipt
this.$matrix.matrixClient
.sendReadReceipt(event)
.then(() => {
this.$matrix.matrixClient.setRoomReadMarkers(this.room.roomId, event.getId());
})
.then(() => {
console.log("RR sent for event: " + event.getId());
this.lastRR = event;
})
.catch((err) => {
console.log("Failed to update read marker: ", err);
})
.finally(() => {
this.restartRRTimer();
});
return; // Bail out here
}
// Stop iterating at first visible
if (event.getId() == eventIdFirst) {
break;
}
}
}
2021-01-20 11:32:21 +01:00
},
2021-03-05 22:34:00 +01:00
showRecordingUI() {
this.showRecorderPTT = false;
this.showRecorder = true;
},
2021-02-22 16:34:19 +01:00
startRecording() {
2021-03-05 22:34:00 +01:00
this.showRecorderPTT = true;
2021-02-22 16:34:19 +01:00
this.showRecorder = true;
},
onVoiceRecording(event) {
2021-03-10 17:24:48 +01:00
this.currentSendShowSendButton = false;
this.currentFileInputs = Array.isArray(this.currentFileInputs) ? [...this.currentFileInputs, event.file] : [event.file];
2021-03-10 17:24:48 +01:00
var text = undefined;
if (this.currentInput && this.currentInput.length > 0) {
text = this.currentInput;
this.currentInput = "";
}
this.sendAttachment(text);
this.showRecorder = false;
// Log event
this.$analytics.event("Audio", "Voice message sent");
2021-03-04 12:48:32 +01:00
},
closeCreateRoomWelcomeHeader() {
this.showCreatedRoomWelcomeHeader = false;
this.$nextTick(() => {
// We change the layout when removing the welcome header, so call
// onScroll here to handle updates (e.g. remove the "scroll to last" if we now
// can see all messages).
this.onScroll();
});
},
updateRecentEmojis() {
if (this.$refs.emojiPicker) {
this.recentEmojis = this.$refs.emojiPicker.mapEmojis["Frequently"];
2021-06-29 14:25:57 +02:00
if (this.recentEmojis.length < 20) {
let peoples = this.$refs.emojiPicker.mapEmojis["Peoples"];
for (var p of peoples) {
this.recentEmojis.push(p);
}
}
return;
}
this.recentEmojis = [];
},
formatBytes(bytes) {
return prettyBytes(bytes);
},
onHeaderClick() {
2023-03-03 14:43:53 +00:00
const invitations = this.$matrix.invites.length;
const joinedRooms = this.$matrix.joinedRooms;
2023-03-03 14:43:53 +00:00
if (invitations == 0 && joinedRooms && joinedRooms.length == 1 && joinedRooms[0].roomId == this.room.roomId) {
// Only joined to this room, go directly to room details!
this.$navigation.push({ name: "RoomInfo" });
return;
}
this.$refs.roomInfoSheet.open();
},
2023-03-03 14:43:53 +00:00
viewRoomDetails() {
this.$navigation.push({ name: "RoomInfo" });
},
pollWasClosed(ignoredE) {
let div = document.createElement("div");
div.classList.add("toast");
div.innerText = this.$t("poll_create.results_shared");
2023-01-30 08:36:02 +00:00
this.chatContainer.parentElement.appendChild(div);
setTimeout(() => {
2023-01-30 08:36:02 +00:00
this.chatContainer.parentElement.removeChild(div);
}, 3000);
2023-03-16 15:23:26 +01:00
},
setShowRecorder() {
if (this.canRecordAudio) {
2023-03-16 15:23:26 +01:00
this.showRecorder = true;
} else {
2023-03-16 15:23:26 +01:00
this.showNoRecordingAvailableDialog = true;
}
},
2023-03-16 15:23:26 +01:00
/**
* Called when an audio message has played to the end. We listen to this so we can optionally auto-play
* the next audio event.
* @param matrixEvent The event that stopped playing
*/
audioPlaybackEnded(matrixEventId) {
if (!this.useVoiceMode) { // Voice mode has own autoplay handling inside "AudioLayout"!
// Auto play consecutive audio messages, either incoming or sent.
const filteredEvents = this.filteredEvents;
const index = filteredEvents.findIndex(e => e.getId() === matrixEventId);
if (index >= 0 && index < (filteredEvents.length - 1)) {
const nextEvent = filteredEvents[index + 1];
if (nextEvent.getContent().msgtype === "m.audio") {
// Yes, audio event!
this.$audioPlayer.play(nextEvent, this.timelineSet);
}
}
}
}
2020-11-09 10:26:56 +01:00
},
};
</script>
<style lang="scss">
@import "@/assets/css/chat.scss";
2022-05-17 15:16:53 +00:00
</style>