@widgetic/chat 0.1.41 → 0.1.42

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.
@@ -13,8 +13,9 @@
13
13
  import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
14
14
  import ChatMessages from './ChatMessages.svelte';
15
15
  import ChatComposer, { type ComposerModelOption } from './ChatComposer.svelte';
16
- import { Chip } from '@widgetic/design-system/components/chat/index';
17
16
  import { showToast } from '@widgetic/design-system/components/toast/index';
17
+ import SelectedElementChip from './SelectedElementChip.svelte';
18
+ import { selectedElementChipLabel, selectedElementChipTitle } from '../utils/selectedElementChip.js';
18
19
  import ActionBar from './ActionBar.svelte';
19
20
  import PanelChatHeader from './PanelChatHeader.svelte';
20
21
  import ComposerAttachmentsTray from './ComposerAttachmentsTray.svelte';
@@ -245,6 +246,16 @@
245
246
  onRemoveSelectedElement?: (elementId: string) => void;
246
247
  /** Fired when all selected widget elements should be cleared (e.g. after sending). */
247
248
  onClearSelectedElements?: () => void;
249
+ /**
250
+ * The part whose note is open over the preview, if any. Its chip is drawn as active. Together with
251
+ * `onSelectedElementClick` it lets a chip and the part's marker on the preview open and fold the same note.
252
+ */
253
+ activeSelectedElementId?: string | null;
254
+ /**
255
+ * Fired when the body of a part's chip is clicked: the host shows that part's note over the preview (or folds it when it is
256
+ * already open). Left out, the chips only say what they hold and are not clickable.
257
+ */
258
+ onSelectedElementClick?: (elementId: string) => void;
248
259
  /** Model list for the DS composer Assistant menu; hidden when empty. */
249
260
  composerModels?: ComposerModelOption[];
250
261
  selectedComposerModelId?: string | null;
@@ -290,7 +301,7 @@
290
301
  updateLastUserMessageAttachments: (attachments: Array<{ id?: string; url: string; file_type?: string; file_name?: string | null }>) => void;
291
302
  }
292
303
 
293
- let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onSketchUndo, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
304
+ let { context, config = {}, class: className = '', locale = null, messages: languageMessages = null, dir = undefined, style = '', isCompleted = false, onStatsUpdate, onChatReady, onCompletionToggle, onSendMessage, onLoadConversations, onLoadMessages, onCreateConversation, onSaveMessage, onRestoreCheckpointBackend, onRateVersion, versionRatings: ratingsFromHost = {}, onTakeScreenshot, onConversationChange, onDraftChange, onRetryMessage, onSketchUndo, onUpgradePlans, onUploadChatFile, showHeader = true, showPanelHeader = false, showConsoleControl = false, sendNudgeToken = 0, consoleOpen = false, onToggleConsole, headerTitle = '', showDescriptionHeader = true, showLogs = true, resizeExpandsContainer = false, onMessagesResize, onMessagesDrag, onMessagesDragEnd, onLoadOlderMessages, widgetHeadCommitSha = null, versionLabelByCommitSha = {}, versionLabelByPrompt = {}, versionTimeline = [], isGenerating = false, generationStream = '', generationThinking = '', generationPlan = null, onStopGeneration, members = [], currentUser = null, renderAgentAvatar, agentSound, tightBubbles = true, renderDesignControls, actionBarExtras, completeReplacement, replaceComplete = false, showSelector = false, isSelectorActive = false, selectedElements = [], onToggleSelector, onRemoveSelectedElement, onClearSelectedElements, activeSelectedElementId = null, onSelectedElementClick, composerExtras, storedLineLabel, composerModels = [], selectedComposerModelId = null, onSelectComposerModel }: Props = $props();
294
305
 
295
306
  // The words of everything inside the chat, in the language the page chose. The page can change the language while the
296
307
  // chat is open: the settings are read again whenever they change (and setting the same language again does nothing).
@@ -2195,41 +2206,6 @@
2195
2206
  </div>
2196
2207
  {/if}
2197
2208
 
2198
- {#if selectedElements && selectedElements.length > 0}
2199
- <div
2200
- 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"
2201
- data-testid="chat-selected-elements-tray"
2202
- >
2203
- {#each selectedElements as item, index (item.id)}
2204
- {@const chipLabel = `<${item.tagName}${item.idAttr ? `#${item.idAttr}` : ''}>${item.note?.trim() ? ` · ${item.note.trim()}` : item.textSnippet ? ` · ${item.textSnippet}` : item.selector ? ` · ${item.selector}` : ''}`}
2205
- <span class="prompt-chat-selected-element-chip max-w-full" title={item.selector} data-testid="chat-selected-element-chip">
2206
- <Chip
2207
- class="max-w-full"
2208
- label={chipLabel}
2209
- showRemove={!!onRemoveSelectedElement}
2210
- removeLabel={$t('chat.selector.removeElement')}
2211
- onRemove={() => onRemoveSelectedElement?.(item.id)}
2212
- >
2213
- {#snippet leading()}
2214
- <span class="bg-primary text-primary-foreground flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-bold">
2215
- {index + 1}
2216
- </span>
2217
- {/snippet}
2218
- </Chip>
2219
- </span>
2220
- {/each}
2221
- {#if selectedElements.length > 1 && onClearSelectedElements}
2222
- <button
2223
- type="button"
2224
- class="ms-auto text-[11px] font-medium text-gray-500 hover:text-gray-800 cursor-pointer"
2225
- onclick={() => onClearSelectedElements?.()}
2226
- >
2227
- {$t('chat.selector.clearAll')}
2228
- </button>
2229
- {/if}
2230
- </div>
2231
- {/if}
2232
-
2233
2209
  {#if localAttachments.length > 0}
2234
2210
  <ComposerAttachmentsTray
2235
2211
  attachments={localAttachments}
@@ -2242,8 +2218,39 @@
2242
2218
  />
2243
2219
  {/if}
2244
2220
 
2221
+ <!--
2222
+ The parts the person picked on the preview, as chips inside the message box (Figma: Selecting elements, frames 2 to 4).
2223
+ A chip says the first words of the part's note; its body opens that note over the part on the preview, and the cross takes
2224
+ the part out of the message. The number on the badge is the number of the marker on the part.
2225
+ -->
2226
+ {#snippet selectedElementChips()}
2227
+ <div class="prompt-chat-selected-elements-tray flex w-full min-w-0 flex-wrap items-center gap-1.5" data-testid="chat-selected-elements-tray">
2228
+ {#each selectedElements ?? [] as item, index (item.id)}
2229
+ <SelectedElementChip
2230
+ index={index + 1}
2231
+ label={selectedElementChipLabel(item)}
2232
+ title={selectedElementChipTitle(item)}
2233
+ active={activeSelectedElementId === item.id}
2234
+ removeLabel={$t('chat.selector.removeElement')}
2235
+ onOpen={onSelectedElementClick ? () => onSelectedElementClick?.(item.id) : undefined}
2236
+ onRemove={onRemoveSelectedElement ? () => onRemoveSelectedElement?.(item.id) : undefined}
2237
+ />
2238
+ {/each}
2239
+ {#if (selectedElements?.length ?? 0) > 1 && onClearSelectedElements}
2240
+ <button
2241
+ type="button"
2242
+ class="text-caption text-muted-foreground hover:text-foreground ms-auto cursor-pointer"
2243
+ onclick={() => onClearSelectedElements?.()}
2244
+ >
2245
+ {$t('chat.selector.clearAll')}
2246
+ </button>
2247
+ {/if}
2248
+ </div>
2249
+ {/snippet}
2250
+
2245
2251
  <ChatComposer
2246
2252
  {sendNudgeToken}
2253
+ attachments={selectedElements && selectedElements.length > 0 ? selectedElementChips : undefined}
2247
2254
  panelLayout={showPanelHeader}
2248
2255
  placeholder={showPanelHeader
2249
2256
  ? (currentMessages?.length ?? 0) > 0
@@ -283,6 +283,16 @@ interface Props {
283
283
  onRemoveSelectedElement?: (elementId: string) => void;
284
284
  /** Fired when all selected widget elements should be cleared (e.g. after sending). */
285
285
  onClearSelectedElements?: () => void;
286
+ /**
287
+ * The part whose note is open over the preview, if any. Its chip is drawn as active. Together with
288
+ * `onSelectedElementClick` it lets a chip and the part's marker on the preview open and fold the same note.
289
+ */
290
+ activeSelectedElementId?: string | null;
291
+ /**
292
+ * Fired when the body of a part's chip is clicked: the host shows that part's note over the preview (or folds it when it is
293
+ * already open). Left out, the chips only say what they hold and are not clickable.
294
+ */
295
+ onSelectedElementClick?: (elementId: string) => void;
286
296
  /** Model list for the DS composer Assistant menu; hidden when empty. */
287
297
  composerModels?: ComposerModelOption[];
288
298
  selectedComposerModelId?: string | null;
@@ -1,4 +1,5 @@
1
1
  <script lang="ts">
2
+ import type { Snippet } from 'svelte';
2
3
  import type { AttachmentInput } from '../types/attachment.js';
3
4
  import { useChatLanguage } from '../i18n/language.js';
4
5
  import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
@@ -34,6 +35,11 @@
34
35
  sendIcon?: 'send' | 'arrow-up';
35
36
  /** Increment from the host to nudge Send before publish. */
36
37
  sendNudgeToken?: number;
38
+ /**
39
+ * What sits inside the message box above the text (the chips of the parts picked on the preview). The box draws nothing
40
+ * for it while this is not given, so a message with no parts looks as it always did.
41
+ */
42
+ attachments?: Snippet;
37
43
  }
38
44
 
39
45
  let {
@@ -55,6 +61,7 @@
55
61
  panelLayout = false,
56
62
  sendIcon = 'send',
57
63
  sendNudgeToken = 0,
64
+ attachments,
58
65
  }: Props = $props();
59
66
 
60
67
  const composerSendIcon = $derived(panelLayout ? 'arrow-up' : sendIcon);
@@ -228,6 +235,7 @@
228
235
  onSend={handleComposerSend}
229
236
  onStop={() => onStop?.()}
230
237
  leading={attachControl}
238
+ {attachments}
231
239
  {sendAttention}
232
240
  />
233
241
  </div>
@@ -1,3 +1,4 @@
1
+ import type { Snippet } from 'svelte';
1
2
  import type { AttachmentInput } from '../types/attachment.js';
2
3
  export type ComposerModelOption = {
3
4
  id: string;
@@ -26,6 +27,11 @@ interface Props {
26
27
  sendIcon?: 'send' | 'arrow-up';
27
28
  /** Increment from the host to nudge Send before publish. */
28
29
  sendNudgeToken?: number;
30
+ /**
31
+ * What sits inside the message box above the text (the chips of the parts picked on the preview). The box draws nothing
32
+ * for it while this is not given, so a message with no parts looks as it always did.
33
+ */
34
+ attachments?: Snippet;
29
35
  }
30
36
  declare const ChatComposer: import("svelte").Component<Props, {}, "value">;
31
37
  type ChatComposer = ReturnType<typeof ChatComposer>;
@@ -0,0 +1,73 @@
1
+ <!--
2
+ Figma: Part Chip (component set 1882:6845 on the Canvas page, file GCC2aXrh3PEHlMWFaAOisR): Default, Hover, Active.
3
+
4
+ One chip per part the person picked on the preview, in the message box. The number on the badge is the number of the marker
5
+ on the part, so the two can be matched by eye. Its body opens the part's note over the part (and folds it again when it is
6
+ already open); the cross takes the part out of the message. A page that does not give `onOpen` gets a chip that only
7
+ says what it holds, as the chat has always shown it.
8
+ -->
9
+ <script lang="ts">
10
+ import IconX from '@tabler/icons-svelte/icons/x';
11
+
12
+ interface Props {
13
+ /** The number on the badge: the part's number on the preview. */
14
+ index: number;
15
+ /** What the chip says: the first words of the part's note, or the part's name while the note is empty. */
16
+ label: string;
17
+ /** The tooltip: the whole note. Defaults to the label. */
18
+ title?: string;
19
+ /** The part's note is open over the preview. */
20
+ active?: boolean;
21
+ /** Name of the cross, for screen readers and its tooltip. */
22
+ removeLabel?: string;
23
+ /** The body was clicked: show the part's note over the preview. */
24
+ onOpen?: () => void;
25
+ /** The cross was clicked: take the part out of the message. */
26
+ onRemove?: () => void;
27
+ class?: string;
28
+ }
29
+
30
+ let { index, label, title, active = false, removeLabel = 'Remove', onOpen, onRemove, class: className = '' }: Props = $props();
31
+ </script>
32
+
33
+ {#snippet chipBody()}
34
+ <span class="bg-brand text-brand-foreground flex size-4 shrink-0 items-center justify-center rounded-full text-[10px] leading-none font-semibold">
35
+ {index}
36
+ </span>
37
+ <span class="truncate">{label}</span>
38
+ {/snippet}
39
+
40
+ <div
41
+ class="prompt-chat-selected-element-chip text-label-small text-foreground duration-fast inline-flex h-7 max-w-full min-w-0 items-center gap-1.5 rounded-lg border ps-2 pe-1.5 transition-colors {active
42
+ ? 'border-brand bg-brand-subtle'
43
+ : 'border-border bg-background hover:bg-accent'} {className}"
44
+ title={title ?? label}
45
+ data-testid="chat-selected-element-chip"
46
+ data-active={active ? 'true' : undefined}
47
+ >
48
+ {#if onOpen}
49
+ <button
50
+ type="button"
51
+ class="focus-visible:ring-ring flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm focus-visible:ring-2 focus-visible:outline-hidden"
52
+ aria-pressed={active}
53
+ onclick={() => onOpen?.()}
54
+ >
55
+ {@render chipBody()}
56
+ </button>
57
+ {:else}
58
+ <span class="flex min-w-0 items-center gap-1.5">
59
+ {@render chipBody()}
60
+ </span>
61
+ {/if}
62
+ {#if onRemove}
63
+ <button
64
+ type="button"
65
+ class="text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-sm focus-visible:ring-2 focus-visible:outline-hidden"
66
+ aria-label={removeLabel}
67
+ title={removeLabel}
68
+ onclick={() => onRemove?.()}
69
+ >
70
+ <IconX class="size-4 stroke-2" aria-hidden="true" />
71
+ </button>
72
+ {/if}
73
+ </div>
@@ -0,0 +1,20 @@
1
+ interface Props {
2
+ /** The number on the badge: the part's number on the preview. */
3
+ index: number;
4
+ /** What the chip says: the first words of the part's note, or the part's name while the note is empty. */
5
+ label: string;
6
+ /** The tooltip: the whole note. Defaults to the label. */
7
+ title?: string;
8
+ /** The part's note is open over the preview. */
9
+ active?: boolean;
10
+ /** Name of the cross, for screen readers and its tooltip. */
11
+ removeLabel?: string;
12
+ /** The body was clicked: show the part's note over the preview. */
13
+ onOpen?: () => void;
14
+ /** The cross was clicked: take the part out of the message. */
15
+ onRemove?: () => void;
16
+ class?: string;
17
+ }
18
+ declare const SelectedElementChip: import("svelte").Component<Props, {}, "">;
19
+ type SelectedElementChip = ReturnType<typeof SelectedElementChip>;
20
+ export default SelectedElementChip;
@@ -14,4 +14,5 @@ export { default as AgentTurn } from './agent/AgentTurn.svelte';
14
14
  export { default as CodeCard } from './agent/CodeCard.svelte';
15
15
  export { default as GenerationModule } from './agent/GenerationModule.svelte';
16
16
  export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
17
+ export { default as SelectedElementChip } from './SelectedElementChip.svelte';
17
18
  export type { ComponentProps } from 'svelte';
@@ -19,3 +19,6 @@ export { default as AgentTurn } from './agent/AgentTurn.svelte';
19
19
  export { default as CodeCard } from './agent/CodeCard.svelte';
20
20
  export { default as GenerationModule } from './agent/GenerationModule.svelte';
21
21
  export { default as MemberAvatar } from './agent/MemberAvatar.svelte';
22
+ // The chip of a part the person picked on the preview (the numbered badge, the first words of its note, the cross), for a page
23
+ // that builds its own message box. Inside `Chat` the chips are drawn for the page, in the message box.
24
+ export { default as SelectedElementChip } from './SelectedElementChip.svelte';
@@ -7,5 +7,7 @@ export type { GenerationActivityPhase } from './generationActivity.js';
7
7
  export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './generationPlan.js';
8
8
  export type { GenerationPlanWire, MappedGenerationPlanCard, WidgetPlanTaskStatusWire, } from './generationPlan.js';
9
9
  export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
10
+ export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
11
+ export type { SelectedElementChipSource } from './selectedElementChip.js';
10
12
  export type { AgentAvatarSize, AgentLook, AvatarStart, FinishedGeneration, GenerationModulesView, SoundStateInput, TurnOutcome, TurnReplyFacts } from './agentTurn.js';
11
13
  export type { AttachmentType, AttachmentValidation, PendingAttachment, UploadStatus } from '../types/index.js';
@@ -9,3 +9,5 @@ export { readGenerationPlanFromMetadata, mapWidgetPlanToPlanCard, } from './gene
9
9
  // The assistant's turn: its avatar's looks, the judgement of a finished turn, who wrote a message, what is kept of the work.
10
10
  // A page that is not the chat (the workflows assistant) follows the same choreography through these.
11
11
  export { AGENT_AVATAR_PIXELS, CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID, MAX_KEPT_GENERATION_CHARS, agentAvatarLabelKey, agentAvatarPixels, agentLookSignature, avatarStartAfter, finishedGenerationBelongsTo, finishedModulesView, keepFinishedGeneration, keptWorkIsOutdated, liveAgentLook, liveModulesView, memberDisplayName, memberMailtoHref, memberTooltipEmail, normalizePromptText, pageNamesPeople, resolveChatMember, settledAgentLook, soundStateOf, turnOutcome } from './agentTurn.js';
12
+ // What the chip of a picked part says: the first words of its note, or its name while the note is empty.
13
+ export { CHIP_NOTE_MAX_CHARACTERS, CHIP_NOTE_MAX_WORDS, firstWords, selectedElementChipLabel, selectedElementChipTitle, selectedElementName, } from './selectedElementChip.js';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What a chip in the message box says about a part the person picked on the preview.
3
+ *
4
+ * Someone who picked a part and wrote a note on it ("Make this button bigger and round.") knows the chip by the first words
5
+ * of that note, so that is what it shows. A part with no note yet is named by what it is: "button · Shop the sale", the tag
6
+ * and the first words of the text it holds (Figma: Part Chip, component set 1882:6845, and Part Note, 1882:6867).
7
+ * The chip's tooltip keeps the whole note, so nothing is lost by the shortening.
8
+ *
9
+ * Plain TypeScript with no Svelte in it, so the tests run it in Node as it is.
10
+ */
11
+ /** How many words of a note a chip shows before it ends in an ellipsis. */
12
+ export declare const CHIP_NOTE_MAX_WORDS = 4;
13
+ /** The most characters of a note a chip shows, so that one long word cannot stretch the chip. */
14
+ export declare const CHIP_NOTE_MAX_CHARACTERS = 26;
15
+ /** How many words of the text a part holds name it, when it has no note. */
16
+ export declare const PART_TEXT_MAX_WORDS = 3;
17
+ /** The most characters of the text a part holds that name it. */
18
+ export declare const PART_TEXT_MAX_CHARACTERS = 24;
19
+ /** The shape of a part this file reads: the chat's `SelectedElementChatReference` has all of it, and a host's own type may too. */
20
+ export interface SelectedElementChipSource {
21
+ tagName?: string;
22
+ /** Compact label the host made when the part was picked (`<em> · to shared company work.`). */
23
+ label?: string;
24
+ /** What the part's text says. */
25
+ textSnippet?: string;
26
+ /** What the person wrote about the part. */
27
+ note?: string;
28
+ rect?: {
29
+ width: number;
30
+ height: number;
31
+ };
32
+ }
33
+ /**
34
+ * The first few words of a text, with an ellipsis when something was left out; an empty string when there is nothing to say.
35
+ * Counts words by spaces and characters by code points (so an emoji or a Chinese character is one), and cuts at the last
36
+ * space that fits rather than in the middle of a word, unless the first word alone is too long.
37
+ */
38
+ export declare function firstWords(text: string | null | undefined, maxWords?: number, maxCharacters?: number): string;
39
+ /**
40
+ * What a part is called when it has no note: its tag and the first words of its text ("button · Shop the sale"), or its size
41
+ * when it holds no text ("div · 240 × 80"). A box drawn on the preview has no tag, so it keeps the label it was given.
42
+ */
43
+ export declare function selectedElementName(part: SelectedElementChipSource): string;
44
+ /** The text on the chip: the first words of the note, or the name of the part while the note is empty. */
45
+ export declare function selectedElementChipLabel(part: SelectedElementChipSource): string;
46
+ /** The chip's tooltip: the whole note, or the name of the part while the note is empty. */
47
+ export declare function selectedElementChipTitle(part: SelectedElementChipSource): string;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * What a chip in the message box says about a part the person picked on the preview.
3
+ *
4
+ * Someone who picked a part and wrote a note on it ("Make this button bigger and round.") knows the chip by the first words
5
+ * of that note, so that is what it shows. A part with no note yet is named by what it is: "button · Shop the sale", the tag
6
+ * and the first words of the text it holds (Figma: Part Chip, component set 1882:6845, and Part Note, 1882:6867).
7
+ * The chip's tooltip keeps the whole note, so nothing is lost by the shortening.
8
+ *
9
+ * Plain TypeScript with no Svelte in it, so the tests run it in Node as it is.
10
+ */
11
+ /** How many words of a note a chip shows before it ends in an ellipsis. */
12
+ export const CHIP_NOTE_MAX_WORDS = 4;
13
+ /** The most characters of a note a chip shows, so that one long word cannot stretch the chip. */
14
+ export const CHIP_NOTE_MAX_CHARACTERS = 26;
15
+ /** How many words of the text a part holds name it, when it has no note. */
16
+ export const PART_TEXT_MAX_WORDS = 3;
17
+ /** The most characters of the text a part holds that name it. */
18
+ export const PART_TEXT_MAX_CHARACTERS = 24;
19
+ const ELLIPSIS = '…';
20
+ /**
21
+ * The first few words of a text, with an ellipsis when something was left out; an empty string when there is nothing to say.
22
+ * Counts words by spaces and characters by code points (so an emoji or a Chinese character is one), and cuts at the last
23
+ * space that fits rather than in the middle of a word, unless the first word alone is too long.
24
+ */
25
+ export function firstWords(text, maxWords = CHIP_NOTE_MAX_WORDS, maxCharacters = CHIP_NOTE_MAX_CHARACTERS) {
26
+ const collapsed = (text ?? '').replace(/\s+/g, ' ').trim();
27
+ if (!collapsed)
28
+ return '';
29
+ const words = collapsed.split(' ');
30
+ let kept = words.slice(0, Math.max(1, maxWords)).join(' ');
31
+ let leftOut = words.length > maxWords;
32
+ const characters = Array.from(kept);
33
+ if (characters.length > maxCharacters) {
34
+ const fitting = characters.slice(0, maxCharacters).join('');
35
+ const lastSpace = fitting.lastIndexOf(' ');
36
+ kept = lastSpace > 0 ? fitting.slice(0, lastSpace) : fitting;
37
+ leftOut = true;
38
+ }
39
+ if (!leftOut)
40
+ return kept;
41
+ // A comma or a full stop before the ellipsis reads as noise ("bigger,…"), so it goes.
42
+ return `${kept.replace(/[\s,;:.\-–—]+$/u, '')}${ELLIPSIS}`;
43
+ }
44
+ /** The label a host made, without the angle brackets of the tag (`<h2> · Title` → `h2 · Title`). */
45
+ function readableLabel(label) {
46
+ return (label ?? '').replace(/[<>]/g, '').replace(/\s+/g, ' ').trim();
47
+ }
48
+ /**
49
+ * What a part is called when it has no note: its tag and the first words of its text ("button · Shop the sale"), or its size
50
+ * when it holds no text ("div · 240 × 80"). A box drawn on the preview has no tag, so it keeps the label it was given.
51
+ */
52
+ export function selectedElementName(part) {
53
+ const tag = (part.tagName ?? '').trim().toLowerCase();
54
+ if (!tag || tag === 'area')
55
+ return readableLabel(part.label) || tag;
56
+ const text = firstWords(part.textSnippet, PART_TEXT_MAX_WORDS, PART_TEXT_MAX_CHARACTERS);
57
+ if (text)
58
+ return `${tag} · ${text}`;
59
+ const size = part.rect;
60
+ if (size && size.width > 0 && size.height > 0) {
61
+ return `${tag} · ${Math.round(size.width)} × ${Math.round(size.height)}`;
62
+ }
63
+ return tag;
64
+ }
65
+ /** The text on the chip: the first words of the note, or the name of the part while the note is empty. */
66
+ export function selectedElementChipLabel(part) {
67
+ return firstWords(part.note) || selectedElementName(part);
68
+ }
69
+ /** The chip's tooltip: the whole note, or the name of the part while the note is empty. */
70
+ export function selectedElementChipTitle(part) {
71
+ const note = (part.note ?? '').replace(/\s+/g, ' ').trim();
72
+ return note || selectedElementName(part);
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/chat",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",