@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.
Files changed (58) hide show
  1. package/README.md +71 -0
  2. package/dist/components/Chat.svelte +63 -4
  3. package/dist/components/Chat.svelte.d.ts +31 -0
  4. package/dist/components/ChatComposer.svelte +5 -1
  5. package/dist/components/ChatMessages.svelte +574 -214
  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/index.d.ts +1 -0
  22. package/dist/i18n/index.js +1 -0
  23. package/dist/i18n/messages.d.ts +46 -9
  24. package/dist/i18n/messages.js +48 -10
  25. package/dist/i18n/sketchLocales.d.ts +2 -0
  26. package/dist/i18n/sketchLocales.js +83 -0
  27. package/dist/services/index.d.ts +5 -0
  28. package/dist/services/index.js +3 -0
  29. package/dist/services/sketchAssistantClient.d.ts +68 -0
  30. package/dist/services/sketchAssistantClient.js +73 -0
  31. package/dist/services/sketchAssistantOrchestrator.d.ts +45 -0
  32. package/dist/services/sketchAssistantOrchestrator.js +128 -0
  33. package/dist/services/sketchAssistantReply.d.ts +12 -0
  34. package/dist/services/sketchAssistantReply.js +28 -0
  35. package/dist/stores/chatStore.d.ts +1 -0
  36. package/dist/stores/chatStore.js +21 -0
  37. package/dist/types/agent.d.ts +74 -0
  38. package/dist/types/agent.js +1 -0
  39. package/dist/types/index.d.ts +1 -0
  40. package/dist/types/index.js +2 -0
  41. package/dist/types/message.d.ts +2 -0
  42. package/dist/utils/agentTurn.d.ts +219 -0
  43. package/dist/utils/agentTurn.js +301 -0
  44. package/dist/utils/bubbleFit.d.ts +75 -0
  45. package/dist/utils/bubbleFit.js +116 -0
  46. package/dist/utils/bubbleShrinkWrap.d.ts +32 -0
  47. package/dist/utils/bubbleShrinkWrap.js +360 -0
  48. package/dist/utils/codeHighlight.d.ts +13 -0
  49. package/dist/utils/codeHighlight.js +61 -0
  50. package/dist/utils/codePrettier.d.ts +6 -0
  51. package/dist/utils/codePrettier.js +34 -0
  52. package/dist/utils/codeStreamFormat.d.ts +90 -0
  53. package/dist/utils/codeStreamFormat.js +429 -0
  54. package/dist/utils/generationArchiveStore.d.ts +5 -0
  55. package/dist/utils/generationArchiveStore.js +1 -0
  56. package/dist/utils/index.d.ts +2 -0
  57. package/dist/utils/index.js +3 -0
  58. package/package.json +3 -2
@@ -1,5 +1,6 @@
1
1
  import type { ChatMessage, ChatContext } from '../types/index.js';
2
2
  import type { ClarificationSuggestion, DesignControlRequest, VersionRating } from '../types/message.js';
3
+ import type { AgentAvatarRenderer, AgentSoundPlayer, ChatMember } from '../types/agent.js';
3
4
  import { type VersionThumb } from '../utils/versionRatings.js';
4
5
  import type { Snippet } from 'svelte';
5
6
  import { type GenerationPlanWire } from '../utils/generationPlan.js';
@@ -95,6 +96,23 @@ interface Props {
95
96
  onRequestOlderMessages?: () => Promise<boolean | void>;
96
97
  /** Widget creator side panel: Figma empty / follow-up suggestion cards. */
97
98
  panelLayout?: boolean;
99
+ /**
100
+ * The people of the project's team. A message a person wrote gets that person's picture (or initials) at its right, and
101
+ * their e-mail while the pointer is on it.
102
+ */
103
+ members?: ChatMember[];
104
+ /** The signed-in person: who wrote the messages they just sent, and anything no member matches. */
105
+ currentUser?: ChatMember | null;
106
+ /** How the assistant's avatar is drawn (the Scribble Mascot in the Widgetic apps). A plain round avatar without it. */
107
+ renderAgentAvatar?: AgentAvatarRenderer;
108
+ /** Lets the avatar be heard: told its state once for each change, for runs the person watched. Silent without it. */
109
+ agentSound?: AgentSoundPlayer;
110
+ /**
111
+ * Sizes the bubbles of what people wrote to their text with Pretext (https://chenglou.me/pretext/bubbles/): a bubble whose text
112
+ * wraps is as narrow as its widest line allows, not as wide as the chat, so no dead space is left beside short lines. A text that
113
+ * does not wrap, and a message with code blocks, keep the width CSS gives them. On by default; pass `false` for CSS's widths.
114
+ */
115
+ tightBubbles?: boolean;
98
116
  /** Active conversation id — persists generation archive in IndexedDB across reload. */
99
117
  conversationId?: string | null;
100
118
  }
@@ -0,0 +1,153 @@
1
+ <script lang="ts" module>
2
+ /** True once the page's drawing has been reported: the warning is for the page, not for each avatar (a history holds dozens). */
3
+ let hasReportedPageAvatarFailure = false;
4
+ </script>
5
+
6
+ <script lang="ts">
7
+ /**
8
+ * The assistant's avatar.
9
+ *
10
+ * It draws what the page gave (`renderAgentAvatar`, the Scribble Mascot in the Widgetic apps) or, when the page gave
11
+ * nothing, a plain round avatar. Its box glides between the large size (waiting, a card to answer, the conclusion) and
12
+ * the small one (writing, history) instead of jumping, and the size it is drawn at is handed to the page's drawing at
13
+ * every step, so the mascot grows and shrinks with its box.
14
+ */
15
+ import { untrack } from 'svelte';
16
+ import { Tween, prefersReducedMotion } from 'svelte/motion';
17
+ import { cubicOut } from 'svelte/easing';
18
+ import IconSparkles from '@tabler/icons-svelte/icons/sparkles';
19
+ import { useChatLanguage } from '../../i18n/language.js';
20
+ import type { AgentAvatarRenderer, AgentAvatarState } from '../../types/agent.js';
21
+ import { agentAvatarLabelKey, agentAvatarPixels, type AgentAvatarSize } from '../../utils/agentTurn.js';
22
+ import { chatLog, chatWarn } from '../../utils/logger.js';
23
+ import AvatarBoundary from './AvatarBoundary.svelte';
24
+
25
+ // The words of the avatar, in the language of the chat above
26
+ const { t } = useChatLanguage();
27
+
28
+ /** How long the avatar takes to grow or shrink: long enough to follow the move, short enough not to hold anything up. */
29
+ const GLIDE_MILLISECONDS = 420;
30
+
31
+ interface Props {
32
+ /**
33
+ * What the assistant is doing: the avatar's motion and, while it works or after it ended, what a screen reader says. (Not called `state`: a local
34
+ * with that name would turn the `$state` rune below into a store subscription.)
35
+ */
36
+ avatarState: AgentAvatarState;
37
+ /** The size it rests at. */
38
+ size: AgentAvatarSize;
39
+ /** False for a still picture (older turns). */
40
+ live?: boolean;
41
+ /** The size to start from, when it should glide to `size` as it appears (the conclusion grows out of the small avatar of the work). */
42
+ startSize?: AgentAvatarSize;
43
+ /**
44
+ * The state to be drawn in as it appears, when it takes over from another avatar (the live one of the run). It moves on to
45
+ * `avatarState` right after, so a drawing that blends between states (the mascot) calms or celebrates from what the person
46
+ * was watching instead of appearing in the new state.
47
+ */
48
+ startState?: AgentAvatarState;
49
+ /** The page's way of drawing the avatar. Without it a plain round avatar is drawn. */
50
+ renderAgentAvatar?: AgentAvatarRenderer;
51
+ class?: string;
52
+ }
53
+
54
+ let {
55
+ avatarState,
56
+ size,
57
+ live = true,
58
+ startSize = undefined,
59
+ startState = undefined,
60
+ renderAgentAvatar = undefined,
61
+ class: className = ''
62
+ }: Props = $props();
63
+
64
+ // The size it rests at, in pixels, and the size it is at right now on its way there
65
+ const restingPixels = $derived(agentAvatarPixels(size, Boolean(renderAgentAvatar)));
66
+ const sizeGlide = new Tween(
67
+ untrack(() => agentAvatarPixels(startSize ?? size, Boolean(renderAgentAvatar))),
68
+ { duration: GLIDE_MILLISECONDS, easing: cubicOut }
69
+ );
70
+
71
+ $effect(() => {
72
+ // A person who asked for less motion gets the new size at once
73
+ const duration = prefersReducedMotion.current ? 0 : GLIDE_MILLISECONDS;
74
+ const target = restingPixels;
75
+ untrack(() => {
76
+ void sizeGlide.set(target, { duration });
77
+ });
78
+ });
79
+
80
+ // Whole pixels only: a drawing that is told a new size at every fraction of a pixel redraws for nothing
81
+ const drawnPixels = $derived(Math.round(sizeGlide.current));
82
+
83
+ // The state the drawing is told. An avatar that takes over from another one is drawn in that one's state for its first pass and
84
+ // then moves on to its own, so a drawing that blends between states does so (the one of the moment, not a swap). With no state
85
+ // to start from it is its own from the start, and nothing extra happens.
86
+ let hasMovedOnFromStart = $state(untrack(() => startState === undefined || startState === avatarState));
87
+ $effect(() => {
88
+ hasMovedOnFromStart = true;
89
+ });
90
+ const drawnState = $derived<AgentAvatarState>(hasMovedOnFromStart ? avatarState : (startState ?? avatarState));
91
+ // What a screen reader says: nothing for an avatar at rest (the words beside it say it all)
92
+ const avatarLabelKey = $derived(agentAvatarLabelKey(avatarState));
93
+ const avatarLabel = $derived(avatarLabelKey ? $t(avatarLabelKey) : '');
94
+ const isWorking = $derived(avatarState === 'thinking' || avatarState === 'writing');
95
+
96
+ // Said once per kind of change (never on every frame of the glide): what the avatar was asked to do
97
+ let lastReportedLook = '';
98
+ $effect(() => {
99
+ const look = `${avatarState}:${size}:${live ? 'live' : 'still'}:${renderAgentAvatar ? 'page' : 'plain'}`;
100
+ if (look === lastReportedLook) return;
101
+ lastReportedLook = look;
102
+ chatLog('[Chat] assistant avatar:', look);
103
+ });
104
+
105
+ // A page's drawing that breaks (no WebGL, a bug) must never take the chat with it: the plain avatar takes its place
106
+ let pageAvatarFailed = $state(false);
107
+ function handlePageAvatarError(error: unknown): void {
108
+ // Said once for the page (each avatar of a history would otherwise say it again), with the error that came first
109
+ if (!hasReportedPageAvatarFailure) {
110
+ hasReportedPageAvatarFailure = true;
111
+ chatWarn('[Chat] The page’s avatar drawing failed, the plain avatar is shown instead:', error);
112
+ }
113
+ pageAvatarFailed = true;
114
+ }
115
+ </script>
116
+
117
+ {#snippet plainAvatar()}
118
+ <span
119
+ class="bg-muted text-foreground flex size-full items-center justify-center rounded-full {isWorking
120
+ ? 'motion-safe:animate-pulse'
121
+ : ''}"
122
+ >
123
+ <IconSparkles
124
+ class="stroke-2"
125
+ style="width: {Math.round(drawnPixels * 0.5)}px; height: {Math.round(drawnPixels * 0.5)}px;"
126
+ aria-hidden="true"
127
+ />
128
+ </span>
129
+ {/snippet}
130
+
131
+ <span
132
+ class="agent-avatar-box relative inline-flex shrink-0 items-center justify-center {className}"
133
+ style="width: {drawnPixels}px; height: {drawnPixels}px;"
134
+ role={avatarLabel ? 'img' : undefined}
135
+ aria-label={avatarLabel || undefined}
136
+ aria-hidden={avatarLabel ? undefined : 'true'}
137
+ data-testid="agent-avatar"
138
+ data-agent-avatar-state={avatarState}
139
+ data-agent-avatar-size={size}
140
+ data-agent-avatar-live={live}
141
+ >
142
+ {#if renderAgentAvatar && !pageAvatarFailed}
143
+ {@const drawPageAvatar = renderAgentAvatar}
144
+ <AvatarBoundary onerror={handlePageAvatarError}>
145
+ {@render drawPageAvatar({ state: drawnState, size: drawnPixels, live, label: avatarLabel })}
146
+ {#snippet fallback()}
147
+ {@render plainAvatar()}
148
+ {/snippet}
149
+ </AvatarBoundary>
150
+ {:else}
151
+ {@render plainAvatar()}
152
+ {/if}
153
+ </span>
@@ -0,0 +1,27 @@
1
+ import type { AgentAvatarRenderer, AgentAvatarState } from '../../types/agent.js';
2
+ import { type AgentAvatarSize } from '../../utils/agentTurn.js';
3
+ interface Props {
4
+ /**
5
+ * What the assistant is doing: the avatar's motion and, while it works or after it ended, what a screen reader says. (Not called `state`: a local
6
+ * with that name would turn the `$state` rune below into a store subscription.)
7
+ */
8
+ avatarState: AgentAvatarState;
9
+ /** The size it rests at. */
10
+ size: AgentAvatarSize;
11
+ /** False for a still picture (older turns). */
12
+ live?: boolean;
13
+ /** The size to start from, when it should glide to `size` as it appears (the conclusion grows out of the small avatar of the work). */
14
+ startSize?: AgentAvatarSize;
15
+ /**
16
+ * The state to be drawn in as it appears, when it takes over from another avatar (the live one of the run). It moves on to
17
+ * `avatarState` right after, so a drawing that blends between states (the mascot) calms or celebrates from what the person
18
+ * was watching instead of appearing in the new state.
19
+ */
20
+ startState?: AgentAvatarState;
21
+ /** The page's way of drawing the avatar. Without it a plain round avatar is drawn. */
22
+ renderAgentAvatar?: AgentAvatarRenderer;
23
+ class?: string;
24
+ }
25
+ declare const AgentAvatar: import("svelte").Component<Props, {}, "">;
26
+ type AgentAvatar = ReturnType<typeof AgentAvatar>;
27
+ export default AgentAvatar;
@@ -0,0 +1,64 @@
1
+ <script lang="ts">
2
+ /**
3
+ * What the assistant says in one turn, with its face: the avatar at the left and everything it said or showed to its right.
4
+ * There is no name over it (it is clear who is speaking): the words are the content's own, "Thinking…", "Writing code…".
5
+ *
6
+ * The same row holds the large avatar of the moments that matter (the card to answer or the plan sits to its right) and the
7
+ * small one of the work (the text sits beside it), so going from one to the other only changes the size of the avatar: the
8
+ * content slides along with it, nothing is rebuilt.
9
+ *
10
+ * The content starts at the avatar's top, whatever its height: the first thing in it (a line of text, "Thinking…", a one-line
11
+ * failure, a card) is level with the top of the avatar, beside the large one as well as beside the small one. A first line is
12
+ * as tall as the small avatar (`min-h-7`, the 28 pixels of `AGENT_AVATAR_PIXELS.small`) with its text in the middle of it, so
13
+ * beside the small avatar a single line is also centred on it, and beside the large one it does not sink to the middle of it.
14
+ */
15
+ import type { Snippet } from 'svelte';
16
+ import type { AgentAvatarRenderer, AgentAvatarState } from '../../types/agent.js';
17
+ import type { AgentAvatarSize, AgentLook } from '../../utils/agentTurn.js';
18
+ import AgentAvatar from './AgentAvatar.svelte';
19
+
20
+ interface Props {
21
+ /** What the avatar looks like and does. */
22
+ look: AgentLook;
23
+ /** The page's way of drawing the avatar (see `AgentAvatarRenderer`). */
24
+ renderAgentAvatar?: AgentAvatarRenderer;
25
+ /** The size the avatar glides from as it appears (the conclusion grows out of the small avatar of the work). */
26
+ startSize?: AgentAvatarSize;
27
+ /** The state the avatar is drawn in as it appears, before it moves on to its own (see `AgentAvatar`). */
28
+ startState?: AgentAvatarState;
29
+ class?: string;
30
+ /** Everything the assistant said or showed in this turn. */
31
+ children: Snippet;
32
+ }
33
+
34
+ let {
35
+ look,
36
+ renderAgentAvatar = undefined,
37
+ startSize = undefined,
38
+ startState = undefined,
39
+ class: className = '',
40
+ children
41
+ }: Props = $props();
42
+ </script>
43
+
44
+ <!--
45
+ Two boxes side by side: the avatar (its box sets the width of the first, so the content follows it while it glides), and the
46
+ content. The row is as tall as the taller of the two; both start at the top of it, so the first line of the content is level
47
+ with the top of the avatar.
48
+ -->
49
+ <div
50
+ class="agent-turn flex w-full items-start gap-3 {className}"
51
+ data-testid="agent-turn"
52
+ data-agent-turn-state={look.state}
53
+ data-agent-turn-size={look.size}
54
+ >
55
+ <!-- A flex box, not a block: the avatar is an inline box, and in a block the line it sits on is taller than it (the strut of the
56
+ line height hangs under it), which made this column a few pixels taller than the avatar and its middle fall below its own. -->
57
+ <div class="flex shrink-0 self-start">
58
+ <AgentAvatar avatarState={look.state} size={look.size} live={look.live} {startSize} {startState} {renderAgentAvatar} />
59
+ </div>
60
+
61
+ <div class="flex min-w-0 flex-1 flex-col gap-2 self-start" data-testid="agent-turn-content">
62
+ {@render children()}
63
+ </div>
64
+ </div>
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What the assistant says in one turn, with its face: the avatar at the left and everything it said or showed to its right.
3
+ * There is no name over it (it is clear who is speaking): the words are the content's own, "Thinking…", "Writing code…".
4
+ *
5
+ * The same row holds the large avatar of the moments that matter (the card to answer or the plan sits to its right) and the
6
+ * small one of the work (the text sits beside it), so going from one to the other only changes the size of the avatar: the
7
+ * content slides along with it, nothing is rebuilt.
8
+ *
9
+ * The content starts at the avatar's top, whatever its height: the first thing in it (a line of text, "Thinking…", a one-line
10
+ * failure, a card) is level with the top of the avatar, beside the large one as well as beside the small one. A first line is
11
+ * as tall as the small avatar (`min-h-7`, the 28 pixels of `AGENT_AVATAR_PIXELS.small`) with its text in the middle of it, so
12
+ * beside the small avatar a single line is also centred on it, and beside the large one it does not sink to the middle of it.
13
+ */
14
+ import type { Snippet } from 'svelte';
15
+ import type { AgentAvatarRenderer, AgentAvatarState } from '../../types/agent.js';
16
+ import type { AgentAvatarSize, AgentLook } from '../../utils/agentTurn.js';
17
+ interface Props {
18
+ /** What the avatar looks like and does. */
19
+ look: AgentLook;
20
+ /** The page's way of drawing the avatar (see `AgentAvatarRenderer`). */
21
+ renderAgentAvatar?: AgentAvatarRenderer;
22
+ /** The size the avatar glides from as it appears (the conclusion grows out of the small avatar of the work). */
23
+ startSize?: AgentAvatarSize;
24
+ /** The state the avatar is drawn in as it appears, before it moves on to its own (see `AgentAvatar`). */
25
+ startState?: AgentAvatarState;
26
+ class?: string;
27
+ /** Everything the assistant said or showed in this turn. */
28
+ children: Snippet;
29
+ }
30
+ declare const AgentTurn: import("svelte").Component<Props, {}, "">;
31
+ type AgentTurn = ReturnType<typeof AgentTurn>;
32
+ export default AgentTurn;
@@ -0,0 +1,29 @@
1
+ <script lang="ts">
2
+ /**
3
+ * Keeps a drawing that breaks from taking the chat down with it: what is inside is drawn as long as nothing throws, and
4
+ * `fallback` is drawn in its place (and `onerror` is told) the moment something does.
5
+ *
6
+ * It is a file of its own on purpose. `<svelte:boundary>` (Svelte 5.3) is not known to the `svelte-eslint-parser` the chat's
7
+ * linter uses (0.43): it stops at the tag with a parse error. Only this file is left out of the linter (`eslint.config.js`),
8
+ * until the parser is updated, instead of the whole avatar.
9
+ */
10
+ import type { Snippet } from 'svelte';
11
+
12
+ interface Props {
13
+ /** What to draw. */
14
+ children: Snippet;
15
+ /** What to draw instead when `children` throws. */
16
+ fallback: Snippet;
17
+ /** Told with the error when something inside throws. */
18
+ onerror?: (error: unknown) => void;
19
+ }
20
+
21
+ let { children, fallback, onerror }: Props = $props();
22
+ </script>
23
+
24
+ <svelte:boundary {onerror}>
25
+ {@render children()}
26
+ {#snippet failed()}
27
+ {@render fallback()}
28
+ {/snippet}
29
+ </svelte:boundary>
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Keeps a drawing that breaks from taking the chat down with it: what is inside is drawn as long as nothing throws, and
3
+ * `fallback` is drawn in its place (and `onerror` is told) the moment something does.
4
+ *
5
+ * It is a file of its own on purpose. `<svelte:boundary>` (Svelte 5.3) is not known to the `svelte-eslint-parser` the chat's
6
+ * linter uses (0.43): it stops at the tag with a parse error. Only this file is left out of the linter (`eslint.config.js`),
7
+ * until the parser is updated, instead of the whole avatar.
8
+ */
9
+ import type { Snippet } from 'svelte';
10
+ interface Props {
11
+ /** What to draw. */
12
+ children: Snippet;
13
+ /** What to draw instead when `children` throws. */
14
+ fallback: Snippet;
15
+ /** Told with the error when something inside throws. */
16
+ onerror?: (error: unknown) => void;
17
+ }
18
+ declare const AvatarBoundary: import("svelte").Component<Props, {}, "">;
19
+ type AvatarBoundary = ReturnType<typeof AvatarBoundary>;
20
+ export default AvatarBoundary;
@@ -0,0 +1,288 @@
1
+ <script lang="ts">
2
+ /**
3
+ * The code the assistant writes, as a card of the chat: the look of the design system's cards (white, a border, round
4
+ * corners) with the code in a grey panel, in the font code editors use, its words coloured by highlight.js.
5
+ *
6
+ * While the code arrives, Prettier lays out what has arrived so far (see `codeStreamFormat`): the code is tidy as it is
7
+ * written, and the line being typed shows as it comes. Prettier is loaded the first time a card is open on a script, and
8
+ * not before. Code that is not a script (a page, a Svelte component) is shown as it was written, coloured.
9
+ *
10
+ * It is open while it is the part being written and closed once the next part (or the conclusion) has taken over; the
11
+ * person's own choice wins from the moment they press it. Under a conclusion it comes back closed, for the person to open.
12
+ */
13
+ import { onDestroy, tick } from 'svelte';
14
+ import IconCheck from '@tabler/icons-svelte/icons/check';
15
+ import IconChevronRight from '@tabler/icons-svelte/icons/chevron-right';
16
+ import IconCode from '@tabler/icons-svelte/icons/code';
17
+ import IconCopy from '@tabler/icons-svelte/icons/copy';
18
+ import { useChatLanguage } from '../../i18n/language.js';
19
+ import { highlightCodeToHtml } from '../../utils/codeHighlight.js';
20
+ import { formatScriptWithCursor } from '../../utils/codePrettier.js';
21
+ import { countCodeLines, createStreamingFormatter, detectCodeKind } from '../../utils/codeStreamFormat.js';
22
+ import { chatLog, chatWarn } from '../../utils/logger.js';
23
+
24
+ // The words of the card, in the language of the chat above
25
+ const { t } = useChatLanguage();
26
+
27
+ interface Props {
28
+ /** Everything written so far. */
29
+ code: string;
30
+ /** The code is still arriving: the footer says so, the newest line stays in view and Prettier follows it. */
31
+ streaming?: boolean;
32
+ /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
33
+ openByDefault?: boolean;
34
+ class?: string;
35
+ }
36
+
37
+ let { code, streaming = false, openByDefault = false, class: className = '' }: Props = $props();
38
+
39
+ /** How often Prettier follows the code while it arrives (a run takes some tens of milliseconds on a long file). */
40
+ const FORMAT_INTERVAL_MS = 250;
41
+ /** Longer code is shown as it was written: laying it out again and again would cost more than it is worth. */
42
+ const MAX_FORMATTED_CHARACTERS = 60_000;
43
+ /** How close to the end of the panel the person has to be for the newest line to stay in view as the code grows. */
44
+ const FOLLOW_THRESHOLD_PIXELS = 24;
45
+
46
+ // What the person chose, once they have chosen: from then on it wins over the default
47
+ let chosenOpen = $state<boolean | null>(null);
48
+ const isOpen = $derived(chosenOpen ?? openByDefault);
49
+
50
+ const bodyId = $props.id();
51
+ let panelElement = $state<HTMLElement | null>(null);
52
+ let isFollowingNewestLine = true;
53
+
54
+ // What the code is decides its colours and whether Prettier can lay it out
55
+ const codeKind = $derived(detectCodeKind(code));
56
+
57
+ // --- Prettier, following the code ---------------------------------------------------------------------------------------
58
+
59
+ /** The start of the code as Prettier laid it out, and the source it stands for. */
60
+ let formattedStart = $state<{ sourcePrefix: string; text: string } | null>(null);
61
+
62
+ const streamingFormatter = createStreamingFormatter(formatScriptWithCursor);
63
+ let formatTimer: ReturnType<typeof setTimeout> | null = null;
64
+ let isFormatting = false;
65
+ let isFormattingAgainNeeded = false;
66
+ let isDestroyed = false;
67
+ let hasReportedFormatFailure = false;
68
+ // What the next run reads: the newest code, not the code of the moment the run was asked for
69
+ let newestCode = '';
70
+ let newestCodeIsComplete = false;
71
+
72
+ /** Runs Prettier on the newest code. Runs never overlap: one that is asked for during another follows it. */
73
+ async function runFormatting(): Promise<void> {
74
+ if (isFormatting) {
75
+ isFormattingAgainNeeded = true;
76
+ return;
77
+ }
78
+ isFormatting = true;
79
+ try {
80
+ do {
81
+ isFormattingAgainNeeded = false;
82
+ const sourceToFormat = newestCode;
83
+ const sourceIsComplete = newestCodeIsComplete;
84
+ const startedAt = performance.now();
85
+ const result = await streamingFormatter.format(sourceToFormat, sourceIsComplete);
86
+ if (isDestroyed) return;
87
+ formattedStart = result.isFormatted
88
+ ? { sourcePrefix: sourceToFormat.slice(0, result.formattedSourceLength), text: result.formattedStart }
89
+ : null;
90
+ if (sourceIsComplete) {
91
+ chatLog(
92
+ '[Chat] code card: laid out',
93
+ sourceToFormat.length,
94
+ 'characters in',
95
+ Math.round(performance.now() - startedAt),
96
+ 'ms:',
97
+ result.isFormatted ? 'formatted' : 'shown as written'
98
+ );
99
+ }
100
+ } while (isFormattingAgainNeeded);
101
+ } catch (error) {
102
+ // The formatter does not reject; this is a guard for the load of Prettier
103
+ if (!hasReportedFormatFailure) {
104
+ hasReportedFormatFailure = true;
105
+ chatWarn('[Chat] code card: the code could not be laid out, it is shown as it was written:', error);
106
+ }
107
+ formattedStart = null;
108
+ } finally {
109
+ isFormatting = false;
110
+ }
111
+ }
112
+
113
+ // Follow the code: while it arrives, a run every FORMAT_INTERVAL_MS; once it is complete, one at once
114
+ $effect(() => {
115
+ const codeToFormat = code;
116
+ const codeIsComplete = !streaming;
117
+ const canFormat = isOpen && codeKind === 'script' && codeToFormat.length <= MAX_FORMATTED_CHARACTERS;
118
+ if (!canFormat) return;
119
+ newestCode = codeToFormat;
120
+ newestCodeIsComplete = codeIsComplete;
121
+ if (codeIsComplete) {
122
+ if (formatTimer !== null) clearTimeout(formatTimer);
123
+ formatTimer = null;
124
+ void runFormatting();
125
+ return;
126
+ }
127
+ if (formatTimer === null) {
128
+ formatTimer = setTimeout(() => {
129
+ formatTimer = null;
130
+ void runFormatting();
131
+ }, FORMAT_INTERVAL_MS);
132
+ }
133
+ });
134
+
135
+ // --- What the card shows ------------------------------------------------------------------------------------------------
136
+
137
+ // The formatted start stands for the start of the code only while the code still starts with the source it was made from
138
+ const isFormattedStartValid = $derived(formattedStart !== null && code.startsWith(formattedStart.sourcePrefix));
139
+
140
+ /** The formatted start, then what has been written since as it was written. */
141
+ const visibleText = $derived.by(() => {
142
+ if (!isFormattedStartValid || formattedStart === null) return code;
143
+ const writtenAfter = code.slice(formattedStart.sourcePrefix.length);
144
+ return writtenAfter === '' ? formattedStart.text : `${formattedStart.text}\n${writtenAfter}`;
145
+ });
146
+
147
+ // The lines that are done are coloured once, when the line after them begins; only the line being typed is coloured as it comes
148
+ const lastLineBreakIndex = $derived(visibleText.lastIndexOf('\n'));
149
+ const settledText = $derived(lastLineBreakIndex === -1 ? '' : visibleText.slice(0, lastLineBreakIndex));
150
+ const typingText = $derived(visibleText.slice(lastLineBreakIndex + 1));
151
+ const settledHtml = $derived(highlightCodeToHtml(settledText, codeKind));
152
+ const typingHtml = $derived(highlightCodeToHtml(typingText, codeKind));
153
+ const lineCount = $derived(countCodeLines(visibleText));
154
+
155
+ // What the buttons say, for a screen reader (the title says what the card is)
156
+ const toggleLabel = $derived(isOpen ? $t('chat.generation.collapseCode') : $t('chat.generation.expandCode'));
157
+
158
+ function toggleOpen(): void {
159
+ chosenOpen = !isOpen;
160
+ chatLog('[Chat] code card', chosenOpen ? 'opened' : 'closed', 'by the person');
161
+ }
162
+
163
+ // --- The newest line stays in view ------------------------------------------------------------------------------------
164
+
165
+ // The person who scrolls up to read is not pulled back down; reaching the end again makes the card follow the code once more
166
+ function updateFollowing(): void {
167
+ if (!panelElement) return;
168
+ const distanceFromEnd = panelElement.scrollHeight - panelElement.scrollTop - panelElement.clientHeight;
169
+ isFollowingNewestLine = distanceFromEnd < FOLLOW_THRESHOLD_PIXELS;
170
+ }
171
+
172
+ $effect(() => {
173
+ if (!streaming || !isOpen || !panelElement) return;
174
+ if (visibleText.length === 0 || !isFollowingNewestLine) return;
175
+ tick()
176
+ .then(() => {
177
+ if (panelElement) panelElement.scrollTop = panelElement.scrollHeight;
178
+ })
179
+ .catch((error) => console.warn('[Chat] Could not keep the newest line of the code in view:', error));
180
+ });
181
+
182
+ // --- Copy -----------------------------------------------------------------------------------------------------------------
183
+
184
+ let hasCopied = $state(false);
185
+ let copiedTimer: ReturnType<typeof setTimeout> | null = null;
186
+
187
+ async function copyCode(): Promise<void> {
188
+ try {
189
+ await navigator.clipboard.writeText(visibleText);
190
+ hasCopied = true;
191
+ chatLog('[Chat] code card: the code was copied');
192
+ if (copiedTimer !== null) clearTimeout(copiedTimer);
193
+ copiedTimer = setTimeout(() => {
194
+ hasCopied = false;
195
+ copiedTimer = null;
196
+ }, 2000);
197
+ } catch (error) {
198
+ chatWarn('[Chat] code card: the code could not be copied:', error);
199
+ }
200
+ }
201
+
202
+ onDestroy(() => {
203
+ isDestroyed = true;
204
+ if (formatTimer !== null) clearTimeout(formatTimer);
205
+ if (copiedTimer !== null) clearTimeout(copiedTimer);
206
+ });
207
+ </script>
208
+
209
+ <div
210
+ class="rounded-card border-border bg-background flex w-full max-w-full min-w-0 flex-col border {isOpen
211
+ ? 'gap-3 p-4'
212
+ : 'px-4 py-2'} {className}"
213
+ data-testid="code-card"
214
+ data-open={isOpen}
215
+ data-streaming={streaming}
216
+ data-formatted={isFormattedStartValid}
217
+ >
218
+ <header class="flex min-w-0 items-center gap-2">
219
+ <button
220
+ type="button"
221
+ class="text-foreground focus-visible:ring-ring flex min-h-7 min-w-0 flex-1 items-center gap-2 rounded-sm text-start focus-visible:ring-2 focus-visible:outline-none"
222
+ aria-expanded={isOpen}
223
+ aria-controls={bodyId}
224
+ onclick={toggleOpen}
225
+ >
226
+ <IconCode class="size-4 shrink-0 stroke-2" aria-hidden="true" />
227
+ <span class="text-body-medium min-w-0 flex-1 truncate">{$t('chat.generation.codeTitle')}</span>
228
+ <IconChevronRight
229
+ class="text-muted-foreground size-4 shrink-0 stroke-2 transition-transform motion-reduce:transition-none rtl:-scale-x-100 {isOpen
230
+ ? 'rotate-90 rtl:-rotate-90'
231
+ : ''}"
232
+ aria-hidden="true"
233
+ />
234
+ <span class="sr-only">{toggleLabel}</span>
235
+ </button>
236
+ {#if isOpen && visibleText !== ''}
237
+ <button
238
+ type="button"
239
+ class="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md transition-colors focus-visible:outline-none"
240
+ title={hasCopied ? $t('chat.code.copied') : $t('chat.code.copyTitle')}
241
+ aria-label={hasCopied ? $t('chat.code.copied') : $t('chat.code.copyTitle')}
242
+ onclick={copyCode}
243
+ data-testid="code-card-copy"
244
+ >
245
+ {#if hasCopied}
246
+ <IconCheck class="size-4 stroke-2" aria-hidden="true" />
247
+ {:else}
248
+ <IconCopy class="size-4 stroke-2" aria-hidden="true" />
249
+ {/if}
250
+ </button>
251
+ {/if}
252
+ </header>
253
+
254
+ {#if isOpen}
255
+ <div id={bodyId} class="flex min-w-0 flex-col gap-3">
256
+ <!-- The colours of the words: keywords blue, tags and strings maroon, the attributes of a tag red-orange (highlight.js also calls
257
+ `name:` in a parameter list an attribute, so only the ones inside a tag are painted), comments muted. Their classes are
258
+ the card's own `wc-code-*`, not the ones of highlight.js: see CODE_TOKEN_CLASS_PREFIX. The two pieces of html in the panel are
259
+ the only ones in the card, and safe: `highlightCodeToHtml` escapes every character of the code, and the only tags it writes
260
+ are the `span`s of the words. -->
261
+ <!-- The panel scrolls, so the keyboard has to be able to reach it -->
262
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
263
+ <pre
264
+ bind:this={panelElement}
265
+ onscroll={updateFollowing}
266
+ tabindex="0"
267
+ aria-label={$t('chat.generation.codeTitle')}
268
+ class="bg-muted text-foreground m-0 max-h-72 w-full overflow-auto rounded-lg p-3 font-[ui-monospace,SFMono-Regular,'SF_Mono',Menlo,Monaco,Consolas,'Liberation_Mono','Courier_New',monospace] text-[12px] leading-[18px] break-words whitespace-pre-wrap [tab-size:2] [scrollbar-color:var(--border)_transparent] [scrollbar-width:thin] [&_.wc-code-tag_.wc-code-attr]:text-[#e5462b] [&_.wc-code-comment]:text-muted-foreground [&_.wc-code-comment]:italic [&_.wc-code-keyword]:text-[#2b5fc2] [&_.wc-code-literal]:text-[#2b5fc2] [&_.wc-code-meta]:text-muted-foreground [&_.wc-code-name]:text-[#8d2a1b] [&_.wc-code-number]:text-[#2b5fc2] [&_.wc-code-regexp]:text-[#8d2a1b] [&_.wc-code-string]:text-[#8d2a1b] [&_.wc-code-tag]:text-[#8d2a1b] [&_.wc-code-title]:text-[#2b5fc2] [.dark_&_.wc-code-tag_.wc-code-attr]:text-[#ff8a73] [.dark_&_.wc-code-keyword]:text-[#8ab4ff] [.dark_&_.wc-code-literal]:text-[#8ab4ff] [.dark_&_.wc-code-name]:text-[#f0a89a] [.dark_&_.wc-code-number]:text-[#8ab4ff] [.dark_&_.wc-code-regexp]:text-[#f0a89a] [.dark_&_.wc-code-string]:text-[#f0a89a] [.dark_&_.wc-code-tag]:text-[#f0a89a] [.dark_&_.wc-code-title]:text-[#8ab4ff]"
269
+ dir="ltr"
270
+ data-testid="code-card-text"><code
271
+ >{@html settledHtml}{lastLineBreakIndex === -1 ? '' : '\n'}{@html typingHtml}</code
272
+ ></pre>
273
+ <footer class="text-caption text-muted-foreground flex flex-col gap-0.5" data-testid="code-card-status">
274
+ <span class="flex items-center gap-2">
275
+ <span
276
+ class="bg-brand size-2 shrink-0 rounded-full {streaming ? 'animate-pulse motion-reduce:animate-none' : ''}"
277
+ aria-hidden="true"
278
+ ></span>
279
+ <span>{streaming ? $t('chat.generation.writingCode') : $t('chat.generation.codeWritten')}</span>
280
+ </span>
281
+ <span class="flex items-center gap-2 ps-0.5">
282
+ <span class="border-border h-2.5 w-2 shrink-0 border-s border-b" aria-hidden="true"></span>
283
+ <span>{$t('chat.generation.codeLineCount', { count: lineCount })}</span>
284
+ </span>
285
+ </footer>
286
+ </div>
287
+ {/if}
288
+ </div>
@@ -0,0 +1,12 @@
1
+ interface Props {
2
+ /** Everything written so far. */
3
+ code: string;
4
+ /** The code is still arriving: the footer says so, the newest line stays in view and Prettier follows it. */
5
+ streaming?: boolean;
6
+ /** Open until the person chooses (the live part), or closed until they do (the part under a conclusion). */
7
+ openByDefault?: boolean;
8
+ class?: string;
9
+ }
10
+ declare const CodeCard: import("svelte").Component<Props, {}, "">;
11
+ type CodeCard = ReturnType<typeof CodeCard>;
12
+ export default CodeCard;