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

Features/refine chat window #90

Merged
merged 4 commits into from
Mar 20, 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
122 changes: 122 additions & 0 deletions src/lib/common/ChatTextArea.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<script>
import { clickOutside } from "$lib/helpers/directives";
import { EditorType } from "$lib/helpers/enums";
import { getAddressOptions } from "$lib/services/conversation-service";
import _ from "lodash";

/** @type {string} */
export let className = '';

/** @type {string} */
export let text;

/** @type {number} */
export let rows = 1;

/** @type {number} */
export let maxLength = 500;

/** @type {number} */
export let optionLimit = 5;

/** @type {boolean} */
export let disabled = false;

/** @type {string} */
export let placeholder = "Enter Message...";

/** @type {string} */
export let editor;

/** @type {(args0: any) => void} */
export let onKeyDown = () => {}

/** @type {number} */
let timeout;

/** @type {string[]} */
let options = [];

/** @type {HTMLTextAreaElement} */
let textArea;

const delay = 500;


/** @param {any} e */
function handleClickOutside(e) {
e.preventDefault();
options = [];
}

/** @param {any} e */
function handleKeyDown(e) {
onKeyDown && onKeyDown(e);
}

function handleFocus() {
options = [];
}

/** @param {string} option */
function handleOptionClick(option) {
options = [];
text = option;
if (textArea) {
textArea.focus();
}
}

/** @param {any} e */
function handleTextChange(e) {
const value = e.target.value;
if (!!!_.trim(value)) {
return;
}

clearTimeout(timeout);
options = [];
if (editor === EditorType.Address) {
timeout = setTimeout(() => {
// @ts-ignore
getAddressOptions(value).then(res => {
// @ts-ignore
const data = res?.results?.map(x => x.formatted_address) || [];
options = data.filter(Boolean).slice(0, optionLimit);
}).catch(err => {
options = [];
});
}, delay);
}
}
</script>


<div use:clickOutside on:click_outside={handleClickOutside}>
{#if options?.length > 0}
<ul class="dropdown-menu chat-option-list">
{#each options as option, idx (idx)}
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<li
class="chat-option-item"
on:keydown={() => {}}
on:click={() => handleOptionClick(option)}
>
{option}
</li>
{/each}
</ul>
{/if}
<textarea
class={`form-control ${className}`}
rows={rows}
maxlength={maxLength}
disabled={disabled}
placeholder={placeholder}
bind:this={textArea}
bind:value={text}
on:input={e => handleTextChange(e)}
on:keydown={e => handleKeyDown(e)}
on:focus={() => handleFocus()}
/>
</div>
17 changes: 17 additions & 0 deletions src/lib/helpers/directives.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** @param {any} node */
export function clickOutside(node) {

const handleClick = (/** @type {any} */ event) => {
if (!!node && !node.contains(event.target)) {
node.dispatchEvent(new CustomEvent('click_outside', node));
}
}

document.addEventListener('click', handleClick, true);

return {
destroy() {
document.removeEventListener('click', handleClick, true);
}
};
}
13 changes: 12 additions & 1 deletion src/lib/helpers/enums.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,15 @@ const contentLogSource = {
AgentResponse: "agent response",
HardRule: "hard rule"
};
export const ContentLogSource = Object.freeze(contentLogSource);
export const ContentLogSource = Object.freeze(contentLogSource);

const editorType = {
None: "none",
Text: "text",
Address: "address",
Phone: "phone",
DateTimePicker: "datetime-picker",
DateTimeRangePicker: 'datetime-range-picker',
Email: 'email'
};
export const EditorType = Object.freeze(editorType);
8 changes: 7 additions & 1 deletion src/lib/helpers/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,16 @@ axios.interceptors.response.use(

/** @param {import('axios').InternalAxiosRequestConfig<any>} config */
function skipLoader(config) {
const regex = new RegExp('http(s*)://(.*?)/conversation/(.*?)/(.*?)', 'g');
let regex = new RegExp('http(s*)://(.*?)/conversation/(.*?)/(.*?)', 'g');
if (config.method === 'post' && !!config.data && regex.test(config.url || '')) {
return true;
}

regex = new RegExp('http(s*)://(.*?)/address/options(.*?)', 'g');
if (config.method === 'get' && regex.test(config.url || '')) {
return true;
}

return false;
}

Expand Down
2 changes: 2 additions & 0 deletions src/lib/helpers/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ IRichContent.prototype.text;
* @typedef {Object} RichContent
* @property {string} messaging_type
* @property {boolean} fill_postback
* @property {string} editor
* @property {string?} [editor_attributes]
* @property {IRichContent} message
*/

Expand Down
1 change: 1 addition & 0 deletions src/lib/scss/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ File: Main Css File
@import "custom/components/demos";
@import "custom/components/print";
@import "custom/components/loader";
@import "custom/components/chat";

// Plugins
@import "custom/plugins/custom-scrollbar";
Expand Down
23 changes: 23 additions & 0 deletions src/lib/scss/custom/components/_chat.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
.chat-option-list {
display: block;
position: absolute;
bottom: 100%;
max-width: 100%;
z-index: 10;
padding: 3px 0px;
font-size: 0.8rem;
border-radius: 5px;
max-height: 25em;
overflow-y: auto;
scrollbar-width: none;

.chat-option-item {
padding: 5px 15px;
cursor: pointer;
}

.chat-option-item:hover {
background-color: var(--bs-primary);
color: white;
}
}
3 changes: 3 additions & 0 deletions src/lib/services/api-endpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,8 @@ export const endpoints = {

// chathub
chatHubUrl: `${host}/chatHub`,

// Google geocode api
addressUrl: `${host}/address/options`
}

15 changes: 15 additions & 0 deletions src/lib/services/conversation-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,19 @@ export async function deleteConversationMessage(conversationId, messageId) {
});
const response = await axios.delete(url);
return response.data;
}


/**
* delete a message in conversation
* @param {string} text The user input
*/
export async function getAddressOptions(text) {
const url = endpoints.addressUrl;
const response = await axios.get(url, {
params: {
address: text
}
});
return response.data;
}
23 changes: 14 additions & 9 deletions src/routes/chat/[agentId]/[conversationId]/chat-box.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import HeadTitle from '$lib/common/HeadTitle.svelte';
import LoadingDots from '$lib/common/LoadingDots.svelte';
import StateModal from '$lib/common/StateModal.svelte';
import ChatTextArea from '$lib/common/ChatTextArea.svelte';
import { utcToLocal } from '$lib/helpers/datetime';
import { replaceNewLine } from '$lib/helpers/http';
import { SenderAction, UserRole } from '$lib/helpers/enums';
Expand All @@ -35,7 +36,6 @@
import "sweetalert2/src/sweetalert2.scss";
import moment from 'moment';


const options = {
scrollbars: {
visibility: 'auto',
Expand Down Expand Up @@ -69,7 +69,9 @@
// @ts-ignore
let scrollbar;
let microphoneIcon = "microphone-off";
let lastBotMsgId = '';

/** @type {import('$types').ChatResponseModel?} */
let lastBotMsg;

/** @type {import('$types').ChatResponseModel[]} */
let dialogs = [];
Expand Down Expand Up @@ -189,16 +191,13 @@
/** @param {import('$types').ChatResponseModel[]} dialogs */
function findLastBotMessage(dialogs) {
const lastMsg = dialogs.slice(-1)[0];
if (lastMsg?.sender?.role === UserRole.Assistant) {
return lastMsg?.message_id || '';
}
return '';
return lastMsg?.sender?.role === UserRole.Assistant ? lastMsg : null;
}

async function refresh() {
// trigger UI render
dialogs = dialogs?.map(item => { return { ...item }; }) || [];
lastBotMsgId = findLastBotMessage(dialogs);
lastBotMsg = findLastBotMessage(dialogs);
groupedDialogs = groupDialogs(dialogs);
await tick();

Expand Down Expand Up @@ -824,7 +823,7 @@
<div class="msg-container">
<RichContent
message={message}
displayExtraElements={message.message_id === lastBotMsgId && !isSendingMsg && !isThinking}
displayExtraElements={message.message_id === lastBotMsg?.message_id && !isSendingMsg && !isThinking}
disableOption={isSendingMsg || isThinking}
onConfirm={confirmSelectedOption}
/>
Expand Down Expand Up @@ -868,7 +867,13 @@
</div>
<div class="col">
<div class="position-relative">
<textarea rows={1} maxlength={500} class="form-control chat-input" bind:value={text} on:keydown={e => onSendMessage(e)} disabled={isSendingMsg || isThinking} placeholder="Enter Message..." />
<ChatTextArea
className={'chat-input'}
bind:text={text}
disabled={isSendingMsg || isThinking}
editor={lastBotMsg?.rich_content?.editor || ''}
onKeyDown={e => onSendMessage(e)}
/>
<div class="chat-input-links" id="tooltip-container">
<ul class="list-inline mb-0">
<li class="list-inline-item">
Expand Down
8 changes: 6 additions & 2 deletions src/routes/page/agent/[agentId]/agent-overview.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,12 @@
<th>Profiles</th>
<td>
{#each agent.profiles as profile}
<input class="form-control" type="text" value={profile} />
<a href={null} class="btn btn-danger">Delete</a>
<div style="display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 5px;">
<input class="form-control" style="flex: 0.9;" type="text" value={profile} />
<div style="flex: 0.1; display: flex; align-items: center; cursor: pointer; font-size: 18px; color: red;">
<i class="bx bxs-no-entry " />
</div>
</div>
{/each}
</td>
</tr>
Expand Down
Loading