@widgetic/chat 0.1.16 → 0.1.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -0
- package/dist/components/ActionBar.svelte +56 -16
- package/dist/components/ActionBar.svelte.d.ts +7 -0
- package/dist/components/AttachmentDisplay.svelte +54 -26
- package/dist/components/Chat.svelte +184 -64
- package/dist/components/Chat.svelte.d.ts +51 -3
- package/dist/components/ChatHeader.svelte +21 -21
- package/dist/components/ChatInput.svelte +39 -18
- package/dist/components/ChatInput.svelte.d.ts +1 -0
- package/dist/components/ChatMessages.svelte +107 -40
- package/dist/components/ChatMessages.svelte.d.ts +12 -1
- package/dist/components/CodeBlock.svelte +14 -9
- package/dist/components/ContextPreview.svelte +8 -3
- package/dist/components/StatusIndicator.svelte +10 -5
- package/dist/components/SuggestionButtons.svelte +19 -64
- package/dist/i18n/index.d.ts +4 -0
- package/dist/i18n/index.js +4 -0
- package/dist/i18n/labels.d.ts +31 -0
- package/dist/i18n/labels.js +69 -0
- package/dist/i18n/language.d.ts +22 -0
- package/dist/i18n/language.js +31 -0
- package/dist/i18n/messages.d.ts +173 -0
- package/dist/i18n/messages.js +182 -0
- package/dist/i18n/suggestions.d.ts +5 -0
- package/dist/i18n/suggestions.js +66 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/types/message.d.ts +39 -0
- package/package.json +5 -3
|
@@ -1,21 +1,45 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { onMount, onDestroy, untrack } from 'svelte';
|
|
3
|
+
import type { Snippet } from 'svelte';
|
|
4
|
+
import { writable } from 'svelte/store';
|
|
5
|
+
import { shareTextDirection, type TextDirection } from '@widgetic/design-system/components/textDirection';
|
|
3
6
|
import { chatStore, getCurrentState, getCurrentMessages } from '../stores/chatStore.js';
|
|
4
7
|
import { createChatService } from '../services/chatService.js';
|
|
5
8
|
import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
|
|
6
9
|
import type { ChatConfig, ChatContext } from '../types/index.js';
|
|
7
|
-
import type { ClarificationSuggestion } from '../types/message.js';
|
|
10
|
+
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
8
11
|
import type { AttachmentInput } from '../types/attachment.js';
|
|
9
12
|
import ChatMessages from './ChatMessages.svelte';
|
|
10
13
|
import ChatInput from './ChatInput.svelte';
|
|
11
14
|
import ActionBar from './ActionBar.svelte';
|
|
12
15
|
import StatusIndicator from './StatusIndicator.svelte';
|
|
16
|
+
import { provideChatLanguage } from '../i18n/language.js';
|
|
17
|
+
import { actionFailureKey, contextTypeLabel } from '../i18n/labels.js';
|
|
18
|
+
import type { ChatMessageKey } from '../i18n/messages.js';
|
|
13
19
|
|
|
14
20
|
// Props
|
|
15
21
|
interface Props {
|
|
16
22
|
context: ChatContext;
|
|
17
23
|
config?: Partial<ChatConfig>;
|
|
18
24
|
class?: string;
|
|
25
|
+
/**
|
|
26
|
+
* The language of the chat: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers are written. Left
|
|
27
|
+
* out, the chat speaks English. Setting it again changes the words of a chat that is already open.
|
|
28
|
+
*/
|
|
29
|
+
locale?: string | null;
|
|
30
|
+
/**
|
|
31
|
+
* The page's own words: any of the chat's messages by key (the catalog is `CHAT_MESSAGES`; `checkChatMessages` says
|
|
32
|
+
* what is wrong with a set). A key left out keeps its English text. Setting it again replaces the whole set.
|
|
33
|
+
*/
|
|
34
|
+
messages?: Readonly<Record<string, unknown>> | null;
|
|
35
|
+
/**
|
|
36
|
+
* Which way the chat is read: "ltr" or "rtl". With "rtl" the layout is the mirror image (what starts a line starts at the
|
|
37
|
+
* right: your messages are at the left, the send button is at the left of the input), and what a person writes in a
|
|
38
|
+
* message reads by its own first letter. It is NOT worked out from `locale`: a chat on a page that is laid out left to
|
|
39
|
+
* right can speak Arabic and still be left to right. Left out, the chat is read the way the screen around it is, and
|
|
40
|
+
* left to right when nothing around it says. Can change while the chat is open. Code is read left to right on every screen.
|
|
41
|
+
*/
|
|
42
|
+
dir?: TextDirection;
|
|
19
43
|
/** Inline style passed to the root chat container (e.g. `height: 600px`). */
|
|
20
44
|
style?: string;
|
|
21
45
|
isCompleted?: boolean;
|
|
@@ -49,6 +73,7 @@
|
|
|
49
73
|
messageType: string,
|
|
50
74
|
attachments?: Array<{ url?: string; file?: File; file_type?: string; file_name?: string | null; file_size?: number | null; display_order?: number }>,
|
|
51
75
|
suggestions?: ClarificationSuggestion[],
|
|
76
|
+
designControls?: DesignControlRequest,
|
|
52
77
|
) => Promise<any>;
|
|
53
78
|
onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
|
|
54
79
|
onTakeScreenshot?: () => Promise<string | null>;
|
|
@@ -61,6 +86,11 @@
|
|
|
61
86
|
* so the host can re-run codegen without duplicating the user bubble.
|
|
62
87
|
*/
|
|
63
88
|
onRetryMessage?: (content: string) => Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
|
|
91
|
+
* billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
|
|
92
|
+
*/
|
|
93
|
+
onUpgradePlans?: () => void;
|
|
64
94
|
/**
|
|
65
95
|
* When provided, attachments are uploaded immediately and stored as CDN URLs
|
|
66
96
|
* instead of large data URLs in chat history. Host should use TUS for files >10MB.
|
|
@@ -105,12 +135,35 @@
|
|
|
105
135
|
/** Host is running widget codegen — send button becomes stop. */
|
|
106
136
|
isGenerating?: boolean;
|
|
107
137
|
onStopGeneration?: () => void;
|
|
138
|
+
/**
|
|
139
|
+
* Renders the inline design-control card attached to an assistant reply
|
|
140
|
+
* (see `addDesignControlsMessage`). The host owns the controls — the chat
|
|
141
|
+
* package stays free of design-schema/editor dependencies — and receives
|
|
142
|
+
* the resolution payload to render. When omitted, the message text still
|
|
143
|
+
* shows and the card is simply skipped.
|
|
144
|
+
*/
|
|
145
|
+
renderDesignControls?: Snippet<[DesignControlRequest]>;
|
|
146
|
+
/** Extra controls in the action bar, next to Complete. The host owns them. */
|
|
147
|
+
actionBarExtras?: Snippet;
|
|
148
|
+
/** Replaces the Complete button. The host owns it. */
|
|
149
|
+
completeReplacement?: Snippet;
|
|
150
|
+
/** When true, the replacement is shown instead of Complete. */
|
|
151
|
+
replaceComplete?: boolean;
|
|
152
|
+
/** Panel under the action bar, shown when those extras expand. */
|
|
153
|
+
composerExtras?: Snippet;
|
|
154
|
+
/**
|
|
155
|
+
* Turns a line the host saved in English into what the visitor reads (the widget creator passes
|
|
156
|
+
* `conversationLineLabel`). When omitted, message text is shown as stored.
|
|
157
|
+
*/
|
|
158
|
+
storedLineLabel?: (content: string) => string;
|
|
108
159
|
}
|
|
109
160
|
|
|
110
161
|
// Expose methods to parent component
|
|
111
162
|
interface ChatMethods {
|
|
112
163
|
sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] }) => Promise<void>;
|
|
113
|
-
addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[]) => void;
|
|
164
|
+
addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) => void;
|
|
165
|
+
/** Add an assistant reply carrying an inline design-control card (no generation). */
|
|
166
|
+
addDesignControlsMessage: (content: string, designControls: DesignControlRequest) => void;
|
|
114
167
|
addUserMessage: (content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) => void;
|
|
115
168
|
/** Returns the current conversation ID (null if no conversation is active). */
|
|
116
169
|
getConversationId: () => string | null;
|
|
@@ -142,7 +195,40 @@
|
|
|
142
195
|
updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
|
|
143
196
|
}
|
|
144
197
|
|
|
145
|
-
let { context, config = {}, class: className = '', style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration }: Props = $props();
|
|
198
|
+
let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onUpgradePlans, onUploadChatFile, showHeader = true, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras, storedLineLabel }: Props = $props();
|
|
199
|
+
|
|
200
|
+
// The words of everything inside the chat, in the language the page chose. The page can change the language while the
|
|
201
|
+
// chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
|
|
202
|
+
const language = provideChatLanguage(untrack(() => ({ locale, messages: languageMessages })));
|
|
203
|
+
const { t } = language;
|
|
204
|
+
$effect(() => {
|
|
205
|
+
language.update({ locale, messages: languageMessages });
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// The direction every part below reads from Svelte's context, and follows when the page changes `dir`.
|
|
209
|
+
const givenDirection = writable<TextDirection | undefined>(untrack(() => dir));
|
|
210
|
+
const textDirection = shareTextDirection(givenDirection);
|
|
211
|
+
$effect(() => {
|
|
212
|
+
givenDirection.set(dir);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
/** The texts of the failures that trying the load again can mend. The banner offers its button for these only. */
|
|
216
|
+
const loadFailureTexts = new Set<string>();
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Says a failure in the banner over the chat, in the language the chat has at this moment. The sentence is made once and
|
|
220
|
+
* kept as it was made: a banner that is open when the page changes the language keeps its words until it is dismissed.
|
|
221
|
+
*/
|
|
222
|
+
function showFailure(key: ChatMessageKey) {
|
|
223
|
+
chatStore.actions.updateUI({ errorMessage: $t(key) });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Says a failure of loading, and remembers its text so the banner offers to load again (a button is for these only). */
|
|
227
|
+
function showLoadFailure(key: ChatMessageKey) {
|
|
228
|
+
const failureText = $t(key);
|
|
229
|
+
loadFailureTexts.add(failureText);
|
|
230
|
+
chatStore.actions.updateUI({ errorMessage: failureText });
|
|
231
|
+
}
|
|
146
232
|
|
|
147
233
|
function notifyDraftChange() {
|
|
148
234
|
onDraftChange?.();
|
|
@@ -271,9 +357,7 @@
|
|
|
271
357
|
|
|
272
358
|
const loaded = await loadConversations();
|
|
273
359
|
if (loaded === null) {
|
|
274
|
-
|
|
275
|
-
errorMessage: 'Could not load chat history.',
|
|
276
|
-
});
|
|
360
|
+
showLoadFailure('chat.error.loadHistory');
|
|
277
361
|
return;
|
|
278
362
|
}
|
|
279
363
|
|
|
@@ -295,9 +379,7 @@
|
|
|
295
379
|
await initializeForContext(context.id);
|
|
296
380
|
} catch (error) {
|
|
297
381
|
console.error('[Chat] Retry load history failed:', error);
|
|
298
|
-
|
|
299
|
-
errorMessage: 'Could not load chat history.',
|
|
300
|
-
});
|
|
382
|
+
showLoadFailure('chat.error.loadHistory');
|
|
301
383
|
}
|
|
302
384
|
}
|
|
303
385
|
|
|
@@ -308,9 +390,7 @@
|
|
|
308
390
|
await initializeForContext(context.id);
|
|
309
391
|
} catch (error) {
|
|
310
392
|
console.error('[Chat] Failed to initialize:', error);
|
|
311
|
-
|
|
312
|
-
errorMessage: 'Failed to initialize chat. Please try again.',
|
|
313
|
-
});
|
|
393
|
+
showFailure('chat.error.initialize');
|
|
314
394
|
} finally {
|
|
315
395
|
isInitialized = true;
|
|
316
396
|
}
|
|
@@ -368,9 +448,7 @@
|
|
|
368
448
|
return loaded;
|
|
369
449
|
} catch (error) {
|
|
370
450
|
console.error('Failed to load conversations:', error);
|
|
371
|
-
|
|
372
|
-
errorMessage: 'Failed to load conversations.'
|
|
373
|
-
});
|
|
451
|
+
showLoadFailure('chat.error.loadConversations');
|
|
374
452
|
return null;
|
|
375
453
|
} finally {
|
|
376
454
|
chatStore.actions.updateUI({ isLoading: false });
|
|
@@ -379,7 +457,7 @@
|
|
|
379
457
|
|
|
380
458
|
async function createNewConversation(title?: string) {
|
|
381
459
|
try {
|
|
382
|
-
const defaultTitle = title ||
|
|
460
|
+
const defaultTitle = title || $t('chat.conversation.defaultTitle', { name: context.title || context.id });
|
|
383
461
|
const conversation = onCreateConversation
|
|
384
462
|
? await onCreateConversation(context.id, defaultTitle)
|
|
385
463
|
: await chatService.createConversation(context.id, { title: defaultTitle });
|
|
@@ -415,9 +493,7 @@
|
|
|
415
493
|
markWidgetHeadAtLatestCommit();
|
|
416
494
|
} catch (error) {
|
|
417
495
|
console.error('Failed to load conversation:', error);
|
|
418
|
-
|
|
419
|
-
errorMessage: 'Failed to load conversation.'
|
|
420
|
-
});
|
|
496
|
+
showLoadFailure('chat.error.loadConversation');
|
|
421
497
|
} finally {
|
|
422
498
|
chatStore.actions.updateUI({ isLoading: false });
|
|
423
499
|
}
|
|
@@ -544,9 +620,7 @@
|
|
|
544
620
|
|
|
545
621
|
} catch (error) {
|
|
546
622
|
console.error('Failed to send message:', error);
|
|
547
|
-
|
|
548
|
-
errorMessage: 'Failed to send message. Please try again.'
|
|
549
|
-
});
|
|
623
|
+
showFailure('chat.error.sendMessage');
|
|
550
624
|
} finally {
|
|
551
625
|
localIsSending = false;
|
|
552
626
|
}
|
|
@@ -555,7 +629,7 @@
|
|
|
555
629
|
/** Add an assistant message to the current conversation (called by parent via chatMethods).
|
|
556
630
|
* When skipPersist is true, the message is shown locally but not saved to DB
|
|
557
631
|
* (use when the backend already persists its own version). */
|
|
558
|
-
function addAssistantMessage(content: string, skipPersist = false, suggestions?: ClarificationSuggestion[]) {
|
|
632
|
+
function addAssistantMessage(content: string, skipPersist = false, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) {
|
|
559
633
|
if (!currentConversationId) return;
|
|
560
634
|
const assistantMsg = {
|
|
561
635
|
id: `assistant_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
|
@@ -570,7 +644,8 @@
|
|
|
570
644
|
_optimistic: false,
|
|
571
645
|
_failed: false,
|
|
572
646
|
_retryCount: 0,
|
|
573
|
-
...(suggestions && suggestions.length > 0 ? { suggestions } : {})
|
|
647
|
+
...(suggestions && suggestions.length > 0 ? { suggestions } : {}),
|
|
648
|
+
...(designControls ? { designControls } : {})
|
|
574
649
|
};
|
|
575
650
|
chatStore.actions.addMessage(currentConversationId, assistantMsg);
|
|
576
651
|
|
|
@@ -587,7 +662,11 @@
|
|
|
587
662
|
// persistence (intent gate) already saved this turn when it served the
|
|
588
663
|
// card; this write is the client-driven path (local-only conversations,
|
|
589
664
|
// hosts without the gate) and lands with the same shape either way.
|
|
590
|
-
|
|
665
|
+
// The card rides the same write as the reply text it sits under, so a
|
|
666
|
+
// reload re-renders the reply *and* its inline controls instead of losing
|
|
667
|
+
// half the turn. `compositionId` on the payload is what lets the host
|
|
668
|
+
// re-attach the controls to the composition they were authored against.
|
|
669
|
+
onSaveMessage(convId, content, 'assistant', undefined, suggestions, designControls).then(saved => {
|
|
591
670
|
if (saved?.id && saved.id !== assistantMsg.id) {
|
|
592
671
|
chatStore.actions.updateMessageId(convId, assistantMsg.id, saved.id);
|
|
593
672
|
}
|
|
@@ -600,6 +679,13 @@
|
|
|
600
679
|
}
|
|
601
680
|
}
|
|
602
681
|
|
|
682
|
+
/** Add an assistant reply that carries an inline design-control card. The
|
|
683
|
+
* host applied a deterministic design change and wants the user to keep
|
|
684
|
+
* adjusting the property by hand; nothing is generated. */
|
|
685
|
+
function addDesignControlsMessage(content: string, designControls: DesignControlRequest) {
|
|
686
|
+
addAssistantMessage(content, false, undefined, designControls);
|
|
687
|
+
}
|
|
688
|
+
|
|
603
689
|
/** Add a user message to the UI without triggering generation (called by parent via chatMethods).
|
|
604
690
|
* Also persists to DB via onSaveMessage so multi-turn history is complete. */
|
|
605
691
|
function addUserMessage(content: string, attachments?: Array<{ id: string; url: string; file_type: string; file_name: string; file_size?: number }>) {
|
|
@@ -651,7 +737,7 @@
|
|
|
651
737
|
|
|
652
738
|
if (!screenshotDataUrl) {
|
|
653
739
|
chatWarn('[Chat] Screenshot capture returned null');
|
|
654
|
-
|
|
740
|
+
showFailure('chat.error.screenshotUnavailable');
|
|
655
741
|
return;
|
|
656
742
|
}
|
|
657
743
|
|
|
@@ -683,9 +769,7 @@
|
|
|
683
769
|
// chatLog('Screenshot captured and added to attachments');
|
|
684
770
|
} catch (error) {
|
|
685
771
|
console.error('Screenshot capture failed:', error);
|
|
686
|
-
|
|
687
|
-
errorMessage: 'Failed to capture screenshot'
|
|
688
|
-
});
|
|
772
|
+
showFailure('chat.error.screenshotFailed');
|
|
689
773
|
}
|
|
690
774
|
}
|
|
691
775
|
|
|
@@ -701,9 +785,7 @@
|
|
|
701
785
|
} catch (error) {
|
|
702
786
|
console.error('Failed to start recording:', error);
|
|
703
787
|
localIsRecording = false;
|
|
704
|
-
|
|
705
|
-
errorMessage: 'Failed to start recording'
|
|
706
|
-
});
|
|
788
|
+
showFailure('chat.error.recordingStartFailed');
|
|
707
789
|
}
|
|
708
790
|
}
|
|
709
791
|
|
|
@@ -733,9 +815,7 @@
|
|
|
733
815
|
|
|
734
816
|
} catch (error) {
|
|
735
817
|
console.error('Failed to stop recording:', error);
|
|
736
|
-
|
|
737
|
-
errorMessage: 'Failed to stop recording'
|
|
738
|
-
});
|
|
818
|
+
showFailure('chat.error.recordingStopFailed');
|
|
739
819
|
}
|
|
740
820
|
}
|
|
741
821
|
|
|
@@ -922,17 +1002,13 @@
|
|
|
922
1002
|
}
|
|
923
1003
|
} catch (error) {
|
|
924
1004
|
console.error('Failed to update conversation status:', error);
|
|
925
|
-
|
|
926
|
-
errorMessage: 'Failed to update conversation status'
|
|
927
|
-
});
|
|
1005
|
+
showFailure('chat.error.statusUpdateFailed');
|
|
928
1006
|
}
|
|
929
1007
|
}
|
|
930
1008
|
|
|
931
1009
|
function handleActionError(detail: { type: string; error: unknown }) {
|
|
932
1010
|
console.error(`ActionBar ${detail.type} error:`, detail.error);
|
|
933
|
-
|
|
934
|
-
errorMessage: `${detail.type} action failed. Please try again.`
|
|
935
|
-
});
|
|
1011
|
+
showFailure(actionFailureKey(detail.type));
|
|
936
1012
|
}
|
|
937
1013
|
|
|
938
1014
|
async function handleSuggestionSelected(suggestion: string) {
|
|
@@ -972,9 +1048,7 @@
|
|
|
972
1048
|
});
|
|
973
1049
|
} catch (err) {
|
|
974
1050
|
console.error('[Chat] Clarification suggestion send failed:', err);
|
|
975
|
-
|
|
976
|
-
errorMessage: 'Failed to send the selected suggestion. Please try again.'
|
|
977
|
-
});
|
|
1051
|
+
showFailure('chat.error.sendSuggestion');
|
|
978
1052
|
}
|
|
979
1053
|
}
|
|
980
1054
|
|
|
@@ -1043,6 +1117,8 @@
|
|
|
1043
1117
|
|
|
1044
1118
|
const checkpointUser = currentMessages.find((msg: any) => msg.id === checkpointUserId);
|
|
1045
1119
|
const headAssistant = currentMessages.find((msg: any) => msg.id === headAssistantId);
|
|
1120
|
+
// The line saved below ("Restored from Version 3") is read back by its words, so it is written in English whatever the
|
|
1121
|
+
// page's language is; `versionLabelText` says it again in the page's language when the turn is drawn.
|
|
1046
1122
|
const sourceLabel = versionLabelForCommitContent(headAssistant?.messageContent) || 'a previous version';
|
|
1047
1123
|
const promptCopy = String(checkpointUser?.messageContent || '').trim();
|
|
1048
1124
|
|
|
@@ -1065,9 +1141,7 @@
|
|
|
1065
1141
|
|
|
1066
1142
|
} catch (error) {
|
|
1067
1143
|
console.error('Failed to restore checkpoint:', error);
|
|
1068
|
-
|
|
1069
|
-
errorMessage: 'Failed to restore checkpoint. Please try again.'
|
|
1070
|
-
});
|
|
1144
|
+
showFailure('chat.error.restoreFailed');
|
|
1071
1145
|
}
|
|
1072
1146
|
}
|
|
1073
1147
|
|
|
@@ -1463,6 +1537,7 @@
|
|
|
1463
1537
|
const chatMethods: ChatMethods = {
|
|
1464
1538
|
sendMessage,
|
|
1465
1539
|
addAssistantMessage,
|
|
1540
|
+
addDesignControlsMessage,
|
|
1466
1541
|
addUserMessage,
|
|
1467
1542
|
getConversationId: () => currentConversationId,
|
|
1468
1543
|
addImageAttachment,
|
|
@@ -1528,6 +1603,33 @@
|
|
|
1528
1603
|
let messagesAreaHeight: number | null = $state(null);
|
|
1529
1604
|
let isResizingMessages = $state(false);
|
|
1530
1605
|
const MIN_MESSAGES_HEIGHT = 120;
|
|
1606
|
+
let generationOptionsEl: HTMLDivElement | null = $state(null);
|
|
1607
|
+
let lastGenerationOptionsHeight = 0;
|
|
1608
|
+
let generationOptionsHeightReady = false;
|
|
1609
|
+
|
|
1610
|
+
// Brand kit / libraries sit in the footer. Grow the host by that height so
|
|
1611
|
+
// the messages area stays put and the input moves down inside the scroller.
|
|
1612
|
+
$effect(() => {
|
|
1613
|
+
const el = generationOptionsEl;
|
|
1614
|
+
if (!el || !resizeExpandsContainer) return;
|
|
1615
|
+
const observer = new ResizeObserver(() => {
|
|
1616
|
+
const next = Math.round(el.getBoundingClientRect().height);
|
|
1617
|
+
if (!generationOptionsHeightReady) {
|
|
1618
|
+
lastGenerationOptionsHeight = next;
|
|
1619
|
+
generationOptionsHeightReady = true;
|
|
1620
|
+
return;
|
|
1621
|
+
}
|
|
1622
|
+
const delta = next - lastGenerationOptionsHeight;
|
|
1623
|
+
if (Math.abs(delta) < 2) return;
|
|
1624
|
+
lastGenerationOptionsHeight = next;
|
|
1625
|
+
untrack(() => onMessagesResize)?.(delta);
|
|
1626
|
+
});
|
|
1627
|
+
observer.observe(el);
|
|
1628
|
+
return () => {
|
|
1629
|
+
observer.disconnect();
|
|
1630
|
+
generationOptionsHeightReady = false;
|
|
1631
|
+
};
|
|
1632
|
+
});
|
|
1531
1633
|
|
|
1532
1634
|
function handleMessagesResizeStart(e: PointerEvent) {
|
|
1533
1635
|
e.preventDefault();
|
|
@@ -1574,6 +1676,7 @@
|
|
|
1574
1676
|
<div
|
|
1575
1677
|
bind:this={chatContainer}
|
|
1576
1678
|
class="{className ? className : 'prompt-chat-ct'} relative flex flex-col overflow-hidden bg-white border border-gray-300 {className ? '' : 'rounded-medium'} h-full min-h-0"
|
|
1679
|
+
dir={$textDirection}
|
|
1577
1680
|
style={style}
|
|
1578
1681
|
>
|
|
1579
1682
|
{#if showHeader}
|
|
@@ -1591,7 +1694,7 @@
|
|
|
1591
1694
|
{#if context.type === 'frame'}📱{:else if context.type === 'text'}📄{:else if context.type === 'image'}🖼️{:else if context.type === 'document'}📋{:else}💬{/if}
|
|
1592
1695
|
</span>
|
|
1593
1696
|
<span class="text-xs text-gray-500">
|
|
1594
|
-
{context.type}
|
|
1697
|
+
{$t('chat.header.typeChat', { type: contextTypeLabel(context.type, $t) })}
|
|
1595
1698
|
</span>
|
|
1596
1699
|
<StatusIndicator
|
|
1597
1700
|
status={isCompleted ? 'completed' : (isLoading ? 'loading' : 'active')}
|
|
@@ -1632,7 +1735,10 @@
|
|
|
1632
1735
|
onSuggestionSelected={handleSuggestionSelected}
|
|
1633
1736
|
onRestoreCheckpoint={handleRestoreCheckpoint}
|
|
1634
1737
|
onRetryMessage={handleRetryMessage}
|
|
1738
|
+
{onUpgradePlans}
|
|
1635
1739
|
onClarificationSuggestionSelected={handleClarificationSuggestionSelected}
|
|
1740
|
+
{renderDesignControls}
|
|
1741
|
+
{storedLineLabel}
|
|
1636
1742
|
/>
|
|
1637
1743
|
</div>
|
|
1638
1744
|
|
|
@@ -1644,8 +1750,8 @@
|
|
|
1644
1750
|
onpointerdown={handleMessagesResizeStart}
|
|
1645
1751
|
role="separator"
|
|
1646
1752
|
aria-orientation="horizontal"
|
|
1647
|
-
aria-label=
|
|
1648
|
-
title=
|
|
1753
|
+
aria-label={$t('chat.resize.label')}
|
|
1754
|
+
title={$t('chat.resize.title')}
|
|
1649
1755
|
>
|
|
1650
1756
|
<div class="drag-grip w-14 h-1 rounded-full bg-gray-500 {isResizingMessages ? 'bg-blue-400' : ''}"></div>
|
|
1651
1757
|
</div>
|
|
@@ -1667,19 +1773,30 @@
|
|
|
1667
1773
|
onRecordStop={() => void handleRecordStop()}
|
|
1668
1774
|
onComplete={(detail) => void handleComplete(detail)}
|
|
1669
1775
|
onError={handleActionError}
|
|
1670
|
-
|
|
1776
|
+
{completeReplacement}
|
|
1777
|
+
{replaceComplete}
|
|
1778
|
+
>
|
|
1779
|
+
{#if actionBarExtras}
|
|
1780
|
+
{@render actionBarExtras()}
|
|
1781
|
+
{/if}
|
|
1782
|
+
</ActionBar>
|
|
1783
|
+
{#if composerExtras}
|
|
1784
|
+
<div class="prompt-chat-generation-options shrink-0 flex flex-col" bind:this={generationOptionsEl}>
|
|
1785
|
+
{@render composerExtras()}
|
|
1786
|
+
</div>
|
|
1787
|
+
{/if}
|
|
1671
1788
|
|
|
1672
1789
|
{#if localAttachments.length > 0}
|
|
1673
1790
|
<div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
|
|
1674
1791
|
{#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
|
|
1675
1792
|
<div class="prompt-chat-attachment-item-ct relative bg-gray-50 rounded-lg overflow-hidden">
|
|
1676
|
-
<span class="prompt-chat-attachment-index-badge absolute top-0.5
|
|
1793
|
+
<span class="prompt-chat-attachment-index-badge absolute top-0.5 start-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{index + 1}</span>
|
|
1677
1794
|
{#if isImageAttachment(attachment)}
|
|
1678
1795
|
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
|
1679
1796
|
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
|
1680
1797
|
<img
|
|
1681
1798
|
src={getFooterAttachmentPreviewUrl(attachment)}
|
|
1682
|
-
alt={attachment.file?.name || 'attachment'}
|
|
1799
|
+
alt={attachment.file?.name || $t('chat.attachment.namelessAlt')}
|
|
1683
1800
|
class="prompt-chat-attachment-image-preview w-16 h-16 object-cover cursor-pointer"
|
|
1684
1801
|
onclick={() => {
|
|
1685
1802
|
const previewUrl = getFooterAttachmentPreviewUrl(attachment);
|
|
@@ -1689,21 +1806,21 @@
|
|
|
1689
1806
|
{:else}
|
|
1690
1807
|
<div class="prompt-chat-attachment-file-preview flex items-center gap-2 p-3 w-32">
|
|
1691
1808
|
<span class="text-lg">📄</span>
|
|
1692
|
-
<span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || 'attachment'}</span>
|
|
1809
|
+
<span class="text-xs text-gray-600 truncate flex-1">{attachment.file?.name || $t('chat.attachment.namelessAlt')}</span>
|
|
1693
1810
|
</div>
|
|
1694
1811
|
{/if}
|
|
1695
1812
|
|
|
1696
1813
|
<button
|
|
1697
1814
|
type="button"
|
|
1698
|
-
class="prompt-chat-remove-attachment-btn absolute top-1
|
|
1815
|
+
class="prompt-chat-remove-attachment-btn absolute top-1 end-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600 cursor-pointer"
|
|
1699
1816
|
onclick={() => removeFooterAttachment(index)}
|
|
1700
|
-
aria-label=
|
|
1817
|
+
aria-label={$t('chat.attachment.remove')}
|
|
1701
1818
|
>
|
|
1702
1819
|
✕
|
|
1703
1820
|
</button>
|
|
1704
1821
|
|
|
1705
1822
|
{#if attachment.uploadProgress && attachment.uploadProgress > 0 && attachment.uploadProgress < 100}
|
|
1706
|
-
<div class="prompt-chat-attachment-upload-bar absolute bottom-0
|
|
1823
|
+
<div class="prompt-chat-attachment-upload-bar absolute bottom-0 start-0 end-0 h-1 bg-gray-200">
|
|
1707
1824
|
<div class="h-full bg-blue-500 transition-all duration-300" style="width: {attachment.uploadProgress}%"></div>
|
|
1708
1825
|
</div>
|
|
1709
1826
|
{/if}
|
|
@@ -1749,9 +1866,10 @@
|
|
|
1749
1866
|
>
|
|
1750
1867
|
<button
|
|
1751
1868
|
type="button"
|
|
1752
|
-
class="prompt-chat-footer-lightbox-close-btn absolute top-4
|
|
1869
|
+
class="prompt-chat-footer-lightbox-close-btn absolute top-4 end-4 w-9 h-9 rounded-full bg-white/15 text-white text-lg flex items-center justify-center cursor-pointer hover:bg-white/30"
|
|
1753
1870
|
onclick={() => (footerLightboxSrc = null)}
|
|
1754
|
-
title=
|
|
1871
|
+
title={$t('chat.attachment.close')}
|
|
1872
|
+
aria-label={$t('chat.attachment.close')}
|
|
1755
1873
|
>
|
|
1756
1874
|
✕
|
|
1757
1875
|
</button>
|
|
@@ -1760,7 +1878,7 @@
|
|
|
1760
1878
|
<div class="prompt-chat-footer-lightbox-content max-w-[90vw] max-h-[90vh]" onclick={(e) => e.stopPropagation()}>
|
|
1761
1879
|
<img
|
|
1762
1880
|
src={footerLightboxSrc}
|
|
1763
|
-
alt=
|
|
1881
|
+
alt={$t('chat.attachment.previewAlt')}
|
|
1764
1882
|
class="prompt-chat-footer-lightbox-image max-w-[90vw] max-h-[85vh] object-contain rounded-lg"
|
|
1765
1883
|
/>
|
|
1766
1884
|
</div>
|
|
@@ -1769,21 +1887,23 @@
|
|
|
1769
1887
|
|
|
1770
1888
|
<!-- Error Display -->
|
|
1771
1889
|
{#if ui?.errorMessage}
|
|
1772
|
-
<div class="error-message-ct absolute top-0
|
|
1890
|
+
<div class="error-message-ct absolute top-0 start-0 end-0 bg-red-50 border-s-4 border-red-400 p-3 flex items-center justify-between gap-2 text-sm text-red-700 rounded-none z-10">
|
|
1773
1891
|
<span class="error-message-text min-w-0 flex-1">{ui.errorMessage}</span>
|
|
1774
1892
|
<div class="error-message-actions flex items-center gap-2 shrink-0">
|
|
1775
|
-
{#if
|
|
1893
|
+
{#if loadFailureTexts.has(ui.errorMessage)}
|
|
1776
1894
|
<button
|
|
1777
1895
|
type="button"
|
|
1778
1896
|
class="retry-load-history-btn px-2 py-1 text-xs font-semibold rounded border border-red-300 bg-white text-red-700 hover:bg-red-100"
|
|
1779
1897
|
onclick={() => void retryLoadHistory()}
|
|
1780
1898
|
>
|
|
1781
|
-
|
|
1899
|
+
{$t('chat.error.retryLoad')}
|
|
1782
1900
|
</button>
|
|
1783
1901
|
{/if}
|
|
1784
1902
|
<button
|
|
1785
|
-
class="
|
|
1903
|
+
class="ms-0 text-red-400 hover:text-red-600 font-semibold w-5 h-5 flex items-center justify-center"
|
|
1786
1904
|
onclick={() => chatStore.actions.updateUI({ errorMessage: null })}
|
|
1905
|
+
title={$t('chat.error.dismiss')}
|
|
1906
|
+
aria-label={$t('chat.error.dismiss')}
|
|
1787
1907
|
>
|
|
1788
1908
|
✕
|
|
1789
1909
|
</button>
|
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
2
|
+
import { type TextDirection } from '@widgetic/design-system/components/textDirection';
|
|
1
3
|
import type { ChatConfig, ChatContext } from '../types/index.js';
|
|
2
|
-
import type { ClarificationSuggestion } from '../types/message.js';
|
|
4
|
+
import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
|
|
3
5
|
import type { AttachmentInput } from '../types/attachment.js';
|
|
4
6
|
interface ChatMethods {
|
|
5
7
|
sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
|
|
6
8
|
skipIntentGate?: boolean;
|
|
7
9
|
chipIntent?: ClarificationSuggestion['intent'];
|
|
8
10
|
}) => Promise<void>;
|
|
9
|
-
addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[]) => void;
|
|
11
|
+
addAssistantMessage: (content: string, skipPersist?: boolean, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) => void;
|
|
12
|
+
/** Add an assistant reply carrying an inline design-control card (no generation). */
|
|
13
|
+
addDesignControlsMessage: (content: string, designControls: DesignControlRequest) => void;
|
|
10
14
|
addUserMessage: (content: string, attachments?: Array<{
|
|
11
15
|
id: string;
|
|
12
16
|
url: string;
|
|
@@ -52,6 +56,24 @@ interface Props {
|
|
|
52
56
|
context: ChatContext;
|
|
53
57
|
config?: Partial<ChatConfig>;
|
|
54
58
|
class?: string;
|
|
59
|
+
/**
|
|
60
|
+
* The language of the chat: a BCP 47 tag ("de", "pt-BR"). It sets the plural rules and how numbers are written. Left
|
|
61
|
+
* out, the chat speaks English. Setting it again changes the words of a chat that is already open.
|
|
62
|
+
*/
|
|
63
|
+
locale?: string | null;
|
|
64
|
+
/**
|
|
65
|
+
* The page's own words: any of the chat's messages by key (the catalog is `CHAT_MESSAGES`; `checkChatMessages` says
|
|
66
|
+
* what is wrong with a set). A key left out keeps its English text. Setting it again replaces the whole set.
|
|
67
|
+
*/
|
|
68
|
+
messages?: Readonly<Record<string, unknown>> | null;
|
|
69
|
+
/**
|
|
70
|
+
* Which way the chat is read: "ltr" or "rtl". With "rtl" the layout is the mirror image (what starts a line starts at the
|
|
71
|
+
* right: your messages are at the left, the send button is at the left of the input), and what a person writes in a
|
|
72
|
+
* message reads by its own first letter. It is NOT worked out from `locale`: a chat on a page that is laid out left to
|
|
73
|
+
* right can speak Arabic and still be left to right. Left out, the chat is read the way the screen around it is, and
|
|
74
|
+
* left to right when nothing around it says. Can change while the chat is open. Code is read left to right on every screen.
|
|
75
|
+
*/
|
|
76
|
+
dir?: TextDirection;
|
|
55
77
|
/** Inline style passed to the root chat container (e.g. `height: 600px`). */
|
|
56
78
|
style?: string;
|
|
57
79
|
isCompleted?: boolean;
|
|
@@ -88,7 +110,7 @@ interface Props {
|
|
|
88
110
|
file_name?: string | null;
|
|
89
111
|
file_size?: number | null;
|
|
90
112
|
display_order?: number;
|
|
91
|
-
}>, suggestions?: ClarificationSuggestion[]) => Promise<any>;
|
|
113
|
+
}>, suggestions?: ClarificationSuggestion[], designControls?: DesignControlRequest) => Promise<any>;
|
|
92
114
|
onRestoreCheckpointBackend?: (conversationId: string, checkpointMessageId: string) => Promise<any>;
|
|
93
115
|
onTakeScreenshot?: () => Promise<string | null>;
|
|
94
116
|
/** Fires whenever the active conversation ID changes (including initial null → uuid). */
|
|
@@ -100,6 +122,11 @@ interface Props {
|
|
|
100
122
|
* so the host can re-run codegen without duplicating the user bubble.
|
|
101
123
|
*/
|
|
102
124
|
onRetryMessage?: (content: string) => Promise<void>;
|
|
125
|
+
/**
|
|
126
|
+
* What the "Upgrade" button of a failure about the plan or the credits does. Without it the button opens the
|
|
127
|
+
* billing page of the Widgetic site; a host that is a guest on somebody else's page gives its own function.
|
|
128
|
+
*/
|
|
129
|
+
onUpgradePlans?: () => void;
|
|
103
130
|
/**
|
|
104
131
|
* When provided, attachments are uploaded immediately and stored as CDN URLs
|
|
105
132
|
* instead of large data URLs in chat history. Host should use TUS for files >10MB.
|
|
@@ -154,6 +181,27 @@ interface Props {
|
|
|
154
181
|
/** Host is running widget codegen — send button becomes stop. */
|
|
155
182
|
isGenerating?: boolean;
|
|
156
183
|
onStopGeneration?: () => void;
|
|
184
|
+
/**
|
|
185
|
+
* Renders the inline design-control card attached to an assistant reply
|
|
186
|
+
* (see `addDesignControlsMessage`). The host owns the controls — the chat
|
|
187
|
+
* package stays free of design-schema/editor dependencies — and receives
|
|
188
|
+
* the resolution payload to render. When omitted, the message text still
|
|
189
|
+
* shows and the card is simply skipped.
|
|
190
|
+
*/
|
|
191
|
+
renderDesignControls?: Snippet<[DesignControlRequest]>;
|
|
192
|
+
/** Extra controls in the action bar, next to Complete. The host owns them. */
|
|
193
|
+
actionBarExtras?: Snippet;
|
|
194
|
+
/** Replaces the Complete button. The host owns it. */
|
|
195
|
+
completeReplacement?: Snippet;
|
|
196
|
+
/** When true, the replacement is shown instead of Complete. */
|
|
197
|
+
replaceComplete?: boolean;
|
|
198
|
+
/** Panel under the action bar, shown when those extras expand. */
|
|
199
|
+
composerExtras?: Snippet;
|
|
200
|
+
/**
|
|
201
|
+
* Turns a line the host saved in English into what the visitor reads (the widget creator passes
|
|
202
|
+
* `conversationLineLabel`). When omitted, message text is shown as stored.
|
|
203
|
+
*/
|
|
204
|
+
storedLineLabel?: (content: string) => string;
|
|
157
205
|
}
|
|
158
206
|
declare const Chat: import("svelte").Component<Props, {}, "">;
|
|
159
207
|
type Chat = ReturnType<typeof Chat>;
|