@lynn123411/dsh-model-submenu 0.3.18 → 0.3.20

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.
@@ -1,49 +1,29 @@
1
- /**
2
- * Catalog flattening, tab derivation, and query matching for the picker.
3
- *
4
- * The model catalog groups models by provider; the picker shows one flat list
5
- * with a tab per provider. The shared text search index matches model and
6
- * provider names and IDs.
7
- */
8
1
 
9
2
  import type { ModelDirectoryState } from '@deepseek-ai/dsh-client-ui-model-selection/client'
10
3
  import { TextSearchIndex } from '@deepseek-ai/dsh-util-text-search'
11
4
 
12
- /** One provider group of the shared catalog. */
13
5
  export type ProviderGroup = ModelDirectoryState['groups'][number]
14
6
 
15
- /** One model inside a provider group. */
16
7
  export type CatalogModel = ProviderGroup['models'][number]
17
8
 
18
- /** One flat catalog row, carrying the provider identity beside the model. */
19
9
  export interface ModelRow extends ModelRef {
20
10
  readonly providerName: string
21
- /** The model id inside its provider, the other half of a selection. */
22
11
  readonly model: string
23
- /** The catalog entry itself, for name and reasoning metadata. */
24
12
  readonly entry: CatalogModel
25
13
  }
26
14
 
27
- /** A provider and one of its models: the pair every selection and favorite names. */
28
15
  export interface ModelRef {
29
16
  readonly provider: string
30
17
  readonly model: string
31
18
  }
32
19
 
33
- /** One picker tab. */
34
20
  export interface PickerTab {
35
21
  readonly id: string
36
22
  readonly label: string
37
23
  }
38
24
 
39
- /** The tab id standing for every provider. */
40
25
  export const ALL_TAB = '*'
41
26
 
42
- /**
43
- * Flatten the catalog to one row per model.
44
- * @param groups - the shared directory's provider groups, in display order.
45
- * @returns the rows in catalog order.
46
- */
47
27
  export function flattenGroups(groups: readonly ProviderGroup[]): readonly ModelRow[] {
48
28
  return groups.flatMap((group) => group.models.map((model) => ({
49
29
  provider: group.id,
@@ -53,12 +33,6 @@ export function flattenGroups(groups: readonly ProviderGroup[]): readonly ModelR
53
33
  })))
54
34
  }
55
35
 
56
- /**
57
- * Build the picker's tabs: the all-tab, then one per provider that has a model.
58
- * @param groups - the shared directory's provider groups.
59
- * @param allLabel - localized label for the all-tab.
60
- * @returns the tabs in catalog order.
61
- */
62
36
  export function pickerTabs(groups: readonly ProviderGroup[], allLabel = 'All'): readonly PickerTab[] {
63
37
  return [
64
38
  { id: ALL_TAB, label: allLabel },
@@ -66,27 +40,16 @@ export function pickerTabs(groups: readonly ProviderGroup[], allLabel = 'All'):
66
40
  ]
67
41
  }
68
42
 
69
- /**
70
- * @param rows - the flat catalog.
71
- * @param tab - the tab id; the all-tab keeps every row.
72
- * @returns the rows the tab shows, in their current order.
73
- */
74
43
  export function rowsForTab(rows: readonly ModelRow[], tab: string): readonly ModelRow[] {
75
44
  return tab === ALL_TAB ? rows : rows.filter((row) => row.provider === tab)
76
45
  }
77
46
 
78
- /** Build a reusable search index for the rows in the current provider tab. */
79
47
  export function createModelSearch(rows: readonly ModelRow[]): TextSearchIndex<ModelRow> {
80
48
  return new TextSearchIndex(rows, (row) => ({
81
49
  fuzzy: [row.entry.name, row.model, row.providerName, row.provider],
82
50
  }))
83
51
  }
84
52
 
85
- /**
86
- * Read the reasoning metadata the catalog advertises for one model.
87
- * @param groups - the shared directory's provider groups.
88
- * @returns the metadata, or undefined when that model advertises none.
89
- */
90
53
  export function reasoningOf(
91
54
  groups: readonly ProviderGroup[],
92
55
  ): (provider: string, model: string) => CatalogModel['reasoning'] {
@@ -1,72 +1,13 @@
1
- /**
2
- * When the composer menu writes a selection.
3
- *
4
- * Both gestures are immediate: clicking a level submits it, clicking a model
5
- * submits it. The only quiet path is clicking the model already in use — that
6
- * closes the menu without a write. A model click also restores the level this
7
- * browser last used for that model, so switching away and back never silently
8
- * resets the effort.
9
- */
10
1
 
11
2
  import type { ModelReasoning } from '@deepseek-ai/dsh-api-session-controller/types'
12
3
  import type { ModelDirectoryState } from '@deepseek-ai/dsh-client-ui-model-selection/client'
13
4
 
14
- /** One complete selection, as the directory's `select` takes it. */
15
5
  export interface Selection {
16
6
  readonly provider: string
17
7
  readonly model: string
18
8
  readonly reasoningEffort?: string
19
9
  }
20
10
 
21
- /** One segment of the reasoning row. */
22
- export interface EffortChoice {
23
- readonly key: string
24
- readonly effort: string | undefined
25
- readonly label: string
26
- }
27
-
28
- /**
29
- * Build the slider's detents for one model.
30
- *
31
- * The provider default is deliberately absent: it is a state, not a level, and
32
- * giving it a detent would read as the weakest reasoning instead of "let the
33
- * provider decide". The label above the track switches to it.
34
- * @param reasoning - the catalog's reasoning metadata, undefined when the model has none.
35
- * @returns one detent per advertised level, in catalog order.
36
- */
37
- export function effortChoices(reasoning: ModelReasoning | undefined): readonly EffortChoice[] {
38
- if (reasoning === undefined) return []
39
- return reasoning.efforts.map((level) => ({
40
- key: level.id,
41
- effort: level.id as string | undefined,
42
- label: level.name,
43
- }))
44
- }
45
-
46
- /**
47
- * The selection a level click submits.
48
- * @param live - the selection in force right now.
49
- * @param effort - the clicked level, undefined meaning the provider default.
50
- * @returns the selection to submit, or null when the level already is the live one.
51
- */
52
- export function planEffortCommit(live: Selection, effort: string | undefined): Selection | null {
53
- if (sameEffort(live.reasoningEffort, effort)) return null
54
- return {
55
- provider: live.provider,
56
- model: live.model,
57
- ...effort === undefined ? {} : { reasoningEffort: effort },
58
- }
59
- }
60
-
61
- /**
62
- * The selection a model click submits.
63
- * @param live - the selection in force right now, null before a first selection resolves.
64
- * @param provider - the clicked model's provider.
65
- * @param model - the clicked model id.
66
- * @param reasoningOf - the catalog's reasoning metadata for one provider and model.
67
- * @param remembered - the level this browser last used for the target model, if any.
68
- * @returns the selection to submit, or null when the click changes nothing.
69
- */
70
11
  export function planModelCommit(
71
12
  live: Selection | null,
72
13
  provider: string,
@@ -76,8 +17,6 @@ export function planModelCommit(
76
17
  ): Selection | null {
77
18
  if (live !== null && sameModel(live, provider, model)) return null
78
19
  const offered = reasoningOf(provider, model)
79
- // The target model's own memory is restored, so switching away and back never
80
- // silently resets the effort.
81
20
  const carried = offered !== undefined
82
21
  && remembered !== undefined
83
22
  && offered.efforts.some((level) => level.id === remembered)
@@ -88,16 +27,6 @@ export function planModelCommit(
88
27
  }
89
28
  }
90
29
 
91
- /**
92
- * The reasoning metadata the catalog advertises for the model in force.
93
- * @param state - the session's directory snapshot.
94
- * @returns the metadata, or undefined when no model is live or it advertises none.
95
- */
96
- export function liveReasoning(state: ModelDirectoryState): ModelReasoning | undefined {
97
- return currentCatalogModel(state)?.reasoning
98
- }
99
-
100
- /** Find the current model by its provider and model IDs. */
101
30
  export function currentCatalogModel(state: ModelDirectoryState) {
102
31
  const current = state.current
103
32
  if (current === null) return undefined
@@ -106,11 +35,6 @@ export function currentCatalogModel(state: ModelDirectoryState) {
106
35
  ?.models.find((model) => model.id === current.model)
107
36
  }
108
37
 
109
- /**
110
- * The selection in force, or null while the Host has not resolved one.
111
- * @param state - the session's directory snapshot.
112
- * @returns the live selection, with the effort only when one is set.
113
- */
114
38
  export function selectionOf(state: ModelDirectoryState): Selection | null {
115
39
  if (state.current === null) return null
116
40
  return state.current.reasoningEffort === undefined
@@ -122,21 +46,6 @@ export function selectionOf(state: ModelDirectoryState): Selection | null {
122
46
  }
123
47
  }
124
48
 
125
- /**
126
- * @param live - one selection.
127
- * @param provider - the provider to compare.
128
- * @param model - the model id to compare.
129
- * @returns whether both name the same model.
130
- */
131
49
  export function sameModel(live: Selection, provider: string, model: string): boolean {
132
50
  return live.provider === provider && live.model === model
133
51
  }
134
-
135
- /**
136
- * @param liveEffort - the level in force, undefined meaning the provider default.
137
- * @param effort - the level in question.
138
- * @returns whether they name the same level.
139
- */
140
- export function sameEffort(liveEffort: string | undefined, effort: string | undefined): boolean {
141
- return liveEffort === effort
142
- }
package/src/index.ts CHANGED
@@ -1,2 +1,35 @@
1
- /** Host entry. This plugin is client-only; the browser half is `./client`. */
2
- export function apply(): void {}
1
+ import type { Context } from '@deepseek-ai/cordis'
2
+ import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection'
3
+ import type {} from '@deepseek-ai/dsh-llm'
4
+ import { ACCOUNT_FACTS_PATH, ACCOUNT_PROVIDER, type AccountModelFacts } from './account-model-facts.ts'
5
+
6
+ export function apply(ctx: Context): void {
7
+ ctx.inject(['connection', 'llm'], (scope) => {
8
+ const { connection } = scope as Context & { connection: HostConnectionHandle }
9
+ return connection.fetch.register({
10
+ path: ACCOUNT_FACTS_PATH,
11
+ methods: ['GET'],
12
+ requestBody: 'buffered',
13
+ async fetch(request) {
14
+ try {
15
+ const llm = scope.llm
16
+ const models = llm.listProviders().some((provider) => provider.id === ACCOUNT_PROVIDER)
17
+ ? await llm.listModels(ACCOUNT_PROVIDER)
18
+ : []
19
+ const resolved = await Promise.allSettled(models.map(async (model): Promise<AccountModelFacts> => {
20
+ const info = await llm.resolveModelInfo(ACCOUNT_PROVIDER, model.id, request.signal)
21
+ return {
22
+ id: model.id,
23
+ ...(info.context === undefined ? {} : { contextWindow: info.context.contextWindow }),
24
+ ...(info.inputModalities === undefined ? {} : { inputModalities: info.inputModalities }),
25
+ }
26
+ }))
27
+ const rows = resolved.flatMap((result) => result.status === 'fulfilled' ? [result.value] : [])
28
+ return Response.json(rows, { headers: { 'Cache-Control': 'no-store' } })
29
+ } catch {
30
+ return new Response(null, { status: 503 })
31
+ }
32
+ },
33
+ })
34
+ })
35
+ }
@@ -1,191 +0,0 @@
1
- /**
2
- * The reasoning-level slider that replaces the Host's effort drill.
3
- *
4
- * The Host's second menu cell is a button that drills into a list of levels.
5
- * This slider sits inside that same cell, between the Host's label and value, so
6
- * the levels are reachable without leaving the menu. The levels are discrete but
7
- * the drag is not: the knob follows the pointer continuously, the level it
8
- * reports is the detent nearest that position, and letting go eases the knob onto
9
- * that detent and commits once. Keyboard arrows step and commit immediately.
10
- *
11
- * The fill takes the level's color, so the track and the two captions read as
12
- * one signal: "off" is neutral, the levels above it walk a blue-to-violet ramp,
13
- * and only the top level fills with the whole gradient.
14
- *
15
- * "Provider default" is not a detent: it is a state, drawn as an empty track
16
- * with a hollow knob, so it never reads as the lowest level.
17
- */
18
- import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';
19
- import type { EffortChoice } from './selection.ts';
20
- import { LEVEL_GRADIENT, isTopLevel, levelColor } from './level-color.ts';
21
- import { detentAt, fillWidth, fractionAt, knobOffset, offsetOf } from './slider.ts';
22
- import css from './ModelOptions.module.css';
23
-
24
- /** Props of the slider: the levels, the one in force, and the commit path. */
25
- export interface EffortSliderProps {
26
- /** The levels in catalog order, lowest first. */
27
- readonly steps: readonly EffortChoice[];
28
- /** Index of the level in force, already clamped into `steps`. */
29
- readonly current: number;
30
- /** Whether the provider default is in force instead of a level. */
31
- readonly defaultActive: boolean;
32
- /** Where the knob rests while the provider default is in force. */
33
- readonly defaultIndex: number;
34
- /** Localized name of the provider default, read while it is in force. */
35
- readonly defaultLabel: string;
36
- /** Whether a selection is in flight; input is ignored while it is. */
37
- readonly busy: boolean;
38
- /** Accessible name, taken from the Host's own row label. */
39
- readonly label: string;
40
- /** @param index - the level the user settled on. */
41
- readonly onCommit: (index: number) => void;
42
- }
43
-
44
- /**
45
- * Render the slider.
46
- * @param props - levels, the level in force, and the commit path.
47
- * @returns one focusable slider over the discrete levels.
48
- */
49
- export function EffortSlider({
50
- steps, current, defaultActive, defaultIndex, defaultLabel, busy, label, onCommit,
51
- }: EffortSliderProps) {
52
- const trackRef = useRef<HTMLDivElement | null>(null);
53
- // The drag position lives in a ref as well as in state: a press and a release
54
- // can arrive in one task, and the release must not read a render that never ran.
55
- const dragRef = useRef<number | null>(null);
56
- const pointerRef = useRef<number | null>(null);
57
- // While dragging this is where the pointer is along the travel, not a level:
58
- // the knob has to move with the pointer, or the drag reads as a series of jumps.
59
- const [drag, setDrag] = useState<number | null>(null);
60
- // After a release that submits, the knob waits on the detent it settled on
61
- // instead of springing back to the old level while the write is in flight.
62
- const [hold, setHold] = useState<number | null>(null);
63
- const dragging = drag !== null;
64
- const resting = defaultActive ? defaultIndex : current;
65
- const active = dragging ? detentAt(drag, steps.length) : resting;
66
- const knobFraction = drag ?? hold ?? offsetOf(resting, steps.length);
67
- // The color and the ticks follow the knob, not the level in force: during a
68
- // drag, and while a commit is in flight, the knob has already gone ahead.
69
- const shown = dragging || hold !== null ? detentAt(knobFraction, steps.length) : resting;
70
- const beginDrag = (fraction: number | null): void => {
71
- dragRef.current = fraction;
72
- setDrag(fraction);
73
- };
74
-
75
- // The hold ends as soon as the write does, whether it landed on the new level
76
- // or was rejected: the displayed level is the truth again either way.
77
- useEffect(() => {
78
- if (!busy) {
79
- setHold(null);
80
- return;
81
- }
82
- pointerRef.current = null;
83
- dragRef.current = null;
84
- setDrag(null);
85
- }, [busy]);
86
- useEffect(() => {
87
- setHold(null);
88
- }, [current, defaultActive]);
89
-
90
- const fractionAtPointer = (clientX: number): number => {
91
- const track = trackRef.current;
92
- if (track === null) return dragRef.current ?? knobFraction;
93
- const rect = track.getBoundingClientRect();
94
- return fractionAt(clientX, rect.left, rect.width);
95
- };
96
-
97
- const onPointerDown = (event: PointerEvent<HTMLDivElement>): void => {
98
- if (busy || event.button !== 0 || pointerRef.current !== null) return;
99
- // The Host's menu cell owns this subtree; without these the press would
100
- // also settle the cell and pull focus out of the slider.
101
- event.preventDefault();
102
- event.stopPropagation();
103
- setHold(null);
104
- pointerRef.current = event.pointerId;
105
- beginDrag(fractionAtPointer(event.clientX));
106
- try {
107
- event.currentTarget.setPointerCapture(event.pointerId);
108
- } catch {
109
- // A synthetic pointer has no capture to take; the drag still tracks moves.
110
- }
111
- event.currentTarget.focus();
112
- };
113
-
114
- const onPointerMove = (event: PointerEvent<HTMLDivElement>): void => {
115
- if (pointerRef.current !== event.pointerId || busy) return;
116
- beginDrag(fractionAtPointer(event.clientX));
117
- };
118
-
119
- const settle = (event: PointerEvent<HTMLDivElement>, commit: boolean): void => {
120
- if (pointerRef.current !== event.pointerId) return;
121
- pointerRef.current = null;
122
- beginDrag(null);
123
- if (!commit || busy) return;
124
- const next = detentAt(fractionAtPointer(event.clientX), steps.length);
125
- // Leaving the provider default is a change even when the knob lands where
126
- // the default already pointed.
127
- if (next !== current || defaultActive) {
128
- setHold(offsetOf(next, steps.length));
129
- onCommit(next);
130
- }
131
- };
132
-
133
- const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
134
- if (event.nativeEvent.isComposing) return;
135
- const last = steps.length - 1;
136
- const next = event.key === 'ArrowRight' || event.key === 'ArrowUp'
137
- ? Math.min(active + 1, last)
138
- : event.key === 'ArrowLeft' || event.key === 'ArrowDown'
139
- ? Math.max(active - 1, 0)
140
- : event.key === 'Home'
141
- ? 0
142
- : event.key === 'End'
143
- ? last
144
- : null;
145
- if (next === null) return;
146
- // The menu walks rows with the arrow keys; a slider keeps them for itself.
147
- event.preventDefault();
148
- event.stopPropagation();
149
- if (!busy && (next !== current || defaultActive)) onCommit(next);
150
- };
151
-
152
- const offset = knobOffset(knobFraction);
153
- // The provider default fills nothing: the knob shows where it lands, the
154
- // track stays empty so it never reads as a chosen level.
155
- const idle = defaultActive && !dragging && hold === null;
156
- const filled = idle ? 0 : knobFraction;
157
- const fill = isTopLevel(shown, steps.length) ? LEVEL_GRADIENT : levelColor(shown, steps.length);
158
- return <div
159
- ref={trackRef}
160
- className={css.slider}
161
- role="slider"
162
- tabIndex={0}
163
- aria-label={label}
164
- aria-valuemin={0}
165
- aria-valuemax={Math.max(0, steps.length - 1)}
166
- aria-valuenow={active}
167
- aria-valuetext={defaultActive && !dragging ? defaultLabel : steps[active]?.label}
168
- aria-disabled={busy || undefined}
169
- data-busy={busy ? '' : undefined}
170
- data-dragging={dragging ? '' : undefined}
171
- data-default={idle ? '' : undefined}
172
- onPointerDown={onPointerDown}
173
- onPointerMove={onPointerMove}
174
- onPointerUp={(event) => { settle(event, true); }}
175
- onPointerCancel={(event) => { settle(event, false); }}
176
- onLostPointerCapture={(event) => { settle(event, false); }}
177
- onKeyDown={onKeyDown}
178
- onClick={(event) => { event.stopPropagation(); }}
179
- >
180
- <div className={css.sliderTrack} aria-hidden="true">
181
- <div className={css.sliderFill} style={{ width: fillWidth(filled), background: fill }} />
182
- {steps.map((step, index) => <span
183
- key={step.key}
184
- className={css.sliderTick}
185
- data-on={index <= shown && !idle ? '' : undefined}
186
- style={{ left: knobOffset(offsetOf(index, steps.length)) }}
187
- />)}
188
- <div className={css.sliderKnob} style={{ left: offset }} />
189
- </div>
190
- </div>;
191
- }
@@ -1,61 +0,0 @@
1
- /**
2
- * Tint the composer's effort caption with the level's color.
3
- *
4
- * The slider's fill and the menu's value already carry the level's color; the
5
- * caption on the collapsed trigger is the third place the level shows, and it
6
- * lives outside the menu. This entry stays mounted for the whole session and
7
- * writes that one color, so all three read as one signal.
8
- *
9
- * The caption is recognized as the trigger's `span[class*='triggerEffort']`
10
- * child — the same class-substring contract the menu row uses. When the model
11
- * declares no levels the span does not exist and nothing is written.
12
- */
13
- import { useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';
14
- import type { ModelSelectInjected } from '@deepseek-ai/dsh-client-ui-model-selection/client';
15
- import { levelColor } from './level-color.ts';
16
- import { effortChoices, liveReasoning } from './selection.ts';
17
-
18
- /** Props of the tint: the shared catalog face. */
19
- export type EffortTintProps = Pick<ModelSelectInjected, 'available' | 'directory'>;
20
-
21
- /**
22
- * Render nothing and keep the trigger caption colored.
23
- * @param props - the session's catalog face.
24
- * @returns an inert marker.
25
- */
26
- export function EffortTint({ available, directory }: EffortTintProps) {
27
- const markerRef = useRef<HTMLSpanElement | null>(null);
28
- const [caption, setCaption] = useState<HTMLElement | null>(null);
29
- const state = useSyncExternalStore(
30
- (listener) => directory.subscribe(listener),
31
- () => directory.getSnapshot(),
32
- );
33
- const levels = effortChoices(liveReasoning(state));
34
- const effort = state.current?.reasoningEffort;
35
- const chosen = effort === undefined ? -1 : levels.findIndex((level) => level.effort === effort);
36
- // The provider default has no color of its own: the caption keeps the Host's.
37
- const color = available && chosen >= 0 && levels.length >= 2
38
- ? levelColor(chosen, levels.length)
39
- : null;
40
-
41
- // The Host rebuilds the trigger on every model change, so the caption is
42
- // re-read after each render; the identity guard keeps that from looping.
43
- useLayoutEffect(() => {
44
- const card = markerRef.current?.closest('[data-composer-card]');
45
- const next = card?.querySelector<HTMLElement>(
46
- '[data-slot="conversation.input.model"] button[aria-haspopup="menu"] span[class*="triggerEffort"]',
47
- ) ?? null;
48
- if (next !== caption) setCaption(next);
49
- });
50
-
51
- useLayoutEffect(() => {
52
- if (caption === null || color === null) return;
53
- const saved = caption.style.color;
54
- caption.style.color = color;
55
- return () => {
56
- caption.style.color = saved;
57
- };
58
- }, [caption, color]);
59
-
60
- return <span ref={markerRef} hidden />;
61
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * The accent one reasoning level carries.
3
- *
4
- * "Off" carries no accent at all — the fill and the caption stay neutral, so
5
- * switching reasoning off reads as switching it off rather than as the first
6
- * shade of a ramp. Every level above it walks a blue-to-violet ramp, and the
7
- * highest level is the only one whose fill is a gradient.
8
- */
9
-
10
- /** Off: the dimmed label tone, the same neutral the Host uses for quiet text. */
11
- const NEUTRAL = 'var(--dsw-alias-label-dimmed)';
12
-
13
- /** Lowest lit level: the blue the composer already uses for accents. */
14
- const LOW = [77, 147, 248] as const;
15
-
16
- /** Highest level: violet. */
17
- const HIGH = [147, 51, 234] as const;
18
-
19
- /**
20
- * @param t - a point on the ramp, 0 at the lowest lit level and 1 at the top.
21
- * @returns the ramp color there.
22
- */
23
- function ramp(t: number): string {
24
- const mix = (from: number, to: number): number => Math.round(from + (to - from) * t);
25
- return `rgb(${mix(LOW[0], HIGH[0])}, ${mix(LOW[1], HIGH[1])}, ${mix(LOW[2], HIGH[2])})`;
26
- }
27
-
28
- /**
29
- * @param index - the level's detent, 0 being "off".
30
- * @param count - number of detents.
31
- * @returns the level's color as a CSS color string.
32
- */
33
- export function levelColor(index: number, count: number): string {
34
- if (index <= 0) return NEUTRAL;
35
- // The top level is always the violet end, even when it is the only lit one.
36
- if (isTopLevel(index, count)) return ramp(1);
37
- const span = Math.max(1, count - 2);
38
- return ramp(Math.min(Math.max((index - 1) / span, 0), 1));
39
- }
40
-
41
- /**
42
- * @param index - the level's detent.
43
- * @param count - number of detents.
44
- * @returns whether this level is the only one painted with a gradient.
45
- */
46
- export function isTopLevel(index: number, count: number): boolean {
47
- return count > 1 && index === count - 1;
48
- }
49
-
50
- /** The top level's fill: the whole ramp, ending on the color its text takes. */
51
- export const LEVEL_GRADIENT = `linear-gradient(90deg, ${ramp(0)}, ${ramp(1)})`;
@@ -1,98 +0,0 @@
1
- /**
2
- * Geometry of the discrete effort slider.
3
- *
4
- * The track is a capsule and the knob a slightly larger circle riding on it, so
5
- * the knob overhangs the track instead of merging with its rounded end. The
6
- * knob's centre travels between two points inset by the knob's radius, so the
7
- * knob never runs past either end. A pointer position becomes a position along
8
- * that travel; a position becomes the detent nearest it, or the CSS lengths that
9
- * put the knob and the fill there.
10
- */
11
-
12
- /**
13
- * Track height in CSS pixels; the stylesheet keeps the same value. Half of it is
14
- * the radius of the track's ends and of the fill's cap.
15
- */
16
- export const TRACK_HEIGHT = 16;
17
-
18
- /**
19
- * Knob diameter in CSS pixels. It is larger than the track, so the knob reads as
20
- * a knob riding on the track rather than as the track's own end cap.
21
- */
22
- export const KNOB_SIZE = 20;
23
-
24
- /** The knob's centre keeps its own radius away from either end of the track. */
25
- const KNOB_RADIUS = KNOB_SIZE / 2;
26
-
27
- /**
28
- * @param index - detent index.
29
- * @param count - number of detents.
30
- * @returns the knob centre as a fraction of the track, 0 at the first detent and 1 at the last.
31
- */
32
- export function offsetOf(index: number, count: number): number {
33
- if (count <= 1) return 0;
34
- const clamped = Math.min(Math.max(index, 0), count - 1);
35
- return clamped / (count - 1);
36
- }
37
-
38
- /**
39
- * Where a pointer sits along the knob's travel. The drag reads this rather than a
40
- * detent, so the knob follows the pointer instead of jumping a level at a time.
41
- * @param clientX - pointer position in viewport coordinates.
42
- * @param left - the track's left edge in viewport coordinates.
43
- * @param width - the track's width in pixels.
44
- * @returns the position as a fraction of the travel, clamped to 0 and 1.
45
- */
46
- export function fractionAt(clientX: number, left: number, width: number): number {
47
- const usable = width - KNOB_SIZE;
48
- if (usable <= 0) return 0;
49
- const fraction = (clientX - left - KNOB_RADIUS) / usable;
50
- return Math.min(Math.max(fraction, 0), 1);
51
- }
52
-
53
- /**
54
- * @param fraction - a knob position between 0 and 1.
55
- * @param count - number of detents.
56
- * @returns the detent nearest that position.
57
- */
58
- export function detentAt(fraction: number, count: number): number {
59
- if (count <= 1) return 0;
60
- const clamped = Math.min(Math.max(fraction, 0), 1);
61
- return Math.round(clamped * (count - 1));
62
- }
63
-
64
- /**
65
- * @param clientX - pointer position in viewport coordinates.
66
- * @param left - the track's left edge in viewport coordinates.
67
- * @param width - the track's width in pixels.
68
- * @param count - number of detents.
69
- * @returns the detent nearest the pointer, clamped to the two ends.
70
- */
71
- export function stepAt(clientX: number, left: number, width: number, count: number): number {
72
- if (count <= 1) return 0;
73
- return detentAt(fractionAt(clientX, left, width), count);
74
- }
75
-
76
- /**
77
- * @param fraction - a knob position between 0 and 1.
78
- * @returns the CSS length that puts the knob centre there, inset at both ends.
79
- */
80
- export function knobOffset(fraction: number): string {
81
- const clamped = Math.min(Math.max(fraction, 0), 1);
82
- return `calc(${KNOB_RADIUS}px + ${clamped} * (100% - ${KNOB_SIZE}px))`;
83
- }
84
-
85
- /**
86
- * Width of the colored fill for a knob position.
87
- *
88
- * The fill is the track's own shape cut at the knob: its right cap carries the
89
- * track's radius and ends under the knob, so the color runs into the knob
90
- * instead of stopping at a straight edge, and the last detent reaches the track's
91
- * end rather than the knob's centre.
92
- * @param fraction - a knob position between 0 and 1.
93
- * @returns the CSS width of the fill.
94
- */
95
- export function fillWidth(fraction: number): string {
96
- const clamped = Math.min(Math.max(fraction, 0), 1);
97
- return `calc(${TRACK_HEIGHT}px + ${clamped} * (100% - ${TRACK_HEIGHT}px))`;
98
- }