@klex/mascot 0.0.0-stage → 0.1.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/src/extras.tsx ADDED
@@ -0,0 +1,241 @@
1
+ import './extras.css';
2
+
3
+ import { useAnimate, useReducedMotion } from 'motion/react';
4
+ import { useEffect, useLayoutEffect, useRef } from 'react';
5
+
6
+ import { popTransition } from './transitions';
7
+
8
+ export const EXTRAS = [
9
+ { id: 'none', name: 'None' },
10
+ { id: 'wave', name: 'Wave' },
11
+ { id: 'phone', name: 'Phone' },
12
+ { id: 'blush', name: 'Blush' },
13
+ { id: 'tear', name: 'Tear' },
14
+ { id: 'sweat', name: 'Sweat drop' },
15
+ { id: 'sleep', name: 'Zzz' },
16
+ { id: 'question', name: 'Question mark' },
17
+ { id: 'sparkles', name: 'Sparkles' },
18
+ { id: 'steam', name: 'Steam clouds' },
19
+ ] as const;
20
+ export type Extra = (typeof EXTRAS)[number]['id'];
21
+
22
+ // Coordinates are relative to the shared face anchor, not a particular body.
23
+ export function KlexExtras({
24
+ extra = 'none',
25
+ headTop = -36,
26
+ handAnchor,
27
+ phoneAnchor,
28
+ paused = false,
29
+ transient = false,
30
+ }: {
31
+ extra?: Extra;
32
+ headTop?: number;
33
+ handAnchor: { x: number; y: number };
34
+ phoneAnchor: { x: number; y: number };
35
+ paused?: boolean;
36
+ transient?: boolean;
37
+ }) {
38
+ return (
39
+ <g data-extra={extra}>
40
+ {extra === 'wave' && (
41
+ <g
42
+ data-wave-anchor
43
+ transform={`translate(${handAnchor.x} ${handAnchor.y})`}
44
+ >
45
+ <WaveHand paused={paused} transient={transient} />
46
+ </g>
47
+ )}
48
+ {extra === 'phone' && (
49
+ <g
50
+ data-phone-anchor
51
+ transform={`translate(${phoneAnchor.x} ${phoneAnchor.y})`}
52
+ >
53
+ {/* Twemoji v17.0.3 telephone receiver (U+1F4DE), © Twitter, Inc. and other contributors, CC BY 4.0. Source: https://github.com/jdecked/twemoji/blob/v17.0.3/assets/svg/1f4de.svg. See LICENSE-TWEMOJI.txt. */}
54
+ <path
55
+ fill="#31373D"
56
+ transform="rotate(-45) scale(-1 1) translate(-7 -7)"
57
+ d="M34.06 26.407l-3.496-3.496c-1.93-1.93-5.06-1.93-6.989 0-.719.718-1.167 1.603-1.351 2.528-5.765-1.078-11.372-6.662-11.721-11.653.947-.176 1.854-.627 2.586-1.36 1.93-1.93 1.93-5.06 0-6.99L9.594 1.94c-1.93-1.93-5.06-1.93-6.99 0-10.486 10.486 20.97 41.942 31.456 31.456 1.929-1.929 1.929-5.059 0-6.989z"
58
+ />
59
+ <ellipse
60
+ cx="8"
61
+ cy="16"
62
+ rx="4.5"
63
+ ry="6"
64
+ transform="rotate(15 8 16)"
65
+ fill="currentColor"
66
+ />
67
+ </g>
68
+ )}
69
+ {extra === 'blush' && (
70
+ <g fill="#ef7b95" opacity="0.7">
71
+ <ellipse cx="-13" cy="11" rx="5" ry="2.7" />
72
+ <ellipse cx="13" cy="11" rx="5" ry="2.7" />
73
+ </g>
74
+ )}
75
+ {extra === 'tear' && (
76
+ <path
77
+ d="M 11 5 C 10 10 5 13 7 17 C 10 23 19 17 15 12 Z"
78
+ fill="#74c8f7"
79
+ />
80
+ )}
81
+ {extra === 'sweat' && (
82
+ <path
83
+ d="M 23 -17 C 21 -10 16 -6 19 -2 C 23 3 30 -2 26 -8 Z"
84
+ fill="#74c8f7"
85
+ />
86
+ )}
87
+ {extra === 'sleep' && (
88
+ <g
89
+ transform={`translate(8 ${headTop})`}
90
+ fill="none"
91
+ stroke="currentColor"
92
+ strokeWidth="2.5"
93
+ strokeLinecap="round"
94
+ strokeLinejoin="round"
95
+ >
96
+ <g
97
+ className="klex-sleep-letters"
98
+ style={{ animationPlayState: paused ? 'paused' : 'running' }}
99
+ >
100
+ {[0, 1, 2].map((index) => (
101
+ <g
102
+ key={index}
103
+ className="klex-sleep-letter"
104
+ transform={`translate(${index * 16} ${-index * 20}) scale(${0.7 + index * 0.25})`}
105
+ style={{
106
+ animationDelay: `${-index * 1.2}s`,
107
+ animationPlayState: paused ? 'paused' : 'running',
108
+ }}
109
+ >
110
+ <path d="M -6 -6 H 6 L -6 6 H 6" />
111
+ </g>
112
+ ))}
113
+ </g>
114
+ </g>
115
+ )}
116
+ {extra === 'question' && (
117
+ <g
118
+ transform={`translate(0 ${headTop - 4})`}
119
+ fill="none"
120
+ stroke="currentColor"
121
+ strokeWidth="2.5"
122
+ strokeLinecap="round"
123
+ >
124
+ <QuestionMark paused={paused} />
125
+ </g>
126
+ )}
127
+ {extra === 'sparkles' && (
128
+ <g fill="#ffe08b">
129
+ <path
130
+ d={`M -35 ${headTop + 9} l 2 -7 2 7 7 2 -7 2 -2 7 -2 -7 -7 -2 Z`}
131
+ />
132
+ <path
133
+ d={`M 30 ${headTop - 3} l 2 -6 2 6 6 2 -6 2 -2 6 -2 -6 -6 -2 Z`}
134
+ />
135
+ <path d="M 29 9 l 1.5 -4 1.5 4 4 1.5 -4 1.5 -1.5 4 -1.5 -4 -4 -1.5 Z" />
136
+ </g>
137
+ )}
138
+ {extra === 'steam' && (
139
+ <g
140
+ transform={`translate(0 ${headTop})`}
141
+ fill="currentColor"
142
+ opacity="0.65"
143
+ >
144
+ <path d="M -22 5 C -38 6 -40 -4 -33 -6 C -40 -15 -26 -20 -23 -11 C -16 -17 -10 -6 -19 -3 Z" />
145
+ <path d="M 22 5 C 38 6 40 -4 33 -6 C 40 -15 26 -20 23 -11 C 16 -17 10 -6 19 -3 Z" />
146
+ </g>
147
+ )}
148
+ </g>
149
+ );
150
+ }
151
+
152
+ function QuestionMark({ paused }: { paused: boolean }) {
153
+ const [scope, animate] = useAnimate<SVGGElement>();
154
+ const reducedMotion = useReducedMotion();
155
+ const playback = useRef<ReturnType<typeof animate> | null>(null);
156
+ useLayoutEffect(() => {
157
+ const animation = animate(
158
+ scope.current,
159
+ { scale: reducedMotion ? 1 : [0, 1] },
160
+ reducedMotion ? { duration: 0 } : popTransition,
161
+ );
162
+ playback.current = animation;
163
+ return () => {
164
+ animation.stop();
165
+ playback.current = null;
166
+ };
167
+ }, [animate, scope, reducedMotion]);
168
+ // biome-ignore lint/correctness/useExhaustiveDependencies: Reapply pause when reduced motion replaces playback.
169
+ useEffect(() => {
170
+ if (paused) playback.current?.pause();
171
+ else playback.current?.play();
172
+ }, [paused, reducedMotion]);
173
+ return (
174
+ <g ref={scope} style={{ transformOrigin: '1px 6px' }}>
175
+ <path d="M -4 -6 C -4 -14 7 -14 7 -7 C 7 -3 1 -3 1 1" />
176
+ <path d="M 1 6 V 6.1" />
177
+ </g>
178
+ );
179
+ }
180
+
181
+ function WaveHand({
182
+ paused,
183
+ transient,
184
+ }: {
185
+ paused: boolean;
186
+ transient: boolean;
187
+ }) {
188
+ const [scope, animate] = useAnimate<SVGGElement>();
189
+ const reducedMotion = useReducedMotion();
190
+ const playback = useRef<ReturnType<typeof animate> | null>(null);
191
+ useLayoutEffect(() => {
192
+ const animation = animate([
193
+ [
194
+ scope.current,
195
+ { scale: reducedMotion ? 1 : [0, 1] },
196
+ reducedMotion ? { duration: 0 } : popTransition,
197
+ ],
198
+ [
199
+ scope.current,
200
+ { rotate: reducedMotion ? 0 : [0, 0, 20, -16, 20, -12, 0, 0] },
201
+ { at: 0, duration: reducedMotion ? 0 : 2.2 },
202
+ ],
203
+ [
204
+ scope.current,
205
+ { scale: transient && !reducedMotion ? 0 : 1 },
206
+ {
207
+ at: reducedMotion ? 0 : 2.08,
208
+ duration: reducedMotion ? 0 : 0.12,
209
+ ease: 'easeIn',
210
+ },
211
+ ],
212
+ ]);
213
+ playback.current = animation;
214
+ return () => {
215
+ animation.stop();
216
+ playback.current = null;
217
+ };
218
+ }, [animate, scope, reducedMotion, transient]);
219
+ // Reapply pause state when the animation above is recreated.
220
+ // biome-ignore lint/correctness/useExhaustiveDependencies: These dependencies replace the playback instance.
221
+ useEffect(() => {
222
+ if (paused) playback.current?.pause();
223
+ else playback.current?.play();
224
+ }, [paused, reducedMotion, transient]);
225
+ return (
226
+ <g ref={scope} style={{ transformOrigin: '0px 8px' }}>
227
+ <text
228
+ x="-15"
229
+ y="8"
230
+ transform="scale(-1 1)"
231
+ fontSize="30"
232
+ style={{
233
+ fontFamily:
234
+ 'Apple Color Emoji, Segoe UI Emoji, Noto Color Emoji, sans-serif',
235
+ }}
236
+ >
237
+ 👋
238
+ </text>
239
+ </g>
240
+ );
241
+ }
package/src/eyes.tsx ADDED
@@ -0,0 +1,179 @@
1
+ import { useId } from 'react';
2
+
3
+ export const EXPRESSIONS = [
4
+ { id: 'neutral', name: 'Neutral' },
5
+ { id: 'happy', name: 'Happy' },
6
+ { id: 'angry', name: 'Angry' },
7
+ { id: 'skeptical', name: 'Skeptical' },
8
+ { id: 'annoyed', name: 'Annoyed' },
9
+ { id: 'sad', name: 'Sad' },
10
+ { id: 'pained', name: 'Pained' },
11
+ { id: 'sleepy', name: 'Sleepy' },
12
+ { id: 'surprised', name: 'Surprised' },
13
+ { id: 'focused', name: 'Focused' },
14
+ { id: 'unsure', name: 'Unsure' },
15
+ { id: 'embarrassed', name: 'Embarrassed' },
16
+ { id: 'suspicious', name: 'Suspicious' },
17
+ { id: 'hearts', name: 'Heart eyes' },
18
+ { id: 'stars', name: 'Star eyes' },
19
+ { id: 'spirals', name: 'Spiral eyes' },
20
+ { id: 'x-eyes', name: 'X eyes' },
21
+ ] as const;
22
+ export type Expression = (typeof EXPRESSIONS)[number]['id'];
23
+
24
+ function eyeShape(expression: Expression) {
25
+ switch (expression) {
26
+ case 'hearts':
27
+ return <path d="M 0 5.5 C -13 -2 -3 -10 0 -4 C 3 -10 13 -2 0 5.5 Z" />;
28
+ case 'stars':
29
+ return (
30
+ <path d="M 0 -7 2 -2 7 -2 3 1 4.5 6 0 3 -4.5 6 -3 1 -7 -2 -2 -2 Z" />
31
+ );
32
+ case 'spirals':
33
+ return (
34
+ <path
35
+ d="M 0 0 C -2 -2 -3 2 0 3 C 5 4 6 -4 1 -5 C -5 -7 -8 2 -4 6"
36
+ fill="none"
37
+ stroke="currentColor"
38
+ strokeWidth="1.7"
39
+ strokeLinecap="round"
40
+ />
41
+ );
42
+ case 'pained':
43
+ return (
44
+ <path
45
+ d="M -4 -3 2 0 -4 3"
46
+ fill="none"
47
+ stroke="currentColor"
48
+ strokeWidth="2.6"
49
+ strokeLinecap="round"
50
+ strokeLinejoin="round"
51
+ />
52
+ );
53
+ case 'x-eyes':
54
+ return (
55
+ <path
56
+ d="M -4 -4 4 4 M 4 -4 -4 4"
57
+ fill="none"
58
+ stroke="currentColor"
59
+ strokeWidth="2.5"
60
+ strokeLinecap="round"
61
+ />
62
+ );
63
+ default:
64
+ return (
65
+ <ellipse
66
+ rx={expression === 'surprised' ? 5.6 : 4.5}
67
+ ry={expression === 'sleepy' ? 4.5 : 6.5}
68
+ />
69
+ );
70
+ }
71
+ }
72
+
73
+ // Masks expose the actual body color. The outer groups stay mounted so the
74
+ // shared ticker can blink each eye without triggering React renders.
75
+ export function KlexEyes({
76
+ expression = 'neutral',
77
+ }: {
78
+ expression?: Expression;
79
+ }) {
80
+ const id = useId();
81
+ return (
82
+ <g data-expression={expression}>
83
+ {(['left', 'right'] as const).map((side, index) => {
84
+ const mask = `${id}-${side}`;
85
+ const sign = index === 0 ? 1 : -1;
86
+ const cut =
87
+ expression === 'angry' ||
88
+ expression === 'sad' ||
89
+ expression === 'focused'
90
+ ? -2
91
+ : expression === 'annoyed' || expression === 'suspicious'
92
+ ? -0.5
93
+ : expression === 'sleepy'
94
+ ? 1
95
+ : expression === 'skeptical' && index === 0
96
+ ? -0.5
97
+ : expression === 'unsure' && index === 1
98
+ ? -2
99
+ : -10;
100
+ const slope =
101
+ (expression === 'angry'
102
+ ? 27
103
+ : expression === 'sad'
104
+ ? -24
105
+ : expression === 'focused'
106
+ ? 12
107
+ : 0) * sign;
108
+ const shiftX =
109
+ expression === 'suspicious'
110
+ ? 1.5
111
+ : expression === 'embarrassed'
112
+ ? -1
113
+ : 0;
114
+ const shiftY = expression === 'embarrassed' ? 1.5 : 0;
115
+ return (
116
+ <g key={side} transform={`translate(${sign * -9} 0)`}>
117
+ <g data-eye={side}>
118
+ <g transform={`translate(${shiftX} ${shiftY})`}>
119
+ <defs>
120
+ <mask
121
+ id={mask}
122
+ maskUnits="userSpaceOnUse"
123
+ x="-10"
124
+ y="-10"
125
+ width="20"
126
+ height="20"
127
+ >
128
+ <rect x="-10" y="-10" width="20" height="20" fill="white" />
129
+ <rect
130
+ x="-16"
131
+ y="-20"
132
+ width="32"
133
+ height="20"
134
+ fill="black"
135
+ data-eyelid="upper"
136
+ style={{
137
+ transform: `translateY(${cut}px) rotate(${slope}deg)`,
138
+ }}
139
+ className="transition-transform duration-200 ease-out motion-reduce:transition-none"
140
+ />
141
+ <ellipse
142
+ cy="7.5"
143
+ rx="6"
144
+ ry="6.5"
145
+ fill="black"
146
+ data-eyelid="happy"
147
+ style={{
148
+ transform: `translateY(${expression === 'happy' ? 0 : 15}px)`,
149
+ }}
150
+ className="transition-transform duration-200 ease-out motion-reduce:transition-none"
151
+ />
152
+ </mask>
153
+ </defs>
154
+ <g
155
+ mask={`url(#${mask})`}
156
+ data-eye-shape={expression}
157
+ transform={
158
+ expression === 'pained' ? `scale(${sign} 1)` : undefined
159
+ }
160
+ >
161
+ {eyeShape(expression)}
162
+ </g>
163
+ </g>
164
+ </g>
165
+ <path
166
+ data-eye-closed={side}
167
+ d="M -4.5 0 H 4.5"
168
+ fill="none"
169
+ stroke="currentColor"
170
+ strokeWidth="1.8"
171
+ strokeLinecap="round"
172
+ opacity="0"
173
+ />
174
+ </g>
175
+ );
176
+ })}
177
+ </g>
178
+ );
179
+ }
package/src/gaze.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { REST_EMOTE } from './emotes';
2
+ import { bodyContour } from './geometry';
3
+ import type { BodyShape } from './presets';
4
+
5
+ // Measure once per body shape. Sampling the same periodic B-spline as the
6
+ // body keeps custom eye placement from gaining unsafe extra travel.
7
+ export function gazeRoom(shape: BodyShape) {
8
+ const contour = bodyContour(shape);
9
+ let clearance = Infinity;
10
+ for (const offset of [-9, 9]) {
11
+ const eyeX = 80 + shape.eyeX + offset;
12
+ for (let i = 0; i < contour.length; i++) {
13
+ const [ax = 0, ay = 0] = contour[i] ?? [];
14
+ const [bx = ax, by = ay] = contour[(i + 1) % contour.length] ?? [];
15
+ const dx = bx - ax;
16
+ const dy = by - ay;
17
+ const t = Math.max(
18
+ 0,
19
+ Math.min(
20
+ 1,
21
+ ((eyeX - ax) * dx + (shape.eyeY - ay) * dy) /
22
+ (dx * dx + dy * dy || 1),
23
+ ),
24
+ );
25
+ clearance = Math.min(
26
+ clearance,
27
+ Math.hypot(eyeX - ax - t * dx, shape.eyeY - ay - t * dy),
28
+ );
29
+ }
30
+ }
31
+ // Room for the largest eye symbol and the static expression's small offset.
32
+ return Math.max(0, clearance - 8.5);
33
+ }
34
+
35
+ export function fitGaze(reaction: typeof REST_EMOTE, room: number) {
36
+ const distance = Math.hypot(reaction.lookX, reaction.lookY);
37
+ if (distance <= room || distance === 0) return reaction;
38
+ const ratio = room / distance;
39
+ return {
40
+ ...reaction,
41
+ lookX: reaction.lookX * ratio,
42
+ lookY: reaction.lookY * ratio,
43
+ // The head follows the remaining distance. Even a narrow drawn head can
44
+ // make a pronounced glance without the eyes leaving its silhouette.
45
+ gazeHeadX: reaction.lookX * (1 - ratio),
46
+ gazeHeadY: reaction.lookY * (1 - ratio),
47
+ };
48
+ }
@@ -0,0 +1,103 @@
1
+ import type { BodyShape } from './presets';
2
+
3
+ const mirroredOutlines = new WeakMap<BodyShape, BodyShape['outline']>();
4
+
5
+ // Align the mirrored contour before interpolating a turn. Custom outlines can
6
+ // start anywhere, so reversing their indices alone pairs unrelated body parts.
7
+ export function mirroredOutline(shape: BodyShape) {
8
+ const cached = mirroredOutlines.get(shape);
9
+ if (cached) return cached;
10
+ const { outline } = shape;
11
+ const count = outline.length;
12
+ let bestOffset = 0;
13
+ let bestFloorMismatches = Infinity;
14
+ let bestDistance = Infinity;
15
+ for (let offset = 0; offset < count; offset++) {
16
+ let floorMismatches = 0;
17
+ const distance = outline.reduce((sum, [x, y], index) => {
18
+ const [mirrorX, mirrorY] = outline[(offset - index + count) % count] ?? [
19
+ x,
20
+ y,
21
+ ];
22
+ if ((y === 128) !== (mirrorY === 128)) floorMismatches++;
23
+ return sum + (x - (160 - mirrorX)) ** 2 + (y - mirrorY) ** 2;
24
+ }, 0);
25
+ // Keep the sole grounded, then align the rest of the silhouette.
26
+ if (
27
+ floorMismatches < bestFloorMismatches ||
28
+ (floorMismatches === bestFloorMismatches && distance < bestDistance)
29
+ ) {
30
+ bestFloorMismatches = floorMismatches;
31
+ bestDistance = distance;
32
+ bestOffset = offset;
33
+ }
34
+ }
35
+ const mirrored = outline.map((point, index) => {
36
+ const [x, y] = outline[(bestOffset - index + count) % count] ?? point;
37
+ return [160 - x, y] as const;
38
+ });
39
+ mirroredOutlines.set(shape, mirrored);
40
+ return mirrored;
41
+ }
42
+
43
+ // Sample the same periodic B-spline used to draw the body.
44
+ export function bodyContour(shape: BodyShape) {
45
+ const outline = shape.outline;
46
+ return outline.flatMap((point, i) => {
47
+ const previous =
48
+ outline[(i + outline.length - 1) % outline.length] ?? point;
49
+ const next = outline[(i + 1) % outline.length] ?? point;
50
+ const after = outline[(i + 2) % outline.length] ?? point;
51
+ return Array.from({ length: 8 }, (_, sample) => {
52
+ const t = sample / 8;
53
+ const weights = [
54
+ (1 - t) ** 3 / 6,
55
+ (3 * t ** 3 - 6 * t ** 2 + 4) / 6,
56
+ (-3 * t ** 3 + 3 * t ** 2 + 3 * t + 1) / 6,
57
+ t ** 3 / 6,
58
+ ];
59
+ return [0, 1].map((axis) =>
60
+ [previous, point, next, after].reduce(
61
+ (sum, p, index) => sum + (p[axis] ?? 0) * (weights[index] ?? 0),
62
+ 0,
63
+ ),
64
+ );
65
+ });
66
+ });
67
+ }
68
+
69
+ // Place the hand just outside the right edge, halfway down the body.
70
+ export function waveAnchor(shape: BodyShape) {
71
+ const contour = bodyContour(shape);
72
+ const heights = contour.map((point) => point[1] ?? 0);
73
+ const y = (Math.min(...heights) + Math.max(...heights)) / 2;
74
+ const right = rightEdge(contour, y);
75
+ // Extras share the face coordinate system; the emoji sits above its baseline.
76
+ return { x: right + 10 - (80 + shape.eyeX), y: y + 6 - shape.eyeY };
77
+ }
78
+
79
+ function rightEdge(contour: number[][], y: number) {
80
+ let right = -Infinity;
81
+ for (let i = 0; i < contour.length; i++) {
82
+ const [ax = 0, ay = 0] = contour[i] ?? [];
83
+ const [bx = ax, by = ay] = contour[(i + 1) % contour.length] ?? [];
84
+ if (ay > y !== by > y) {
85
+ right = Math.max(right, ax + ((y - ay) / (by - ay)) * (bx - ax));
86
+ }
87
+ }
88
+ return right;
89
+ }
90
+
91
+ // The earpiece rests just outside the head, slightly above the eyes.
92
+ export function phoneAnchor(shape: BodyShape) {
93
+ const contour = bodyContour(shape);
94
+ const heights = contour.map((point) => point[1] ?? 0);
95
+ const y = Math.max(
96
+ Math.min(...heights) + 2,
97
+ Math.min(Math.max(...heights) - 2, shape.eyeY - 9),
98
+ );
99
+ return {
100
+ x: rightEdge(contour, y) + 3 - (80 + shape.eyeX),
101
+ y: y - shape.eyeY,
102
+ };
103
+ }