@klex/mascot 0.5.0 → 0.6.0

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 CHANGED
@@ -26,10 +26,10 @@ The component uses Tailwind utilities and `@stagewise/ui` theme tokens. Import t
26
26
  | `Klex`, `KlexHandle`, `KlexProps`, `EmoteId` | The animated character and its ref commands. |
27
27
  | `BODY_SHAPES`, `BodyShape`, `PALETTES`, `KlexPalette` | Built-in silhouettes and colors. |
28
28
  | `DEFAULT_GLIDE`, `MOVEMENT_STYLES`, `MovementMode` | Movement settings for `crawl`, `fly`, and `hop`. |
29
- | `ACTIVITIES`, `KlexActivity` | Resting activities: `idle`, `sleeping`, `working`, `calling`. |
29
+ | `ACTIVITIES`, `KlexActivity` | Resting activities: `idle`, `sleeping`, `working`, `calling`, `recalling`, `learning`. |
30
30
  | `EMOTES`, `EMOTE_CATEGORIES`, `Emote`, `emotePose`, `REST_EMOTE` | Emote catalog and poses. |
31
31
  | `EXPRESSIONS`, `Expression`, `KlexEyes` | Facial expressions and the eye renderer. |
32
- | `EXTRAS`, `Extra`, `KlexExtras` | Extras such as wave, phone, sparkles, and sleep. |
32
+ | `EXTRAS`, `Extra`, `KlexExtras` | Extras such as wave, phone, sparkles, sleep, and thought. |
33
33
  | `KlexGroundGrid` | Perspective floor grid for scenes. |
34
34
  | `klexBody`, `KlexPosition`, `fitGaze`, `gazeRoom`, `waveAnchor`, `phoneAnchor` | Geometry helpers for editors and static previews. |
35
35
  | `observeVisibility` | Shared `IntersectionObserver` that Klex uses to pause offscreen characters. |
@@ -97,12 +97,14 @@ Emotes, including jumps and shaking, scale down with the avatar. The ground is t
97
97
 
98
98
  `idle` defaults to `true`. Resting characters breathe gently, sway their heads, blink and occasionally glance around without changing their expression or position. Every instance has its own breathing pace and independently randomized blink and glance pauses. Each glance also varies in direction and duration. The idle pose fades out for travel and emotes, then returns automatically. Flying characters keep their hover. Use `idle={false}` for static avatars or long lists that do not need continuous animation.
99
99
 
100
- `activity` selects a persistent animation and defaults to `'idle'`. `'sleeping'` closes the eyes, lowers and tilts the head, and breathes slowly. `'calling'` holds a bundled Twemoji 📞 SVG against the head, mirrored toward the face and held by a small hand in the body color. A fixed graphic avoids platform-dependent emoji font shapes and baselines. The earpiece follows the deformed silhouette slightly above the eyes, including custom shapes. Each avatar alternates attentive listening, irregular conversational emphasis, and a friendly double nod, with natural blinks and pauses. These are ambient gestures, not speech detection; reduced motion keeps a static listening pose. No laptop is shown. `'working'` places a laptop in front of the character, with its back facing the viewer. Each avatar independently alternates between reading across successive lines, typing in irregular bursts, and looking up to think with a question mark overhead. Phase order, durations, and pauses are randomized anew throughout the animation. Travel and emotes take precedence, then the latest activity resumes. `idle={false}` disables only the default idle animation; an explicit sleeping, working or calling activity still runs.
100
+ `activity` selects a persistent animation and defaults to `'idle'`. `'sleeping'` closes the eyes, lowers and tilts the head, and breathes slowly. `'calling'` holds a bundled Twemoji 📞 SVG against the head, mirrored toward the face and held by a small hand in the body color. A fixed graphic avoids platform-dependent emoji font shapes and baselines. The earpiece follows the deformed silhouette slightly above the eyes, including custom shapes. Each avatar alternates attentive listening, irregular conversational emphasis, and a friendly double nod, with natural blinks and pauses. These are ambient gestures, not speech detection; reduced motion keeps a static listening pose. No laptop is shown. `'working'` places a laptop in front of the character, with its back facing the viewer. Each avatar independently alternates between reading across successive lines, typing in irregular bursts, and looking up to think with a question mark overhead. Phase order, durations, and pauses are randomized anew throughout the animation. `'recalling'` shows a thought bubble with pulsing dots above the head. The character alternates quiet pondering toward the bubble, quick searching glances, and a short happy nod; these are ambient gestures and never claim a memory was found. `'learning'` holds an open book and writes into it with a pencil. Ink fills the right-hand page line by line in uneven bursts, the pen lifts while returning to the start of a line, and the character pauses to reread or think. A full page turns over and writing starts on a fresh page. Travel and emotes take precedence, then the latest activity resumes. `idle={false}` disables only the default idle animation; an explicit sleeping, working, calling, recalling or learning activity still runs.
101
101
 
102
102
  ```tsx
103
103
  <Klex activity="sleeping" size={40} />
104
104
  <Klex activity="working" size={40} />
105
105
  <Klex activity="calling" size={40} />
106
+ <Klex activity="recalling" size={40} />
107
+ <Klex activity="learning" size={40} />
106
108
  ```
107
109
 
108
110
  Change the prop to switch activities without remounting the character. These are visual states; the component does not fetch agent status.
@@ -163,11 +165,11 @@ Movement modes are `crawl`, `fly`, and `hop`. Omitting the mode keeps the curren
163
165
 
164
166
  All emotes, expressions and extras are typed IDs. The catalogs are `EMOTES`, `EXPRESSIONS`, and `EXTRAS`. For example, `shiver`, `wink`, `look-left`, `look-right`, `look-up`, `look-down`, and `thanks` are emotes; `happy`, `angry`, `sleepy`, and `hearts` are expressions.
165
167
 
166
- `onMoveArrival` fires once near the latest destination, before the body finishes settling, so a conversation or scene action can begin promptly. `onMoveComplete` fires after settling. Both fire without animated travel when reduced motion is enabled; stopping or snapping cancels pending callbacks. `onEmoteComplete` fires when an emote finishes or is cancelled. No callbacks fire after unmount. Each component owns one controller for activities, movement and emotes and releases its ticker on pause or unmount. Grounded characters with `idle={false}` and no sleeping, working or calling activity release the ticker once their actions settle.
168
+ `onMoveArrival` fires once near the latest destination, before the body finishes settling, so a conversation or scene action can begin promptly. `onMoveComplete` fires after settling. Both fire without animated travel when reduced motion is enabled; stopping or snapping cancels pending callbacks. `onEmoteComplete` fires when an emote finishes or is cancelled. No callbacks fire after unmount. Each component owns one controller for activities, movement and emotes and releases its ticker on pause or unmount. Grounded characters with `idle={false}` and no sleeping, working, calling, recalling or learning activity release the ticker once their actions settle.
167
169
 
168
170
  Speech bubbles animate out and back in when their text changes. Bubbles and extras share the same spring transition. `KlexGroundGrid` accepts optional fade values, so its parent can own the mask, and `floor` adjusts its geometry and line thickness for a plane tilted back by 60 degrees.
169
171
 
170
- The component respects the system's reduced-motion preference: idle and emotes are skipped and destinations are applied without animated travel. Sleeping, working and calling retain a static pose without a continuous ticker. Facial expressions and extras remain available.
172
+ The component respects the system's reduced-motion preference: idle and emotes are skipped and destinations are applied without animated travel. Sleeping, working, calling, recalling and learning retain a static pose without a continuous ticker. Facial expressions and extras remain available.
171
173
 
172
174
  ## License
173
175
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klex/mascot",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "The animated Klex mascot: a React component, its GSAP motion engine, body presets, and SVG helpers.",
5
5
  "type": "module",
6
6
  "license": "MIT AND CC-BY-4.0",
package/src/activity.ts CHANGED
@@ -3,12 +3,16 @@ import { spring } from 'motion';
3
3
  import { createCalling } from './calling';
4
4
  import { REST_EMOTE } from './emotes';
5
5
  import { createIdle } from './idle';
6
+ import { createLearning } from './learning';
7
+ import { createRecalling } from './recalling';
6
8
  import { createWorking } from './working';
7
9
 
8
10
  export const ACTIVITIES = [
9
11
  { id: 'idle', name: 'Idle' },
10
12
  { id: 'sleeping', name: 'Sleeping' },
11
13
  { id: 'working', name: 'Working' },
14
+ { id: 'recalling', name: 'Recalling' },
15
+ { id: 'learning', name: 'Learning' },
12
16
  { id: 'calling', name: 'On a call' },
13
17
  { id: 'flying', name: 'Flying up' },
14
18
  ] as const;
@@ -35,6 +39,24 @@ function activityPose(activity: KlexActivity | false, time: number) {
35
39
  lookY: 2,
36
40
  };
37
41
  }
42
+ if (activity === 'recalling')
43
+ // Looks up toward the thought bubble.
44
+ return {
45
+ ...REST_EMOTE,
46
+ compression: 0.01,
47
+ headTilt: 6,
48
+ nod: -0.25,
49
+ lookX: 3,
50
+ lookY: -6.5,
51
+ };
52
+ if (activity === 'learning')
53
+ return {
54
+ ...REST_EMOTE,
55
+ compression: 0.025,
56
+ headTilt: 2,
57
+ nod: 0.35,
58
+ lookY: 4,
59
+ };
38
60
  if (activity === 'flying')
39
61
  // Looks up and stretches toward where it is going, swaying a little.
40
62
  return {
@@ -56,31 +78,80 @@ function activityPose(activity: KlexActivity | false, time: number) {
56
78
  return REST_EMOTE;
57
79
  }
58
80
 
81
+ /** A held object that springs into view with its activity and shrinks away after. */
82
+ function createProp() {
83
+ let scale = 0;
84
+ let visible = false;
85
+ let motion: ReturnType<typeof spring> | null = null;
86
+ let time = 0;
87
+ return {
88
+ get scale() {
89
+ return scale;
90
+ },
91
+ get settling() {
92
+ return motion !== null;
93
+ },
94
+ snap(next: boolean) {
95
+ visible = next;
96
+ scale = Number(next);
97
+ motion = null;
98
+ },
99
+ advance(dt: number, show: boolean) {
100
+ if (show !== visible) {
101
+ visible = show;
102
+ time = 0;
103
+ motion = spring({
104
+ keyframes: [scale, Number(show)],
105
+ bounce: show ? 0.6 : 0,
106
+ visualDuration: show ? 0.28 : 0.12,
107
+ });
108
+ }
109
+ if (!motion) return;
110
+ time += dt;
111
+ const frame = motion.next(time * 1000);
112
+ scale = frame.value;
113
+ if (frame.done) motion = null;
114
+ },
115
+ };
116
+ }
117
+
59
118
  // Blend persistent poses on the existing ticker, including interrupted changes.
60
119
  export function createActivity() {
61
120
  const idle = createIdle();
62
121
  const working = createWorking();
122
+ const recalling = createRecalling();
123
+ const learning = createLearning();
63
124
  const calling = createCalling();
64
- const weights = { idle: 0, sleeping: 0, working: 0, calling: 0, flying: 0 };
125
+ const weights = {
126
+ idle: 0,
127
+ sleeping: 0,
128
+ working: 0,
129
+ recalling: 0,
130
+ learning: 0,
131
+ calling: 0,
132
+ flying: 0,
133
+ };
65
134
  let time = Math.random() * 6;
66
- let laptopScale = 0;
67
- let laptopVisible = false;
68
- let laptopSpring: ReturnType<typeof spring> | null = null;
69
- let laptopTime = 0;
135
+ const laptop = createProp();
136
+ const book = createProp();
70
137
 
71
138
  return {
72
139
  get active() {
73
140
  return (
74
- laptopSpring !== null || ACTIVITIES.some(({ id }) => weights[id] > 0)
141
+ laptop.settling ||
142
+ book.settling ||
143
+ ACTIVITIES.some(({ id }) => weights[id] > 0)
75
144
  );
76
145
  },
77
146
  get laptopScale() {
78
- return laptopScale;
147
+ return laptop.scale;
79
148
  },
80
- snapLaptop(visible: boolean) {
81
- laptopVisible = visible;
82
- laptopScale = Number(visible);
83
- laptopSpring = null;
149
+ get bookScale() {
150
+ return book.scale;
151
+ },
152
+ snapProps(activity: KlexActivity | false) {
153
+ laptop.snap(activity === 'working');
154
+ book.snap(activity === 'learning');
84
155
  },
85
156
  get workingBob() {
86
157
  const { laptopFloat, laptopTap } = working.pose();
@@ -89,32 +160,38 @@ export function createActivity() {
89
160
  weights.working
90
161
  );
91
162
  },
163
+ /** Gentle sway of the held book; still while the pen is on the page. */
164
+ get learningBob() {
165
+ return (
166
+ Math.sin((time * Math.PI * 2) / 4.2) *
167
+ 1.2 *
168
+ learning.pen.lift *
169
+ weights.learning
170
+ );
171
+ },
92
172
  get callingExpression() {
93
173
  return calling.expression;
94
174
  },
175
+ get recallingExpression() {
176
+ return recalling.expression;
177
+ },
178
+ get learningExpression() {
179
+ return learning.expression;
180
+ },
95
181
  get thinking() {
96
182
  return working.thinking;
97
183
  },
184
+ get learning() {
185
+ return learning;
186
+ },
98
187
  advance(dt: number, activity: KlexActivity | false) {
99
188
  time += dt;
100
- const showLaptop = activity === 'working';
101
- if (showLaptop) working.advance(dt);
189
+ if (activity === 'working') working.advance(dt);
190
+ if (activity === 'recalling') recalling.advance(dt);
191
+ if (activity === 'learning') learning.advance(dt);
102
192
  if (activity === 'calling') calling.advance(dt);
103
- if (showLaptop !== laptopVisible) {
104
- laptopVisible = showLaptop;
105
- laptopTime = 0;
106
- laptopSpring = spring({
107
- keyframes: [laptopScale, Number(showLaptop)],
108
- bounce: showLaptop ? 0.6 : 0,
109
- visualDuration: showLaptop ? 0.28 : 0.12,
110
- });
111
- }
112
- if (laptopSpring) {
113
- laptopTime += dt;
114
- const frame = laptopSpring.next(laptopTime * 1000);
115
- laptopScale = frame.value;
116
- if (frame.done) laptopSpring = null;
117
- }
193
+ laptop.advance(dt, activity === 'working');
194
+ book.advance(dt, activity === 'learning');
118
195
  idle.advance(dt, activity === 'idle');
119
196
  const decay = Math.exp(-6 * dt);
120
197
  for (const { id } of ACTIVITIES) {
@@ -130,6 +207,8 @@ export function createActivity() {
130
207
  const resting = idle.pose(weights.idle);
131
208
  const sleeping = activityPose('sleeping', time);
132
209
  const workingPose = working.pose();
210
+ const recallingPose = recalling.pose();
211
+ const learningPose = learning.pose();
133
212
  const callingPose = calling.pose();
134
213
  const flying = activityPose('flying', time);
135
214
  const pose = { ...REST_EMOTE };
@@ -147,6 +226,8 @@ export function createActivity() {
147
226
  resting[key] +
148
227
  sleeping[key] * weights.sleeping +
149
228
  workingPose[key] * weights.working +
229
+ recallingPose[key] * weights.recalling +
230
+ learningPose[key] * weights.learning +
150
231
  callingPose[key] * weights.calling +
151
232
  flying[key] * weights.flying;
152
233
  }
package/src/book.tsx ADDED
@@ -0,0 +1,94 @@
1
+ import { BOOK_LINE_LENGTH, bookLineY, bookPlacement } from './geometry';
2
+ import { BOOK_LINES } from './learning';
3
+ import type { BodyShape } from './presets';
4
+
5
+ const page = 'M 0 2 C 8 -2 22 -3 34 0 L 35 23 C 23 20 9 20 0 24 Z';
6
+ const lines = Array.from({ length: BOOK_LINES }, (_, index) => index);
7
+
8
+ /**
9
+ * An open notebook held in front of the body. The right-hand page fills with
10
+ * ink as Klex writes; animation drives `[data-book-ink]`, `[data-book-pen]`
11
+ * and the turning sheet `[data-book-turn]`.
12
+ */
13
+ export function KlexBook({ shape }: { shape: BodyShape }) {
14
+ const { x, y, scale } = bookPlacement(shape);
15
+ return (
16
+ <g transform={`translate(${x} ${y}) scale(${scale})`}>
17
+ <path
18
+ d="M -37 3 C -24 -1 -8 0 0 4 C 8 0 24 -1 37 3 L 38 26 C 24 23 8 24 0 27 C -8 24 -24 23 -38 26 Z"
19
+ fill="#6d7fae"
20
+ />
21
+ <path d={page} transform="scale(-1 1)" fill="#f4efe4" />
22
+ <path d={page} fill="#fbf8f1" />
23
+ <g stroke="#b3ab9d" strokeWidth="1.1" strokeLinecap="round">
24
+ {lines.map((index) => (
25
+ <path
26
+ key={index}
27
+ d={`M -5 ${bookLineY(index)} l ${index === BOOK_LINES - 1 ? -14 : -BOOK_LINE_LENGTH} -0.8`}
28
+ />
29
+ ))}
30
+ </g>
31
+ <g
32
+ data-book-ink=""
33
+ fill="none"
34
+ stroke="#4a5160"
35
+ strokeWidth="1.1"
36
+ strokeLinecap="round"
37
+ strokeLinejoin="round"
38
+ >
39
+ {lines.map((index) => (
40
+ <path
41
+ key={index}
42
+ // A loose handwriting squiggle along the line.
43
+ d={`M 5 ${bookLineY(index)} q 1.5 -2 3 0 t 3 0 t 3 0 t 3 0 t 3 0 t 3 0 t 3 0 t 3 0`}
44
+ transform={`rotate(-1.9 5 ${bookLineY(index)})`}
45
+ pathLength="1"
46
+ strokeDasharray="1 1"
47
+ strokeDashoffset="1"
48
+ />
49
+ ))}
50
+ </g>
51
+ <g data-book-turn="" opacity="0">
52
+ <path d={page} fill="#fbf8f1" stroke="#e3dccd" strokeWidth="0.6" />
53
+ <g
54
+ data-book-turn-ink=""
55
+ stroke="#4a5160"
56
+ strokeWidth="1.1"
57
+ strokeLinecap="round"
58
+ >
59
+ {lines.map((index) => (
60
+ <path
61
+ key={index}
62
+ d={`M 5 ${bookLineY(index)} l ${BOOK_LINE_LENGTH} -0.8`}
63
+ />
64
+ ))}
65
+ </g>
66
+ </g>
67
+ <path
68
+ d="M 0 4 L 0 27"
69
+ stroke="#d7cfbf"
70
+ strokeWidth="0.8"
71
+ strokeLinecap="round"
72
+ />
73
+ <g data-book-pen="">
74
+ <g transform="rotate(-38)">
75
+ <path d="M 0 0 L 2 -4 L -2 -4 Z" fill="#e9cfa6" />
76
+ <path d="M 0 0 L 0.7 -1.4 L -0.7 -1.4 Z" fill="#4a5160" />
77
+ <rect x="-2" y="-19" width="4" height="15" fill="#f2c14e" />
78
+ <rect x="-2" y="-22" width="4" height="3" rx="1" fill="#e88d9b" />
79
+ </g>
80
+ <ellipse
81
+ cx="3.5"
82
+ cy="-6"
83
+ rx="4"
84
+ ry="3.2"
85
+ transform="rotate(-20 3.5 -6)"
86
+ fill="currentColor"
87
+ stroke="black"
88
+ strokeOpacity="0.15"
89
+ strokeWidth="0.6"
90
+ />
91
+ </g>
92
+ </g>
93
+ );
94
+ }
package/src/extras.css CHANGED
@@ -38,9 +38,63 @@
38
38
  }
39
39
  }
40
40
 
41
+ .klex-thought {
42
+ animation: klex-thought-float 3.4s ease-in-out infinite;
43
+ }
44
+
45
+ .klex-thought-pop {
46
+ transform-box: fill-box;
47
+ transform-origin: 30% 80%;
48
+ animation: klex-thought-pop 0.42s cubic-bezier(0.3, 1.6, 0.5, 1) both;
49
+ }
50
+
51
+ .klex-thought-dot {
52
+ animation: klex-thought-dot 1.3s ease-in-out infinite both;
53
+ }
54
+
55
+ @keyframes klex-thought-float {
56
+ 0%,
57
+ 100% {
58
+ transform: translate(0, 0);
59
+ }
60
+ 50% {
61
+ transform: translate(0.8px, -1.6px);
62
+ }
63
+ }
64
+
65
+ @keyframes klex-thought-pop {
66
+ from {
67
+ opacity: 0;
68
+ transform: scale(0);
69
+ }
70
+ to {
71
+ opacity: 1;
72
+ transform: scale(1);
73
+ }
74
+ }
75
+
76
+ @keyframes klex-thought-dot {
77
+ 0%,
78
+ 100% {
79
+ opacity: 0.25;
80
+ transform: translate(0, 0);
81
+ }
82
+ 35% {
83
+ opacity: 1;
84
+ transform: translate(0, -1.2px);
85
+ }
86
+ 70% {
87
+ opacity: 0.25;
88
+ transform: translate(0, 0);
89
+ }
90
+ }
91
+
41
92
  @media (prefers-reduced-motion: reduce) {
42
93
  .klex-sleep-letters,
43
- .klex-sleep-letter {
94
+ .klex-sleep-letter,
95
+ .klex-thought,
96
+ .klex-thought-pop,
97
+ .klex-thought-dot {
44
98
  animation: none;
45
99
  }
46
100
 
package/src/extras.tsx CHANGED
@@ -14,6 +14,7 @@ export const EXTRAS = [
14
14
  { id: 'sweat', name: 'Sweat drop' },
15
15
  { id: 'sleep', name: 'Zzz' },
16
16
  { id: 'question', name: 'Question mark' },
17
+ { id: 'thought', name: 'Thought bubble' },
17
18
  { id: 'sparkles', name: 'Sparkles' },
18
19
  { id: 'steam', name: 'Steam clouds' },
19
20
  ] as const;
@@ -124,6 +125,11 @@ export function KlexExtras({
124
125
  <QuestionMark paused={paused} />
125
126
  </g>
126
127
  )}
128
+ {extra === 'thought' && (
129
+ <g transform={`translate(10 ${headTop + 2})`}>
130
+ <ThoughtBubble paused={paused} />
131
+ </g>
132
+ )}
127
133
  {extra === 'sparkles' && (
128
134
  <g fill="#ffe08b">
129
135
  <path
@@ -149,6 +155,54 @@ export function KlexExtras({
149
155
  );
150
156
  }
151
157
 
158
+ function ThoughtBubble({ paused }: { paused: boolean }) {
159
+ const play = (delay = 0) => ({
160
+ animationDelay: `${delay}s`,
161
+ animationPlayState: paused ? 'paused' : 'running',
162
+ });
163
+ return (
164
+ <g
165
+ className="klex-thought"
166
+ fill="none"
167
+ stroke="currentColor"
168
+ strokeWidth="2.5"
169
+ strokeLinecap="round"
170
+ strokeLinejoin="round"
171
+ style={play()}
172
+ >
173
+ <circle
174
+ className="klex-thought-pop"
175
+ cx="0"
176
+ cy="3"
177
+ r="1.4"
178
+ style={play()}
179
+ />
180
+ <circle
181
+ className="klex-thought-pop"
182
+ cx="5"
183
+ cy="-4"
184
+ r="2.4"
185
+ style={play(0.12)}
186
+ />
187
+ <g className="klex-thought-pop" style={play(0.24)}>
188
+ <path d="M 9 -13 C 4 -13 4 -21 9.5 -21 C 9.5 -27 18 -28 20 -24 C 23 -29 32 -28 32 -22 C 37 -22 37 -13 32 -13 C 30 -9 23 -9 21 -12 C 18 -9 11 -9 9 -13 Z" />
189
+ <g fill="currentColor" stroke="none">
190
+ {[0, 1, 2].map((index) => (
191
+ <circle
192
+ key={index}
193
+ className="klex-thought-dot"
194
+ cx={15 + index * 6}
195
+ cy="-17"
196
+ r="1.6"
197
+ style={play(0.4 + index * 0.22)}
198
+ />
199
+ ))}
200
+ </g>
201
+ </g>
202
+ </g>
203
+ );
204
+ }
205
+
152
206
  function QuestionMark({ paused }: { paused: boolean }) {
153
207
  const [scope, animate] = useAnimate<SVGGElement>();
154
208
  const reducedMotion = useReducedMotion();
package/src/geometry.ts CHANGED
@@ -101,3 +101,30 @@ export function phoneAnchor(shape: BodyShape) {
101
101
  y: y - shape.eyeY,
102
102
  };
103
103
  }
104
+
105
+ export const BOOK_LINE_LENGTH = 24;
106
+ export const bookLineY = (index: number) => 6.5 + index * 4.4;
107
+ /**
108
+ * Pen tip on the right-hand page, in book coordinates. `down` (0–1) makes it
109
+ * follow the handwriting squiggle instead of the line.
110
+ */
111
+ export function bookPenPoint(line: number, progress: number, down = 0) {
112
+ return {
113
+ x: 5 + progress * BOOK_LINE_LENGTH,
114
+ y:
115
+ bookLineY(line) -
116
+ progress * 0.8 -
117
+ Math.sin(progress * 8 * Math.PI) * down -
118
+ (1 - down) * 2.5,
119
+ };
120
+ }
121
+
122
+ /** Where the book sits for a body, shared by rendering and animation. */
123
+ export function bookPlacement(shape: BodyShape) {
124
+ const top = Math.max(84, shape.eyeY + 22);
125
+ return {
126
+ x: 80 + shape.eyeX * 0.3,
127
+ y: top,
128
+ scale: Math.min(1, Math.max(0.55, (124 - top) / 30)),
129
+ };
130
+ }
package/src/glide.ts CHANGED
@@ -9,7 +9,13 @@ import {
9
9
  REST_EMOTE,
10
10
  } from './emotes';
11
11
  import { fitGaze, gazeRoom } from './gaze';
12
- import { mirroredOutline, phoneAnchor, waveAnchor } from './geometry';
12
+ import {
13
+ bookPenPoint,
14
+ bookPlacement,
15
+ mirroredOutline,
16
+ phoneAnchor,
17
+ waveAnchor,
18
+ } from './geometry';
13
19
  import { BODY_SHAPES, type BodyShape, DEFAULT_GLIDE } from './presets';
14
20
  import { roundedPath } from './svg';
15
21
 
@@ -315,6 +321,7 @@ type GlideElements = {
315
321
  body: SVGPathElement;
316
322
  eyes: SVGGElement;
317
323
  laptop?: SVGGElement;
324
+ book?: SVGGElement;
318
325
  onFrame?: GlideFrameListener;
319
326
  /**
320
327
  * True while the renderer turns the body in depth. Turning emotes then
@@ -332,6 +339,7 @@ export function createGlide(
332
339
  body,
333
340
  eyes,
334
341
  laptop,
342
+ book,
335
343
  onFrame,
336
344
  turnsInDepth,
337
345
  }: GlideElements,
@@ -398,6 +406,10 @@ export function createGlide(
398
406
  );
399
407
  let hand = eyes.querySelector('[data-wave-anchor]');
400
408
  let phone = eyes.querySelector('[data-phone-anchor]');
409
+ const bookInk = [...(book?.querySelectorAll('[data-book-ink] > path') ?? [])];
410
+ const bookPen = book?.querySelector('[data-book-pen]');
411
+ const bookTurn = book?.querySelector('[data-book-turn]');
412
+ const bookTurnInk = book?.querySelector('[data-book-turn-ink]');
401
413
  let hop: {
402
414
  from: number;
403
415
  to: number;
@@ -409,6 +421,44 @@ export function createGlide(
409
421
  load: number;
410
422
  } | null = null;
411
423
 
424
+ function renderBook() {
425
+ if (!book) return;
426
+ const bookScale = reducedMotion
427
+ ? Number(activity === 'learning')
428
+ : activityMotion.bookScale;
429
+ const { x, y, scale: size } = bookPlacement(shape);
430
+ const pivotY = y + 26 * size;
431
+ setAttribute(
432
+ book,
433
+ 'transform',
434
+ `translate(${shape.eyeX * 0.3 * (pose.facing - 1)} ${reducedMotion ? 0 : activityMotion.learningBob}) translate(${x} ${pivotY}) scale(${bookScale}) translate(${-x} ${-pivotY})`,
435
+ );
436
+ setAttribute(book, 'opacity', String(Number(bookScale > 0)));
437
+ if (bookScale === 0) return;
438
+ const { ink, pen, turn } = activityMotion.learning;
439
+ // A turning page already shows the fresh one beneath it.
440
+ const written = reducedMotion ? 2.6 : turn > 0 ? 0 : ink;
441
+ for (const [index, line] of bookInk.entries())
442
+ setAttribute(
443
+ line,
444
+ 'stroke-dashoffset',
445
+ (1 - Math.min(1, Math.max(0, written - index))).toFixed(3),
446
+ );
447
+ const tip = reducedMotion
448
+ ? bookPenPoint(2, 0.6, 1)
449
+ : bookPenPoint(pen.line, pen.x, 1 - pen.lift);
450
+ setAttribute(
451
+ bookPen,
452
+ 'transform',
453
+ `translate(${tip.x.toFixed(2)} ${tip.y.toFixed(2)})`,
454
+ );
455
+ // The full page folds over the spine onto the left; its back is blank.
456
+ const fold = Math.cos(Math.PI * turn * turn * (3 - 2 * turn));
457
+ setAttribute(bookTurn, 'opacity', String(Number(turn > 0 && turn < 1)));
458
+ setAttribute(bookTurn, 'transform', `scale(${fold.toFixed(3)} 1)`);
459
+ setAttribute(bookTurnInk, 'opacity', String(Number(fold > 0)));
460
+ }
461
+
412
462
  function render() {
413
463
  const laptopScale = reducedMotion
414
464
  ? Number(activity === 'working')
@@ -421,6 +471,7 @@ export function createGlide(
421
471
  `translate(${shape.eyeX * 0.4 * (pose.facing - 1)} ${reducedMotion ? 0 : activityMotion.workingBob}) translate(${laptopX} ${laptopY}) scale(${laptopScale}) translate(${-laptopX} ${-laptopY})`,
422
472
  );
423
473
  setAttribute(laptop, 'opacity', String(Number(laptopScale > 0)));
474
+ renderBook();
424
475
  const resting = !busy && !transitioning && !emote;
425
476
  const restingPose = activityMotion.pose(
426
477
  reducedMotion ? activity : undefined,
@@ -444,24 +495,37 @@ export function createGlide(
444
495
  );
445
496
  const look: EmoteLook = emote
446
497
  ? emoteLook(emote.action.id, emote.time / emote.action.duration)
447
- : resting && activity === 'working'
498
+ : resting && activity === 'recalling'
448
499
  ? {
449
- expression: 'neutral',
450
- extra:
451
- !reducedMotion && activityMotion.thinking
452
- ? 'question'
453
- : undefined,
500
+ extra: 'thought',
501
+ expression: reducedMotion
502
+ ? 'neutral'
503
+ : activityMotion.recallingExpression,
454
504
  }
455
- : resting && activity === 'calling'
505
+ : resting && activity === 'learning'
456
506
  ? {
457
- extra: 'phone',
458
507
  expression: reducedMotion
459
- ? 'neutral'
460
- : activityMotion.callingExpression,
508
+ ? 'focused'
509
+ : activityMotion.learningExpression,
461
510
  }
462
- : resting && activity === 'sleeping'
463
- ? { extra: 'sleep' }
464
- : {};
511
+ : resting && activity === 'working'
512
+ ? {
513
+ expression: 'neutral',
514
+ extra:
515
+ !reducedMotion && activityMotion.thinking
516
+ ? 'question'
517
+ : undefined,
518
+ }
519
+ : resting && activity === 'calling'
520
+ ? {
521
+ extra: 'phone',
522
+ expression: reducedMotion
523
+ ? 'neutral'
524
+ : activityMotion.callingExpression,
525
+ }
526
+ : resting && activity === 'sleeping'
527
+ ? { extra: 'sleep' }
528
+ : {};
465
529
  if (
466
530
  look.expression !== lastLook.expression ||
467
531
  look.extra !== lastLook.extra
@@ -902,7 +966,7 @@ export function createGlide(
902
966
  settings = next;
903
967
  reducedMotion = reduced;
904
968
  activity = nextActivity === 'idle' && !nextIdle ? false : nextActivity;
905
- if (reduced) activityMotion.snapLaptop(activity === 'working');
969
+ if (reduced) activityMotion.snapProps(activity);
906
970
  if (reduced && emote) {
907
971
  emote = null;
908
972
  onEmoteComplete();
package/src/klex.tsx CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { Badge } from '@stagewise/ui';
18
18
 
19
19
  import type { KlexActivity } from './activity';
20
+ import { KlexBook } from './book';
20
21
  import { EMOTES, type Emote, type EmoteLook } from './emotes';
21
22
  import { type Extra, KlexExtras } from './extras';
22
23
  import { type Expression, KlexEyes } from './eyes';
@@ -187,6 +188,7 @@ export function Klex({
187
188
  const bodyRef = useRef<SVGPathElement>(null);
188
189
  const eyesRef = useRef<SVGGElement>(null);
189
190
  const laptopRef = useRef<SVGGElement>(null);
191
+ const bookRef = useRef<SVGGElement>(null);
190
192
  const motionRef = useRef<ReturnType<typeof createGlide> | null>(null);
191
193
  const canvasRef = useRef<HTMLCanvasElement>(null);
192
194
  const softShadowRef = useRef<SVGEllipseElement>(null);
@@ -255,10 +257,22 @@ export function Klex({
255
257
  const body = bodyRef.current;
256
258
  const eyes = eyesRef.current;
257
259
  const laptop = laptopRef.current;
258
- if (!travel || !actor || !shadow || !body || !eyes || !laptop) return;
260
+ const book = bookRef.current;
261
+ if (!travel || !actor || !shadow || !body || !eyes || !laptop || !book)
262
+ return;
259
263
 
260
264
  const motion = createGlide(
261
- { travel, actor, shadow, body, eyes, laptop, onFrame, turnsInDepth },
265
+ {
266
+ travel,
267
+ actor,
268
+ shadow,
269
+ body,
270
+ eyes,
271
+ laptop,
272
+ book,
273
+ onFrame,
274
+ turnsInDepth,
275
+ },
262
276
  completeMove,
263
277
  completeEmote,
264
278
  setReactionLook,
@@ -414,6 +428,15 @@ export function Klex({
414
428
  >
415
429
  <KlexLaptop shape={shape} />
416
430
  </g>
431
+ <g
432
+ ref={bookRef}
433
+ opacity="0"
434
+ visibility={extrasEnabled ? 'visible' : 'hidden'}
435
+ style={{ color }}
436
+ data-testid="klex-book"
437
+ >
438
+ <KlexBook shape={shape} />
439
+ </g>
417
440
  </>
418
441
  );
419
442
  const shadow = (
@@ -0,0 +1,126 @@
1
+ import { emotePose } from './emotes';
2
+
3
+ /** Written lines on the right-hand page before Klex turns it. */
4
+ export const BOOK_LINES = 4;
5
+ const TURN_SECONDS = 0.75;
6
+ const between = (min: number, max: number) => min + Math.random() * (max - min);
7
+
8
+ type Phase = 'writing' | 'reading' | 'pondering' | 'turning';
9
+
10
+ // Each avatar writes at its own uneven pace and pauses to reread or think.
11
+ export function createLearning() {
12
+ let phase: Phase = Math.random() < 0.7 ? 'writing' : 'reading';
13
+ const duration = () =>
14
+ phase === 'writing'
15
+ ? between(3.5, 6.5)
16
+ : phase === 'reading'
17
+ ? between(1.8, 3)
18
+ : phase === 'pondering'
19
+ ? between(1.4, 2.4)
20
+ : TURN_SECONDS;
21
+ let phaseDuration = duration();
22
+ let time = 0;
23
+ let ink = Math.floor(Math.random() * BOOK_LINES);
24
+ let speed = 0;
25
+ let speedIn = 0;
26
+ let blinkIn = between(2.5, 5);
27
+ let blinkTime = Infinity;
28
+ const pen = { x: ink % 1, line: Math.floor(ink), lift: 1 };
29
+ const pose = {
30
+ compression: 0.025,
31
+ headTilt: 0,
32
+ headSway: 0,
33
+ nod: 0.25,
34
+ lookX: 0,
35
+ lookY: 4,
36
+ };
37
+
38
+ const next = () => {
39
+ phase =
40
+ ink >= BOOK_LINES
41
+ ? 'turning'
42
+ : phase === 'writing'
43
+ ? Math.random() < 0.6
44
+ ? 'reading'
45
+ : 'pondering'
46
+ : 'writing';
47
+ phaseDuration = duration();
48
+ time = 0;
49
+ };
50
+
51
+ return {
52
+ get expression() {
53
+ return phase === 'writing' ? ('focused' as const) : ('neutral' as const);
54
+ },
55
+ /** Written share of the right-hand page, in lines. */
56
+ get ink() {
57
+ return ink;
58
+ },
59
+ /** Pen tip on the current line (0 = start, 1 = end) and its lift (1 = up). */
60
+ get pen() {
61
+ return pen;
62
+ },
63
+ /** Page turn progress from 0 to 1 while a full page turns, else 0. */
64
+ get turn() {
65
+ return phase === 'turning' ? Math.min(1, time / TURN_SECONDS) : 0;
66
+ },
67
+ advance(dt: number) {
68
+ time += dt;
69
+ blinkTime += dt;
70
+ blinkIn -= dt;
71
+ if (phase === 'turning' && time >= TURN_SECONDS) {
72
+ ink = 0;
73
+ phase = 'writing';
74
+ phaseDuration = duration();
75
+ time = 0;
76
+ } else if (time >= phaseDuration) next();
77
+ if (blinkIn <= 0) {
78
+ blinkTime = 0;
79
+ blinkIn = between(2.5, 5);
80
+ }
81
+ if (phase === 'writing') {
82
+ speedIn -= dt;
83
+ if (speedIn <= 0) {
84
+ // Words come in bursts with short gaps between them.
85
+ speedIn = between(0.25, 0.6);
86
+ speed = Math.random() < 0.2 ? 0 : between(0.35, 0.85);
87
+ }
88
+ ink = Math.min(BOOK_LINES, ink + speed * dt);
89
+ if (ink >= BOOK_LINES) next();
90
+ }
91
+ const writing = phase === 'writing';
92
+ const line = Math.min(BOOK_LINES - 1, Math.floor(ink));
93
+ const target = writing ? ink - line : pen.x;
94
+ pen.line = line;
95
+ pen.x += (target - pen.x) * (1 - Math.exp(-28 * dt));
96
+ // The pen lifts while it travels back to the start of a line.
97
+ const travelling = Math.min(1, Math.abs(target - pen.x) * 6);
98
+ pen.lift +=
99
+ ((writing && speed > 0 ? travelling : 1) - pen.lift) *
100
+ (1 - Math.exp(-20 * dt));
101
+ const scan = (time * 1.3) % 1;
102
+ const thinking = phase === 'pondering';
103
+ const targetPose = {
104
+ compression: 0.025 + (writing ? (1 - pen.lift) * 0.008 : 0),
105
+ headTilt: thinking ? -5 : writing ? 2 + pen.x * 2 : 0,
106
+ headSway: thinking ? -1 : writing ? (pen.x - 0.5) * 1.2 : 0,
107
+ nod: thinking ? -0.3 : 0.25 + (writing ? 0.1 : 0),
108
+ lookX: thinking
109
+ ? -3
110
+ : writing
111
+ ? -1 + pen.x * 4
112
+ : phase === 'reading'
113
+ ? -1 + scan * 4
114
+ : 1,
115
+ lookY: thinking ? -6 : writing ? 4 + line * 0.5 : 4,
116
+ };
117
+ const blend = 1 - Math.exp(-12 * dt);
118
+ for (const key of Object.keys(pose) as (keyof typeof pose)[])
119
+ pose[key] += (targetPose[key] - pose[key]) * blend;
120
+ },
121
+ pose() {
122
+ const blink = emotePose('blink', blinkTime / 0.3).blinkLeft;
123
+ return { ...pose, blinkLeft: blink, blinkRight: blink };
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,111 @@
1
+ import { emotePose } from './emotes';
2
+
3
+ const phases = ['pondering', 'searching', 'remembering'] as const;
4
+ const between = (min: number, max: number) => min + Math.random() * (max - min);
5
+
6
+ // Thinking is ambient: it never claims a memory was actually found.
7
+ export function createRecalling() {
8
+ let phase: (typeof phases)[number] =
9
+ Math.random() < 0.6 ? 'pondering' : 'searching';
10
+ const duration = () =>
11
+ phase === 'pondering'
12
+ ? between(3, 5.5)
13
+ : phase === 'searching'
14
+ ? between(2, 3.5)
15
+ : between(1.1, 1.6);
16
+ let phaseDuration = duration();
17
+ let time = between(0, phaseDuration * 0.5);
18
+ let blinkIn = between(2.5, 5);
19
+ let blinkTime = Infinity;
20
+ let glanceIn = 0;
21
+ let glanceX = 0;
22
+ let glanceY = -6;
23
+ const pose = {
24
+ compression: 0.01,
25
+ headTilt: 5,
26
+ headSway: 0,
27
+ nod: -0.2,
28
+ lookX: 3,
29
+ lookY: -6,
30
+ };
31
+
32
+ return {
33
+ get expression() {
34
+ return phase === 'remembering' && time > 0.2
35
+ ? ('happy' as const)
36
+ : ('neutral' as const);
37
+ },
38
+ advance(dt: number) {
39
+ time += dt;
40
+ blinkTime += dt;
41
+ blinkIn -= dt;
42
+ if (time >= phaseDuration) {
43
+ // Remembering always returns to quiet pondering.
44
+ phase =
45
+ phase === 'remembering'
46
+ ? 'pondering'
47
+ : phase === 'pondering'
48
+ ? Math.random() < 0.6
49
+ ? 'searching'
50
+ : 'remembering'
51
+ : 'remembering';
52
+ phaseDuration = duration();
53
+ time = 0;
54
+ glanceIn = 0;
55
+ blinkIn = Math.min(blinkIn, 0.15);
56
+ }
57
+ if (blinkIn <= 0) {
58
+ blinkTime = 0;
59
+ blinkIn = between(2.5, 5);
60
+ }
61
+ if (phase === 'searching') {
62
+ glanceIn -= dt;
63
+ if (glanceIn <= 0) {
64
+ // Quick saccades between places a memory might be.
65
+ glanceIn = between(0.35, 0.8);
66
+ glanceX = between(-4, 4);
67
+ glanceY = between(-7, -3);
68
+ }
69
+ }
70
+ const slow = Math.sin((time * Math.PI * 2) / 4.2);
71
+ const nod =
72
+ phase === 'remembering'
73
+ ? Math.sin(Math.min(time / 0.6, 1) * Math.PI)
74
+ : 0;
75
+ const target =
76
+ phase === 'pondering'
77
+ ? {
78
+ compression: 0.01 + 0.006 * (1 - Math.cos(time * 1.4)),
79
+ headTilt: 6 + 1.5 * slow,
80
+ headSway: 0.8 * slow,
81
+ nod: -0.25,
82
+ lookX: 3 + 0.6 * slow,
83
+ lookY: -6.5,
84
+ }
85
+ : phase === 'searching'
86
+ ? {
87
+ compression: 0.012,
88
+ headTilt: 2 + glanceX * 0.5,
89
+ headSway: glanceX * 0.2,
90
+ nod: -0.15,
91
+ lookX: glanceX,
92
+ lookY: glanceY,
93
+ }
94
+ : {
95
+ compression: 0.015 + nod * 0.03,
96
+ headTilt: 1,
97
+ headSway: 0,
98
+ nod: nod * 0.6,
99
+ lookX: 0.5,
100
+ lookY: 0,
101
+ };
102
+ const blend = 1 - Math.exp((phase === 'searching' ? -16 : -8) * dt);
103
+ for (const key of Object.keys(pose) as (keyof typeof pose)[])
104
+ pose[key] += (target[key] - pose[key]) * blend;
105
+ },
106
+ pose() {
107
+ const blink = emotePose('blink', blinkTime / 0.3).blinkLeft;
108
+ return { ...pose, blinkLeft: blink, blinkRight: blink };
109
+ },
110
+ };
111
+ }