@widgetic/chat 0.1.23 → 0.1.25

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/LICENSE ADDED
@@ -0,0 +1,122 @@
1
+ Widgetic Integration License
2
+ Version 1.0
3
+
4
+ Copyright (c) Widgetic. All rights reserved.
5
+
6
+ This license covers the software package that it came with, in source and
7
+ compiled form, together with its documentation (the "Software"). By
8
+ installing, copying or using the Software you accept this license. If you do
9
+ not accept it, do not install or use the Software.
10
+
11
+ In this license, "Widgetic" is the company that publishes the Software, "you"
12
+ is the person or organization that uses it, and "Your Application" is an
13
+ application, website, product or service that you build or operate, for
14
+ yourself or for a client. "Widgetic Services" are the services that Widgetic
15
+ operates: the Widgetic API, widgets, compositions, embeds, editors, file
16
+ browser, chat and AI creator, and the other services that can be reached from
17
+ widgetic.com or its API hosts.
18
+
19
+ 1. What you may do
20
+
21
+ Widgetic grants you a worldwide, non-exclusive, non-transferable and
22
+ non-sublicensable license to use the Software, unmodified, for one purpose: to
23
+ integrate the Widgetic Services into Your Application. Within that purpose you
24
+ may:
25
+
26
+ (a) install the Software and run it in Your Application, in development,
27
+ testing and production;
28
+
29
+ (b) use it to call the Widgetic API, to show Widgetic widgets and
30
+ compositions, and to open Widgetic's editors, file browser, chat and AI
31
+ creator inside Your Application;
32
+
33
+ (c) bundle, minify and tree-shake the Software with the build tools of Your
34
+ Application, deliver the result to the people who use Your Application as a
35
+ part of it, and let them run it there;
36
+
37
+ (d) keep the copies of the Software that (a), (b) and (c) need, including
38
+ copies in your version control, your build systems and your backups.
39
+
40
+ 2. What you may not do
41
+
42
+ You may not, and may not allow anyone else to:
43
+
44
+ (a) use the Software for any purpose other than the one in section 1;
45
+
46
+ (b) use the Software to build, run or improve a service that offers what the
47
+ Widgetic Services offer, or to connect Your Application to anything other than
48
+ the Widgetic Services (a proxy of yours that forwards calls to the Widgetic
49
+ Services is fine);
50
+
51
+ (c) copy, modify, translate, adapt or make derivative works of the Software,
52
+ except as section 1(c) allows;
53
+
54
+ (d) publish, sell, rent, lease, sublicense or distribute the Software on its
55
+ own, or inside a library, SDK, template or product that others could use for
56
+ anything other than integrating the Widgetic Services, including by
57
+ publishing it, or a copy of it, to a package registry or a public CDN;
58
+
59
+ (e) reverse engineer, decompile or disassemble the Software, or try to get at
60
+ its source code, except as far as the law lets you despite this restriction;
61
+
62
+ (f) remove or change a copyright, license or attribution notice in the
63
+ Software;
64
+
65
+ (g) bypass, disable or interfere with the authentication, rate limits, quotas,
66
+ credits, plan limits or other protections of the Widgetic Services, or help
67
+ anyone else to;
68
+
69
+ (h) use the name, logo or trademarks of Widgetic, except to say truthfully
70
+ that Your Application integrates Widgetic.
71
+
72
+ 3. The Widgetic Services are separate
73
+
74
+ This license is for the Software only. It does not give you the right to use
75
+ the Widgetic Services. That right comes from your account or agreement with
76
+ Widgetic and from Widgetic's Terms of Service (https://widgetic.com/terms),
77
+ which this license does not change.
78
+
79
+ 4. Ownership
80
+
81
+ The Software is licensed to you, not sold. Widgetic and its licensors keep all
82
+ rights in it. Any right that this license does not give you in plain words is
83
+ reserved to Widgetic.
84
+
85
+ 5. Third-party software
86
+
87
+ The Software may include or depend on software from others. That software is
88
+ under its own license, which applies to it instead of this one, and nothing in
89
+ this license limits your rights under it.
90
+
91
+ 6. How long it lasts
92
+
93
+ This license lasts while you follow it and while you are entitled to use the
94
+ Widgetic Services. It ends on its own if you break it or that entitlement
95
+ ends. When it ends, you stop using the Software and delete your copies of it,
96
+ except copies that the law requires you to keep. Sections 4, 8 and 9 still
97
+ apply after it has ended.
98
+
99
+ 7. Versions
100
+
101
+ This license applies to the version of the Software that it came with and to
102
+ later versions that carry it. A version that Widgetic published under another
103
+ license stays under that license, for the copies of it that you already have.
104
+
105
+ 8. No warranty
106
+
107
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
108
+ IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
109
+ PURPOSE AND NON-INFRINGEMENT.
110
+
111
+ 9. Limit of liability
112
+
113
+ TO THE EXTENT THE LAW ALLOWS, WIDGETIC IS NOT LIABLE FOR ANY INDIRECT,
114
+ INCIDENTAL, SPECIAL, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR FOR LOST PROFITS,
115
+ REVENUE, DATA OR GOODWILL, THAT ARISE FROM THE SOFTWARE OR FROM THIS LICENSE,
116
+ EVEN IF IT HAS BEEN TOLD THAT THEY ARE POSSIBLE. NOTHING IN THIS LICENSE
117
+ LIMITS A LIABILITY THAT THE LAW DOES NOT ALLOW TO BE LIMITED.
118
+
119
+ 10. Questions
120
+
121
+ If you need to do something that this license does not allow, ask first:
122
+ support@widgetic.com.
package/README.md CHANGED
@@ -225,16 +225,6 @@ const customConfig = {
225
225
  };
226
226
  ```
227
227
 
228
- ### Environment for local development
229
-
230
- The demo app in this repo reads its settings from a `.env` file. The file is not committed, because every `PUBLIC_*` value ends up in the JavaScript that browsers download. Copy the template and fill it in:
231
-
232
- ```bash
233
- cp .env.example .env
234
- ```
235
-
236
- Use an ordinary API key for `PUBLIC_API_KEY`. Never put an internal service key (`wgt_srv_...`) in any `PUBLIC_*` variable.
237
-
238
228
  ## Languages
239
229
 
240
230
  The chat shows English until it is told otherwise. Two props of `Chat` change that, and both can change while the chat
@@ -628,7 +618,7 @@ npm run package:watch
628
618
 
629
619
  ## License
630
620
 
631
- MIT
621
+ This package is licensed under the Widgetic Integration License (see the `LICENSE` file in the package): you may use it to integrate Widgetic into your own application, and for nothing else. It is not open source. For any other use, write to support@widgetic.com.
632
622
 
633
623
  ## Contributing
634
624
 
@@ -16,9 +16,12 @@
16
16
  showScreenshot?: boolean;
17
17
  showRecord?: boolean;
18
18
  showUpload?: boolean;
19
+ showSelector?: boolean;
20
+ isSelectorActive?: boolean;
19
21
  showComplete?: boolean;
20
22
  onScreenshot?: () => void;
21
23
  onUpload?: () => void;
24
+ onToggleSelector?: (active: boolean) => void;
22
25
  onRecordStart?: () => void;
23
26
  onRecordStop?: () => void;
24
27
  onComplete?: (detail: { completed: boolean }) => void;
@@ -40,9 +43,12 @@
40
43
  showScreenshot = true,
41
44
  showRecord = true,
42
45
  showUpload = true,
46
+ showSelector = false,
47
+ isSelectorActive = false,
43
48
  showComplete = true,
44
49
  onScreenshot,
45
50
  onUpload,
51
+ onToggleSelector,
46
52
  onRecordStart,
47
53
  onRecordStop,
48
54
  onComplete,
@@ -87,6 +93,12 @@
87
93
  onUpload?.();
88
94
  }
89
95
 
96
+ // Handle widget element selector toggle (disabled by default)
97
+ function handleSelectorToggle() {
98
+ if (disabled) return;
99
+ onToggleSelector?.(!isSelectorActive);
100
+ }
101
+
90
102
  // Handle completion toggle
91
103
  function handleCompletionToggle() {
92
104
  if (disabled || !conversationId) return;
@@ -155,6 +167,36 @@
155
167
  </button>
156
168
  {/if}
157
169
 
170
+ {#if showSelector}
171
+ <!-- Widget Element Selector Toggle Button -->
172
+ <button
173
+ type="button"
174
+ class="action-button selector-button"
175
+ class:active={isSelectorActive}
176
+ onclick={handleSelectorToggle}
177
+ disabled={disabled}
178
+ aria-pressed={isSelectorActive}
179
+ title={isSelectorActive ? $t('chat.actions.selectorActiveTitle') : $t('chat.actions.selectorTitle')}
180
+ aria-label={$t('chat.actions.selectorLabel')}
181
+ data-testid="chat-selector-toggle-btn"
182
+ >
183
+ <svg viewBox="0 0 24 24" class="action-icon">
184
+ <path d="M5 3a2 2 0 0 0-2 2" />
185
+ <path d="M19 3a2 2 0 0 1 2 2" />
186
+ <path d="M21 19a2 2 0 0 1-2 2" />
187
+ <path d="M5 21a2 2 0 0 1-2-2" />
188
+ <path d="M9 3h1" />
189
+ <path d="M9 21h1" />
190
+ <path d="M14 3h1" />
191
+ <path d="M3 9v1" />
192
+ <path d="M21 9v1" />
193
+ <path d="M3 14v1" />
194
+ <path d="m12 12 7 2-3 1.5L14.5 19 12 12Z" />
195
+ </svg>
196
+ <span class="action-label">{$t('chat.actions.selector')}</span>
197
+ </button>
198
+ {/if}
199
+
158
200
  {#if replaceComplete && completeReplacement}
159
201
  {@render completeReplacement()}
160
202
  {:else if showComplete}
@@ -312,6 +354,24 @@
312
354
  color: #15803d;
313
355
  }
314
356
 
357
+ /* Selector toggle button styling */
358
+ .selector-button:hover:not(:disabled) {
359
+ background-color: #f0fdf4;
360
+ border-color: #6d9a59;
361
+ color: #2f5421;
362
+ }
363
+
364
+ .selector-button.active {
365
+ background-color: #eef6ea;
366
+ border-color: #5e8c4a;
367
+ color: #2b4c1e;
368
+ box-shadow: inset 0 0 0 1px rgba(94, 140, 74, 0.35);
369
+ }
370
+
371
+ .selector-button.active:hover:not(:disabled) {
372
+ background-color: #e1f0da;
373
+ }
374
+
315
375
  /* Completion button styling */
316
376
  .completion-button.completed {
317
377
  background-color: #dcfce7;
@@ -9,9 +9,12 @@ interface Props {
9
9
  showScreenshot?: boolean;
10
10
  showRecord?: boolean;
11
11
  showUpload?: boolean;
12
+ showSelector?: boolean;
13
+ isSelectorActive?: boolean;
12
14
  showComplete?: boolean;
13
15
  onScreenshot?: () => void;
14
16
  onUpload?: () => void;
17
+ onToggleSelector?: (active: boolean) => void;
15
18
  onRecordStart?: () => void;
16
19
  onRecordStop?: () => void;
17
20
  onComplete?: (detail: {
@@ -57,6 +57,7 @@
57
57
  if (fileType.startsWith('video/')) return '🎥';
58
58
  if (fileType.startsWith('audio/')) return '🎵';
59
59
  if (fileType.includes('pdf')) return '📄';
60
+ if (fileType.includes('csv')) return '📊';
60
61
  if (fileType.includes('text') || fileType.includes('markdown')) return '📝';
61
62
  if (fileType.includes('mermaid')) return '📊';
62
63
  return '📎';
@@ -8,7 +8,7 @@
8
8
  import { setLogsEnabled, chatLog, chatWarn } from '../utils/logger.js';
9
9
  import type { ChatConfig, ChatContext } from '../types/index.js';
10
10
  import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
11
- import type { AttachmentInput } from '../types/attachment.js';
11
+ import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
12
12
  import ChatMessages from './ChatMessages.svelte';
13
13
  import ChatInput from './ChatInput.svelte';
14
14
  import ActionBar from './ActionBar.svelte';
@@ -61,7 +61,11 @@
61
61
  fileName: string;
62
62
  fileSize?: number;
63
63
  }>,
64
- options?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] },
64
+ options?: {
65
+ skipIntentGate?: boolean;
66
+ chipIntent?: ClarificationSuggestion['intent'];
67
+ selectedElements?: SelectedElementChatReference[];
68
+ },
65
69
  ) => Promise<void>;
66
70
  /** Backend integration callbacks — when provided, replace mock chatService methods */
67
71
  onLoadConversations?: (contextId: string) => Promise<any[] | null>;
@@ -119,7 +123,7 @@
119
123
  onMessagesDrag?: (totalDy: number) => void;
120
124
  onMessagesDragEnd?: () => void;
121
125
  /** Messages older than the ones on screen. Empty, or `hasOlder: false`, means the top is the start. */
122
- onLoadOlderMessages?: (conversationId: string) => Promise<Array<{ id?: string; hasOlder?: boolean }>>;
126
+ onLoadOlderMessages?: (conversationId: string) => Promise<any[]>;
123
127
  /**
124
128
  * Widget Git HEAD from the host (panel lastCommitId). Used so Head / Restore chrome
125
129
  * still appears when assistant commit bubbles were never persisted.
@@ -161,6 +165,18 @@
161
165
  * `conversationLineLabel`). When omitted, message text is shown as stored.
162
166
  */
163
167
  storedLineLabel?: (content: string) => string;
168
+ /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
169
+ showSelector?: boolean;
170
+ /** Whether the Widget Element Selector is currently active for this chat's widget. */
171
+ isSelectorActive?: boolean;
172
+ /** Selected widget elements currently referenced in this chat. */
173
+ selectedElements?: SelectedElementChatReference[];
174
+ /** Fired when the user toggles the Selector button in the action bar. */
175
+ onToggleSelector?: (active: boolean) => void;
176
+ /** Fired when the user removes a single selected widget element chip. */
177
+ onRemoveSelectedElement?: (elementId: string) => void;
178
+ /** Fired when all selected widget elements should be cleared (e.g. after sending). */
179
+ onClearSelectedElements?: () => void;
164
180
  }
165
181
 
166
182
  // Expose methods to parent component
@@ -200,7 +216,7 @@
200
216
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
201
217
  }
202
218
 
203
- 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, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, composerExtras, storedLineLabel }: Props = $props();
219
+ 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, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], viewingVersion = null, isGenerating = false, onStopGeneration, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel }: Props = $props();
204
220
 
205
221
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
206
222
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -619,6 +635,11 @@
619
635
  // chatLog('[Chat] Sending message:', content.substring(0, 60));
620
636
  const submittedContent = content;
621
637
  const submittedAttachments = normalizedAttachments;
638
+ const submittedSelectedElements =
639
+ selectedElements && selectedElements.length > 0 ? [...selectedElements] : undefined;
640
+ const displayMessageContent = submittedSelectedElements
641
+ ? `[Selected: ${submittedSelectedElements.map((el) => el.label).join(', ')}]\n${submittedContent}`
642
+ : submittedContent;
622
643
 
623
644
  try {
624
645
  localIsSending = true;
@@ -627,6 +648,12 @@
627
648
  // image thumbnails linger during long generations and can re-save them as drafts.
628
649
  localInputText = '';
629
650
  localAttachments = [];
651
+ if (submittedSelectedElements) {
652
+ onClearSelectedElements?.();
653
+ if (isSelectorActive) {
654
+ onToggleSelector?.(false);
655
+ }
656
+ }
630
657
  notifyDraftChange();
631
658
 
632
659
  // Clear head/checkpoint marks — new prompt starts a new turn
@@ -642,7 +669,7 @@
642
669
 
643
670
  // Add user message to the UI immediately (local mock for instant feedback)
644
671
  const userMessage = await chatService.sendMessage(activeConversationId, {
645
- messageContent: submittedContent,
672
+ messageContent: displayMessageContent,
646
673
  attachments: submittedAttachments
647
674
  });
648
675
  chatStore.actions.addMessage(activeConversationId, userMessage);
@@ -660,7 +687,7 @@
660
687
  })).filter((att: { url?: string; file?: File }) => !!att.url || att.file instanceof File);
661
688
  const saved = await onSaveMessage(
662
689
  activeConversationId,
663
- submittedContent,
690
+ displayMessageContent,
664
691
  'user',
665
692
  persistAttachments.length > 0 ? persistAttachments : undefined,
666
693
  );
@@ -678,15 +705,33 @@
678
705
  }
679
706
 
680
707
  if (onSendMessage) {
681
- const outgoing = (submittedAttachments || []).map((att) => ({
682
- file: att.file,
683
- url: att.uploadedUrl || att.preview,
684
- uploadId: att.uploadId,
685
- fileType: att.file?.type || 'application/octet-stream',
686
- fileName: att.file?.name || 'attachment',
687
- fileSize: att.file?.size,
688
- }));
689
- await onSendMessage(submittedContent, outgoing.length > 0 ? outgoing : undefined, options);
708
+ const outgoing = (submittedAttachments || []).map((att) => {
709
+ const rawFileName = att.file?.name || 'attachment';
710
+ const rawFileType = att.file?.type || '';
711
+ const resolvedFileType =
712
+ rawFileName.toLowerCase().endsWith('.csv') &&
713
+ (!rawFileType ||
714
+ rawFileType === 'application/octet-stream' ||
715
+ rawFileType === 'application/vnd.ms-excel' ||
716
+ rawFileType === 'application/csv')
717
+ ? 'text/csv'
718
+ : rawFileType || 'application/octet-stream';
719
+ return {
720
+ file: att.file,
721
+ url: att.uploadedUrl || att.preview,
722
+ uploadId: att.uploadId,
723
+ fileType: resolvedFileType,
724
+ fileName: rawFileName,
725
+ fileSize: att.file?.size,
726
+ };
727
+ });
728
+ await onSendMessage(
729
+ submittedContent,
730
+ outgoing.length > 0 ? outgoing : undefined,
731
+ submittedSelectedElements
732
+ ? { ...options, selectedElements: submittedSelectedElements }
733
+ : options
734
+ );
690
735
  } else {
691
736
  const aiResponse = await chatService.processAIResponse(activeConversationId, userMessage);
692
737
  chatStore.actions.addMessage(activeConversationId, aiResponse);
@@ -1278,7 +1323,7 @@
1278
1323
 
1279
1324
  function getAttachmentUploadIds(): string[] {
1280
1325
  return localAttachments
1281
- .filter((att) => att.type === 'image' && att.uploadId)
1326
+ .filter((att) => Boolean(att.uploadId))
1282
1327
  .map((att) => att.uploadId as string);
1283
1328
  }
1284
1329
 
@@ -1851,9 +1896,12 @@
1851
1896
  showScreenshot={config?.features?.screenshot !== false}
1852
1897
  showRecord={config?.features?.screenRecording !== false}
1853
1898
  showUpload={config?.features?.fileUpload !== false}
1899
+ {showSelector}
1900
+ {isSelectorActive}
1854
1901
  showComplete={config?.features?.markComplete !== false}
1855
1902
  onScreenshot={() => void handleScreenshot()}
1856
1903
  onUpload={() => void handleUpload()}
1904
+ onToggleSelector={(active) => onToggleSelector?.(active)}
1857
1905
  onRecordStart={() => void handleRecordStart()}
1858
1906
  onRecordStop={() => void handleRecordStop()}
1859
1907
  onComplete={(detail) => void handleComplete(detail)}
@@ -1871,6 +1919,58 @@
1871
1919
  </div>
1872
1920
  {/if}
1873
1921
 
1922
+ {#if selectedElements && selectedElements.length > 0}
1923
+ <div
1924
+ class="prompt-chat-selected-elements-tray flex flex-wrap items-center gap-1.5 border-t border-gray-100 bg-[#F7FAF5] px-3 py-2 shrink-0"
1925
+ data-testid="chat-selected-elements-tray"
1926
+ >
1927
+ {#each selectedElements as item, index (item.id)}
1928
+ <div
1929
+ class="prompt-chat-selected-element-chip inline-flex max-w-full items-center gap-1.5 rounded-md border border-[#7BA668]/45 bg-white px-2 py-1 text-xs text-gray-800 shadow-xs"
1930
+ title={item.selector}
1931
+ >
1932
+ <span class="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-[#6D9A59] font-sans text-[10px] font-bold text-white">
1933
+ {index + 1}
1934
+ </span>
1935
+ <span class="rounded bg-[#7BA668]/15 px-1 py-0.5 font-mono text-[11px] font-medium text-[#3C632C]">
1936
+ &lt;{item.tagName}{item.idAttr ? `#${item.idAttr}` : ''}&gt;
1937
+ </span>
1938
+ {#if item.textSnippet}
1939
+ <span class="text-gray-400">·</span>
1940
+ <span class="max-w-[180px] truncate text-[11px] text-gray-600">
1941
+ {item.textSnippet}
1942
+ </span>
1943
+ {:else if item.selector}
1944
+ <span class="text-gray-400">·</span>
1945
+ <span class="max-w-[160px] truncate font-mono text-[10px] text-gray-500">
1946
+ {item.selector}
1947
+ </span>
1948
+ {/if}
1949
+ {#if onRemoveSelectedElement}
1950
+ <button
1951
+ type="button"
1952
+ class="ms-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-gray-400 hover:bg-gray-200 hover:text-gray-700 cursor-pointer"
1953
+ onclick={() => onRemoveSelectedElement?.(item.id)}
1954
+ title={$t('chat.selector.removeElement')}
1955
+ aria-label={$t('chat.selector.removeElement')}
1956
+ >
1957
+ ✕
1958
+ </button>
1959
+ {/if}
1960
+ </div>
1961
+ {/each}
1962
+ {#if selectedElements.length > 1 && onClearSelectedElements}
1963
+ <button
1964
+ type="button"
1965
+ class="ms-auto text-[11px] font-medium text-gray-500 hover:text-gray-800 cursor-pointer"
1966
+ onclick={() => onClearSelectedElements?.()}
1967
+ >
1968
+ {$t('chat.selector.clearAll')}
1969
+ </button>
1970
+ {/if}
1971
+ </div>
1972
+ {/if}
1973
+
1874
1974
  {#if localAttachments.length > 0}
1875
1975
  <div class="prompt-chat-attachments-tray-ct flex flex-wrap gap-2 p-3 border-t border-gray-100 bg-white shrink-0">
1876
1976
  {#each localAttachments as attachment, index (attachment.preview || attachment.uploadedUrl || attachment.file?.name || index)}
@@ -2,7 +2,7 @@ import type { Snippet } from 'svelte';
2
2
  import { type TextDirection } from '@widgetic/design-system/components/textDirection';
3
3
  import type { ChatConfig, ChatContext } from '../types/index.js';
4
4
  import type { ClarificationSuggestion, DesignControlRequest } from '../types/message.js';
5
- import type { AttachmentInput } from '../types/attachment.js';
5
+ import type { AttachmentInput, SelectedElementChatReference } from '../types/attachment.js';
6
6
  interface ChatMethods {
7
7
  sendMessage: (content: string, attachments?: Array<File | AttachmentInput>, options?: {
8
8
  skipIntentGate?: boolean;
@@ -98,6 +98,7 @@ interface Props {
98
98
  }>, options?: {
99
99
  skipIntentGate?: boolean;
100
100
  chipIntent?: ClarificationSuggestion['intent'];
101
+ selectedElements?: SelectedElementChatReference[];
101
102
  }) => Promise<void>;
102
103
  /** Backend integration callbacks — when provided, replace mock chatService methods */
103
104
  onLoadConversations?: (contextId: string) => Promise<any[] | null>;
@@ -161,10 +162,7 @@ interface Props {
161
162
  onMessagesDrag?: (totalDy: number) => void;
162
163
  onMessagesDragEnd?: () => void;
163
164
  /** Messages older than the ones on screen. Empty, or `hasOlder: false`, means the top is the start. */
164
- onLoadOlderMessages?: (conversationId: string) => Promise<Array<{
165
- id?: string;
166
- hasOlder?: boolean;
167
- }>>;
165
+ onLoadOlderMessages?: (conversationId: string) => Promise<any[]>;
168
166
  /**
169
167
  * Widget Git HEAD from the host (panel lastCommitId). Used so Head / Restore chrome
170
168
  * still appears when assistant commit bubbles were never persisted.
@@ -210,6 +208,18 @@ interface Props {
210
208
  * `conversationLineLabel`). When omitted, message text is shown as stored.
211
209
  */
212
210
  storedLineLabel?: (content: string) => string;
211
+ /** Show the Widget Element Selector toggle button in the action bar (disabled by default). */
212
+ showSelector?: boolean;
213
+ /** Whether the Widget Element Selector is currently active for this chat's widget. */
214
+ isSelectorActive?: boolean;
215
+ /** Selected widget elements currently referenced in this chat. */
216
+ selectedElements?: SelectedElementChatReference[];
217
+ /** Fired when the user toggles the Selector button in the action bar. */
218
+ onToggleSelector?: (active: boolean) => void;
219
+ /** Fired when the user removes a single selected widget element chip. */
220
+ onRemoveSelectedElement?: (elementId: string) => void;
221
+ /** Fired when all selected widget elements should be cleared (e.g. after sending). */
222
+ onClearSelectedElements?: () => void;
213
223
  }
214
224
  declare const Chat: import("svelte").Component<Props, {}, "">;
215
225
  type Chat = ReturnType<typeof Chat>;
@@ -115,6 +115,12 @@ export declare const CHAT_MESSAGES: {
115
115
  readonly 'chat.actions.upload': "Upload";
116
116
  readonly 'chat.actions.uploadTitle': "Upload File";
117
117
  readonly 'chat.actions.uploadLabel': "Upload file";
118
+ readonly 'chat.actions.selector': "Selector";
119
+ readonly 'chat.actions.selectorTitle': "Select a specific part of the widget to reference in chat";
120
+ readonly 'chat.actions.selectorActiveTitle': "Disable widget element selector";
121
+ readonly 'chat.actions.selectorLabel': "Toggle widget element selector";
122
+ readonly 'chat.selector.removeElement': "Remove selected element";
123
+ readonly 'chat.selector.clearAll': "Clear all";
118
124
  readonly 'chat.actions.complete': "Complete";
119
125
  readonly 'chat.actions.completed': "Completed";
120
126
  readonly 'chat.actions.markCompleteTitle': "Mark this chat as done. You can still send messages and iterate on the widget.";
@@ -122,6 +122,12 @@ export const CHAT_MESSAGES = {
122
122
  'chat.actions.upload': 'Upload',
123
123
  'chat.actions.uploadTitle': 'Upload File',
124
124
  'chat.actions.uploadLabel': 'Upload file',
125
+ 'chat.actions.selector': 'Selector',
126
+ 'chat.actions.selectorTitle': 'Select a specific part of the widget to reference in chat',
127
+ 'chat.actions.selectorActiveTitle': 'Disable widget element selector',
128
+ 'chat.actions.selectorLabel': 'Toggle widget element selector',
129
+ 'chat.selector.removeElement': 'Remove selected element',
130
+ 'chat.selector.clearAll': 'Clear all',
125
131
  'chat.actions.complete': 'Complete',
126
132
  'chat.actions.completed': 'Completed',
127
133
  'chat.actions.markCompleteTitle': 'Mark this chat as done. You can still send messages and iterate on the widget.',
@@ -7,6 +7,28 @@ export type AttachmentType = 'image' | 'video' | 'document' | 'other';
7
7
  * Attachment upload status
8
8
  */
9
9
  export type UploadStatus = 'pending' | 'uploading' | 'completed' | 'failed';
10
+ /**
11
+ * Selected DOM element reference from the interactive Widget Element Selector on the canvas
12
+ */
13
+ export interface SelectedElementChatReference {
14
+ id: string;
15
+ tagName: string;
16
+ selector: string;
17
+ idAttr?: string;
18
+ classList?: string[];
19
+ textSnippet?: string;
20
+ dataContent?: string;
21
+ parentTag?: string;
22
+ outerHtmlSnippet?: string;
23
+ attributes?: Record<string, string>;
24
+ rect?: {
25
+ x: number;
26
+ y: number;
27
+ width: number;
28
+ height: number;
29
+ };
30
+ label: string;
31
+ }
10
32
  /**
11
33
  * Input for creating attachments
12
34
  */
@@ -20,7 +20,7 @@ export const FILE_TYPE_CONFIG = {
20
20
  type: 'document',
21
21
  icon: 'file-text',
22
22
  preview: false,
23
- accept: ['application/pdf', 'text/plain', 'text/markdown', '.mermaid', '.md'],
23
+ accept: ['application/pdf', 'text/plain', 'text/markdown', 'text/csv', '.mermaid', '.md', '.csv'],
24
24
  maxSize: 25 * 1024 * 1024, // 25MB
25
25
  },
26
26
  other: {
@@ -20,7 +20,7 @@ export const fileTypeConfig = {
20
20
  type: 'document',
21
21
  icon: 'file-text',
22
22
  preview: false,
23
- accept: ['application/pdf', 'text/plain', 'text/markdown', '.mermaid', '.md'],
23
+ accept: ['application/pdf', 'text/plain', 'text/markdown', 'text/csv', '.mermaid', '.md', '.csv'],
24
24
  maxSize: 25 * 1024 * 1024, // 25MB
25
25
  },
26
26
  other: {
@@ -38,7 +38,7 @@ export function detectFileType(mimeType, fileName) {
38
38
  // Check by file extension first for special cases
39
39
  if (fileName) {
40
40
  const extension = getFileExtension(fileName);
41
- if (extension === 'mermaid' || extension === 'md') {
41
+ if (extension === 'mermaid' || extension === 'md' || extension === 'csv') {
42
42
  return 'document';
43
43
  }
44
44
  }
@@ -51,6 +51,9 @@ export function detectFileType(mimeType, fileName) {
51
51
  if (mimeType === 'application/pdf' ||
52
52
  mimeType === 'text/plain' ||
53
53
  mimeType === 'text/markdown' ||
54
+ mimeType === 'text/csv' ||
55
+ mimeType === 'application/csv' ||
56
+ mimeType === 'application/vnd.ms-excel' ||
54
57
  mimeType.startsWith('text/')) {
55
58
  return 'document';
56
59
  }
@@ -79,10 +82,17 @@ export function validateFile(file, config) {
79
82
  const mimeTypeAllowed = allowedTypes.includes(file.type);
80
83
  // Check if file extension is explicitly allowed (e.g., .mermaid)
81
84
  const extensionAllowed = allowedTypes.includes(`.${extension}`) || allowedTypes.includes(extension);
82
- // Special handling for .mermaid and .md files with text/plain MIME type
83
- const isSpecialTextFile = (extension === 'mermaid' || extension === 'md') &&
84
- file.type === 'text/plain' &&
85
- (allowedTypes.includes('text/plain') || allowedTypes.includes('text/markdown'));
85
+ // Special handling for .mermaid, .md, and .csv files with browser-specific text/csv MIME types
86
+ const isSpecialTextFile = (extension === 'mermaid' || extension === 'md' || extension === 'csv') &&
87
+ (file.type === 'text/plain' ||
88
+ file.type === 'text/csv' ||
89
+ file.type === 'application/csv' ||
90
+ file.type === 'application/vnd.ms-excel' ||
91
+ file.type === '') &&
92
+ (allowedTypes.includes('text/plain') ||
93
+ allowedTypes.includes('text/markdown') ||
94
+ allowedTypes.includes('text/csv') ||
95
+ allowedTypes.includes('.csv'));
86
96
  if (!mimeTypeAllowed && !extensionAllowed && !isSpecialTextFile) {
87
97
  return {
88
98
  valid: false,
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
+ "license": "SEE LICENSE IN LICENSE",
4
5
  "type": "module",
5
6
  "main": "./dist/index.js",
6
7
  "types": "./dist/index.d.ts",
package/dist/config.d.ts DELETED
@@ -1,43 +0,0 @@
1
- /**
2
- * SDK Configuration Management
3
- *
4
- * Centralizes all SDK configuration including:
5
- * - Environment variables
6
- * - API configuration
7
- * - SDK settings
8
- * - Configuration validation
9
- * - Helper functions
10
- */
11
- import { Configuration } from '@widgetic/api-sdk';
12
- interface Config {
13
- NODE_ENV: string;
14
- API_URL: string;
15
- API_VERSION: string;
16
- INTERNAL_KEY?: string;
17
- API_KEY?: string;
18
- CLIENT_URL: string;
19
- PRODUCTION_URL: string;
20
- }
21
- export declare const config: Config;
22
- /**
23
- * Creates SDK configuration for API clients
24
- * Used by core and modules
25
- * Priority: passed apiKey > env API_KEY > env INTERNAL_KEY
26
- */
27
- export declare function createSdkConfig(options?: {
28
- apiKey?: string;
29
- basePath?: string;
30
- }): Configuration;
31
- /**
32
- * Gets the full API URL for the current environment
33
- */
34
- export declare function getApiUrl(): string;
35
- /**
36
- * Environment-specific settings
37
- */
38
- export declare const environment: {
39
- readonly isProduction: boolean;
40
- readonly apiUrl: string;
41
- readonly apiKey: string | undefined;
42
- };
43
- export {};
package/dist/config.js DELETED
@@ -1,67 +0,0 @@
1
- /**
2
- * SDK Configuration Management
3
- *
4
- * Centralizes all SDK configuration including:
5
- * - Environment variables
6
- * - API configuration
7
- * - SDK settings
8
- * - Configuration validation
9
- * - Helper functions
10
- */
11
- import { env } from "$env/dynamic/public";
12
- import { Configuration } from '@widgetic/api-sdk';
13
- // Validate that at least one key type is present
14
- if (!env.PUBLIC_INTERNAL_KEY && !env.PUBLIC_API_KEY) {
15
- throw new Error('Either PUBLIC_INTERNAL_KEY or PUBLIC_API_KEY must be set');
16
- }
17
- if (!env.PUBLIC_API_URL) {
18
- throw new Error('PUBLIC_API_URL environment variable is not set');
19
- }
20
- if (!env.PUBLIC_API_VERSION) {
21
- throw new Error('PUBLIC_API_VERSION environment variable is not set');
22
- }
23
- if (!env.PUBLIC_CLIENT_URL) {
24
- throw new Error('PUBLIC_CLIENT_URL environment variable is not set');
25
- }
26
- if (!env.PUBLIC_PRODUCTION_URL) {
27
- throw new Error('PUBLIC_PRODUCTION_URL environment variable is not set');
28
- }
29
- // Create and export the config object with proper typing
30
- export const config = {
31
- API_URL: env.PUBLIC_API_URL,
32
- API_VERSION: env.PUBLIC_API_VERSION,
33
- INTERNAL_KEY: env.PUBLIC_INTERNAL_KEY,
34
- API_KEY: env.PUBLIC_API_KEY,
35
- CLIENT_URL: env.PUBLIC_CLIENT_URL,
36
- PRODUCTION_URL: env.PUBLIC_PRODUCTION_URL,
37
- NODE_ENV: env.PUBLIC_NODE_ENV
38
- };
39
- /**
40
- * Creates SDK configuration for API clients
41
- * Used by core and modules
42
- * Priority: passed apiKey > env API_KEY > env INTERNAL_KEY
43
- */
44
- export function createSdkConfig(options) {
45
- return new Configuration({
46
- apiKey: (name) => options?.apiKey || config.API_KEY || config.INTERNAL_KEY || '',
47
- basePath: options?.basePath || getApiUrl()
48
- });
49
- }
50
- /**
51
- * Gets the full API URL for the current environment
52
- */
53
- export function getApiUrl() {
54
- const baseUrl = config.NODE_ENV === 'production'
55
- ? config.PRODUCTION_URL
56
- : config.API_URL;
57
- return `${baseUrl}${config.API_VERSION}`;
58
- }
59
- /**
60
- * Environment-specific settings
61
- */
62
- export const environment = {
63
- isProduction: config.NODE_ENV === 'production',
64
- apiUrl: getApiUrl(),
65
- // Use API_KEY if available, fall back to INTERNAL_KEY
66
- apiKey: config.API_KEY || config.INTERNAL_KEY
67
- };