@widgetic/chat 0.1.38 → 0.1.40
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 +71 -0
- package/dist/components/AttachmentDisplay.svelte +14 -4
- package/dist/components/Chat.svelte +131 -106
- package/dist/components/Chat.svelte.d.ts +29 -0
- package/dist/components/ChatComposer.svelte +5 -1
- package/dist/components/ChatMessages.svelte +595 -175
- package/dist/components/ChatMessages.svelte.d.ts +20 -0
- package/dist/components/CodeBlock.svelte +9 -1
- package/dist/components/ComposerAttachmentsTray.svelte +64 -0
- package/dist/components/ComposerAttachmentsTray.svelte.d.ts +11 -0
- package/dist/components/PanelChatHeader.svelte +26 -6
- package/dist/components/PanelChatHeader.svelte.d.ts +1 -0
- package/dist/components/PanelFollowUpSuggestions.svelte +2 -2
- package/dist/components/PanelSuggestionButtons.svelte +2 -1
- package/dist/components/agent/AgentAvatar.svelte +153 -0
- package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
- package/dist/components/agent/AgentTurn.svelte +64 -0
- package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
- package/dist/components/agent/AvatarBoundary.svelte +29 -0
- package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
- package/dist/components/agent/CodeCard.svelte +288 -0
- package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
- package/dist/components/agent/GenerationModule.svelte +99 -0
- package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
- package/dist/components/agent/MemberAvatar.svelte +87 -0
- package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
- package/dist/components/index.d.ts +5 -0
- package/dist/components/index.js +9 -0
- package/dist/i18n/messages.d.ts +32 -10
- package/dist/i18n/messages.js +32 -10
- package/dist/types/agent.d.ts +74 -0
- package/dist/types/agent.js +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +2 -0
- package/dist/utils/agentTurn.d.ts +219 -0
- package/dist/utils/agentTurn.js +301 -0
- package/dist/utils/attachmentPreviewUrl.d.ts +21 -0
- package/dist/utils/attachmentPreviewUrl.js +39 -0
- package/dist/utils/bubbleFit.d.ts +75 -0
- package/dist/utils/bubbleFit.js +116 -0
- package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
- package/dist/utils/bubbleShrinkWrap.js +360 -0
- package/dist/utils/chatImageUploadPrep.d.ts +22 -0
- package/dist/utils/chatImageUploadPrep.js +90 -0
- package/dist/utils/codeHighlight.d.ts +13 -0
- package/dist/utils/codeHighlight.js +61 -0
- package/dist/utils/codePrettier.d.ts +6 -0
- package/dist/utils/codePrettier.js +34 -0
- package/dist/utils/codeStreamFormat.d.ts +90 -0
- package/dist/utils/codeStreamFormat.js +429 -0
- package/dist/utils/generationArchiveStore.d.ts +15 -0
- package/dist/utils/generationArchiveStore.js +89 -0
- package/dist/utils/imageTransform.d.ts +12 -0
- package/dist/utils/imageTransform.js +45 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/suggestionDraft.d.ts +5 -0
- package/dist/utils/suggestionDraft.js +15 -0
- package/package.json +5 -4
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/** A turn that is not the newest, or has nothing to say about itself: small, still, calm. */
|
|
2
|
+
const RESTING_STILL_LOOK = { state: 'idle', size: 'small', live: false };
|
|
3
|
+
/**
|
|
4
|
+
* The look while a generation runs.
|
|
5
|
+
*
|
|
6
|
+
* - Waiting for the first word of the model: the avatar is large and thinks. A plan card or a question, when there is
|
|
7
|
+
* one, sits to its right.
|
|
8
|
+
* - Its reasoning streams: the avatar shrinks to the left and KEEPS THINKING for as long as the reasoning is being written.
|
|
9
|
+
* The words beside it say "Thinking…" (the thinking module's own title): the avatar carries no name or label.
|
|
10
|
+
* - What it writes next streams (the code, or the reply the model writes: the chat has no other stream than the reasoning and
|
|
11
|
+
* this one): still small, and now it WRITES; the code module's title says "Writing code…".
|
|
12
|
+
*
|
|
13
|
+
* (The mascot package maps the phases the same way: `thinking-stream` is its `thinking` state.)
|
|
14
|
+
*/
|
|
15
|
+
export function liveAgentLook(phase) {
|
|
16
|
+
switch (phase) {
|
|
17
|
+
case 'shimmer-only':
|
|
18
|
+
return { state: 'thinking', size: 'large', live: true };
|
|
19
|
+
case 'thinking-stream':
|
|
20
|
+
return { state: 'thinking', size: 'small', live: true };
|
|
21
|
+
case 'thinking-and-code':
|
|
22
|
+
case 'code-only':
|
|
23
|
+
return { state: 'writing', size: 'small', live: true };
|
|
24
|
+
case 'idle':
|
|
25
|
+
default:
|
|
26
|
+
return { ...RESTING_STILL_LOOK, live: true };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Judges a turn from its visible replies. The LAST reply decides how it ended; a commit or a completion line anywhere in
|
|
31
|
+
* the turn (or a generation that ran for it) makes an ordinary last reply a success.
|
|
32
|
+
*/
|
|
33
|
+
export function turnOutcome(replies, generationRanForTurn) {
|
|
34
|
+
const lastReply = replies[replies.length - 1];
|
|
35
|
+
if (!lastReply)
|
|
36
|
+
return generationRanForTurn ? 'success' : null;
|
|
37
|
+
if (lastReply.isStopped)
|
|
38
|
+
return 'stopped';
|
|
39
|
+
if (lastReply.isFailure)
|
|
40
|
+
return 'error';
|
|
41
|
+
if (lastReply.hasQuestion)
|
|
42
|
+
return 'question';
|
|
43
|
+
if (generationRanForTurn || replies.some((reply) => reply.hasCommit || reply.isCompletion))
|
|
44
|
+
return 'success';
|
|
45
|
+
return 'answer';
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The look of a turn that is not running. Only the newest turn moves, and only its conclusion is large (the success or
|
|
49
|
+
* the error avatar, or a question to answer): older turns are small still pictures, so a long chat keeps one mascot
|
|
50
|
+
* alive instead of one per message.
|
|
51
|
+
*/
|
|
52
|
+
export function settledAgentLook(outcome, isNewestTurn) {
|
|
53
|
+
if (!isNewestTurn)
|
|
54
|
+
return RESTING_STILL_LOOK;
|
|
55
|
+
switch (outcome) {
|
|
56
|
+
case 'success':
|
|
57
|
+
return { state: 'success', size: 'large', live: true };
|
|
58
|
+
case 'error':
|
|
59
|
+
return { state: 'error', size: 'large', live: true };
|
|
60
|
+
case 'question':
|
|
61
|
+
return { state: 'idle', size: 'large', live: true };
|
|
62
|
+
case 'stopped':
|
|
63
|
+
case 'answer':
|
|
64
|
+
default:
|
|
65
|
+
return { state: 'idle', size: 'small', live: true };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The live avatar of a run and the one of its ending are two avatars, one after the other, in the same place. The second one starts
|
|
70
|
+
* from how the first one looked when the run ended, so what the person watched carries on instead of being swapped: a Stop pressed
|
|
71
|
+
* while the avatar is still large shrinks it down to its small size, and the mascot calms from what it was doing; a conclusion
|
|
72
|
+
* grows out of the avatar of the work.
|
|
73
|
+
*
|
|
74
|
+
* Without a live avatar to take over from (the conversation was opened or reloaded after the run) it starts from the small one,
|
|
75
|
+
* which is where a conclusion has always grown out of.
|
|
76
|
+
*/
|
|
77
|
+
export function avatarStartAfter(lastLiveLook) {
|
|
78
|
+
if (!lastLiveLook)
|
|
79
|
+
return { startSize: 'small', startState: undefined };
|
|
80
|
+
return { startSize: lastLiveLook.size, startState: lastLiveLook.state };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The state of the avatar the person is looking at, for the page's sound to follow, or null when there is nothing to hear.
|
|
84
|
+
*
|
|
85
|
+
* - While a run works, the live avatar's own state: thinking when it starts, writing when code or the answer is written.
|
|
86
|
+
* - When it ends, the state of the newest turn's avatar: success or error say how it went, and idle (a question, a stop) says it
|
|
87
|
+
* is waiting.
|
|
88
|
+
* - Never for a conversation that was only opened: its newest turn may be left in `error` or `success`, but nothing happened in
|
|
89
|
+
* front of the person, so nothing is heard. Opening a chat must not play the sound of a failure.
|
|
90
|
+
* - Null as well while the newest turn has nothing to show yet (a prompt just sent, or a run that has ended a moment before its
|
|
91
|
+
* conclusion arrives): the sound keeps what it last heard.
|
|
92
|
+
*
|
|
93
|
+
* Only a change of this value is worth telling the sound about, and the caller tells it once for each.
|
|
94
|
+
*/
|
|
95
|
+
export function soundStateOf(input) {
|
|
96
|
+
if (input.runIsLive)
|
|
97
|
+
return input.liveLook.state;
|
|
98
|
+
if (!input.runWasWatched || input.newestTurnLook === null)
|
|
99
|
+
return null;
|
|
100
|
+
return input.newestTurnLook.state;
|
|
101
|
+
}
|
|
102
|
+
/** The side of the avatar in pixels. Without a page's own avatar the large one is only a little larger: a plain circle that big is noise. */
|
|
103
|
+
export const AGENT_AVATAR_PIXELS = {
|
|
104
|
+
/** The mascot's full drawing (64 px and up). */
|
|
105
|
+
largeWithPageAvatar: 80,
|
|
106
|
+
largeWithoutPageAvatar: 32,
|
|
107
|
+
/** The mascot's compact drawing, which still moves (28 px and up). */
|
|
108
|
+
small: 28
|
|
109
|
+
};
|
|
110
|
+
export function agentAvatarPixels(size, hasPageAvatar) {
|
|
111
|
+
if (size === 'small')
|
|
112
|
+
return AGENT_AVATAR_PIXELS.small;
|
|
113
|
+
return hasPageAvatar ? AGENT_AVATAR_PIXELS.largeWithPageAvatar : AGENT_AVATAR_PIXELS.largeWithoutPageAvatar;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The catalog key of what a screen reader says about the avatar in a state, or null when it says nothing: an avatar at rest
|
|
117
|
+
* sits beside the words of the turn, which are what is read (the others say what is going on, which no words beside it do).
|
|
118
|
+
*/
|
|
119
|
+
export function agentAvatarLabelKey(state) {
|
|
120
|
+
switch (state) {
|
|
121
|
+
case 'thinking':
|
|
122
|
+
return 'chat.generation.statusThinking';
|
|
123
|
+
case 'writing':
|
|
124
|
+
return 'chat.generation.statusWritingCode';
|
|
125
|
+
case 'success':
|
|
126
|
+
return 'chat.agent.avatar.success';
|
|
127
|
+
case 'error':
|
|
128
|
+
return 'chat.agent.avatar.error';
|
|
129
|
+
case 'idle':
|
|
130
|
+
default:
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** A stable text for a look, so the chat can say a change once and not on every redraw. */
|
|
135
|
+
export function agentLookSignature(look) {
|
|
136
|
+
return `${look.state}:${look.size}:${look.live ? 'live' : 'still'}`;
|
|
137
|
+
}
|
|
138
|
+
const NOTHING_SHOWN = {
|
|
139
|
+
showShimmer: false,
|
|
140
|
+
showThinking: false,
|
|
141
|
+
thinkingStreaming: false,
|
|
142
|
+
thinkingOpenByDefault: false,
|
|
143
|
+
showCode: false,
|
|
144
|
+
codeStreaming: false,
|
|
145
|
+
codeOpenByDefault: false
|
|
146
|
+
};
|
|
147
|
+
/** The modules while a generation runs. The thoughts fold away once the code starts, the code stays open while it streams. */
|
|
148
|
+
export function liveModulesView(phase) {
|
|
149
|
+
switch (phase) {
|
|
150
|
+
case 'shimmer-only':
|
|
151
|
+
return { ...NOTHING_SHOWN, showShimmer: true };
|
|
152
|
+
case 'thinking-stream':
|
|
153
|
+
return { ...NOTHING_SHOWN, showThinking: true, thinkingStreaming: true, thinkingOpenByDefault: true };
|
|
154
|
+
case 'thinking-and-code':
|
|
155
|
+
return { ...NOTHING_SHOWN, showThinking: true, showCode: true, codeStreaming: true, codeOpenByDefault: true };
|
|
156
|
+
case 'code-only':
|
|
157
|
+
return { ...NOTHING_SHOWN, showCode: true, codeStreaming: true, codeOpenByDefault: true };
|
|
158
|
+
case 'idle':
|
|
159
|
+
default:
|
|
160
|
+
return NOTHING_SHOWN;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** The modules under a conclusion: whatever was kept, closed, for the person to open. */
|
|
164
|
+
export function finishedModulesView(finished) {
|
|
165
|
+
if (!finished)
|
|
166
|
+
return NOTHING_SHOWN;
|
|
167
|
+
return {
|
|
168
|
+
...NOTHING_SHOWN,
|
|
169
|
+
showThinking: finished.thinking.trim().length > 0,
|
|
170
|
+
showCode: finished.code.trim().length > 0
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The most text kept of either part. A generation streams tails; the chat stitches them, and a runaway stream
|
|
175
|
+
* must not grow memory without end.
|
|
176
|
+
*/
|
|
177
|
+
export const MAX_KEPT_GENERATION_CHARS = 120_000;
|
|
178
|
+
/**
|
|
179
|
+
* A prompt as a way to recognise its turn. A message id is no use: the host swaps a made-up id for the saved one, and
|
|
180
|
+
* may reload the whole conversation after a generation. The words the person wrote survive both.
|
|
181
|
+
*/
|
|
182
|
+
export function normalizePromptText(content) {
|
|
183
|
+
return (content ?? '').replace(/\s+/g, ' ').trim();
|
|
184
|
+
}
|
|
185
|
+
/** What to keep of a generation that ended, or null when it left nothing to show. */
|
|
186
|
+
export function keepFinishedGeneration(input) {
|
|
187
|
+
const thinking = input.thinking.slice(-MAX_KEPT_GENERATION_CHARS);
|
|
188
|
+
const code = input.code.slice(-MAX_KEPT_GENERATION_CHARS);
|
|
189
|
+
if (thinking.trim().length === 0 && code.trim().length === 0)
|
|
190
|
+
return null;
|
|
191
|
+
return {
|
|
192
|
+
prompt: normalizePromptText(input.promptText),
|
|
193
|
+
thinking,
|
|
194
|
+
code,
|
|
195
|
+
thoughtSeconds: input.thoughtSeconds
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** Whether the kept work belongs under the turn of this prompt: the newest turn, found again by the words of its prompt. */
|
|
199
|
+
export function finishedGenerationBelongsTo(finished, newestTurnPromptText) {
|
|
200
|
+
if (!finished)
|
|
201
|
+
return false;
|
|
202
|
+
return finished.prompt === normalizePromptText(newestTurnPromptText);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Whether the work kept for a run is out of date because the person sent another prompt after the one that run answered.
|
|
206
|
+
* The words of a prompt sent again (a retry) are the same, so `finishedGenerationBelongsTo` cannot tell the new turn from the
|
|
207
|
+
* old one, and for as long as the host takes to save the prompt and start the run (the chat adds the message first) the new turn
|
|
208
|
+
* would show the last run's conclusion. The message the kept work answered tells them apart: a user message after it is a new turn.
|
|
209
|
+
*
|
|
210
|
+
* That message is found by its id, not by the object: the chat builds new message objects when a prompt is sent (it clears the
|
|
211
|
+
* marks of the last version first), while the id of a prompt is the saved one by the time its run ends, because the host
|
|
212
|
+
* saves a prompt before it starts the run.
|
|
213
|
+
*
|
|
214
|
+
* When there is no id, or no message with it in the list any more (the host loaded the conversation again, or the work came back
|
|
215
|
+
* from the archive, which knows only the words) there is nothing to tell by, and the words decide, as they always did.
|
|
216
|
+
*/
|
|
217
|
+
export function keptWorkIsOutdated(answeredMessageId, messagesInOrder) {
|
|
218
|
+
if (!answeredMessageId)
|
|
219
|
+
return false;
|
|
220
|
+
let answeredIndex = -1;
|
|
221
|
+
for (let index = messagesInOrder.length - 1; index >= 0; index--) {
|
|
222
|
+
if (messagesInOrder[index].id === answeredMessageId) {
|
|
223
|
+
answeredIndex = index;
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (answeredIndex === -1)
|
|
228
|
+
return false;
|
|
229
|
+
for (let index = answeredIndex + 1; index < messagesInOrder.length; index++) {
|
|
230
|
+
if (messagesInOrder[index].messageType === 'user')
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
// --- who wrote it -------------------------------------------------------------------------------------------
|
|
236
|
+
/** The `userId` the chat gives a message the signed-in person adds with `addUserMessage`, before the host has saved it and told the real one. */
|
|
237
|
+
export const CURRENT_USER_PLACEHOLDER_ID = 'current_user';
|
|
238
|
+
/**
|
|
239
|
+
* The `userId` the chat's own local service gives every message the person types: `Chat.sendMessage` shows the message at
|
|
240
|
+
* once, made by that service, and `onSaveMessage` swaps the id of the message but never this. A made-up id too: until the page
|
|
241
|
+
* loads the history again (and the messages carry the real ids), it stands for the signed-in person.
|
|
242
|
+
*/
|
|
243
|
+
export const LOCAL_SERVICE_USER_ID = 'test_user';
|
|
244
|
+
/** Every id the chat makes up for a message of the signed-in person that the page has not told the real id of. */
|
|
245
|
+
const MADE_UP_USER_IDS = new Set([CURRENT_USER_PLACEHOLDER_ID, LOCAL_SERVICE_USER_ID]);
|
|
246
|
+
/**
|
|
247
|
+
* Finds the person behind a message. The team the page gave wins (it is the list the page keeps up to date); the
|
|
248
|
+
* signed-in person comes next, which is also who the made-up ids of a message that is not saved yet stand for.
|
|
249
|
+
* Null when nobody can be named: the message then has no face and no tooltip, instead of a wrong one.
|
|
250
|
+
*/
|
|
251
|
+
export function resolveChatMember(userId, members, currentUser) {
|
|
252
|
+
const standsForCurrentUser = userId != null && MADE_UP_USER_IDS.has(userId);
|
|
253
|
+
const wantedId = standsForCurrentUser ? currentUser?.id : userId;
|
|
254
|
+
if (!wantedId)
|
|
255
|
+
return null;
|
|
256
|
+
const teamMember = members.find((member) => member.id === wantedId);
|
|
257
|
+
if (teamMember)
|
|
258
|
+
return teamMember;
|
|
259
|
+
if (currentUser && currentUser.id === wantedId)
|
|
260
|
+
return currentUser;
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
/** The text the initials of an avatar come from: the name, or the part of the e-mail before the @. Empty when there is neither. */
|
|
264
|
+
export function memberDisplayName(member) {
|
|
265
|
+
const name = (member?.name ?? '').trim();
|
|
266
|
+
if (name)
|
|
267
|
+
return name;
|
|
268
|
+
const email = (member?.email ?? '').trim();
|
|
269
|
+
return email ? (email.split('@')[0] ?? '') : '';
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The e-mail line of the tooltip over an avatar: the e-mail only, never a placeholder word. The same rule as the
|
|
273
|
+
* project header of the Widgetic site (`projectMemberTooltipEmail`), so a person sees the same thing in both places.
|
|
274
|
+
*/
|
|
275
|
+
export function memberTooltipEmail(email) {
|
|
276
|
+
const trimmed = (email ?? '').trim();
|
|
277
|
+
if (!trimmed)
|
|
278
|
+
return null;
|
|
279
|
+
if (trimmed.toLowerCase() === 'undefined')
|
|
280
|
+
return null;
|
|
281
|
+
return trimmed;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Where a click on an avatar goes: a `mailto:` link to the e-mail of the person, as the avatars of the project header of the
|
|
285
|
+
* Widgetic site do (`personMailtoHref`). Null when there is no e-mail to write to (the same rule as the tooltip's: never a
|
|
286
|
+
* placeholder word), and the avatar is then only a picture. The part before the @ is encoded (a `+` in it would otherwise be
|
|
287
|
+
* read as a space); the domain is left as it is.
|
|
288
|
+
*/
|
|
289
|
+
export function memberMailtoHref(email) {
|
|
290
|
+
const address = memberTooltipEmail(email);
|
|
291
|
+
if (!address)
|
|
292
|
+
return null;
|
|
293
|
+
const atIndex = address.indexOf('@');
|
|
294
|
+
if (atIndex < 0)
|
|
295
|
+
return `mailto:${encodeURIComponent(address)}`;
|
|
296
|
+
return `mailto:${encodeURIComponent(address.slice(0, atIndex))}@${address.slice(atIndex + 1)}`;
|
|
297
|
+
}
|
|
298
|
+
/** Whether the page told the chat anything about who is who: without it the chat draws no faces next to what people wrote. */
|
|
299
|
+
export function pageNamesPeople(members, currentUser) {
|
|
300
|
+
return members.length > 0 || Boolean(currentUser?.id);
|
|
301
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AttachmentInput } from '../types/attachment.js';
|
|
2
|
+
/**
|
|
3
|
+
* Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
|
|
4
|
+
*
|
|
5
|
+
* It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
|
|
6
|
+
* value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
|
|
7
|
+
* The page gives the address back when the attachment is removed or the draft is cleared.
|
|
8
|
+
*
|
|
9
|
+
* @param file The file the person picked.
|
|
10
|
+
* @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createLocalPreviewUrl(file: File | null | undefined): string | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
|
|
15
|
+
* address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
|
|
16
|
+
* is safe to call from a template or a derived value.
|
|
17
|
+
*
|
|
18
|
+
* @param attachment The attachment of the composer tray.
|
|
19
|
+
* @returns An address a picture can be drawn from, or '' when the attachment has none yet.
|
|
20
|
+
*/
|
|
21
|
+
export declare function readAttachmentPreviewUrl(attachment: Pick<AttachmentInput, 'preview' | 'uploadedUrl' | 'persistedDataUrl'> | null | undefined): string;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Kinds of file that have a picture to draw in the composer tray: images, videos and PDFs. */
|
|
2
|
+
function fileTypeHasLocalPreview(fileType) {
|
|
3
|
+
const type = (fileType || '').toLowerCase();
|
|
4
|
+
return type.startsWith('image/') || type.startsWith('video/') || type === 'application/pdf';
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Makes the address the composer tray draws a picked file with — a `blob:` address of the file on this page.
|
|
8
|
+
*
|
|
9
|
+
* It is made once, when the file is attached, and not while the tray draws: the tray reads the address inside a derived
|
|
10
|
+
* value, and Svelte does not allow a write to state there (the picture of a tile used to stay empty for that reason).
|
|
11
|
+
* The page gives the address back when the attachment is removed or the draft is cleared.
|
|
12
|
+
*
|
|
13
|
+
* @param file The file the person picked.
|
|
14
|
+
* @returns The `blob:` address, or `undefined` for a file that has no picture to show (a text file, say) or when the browser refuses.
|
|
15
|
+
*/
|
|
16
|
+
export function createLocalPreviewUrl(file) {
|
|
17
|
+
if (!file || !fileTypeHasLocalPreview(file.type))
|
|
18
|
+
return undefined;
|
|
19
|
+
try {
|
|
20
|
+
return URL.createObjectURL(file);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.warn('[Chat] Could not make a local preview of the attached file:', error);
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The address the tray draws an attachment with, in the order of what is best known: the preview of the page, the CDN
|
|
29
|
+
* address of the upload, then the `data:` copy the draft keeps. It only reads: it never writes to the attachment, so it
|
|
30
|
+
* is safe to call from a template or a derived value.
|
|
31
|
+
*
|
|
32
|
+
* @param attachment The attachment of the composer tray.
|
|
33
|
+
* @returns An address a picture can be drawn from, or '' when the attachment has none yet.
|
|
34
|
+
*/
|
|
35
|
+
export function readAttachmentPreviewUrl(attachment) {
|
|
36
|
+
if (!attachment)
|
|
37
|
+
return '';
|
|
38
|
+
return attachment.preview || attachment.uploadedUrl || attachment.persistedDataUrl || '';
|
|
39
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of tight chat bubbles, apart from the page.
|
|
3
|
+
*
|
|
4
|
+
* CSS gives a bubble whose text wraps the whole `max-width`, however short its lines (it picks the width of a box before it
|
|
5
|
+
* breaks the lines), which leaves dead space beside them. The narrowest width that still wraps to the same number of lines has
|
|
6
|
+
* to be searched for, and that needs the text measured at several widths: what Pretext does with plain arithmetic, without
|
|
7
|
+
* touching the DOM. This file holds the search and a few small helpers, with no import of Pretext and nothing from the browser,
|
|
8
|
+
* so they run in Node and are tested there with a fake text engine. The browser side is `bubbleShrinkWrap.ts`.
|
|
9
|
+
*/
|
|
10
|
+
/** How a text wraps in a box of one width. */
|
|
11
|
+
export interface WrapStats {
|
|
12
|
+
/** How many lines the text makes. */
|
|
13
|
+
lineCount: number;
|
|
14
|
+
/** How wide the widest of those lines is, in px. */
|
|
15
|
+
maxLineWidth: number;
|
|
16
|
+
}
|
|
17
|
+
/** What the search needs to know about one text: Pretext's prepared text answers it, a fake one does in the tests. */
|
|
18
|
+
export interface BubbleTextEngine {
|
|
19
|
+
/** The width of the widest line when only the explicit line breaks apply (CSS `max-content`), in px. */
|
|
20
|
+
naturalWidth: number;
|
|
21
|
+
/** How the text wraps in a box this wide. */
|
|
22
|
+
measureWrap(width: number): WrapStats;
|
|
23
|
+
}
|
|
24
|
+
/** The width a bubble's text is given, and the number of lines it makes there. */
|
|
25
|
+
export interface TightTextWidth {
|
|
26
|
+
/** Whole px: the widest line of the narrowest wrapping that keeps the line count. */
|
|
27
|
+
width: number;
|
|
28
|
+
/** How many lines the text makes at that width. */
|
|
29
|
+
lineCount: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The narrowest width, in whole px, at which a text still wraps to the same number of lines it makes in `availableWidth`.
|
|
33
|
+
*
|
|
34
|
+
* Returns `null` when CSS cannot do better, so the bubble is left alone: there is no room to measure, the text does not wrap
|
|
35
|
+
* (CSS `fit-content` is already as wide as its widest line, and that is the case of most messages), or the measurements are not
|
|
36
|
+
* usable. A narrower width than the answer would add a line; a wider one would only add dead space.
|
|
37
|
+
*
|
|
38
|
+
* It is the algorithm of the Pretext "bubbles" demo: a binary search over the line count (more lines the narrower the box, never
|
|
39
|
+
* fewer), then the widest line at the width found.
|
|
40
|
+
*
|
|
41
|
+
* @param engine How the text wraps at a given width.
|
|
42
|
+
* @param availableWidth The room the text has when the bubble is as wide as it may be, in px (the content box CSS gives it).
|
|
43
|
+
*/
|
|
44
|
+
export declare function findTightTextWidth(engine: BubbleTextEngine, availableWidth: number): TightTextWidth | null;
|
|
45
|
+
/**
|
|
46
|
+
* The widths to try, in order, when the browser wraps a text in more lines than Pretext counted at `width`: the width itself,
|
|
47
|
+
* then a little wider (a pixel or two of difference in how the browser and the canvas measure a line), never past the room.
|
|
48
|
+
*/
|
|
49
|
+
export declare function widerWidthsToTry(width: number, maxWidth: number): number[];
|
|
50
|
+
/**
|
|
51
|
+
* How many lines a set of text boxes makes, from the top edge of each (the boxes of one line share a top, give or take the
|
|
52
|
+
* odd pixel of a link or a bold word in it).
|
|
53
|
+
*
|
|
54
|
+
* @param tops The `top` of each client rectangle of the text.
|
|
55
|
+
* @param tolerance How far two tops may be apart and still be the same line, in px.
|
|
56
|
+
*/
|
|
57
|
+
export declare function countLinesByTops(tops: readonly number[], tolerance?: number): number;
|
|
58
|
+
/** The parts of an element's computed style the canvas font string is made of. */
|
|
59
|
+
export interface FontParts {
|
|
60
|
+
fontStyle: string;
|
|
61
|
+
fontWeight: string;
|
|
62
|
+
fontSize: string;
|
|
63
|
+
fontFamily: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The canvas `font` shorthand Pretext measures with, from computed style: `italic 500 14px Inter, sans-serif`.
|
|
67
|
+
* (`getComputedStyle(...).font` is empty in some browsers, so the shorthand is put together from its parts.) An empty answer
|
|
68
|
+
* means the style cannot say, and the text is left to CSS.
|
|
69
|
+
*/
|
|
70
|
+
export declare function buildCanvasFont(parts: FontParts): string;
|
|
71
|
+
/**
|
|
72
|
+
* The letter spacing, in px, of a computed `letter-spacing` value: `normal` is none, `0.5px` is 0.5. Anything that is not a
|
|
73
|
+
* length in px (the browser always answers in px) counts as none.
|
|
74
|
+
*/
|
|
75
|
+
export declare function letterSpacingInPixels(computedLetterSpacing: string): number;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The arithmetic of tight chat bubbles, apart from the page.
|
|
3
|
+
*
|
|
4
|
+
* CSS gives a bubble whose text wraps the whole `max-width`, however short its lines (it picks the width of a box before it
|
|
5
|
+
* breaks the lines), which leaves dead space beside them. The narrowest width that still wraps to the same number of lines has
|
|
6
|
+
* to be searched for, and that needs the text measured at several widths: what Pretext does with plain arithmetic, without
|
|
7
|
+
* touching the DOM. This file holds the search and a few small helpers, with no import of Pretext and nothing from the browser,
|
|
8
|
+
* so they run in Node and are tested there with a fake text engine. The browser side is `bubbleShrinkWrap.ts`.
|
|
9
|
+
*/
|
|
10
|
+
/** True when a measurement can be used: finite numbers and at least no negative line count. */
|
|
11
|
+
function isUsableStats(stats) {
|
|
12
|
+
return !!stats && Number.isFinite(stats.lineCount) && stats.lineCount >= 0 && Number.isFinite(stats.maxLineWidth) && stats.maxLineWidth >= 0;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The narrowest width, in whole px, at which a text still wraps to the same number of lines it makes in `availableWidth`.
|
|
16
|
+
*
|
|
17
|
+
* Returns `null` when CSS cannot do better, so the bubble is left alone: there is no room to measure, the text does not wrap
|
|
18
|
+
* (CSS `fit-content` is already as wide as its widest line, and that is the case of most messages), or the measurements are not
|
|
19
|
+
* usable. A narrower width than the answer would add a line; a wider one would only add dead space.
|
|
20
|
+
*
|
|
21
|
+
* It is the algorithm of the Pretext "bubbles" demo: a binary search over the line count (more lines the narrower the box, never
|
|
22
|
+
* fewer), then the widest line at the width found.
|
|
23
|
+
*
|
|
24
|
+
* @param engine How the text wraps at a given width.
|
|
25
|
+
* @param availableWidth The room the text has when the bubble is as wide as it may be, in px (the content box CSS gives it).
|
|
26
|
+
*/
|
|
27
|
+
export function findTightTextWidth(engine, availableWidth) {
|
|
28
|
+
if (!Number.isFinite(availableWidth))
|
|
29
|
+
return null;
|
|
30
|
+
// Whole pixels, so that the explicit width never goes past the room the bubble has
|
|
31
|
+
const maxWidth = Math.floor(availableWidth);
|
|
32
|
+
if (maxWidth < 1)
|
|
33
|
+
return null;
|
|
34
|
+
// Not wrapped at all: the bubble is already as wide as its widest line
|
|
35
|
+
if (!(engine.naturalWidth > availableWidth))
|
|
36
|
+
return null;
|
|
37
|
+
const atAvailable = engine.measureWrap(availableWidth);
|
|
38
|
+
if (!isUsableStats(atAvailable) || atAvailable.lineCount < 2)
|
|
39
|
+
return null;
|
|
40
|
+
const atMax = maxWidth === availableWidth ? atAvailable : engine.measureWrap(maxWidth);
|
|
41
|
+
// Rounding the room down would already cost a line: leave it to CSS
|
|
42
|
+
if (!isUsableStats(atMax) || atMax.lineCount > atAvailable.lineCount)
|
|
43
|
+
return null;
|
|
44
|
+
// The narrowest whole width that keeps the line count (it never gets fewer lines when narrower, so the search is a bisection)
|
|
45
|
+
let narrowest = 1;
|
|
46
|
+
let widest = maxWidth;
|
|
47
|
+
while (narrowest < widest) {
|
|
48
|
+
const middle = Math.floor((narrowest + widest) / 2);
|
|
49
|
+
const atMiddle = engine.measureWrap(middle);
|
|
50
|
+
if (isUsableStats(atMiddle) && atMiddle.lineCount <= atAvailable.lineCount)
|
|
51
|
+
widest = middle;
|
|
52
|
+
else
|
|
53
|
+
narrowest = middle + 1;
|
|
54
|
+
}
|
|
55
|
+
const atTight = engine.measureWrap(narrowest);
|
|
56
|
+
if (!isUsableStats(atTight) || atTight.lineCount > atAvailable.lineCount)
|
|
57
|
+
return null;
|
|
58
|
+
return { width: Math.min(Math.ceil(atTight.maxLineWidth), maxWidth), lineCount: atTight.lineCount };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The widths to try, in order, when the browser wraps a text in more lines than Pretext counted at `width`: the width itself,
|
|
62
|
+
* then a little wider (a pixel or two of difference in how the browser and the canvas measure a line), never past the room.
|
|
63
|
+
*/
|
|
64
|
+
export function widerWidthsToTry(width, maxWidth) {
|
|
65
|
+
const steps = [0, 1, 2, 4, 8];
|
|
66
|
+
const widths = [];
|
|
67
|
+
for (const step of steps) {
|
|
68
|
+
const candidate = Math.min(width + step, Math.floor(maxWidth));
|
|
69
|
+
if (candidate >= 1 && !widths.includes(candidate))
|
|
70
|
+
widths.push(candidate);
|
|
71
|
+
}
|
|
72
|
+
return widths;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* How many lines a set of text boxes makes, from the top edge of each (the boxes of one line share a top, give or take the
|
|
76
|
+
* odd pixel of a link or a bold word in it).
|
|
77
|
+
*
|
|
78
|
+
* @param tops The `top` of each client rectangle of the text.
|
|
79
|
+
* @param tolerance How far two tops may be apart and still be the same line, in px.
|
|
80
|
+
*/
|
|
81
|
+
export function countLinesByTops(tops, tolerance = 3) {
|
|
82
|
+
const sorted = tops.filter((top) => Number.isFinite(top)).sort((first, second) => first - second);
|
|
83
|
+
let lineCount = 0;
|
|
84
|
+
let lineTop = Number.NEGATIVE_INFINITY;
|
|
85
|
+
for (const top of sorted) {
|
|
86
|
+
if (top - lineTop > tolerance) {
|
|
87
|
+
lineCount += 1;
|
|
88
|
+
lineTop = top;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return lineCount;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The canvas `font` shorthand Pretext measures with, from computed style: `italic 500 14px Inter, sans-serif`.
|
|
95
|
+
* (`getComputedStyle(...).font` is empty in some browsers, so the shorthand is put together from its parts.) An empty answer
|
|
96
|
+
* means the style cannot say, and the text is left to CSS.
|
|
97
|
+
*/
|
|
98
|
+
export function buildCanvasFont(parts) {
|
|
99
|
+
const size = parts.fontSize?.trim();
|
|
100
|
+
const family = parts.fontFamily?.trim();
|
|
101
|
+
if (!size || !family)
|
|
102
|
+
return '';
|
|
103
|
+
const style = parts.fontStyle && parts.fontStyle !== 'normal' ? `${parts.fontStyle} ` : '';
|
|
104
|
+
const weight = parts.fontWeight && parts.fontWeight !== 'normal' ? `${parts.fontWeight} ` : '';
|
|
105
|
+
return `${style}${weight}${size} ${family}`;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The letter spacing, in px, of a computed `letter-spacing` value: `normal` is none, `0.5px` is 0.5. Anything that is not a
|
|
109
|
+
* length in px (the browser always answers in px) counts as none.
|
|
110
|
+
*/
|
|
111
|
+
export function letterSpacingInPixels(computedLetterSpacing) {
|
|
112
|
+
if (!computedLetterSpacing || computedLetterSpacing === 'normal')
|
|
113
|
+
return 0;
|
|
114
|
+
const pixels = Number.parseFloat(computedLetterSpacing);
|
|
115
|
+
return Number.isFinite(pixels) && computedLetterSpacing.trim().endsWith('px') ? pixels : 0;
|
|
116
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** What the action takes. */
|
|
2
|
+
export interface ShrinkWrapOptions {
|
|
3
|
+
/** The text the bubble shows. The width is read from what is laid out; a change of the text is what makes the bubble measured again. */
|
|
4
|
+
text: string;
|
|
5
|
+
/** Turns it off: the bubble goes back to the width CSS gives it. Default true. */
|
|
6
|
+
enabled?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* What is held on to right now, for tests and the demo page: when every chat is gone all of it must be back to zero, which is how
|
|
10
|
+
* a leak would show.
|
|
11
|
+
*/
|
|
12
|
+
export declare function getBubbleShrinkWrapStats(): {
|
|
13
|
+
bubbles: number;
|
|
14
|
+
rows: number;
|
|
15
|
+
watchingRows: boolean;
|
|
16
|
+
listeningToFonts: boolean;
|
|
17
|
+
framePending: boolean;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Sizes the text element of a bubble to the narrowest width that keeps its number of lines. Put it on the element that holds the
|
|
21
|
+
* text (`<p class="whitespace-pre-wrap">`), inside a bubble as wide as its content, and mark the row the bubble sits in with
|
|
22
|
+
* `data-bubble-row` (the element whose width is the room of the bubble; without one, the element's parent stands for it).
|
|
23
|
+
*
|
|
24
|
+
* Plain text only: a bubble with code blocks or other widgets in it keeps the width CSS gives it.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* <p class="whitespace-pre-wrap" use:shrinkWrapBubble={{ text: message.content, enabled: tightBubbles }}>{message.content}</p>
|
|
28
|
+
*/
|
|
29
|
+
export declare function shrinkWrapBubble(node: HTMLElement, options: ShrinkWrapOptions): {
|
|
30
|
+
update(nextOptions: ShrinkWrapOptions): void;
|
|
31
|
+
destroy(): void;
|
|
32
|
+
};
|