Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add like message #230

Merged
merged 1 commit into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions src/lib/common/LiveChatEntry.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,20 @@

onMount(async () => {
const agentSettings = await getSettingDetail("Agent");
chatUrl = `${PUBLIC_LIVECHAT_HOST}chat/${agentSettings.hostAgentId}?isFrame=true`;
chatUrl = `${PUBLIC_LIVECHAT_HOST}chat/${agentSettings.hostAgentId}`;
});

// Handle event from iframe
window.onmessage = async function(e) {
if (e.data.action == 'close') {
chatBotStore.set({
showChatBox: false
});
chatBotStore.set({ showChatBox: false });
} else if (e.data.action == 'open') {
chatBotStore.set({ showChatBox: true });
}
};

function openChatBox() {
chatBotStore.set({
showChatBox: true
});
chatBotStore.set({ showChatBox: true });
}
</script>

Expand All @@ -51,7 +49,6 @@
src={chatUrl}
width="0px"
height="0px"
class={`border border-2 rounded-3 m-3 float-end chat-iframe`}
title="live chat"
id={CHAT_FRAME_ID}
/>
Expand Down
3 changes: 2 additions & 1 deletion src/lib/common/ProfileDropdown.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { PUBLIC_SERVICE_URL } from '$env/static/public';
import { _ } from 'svelte-i18n';
import { buildUrl } from '$lib/helpers/utils/common';
import { ChatAction } from '$lib/helpers/enums';

/** @type {any} */
export let user;
Expand All @@ -19,7 +20,7 @@
const chatFrame = document.getElementById('chat-frame');
if (chatFrame) {
// @ts-ignore
chatFrame.contentWindow.postMessage({ action: "logout" }, "*");
chatFrame.contentWindow.postMessage({ action: ChatAction.Logout }, "*");
}

goto('login');
Expand Down
8 changes: 4 additions & 4 deletions src/lib/common/audio-player/AudioSpeaker.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,14 @@
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="{disableDefaultStyles ? '' : 'chat-speaker-container'} {containerClasses}"
class="{disableDefaultStyles ? '' : 'chat-speaker-container'} line-align-center {containerClasses}"
style={`${containerStyles}`}
>
<span style="display: inline-block;" on:click={() => speak()}>
<div on:click={() => speak()}>
{#if !speaking}
<i class="bx bx-volume-full" />
<i class="bx bx-volume-full clickable" />
{:else}
<Stretch unit='px' size='5' gap='5' color="var(--bs-primary)" />
{/if}
</span>
</div>
</div>
9 changes: 8 additions & 1 deletion src/lib/helpers/enums.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,11 @@ const knowledgeDocSource = {
User: 'user',
Web: 'web'
};
export const KnowledgeDocSource = Object.freeze(knowledgeDocSource);
export const KnowledgeDocSource = Object.freeze(knowledgeDocSource);

const chatAction = {
Logout: 'logout',
Chat: 'chat',
NewChat: 'new-chat'
};
export const ChatAction = Object.freeze(chatAction);
7 changes: 4 additions & 3 deletions src/lib/helpers/utils/chat.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/**
* @param {string} action
* @param {string} chatFrameId
* @param {string} text
* @param {string | null} text
* @param {import('$conversationTypes').MessageData | null} data
*/
export function sendToChatBot(chatFrameId, text, data = null) {
export function sendToChatBot(action, chatFrameId, text = null, data = null) {
const chatFrame = document.getElementById(chatFrameId);
const content = { action: "chat", text: text, data: data };
const content = { action: action, text: text, data: data };

if (chatFrame) {
// @ts-ignore
Expand Down
20 changes: 6 additions & 14 deletions src/routes/chat/[agentId]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,15 @@
}

conversationId = conversation.id;
let chatUrl = `chat/${agentId}/${conversationId}`;
let query = "";

const chatUrl = new URL(`chat/${agentId}/${conversationId}`, window.location.origin);

const searchParams = new URLSearchParams();
if (agentId === LERNER_ID) {
query += `mode=${TRAINING_MODE}`;
}

const isFrame = $page.url.searchParams.get('isFrame');
if (isFrame === 'true') {
query += "isFrame=true";
}

if (!!query) {
chatUrl = `${chatUrl}?${query}`;
searchParams.append('mode', TRAINING_MODE);
}

window.location.href = chatUrl;
chatUrl.search = searchParams?.toString();
window.location.href = chatUrl.toString();
});
</script>

Expand Down
110 changes: 91 additions & 19 deletions src/routes/chat/[agentId]/[conversationId]/chat-box.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
import { utcToLocal } from '$lib/helpers/datetime';
import { replaceNewLine } from '$lib/helpers/http';
import { isAudio, isExcel, isPdf } from '$lib/helpers/utils/file';
import { EditorType, FileSourceType, SenderAction, UserRole } from '$lib/helpers/enums';
import { ChatAction, EditorType, FileSourceType, SenderAction, UserRole } from '$lib/helpers/enums';
import RichContent from './rich-content/rich-content.svelte';
import RcMessage from "./rich-content/rc-message.svelte";
import RcDisclaimer from './rich-content/rc-disclaimer.svelte';
Expand All @@ -55,6 +55,7 @@
import ChatBigMessage from './chat-util/chat-big-message.svelte';
import PersistLog from './persist-log/persist-log.svelte';
import InstantLog from './instant-log/instant-log.svelte';
import Loader from '$lib/common/Loader.svelte';


const options = {
Expand Down Expand Up @@ -151,6 +152,7 @@
let disableAction = false;
let loadChatUtils = false;
let disableSpeech = false;
let isLoading = false;


$: {
Expand Down Expand Up @@ -192,19 +194,38 @@
refresh();
autoScrollLog = false;

window.addEventListener('message', e => {
if (e.data.action === 'logout') {
window.addEventListener('message', async e => {
if (e.data.action === ChatAction.Logout) {
resetLocalStorage(true);
return;
}

if (e.data.action === 'chat' && !isThinking && !isSendingMsg) {
sendChatMessage(e.data.text, e.data.data || null);
if (e.data.action === ChatAction.NewChat) {
const conv = await createNewConversation();
if (!!e.data.text && !isThinking && !isSendingMsg) {
isLoading = true;
sendChatMessage(e.data.text, e.data.data || null, conv.id).then(() => {
redirectToNewConversation(conv);
isLoading = false;
openFrame();
});
}
return;
}

if (e.data.action === ChatAction.Chat && !!e.data.text && !isThinking && !isSendingMsg) {
sendChatMessage(e.data.text, e.data.data || null).then(() => {
openFrame();
});
return;
}
});

// window.parent.postMessage({ event: "chat-box-mounted" }, "*");
});

function openFrame() {
window.parent.postMessage({ action: "open" }, "*");
}

function resizeChatWindow() {
isLite = Viewport.Width <= screenWidthThreshold;
if (!isLite) {
Expand All @@ -219,7 +240,7 @@
}

function initChatView() {
isFrame = $page.url.searchParams.get('isFrame') === 'true';
isFrame = window.location != window.parent.location;
mode = $page.url.searchParams.get('mode') || '';
// initial condition
isPersistLogClosed = false;
Expand Down Expand Up @@ -430,10 +451,22 @@
}

async function handleNewConversation() {
const conv = await createNewConversation();
redirectToNewConversation(conv);
}

async function createNewConversation() {
const conversation = await newConversation(params.agentId);
conversationStore.set(conversation);
const url = `chat/${params.agentId}/${conversation.id}`;
window.location.href = url;
return conversation;
}

/** @param {import('$conversationTypes').ConversationModel} conversation */
function redirectToNewConversation(conversation) {
const url = new URL(`chat/${params.agentId}/${conversation.id}`, window.location.origin);
const searchParams = $page.url.searchParams;
url.search = searchParams?.toString();
window.location.href = url.toString();
}

function handleSaveKnowledge() {
Expand All @@ -443,8 +476,9 @@
/**
* @param {string} msgText
* @param {import('$conversationTypes').MessageData?} data
* @param {string?} conversationId
*/
function sendChatMessage(msgText, data = null) {
function sendChatMessage(msgText, data = null, conversationId = null) {
isSendingMsg = true;
autoScrollLog = true;
clearInstantLogs();
Expand All @@ -471,7 +505,7 @@
if (files?.length > 0 && !!!messageData.inputMessageId) {
const filePayload = buildFilePayload(files);
return new Promise((resolve, reject) => {
uploadConversationFiles(params.agentId, params.conversationId, files).then(resMessageId => {
uploadConversationFiles(params.agentId, conversationId || params.conversationId, files).then(resMessageId => {
messageData = { ...messageData, inputMessageId: resMessageId };
if (!!filePayload) {
messageData = {
Expand All @@ -484,7 +518,7 @@
};
}

sendMessageToHub(params.agentId, params.conversationId, msgText, messageData).then(res => {
sendMessageToHub(params.agentId, conversationId || params.conversationId, msgText, messageData).then(res => {
resolve(res);
}).catch(err => {
reject(err);
Expand All @@ -510,7 +544,7 @@
};
}

sendMessageToHub(params.agentId, params.conversationId, msgText, messageData).then(res => {
sendMessageToHub(params.agentId, conversationId || params.conversationId, msgText, messageData).then(res => {
resolve(res);
}).catch(err => {
reject(err);
Expand All @@ -520,7 +554,7 @@
});
});
} else {
sendMessageToHub(params.agentId, params.conversationId, msgText, messageData).then(res => {
sendMessageToHub(params.agentId, conversationId || params.conversationId, msgText, messageData).then(res => {
resolve(res);
}).catch(err => {
reject(err);
Expand Down Expand Up @@ -1003,11 +1037,34 @@
bigText = '';
sendChatMessage(text);
}

/**
* @param {any} e
* @param {any} message
*/
function likeMessage(e, message) {
e.preventDefault();

const text = 'I like this message.';
const data = {
postback: {
functionName: 'like_response',
payload: 'I really like this message!',
parentId: message?.id
},
states: []
};
sendChatMessage(text, data);
}
</script>


<svelte:window on:resize={() => resizeChatWindow()}/>

{#if isLoading}
<Loader size={35} />
{/if}

<DialogModal
title={'Edit message'}
size={'md'}
Expand Down Expand Up @@ -1217,10 +1274,25 @@
<div class="msg-container">
<RcMessage message={message} />
{#if message?.message_id === lastBotMsg?.message_id}
<AudioSpeaker
id={message?.message_id}
text={message?.rich_content?.message?.text || message?.text}
/>
<div style="display: flex; gap: 10px;">
<AudioSpeaker
id={message?.message_id}
text={message?.rich_content?.message?.text || message?.text}
/>
<div class="line-align-center" style="font-size: 17px;">
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
class="clickable"
style="height: 95%;"
on:click={e => likeMessage(e, message)}
>
<i
class="mdi mdi-thumb-up-outline text-primary"
/>
</div>
</div>
</div>
{/if}
{#if !!message.is_chat_message || !!message.has_message_files}
<MessageFileGallery
Expand Down
6 changes: 4 additions & 2 deletions src/routes/page/plugin/plugin-list.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
import { installPlugin, removePlugin } from '$lib/services/plugin-service';
import Swal from 'sweetalert2';
import { sendToChatBot } from '$lib/helpers/utils/chat';

import { CHAT_FRAME_ID } from '$lib/helpers/constants';
import { ChatAction } from '$lib/helpers/enums';

/** @type {import('$pluginTypes').PluginDefModel[]} */
export let plugins;
Expand Down Expand Up @@ -59,7 +59,9 @@
},
states: []
};
sendToChatBot(CHAT_FRAME_ID, text, data);
// ChatAction.Chat: send to current chat
// ChatAction.NewChat: init a new conversation, and then send the message
sendToChatBot(ChatAction.Chat, CHAT_FRAME_ID, text, data);
}
</script>

Expand Down
Loading