@widgetic/chat 0.1.39 → 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.
Files changed (43) hide show
  1. package/README.md +71 -0
  2. package/dist/components/Chat.svelte +35 -1
  3. package/dist/components/Chat.svelte.d.ts +29 -0
  4. package/dist/components/ChatComposer.svelte +5 -1
  5. package/dist/components/ChatMessages.svelte +545 -210
  6. package/dist/components/ChatMessages.svelte.d.ts +18 -0
  7. package/dist/components/agent/AgentAvatar.svelte +153 -0
  8. package/dist/components/agent/AgentAvatar.svelte.d.ts +27 -0
  9. package/dist/components/agent/AgentTurn.svelte +64 -0
  10. package/dist/components/agent/AgentTurn.svelte.d.ts +32 -0
  11. package/dist/components/agent/AvatarBoundary.svelte +29 -0
  12. package/dist/components/agent/AvatarBoundary.svelte.d.ts +20 -0
  13. package/dist/components/agent/CodeCard.svelte +288 -0
  14. package/dist/components/agent/CodeCard.svelte.d.ts +12 -0
  15. package/dist/components/agent/GenerationModule.svelte +99 -0
  16. package/dist/components/agent/GenerationModule.svelte.d.ts +16 -0
  17. package/dist/components/agent/MemberAvatar.svelte +87 -0
  18. package/dist/components/agent/MemberAvatar.svelte.d.ts +8 -0
  19. package/dist/components/index.d.ts +5 -0
  20. package/dist/components/index.js +9 -0
  21. package/dist/i18n/messages.d.ts +31 -9
  22. package/dist/i18n/messages.js +31 -9
  23. package/dist/types/agent.d.ts +74 -0
  24. package/dist/types/agent.js +1 -0
  25. package/dist/types/index.d.ts +1 -0
  26. package/dist/types/index.js +2 -0
  27. package/dist/utils/agentTurn.d.ts +219 -0
  28. package/dist/utils/agentTurn.js +301 -0
  29. package/dist/utils/bubbleFit.d.ts +75 -0
  30. package/dist/utils/bubbleFit.js +116 -0
  31. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  32. package/dist/utils/bubbleShrinkWrap.js +360 -0
  33. package/dist/utils/codeHighlight.d.ts +13 -0
  34. package/dist/utils/codeHighlight.js +61 -0
  35. package/dist/utils/codePrettier.d.ts +6 -0
  36. package/dist/utils/codePrettier.js +34 -0
  37. package/dist/utils/codeStreamFormat.d.ts +90 -0
  38. package/dist/utils/codeStreamFormat.js +429 -0
  39. package/dist/utils/generationArchiveStore.d.ts +5 -0
  40. package/dist/utils/generationArchiveStore.js +1 -0
  41. package/dist/utils/index.d.ts +2 -0
  42. package/dist/utils/index.js +3 -0
  43. package/package.json +3 -2
@@ -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
+ };
@@ -0,0 +1,360 @@
1
+ import { chatLog, chatWarn } from './logger.js';
2
+ import { buildCanvasFont, countLinesByTops, findTightTextWidth, letterSpacingInPixels, widerWidthsToTry } from './bubbleFit.js';
3
+ /** An attribute the width given to a bubble can be told by: `tight` or `css` (left to CSS). Handy to look at in a browser. */
4
+ const FIT_ATTRIBUTE = 'data-bubble-fit';
5
+ /** What marks the element whose width is the room of the bubbles in it (the row the bubble sits in with the avatar of its author). */
6
+ const ROW_ATTRIBUTE = 'data-bubble-row';
7
+ const entries = new Set();
8
+ const entriesOfRow = new Map();
9
+ const lastWidthOfRow = new Map();
10
+ let rowObserver = null;
11
+ let scheduledFrame = null;
12
+ let listeningToFonts = false;
13
+ let pretextPromise = null;
14
+ let loadedPretext = null;
15
+ /** Each of these is said once, however many bubbles there are. */
16
+ let loggedFirstFit = false;
17
+ let loggedUnavailable = false;
18
+ let loggedDisagreement = false;
19
+ let loggedMeasureFailure = false;
20
+ // --- Pretext, loaded when first needed --------------------------------------------------------------------------
21
+ /** Pretext, or `null` when it cannot run here (not a browser, no canvas, an old browser, the module did not load). */
22
+ function loadPretext() {
23
+ if (!pretextPromise) {
24
+ pretextPromise =
25
+ typeof window === 'undefined'
26
+ ? Promise.resolve(null)
27
+ : import('@chenglou/pretext')
28
+ .then((module) => {
29
+ loadedPretext = module;
30
+ return module;
31
+ })
32
+ .catch((error) => {
33
+ if (!loggedUnavailable) {
34
+ loggedUnavailable = true;
35
+ chatWarn('[Chat] Pretext could not load: bubbles keep the width CSS gives them.', error);
36
+ }
37
+ return null;
38
+ });
39
+ }
40
+ return pretextPromise;
41
+ }
42
+ // --- the frame ----------------------------------------------------------------------------------------------------
43
+ function scheduleFlush() {
44
+ if (scheduledFrame !== null || typeof requestAnimationFrame === 'undefined')
45
+ return;
46
+ scheduledFrame = requestAnimationFrame(() => {
47
+ scheduledFrame = null;
48
+ void flushBubbles();
49
+ });
50
+ }
51
+ function pixelsOf(cssLength) {
52
+ const pixels = Number.parseFloat(cssLength);
53
+ return Number.isFinite(pixels) ? pixels : 0;
54
+ }
55
+ /** Reads what the search needs from a bubble's text element, or `null` when it cannot be measured now (hidden, or not a text Pretext knows). */
56
+ function readBubbleBox(node) {
57
+ const style = window.getComputedStyle(node);
58
+ if (style.display === 'none' || node.offsetWidth === 0)
59
+ return null;
60
+ const text = (node.textContent ?? '').replace(/\r\n?/g, '\n');
61
+ if (!text.trim())
62
+ return null;
63
+ // Pretext knows `white-space: normal` and `pre-wrap` (and `word-break: normal` and `keep-all`); other settings are left to CSS
64
+ const whiteSpace = style.whiteSpace === 'pre-wrap' || style.whiteSpace === 'break-spaces' ? 'pre-wrap' : style.whiteSpace === 'normal' ? 'normal' : null;
65
+ const wordBreak = style.wordBreak === 'keep-all' ? 'keep-all' : style.wordBreak === 'normal' ? 'normal' : null;
66
+ if (!whiteSpace || !wordBreak)
67
+ return null;
68
+ const font = buildCanvasFont({ fontStyle: style.fontStyle, fontWeight: style.fontWeight, fontSize: style.fontSize, fontFamily: style.fontFamily });
69
+ if (!font)
70
+ return null;
71
+ // Both sides are added, so the screen's direction does not change the sum; the logical names say that (the audit of the chat asks for them)
72
+ const paddingX = pixelsOf(style.paddingInlineStart) + pixelsOf(style.paddingInlineEnd);
73
+ const borderX = pixelsOf(style.borderInlineStartWidth) + pixelsOf(style.borderInlineEndWidth);
74
+ const sizesByBorderBox = style.boxSizing === 'border-box';
75
+ // The used width (a number of px for a block that is laid out); without it, the client width, which is rounded
76
+ const usedWidth = Number.parseFloat(style.width);
77
+ const contentWidth = Number.isFinite(usedWidth) ? (sizesByBorderBox ? usedWidth - paddingX - borderX : usedWidth) : node.clientWidth - paddingX;
78
+ if (!(contentWidth >= 1))
79
+ return null;
80
+ return {
81
+ text,
82
+ availableWidth: contentWidth,
83
+ extraWidth: sizesByBorderBox ? paddingX + borderX : 0,
84
+ font,
85
+ letterSpacing: letterSpacingInPixels(style.letterSpacing),
86
+ whiteSpace,
87
+ wordBreak
88
+ };
89
+ }
90
+ /** The tight width of one bubble's text, or `null` to leave the bubble to CSS. */
91
+ function computeTightWidth(pretext, entry, box) {
92
+ if (!box)
93
+ return null;
94
+ try {
95
+ // `prepare()` is the expensive part, done once per text and font; a new width only runs the arithmetic after it
96
+ const preparedKey = `${box.font}|${box.letterSpacing}|${box.whiteSpace}|${box.wordBreak}|${box.text}`;
97
+ if (!entry.prepared || entry.preparedKey !== preparedKey) {
98
+ entry.prepared = pretext.prepare(box.text, box.font, {
99
+ whiteSpace: box.whiteSpace,
100
+ ...(box.wordBreak === 'keep-all' ? { wordBreak: 'keep-all' } : {}),
101
+ ...(box.letterSpacing !== 0 ? { letterSpacing: box.letterSpacing } : {})
102
+ });
103
+ entry.preparedKey = preparedKey;
104
+ }
105
+ const prepared = entry.prepared;
106
+ const engine = {
107
+ naturalWidth: pretext.measureNaturalWidth(prepared),
108
+ measureWrap: (width) => pretext.measureLineStats(prepared, width)
109
+ };
110
+ return findTightTextWidth(engine, box.availableWidth);
111
+ }
112
+ catch (error) {
113
+ // No canvas, a font string the canvas cannot read: the bubble stays as CSS made it
114
+ entry.prepared = null;
115
+ entry.preparedKey = '';
116
+ if (!loggedMeasureFailure) {
117
+ loggedMeasureFailure = true;
118
+ chatWarn('[Chat] A bubble could not be measured with Pretext, and keeps the width CSS gives it.', error);
119
+ }
120
+ return null;
121
+ }
122
+ }
123
+ function writeWidth(node, contentWidth, extraWidth) {
124
+ if (contentWidth === null) {
125
+ node.style.removeProperty('width');
126
+ node.style.removeProperty('max-width');
127
+ node.setAttribute(FIT_ATTRIBUTE, 'css');
128
+ return;
129
+ }
130
+ node.style.width = `${contentWidth + extraWidth}px`;
131
+ // Never past the room, if the room shrinks before the bubble is measured again
132
+ node.style.maxWidth = '100%';
133
+ node.setAttribute(FIT_ATTRIBUTE, 'tight');
134
+ }
135
+ /** How many lines the browser made of the text of an element. */
136
+ function countRenderedLines(node) {
137
+ const range = document.createRange();
138
+ range.selectNodeContents(node);
139
+ return countLinesByTops(Array.from(range.getClientRects(), (rectangle) => rectangle.top));
140
+ }
141
+ /**
142
+ * Makes sure that no bubble came out with more lines than Pretext counted (which would be worse than CSS): it widens it a little,
143
+ * and gives it back to CSS if that does not help. Only runs on the bubbles that were given a width, and almost never has to act.
144
+ */
145
+ function verifyWrapping(measured) {
146
+ for (const { entry, box, tight } of measured) {
147
+ if (countRenderedLines(entry.node) <= tight.lineCount)
148
+ continue;
149
+ let fitted = false;
150
+ for (const widerWidth of widerWidthsToTry(tight.width, box.availableWidth)) {
151
+ writeWidth(entry.node, widerWidth, box.extraWidth);
152
+ if (countRenderedLines(entry.node) <= tight.lineCount) {
153
+ fitted = true;
154
+ break;
155
+ }
156
+ }
157
+ if (!fitted)
158
+ writeWidth(entry.node, null, box.extraWidth);
159
+ if (!loggedDisagreement) {
160
+ loggedDisagreement = true;
161
+ chatWarn(fitted
162
+ ? '[Chat] The browser wrapped a bubble in more lines than Pretext counted: it was widened a little.'
163
+ : '[Chat] The browser wrapped a bubble in more lines than Pretext counted: it keeps the width CSS gives it.', { font: box.font, lineCount: tight.lineCount });
164
+ }
165
+ }
166
+ }
167
+ /** Gives every bubble that needs it its tight width, all in one pass over the page. */
168
+ async function flushBubbles() {
169
+ const pretext = await loadPretext();
170
+ const pending = [...entries].filter((entry) => entry.dirty && entry.node.isConnected);
171
+ if (pending.length === 0)
172
+ return;
173
+ if (!pretext) {
174
+ // Nothing to measure with: hand every bubble back to CSS, once
175
+ for (const entry of pending) {
176
+ writeWidth(entry.node, null, 0);
177
+ entry.dirty = false;
178
+ }
179
+ return;
180
+ }
181
+ // A font that is still loading would be measured as its fallback: its end wakes this up again
182
+ if (typeof document !== 'undefined' && document.fonts && document.fonts.status === 'loading')
183
+ return;
184
+ try {
185
+ // 1) Write: let CSS decide each width again, so that what is read next is the room the bubble has, not the width of an earlier pass
186
+ for (const entry of pending) {
187
+ entry.node.style.removeProperty('width');
188
+ entry.node.style.removeProperty('max-width');
189
+ }
190
+ // 2) Read: one layout for all of them
191
+ const boxes = pending.map((entry) => readBubbleBox(entry.node));
192
+ // 3) Compute: no DOM in here
193
+ const tightWidths = pending.map((entry, index) => computeTightWidth(pretext, entry, boxes[index] ?? null));
194
+ // 4) Write: every width
195
+ const measured = [];
196
+ pending.forEach((entry, index) => {
197
+ const box = boxes[index] ?? null;
198
+ const tight = tightWidths[index] ?? null;
199
+ writeWidth(entry.node, tight ? tight.width : null, box ? box.extraWidth : 0);
200
+ if (box && tight)
201
+ measured.push({ entry, box, tight });
202
+ entry.dirty = false;
203
+ });
204
+ // 5) Verify what the browser did against what Pretext counted
205
+ verifyWrapping(measured);
206
+ if (!loggedFirstFit) {
207
+ loggedFirstFit = true;
208
+ chatLog('[Chat] Bubbles are sized to their text with Pretext.', { bubbles: pending.length, tight: measured.length });
209
+ }
210
+ }
211
+ catch (error) {
212
+ chatWarn('[Chat] Sizing the bubbles failed: they keep the width CSS gives them.', error);
213
+ for (const entry of pending) {
214
+ writeWidth(entry.node, null, 0);
215
+ entry.dirty = false;
216
+ }
217
+ }
218
+ }
219
+ // --- what wakes the bubbles up ------------------------------------------------------------------------------------
220
+ function markEveryBubbleDirty() {
221
+ for (const entry of entries)
222
+ entry.dirty = true;
223
+ scheduleFlush();
224
+ }
225
+ /** A web font finished loading: widths measured before were those of the fallback font. */
226
+ function handleFontsLoaded() {
227
+ loadedPretext?.clearCache();
228
+ for (const entry of entries) {
229
+ entry.prepared = null;
230
+ entry.preparedKey = '';
231
+ }
232
+ markEveryBubbleDirty();
233
+ }
234
+ function startListeningToFonts() {
235
+ if (listeningToFonts || typeof document === 'undefined' || !document.fonts)
236
+ return;
237
+ listeningToFonts = true;
238
+ document.fonts.addEventListener('loadingdone', handleFontsLoaded);
239
+ }
240
+ function stopListeningToFonts() {
241
+ if (!listeningToFonts || typeof document === 'undefined' || !document.fonts)
242
+ return;
243
+ listeningToFonts = false;
244
+ document.fonts.removeEventListener('loadingdone', handleFontsLoaded);
245
+ }
246
+ function observeRow(row, entry) {
247
+ let entriesInRow = entriesOfRow.get(row);
248
+ if (!entriesInRow) {
249
+ entriesInRow = new Set();
250
+ entriesOfRow.set(row, entriesInRow);
251
+ if (typeof ResizeObserver !== 'undefined') {
252
+ rowObserver ??= new ResizeObserver((records) => {
253
+ for (const record of records) {
254
+ const target = record.target;
255
+ const width = record.contentRect.width;
256
+ const previousWidth = lastWidthOfRow.get(target);
257
+ lastWidthOfRow.set(target, width);
258
+ // The first report only says where the row is; later ones matter only when its width changed (a new height is the
259
+ // bubble's own doing, and must not wake it up again)
260
+ if (previousWidth === undefined || Math.abs(previousWidth - width) < 0.5)
261
+ continue;
262
+ for (const entryInRow of entriesOfRow.get(target) ?? [])
263
+ entryInRow.dirty = true;
264
+ scheduleFlush();
265
+ }
266
+ });
267
+ rowObserver.observe(row);
268
+ }
269
+ }
270
+ entriesInRow.add(entry);
271
+ }
272
+ function unobserveRow(row, entry) {
273
+ const entriesInRow = entriesOfRow.get(row);
274
+ if (!entriesInRow)
275
+ return;
276
+ entriesInRow.delete(entry);
277
+ if (entriesInRow.size > 0)
278
+ return;
279
+ entriesOfRow.delete(row);
280
+ lastWidthOfRow.delete(row);
281
+ rowObserver?.unobserve(row);
282
+ }
283
+ /**
284
+ * 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
285
+ * a leak would show.
286
+ */
287
+ export function getBubbleShrinkWrapStats() {
288
+ return {
289
+ bubbles: entries.size,
290
+ rows: entriesOfRow.size,
291
+ watchingRows: rowObserver !== null,
292
+ listeningToFonts,
293
+ framePending: scheduledFrame !== null
294
+ };
295
+ }
296
+ // --- the action ---------------------------------------------------------------------------------------------------
297
+ /**
298
+ * 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
299
+ * text (`<p class="whitespace-pre-wrap">`), inside a bubble as wide as its content, and mark the row the bubble sits in with
300
+ * `data-bubble-row` (the element whose width is the room of the bubble; without one, the element's parent stands for it).
301
+ *
302
+ * Plain text only: a bubble with code blocks or other widgets in it keeps the width CSS gives it.
303
+ *
304
+ * @example
305
+ * <p class="whitespace-pre-wrap" use:shrinkWrapBubble={{ text: message.content, enabled: tightBubbles }}>{message.content}</p>
306
+ */
307
+ export function shrinkWrapBubble(node, options) {
308
+ let entry = null;
309
+ function attach() {
310
+ if (entry || typeof window === 'undefined')
311
+ return;
312
+ const row = node.closest(`[${ROW_ATTRIBUTE}]`) ?? node.parentElement;
313
+ entry = { node, row, dirty: true, preparedKey: '', prepared: null };
314
+ entries.add(entry);
315
+ if (row)
316
+ observeRow(row, entry);
317
+ startListeningToFonts();
318
+ scheduleFlush();
319
+ }
320
+ function detach() {
321
+ if (!entry)
322
+ return;
323
+ entries.delete(entry);
324
+ if (entry.row)
325
+ unobserveRow(entry.row, entry);
326
+ entry = null;
327
+ // The bubble goes back to the width CSS gives it
328
+ node.style.removeProperty('width');
329
+ node.style.removeProperty('max-width');
330
+ node.removeAttribute(FIT_ATTRIBUTE);
331
+ if (entries.size === 0) {
332
+ stopListeningToFonts();
333
+ rowObserver?.disconnect();
334
+ rowObserver = null;
335
+ if (scheduledFrame !== null && typeof cancelAnimationFrame !== 'undefined')
336
+ cancelAnimationFrame(scheduledFrame);
337
+ scheduledFrame = null;
338
+ }
339
+ }
340
+ if (options.enabled !== false)
341
+ attach();
342
+ return {
343
+ update(nextOptions) {
344
+ if (nextOptions.enabled !== false) {
345
+ if (entry) {
346
+ // A new text (or the same, re-rendered): measured again
347
+ entry.dirty = true;
348
+ scheduleFlush();
349
+ }
350
+ else
351
+ attach();
352
+ }
353
+ else
354
+ detach();
355
+ },
356
+ destroy() {
357
+ detach();
358
+ }
359
+ };
360
+ }
@@ -0,0 +1,13 @@
1
+ import type { CodeKind } from './codeStreamFormat.js';
2
+ /** Escapes the five characters that matter in HTML. */
3
+ export declare function escapeHtml(text: string): string;
4
+ /**
5
+ * The class prefix of the tokens the card draws (`wc-code-keyword`...), in place of highlight.js's own `hljs-`.
6
+ *
7
+ * A page's highlight.js theme, and the chat's own `CodeBlock`, paint `.hljs-keyword` and the like with rules that sit outside
8
+ * every cascade layer, and a rule outside the layers beats any utility class whatever its specificity. With another prefix no
9
+ * such theme can match the card's tokens, so the card's palette (Tailwind classes on the panel) is always the one that shows.
10
+ */
11
+ export declare const CODE_TOKEN_CLASS_PREFIX = "wc-code-";
12
+ /** The HTML of the code with its tokens in spans, or the code escaped when it has no grammar or the grammar fails. */
13
+ export declare function highlightCodeToHtml(code: string, kind: CodeKind): string;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Colours code for the code card: highlight.js turns the text into HTML whose spans carry the token classes (`hljs-keyword`,
3
+ * `hljs-tag`, `hljs-attr`...) that the card paints. The text is always escaped, so what the assistant wrote is never markup.
4
+ */
5
+ import hljs from 'highlight.js/lib/core';
6
+ import css from 'highlight.js/lib/languages/css';
7
+ import json from 'highlight.js/lib/languages/json';
8
+ import typescript from 'highlight.js/lib/languages/typescript';
9
+ import xml from 'highlight.js/lib/languages/xml';
10
+ import { chatWarn } from './logger.js';
11
+ // The grammars of what widgets are made of. (`CodeBlock` registers its own set on the same core: registering twice is harmless.)
12
+ hljs.registerLanguage('typescript', typescript);
13
+ hljs.registerLanguage('xml', xml);
14
+ hljs.registerLanguage('json', json);
15
+ hljs.registerLanguage('css', css);
16
+ /** The grammar for each kind of code: TSX is read by the TypeScript grammar, which knows JSX; a page or a component is markup. */
17
+ const HIGHLIGHT_LANGUAGE_BY_KIND = {
18
+ script: 'typescript',
19
+ markup: 'xml',
20
+ json: 'json',
21
+ plain: null
22
+ };
23
+ /** Escapes the five characters that matter in HTML. */
24
+ export function escapeHtml(text) {
25
+ return text
26
+ .replace(/&/g, '&amp;')
27
+ .replace(/</g, '&lt;')
28
+ .replace(/>/g, '&gt;')
29
+ .replace(/"/g, '&quot;')
30
+ .replace(/'/g, '&#039;');
31
+ }
32
+ /**
33
+ * The class prefix of the tokens the card draws (`wc-code-keyword`...), in place of highlight.js's own `hljs-`.
34
+ *
35
+ * A page's highlight.js theme, and the chat's own `CodeBlock`, paint `.hljs-keyword` and the like with rules that sit outside
36
+ * every cascade layer, and a rule outside the layers beats any utility class whatever its specificity. With another prefix no
37
+ * such theme can match the card's tokens, so the card's palette (Tailwind classes on the panel) is always the one that shows.
38
+ */
39
+ export const CODE_TOKEN_CLASS_PREFIX = 'wc-code-';
40
+ /** Gives the tokens of highlight.js's output the prefix of the card (a class like `function_` that has no prefix stays as it is). */
41
+ function renameTokenClasses(highlightedHtml) {
42
+ return highlightedHtml.replace(/class="([^"]*)"/g, (_match, classNames) => `class="${classNames.replace(/\bhljs-/g, CODE_TOKEN_CLASS_PREFIX)}"`);
43
+ }
44
+ /** Said once: a grammar that fails on one text will fail again on the next, and the code is shown plain either way. */
45
+ let hasReportedHighlightFailure = false;
46
+ /** The HTML of the code with its tokens in spans, or the code escaped when it has no grammar or the grammar fails. */
47
+ export function highlightCodeToHtml(code, kind) {
48
+ const language = HIGHLIGHT_LANGUAGE_BY_KIND[kind];
49
+ if (!language || code === '')
50
+ return escapeHtml(code);
51
+ try {
52
+ return renameTokenClasses(hljs.highlight(code, { language, ignoreIllegals: true }).value);
53
+ }
54
+ catch (error) {
55
+ if (!hasReportedHighlightFailure) {
56
+ hasReportedHighlightFailure = true;
57
+ chatWarn('[Chat] code card: the code could not be coloured, it is shown plain:', error);
58
+ }
59
+ return escapeHtml(code);
60
+ }
61
+ }
@@ -0,0 +1,6 @@
1
+ import type { FormatWithCursor } from './codeStreamFormat.js';
2
+ /**
3
+ * Formats a script (JavaScript, TypeScript, JSX or TSX: the `babel-ts` parser reads all four) and tells where the character at
4
+ * `cursorOffset` ended up. Rejects when the text does not parse, which the formatting of half-written code takes in stride.
5
+ */
6
+ export declare const formatScriptWithCursor: FormatWithCursor;
@@ -0,0 +1,34 @@
1
+ import { chatLog, chatWarn } from './logger.js';
2
+ /** How long a failed load is remembered: a card does not ask the network again for every line of code it formats. */
3
+ const RETRY_LOADING_AFTER_MS = 30_000;
4
+ /** The one load, shared by every card. */
5
+ let loadingPrettier = null;
6
+ function loadPrettier() {
7
+ if (!loadingPrettier) {
8
+ chatLog('[Chat] code card: loading Prettier');
9
+ loadingPrettier = Promise.all([
10
+ import('prettier/standalone'),
11
+ import('prettier/plugins/babel'),
12
+ import('prettier/plugins/estree')
13
+ ])
14
+ .then(([prettier, babel, estree]) => ({ prettier, plugins: [babel, estree] }))
15
+ .catch((error) => {
16
+ chatWarn('[Chat] code card: Prettier could not be loaded, the code is shown as it was written:', error);
17
+ // Forgotten after a while, so that a card opened later can try again
18
+ setTimeout(() => {
19
+ loadingPrettier = null;
20
+ }, RETRY_LOADING_AFTER_MS);
21
+ throw error;
22
+ });
23
+ }
24
+ return loadingPrettier;
25
+ }
26
+ /**
27
+ * Formats a script (JavaScript, TypeScript, JSX or TSX: the `babel-ts` parser reads all four) and tells where the character at
28
+ * `cursorOffset` ended up. Rejects when the text does not parse, which the formatting of half-written code takes in stride.
29
+ */
30
+ export const formatScriptWithCursor = async (text, cursorOffset) => {
31
+ const { prettier, plugins } = await loadPrettier();
32
+ const result = await prettier.formatWithCursor(text, { parser: 'babel-ts', plugins, cursorOffset });
33
+ return { formatted: result.formatted, cursorOffset: result.cursorOffset };
34
+ };