-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChatAssistant.java
More file actions
348 lines (319 loc) · 11.6 KB
/
ChatAssistant.java
File metadata and controls
348 lines (319 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*-
* #%L
* Chat Assistant Add-on
* %%
* Copyright (C) 2023 - 2024 Flowing Code
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.flowingcode.vaadin.addons.chatassistant;
import com.flowingcode.vaadin.addons.chatassistant.model.Message;
import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.messages.MessageInput;
import com.vaadin.flow.component.messages.MessageInput.SubmitEvent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.virtuallist.VirtualList;
import com.vaadin.flow.data.provider.DataProvider;
import com.vaadin.flow.data.renderer.ComponentRenderer;
import com.vaadin.flow.dom.DomEvent;
import com.vaadin.flow.shared.Registration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Component that allows to create a floating chat button that will open a chat window that can be
* used to provide a chat assistant feature.
*
* @author mmlopez
*/
@SuppressWarnings("serial")
@NpmPackage(value = "wc-chatbot", version = "0.2.0")
@JsModule("wc-chatbot/dist/wc-chatbot.js")
@CssImport("./styles/chat-assistant-styles.css")
@Tag("chat-bot")
public class ChatAssistant extends Div {
private static final String CHAT_HEADER_CLASS_NAME = "chat-header";
private Component headerComponent;
private Component footerComponent;
private VerticalLayout footerContainer;
private VirtualList<Message> content = new VirtualList<>();
private List<Message> messages;
private MessageInput messageInput;
private Span whoIsTyping;
private boolean minimized = false;
private Registration defaultSubmitListenerRegistration;
/**
* Default constructor. Creates a ChatAssistant with no messages.
*/
public ChatAssistant() {
this(new ArrayList<>(), false);
}
/**
* Creates a ChatAssistant with no messages.
*
* @param markdownEnabled flag to enable or disable markdown support
*/
public ChatAssistant(boolean markdownEnabled) {
this(new ArrayList<>(), markdownEnabled);
}
/**
* Creates a ChatAssistant with the given list of messages.
*
* @param messages the list of messages
* @param markdownEnabled flag to enable or disable markdown support
*/
public ChatAssistant(List<Message> messages, boolean markdownEnabled) {
this.messages = messages;
content.getElement().setAttribute("slot", "content");
content.setItems(messages);
content.setRenderer(new ComponentRenderer<ChatMessage, Message>(
message -> new ChatMessage(message, markdownEnabled), (component, message) -> {
((ChatMessage) component).setMessage(message);
return component;
}));
this.add(content);
messageInput = new MessageInput();
messageInput.setSizeFull();
defaultSubmitListenerRegistration = messageInput
.addSubmitListener(se -> this.sendMessage(Message.builder().messageTime(LocalDateTime.now())
.name("User").content(se.getValue()).build()));
whoIsTyping = new Span();
whoIsTyping.setClassName("chat-assistant-who-is-typing");
whoIsTyping.setVisible(false);
footerContainer = new VerticalLayout(whoIsTyping);
footerContainer.setSpacing(false);
footerContainer.setMargin(false);
footerContainer.setPadding(false);
footerContainer.getElement().setAttribute("slot", "footer");
add(footerContainer);
this.setFooterComponent(messageInput);
this.getElement().addEventListener("bot-button-clicked", this::handleClick).addEventData("event.detail");
Icon minimize = VaadinIcon.CHEVRON_DOWN_SMALL.create();
minimize.addClickListener(ev -> this.setMinimized(!minimized));
Span title = new Span("Chat Assistant");
title.setWidthFull();
HorizontalLayout headerBar = new HorizontalLayout(title, minimize);
headerBar.setWidthFull();
this.setHeaderComponent(headerBar);
}
private void handleClick(DomEvent event) {
minimized = event.getEventData().getObject("event.detail").getBoolean("minimized");
if (!minimized) {
refreshContent();
}
}
/**
* Sets the data provider of the internal VirtualList.
*
* @param dataProvider the data provider to be used
*/
public void setDataProvider(DataProvider<Message, ?> dataProvider) {
content.setDataProvider(dataProvider);
}
/**
* Uses the provided string as the text shown over the message input to indicate that someone is typing.
*
* @param whoIsTyping string to be shown as an indication of someone typing
*/
public void setWhoIsTyping(String whoIsTyping) {
this.whoIsTyping.setText(whoIsTyping);
this.whoIsTyping.setVisible(true);
}
/**
* Returns the current text shown over the message input to indicate that someone is typing.
*
* @return the current text or null if not configured
*/
public String getWhoIsTyping() {
return whoIsTyping.getText();
}
/**
* Clears the text shown over the message input to indicate that someone is typing.
*/
public void clearWhoIsTyping() {
this.whoIsTyping.setText(null);
this.whoIsTyping.setVisible(false);
}
/**
* Sets the SubmitListener that will be notified when the user submits a message on the underlying messageInput.
*
* @param listener the listener that will be notified when the SubmitEvent is fired
* @return registration for removal of the listener
*/
public Registration setSubmitListener(ComponentEventListener<SubmitEvent> listener) {
defaultSubmitListenerRegistration.remove();
return messageInput.addSubmitListener(listener);
}
protected void onAttach(AttachEvent attachEvent) {
if (!minimized) {
getElement().executeJs("setTimeout(() => this.toggle())");
this.getElement().executeJs("return;").then((ev) -> {
refreshContent();
});
}
this.getElement().executeJs("setTimeout(() => this.shadowRoot.querySelector($0).innerHTML = $1)",
".chatbot-body", "<slot name='content'></slot>");
this.getElement().executeJs(
"this.shadowRoot.querySelector($0).style.setProperty('padding', '0px');",
".chatbot-body");
this.getElement().executeJs("""
setTimeout(() => {
let chatbot = this;
let chatBotContainer = this.shadowRoot.querySelector($1);
this.shadowRoot.querySelector($0).addEventListener("click", function() {
let buttonClickedEvent = new CustomEvent("bot-button-clicked", {
detail: {
minimized: chatBotContainer.classList.contains('animation-scale-out'),
},
});
chatbot.dispatchEvent(buttonClickedEvent);
});
})
""", ".bot-button", ".chatbot-container");
if (footerComponent!=null) {
this.setFooterComponent(footerComponent);
}
if (headerComponent!=null) {
this.setHeaderComponent(headerComponent);
}
}
private void refreshContent() {
this.content.getDataProvider().refreshAll();
this.content.getElement().executeJs("this.requestContentUpdate();");
this.content.scrollToEnd();
}
/**
* Sends a message programmatically to the component. Should not be used when a custom
* DataProvider is used. Instead just refresh the custom DataProvider.
*
* @param message the message to be sent programmatically
*/
public void sendMessage(Message message) {
messages.add(message);
content.getDataProvider().refreshAll();
content.scrollToEnd();
}
/**
* Updates a previously entered message.
*
* @param message the message to be updated
*/
public void updateMessage(Message message) {
this.content.getDataProvider().refreshItem(message);
}
/**
* Shows or hides chat window.
*
* @param minimized true for hiding the chat window and false for displaying it
*/
public void setMinimized(boolean minimized) {
if (!minimized && this.minimized) {
getElement().executeJs("setTimeout(() => {this.toggle();})");
this.refreshContent();
} else if (minimized && !this.minimized) {
getElement().executeJs("setTimeout(() => {this.toggle();})");
}
this.minimized = minimized;
}
/**
* Returns the visibility of the chat window.
*
* @return true if the chat window is minimized false otherwise
*/
public boolean isMinimized() {
return minimized;
}
/**
* Allows changing the header of the chat window.
*
* @param component to be used as a replacement for the header
*/
public void setHeaderComponent(Component component) {
if (headerComponent!=null) {
this.remove(headerComponent);
}
component.addClassName(CHAT_HEADER_CLASS_NAME);
this.headerComponent = component;
this.getElement().executeJs("setTimeout(() => this.shadowRoot.querySelector($0).innerHTML = $1)", ".chatbot-header", "<slot name='header'></slot>");
component.getElement().setAttribute("slot", "header");
this.add(headerComponent);
}
/**
* Returns the current component configured as the header of the chat window.
*
* @return component used as the header of the chat window
*/
public Component getHeaderComponent() {
return headerComponent;
}
/**
* Allows changing the footer of the chat window.
*
* @param component to be used as a replacement for the footer, it cannot be null
*/
public void setFooterComponent(Component component) {
Objects.requireNonNull(component, "Component cannot not be null");
if (footerComponent!=null) {
this.footerContainer.remove(footerComponent);
}
this.getElement().executeJs("setTimeout(() => this.shadowRoot.querySelector($0).innerHTML = $1)", ".chat-footer", "<slot name='footer'></slot>");
this.footerComponent = component;
footerContainer.add(footerComponent);
}
/**
* Returns the current component configured as the footer of the chat window.
*
* @return component used as the footer of the chat window
*/
public Component getFooterComponent() {
return footerComponent;
}
/**
* Scrolls to the given position. Scrolls so that the element is shown at
* the start of the visible area whenever possible.
* <p>
* If the index parameter exceeds current item set size the grid will scroll
* to the end.
*
* @param position
* zero based index of the item to scroll to in the current view.
*/
public void scrollToIndex(int position) {
this.content.scrollToIndex(position);
}
/**
* Scrolls to the first element.
*/
public void scrollToStart() {
this.content.scrollToStart();
}
/**
* Scrolls to the last element of the list.
*/
public void scrollToEnd() {
this.content.scrollToEnd();
}
}