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