@kodax-ai/botui 0.1.1 → 0.1.3

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 (53) hide show
  1. package/README.md +140 -113
  2. package/core/identity.js +46 -0
  3. package/{themes/solids → core}/motion.js +114 -114
  4. package/core/registry.js +26 -18
  5. package/docs/usage.md +202 -0
  6. package/element.js +5 -0
  7. package/index.d.ts +2 -0
  8. package/index.js +11 -5
  9. package/package.json +38 -2
  10. package/themes/caret/README.md +43 -0
  11. package/themes/caret/avatar.js +10 -0
  12. package/themes/caret/engine.js +143 -0
  13. package/themes/caret/index.d.ts +24 -0
  14. package/themes/caret/index.js +35 -0
  15. package/themes/critter/README.md +43 -0
  16. package/themes/critter/avatar.js +12 -0
  17. package/themes/critter/engine.js +113 -0
  18. package/themes/critter/index.d.ts +28 -0
  19. package/themes/critter/index.js +35 -0
  20. package/themes/doodle/README.md +43 -0
  21. package/themes/doodle/avatar.js +10 -0
  22. package/themes/doodle/engine.js +149 -0
  23. package/themes/doodle/index.d.ts +24 -0
  24. package/themes/doodle/index.js +36 -0
  25. package/themes/dots/README.md +42 -0
  26. package/themes/dots/avatar.js +15 -0
  27. package/themes/dots/engine.js +179 -0
  28. package/themes/dots/index.d.ts +24 -0
  29. package/themes/dots/index.js +35 -0
  30. package/themes/kaomoji/README.md +42 -0
  31. package/themes/kaomoji/avatar.js +10 -0
  32. package/themes/kaomoji/engine.js +110 -0
  33. package/themes/kaomoji/index.d.ts +24 -0
  34. package/themes/kaomoji/index.js +35 -0
  35. package/themes/liquid/README.md +47 -0
  36. package/themes/liquid/avatar.js +10 -0
  37. package/themes/liquid/engine.js +161 -0
  38. package/themes/liquid/index.d.ts +24 -0
  39. package/themes/liquid/index.js +35 -0
  40. package/themes/matrix/README.md +48 -0
  41. package/themes/matrix/avatar.js +227 -0
  42. package/themes/matrix/engine.js +479 -0
  43. package/themes/matrix/index.d.ts +47 -0
  44. package/themes/matrix/index.js +34 -0
  45. package/themes/orb/README.md +44 -0
  46. package/themes/orb/avatar.js +10 -0
  47. package/themes/orb/engine.js +130 -0
  48. package/themes/orb/index.d.ts +24 -0
  49. package/themes/orb/index.js +36 -0
  50. package/themes/solids/README.md +2 -2
  51. package/themes/solids/avatar.js +561 -579
  52. package/themes/solids/face.js +52 -56
  53. package/themes/solids/index.js +34 -28
@@ -0,0 +1,161 @@
1
+ // The liquid theme's model: the matrix theme's tile as a glass, filled with the Bot's colour.
2
+ //
3
+ // No eyes: the surface of the liquid is the face. It smiles (the edges climb the
4
+ // glass), droops when sad, boils when angry, lies flat and low when asleep. The
5
+ // liquid stays level as the glass tilts, and sloshes behind when it jumps or
6
+ // spins. Bubbles rise while it works; progress is how full it is.
7
+ //
8
+ // Everything else (outline, motion, marks, particles, halo, handling) is the
9
+ // matrix model's. Pure, like it: no DOM, no clock, no Math.random. The one
10
+ // exception is a counter in the clip id, so two glasses on a page never share one.
11
+ // Sketched in avatar-lab as direction U (液面), made a theme on 2026-11-28.
12
+
13
+ import {Matrix} from '../matrix/engine.js';
14
+ import {TAU, ease, clamp} from '../../core/core.js';
15
+
16
+ const {sin, cos, tan, abs, max, min, floor} = Math;
17
+ const fixed = v => v.toFixed(2);
18
+ const TOP = 12, BOTTOM = 88, LEFT = 10, RIGHT = 90, COLS = 24, BUBBLES = 7, SLOSH = 60, SLOSH_DAMP = 3.2;
19
+ const HEART = 15;
20
+ let made = 0;
21
+
22
+ /** The eye styles become the bubbles: dot (圆点) a few big ones, bar (竖条) medium, tall (长条) many small. */
23
+ const FIZZ = {dot: {r: 3.2, n: 4}, bar: {r: 2.3, n: 6}, tall: {r: 1.6, n: 7}};
24
+ export const liquidEyes = Object.freeze(Object.keys(FIZZ));
25
+
26
+ // ---- the face: the surface ----
27
+ // curve: + smiles (the edges climb), - droops. wave: ripple height. chop: how fast and broken the ripples are.
28
+ // tilt: a lean of the surface. boil: extra bubbles. lean: a hue the colour leans toward.
29
+ const S = (curve = 0, wave = 0.6, extra) => ({curve, wave, chop: 1, tilt: 0, boil: 0, ...extra});
30
+ /** The 21 expressions, each a way the surface sits: (t) -> {curve, wave, chop, tilt, boil, lean}. */
31
+ export const FACES = {
32
+ neutral: () => S(),
33
+ wide: () => S(0, 2.2, {chop: 1.4}),
34
+ happy: () => S(20, 0.8),
35
+ closed: () => S(0, 0.2),
36
+ sleep: () => S(-3, 0.15, {chop: 0.4}),
37
+ squint: () => S(13, 1.6, {chop: 1.8}),
38
+ sad: () => S(-17, 0.3, {chop: 0.5, lean: 250}),
39
+ focus: () => S(0, 0.1),
40
+ angry: () => S(-6, 2.6, {chop: 2.6, boil: 1, lean: 25}),
41
+ calm: () => S(8, 0.3, {chop: 0.5}),
42
+ sleepy: () => S(0, 0.2, {chop: 0.4}),
43
+ shy: () => S(7, 0.5, {lean: HEART}),
44
+ inspecting: () => S(0, 0.4, {tilt: 0.16}),
45
+ confused: t => S(0, 1, {tilt: 0.14 * sin(t * 2.4)}),
46
+ wink: () => S(13, 0.6, {tilt: -0.1}),
47
+ skeptic: () => S(-3, 0.3, {tilt: 0.2}),
48
+ cross: () => S(-2, 1.8, {chop: 3}),
49
+ surprised: () => S(0, 3.4, {chop: 1.6}),
50
+ dizzy: t => S(0, 1.8, {tilt: 0.24 * sin(t * 3.3)}),
51
+ love: () => S(15, 0.8, {boil: 0.6, lean: HEART}),
52
+ sparkle: () => S(15, 1.2, {boil: 1}),
53
+ };
54
+
55
+ // ---- the states: how full, and how lively ----
56
+ // level: 0 empty .. 1 full (null keeps the default). bubbles: 0..1. speed: of the ripples.
57
+ const M = (level, bubbles = 0, speed = 1, extra) => ({level, bubbles, speed, ...extra});
58
+ const WORK = M(0.58, 0.8, 1.5);
59
+ export const MOODS = {
60
+ idle: M(0.56, 0.15, 0.8), listening: M(0.6, 0.2, 1),
61
+ thinking: M(0.58, 0.6, 1.2, {swirl: 1}), searching: WORK, reading: WORK, working: WORK, coding: WORK, running: M(0.58, 0.9, 2.2), computing: M(0.58, 1, 1.8), controlling: WORK,
62
+ streaming: M(0.6, 0.5, 2.4), writing: M(0.6, 0.5, 1.6), dictating: M(0.6, 0.4, 2),
63
+ loading: M(0.56, 0.3, 1.2, {pump: 1}), orbit: M(0.58, 0.6, 1.4, {swirl: 1}), radar: M(0.58, 0.4, 1.2, {swirl: 1}),
64
+ progress: M(null, 0.5, 1.2, {fill: 1}), spawning: M(null, 0.6, 1.4, {grow: 1}),
65
+ sending: M(0.56, 0.3, 1.6, {flow: 1}), receiving: M(0.56, 0.3, 1.6, {flow: -1}), uploading: M(0.56, 1, 1.6, {rise: 1}),
66
+ finished: M(0.66, 0.7, 1.2), approving: M(0.64, 0.4, 1), proud: M(0.66, 0.3, 1),
67
+ excited: M(0.7, 1, 2), celebrating: M(0.72, 1, 2.2), laughing: M(0.66, 0.8, 2.4), happy: M(0.64, 0.5, 1.3), playful: M(0.62, 0.5, 1.6),
68
+ angry: M(0.6, 1, 2.4), error: M(0.42, 0, 0.6, {lean: 25}), alerting: M(0.6, 0.6, 2.2, {lean: 45}),
69
+ sad: M(0.38, 0, 0.5), scared: M(0.46, 0.2, 2.6), blocked: M(0.4, 0, 0.3),
70
+ sleeping: M(0.34, 0, 0.35), drowsy: M(0.42, 0, 0.5), bored: M(0.4, 0, 0.5),
71
+ 'powering-down': M(0.2, 0, 0.2, {drain: 1}), loving: M(0.62, 0.6, 1, {lean: HEART}),
72
+ };
73
+ const IDLE = MOODS.idle;
74
+ const pseudo = i => { const s = sin(i * 12.9898 + 78.233) * 43758.5453; return s - floor(s); };
75
+
76
+ class Liquid extends Matrix {
77
+ tileLayout(ink, node) {
78
+ const [outline] = super.tileLayout(ink, node), id = `botui-liquid-${++made}-clip`;
79
+ this.fluid = {level: IDLE.level, slope: 0, vslope: 0, curve: 0, wave: 0.6, chop: 1, tilt: 0, boil: 0, bubbles: 0.15, speed: 0.8, mix: 0, lean: null, phase: this.rng() * 10, rise: this.rng() * 10, splash: 0};
80
+ this.lastRoll = 0;
81
+ const defs = node('tile', 'defs'), clip = node('tile', 'clipPath', {id}, defs), inside = node('tile', 'g', {'clip-path': `url(#${id})`});
82
+ return [
83
+ defs, clip, node('tile', 'path', {d: outline.attrs.d}, clip),
84
+ // The glass, the back of the liquid, the liquid, the bright line of its surface, the bubbles, a glint on the glass.
85
+ {...outline, attrs: {...outline.attrs, 'stroke-width': 2.2}}, inside,
86
+ node('tile', 'path', {}, inside), node('tile', 'path', {}, inside),
87
+ node('tile', 'path', {fill: 'none', 'stroke-linecap': 'round', 'stroke-width': 2.2}, inside),
88
+ ...Array.from({length: BUBBLES}, () => node('tile', 'circle', {fill: 'none', 'stroke-width': 1.3}, inside)),
89
+ node('tile', 'path', {fill: 'none', stroke: '#fff', 'stroke-linecap': 'round', 'stroke-width': 3, d: 'M24,34Q27,24 36,20'}),
90
+ ];
91
+ }
92
+ /** Where the fluid is heading this frame: the state's mood with the expression's surface on top. */
93
+ want() {
94
+ const mood = (!this.forced && MOODS[this.state]) || IDLE, face = (FACES[this.shown] || FACES.neutral)(this.t);
95
+ let level = mood.level ?? IDLE.level;
96
+ if (mood.fill) level = 0.08 + 0.84 * clamp(this.progress ?? (this.t * 0.22) % 1, 0, 1);
97
+ if (mood.grow) level = 0.56 * clamp(this.since / 1.2, 0, 1);
98
+ if (mood.drain) level = max(0.06, 0.56 - this.since * 0.4);
99
+ if (mood.pump) level += 0.1 * sin(this.t * 3);
100
+ return {...face, level, bubbles: clamp(mood.bubbles + face.boil * 0.6, 0, 1), speed: mood.speed * face.chop, lean: face.lean ?? mood.lean ?? null, mood};
101
+ }
102
+ drawTile(nodes, n, {dt, ink, dim}) {
103
+ const want = this.want(), f = this.fluid, tone = this.tone, p = this.p, roll = p.roll + this.g.roll;
104
+ if (dt === null) {
105
+ Object.assign(f, {level: want.level, curve: want.curve, wave: want.wave, chop: want.chop, tilt: want.tilt, bubbles: want.bubbles, speed: want.speed, slope: 0, vslope: 0, splash: 0});
106
+ f.lean = want.lean; f.mix = want.lean == null ? 0 : 1; this.lastRoll = roll;
107
+ } else {
108
+ f.level = ease(f.level, want.level, dt, 2.5);
109
+ for (const key of ['curve', 'wave', 'chop', 'tilt', 'bubbles', 'speed']) f[key] = ease(f[key], want[key], dt, 4);
110
+ if (want.lean != null) f.lean = want.lean;
111
+ f.mix = ease(f.mix, want.lean == null ? 0 : 1, dt, 3);
112
+ // The surface lags the glass: a spring on its slope, kicked by turning and by hops; it settles level.
113
+ const turned = roll - this.lastRoll; this.lastRoll = roll;
114
+ f.vslope += turned * 4 + (-SLOSH * f.slope - SLOSH_DAMP * f.vslope) * dt; f.slope = clamp(f.slope + f.vslope * dt, -0.5, 0.5);
115
+ f.splash = ease(f.splash, 0, dt, 1.6) + abs(this.vel.lift) * dt * 0.02 + abs(this.omega) * dt * 0.004;
116
+ f.phase += dt * f.speed * 3; f.rise += dt * (0.25 + 0.5 * f.speed);
117
+ }
118
+ n += 3;
119
+ // The glass: pale and tinted; the liquid: the Bot's colour, deeper behind.
120
+ const hue = (tone.hue + (((f.lean ?? tone.hue) - tone.hue + 540) % 360 - 180) * f.mix + 360) % 360;
121
+ const chroma = (tone.chroma ?? 0.15) * (0.7 + 0.3 * p.sat), light = tone.light ?? 0.74;
122
+ Object.assign(nodes[n++], {fill: `oklch(${min(0.97, light + 0.2).toFixed(3)} ${(chroma * 0.18).toFixed(3)} ${tone.hue})`, stroke: tone.edge ?? `oklch(${(light - 0.1).toFixed(3)} ${(chroma * 0.8).toFixed(3)} ${tone.hue})`});
123
+ n++;
124
+ // The surface, in the glass's own frame: level, minus the glass's roll so it stays level, plus slosh, the face, ripples.
125
+ const base = BOTTOM - f.level * (BOTTOM - TOP), slope = tan(clamp(-roll / 2 + f.slope + f.tilt, -0.9, 0.9)), blink = (1 - p.open) * 1.6;
126
+ const wave = f.wave + blink + min(6, f.splash * 40);
127
+ const surface = (x, shift = 0) => {
128
+ const u = (x - 50) / 40;
129
+ return base + slope * (x - 50) - f.curve * (u * u - 0.33) + wave * (0.65 * sin(u * 5.2 + f.phase + shift) + 0.35 * sin(u * 11 - f.phase * 1.7 + shift * 2));
130
+ };
131
+ const edge = (shift, lift) => {
132
+ let d = '';
133
+ for (let i = 0; i <= COLS; i++) { const x = LEFT + (RIGHT - LEFT) * i / COLS; d += (i ? 'L' : 'M') + fixed(x) + ',' + fixed(clamp(surface(x, shift) - lift, 2, 98)); }
134
+ return d;
135
+ };
136
+ const fillUnder = d => d + `L${RIGHT + 8},${BOTTOM + 14}L${LEFT - 8},${BOTTOM + 14}Z`;
137
+ Object.assign(nodes[n++], {d: fillUnder(edge(2.1, 2)), fill: `oklch(${max(0.3, light - 0.14).toFixed(3)} ${(chroma * 1.1).toFixed(3)} ${hue.toFixed(1)})`, opacity: fixed(0.9 * dim + 0.1)});
138
+ const top = edge(0, 0);
139
+ Object.assign(nodes[n++], {d: fillUnder(top), fill: `oklch(${light.toFixed(3)} ${chroma.toFixed(3)} ${hue.toFixed(1)})`});
140
+ Object.assign(nodes[n++], {d: top, stroke: `oklch(${min(0.96, light + 0.14).toFixed(3)} ${(chroma * 0.7).toFixed(3)} ${hue.toFixed(1)})`, opacity: fixed(0.8 * dim)});
141
+ // Bubbles rise from the bottom and burst at the surface.
142
+ const fizz = FIZZ[this.eyes] || FIZZ.bar, shown = f.bubbles * fizz.n;
143
+ for (let i = 0; i < BUBBLES; i++) {
144
+ const node = nodes[n++], seen = clamp(shown - i, 0, 1);
145
+ if (i >= fizz.n || seen <= 0.01) { Object.assign(node, {r: 0, opacity: 0}); continue; }
146
+ const u = (f.rise * (0.8 + 0.5 * pseudo(i)) + pseudo(i + 9)) % 1;
147
+ let x = 22 + 56 * pseudo(i + 3) + 2.5 * sin(f.rise * 6 + i);
148
+ if (want.mood.swirl) x = 50 + 22 * cos(f.rise * 3 + i * TAU / fizz.n);
149
+ if (want.mood.flow) x = 50 + want.mood.flow * (-28 + 56 * ((u + pseudo(i)) % 1));
150
+ const y = BOTTOM - 4 - u * (BOTTOM - 4 - surface(x)), r = fizz.r * (0.7 + 0.5 * pseudo(i + 5)) * (0.6 + 0.4 * u);
151
+ Object.assign(node, {cx: fixed(x), cy: fixed(y), r: fixed(r), stroke: `oklch(${min(0.97, light + 0.18).toFixed(3)} ${(chroma * 0.5).toFixed(3)} ${hue.toFixed(1)})`, opacity: fixed(seen * min(1, (1 - u) * 6) * dim)});
152
+ }
153
+ Object.assign(nodes[n++], {opacity: fixed(0.55 * dim)});
154
+ return n;
155
+ }
156
+ faceLayout() { return []; }
157
+ drawFace(nodes, n) { return n; }
158
+ }
159
+
160
+ /** A liquid model. Options as createMatrix's: identity, hue, chroma, light, dots, edge, shape, eyes, state, progress, size, emphasized. */
161
+ export const createLiquid = options => new Liquid(options);
@@ -0,0 +1,24 @@
1
+ // Types for '@kodax-ai/botui/themes/liquid'.
2
+
3
+ import type {ColorName, EyeStyle, ExpressionName, IdentityPool, Theme} from '../../index.js';
4
+ import type {MatrixAvatar, MatrixOptions, MatrixShape, MatrixModel, MatrixTone} from '../matrix/index.js';
5
+
6
+ export type {Avatar, AvatarOptions, ColorName, EyeStyle, ExpressionName, GestureName, IdentityPool, StateName, StateAlias, StateGroup, Theme} from '../../index.js';
7
+ export type {MatrixOptions as LiquidOptions, MatrixShape as LiquidShape} from '../matrix/index.js';
8
+ export {setAttention, resolveState, STATES, STATE_GROUPS, ALIASES, COLORS, BIRTH_COLORS, HUES, EYE_STYLES, GESTURES} from '../../index.js';
9
+ export {SHAPES, GROUPS} from '../matrix/index.js';
10
+
11
+ export interface LiquidAvatar extends MatrixAvatar {}
12
+ export const LiquidAvatar: {new (options?: MatrixOptions): LiquidAvatar};
13
+
14
+ export const theme: Theme;
15
+ export function createAvatar(options?: MatrixOptions): LiquidAvatar;
16
+ export function identityFrom(identity: string, pool?: IdentityPool): {shape: MatrixShape; color: ColorName; eyes: EyeStyle};
17
+ export const EXPRESSIONS: Record<ExpressionName, Function>;
18
+
19
+ // The pure model: the matrix model with the tile as a glass, the surface of the liquid for a face.
20
+ export function createLiquid(options: MatrixTone & {identity?: string; shape: MatrixShape; eyes?: EyeStyle; state?: string; progress?: number | null; size?: number; emphasized?: boolean}): MatrixModel;
21
+ export const liquidShapes: readonly MatrixShape[];
22
+ export const liquidEyes: readonly EyeStyle[];
23
+ export const FACES: Record<ExpressionName, Function>;
24
+ export const MOODS: Record<string, {level: number | null; bubbles: number; speed: number; [key: string]: unknown}>;
@@ -0,0 +1,35 @@
1
+ // BotUI liquid theme: a glass of the Bot's colour, its surface for a face.
2
+ //
3
+ // import {createAvatar} from './themes/liquid/index.js';
4
+ // const bot = createAvatar({identity: 'research-bot', size: 36});
5
+ // sidebar.append(bot.el);
6
+ // bot.setState('thinking');
7
+
8
+ import {LiquidAvatar} from './avatar.js';
9
+ import {COLORS, EYE_STYLES} from '../../core/identity.js';
10
+ import {STATES} from '../../core/states.js';
11
+ import {registerTheme} from '../../core/registry.js';
12
+ import {GESTURES} from '../../core/motion.js';
13
+ import {FACES} from './engine.js';
14
+ import {SHAPES} from '../matrix/engine.js';
15
+
16
+ export {LiquidAvatar, identityFrom} from './avatar.js';
17
+ export {COLORS, BIRTH_COLORS, HUES, EYE_STYLES} from '../../core/identity.js';
18
+ export {STATES, STATE_GROUPS, ALIASES, resolveState} from '../../core/states.js';
19
+ export {setAttention} from '../../core/core.js';
20
+ export {GESTURES} from '../../core/motion.js';
21
+ export {SHAPES, GROUPS, matrixShapes as liquidShapes} from '../matrix/engine.js';
22
+ export {createLiquid, liquidEyes, FACES, MOODS} from './engine.js';
23
+ /** The expressions, by name; here each one is a way the surface sits (see FACES). */
24
+ export const EXPRESSIONS = FACES;
25
+
26
+ /** Create an avatar. Options as MatrixAvatar's. Append `.el` to the page. */
27
+ export function createAvatar(options) { return new LiquidAvatar(options); }
28
+
29
+ /** This theme, in the form core/registry.js expects. */
30
+ export const theme = {
31
+ name: 'liquid', zh: '液面', create: createAvatar,
32
+ catalog: () => ({shapes: SHAPES, colors: Object.keys(COLORS), eyes: Object.keys(EYE_STYLES), states: Object.keys(STATES), gestures: Object.keys(GESTURES), expressions: Object.keys(FACES)}),
33
+ };
34
+ // Importing a theme makes it available to createAvatar({theme}) from the package entry.
35
+ registerTheme(theme);
@@ -0,0 +1,48 @@
1
+ # 点阵 matrix
2
+
3
+ 彩色方块上的 5×5 点阵屏。一个 Bot 的形象 = 外形 × 颜色 × 眼型,由 Bot ID 稳定决定。颜色和眼型与立体家族算法相同,所以同一个 Bot 在两个主题里是同一种颜色、同一种眼睛。
4
+
5
+ 最早由 RSIBot 绘制(`ui/bot-avatar/engine.js`),2026-11-28 收回 BotUI,并改了视觉:方块缩小留出边距,点更小且灭点也看得见,压扁和倾斜减弱,换成真正的圆角六边形,白色方块加细描边,思考轨迹更亮。
6
+
7
+ ## 用法
8
+
9
+ ```js
10
+ import {createAvatar} from '@kodax-ai/botui/themes/matrix'; // 或相对路径 ./themes/matrix/index.js
11
+
12
+ const bot = createAvatar({identity: 'research-bot', size: 36});
13
+ sidebar.append(bot.el);
14
+ bot.setState('thinking');
15
+ ```
16
+
17
+ 从总入口用:先 `import '@kodax-ai/botui/themes/matrix'`,再 `createAvatar({theme: 'matrix', ...})`(不写 `theme` 时是默认的立体家族)。自定义元素:同样先加载主题脚本,再写 `<bot-avatar theme="matrix" identity="research-bot"></bot-avatar>`。
18
+
19
+ ## 与立体家族的差别
20
+
21
+ 选项、方法、状态、动作、眼神、交互、水印都和 [立体家族](../solids/README.md) 一样,只有这些不同:
22
+
23
+ | 项 | 点阵 |
24
+ |---|---|
25
+ | `shape` | 屏幕外形:`squircle` 圆角方、`circle` 圆、`hex` 六边形 |
26
+ | `eyes` | 同样是 `bar`、`dot`、`tall`,画成 2、1、3 个竖排的点 |
27
+ | `eyeColor` | 不适用,点用方块自己的墨色 |
28
+ | `signals` | 不适用:信号状态(环绕、雷达、进度、上传等)直接在屏幕上播放 |
29
+ | 眼神 | 21 种都有,画成点的图案(`FACES`) |
30
+ | 转身 | 小角度时脸在屏上平移;转过约四分之一圈像卡片一样翻面,背面不显示脸 |
31
+ | 压扁 | 不到立体家族的三分之一。屏幕是硬的,阻塞和按住靠下沉、闭眼、点变暗来表现 |
32
+
33
+ 动作和姿态表与立体家族共用 `core/motion.js`,所有主题动起来节奏一致。
34
+
35
+ ## 纯模型
36
+
37
+ `createMatrix(options)` 是不碰 DOM 的模型:`step(dt, {look, hover, press, dragging})` 返回 `{transform, nodes}`(纯 SVG 属性),`layout` 列出要建的节点。同样的 Bot、同样的输入永远得到同样的帧。想用别的渲染方式(Canvas、原生端)可以只拿它。
38
+
39
+ ## 文件
40
+
41
+ | 文件 | 内容 |
42
+ |---|---|
43
+ | `index.js` | 入口:`createAvatar`、`theme` 和各种表 |
44
+ | `avatar.js` | `MatrixAvatar`:DOM、交互、视线、水印 |
45
+ | `engine.js` | 纯模型:外形、点阵表情、屏幕动画、周边记号和粒子 |
46
+ | `playground.html` | 试玩页(与立体家族共用 `../solids/playground.js`) |
47
+
48
+ 活点、字符脸、光标、光晕、液面、像素生物、手绘这七个主题都建在点阵上:继承 `Matrix` 和 `MatrixAvatar`,按需重写 `tileLayout` / `drawTile`(身体)、`faceLayout` / `drawFace`(脸)、`static shapes`(外形表)和 `createModel`。模型节点可以带 `parent` 嵌套(用于 `defs`、`clipPath`、渐变),名为 `text` 的属性是文本内容。改这里的公共部分时,所有主题一起跑 `tests/check.html`。
@@ -0,0 +1,227 @@
1
+ // The matrix theme: a 5x5 dot screen on a coloured tile, drawn as SVG.
2
+ //
3
+ // Same options, methods, interaction and watermark as the solids. The motion is
4
+ // the solids' own; engine.js turns it into dots. A Bot keeps its solids colour and
5
+ // eye style here, so it looks like itself in either theme.
6
+
7
+ import {clamp, pointer, world, join, leave, joined, prefersDark} from '../../core/core.js';
8
+ import {resolveState} from '../../core/states.js';
9
+ import {COLORS, EYE_STYLES, bornLook, shapeFor, WATERMARK, WATERMARK_FROM, CREDIT} from '../../core/identity.js';
10
+ import {createMatrix, matrixShapes} from './engine.js';
11
+
12
+ const NS = 'http://www.w3.org/2000/svg';
13
+ function el(name, attrs, parent) {
14
+ const node = document.createElementNS(NS, name);
15
+ // `text` is the node's text content; everything else is an attribute.
16
+ for (const key in attrs) if (key === 'text') node.textContent = attrs[key]; else node.setAttribute(key, attrs[key]);
17
+ if (parent) parent.append(node);
18
+ return node;
19
+ }
20
+
21
+ /**
22
+ * The look a Bot ID maps to: one of `shapes` (the tile outlines by default), and
23
+ * the same colour and eye style as in every theme. `pool` can limit the choice: {shapes, colors, eyes}.
24
+ */
25
+ export const identityFrom = (identity, pool, shapes = matrixShapes) => ({shape: shapeFor(identity, shapes, pool), ...bornLook(identity, pool)});
26
+
27
+ // How a tile shows each colour: the saturated ones bright, the neutrals as themselves.
28
+ // A tile that would fade into the page gets an edge.
29
+ const NEUTRALS = {
30
+ brown: {chroma: 0.07, light: 0.6}, gray: {chroma: 0.012, light: 0.7},
31
+ black: {chroma: 0.012, light: 0.36, dots: 'oklch(0.94 0.01 260)'}, white: {chroma: 0.006, light: 0.95},
32
+ };
33
+ function toneOf(color, spec, dark) {
34
+ const tone = {hue: spec.hue, ...(NEUTRALS[color] ?? {chroma: spec.chroma ?? 0.15})};
35
+ if (color === 'white' && !dark) tone.edge = 'oklch(0.84 0.01 260)';
36
+ if (color === 'black' && dark) tone.edge = 'oklch(0.56 0.01 260)';
37
+ return tone;
38
+ }
39
+
40
+ export class MatrixAvatar {
41
+ /** The host element's theme class; a theme built on this one sets its own. */
42
+ static className = 'botui-matrix';
43
+ /** The shapes this theme draws; a theme built on this one with other bodies sets its own. */
44
+ static shapes = matrixShapes;
45
+ /**
46
+ * Options as SolidAvatar's, except: `shape` is a tile outline from matrixShapes
47
+ * (squircle, circle, hex); `signals` and `eyeColor` do not apply, the screen
48
+ * shows signals itself and the dots take the tile's ink.
49
+ */
50
+ constructor(options = {}) {
51
+ this.identity = options.identity ?? 'bot';
52
+ this.pool = options.pool ?? null;
53
+ const born = this.identityFrom(this.identity);
54
+ this.size = Number(options.size ?? 36);
55
+ this.shape = this.constructor.shapes.includes(options.shape) ? options.shape : born.shape;
56
+ this.eyes = EYE_STYLES[options.eyes] ? options.eyes : born.eyes;
57
+ this.scheme = options.scheme ?? 'light'; this.emphasized = !!options.emphasized;
58
+ this.state = resolveState(options.state) || 'idle'; this.progress = options.progress ?? null;
59
+ this.watermark = options.watermark ?? true;
60
+ this.track = options.track ?? true; this.static = !!options.static; this.playing = options.playing ?? true; this.maxFrameRate = options.maxFrameRate ?? 60;
61
+ this.visible = true; this.settled = false;
62
+ this.hover = false; this.press = false; this.dragging = false;
63
+ this.focus = null; this.fixed = null; this.rectAge = 99; this.center = {x: 0, y: 0};
64
+ this.paint(options.color, options.hue, born.color);
65
+
66
+ this.el = document.createElement('span');
67
+ this.el.className = 'botui-avatar ' + this.constructor.className; this.el.botAvatar = this; this.el.dataset.state = this.state;
68
+ this.el.style.cssText = 'display:inline-block;line-height:0;vertical-align:middle;user-select:none;-webkit-user-select:none';
69
+ this.name(options.label);
70
+ this.svg = el('svg', {viewBox: '0 0 100 100', width: this.size, height: this.size, overflow: 'visible'}, this.el);
71
+ el('metadata', {}, this.svg).textContent = CREDIT;
72
+ this.layers = {back: el('g', {}, this.svg), tile: el('g', {}, this.svg), front: el('g', {}, this.svg)};
73
+ this.markNode = el('text', {x: 99, y: 98, 'text-anchor': 'end', 'font-family': "system-ui, 'Segoe UI', sans-serif", 'font-weight': 600, fill: '#8b8b8b', 'fill-opacity': 0.75, 'pointer-events': 'none', display: 'none'}, this.svg);
74
+ this.markNode.textContent = WATERMARK;
75
+ this.build();
76
+ if (options.interactive ?? true) this.listen();
77
+ this.settle();
78
+ this.auto = options.autoplay ?? true;
79
+ if (this.auto) join(this);
80
+ }
81
+
82
+ // ---- public API ----
83
+ /** Change any of: label, size, shape, color, hue, eyes, scheme, emphasized, state, progress, track, static, playing, maxFrameRate, watermark, identity. */
84
+ update(options) {
85
+ let rebuild = false;
86
+ if (options.identity !== undefined && options.identity !== this.identity) {
87
+ this.identity = options.identity; const born = this.identityFrom(this.identity);
88
+ Object.assign(this, {shape: born.shape, eyes: born.eyes}); this.paint(born.color); rebuild = true;
89
+ }
90
+ if (options.color !== undefined || options.hue !== undefined) { this.paint(options.color, options.hue, this.color); rebuild = true; }
91
+ if (this.constructor.shapes.includes(options.shape) && options.shape !== this.shape) { this.shape = options.shape; rebuild = true; }
92
+ if (EYE_STYLES[options.eyes] && options.eyes !== this.eyes) { this.eyes = options.eyes; rebuild = true; }
93
+ if (options.scheme !== undefined && options.scheme !== this.scheme) { this.scheme = options.scheme; this.paint(this.color, this.spec.hue, this.color); rebuild = true; }
94
+ for (const key of ['track', 'playing', 'maxFrameRate', 'watermark']) if (options[key] !== undefined) this[key] = options[key];
95
+ if (options.progress !== undefined) this.progress = options.progress;
96
+ if (options.emphasized !== undefined) this.emphasized = !!options.emphasized;
97
+ if (options.static !== undefined) this.static = !!options.static;
98
+ if (options.label !== undefined) this.name(options.label);
99
+ if (options.size !== undefined) { this.size = Number(options.size); this.svg.setAttribute('width', this.size); this.svg.setAttribute('height', this.size); }
100
+ if (options.state !== undefined) this.state = resolveState(options.state) || this.state;
101
+ if (rebuild) { this.build(); this.settle(); }
102
+ else { Object.assign(this.model, {progress: this.progress, emphasized: this.emphasized, size: this.size}); this.marked(); this.setState(this.state); }
103
+ this.settled = false;
104
+ if (!joined(this)) this.draw(this.model.render(null));
105
+ return this;
106
+ }
107
+ setState(name) {
108
+ const state = resolveState(name);
109
+ if (!state) return this;
110
+ this.state = state; this.el.dataset.state = state;
111
+ if (state !== this.model.state) { this.model.setState(state); this.settled = false; }
112
+ return this;
113
+ }
114
+ /** Play a one-shot gesture from GESTURES. */
115
+ play(name) { this.model.play(name); return this; }
116
+ /** Show an expression from EXPRESSIONS for `ms` milliseconds, over whatever the state shows. */
117
+ express(name, ms = 1500) { this.model.express(name, ms); return this; }
118
+ /** Watch a client-space point; lookAt(null) hands control back to the pointer. */
119
+ lookAt(x, y) { this.focus = x == null ? null : {x, y}; this.rectAge = 99; return this; }
120
+ /** Hold a direction, each axis -1..1; look(null) releases it. */
121
+ look(direction) { this.fixed = direction ? {x: clamp(direction.x ?? 0, -1, 1), y: clamp(direction.y ?? 0, -1, 1)} : null; return this; }
122
+ blink() { this.model.blink(); return this; }
123
+ /** A small acknowledging bob, e.g. on each keystroke. */
124
+ nudge() { this.model.nudge(); return this; }
125
+ /** React to a touch: 'spin' with {turns}, or any gesture name; with no action it picks a reaction itself. */
126
+ poke(action, options) { this.model.poke(action, options); return this; }
127
+ /** Advance by dt seconds and redraw. */
128
+ step(dt) {
129
+ this.settled = false;
130
+ this.draw(this.model.step(dt, {look: this.attend(), hover: this.hover, press: this.press, dragging: this.dragging}));
131
+ return this;
132
+ }
133
+ /** Start the current state again from its resting pose. */
134
+ restart() { this.model.since = 0; this.settle(); this.settled = false; return this; }
135
+ suspend() { leave(this); return this; }
136
+ resume() { if (this.auto) join(this); return this; }
137
+ /** The current frame as standalone SVG markup. */
138
+ toSVG() {
139
+ const copy = this.svg.cloneNode(true);
140
+ copy.setAttribute('xmlns', NS);
141
+ for (const node of copy.querySelectorAll('[display="none"]')) node.remove();
142
+ return copy.outerHTML;
143
+ }
144
+ dispose() { leave(this); this.el.botAvatar = null; this.el.remove(); }
145
+ gaze(point) { return point ? this.lookAt(point.x, point.y) : this.lookAt(null); }
146
+ setExpression(name, {duration = 1200} = {}) { return this.express(name, duration); }
147
+ /** The model's pose, for tools and tests. */
148
+ get p() { return this.model.p; }
149
+
150
+ /** Jump straight to the resting pose of the current state and draw it. */
151
+ settle() { this.draw(this.model.settle()); this.settled = true; }
152
+
153
+ // ---- internals ----
154
+ identityFrom(identity) { return identityFrom(identity, this.pool, this.constructor.shapes); }
155
+ name(label) {
156
+ if (label) { this.el.setAttribute('role', 'img'); this.el.setAttribute('aria-label', label); this.el.removeAttribute('aria-hidden'); }
157
+ else { this.el.removeAttribute('role'); this.el.removeAttribute('aria-label'); this.el.setAttribute('aria-hidden', 'true'); }
158
+ }
159
+ paint(color, hue, fallback) {
160
+ const given = hue != null && hue !== '' && Number.isFinite(Number(hue)), named = COLORS[color] ? color : given ? null : fallback;
161
+ if (!named && !given) return;
162
+ this.color = named ?? null;
163
+ this.spec = named ? COLORS[named] : {hue: Number(hue)};
164
+ this.dark = this.scheme === 'dark' || (this.scheme === 'auto' && prefersDark());
165
+ this.tone = toneOf(this.color, this.spec, this.dark);
166
+ }
167
+ marked() {
168
+ // The mark keeps a readable pixel size; below 48 px it would not be legible at all.
169
+ if (this.watermark !== false && this.size >= WATERMARK_FROM) { this.markNode.setAttribute('font-size', (clamp(this.size * 0.075, 5.5, 10) * 100 / this.size).toFixed(2)); this.markNode.removeAttribute('display'); }
170
+ else this.markNode.setAttribute('display', 'none');
171
+ }
172
+ /** The model behind the drawing; a theme built on this one returns its own. */
173
+ createModel(options) { return createMatrix(options); }
174
+ /** A fresh model and fresh nodes for the current look. The state carries over; the pose starts at rest. */
175
+ build() {
176
+ this.model = this.createModel({identity: this.identity, ...this.tone, shape: this.shape, eyes: this.eyes, state: this.state, progress: this.progress, size: this.size, emphasized: this.emphasized});
177
+ for (const layer of Object.values(this.layers)) layer.replaceChildren();
178
+ // A layout entry may name an earlier entry as its `parent` (a gradient's stops, a clip's path).
179
+ const made = new Map();
180
+ this.nodes = this.model.layout.map(entry => { const node = el(entry.tag, entry.attrs, entry.parent ? made.get(entry.parent) : this.layers[entry.layer]); made.set(entry, node); return node; });
181
+ this.seen = this.nodes.map(() => ({}));
182
+ this.el.dataset.shape = this.shape;
183
+ this.marked();
184
+ }
185
+ draw({transform, nodes}) {
186
+ if (this.scheme === 'auto' && prefersDark() !== this.dark) { this.paint(this.color, this.spec.hue, this.color); this.build(); this.settle(); return; }
187
+ this.layers.tile.setAttribute('transform', transform);
188
+ nodes.forEach((attrs, i) => {
189
+ const seen = this.seen[i];
190
+ for (const name in attrs) if (seen[name] !== attrs[name]) { seen[name] = attrs[name]; if (name === 'text') this.nodes[i].textContent = attrs[name]; else this.nodes[i].setAttribute(name, attrs[name]); }
191
+ });
192
+ }
193
+ listen() {
194
+ const host = this.el;
195
+ host.style.cursor = 'grab'; host.style.touchAction = 'pan-y';
196
+ host.addEventListener('pointerenter', () => { this.hover = true; });
197
+ host.addEventListener('pointerleave', () => { this.hover = false; });
198
+ host.addEventListener('pointerdown', e => {
199
+ this.press = true; this.dragging = false; this.drag = {x: e.clientX, y: e.clientY, travel: 0, at: performance.now()};
200
+ host.setPointerCapture?.(e.pointerId);
201
+ });
202
+ host.addEventListener('pointermove', e => {
203
+ if (!this.press) return;
204
+ const d = this.drag, dx = e.clientX - d.x, dy = e.clientY - d.y, now = performance.now(), dt = Math.max(0.004, (now - d.at) / 1000);
205
+ d.x = e.clientX; d.y = e.clientY; d.at = now; d.travel += Math.abs(dx) + Math.abs(dy);
206
+ if (d.travel < 5) return;
207
+ this.dragging = true; host.style.cursor = 'grabbing';
208
+ this.model.drag(dx, dy, dt);
209
+ });
210
+ host.addEventListener('pointerup', () => {
211
+ if (!this.press) return;
212
+ if (this.dragging) this.model.release();
213
+ else { this.poke(); host.dispatchEvent(new CustomEvent('bot-poke', {bubbles: true, detail: {avatar: this}})); }
214
+ this.press = false; this.dragging = false; host.style.cursor = 'grab';
215
+ });
216
+ host.addEventListener('pointercancel', () => { this.press = false; this.dragging = false; host.style.cursor = 'grab'; });
217
+ }
218
+ // Where to look, as a vector that saturates with distance; null lets the model glance around.
219
+ attend() {
220
+ if (this.fixed) return this.fixed;
221
+ const target = this.focus || world.attention || (this.track && performance.now() - pointer.at < 6000 ? pointer : null);
222
+ if (!target) return null;
223
+ if ((this.rectAge += this.model.dt || 0.016) > 0.4) { const r = this.el.getBoundingClientRect(); this.center = {x: r.left + r.width / 2, y: r.top + r.height / 2}; this.rectAge = 0; }
224
+ const dx = target.x - this.center.x, dy = target.y - this.center.y, d = Math.hypot(dx, dy) + 60 + this.size;
225
+ return {x: dx / d, y: dy / d};
226
+ }
227
+ }