@widgetic/chat 0.1.39 → 0.1.41
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/Chat.svelte +63 -4
- package/dist/components/Chat.svelte.d.ts +31 -0
- package/dist/components/ChatComposer.svelte +5 -1
- package/dist/components/ChatMessages.svelte +574 -214
- package/dist/components/ChatMessages.svelte.d.ts +18 -0
- 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/index.d.ts +1 -0
- package/dist/i18n/index.js +1 -0
- package/dist/i18n/messages.d.ts +46 -9
- package/dist/i18n/messages.js +48 -10
- package/dist/i18n/sketchLocales.d.ts +2 -0
- package/dist/i18n/sketchLocales.js +83 -0
- package/dist/services/index.d.ts +5 -0
- package/dist/services/index.js +3 -0
- package/dist/services/sketchAssistantClient.d.ts +68 -0
- package/dist/services/sketchAssistantClient.js +73 -0
- package/dist/services/sketchAssistantOrchestrator.d.ts +45 -0
- package/dist/services/sketchAssistantOrchestrator.js +128 -0
- package/dist/services/sketchAssistantReply.d.ts +12 -0
- package/dist/services/sketchAssistantReply.js +28 -0
- package/dist/stores/chatStore.d.ts +1 -0
- package/dist/stores/chatStore.js +21 -0
- 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/types/message.d.ts +2 -0
- package/dist/utils/agentTurn.d.ts +219 -0
- package/dist/utils/agentTurn.js +301 -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/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 +5 -0
- package/dist/utils/generationArchiveStore.js +1 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +3 -0
- package/package.json +3 -2
|
@@ -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, '&')
|
|
27
|
+
.replace(/</g, '<')
|
|
28
|
+
.replace(/>/g, '>')
|
|
29
|
+
.replace(/"/g, '"')
|
|
30
|
+
.replace(/'/g, ''');
|
|
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
|
+
};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formatting code while it is still being written.
|
|
3
|
+
*
|
|
4
|
+
* The code card shows what the assistant has written so far, formatted the way Prettier would. Prettier needs a whole
|
|
5
|
+
* program, and what has arrived is the first part of one: it ends in the middle of a function, of a JSX element, of a line.
|
|
6
|
+
* So the text is cut after its last whole line, whatever is still open at the cut is closed (`)`, `]`, `}` and the closing
|
|
7
|
+
* tags of the elements that are open), the result is formatted, and the formatted text is cut again where the real text
|
|
8
|
+
* ended (Prettier maps a cursor position through the formatting for that), so the closing text added for the format never
|
|
9
|
+
* shows. What came after the cut (the line being typed) follows as it is.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is plain TypeScript with no import of Prettier (the caller hands in `format`), so it is tested as it is.
|
|
12
|
+
*/
|
|
13
|
+
/** What is known at one line break of the text. */
|
|
14
|
+
export interface LineEndSnapshot {
|
|
15
|
+
/** The index just after the line break: the text before it is whole lines. */
|
|
16
|
+
index: number;
|
|
17
|
+
/**
|
|
18
|
+
* What closes everything that is still open at this line break, or null when the line break is inside a string, a comment,
|
|
19
|
+
* a template or a tag (a cut there cannot be completed).
|
|
20
|
+
*/
|
|
21
|
+
closers: string | null;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Reads the text once and notes, at each of its last line breaks, what is open there. It knows strings, template literals,
|
|
25
|
+
* comments, regular expressions, brackets and JSX (tags, attributes, expression containers and text), which is what code
|
|
26
|
+
* made by an assistant for a widget is made of. It does not have to be a parser: whatever it gets wrong makes a cut that
|
|
27
|
+
* Prettier then refuses, and the next earlier cut is tried.
|
|
28
|
+
*
|
|
29
|
+
* @param source The code so far.
|
|
30
|
+
* @param keepLast How many of the last line breaks to keep (the cuts worth trying are the newest ones).
|
|
31
|
+
*/
|
|
32
|
+
export declare function scanLineEnds(source: string, keepLast?: number): LineEndSnapshot[];
|
|
33
|
+
/** What the code is, for the words that colour it and for whether Prettier can format it. */
|
|
34
|
+
export type CodeKind = 'script' | 'markup' | 'json' | 'plain';
|
|
35
|
+
/** Reads the start of the code to tell what it is. Code that starts in the middle of a file is plain: nothing is guessed. */
|
|
36
|
+
export declare function detectCodeKind(source: string): CodeKind;
|
|
37
|
+
/** The number of lines of the code, the way an editor counts them (a last line break does not start a line). */
|
|
38
|
+
export declare function countCodeLines(source: string): number;
|
|
39
|
+
/**
|
|
40
|
+
* Formats a whole text and tells where the character at `cursorOffset` ended up, the way Prettier's `formatWithCursor` does.
|
|
41
|
+
* It rejects when the text does not parse.
|
|
42
|
+
*/
|
|
43
|
+
export type FormatWithCursor = (text: string, cursorOffset: number) => Promise<{
|
|
44
|
+
formatted: string;
|
|
45
|
+
cursorOffset: number;
|
|
46
|
+
}>;
|
|
47
|
+
/** The code as the card shows it: a formatted start, then whatever has been written since as it was written. */
|
|
48
|
+
export interface FormattedCode {
|
|
49
|
+
/** The part that went through the formatter (empty when none did). */
|
|
50
|
+
formattedStart: string;
|
|
51
|
+
/** The rest, as it was written: the line being typed, or all of it when nothing could be formatted. */
|
|
52
|
+
writtenAfter: string;
|
|
53
|
+
/** What to draw: `formattedStart`, a line break, `writtenAfter`. */
|
|
54
|
+
text: string;
|
|
55
|
+
/** Whether any of it went through the formatter. */
|
|
56
|
+
isFormatted: boolean;
|
|
57
|
+
/** How many characters of the source the formatted start stands for. */
|
|
58
|
+
formattedSourceLength: number;
|
|
59
|
+
}
|
|
60
|
+
/** How many of the last line breaks are tried as the place to cut, newest first (each try is a run of Prettier). */
|
|
61
|
+
export declare const MAX_CUTS_TRIED = 8;
|
|
62
|
+
/**
|
|
63
|
+
* Whether the cut of a formatted text is the same code as the text it was cut for. Prettier never drops code, so a cut that
|
|
64
|
+
* is a lot shorter points at a wrong mapping of the cursor, and one that is a lot longer has kept the closing text.
|
|
65
|
+
*/
|
|
66
|
+
export declare function isFaithfulCut(sourcePrefix: string, formattedPrefix: string): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Formats the code that has arrived so far, as far as it can be formatted.
|
|
69
|
+
*
|
|
70
|
+
* With the whole text complete (`isComplete`) the whole text is tried first. Otherwise, or when that is refused, the text is
|
|
71
|
+
* cut after one of its last whole lines (newest first, `MAX_CUTS_TRIED` of them), what is still open there is closed, the
|
|
72
|
+
* result is formatted and cut again at the place the real text ended. Nothing parses at some cuts (a function with no body
|
|
73
|
+
* yet, a `try` with no `catch`): the next earlier one is tried. When none works the code is shown as written.
|
|
74
|
+
*
|
|
75
|
+
* It never rejects.
|
|
76
|
+
*/
|
|
77
|
+
export declare function formatCodeSoFar(source: string, format: FormatWithCursor, options: {
|
|
78
|
+
isComplete: boolean;
|
|
79
|
+
maxCutsTried?: number;
|
|
80
|
+
}): Promise<FormattedCode>;
|
|
81
|
+
/**
|
|
82
|
+
* A formatter that remembers its last result, so that a new character on the line being typed does not run Prettier again:
|
|
83
|
+
* only a new whole line (or the end of the code) does. The calls are not to overlap: the caller drops a result that was
|
|
84
|
+
* overtaken by a newer text (see `CodeCard`).
|
|
85
|
+
*/
|
|
86
|
+
export declare function createStreamingFormatter(format: FormatWithCursor): {
|
|
87
|
+
format(source: string, isComplete: boolean): Promise<FormattedCode>;
|
|
88
|
+
/** Forgets the last result (a new run starts, or the text is a different one). */
|
|
89
|
+
reset(): void;
|
|
90
|
+
};
|