@cortexkit/common-auth 0.30.0 → 0.32.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,605 @@
1
+ import type { RGBA } from '@opentui/core'
2
+ import type { JSX } from '@opentui/solid'
3
+ import {
4
+ createContext,
5
+ createMemo,
6
+ createSignal,
7
+ For,
8
+ mergeProps,
9
+ Show,
10
+ useContext,
11
+ } from 'solid-js'
12
+ import type { QuotaWindowPart } from '../quota/format.js'
13
+ import { formatQuota, quotaWindowParts } from '../quota/format.js'
14
+ import type { ProjectedQuota } from '../quota/projection.js'
15
+
16
+ export type Tone =
17
+ | 'text'
18
+ | 'textMuted'
19
+ | 'accent'
20
+ | 'success'
21
+ | 'warning'
22
+ | 'error'
23
+
24
+ export type SidebarTheme = Readonly<
25
+ Partial<
26
+ Record<Tone | 'background' | 'borderActive', RGBA | string | undefined>
27
+ >
28
+ >
29
+
30
+ export interface SidebarAppearance {
31
+ barWidth: number
32
+ barFilledChar: string
33
+ barEmptyChar: string
34
+ warnThreshold: number
35
+ errorThreshold: number
36
+ }
37
+
38
+ export interface PaceView {
39
+ text: string
40
+ tone: Tone
41
+ /** The elapsed-window percentage, not the difference from usage. */
42
+ overlay?: { kind: 'reserve' | 'deficit'; percent: number }
43
+ }
44
+
45
+ export interface QuotaGroupView {
46
+ title?: string
47
+ rows: readonly { part: QuotaWindowPart; pace?: PaceView }[]
48
+ }
49
+
50
+ export interface AccountView {
51
+ id: string
52
+ label: string
53
+ titleSuffix?: string
54
+ status: { text: string; tone: Tone }
55
+ blocked: boolean
56
+ indicatorTone: Tone
57
+ quota: ProjectedQuota | undefined
58
+ groups: readonly QuotaGroupView[]
59
+ emptyQuotaText?: { expanded: string; collapsed: string }
60
+ /** Presentation decided by the plugin, never inferred from status or freshness. */
61
+ collapsed?: { quotaTone?: Tone; muted?: boolean }
62
+ }
63
+
64
+ export interface SidebarFrameProps {
65
+ header: { badge: string; version?: string }
66
+ accounts: readonly AccountView[]
67
+ theme?: SidebarTheme
68
+ appearance: SidebarAppearance
69
+ showQuota: boolean
70
+ now: number
71
+ collapsed: boolean
72
+ onToggle: () => void
73
+ beforeQuota?: (account: AccountView) => JSX.Element
74
+ afterQuota?: (account: AccountView) => JSX.Element
75
+ sections?: () => JSX.Element
76
+ collapsedSections?: () => JSX.Element
77
+ }
78
+
79
+ type FrameContextProps = Omit<SidebarFrameProps, 'theme'> & {
80
+ theme: SidebarTheme
81
+ }
82
+
83
+ const FrameContext = createContext<FrameContextProps>()
84
+
85
+ function frameContext(): FrameContextProps {
86
+ const context = useContext(FrameContext)
87
+ if (!context)
88
+ throw new Error('Sidebar primitives must be inside SidebarFrame')
89
+ return context
90
+ }
91
+
92
+ function displayWidth(text: string): number {
93
+ const bun = (
94
+ globalThis as { Bun?: { stringWidth?: (text: string) => number } }
95
+ ).Bun
96
+ return bun?.stringWidth ? bun.stringWidth(text) : Array.from(text).length
97
+ }
98
+
99
+ function fitText(text: string, columns: number): string {
100
+ if (displayWidth(text) <= columns) return text
101
+ if (columns < 1) return ''
102
+ let kept = ''
103
+ let used = 0
104
+ for (const char of text) {
105
+ const width = displayWidth(char)
106
+ if (used + width > columns - 1) break
107
+ kept += char
108
+ used += width
109
+ }
110
+ return `${kept}\u2026`
111
+ }
112
+
113
+ /** A heading and its plugin-owned rows, with the frame's section spacing. */
114
+ export function SidebarSection(props: {
115
+ title: string
116
+ children?: JSX.Element
117
+ }) {
118
+ const context = frameContext()
119
+ return (
120
+ <>
121
+ <box width='100%' marginTop={1}>
122
+ <text fg={context.theme.text}>
123
+ <b>{props.title}</b>
124
+ </text>
125
+ </box>
126
+ {props.children}
127
+ </>
128
+ )
129
+ }
130
+
131
+ /** Keep labels whole and reserve one blank cell before an ellipsized value. */
132
+ export function SidebarStatRow(props: {
133
+ label: string
134
+ value: string
135
+ tone?: Tone
136
+ }) {
137
+ const context = frameContext()
138
+ const [width, setWidth] = createSignal(0)
139
+ let row: { width: number } | undefined
140
+ const value = () =>
141
+ width() <= 0
142
+ ? props.value
143
+ : fitText(props.value, width() - displayWidth(props.label) - 1)
144
+ return (
145
+ <box
146
+ ref={(element: { width: number }) => {
147
+ row = element
148
+ }}
149
+ onSizeChange={() => setWidth(row?.width ?? 0)}
150
+ width='100%'
151
+ flexDirection='row'
152
+ justifyContent='space-between'
153
+ columnGap={1}
154
+ >
155
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
156
+ {props.label}
157
+ </text>
158
+ <text
159
+ fg={context.theme[props.tone ?? 'text']}
160
+ wrapMode='none'
161
+ flexShrink={1}
162
+ >
163
+ <b>{value()}</b>
164
+ </text>
165
+ </box>
166
+ )
167
+ }
168
+
169
+ export function SidebarTextRow(props: {
170
+ text: string
171
+ tone?: Tone
172
+ wrapMode?: JSX.IntrinsicElements['text']['wrapMode']
173
+ }) {
174
+ const context = frameContext()
175
+ return (
176
+ <text
177
+ fg={context.theme[props.tone ?? 'textMuted']}
178
+ wrapMode={props.wrapMode}
179
+ >
180
+ {props.text}
181
+ </text>
182
+ )
183
+ }
184
+
185
+ function usageTone(used: number, appearance: SidebarAppearance): Tone {
186
+ if (used >= appearance.errorThreshold) return 'error'
187
+ if (used >= appearance.warnThreshold) return 'warning'
188
+ return 'success'
189
+ }
190
+
191
+ function barSegments(
192
+ used: number,
193
+ appearance: SidebarAppearance,
194
+ pace?: PaceView,
195
+ ) {
196
+ const width = appearance.barWidth
197
+ const cells = (pct: number) =>
198
+ Math.max(0, Math.min(Math.round((pct / 100) * width), width))
199
+ const usedCells = cells(used)
200
+ const tone = usageTone(used, appearance)
201
+ const plain = [
202
+ { text: appearance.barFilledChar.repeat(usedCells), tone },
203
+ { text: appearance.barEmptyChar.repeat(width - usedCells), tone },
204
+ ]
205
+ const overlay = pace?.overlay
206
+ if (!overlay) return plain.filter((segment) => segment.text.length > 0)
207
+ const paceCells = cells(overlay.percent)
208
+ const lo = Math.min(usedCells, paceCells)
209
+ const hi = Math.max(usedCells, paceCells)
210
+ if (lo === hi) return plain.filter((segment) => segment.text.length > 0)
211
+ return [
212
+ { text: appearance.barFilledChar.repeat(lo), tone },
213
+ {
214
+ text: (overlay.kind === 'deficit' ? '\u2593' : '\u2592').repeat(hi - lo),
215
+ tone:
216
+ overlay.kind === 'deficit' ? ('error' as const) : ('success' as const),
217
+ },
218
+ { text: appearance.barEmptyChar.repeat(width - hi), tone },
219
+ ].filter((segment) => segment.text.length > 0)
220
+ }
221
+
222
+ function QuotaRow(props: {
223
+ part: QuotaWindowPart
224
+ pace?: PaceView
225
+ labelWidth: number
226
+ barCells: number
227
+ resetWidth: number
228
+ showReset: boolean
229
+ }) {
230
+ const context = frameContext()
231
+ const [columns, setColumns] = createSignal(0)
232
+ let row: { width: number } | undefined
233
+ const label = () =>
234
+ props.part.name +
235
+ ' '.repeat(Math.max(0, props.labelWidth - displayWidth(props.part.name)))
236
+ const figure = () =>
237
+ ` ${props.part.kind === 'budget' && props.part.figure.startsWith(`${props.part.name} `) ? props.part.figure.slice(props.part.name.length + 1) : props.part.figure}`
238
+ const used = () => 100 - (props.part.remainingPercent ?? 100)
239
+ const paceLine = () => {
240
+ const text = props.pace?.text
241
+ if (!text || columns() <= 0) return text
242
+ return fitText(text, columns() - props.labelWidth)
243
+ }
244
+ return (
245
+ <>
246
+ <box
247
+ ref={(element: { width: number }) => {
248
+ row = element
249
+ }}
250
+ onSizeChange={() => setColumns(row?.width ?? 0)}
251
+ width='100%'
252
+ flexDirection='row'
253
+ justifyContent='space-between'
254
+ >
255
+ <box
256
+ flexDirection='row'
257
+ flexShrink={props.part.resetSinceReading ? 1 : 0}
258
+ >
259
+ <Show when={props.labelWidth > 0}>
260
+ <text fg={context.theme.textMuted} wrapMode='none' flexShrink={0}>
261
+ {label()}
262
+ </text>
263
+ </Show>
264
+ <Show
265
+ when={!props.part.resetSinceReading}
266
+ fallback={
267
+ <text fg={context.theme.textMuted} wrapMode='none'>
268
+ reset since last check
269
+ </text>
270
+ }
271
+ >
272
+ <For
273
+ each={barSegments(
274
+ used(),
275
+ { ...context.appearance, barWidth: props.barCells },
276
+ props.pace,
277
+ )}
278
+ >
279
+ {(segment) => (
280
+ <text fg={context.theme[segment.tone]} wrapMode='none'>
281
+ {segment.text}
282
+ </text>
283
+ )}
284
+ </For>
285
+ <text
286
+ fg={context.theme[usageTone(used(), context.appearance)]}
287
+ wrapMode='none'
288
+ >
289
+ {figure()}
290
+ </text>
291
+ </Show>
292
+ </box>
293
+ <Show when={props.showReset && !props.part.resetSinceReading}>
294
+ <box
295
+ width={props.resetWidth}
296
+ flexShrink={0}
297
+ flexDirection='row'
298
+ justifyContent='flex-end'
299
+ >
300
+ <Show when={props.part.resetIn}>
301
+ <text fg={context.theme.textMuted} wrapMode='none'>
302
+ {props.part.resetIn}
303
+ </text>
304
+ </Show>
305
+ </box>
306
+ </Show>
307
+ </box>
308
+ {/* A changed fitted line needs a fresh text node to draw at its new width. */}
309
+ <Show when={!props.part.resetSinceReading && paceLine()} keyed>
310
+ {(line: string) => (
311
+ <box width='100%' flexDirection='row'>
312
+ <Show when={props.labelWidth > 0}>
313
+ <text fg={context.theme.textMuted}>
314
+ {''.padEnd(props.labelWidth)}
315
+ </text>
316
+ </Show>
317
+ <text
318
+ fg={context.theme[props.pace?.tone ?? 'textMuted']}
319
+ wrapMode='none'
320
+ >
321
+ {line}
322
+ </text>
323
+ </box>
324
+ )}
325
+ </Show>
326
+ </>
327
+ )
328
+ }
329
+
330
+ function CollapsedAccountRow(props: { account: AccountView }) {
331
+ const context = frameContext()
332
+ const [width, setWidth] = createSignal(0)
333
+ let row: { width: number } | undefined
334
+ const hasQuota = () =>
335
+ quotaWindowParts(props.account.quota, { now: context.now }).windows.length >
336
+ 0
337
+ const text = () =>
338
+ hasQuota()
339
+ ? formatQuota(props.account.quota, { now: context.now, form: 'narrow' })
340
+ : (props.account.emptyQuotaText?.collapsed ?? '\u2014')
341
+ // Reserve an ellipsis, a separator and the trailing indicator before keeping quota.
342
+ const showQuota = () => width() <= 0 || displayWidth(text()) + 4 <= width()
343
+ const label = () => {
344
+ if (width() <= 0) return props.account.label
345
+ return fitText(
346
+ props.account.label,
347
+ width() - (showQuota() ? displayWidth(text()) + 3 : 2),
348
+ )
349
+ }
350
+ const muted = () => props.account.collapsed?.muted ?? false
351
+ const quotaTone = () =>
352
+ muted() ? 'textMuted' : (props.account.collapsed?.quotaTone ?? 'success')
353
+ return (
354
+ <box
355
+ ref={(element: { width: number }) => {
356
+ row = element
357
+ }}
358
+ onSizeChange={() => setWidth(row?.width ?? 0)}
359
+ width='100%'
360
+ flexDirection='row'
361
+ justifyContent='space-between'
362
+ columnGap={label() ? 1 : 0}
363
+ >
364
+ <Show when={label()}>
365
+ <text
366
+ fg={context.theme[muted() ? 'textMuted' : 'text']}
367
+ wrapMode='none'
368
+ flexShrink={1}
369
+ >
370
+ {label()}
371
+ </text>
372
+ </Show>
373
+ <box flexDirection='row' flexShrink={0}>
374
+ <Show when={showQuota()}>
375
+ <Show
376
+ when={hasQuota() && !muted()}
377
+ fallback={<text fg={context.theme.textMuted}>{text()}</text>}
378
+ >
379
+ <text fg={context.theme[quotaTone()]}>
380
+ <b>{text()}</b>
381
+ </text>
382
+ </Show>
383
+ </Show>
384
+ <text fg={context.theme[props.account.indicatorTone]}>
385
+ {showQuota() ? ' ' : ''}
386
+ {props.account.blocked ? '\u2298' : '\u25cf'}
387
+ </text>
388
+ </box>
389
+ </box>
390
+ )
391
+ }
392
+
393
+ function AccountBlock(props: { account: AccountView; marginTop: number }) {
394
+ const context = frameContext()
395
+ const [columns, setColumns] = createSignal(0)
396
+ let block: { width: number } | undefined
397
+ const rows = () => props.account.groups.flatMap((group) => group.rows)
398
+ const labelWidth = () =>
399
+ Math.max(
400
+ 0,
401
+ ...rows().map(({ part }) =>
402
+ part.name ? Math.max(3, displayWidth(part.name) + 1) : 0,
403
+ ),
404
+ )
405
+ const resetWidth = () =>
406
+ Math.max(
407
+ 0,
408
+ ...rows().map(({ part }) =>
409
+ part.resetSinceReading ? 0 : displayWidth(part.resetIn ?? ''),
410
+ ),
411
+ )
412
+ const figureWidth = createMemo(() =>
413
+ Math.max(
414
+ 10,
415
+ ...rows()
416
+ .filter(({ part }) => !part.resetSinceReading)
417
+ .map(({ part }) =>
418
+ displayWidth(
419
+ ` ${part.kind === 'budget' && part.figure.startsWith(`${part.name} `) ? part.figure.slice(part.name.length + 1) : part.figure}`,
420
+ ),
421
+ ),
422
+ ),
423
+ )
424
+ const fit = (rowLabelWidth: number) => {
425
+ const desired = context.appearance.barWidth
426
+ // Four cells still distinguish quarters of a window without sacrificing its reset.
427
+ const minimum = Math.min(4, desired)
428
+ if (columns() <= 0)
429
+ return { barCells: desired, showReset: resetWidth() > 0 }
430
+ const room = columns() - rowLabelWidth - figureWidth()
431
+ const withReset = room - resetWidth() - 1
432
+ const showReset = resetWidth() > 0 && withReset >= minimum
433
+ const available = showReset ? withReset : room
434
+ return {
435
+ barCells: available >= minimum ? Math.min(desired, available) : 0,
436
+ showReset,
437
+ }
438
+ }
439
+ const label = () => {
440
+ const full = `${props.account.label}${props.account.titleSuffix ? ` · ${props.account.titleSuffix}` : ''}`
441
+ return columns() <= 0
442
+ ? full
443
+ : fitText(full, columns() - displayWidth(props.account.status.text) - 1)
444
+ }
445
+ const age = () =>
446
+ quotaWindowParts(props.account.quota, { now: context.now }).age
447
+ const hasRows = () =>
448
+ props.account.groups.some((group) => group.rows.length > 0)
449
+ return (
450
+ <box
451
+ ref={(element: { width: number }) => {
452
+ block = element
453
+ }}
454
+ onSizeChange={() => setColumns(block?.width ?? 0)}
455
+ width='100%'
456
+ flexDirection='column'
457
+ marginTop={props.marginTop}
458
+ >
459
+ <box
460
+ width='100%'
461
+ flexDirection='row'
462
+ justifyContent='space-between'
463
+ columnGap={1}
464
+ >
465
+ <text fg={context.theme.text} wrapMode='none' flexShrink={1}>
466
+ <b>{label()}</b>
467
+ </text>
468
+ <text
469
+ fg={context.theme[props.account.status.tone]}
470
+ wrapMode='none'
471
+ flexShrink={0}
472
+ >
473
+ <b>{props.account.status.text}</b>
474
+ </text>
475
+ </box>
476
+ {context.beforeQuota?.(props.account)}
477
+ <Show
478
+ when={hasRows()}
479
+ fallback={
480
+ <SidebarTextRow
481
+ text={props.account.emptyQuotaText?.expanded ?? '\u2014'}
482
+ wrapMode='none'
483
+ />
484
+ }
485
+ >
486
+ <For each={props.account.groups}>
487
+ {(group) => (
488
+ <>
489
+ <Show when={group.title}>
490
+ <SidebarTextRow
491
+ text={group.title ?? ''}
492
+ tone='text'
493
+ wrapMode='none'
494
+ />
495
+ </Show>
496
+ <For each={group.rows}>
497
+ {(row) => {
498
+ const rowLabelWidth = () => (row.part.name ? labelWidth() : 0)
499
+ const rowFit = createMemo(() => fit(rowLabelWidth()))
500
+ return (
501
+ <QuotaRow
502
+ part={row.part}
503
+ pace={row.pace}
504
+ labelWidth={rowLabelWidth()}
505
+ barCells={rowFit().barCells}
506
+ resetWidth={resetWidth()}
507
+ showReset={rowFit().showReset}
508
+ />
509
+ )
510
+ }}
511
+ </For>
512
+ </>
513
+ )}
514
+ </For>
515
+ </Show>
516
+ <Show when={age()}>
517
+ {(text: () => string) => (
518
+ <SidebarTextRow text={text()} wrapMode='none' />
519
+ )}
520
+ </Show>
521
+ {context.afterQuota?.(props.account)}
522
+ </box>
523
+ )
524
+ }
525
+
526
+ /** Borderless, controlled presentation; host registration and provider policy stay in the plugin. */
527
+ export function SidebarFrame(props: SidebarFrameProps) {
528
+ const hasData = () => props.accounts.length > 0
529
+ const headerLabel = () =>
530
+ !hasData()
531
+ ? props.header.badge
532
+ : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`
533
+ // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
534
+ const context = mergeProps(props, {
535
+ get theme(): SidebarTheme {
536
+ const theme = props.theme
537
+ return {
538
+ ...theme,
539
+ textMuted: theme?.textMuted ?? theme?.text,
540
+ accent: theme?.accent ?? theme?.text,
541
+ success: theme?.success ?? theme?.text,
542
+ warning: theme?.warning ?? theme?.text,
543
+ error: theme?.error ?? theme?.text,
544
+ }
545
+ },
546
+ })
547
+ // Inverting an incomplete badge palette can put light text on a light background.
548
+ const invertBadge = () =>
549
+ props.theme?.accent !== undefined && props.theme?.background !== undefined
550
+ return (
551
+ <FrameContext.Provider value={context}>
552
+ <box width='100%' flexDirection='column'>
553
+ {/* Blocked accounts retain their own indicators; the header always keeps its version. */}
554
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: OpenTUI terminal widgets do not have DOM roles */}
555
+ <box
556
+ width='100%'
557
+ flexDirection='row'
558
+ justifyContent='space-between'
559
+ alignItems='center'
560
+ onMouseDown={() => {
561
+ if (hasData()) props.onToggle()
562
+ }}
563
+ >
564
+ <box
565
+ paddingLeft={1}
566
+ paddingRight={1}
567
+ backgroundColor={invertBadge() ? props.theme?.accent : undefined}
568
+ >
569
+ <text
570
+ fg={
571
+ invertBadge() ? props.theme?.background : context.theme.accent
572
+ }
573
+ >
574
+ <b>{headerLabel()}</b>
575
+ </text>
576
+ </box>
577
+ <Show when={props.header.version}>
578
+ <text fg={context.theme.textMuted}>{props.header.version}</text>
579
+ </Show>
580
+ </box>
581
+ <Show when={props.collapsed && hasData()}>
582
+ <For each={props.accounts}>
583
+ {(account) => <CollapsedAccountRow account={account} />}
584
+ </For>
585
+ {props.collapsedSections?.()}
586
+ </Show>
587
+ <Show when={!props.collapsed || !hasData()}>
588
+ <Show when={props.showQuota && hasData()}>
589
+ <SidebarSection title='Quota'>
590
+ <For each={props.accounts}>
591
+ {(account, index) => (
592
+ <AccountBlock
593
+ account={account}
594
+ marginTop={index() === 0 ? 0 : 1}
595
+ />
596
+ )}
597
+ </For>
598
+ </SidebarSection>
599
+ </Show>
600
+ {props.sections?.()}
601
+ </Show>
602
+ </box>
603
+ </FrameContext.Provider>
604
+ )
605
+ }