@miadi/companion-ui 0.0.0-stage → 0.2.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.
@@ -0,0 +1,381 @@
1
+ "use client"
2
+
3
+ /**
4
+ * The conversation with a companion seat, as React: the person's takes and the seat's
5
+ * replies in the order they happened, each with its playback, and the card an episode
6
+ * room shows for it.
7
+ *
8
+ * Data in, intent out. The host builds the thread (`buildCompanionThread`), decides who
9
+ * hears a take (`takeAudioUrl` answers null for a reader who may not), and says where a
10
+ * related card leads (`relatedHref`). No component fetches, holds a URL or knows a root.
11
+ */
12
+
13
+ import { useRef, useState, type CSSProperties, type ReactNode } from "react"
14
+ import {
15
+ personaLabel,
16
+ stampOf,
17
+ type CompanionReplyTurn,
18
+ type CompanionTakeTurn,
19
+ type CompanionThread,
20
+ type CompanionTurn,
21
+ } from "./thread.js"
22
+
23
+ /** The fields `@miadi/episode-ui`'s `EpisodeUITheme` carries, so `CHRONICLE_THEME` fits as it is. */
24
+ export interface CompanionTheme {
25
+ background: string
26
+ card: string
27
+ text: string
28
+ textDim: string
29
+ muted: string
30
+ accent: string
31
+ border: string
32
+ success: string
33
+ warning: string
34
+ mono: string
35
+ }
36
+
37
+ /** The Chronicle's surface (the values of `@miadi/episode-ui/chronicle-theme`), every text colour at 4.5:1 or better. */
38
+ export const COMPANION_THEME: CompanionTheme = {
39
+ background: "#151515",
40
+ card: "#242424",
41
+ text: "#f9f9f9",
42
+ textDim: "#c8c8c8",
43
+ muted: "#959595",
44
+ accent: "#d4a843",
45
+ border: "#404040",
46
+ success: "#5ac37d",
47
+ warning: "#e0a458",
48
+ mono: "'JetBrains Mono', ui-monospace, monospace",
49
+ }
50
+
51
+ export interface CompanionTurnOptions {
52
+ /** A take's audio URL, or null when this reader does not hear takes. */
53
+ takeAudioUrl?: (take: CompanionTakeTurn) => string | null
54
+ /** The name a take is shown under. */
55
+ takeSpeaker?: string
56
+ /** Where a related card leads; the card's own href when absent, text when it answers null. */
57
+ relatedHref?: (href: string) => string | null
58
+ /** False when the host could not read the voices, so a reply without one is not called unvoiced. */
59
+ voicesRead?: boolean
60
+ theme?: Partial<CompanionTheme>
61
+ }
62
+
63
+ // ---------- playback ----------
64
+
65
+ interface Playing {
66
+ turn: string
67
+ part: number
68
+ parts: number
69
+ paused: boolean
70
+ }
71
+
72
+ /** One audio element per surface; a reply plays its voices one after another. */
73
+ function usePlayer() {
74
+ const audio = useRef<HTMLAudioElement>(null)
75
+ const queue = useRef<string[]>([])
76
+ const [playing, setPlaying] = useState<Playing | null>(null)
77
+
78
+ const start = (turn: string, srcs: string[], part = 0) => {
79
+ const a = audio.current
80
+ const src = srcs[part]
81
+ if (!a || !src) return
82
+ queue.current = srcs
83
+ setPlaying({ turn, part, parts: srcs.length, paused: false })
84
+ a.src = src
85
+ a.play().catch(() => {})
86
+ }
87
+ const play = (turn: string, srcs: string[]) => {
88
+ const a = audio.current
89
+ if (playing?.turn === turn && a) {
90
+ if (a.paused) a.play().catch(() => {})
91
+ else a.pause()
92
+ return
93
+ }
94
+ start(turn, srcs)
95
+ }
96
+ const onEnded = () => {
97
+ if (!playing) return
98
+ if (playing.part + 1 < queue.current.length) start(playing.turn, queue.current, playing.part + 1)
99
+ else setPlaying(null)
100
+ }
101
+ const onPause = () => setPlaying((p) => (p && !p.paused ? { ...p, paused: true } : p))
102
+ const onResume = () => setPlaying((p) => (p && p.paused ? { ...p, paused: false } : p))
103
+ return { audio, playing, play, events: { onEnded, onPause, onPlay: onResume } }
104
+ }
105
+
106
+ function sourcesOf(turn: CompanionTurn, options: CompanionTurnOptions): string[] {
107
+ if (turn.kind === "take") {
108
+ const url = options.takeAudioUrl?.(turn)
109
+ return url ? [url] : []
110
+ }
111
+ return turn.audio.map((v) => v.src).filter((src): src is string => Boolean(src))
112
+ }
113
+
114
+ // ---------- text ----------
115
+
116
+ /** Paragraphs, with `**bold**` kept as emphasis and every other character as written. */
117
+ function Prose({ text, color }: { text: string; color: string }) {
118
+ const paragraphs = text.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
119
+ return (
120
+ <>
121
+ {paragraphs.map((p, i) => (
122
+ <p key={i} style={{ margin: i === 0 ? 0 : "8px 0 0", whiteSpace: "pre-wrap", overflowWrap: "anywhere", color }}>
123
+ {p.split(/(\*\*[^*]+\*\*)/g).map((piece, j) =>
124
+ /^\*\*[^*]+\*\*$/.test(piece) ? <strong key={j}>{piece.slice(2, -2)}</strong> : <span key={j}>{piece}</span>,
125
+ )}
126
+ </p>
127
+ ))}
128
+ </>
129
+ )
130
+ }
131
+
132
+ const LONG = 520
133
+
134
+ // ---------- one turn ----------
135
+
136
+ export interface CompanionTurnViewProps extends CompanionTurnOptions {
137
+ turn: CompanionTurn
138
+ /** The take this reply answers, when it is not the turn just before. */
139
+ answers?: CompanionTakeTurn
140
+ playing?: Playing | null
141
+ onPlay?: (turn: CompanionTurn, srcs: string[]) => void
142
+ /** Show the whole text at once. */
143
+ open?: boolean
144
+ anchorPrefix?: string
145
+ }
146
+
147
+ export function CompanionTurnView({ turn, answers, playing, onPlay, open = false, anchorPrefix = "turn-", ...options }: CompanionTurnViewProps) {
148
+ const t = { ...COMPANION_THEME, ...options.theme }
149
+ const [expanded, setExpanded] = useState(open)
150
+ const take = turn.kind === "take"
151
+ const srcs = sourcesOf(turn, options)
152
+ const on = playing?.turn === turn.id
153
+ const sounding = on && !playing?.paused
154
+ const long = turn.text.length > LONG
155
+ const who = take ? (options.takeSpeaker ?? "Take") : personaLabel(turn.persona)
156
+
157
+ const bubble: CSSProperties = {
158
+ alignSelf: take ? "flex-end" : "flex-start",
159
+ width: "min(100%, 680px)",
160
+ boxSizing: "border-box",
161
+ background: t.card,
162
+ border: `1px solid ${on ? t.accent : take ? `${t.accent}55` : t.border}`,
163
+ borderRadius: take ? "12px 12px 4px 12px" : "12px 12px 12px 4px",
164
+ padding: "10px 12px",
165
+ display: "flex",
166
+ flexDirection: "column",
167
+ gap: 6,
168
+ }
169
+
170
+ return (
171
+ <article id={`${anchorPrefix}${turn.id}`} data-turn={turn.kind} data-turn-id={turn.id} style={bubble}>
172
+ <header style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "4px 10px", fontSize: 12 }}>
173
+ {srcs.length > 0 && (
174
+ <button
175
+ type="button"
176
+ onClick={() => onPlay?.(turn, srcs)}
177
+ aria-label={`${sounding ? "Pause" : "Play"} ${who} ${stampOf(turn.at)}`}
178
+ style={{
179
+ width: 26, height: 26, flex: "none", borderRadius: 999, border: "none", cursor: "pointer",
180
+ background: on ? t.accent : t.muted, color: t.background, fontSize: 11, display: "flex", alignItems: "center", justifyContent: "center",
181
+ }}
182
+ >
183
+ {sounding ? "❚❚" : "▶"}
184
+ </button>
185
+ )}
186
+ <strong style={{ color: take ? t.accent : t.text }}>{who}</strong>
187
+ <span style={{ color: t.muted, fontFamily: t.mono, fontSize: 11 }}>{stampOf(turn.at)}</span>
188
+ {on && playing && playing.parts > 1 && (
189
+ <span style={{ color: t.accent, fontFamily: t.mono, fontSize: 11 }}>part {playing.part + 1} of {playing.parts}</span>
190
+ )}
191
+ {!take && answers && (
192
+ <a href={`#${anchorPrefix}${answers.id}`} style={{ color: t.textDim, fontSize: 11 }}>
193
+ answers the take of {stampOf(answers.at)}
194
+ </a>
195
+ )}
196
+ {!take && turn.feedback && (
197
+ <span title={turn.feedback === "up" ? "marked as working" : "marked as not working"} style={{ fontSize: 12 }}>
198
+ {turn.feedback === "up" ? "👍" : "👎"}
199
+ </span>
200
+ )}
201
+ </header>
202
+
203
+ {turn.text ? (
204
+ <div
205
+ style={{
206
+ fontSize: 13.5, lineHeight: 1.55,
207
+ ...(long && !expanded ? { maxHeight: "9.5em", overflow: "hidden", WebkitMaskImage: "linear-gradient(#000 70%, transparent)", maskImage: "linear-gradient(#000 70%, transparent)" } : {}),
208
+ }}
209
+ >
210
+ <Prose text={turn.text} color={t.text} />
211
+ </div>
212
+ ) : (
213
+ <div style={{ fontSize: 12.5, fontStyle: "italic", color: t.textDim }}>{take ? "No transcript yet." : "No text."}</div>
214
+ )}
215
+ {long && (
216
+ <button
217
+ type="button"
218
+ onClick={() => setExpanded(!expanded)}
219
+ style={{ alignSelf: "flex-start", background: "none", border: "none", padding: 0, cursor: "pointer", color: t.accent, fontSize: 12, fontFamily: "inherit" }}
220
+ >
221
+ {expanded ? "Show less" : "Read all"}
222
+ </button>
223
+ )}
224
+
225
+ {!take && turn.related?.length ? (
226
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
227
+ {turn.related.map((card) => {
228
+ const href = options.relatedHref ? options.relatedHref(card.href) : card.href
229
+ const chip: CSSProperties = { fontSize: 11.5, padding: "3px 8px", borderRadius: 999, border: `1px solid ${t.border}`, color: t.textDim, textDecoration: "none" }
230
+ return href ? (
231
+ <a key={`${card.label}-${card.href}`} href={href} style={{ ...chip, color: t.accent }} title={card.href}>{card.label}</a>
232
+ ) : (
233
+ <span key={`${card.label}-${card.href}`} style={chip} title={card.href}>{card.label}</span>
234
+ )
235
+ })}
236
+ </div>
237
+ ) : null}
238
+
239
+ {!take && turn.fromVoices && (
240
+ <div style={{ fontSize: 11, color: t.muted }}>Shown from its voice: the reply's own record is not on this host.</div>
241
+ )}
242
+ {!take && srcs.length === 0 && !turn.fromVoices && (
243
+ <div style={{ fontSize: 11, color: t.muted }}>{options.voicesRead === false ? "Its voice could not be read just now." : "Not voiced."}</div>
244
+ )}
245
+ </article>
246
+ )
247
+ }
248
+
249
+ // ---------- the whole conversation ----------
250
+
251
+ export interface CompanionDialogueProps extends CompanionTurnOptions {
252
+ thread: CompanionThread
253
+ /** How many of the latest turns show before "show earlier". Default 12; 0 shows all. */
254
+ initialTurns?: number
255
+ /** A line above the turns, for instance why the takes are not shown to this reader. */
256
+ note?: ReactNode
257
+ anchorPrefix?: string
258
+ }
259
+
260
+ export function CompanionDialogue({ thread, initialTurns = 12, note, anchorPrefix = "turn-", ...options }: CompanionDialogueProps) {
261
+ const t = { ...COMPANION_THEME, ...options.theme }
262
+ const { audio, playing, play, events } = usePlayer()
263
+ const [shown, setShown] = useState(initialTurns > 0 ? initialTurns : thread.turns.length)
264
+ const from = Math.max(0, thread.turns.length - shown)
265
+ const turns = thread.turns.slice(from)
266
+
267
+ return (
268
+ <section data-companion-dialogue={thread.turns.length} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
269
+ <audio ref={audio} {...events} controls preload="none" style={{ width: "100%", height: 36, display: playing ? "block" : "none" }} />
270
+ {note ? <div style={{ fontSize: 12.5, color: t.textDim }}>{note}</div> : null}
271
+ {thread.turns.length === 0 && <div style={{ fontSize: 13, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>}
272
+ {from > 0 && (
273
+ <button
274
+ type="button"
275
+ onClick={() => setShown(thread.turns.length)}
276
+ style={{ alignSelf: "center", background: "transparent", border: `1px solid ${t.border}`, borderRadius: 999, color: t.accent, padding: "6px 14px", cursor: "pointer", fontSize: 12.5, fontFamily: "inherit" }}
277
+ >
278
+ Show {from} earlier turn{from === 1 ? "" : "s"}
279
+ </button>
280
+ )}
281
+ {turns.map((turn, i) => {
282
+ const before = i > 0 ? turns[i - 1] : from > 0 ? thread.turns[from - 1] : undefined
283
+ const answers = turn.kind === "reply" && turn.take && !(before?.kind === "take" && before.id === turn.take)
284
+ ? (thread.turns.find((x) => x.kind === "take" && x.id === turn.take) as CompanionTakeTurn | undefined)
285
+ : undefined
286
+ return (
287
+ <CompanionTurnView
288
+ key={`${turn.kind}-${turn.id}`}
289
+ turn={turn}
290
+ answers={answers}
291
+ playing={playing}
292
+ onPlay={(x, srcs) => play(x.id, srcs)}
293
+ anchorPrefix={anchorPrefix}
294
+ {...options}
295
+ />
296
+ )
297
+ })}
298
+ </section>
299
+ )
300
+ }
301
+
302
+ // ---------- the card an episode room shows ----------
303
+
304
+ export interface CompanionLink {
305
+ label: string
306
+ href: string
307
+ /** Opens in a new tab. */
308
+ external?: boolean
309
+ }
310
+
311
+ export interface CompanionCardProps extends CompanionTurnOptions {
312
+ thread: CompanionThread
313
+ /** The page that shows the whole conversation. */
314
+ conversationHref?: string
315
+ /** Other places the reader may go: the seat's pane, the page that records a take. */
316
+ links?: CompanionLink[]
317
+ /** Shown under the links, for instance `<CompanionOpener>` for a person who may open a seat. */
318
+ children?: ReactNode
319
+ /** How many of the latest turns the card shows. Default 2. */
320
+ latest?: number
321
+ title?: string
322
+ }
323
+
324
+ export function CompanionCard({ thread, conversationHref, links = [], children, latest = 2, title = "Companion", ...options }: CompanionCardProps) {
325
+ const t = { ...COMPANION_THEME, ...options.theme }
326
+ const { audio, playing, play, events } = usePlayer()
327
+ const personas = [...new Set(thread.turns.flatMap((x) => (x.kind === "reply" ? [personaLabel(x.persona)] : [])))]
328
+ const turns = thread.turns.slice(-latest)
329
+ const counts = [
330
+ thread.takes ? `${thread.takes} take${thread.takes === 1 ? "" : "s"}` : "",
331
+ thread.replies ? `${thread.replies} repl${thread.replies === 1 ? "y" : "ies"}` : "",
332
+ ].filter(Boolean).join(" · ")
333
+
334
+ return (
335
+ <section data-companion-card={thread.turns.length} style={{ background: t.card, border: `1px solid ${t.border}`, borderRadius: 10, padding: 15, display: "flex", flexDirection: "column", gap: 10 }}>
336
+ <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, flexWrap: "wrap" }}>
337
+ <div style={{ fontSize: 11.5, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.06em", color: t.muted }}>{title}</div>
338
+ {(personas.length > 0 || counts) && (
339
+ <div style={{ fontSize: 11.5, color: t.textDim }}>{[personas.join(", "), counts].filter(Boolean).join(" · ")}</div>
340
+ )}
341
+ </div>
342
+ <audio ref={audio} {...events} controls preload="none" style={{ width: "100%", height: 32, display: playing ? "block" : "none" }} />
343
+ {turns.length === 0 ? (
344
+ <div style={{ fontSize: 12.5, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>
345
+ ) : (
346
+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
347
+ {turns.map((turn) => (
348
+ <CompanionTurnView
349
+ key={`${turn.kind}-${turn.id}`}
350
+ turn={turn}
351
+ playing={playing}
352
+ onPlay={(x, srcs) => play(x.id, srcs)}
353
+ anchorPrefix="companion-card-"
354
+ {...options}
355
+ />
356
+ ))}
357
+ </div>
358
+ )}
359
+ {(conversationHref || links.length > 0) && (
360
+ <nav style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 13 }}>
361
+ {conversationHref && thread.turns.length > 0 && (
362
+ <a href={conversationHref} style={{ color: t.accent, fontWeight: 700, textDecoration: "none" }}>
363
+ Open the whole conversation →
364
+ </a>
365
+ )}
366
+ {links.map((link) => (
367
+ <a
368
+ key={link.href}
369
+ href={link.href}
370
+ {...(link.external ? { target: "_blank", rel: "noreferrer" } : {})}
371
+ style={{ color: t.accent, textDecoration: "none" }}
372
+ >
373
+ {link.label}{link.external ? " ↗" : " →"}
374
+ </a>
375
+ ))}
376
+ </nav>
377
+ )}
378
+ {children}
379
+ </section>
380
+ )
381
+ }
package/src/glyphs.tsx ADDED
@@ -0,0 +1,71 @@
1
+ "use client"
2
+
3
+ /**
4
+ * The companions a page can open, as a row of glyphs: 🧠 for Mia, then each agent
5
+ * that holds a companion seat. Pressing a glyph asks the host to show (or hide) that
6
+ * agent's opener, so the opener takes no room until someone wants it (Guillaume's
7
+ * screenwalk of the cockpit, review a425d070, jgwill/Miadi#817).
8
+ *
9
+ * The agents come from the host: the factory serves them at /api/factory/agents,
10
+ * built from ~/.agents/agents and data/GlyphMap.json. Only agents with a seat are
11
+ * drawn, because only they can be opened.
12
+ */
13
+
14
+ import type { CSSProperties } from "react"
15
+ import { OPENER_THEME, type CompanionOpenerTheme } from "./opener.js"
16
+
17
+ export interface CompanionAgent {
18
+ key: string
19
+ name: string
20
+ glyph: string
21
+ role?: string | null
22
+ /** True when tide can open a companion seat for this agent. */
23
+ seat: boolean
24
+ }
25
+
26
+ export interface CompanionGlyphBarProps {
27
+ agents: readonly CompanionAgent[]
28
+ /** The agent whose opener is shown, or null when all are collapsed. */
29
+ open: string | null
30
+ onToggle(key: string): void
31
+ theme?: Partial<CompanionOpenerTheme>
32
+ style?: CSSProperties
33
+ }
34
+
35
+ /** The agents the bar draws: seat holders, in the order the host gave them. */
36
+ export function seatAgents(agents: readonly CompanionAgent[]): CompanionAgent[] {
37
+ return agents.filter((a) => a.seat && a.glyph)
38
+ }
39
+
40
+ export function CompanionGlyphBar({ agents, open, onToggle, theme, style }: CompanionGlyphBarProps) {
41
+ const t = { ...OPENER_THEME, ...theme }
42
+ const shown = seatAgents(agents)
43
+ if (shown.length === 0) return null
44
+ return (
45
+ <div role="group" aria-label="companions" data-companion-glyphs="" style={{ display: "inline-flex", gap: 4, ...style }}>
46
+ {shown.map((a) => {
47
+ const pressed = open === a.key
48
+ return (
49
+ <button
50
+ key={a.key}
51
+ type="button"
52
+ aria-pressed={pressed}
53
+ aria-label={`${pressed ? "Hide" : "Open"} ${a.name}`}
54
+ title={`${a.name}${a.role ? ` · ${a.role}` : ""}`}
55
+ data-companion-glyph={a.key}
56
+ onClick={() => onToggle(a.key)}
57
+ style={{
58
+ minWidth: 36, minHeight: 36, padding: "0 6px", borderRadius: 999, cursor: "pointer",
59
+ fontSize: 18, lineHeight: 1, fontFamily: t.mono,
60
+ background: pressed ? `${t.accent}26` : "transparent",
61
+ border: `1px solid ${pressed ? t.accent : `${t.accent}55`}`,
62
+ color: t.text,
63
+ }}
64
+ >
65
+ <span aria-hidden="true">{a.glyph}</span>
66
+ </button>
67
+ )
68
+ })}
69
+ </div>
70
+ )
71
+ }
package/src/index.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @miadi/companion-ui — an episode's companion seat, as React.
3
+ *
4
+ * - The conversation: `buildCompanionThread` joins the person's takes, the seat's
5
+ * replies and the voices cut from them; `CompanionDialogue` shows it with each
6
+ * turn's playback; `CompanionCard` is the short form an episode room shows.
7
+ * - The seat: `CompanionOpener` plans and opens a seat for an episode through a
8
+ * transport the host gives it (`httpCompanionTransport`). `CompanionGlyphBar`
9
+ * draws one glyph per agent with a seat, and the host shows the opener of the
10
+ * one pressed.
11
+ *
12
+ * Data and a transport in, intent out. No component holds a URL, a token or a
13
+ * chronicle root, and none decides who may hear a take or open a seat: the host
14
+ * decides, and passes or withholds. `@miadi/companion-ui/node` reads the files.
15
+ *
16
+ * The React modules are client modules. A server component imports the data from
17
+ * `@miadi/companion-ui/thread` and `@miadi/companion-ui/seat`, which hold no React.
18
+ */
19
+
20
+ export {
21
+ COMPANION_VOICE_SOURCE,
22
+ buildCompanionThread,
23
+ isCompanionVoice,
24
+ personaLabel,
25
+ seatOfSession,
26
+ speakable,
27
+ stampOf,
28
+ takeOf,
29
+ type CompanionFeedback,
30
+ type CompanionRelated,
31
+ type CompanionReply,
32
+ type CompanionReplyTurn,
33
+ type CompanionTake,
34
+ type CompanionTakeTurn,
35
+ type CompanionThread,
36
+ type CompanionTurn,
37
+ type CompanionVoice,
38
+ } from "./thread.js"
39
+ export {
40
+ COMPANION_SEATS,
41
+ LISTENING,
42
+ NOTHING_TO_RUN,
43
+ companionSessionName,
44
+ httpCompanionTransport,
45
+ sayFault,
46
+ sayPlan,
47
+ seatLabel,
48
+ type CompanionAnswer,
49
+ type CompanionOpenRequest,
50
+ type CompanionPlan,
51
+ type CompanionTransport,
52
+ } from "./seat.js"
53
+ export {
54
+ COMPANION_THEME,
55
+ CompanionCard,
56
+ CompanionDialogue,
57
+ CompanionTurnView,
58
+ type CompanionCardProps,
59
+ type CompanionDialogueProps,
60
+ type CompanionLink,
61
+ type CompanionTheme,
62
+ type CompanionTurnOptions,
63
+ type CompanionTurnViewProps,
64
+ } from "./dialogue.js"
65
+ export { CompanionOpener, OPENER_THEME, type CompanionOpenerProps, type CompanionOpenerTheme } from "./opener.js"
66
+ export { CompanionGlyphBar, seatAgents, type CompanionAgent, type CompanionGlyphBarProps } from "./glyphs.js"