-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathchat-input.ts
More file actions
611 lines (534 loc) · 18.6 KB
/
Copy pathchat-input.ts
File metadata and controls
611 lines (534 loc) · 18.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
import { ContextConsumer, consume } from '@lit/context';
import { html, LitElement, nothing, type PropertyValues } from 'lit';
import { query, state } from 'lit/decorators.js';
import { cache } from 'lit/directives/cache.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { until } from 'lit/directives/until.js';
import { addThemingController } from '../../theming/theming-controller.js';
import IgcIconButtonComponent from '../button/icon-button.js';
import IgcChipComponent from '../chip/chip.js';
import { chatContext, chatUserInputContext } from '../common/context.js';
import { addAdoptedStylesController } from '../common/controllers/adopt-styles.js';
import { enterKey, tabKey } from '../common/controllers/key-bindings.js';
import { registerComponent } from '../common/definitions/register.js';
import { partMap } from '../common/part-map.js';
import { bindIf, hasFiles, isEmpty, trimmedHtml } from '../common/util.js';
import IgcIconComponent from '../icon/icon.js';
import IgcTextareaComponent from '../textarea/textarea.js';
import type { ChatState } from './chat-state.js';
import type { ISttClient } from './extras/stt-client-base.js';
import { WebSpeechSttClient } from './extras/stt-client-webspeech.js';
import { styles } from './themes/input.base.css.js';
import { all } from './themes/input.js';
import { styles as shared } from './themes/shared/input/input.common.css.js';
import type {
ChatInputRenderContext,
ChatRenderContext,
ChatTemplateRenderer,
IgcChatMessageAttachment,
} from './types.js';
import {
type ChatAcceptedFileTypes,
getChatAcceptedFiles,
getIconName,
} from './utils.js';
type DefaultInputRenderers = {
input: ChatTemplateRenderer<ChatInputRenderContext>;
inputActions: ChatTemplateRenderer<ChatRenderContext>;
inputActionsEnd: ChatTemplateRenderer<ChatRenderContext>;
inputActionsStart: ChatTemplateRenderer<ChatRenderContext>;
inputAttachments: ChatTemplateRenderer<ChatInputRenderContext>;
fileUploadButton: ChatTemplateRenderer<ChatRenderContext>;
speechToTextButton: ChatTemplateRenderer<ChatRenderContext>;
sendButton: ChatTemplateRenderer<ChatRenderContext>;
};
/* blazorSuppress */
/**
* A web component that provides the input area for the `igc-chat` interface.
*
* It supports:
* - Text input with automatic resizing
* - Sending messages on Enter key (with Shift+Enter for newlines)
* - File attachments via file picker or drag-and-drop
* - Customizable templates for send button, attachments, and text input
* - Emits various chat-related events (typing, input focus/blur, attachment drop, etc.)
*
* @element igc-chat-input
*
* @slot - Default unnamed slot for rendering inside the component
* @fires igcTypingChange - Fired when the user starts/stops typing
* @fires igcInputFocus - Fired when the input area receives focus
* @fires igcInputBlur - Fired when the input area loses focus
* @fires igcAttachmentDrag - Fired when dragging a file over the input
* @fires igcAttachmentDrop - Fired when a file is dropped into the input
* @fires igcChange - Fired when file input changes (delegated from `<igc-file-input>`)
*
* @csspart input-container - Container for the input section
* @csspart input-wrapper - Wrapper around the text input
* @csspart text-input - The `<igc-textarea>` component
* @csspart actions-container - Container for file upload/send buttons
* @csspart send-button - The send icon button
* @csspart attachments - Container for rendering attachments
* @csspart attachment-wrapper - Wrapper for individual attachment
* @csspart attachment-name - Display name of an attachment
*/
export default class IgcChatInputComponent extends LitElement {
public static readonly tagName = 'igc-chat-input';
public static override styles = [styles, shared];
/* blazorSuppress */
public static register(): void {
registerComponent(
IgcChatInputComponent,
IgcTextareaComponent,
IgcIconButtonComponent,
IgcChipComponent,
IgcIconComponent
);
}
private readonly _defaults: Readonly<DefaultInputRenderers> = Object.freeze({
fileUploadButton: () => this._renderFileUploadButton(),
speechToTextButton: () => this._renderSpeechToTextButton(),
input: () => this._renderTextArea(),
inputActions: () => this._renderActionsArea(),
inputActionsEnd: () => nothing,
inputActionsStart: () => nothing,
inputAttachments: (ctx) => this._renderAttachmentsArea(ctx.attachments),
sendButton: () => this._renderSendButton(),
});
private _userIsTyping = false;
private _userLastTypeTime = Date.now();
private _typingTimeout = 0;
private readonly _adoptedStyles = addAdoptedStylesController(this);
private readonly _stateChanged = () => {
this._shouldAdoptRootStyles = Boolean(this._state.options?.adoptRootStyles);
};
private readonly _stateConsumer = new ContextConsumer(this, {
context: chatContext,
callback: this._stateChanged,
subscribe: true,
});
@consume({ context: chatUserInputContext, subscribe: true })
private readonly _userInputState!: ChatState;
@query(IgcTextareaComponent.tagName)
private readonly _textInputElement?: IgcTextareaComponent;
@query('#input_attachments')
protected readonly _fileInput?: HTMLInputElement;
@state()
private _parts = { 'input-container': true, dragging: false };
@state()
private _shouldAdoptRootStyles = false;
private get _state(): ChatState {
return this._stateConsumer.value!;
}
private get _acceptedTypes(): ChatAcceptedFileTypes | null {
return this._state.acceptedFileTypes;
}
private _sttClient?: ISttClient;
@state()
private isRecording = false;
@state()
private isStopInProgress = false;
onPulseSignal = () => {
const el = this.renderRoot.querySelector<HTMLElement>(
'igc-icon-button[part="speech-to-text"]'
);
if (!el) return;
el.classList.add('pulsate');
el.addEventListener('animationend', () => el.classList.remove('pulsate'), {
once: true,
});
};
onStartCountdown = (ms: number | null) => {
if (ms) {
const circle = this.renderRoot.querySelector<SVGCircleElement>(
'svg.countdown-ring .ring-progress'
);
if (!circle) return;
circle.style.transition = 'none';
circle.style.strokeDashoffset = '100';
void circle.getBoundingClientRect(); // reflow
circle.style.transition = `stroke-dashoffset ${ms}ms linear`;
circle.style.strokeDashoffset = '0';
} else {
const circle = this.renderRoot.querySelector<SVGCircleElement>(
'svg.countdown-ring .ring-progress'
);
if (circle) {
circle.style.transition = 'none';
circle.style.strokeDashoffset = '100';
}
}
};
onStopInProgress = () => {
this.isStopInProgress = true;
};
onTranscript = (text: string) => {
this._state.inputValue = text;
};
onFinishedTranscribing = (finished: 'auto' | 'manual') => {
this.isStopInProgress = false;
this.isRecording = false;
if (finished === 'auto') {
this._sendMessage();
}
};
private async _toggleMic(): Promise<void> {
if (!this.isRecording) {
if (this._state.options?.speechToText?.serviceProvider === 'webspeech') {
this._sttClient = new WebSpeechSttClient(
this.onPulseSignal,
this.onStartCountdown,
this.onTranscript,
this.onStopInProgress,
this.onFinishedTranscribing
);
} else if (
this._state.options?.speechToText?.serviceProvider === 'backend' &&
this._state.options?.speechToText?.serviceUri
) {
const { BackendSttClient } =
await import('./extras/stt-client-backend.js');
this._sttClient = new BackendSttClient(
this._state.options?.speechToText?.serviceUri ?? undefined,
this.onPulseSignal,
this.onStartCountdown,
this.onTranscript,
this.onStopInProgress,
this.onFinishedTranscribing
);
} else {
// console.error('No STT service configured');
}
if (!this._sttClient) {
return;
}
try {
await this._sttClient.start(this._state.options?.speechToText?.lang);
this.isRecording = true;
this.isStopInProgress = false;
} catch {
this._sttClient = undefined;
this.isRecording = false;
this.isStopInProgress = false;
}
} else {
this._sttClient?.stop();
}
}
constructor() {
super();
addThemingController(this, all, { themeChange: this._adoptPageStyles });
}
protected override update(props: PropertyValues): void {
if (props.has('_shouldAdoptRootStyles')) {
this._adoptedStyles.shouldAdoptStyles(this._shouldAdoptRootStyles);
}
super.update(props);
}
/** @internal */
public focusInput(): void {
this._textInputElement?.focus();
}
private _adoptPageStyles(): void {
this._adoptedStyles.invalidateCache(this.ownerDocument);
this._adoptedStyles.shouldAdoptStyles(this._shouldAdoptRootStyles);
}
private _getRenderer<U extends keyof DefaultInputRenderers>(
name: U
): DefaultInputRenderers[U] {
return this._state.options?.renderers
? ((this._state.options.renderers[name] ??
this._defaults[name]) as DefaultInputRenderers[U])
: this._defaults[name];
}
private async _sendMessage(): Promise<void> {
if (
!this._userInputState.hasInputValue &&
!this._userInputState.hasInputAttachments
) {
return;
}
this._userInputState.addMessageWithEvent({
text: this._userInputState.inputValue,
attachments: this._userInputState.inputAttachments,
});
this.style.height = 'auto';
await this._userInputState.host.updateComplete;
this.focusInput();
}
private _setTypingStateAndEmit(state: boolean): void {
this._userIsTyping = state;
this._userInputState.emitUserTypingState(state);
}
private _handleAttachmentRemoved(attachment: IgcChatMessageAttachment): void {
const current = this._userInputState.inputAttachments;
if (this._state.emitAttachmentRemoved(attachment)) {
this._state.inputAttachments = current.toSpliced(
current.indexOf(attachment),
1
);
}
}
private _handleKeydown(event: KeyboardEvent): void {
this._userLastTypeTime = Date.now();
const isEnterKey = event.key.toLowerCase() === enterKey.toLowerCase();
const isTab = event.key.toLocaleLowerCase() === tabKey.toLowerCase();
if (isTab && !this._userIsTyping) {
return;
}
if (isEnterKey && !event.shiftKey) {
event.preventDefault();
this._sendMessage();
if (this._userIsTyping) {
clearTimeout(this._typingTimeout);
this._setTypingStateAndEmit(false);
}
return;
}
clearTimeout(this._typingTimeout);
const delay = this._state.stopTypingDelay;
if (!this._userIsTyping) {
this._setTypingStateAndEmit(true);
}
this._typingTimeout = setTimeout(() => {
if (this._userIsTyping && this._userLastTypeTime + delay <= Date.now()) {
this._setTypingStateAndEmit(false);
}
}, delay);
}
private _handleFileInputClick(): void {
this._fileInput?.showPicker();
}
private _handleFocusState(event: FocusEvent): void {
this._state.emitEvent(
event.type === 'focus' ? 'igcInputFocus' : 'igcInputBlur'
);
}
private _handleDragEnter(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
const validFiles = getChatAcceptedFiles(event, this._acceptedTypes);
this._parts = { 'input-container': true, dragging: !isEmpty(validFiles) };
this._state.emitEvent('igcAttachmentDrag');
}
private _handleDragOver(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
}
private _handleDragLeave(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
// Check if we're actually leaving the container
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
const x = event.clientX;
const y = event.clientY;
if (
x <= rect.left ||
x >= rect.right ||
y <= rect.top ||
y >= rect.bottom
) {
this._parts = { 'input-container': true, dragging: false };
}
}
private _handleDrop(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
this._parts = { 'input-container': true, dragging: false };
const validFiles = getChatAcceptedFiles(event, this._acceptedTypes);
this._state.emitEvent('igcAttachmentDrop');
this._state.attachFilesWithEvent(validFiles);
this.requestUpdate();
}
private _handleInput({ detail }: CustomEvent<string>): void {
this._state.inputValue = detail;
this._state.emitEvent('igcInputChange', { detail: { value: detail } });
}
private _handleFileUpload(event: Event): void {
const input = event.target as HTMLInputElement;
if (hasFiles(input)) {
this._state.attachFilesWithEvent(Array.from(input.files!));
}
}
/**
* Default attachments area template used when no custom template is provided.
* Renders the list of input attachments as chips.
* @returns TemplateResult containing the attachments area
*/
private _renderAttachmentsArea(attachments: IgcChatMessageAttachment[]) {
return html`${attachments?.map(
(attachment) => html`
<div part="attachment-wrapper" role="listitem">
<igc-chip
removable
@igcRemove=${() => this._handleAttachmentRemoved(attachment)}
>
<igc-icon
part="attachment-icon"
slot="prefix"
name=${getIconName(attachment.file?.type ?? attachment.type)}
></igc-icon>
<span part="attachment-name">${attachment.name}</span>
</igc-chip>
</div>
`
)} `;
}
/**
* Default text area template used when no custom template is provided.
* Renders a text area for user input.
* @returns TemplateResult containing the text area
*/
private _renderTextArea() {
return html`
<igc-textarea
part="text-input"
aria-label="Chat text input"
placeholder=${ifDefined(
this.isRecording
? (this._state.options?.speakPlaceholder ??
this._state.options?.inputPlaceholder)
: this._state.options?.inputPlaceholder
)}
resize="auto"
rows="1"
.value=${this._userInputState?.inputValue}
@igcInput=${this._handleInput}
@keydown=${this._handleKeydown}
@focus=${this._handleFocusState}
@blur=${this._handleFocusState}
></igc-textarea>
`;
}
private _renderFileUploadButton() {
const accepted = this._state.options?.acceptedFiles;
const attachmentsDisabled = this._state.options?.disableInputAttachments;
return html`${cache(
attachmentsDisabled
? nothing
: html`
<label for="input_attachments" part="file-upload">
<igc-icon-button
aria-label="Attach files"
variant="flat"
name="attach_file"
@click=${this._handleFileInputClick}
></igc-icon-button>
<input
type="file"
id="input_attachments"
tabindex="-1"
name="input_attachments"
aria-label="Upload button"
multiple
accept=${bindIf(accepted, accepted)}
@change=${this._handleFileUpload}
/>
</label>
`
)}`;
}
private _renderSpeechToTextButton() {
const sttEnabled = this._state.options?.speechToText?.enable;
return html`${cache(
sttEnabled
? html` <div class="stop-btn-wrapper">
<igc-icon-button
part="speech-to-text"
aria-label="Speech to text"
variant="flat"
@click=${this._toggleMic}
?disabled=${this.isStopInProgress}
>
${this.isRecording ? '🛑' : '🎤'}
</igc-icon-button>
${this.isRecording && !this.isStopInProgress
? html`
<svg
class="countdown-ring"
viewBox="0 0 36 36"
aria-hidden="true"
>
<circle class="ring-bg" cx="18" cy="18" r="14"></circle>
<circle
class="ring-progress"
cx="18"
cy="18"
r="14"
></circle>
</svg>
`
: nothing}
</div>`
: nothing
)}`;
}
private _renderSendButton() {
const enabled =
this._state.hasInputValue || this._state.hasInputAttachments;
return html`
<igc-icon-button
aria-label="Send message"
name="send_message"
variant="contained"
part="send-button"
?disabled=${!enabled}
@click=${this._sendMessage}
></igc-icon-button>
`;
}
private _renderActionsArea() {
const ctx: ChatRenderContext = { instance: this._state.host };
return trimmedHtml`
<div part="file-upload-container">
${this._getRenderer('fileUploadButton')(ctx)}
</div>
<div part="speech-to-text-container">
${this._getRenderer('speechToTextButton')(ctx)}
</div>
<div part="input-actions-start">
${this._getRenderer('inputActionsStart')(ctx)}
</div>
<div part="send-button-container">${this._getRenderer('sendButton')(ctx)}</div>
<div part="input-actions-end">
${this._getRenderer('inputActionsEnd')(ctx)}
</div>
`;
}
protected override render() {
const ctx: ChatRenderContext = { instance: this._state.host };
const inputCtx: ChatInputRenderContext = {
...ctx,
attachments: this._state.inputAttachments,
value: this._state.inputValue,
};
return html`
<div
part=${partMap(this._parts)}
@dragenter=${this._handleDragEnter}
@dragover=${this._handleDragOver}
@dragleave=${this._handleDragLeave}
@drop=${this._handleDrop}
>
${this._state.hasInputAttachments
? html`
<div part="attachments" role="list" aria-label="Attachments">
${until(this._getRenderer('inputAttachments')(inputCtx))}
</div>
`
: nothing}
<div part="input-wrapper">
${until(this._getRenderer('input')(inputCtx))}
</div>
<div part="actions-container">
${until(this._getRenderer('inputActions')(ctx))}
</div>
</div>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'igc-chat-input': IgcChatInputComponent;
}
}