@jsvision/ui / ColorSwatch
Class: ColorSwatch
Documented in: Color swatch
Defined in: ui/src/color/color-swatch.ts:85
A focusable grid of color cells. Selection is live — the bound value changes on every arrow key, click, and drag (each firing onInput), and the ◘ marker tracks it. Enter/Space or a mouse-up over a cell is the discrete commit and fires onChange (used by a hosting ColorPicker to close its dropdown).
Example
import { Group, ColorSwatch, signal } from '@jsvision/ui';
import { ANSI16_ORDER } from '@jsvision/core';
import type { Color } from '@jsvision/core';
const g = new Group();
const value = signal<Color>('brightCyan');
// A 4×4 grid of the 16 DOS colors, bound two-way to `value`.
const swatch = new ColorSwatch({
value,
colors: ANSI16_ORDER as readonly Color[],
columns: 4,
onInput: (c) => console.log('previewing', c), // arrows / click / drag update `value` live
onChange: (c) => console.log('committed', c), // Enter / Space / mouse-up commits
});
swatch.layout = { position: 'absolute', rect: { x: 1, y: 1, width: 12, height: 4 } };
g.add(swatch);Extends
Constructors
Constructor
new ColorSwatch(
opts):ColorSwatch
Defined in: ui/src/color/color-swatch.ts:106
Parameters
opts
The two-way value + optional colors/columns/onInput/onChange/nameFor.
Returns
ColorSwatch
Overrides
Properties
bounds
bounds:
Rect
Defined in: ui/src/view/view.ts:65
Parent-relative integer rect; written by the layout pass — read it in draw/hit-testing.
Inherited from
castsShadow
castsShadow:
boolean=false
Defined in: ui/src/view/view.ts:78
When true, the renderer paints a drop shadow on the cells just below and to the right of this view, in paint order (a later sibling's shadow falls over an earlier one). Default false. The Desktop sets it per window.
Inherited from
centered
centered:
boolean=false
Defined in: ui/src/view/view.ts:86
When true, the layout pass recentres this view within its parent after layout — origin = (parent - self) / 2 on both axes. Intended for absolutely-placed views (a modal dialog, a message box) whose size is fixed and whose origin would otherwise be placed by the caller. Default false; Dialog sets it when centered.
Inherited from
colors
protectedreadonlycolors: readonlyColor[]
Defined in: ui/src/color/color-swatch.ts:94
columns
protectedreadonlycolumns:number
Defined in: ui/src/color/color-swatch.ts:95
cursor
protectedreadonlycursor:Signal<number>
Defined in: ui/src/color/color-swatch.ts:99
The cell the arrow keys move from; kept in sync with value on every change.
focusable
focusable:
boolean=true
Defined in: ui/src/color/color-swatch.ts:87
The swatch takes focus so its arrow-key navigation is scoped to it.
Overrides
layout
layout:
LayoutProps={}
Defined in: ui/src/view/view.ts:69
Layout props for this view (direction, size, padding, absolute placement, …).
Inherited from
nameFor?
readonlyoptionalnameFor?: (c) =>string
Defined in: ui/src/color/color-swatch.ts:92
Optional pure color-name accessor, read by a hosting ColorPicker caption.
Parameters
c
Color
Returns
string
onChange?
protectedreadonlyoptionalonChange?: (c) =>void
Defined in: ui/src/color/color-swatch.ts:97
Parameters
c
Color
Returns
void
onInput?
protectedreadonlyoptionalonInput?: (c) =>void
Defined in: ui/src/color/color-swatch.ts:96
Parameters
c
Color
Returns
void
postProcess
postProcess:
boolean=false
Defined in: ui/src/view/view.ts:98
Take part in the post-process sweep (after the focused view sees the event).
Inherited from
preProcess
preProcess:
boolean=false
Defined in: ui/src/view/view.ts:96
Take part in the pre-process sweep (root→down, before the focused view sees the event).
Inherited from
state
readonlystate:ViewState
Defined in: ui/src/view/view.ts:67
Draw-against flags. The object reference is fixed; individual fields mutate (e.g. focused).
Inherited from
value
readonlyvalue:Signal<Color>
Defined in: ui/src/color/color-swatch.ts:90
Two-way selected color.
Methods
accelerators()
accelerators(): readonly
string[]
Defined in: ui/src/view/view.ts:114
The Alt+hotkey accelerator characters (lowercase) this view claims in its focus scope, for duplicate-accelerator detection. The base returns none; accelerator-bearing widgets (Button/Label/CheckGroup/RadioGroup) override it to report their ~X~ hotkey(s).
Returns
readonly string[]
The claimed accelerator chars, or an empty list when the view claims none.
Inherited from
applyHit()
protectedapplyHit(localX,localY):void
Defined in: ui/src/color/color-swatch.ts:252
Select the cell under a view-local pointer: revert outside the grid, clamp a partial-row overshoot.
Parameters
localX
number
localY
number
Returns
void
bind()
bind<
T>(reader,apply?,opts?):void
Defined in: ui/src/view/view.ts:228
Bind a reactive value to a redraw. Creates an effect (owned by this view's scope) that reads reader() — subscribing to whatever signals it touches — runs the optional apply(value), then requests a frame: a repaint by default, or a reflow when { relayout: true }. It re-runs automatically whenever those signals change, and is disposed when the view unmounts.
Call it from onMount, not the constructor — the view's scope only exists once mounted, so a pre-mount bind throws rather than silently dropping the binding.
Type Parameters
T
T
Parameters
reader
() => T
Reads the reactive source; the signals it reads become dependencies.
apply?
(v) => void
Optional: apply the read value to the widget (e.g. store it in a field).
opts?
Pass { relayout: true } when the change affects layout, so it reflows instead of just repainting.
relayout?
boolean
Returns
void
Example
import { signal } from '@jsvision/ui';
const count = signal(0);
// `status` is a View whose draw() reads count():
status.onMount(() => {
status.bind(() => count()); // repaint the status line whenever `count` changes
});Inherited from
close()
protectedclose():void
Defined in: ui/src/color/color-swatch.ts:157
Fire the commit callback (onChange) with the current value (Enter/Space or a mouse-up over a cell).
Returns
void
derived()
protectedderived<T>(fn): () =>T
Defined in: ui/src/view/view.ts:261
Create a stable derived accessor owned by this view's scope. The returned () => T keeps the same identity for the life of the view, so it is safe to build in the constructor and hand to child views before this view mounts. The backing computed is created lazily under the view's own scope, so it is always owned and disposed at unmount — unlike a bare computed() in the constructor, which would run before any scope exists, leak, and warn.
Reads behave sensibly across the lifecycle:
- Before mount: evaluates
fn()directly (correct current value, nothing persisted). Good for a pre-mount natural-size measure. - After mount: builds and memoizes a
computed(fn)under the view's scope. - After an unmount→remount: the memo is keyed to the scope it was built under, so a remounted view (which gets a fresh scope) re-derives under the new scope instead of returning the previous mount's disposed, now-frozen computed — keeping a
Show/For-remounted widget reactive.
Type Parameters
T
T
Parameters
fn
() => T
The derivation (pure; the signals it reads become the computed's dependencies).
Returns
A stable accessor; call it to read the derived value.
() => T
Inherited from
desiredCaret()
desiredCaret():
Point|null
Defined in: ui/src/view/view.ts:192
Where this view wants the hardware text cursor, in view-local cells, or null for no cursor (the default — most views never show one). A focused text input overrides this to place the caret at the edit position; the event loop reads it after each frame, converts it to an absolute cell, and moves the terminal cursor there.
Returns
Point | null
The view-local caret point (0-based, relative to this view's origin), or null.
Inherited from
draw()
draw(
ctx):void
Defined in: ui/src/color/color-swatch.ts:162
Paint the color cells, then the ◘ marker on the selected cell (contrasting colour if near-black).
Parameters
ctx
Returns
void
Overrides
focusSignal()
focusSignal():
Signal<void>
Defined in: ui/src/view/view.ts:136
Subscribe to this view's focus changes. Reading the returned signal inside a bind/effect re-runs that effect whenever this view gains or loses focus — including from another view (e.g. a Label repainting when the control it labels is focused). The signal notifies on every poke even without a value change. Lazy: the backing signal is created on first call.
Returns
Signal<void>
A signal that ticks whenever this view gains or loses focus.
Example
// Inside a widget's onMount, repaint whenever `other` view's focus changes:
this.onMount(() => this.bind(() => other.focusSignal()()));Inherited from
handleMouse()
protectedhandleMouse(ev):void
Defined in: ui/src/color/color-swatch.ts:225
Mouse down snapshots the current cell (as the revert target), selects the cell under the pointer, and captures the pointer so the drag keeps tracking even off the grid. A drag selects the cell under the pointer live, reverting to the snapshot when the pointer moves outside the grid. A mouse-up over a real cell fires the close hook (so a hosting ColorPicker closes); a release outside the grid does not close.
Parameters
ev
The dispatch envelope (carries local plus the pointer-capture seams).
Returns
void
invalidate()
invalidate():
void
Defined in: ui/src/view/view.ts:197
Request a repaint of this view. A no-op before the view is mounted (the first frame paints everything).
Returns
void
Inherited from
invalidateLayout()
invalidateLayout():
void
Defined in: ui/src/view/view.ts:202
Request a reflow (re-run layout, then repaint). Use this when a change affects size/position, not just pixels.
Returns
void
Inherited from
measure()
measure():
Size2D
Defined in: ui/src/color/color-swatch.ts:132
Advertise the grid's intrinsic size (width × rows) for auto sizing.
Returns
Overrides
onCleanup()
onCleanup(
fn):void
Defined in: ui/src/view/view.ts:298
Register a teardown callback that runs once when this view unmounts. Requires a mounted view — so call it from within onMount. Use it to release anything the view acquired (a timer, an external subscription).
Parameters
fn
() => void
The teardown callback.
Returns
void
Inherited from
onEvent()
onEvent(
ev):void
Defined in: ui/src/color/color-swatch.ts:185
Handle keyboard (wrap-around arrows + Enter/Space commit) and mouse (click/drag selection). Plain arrow keys are always consumed so navigation never leaves the swatch.
Parameters
ev
The dispatch envelope.
Returns
void
Overrides
onMount()
onMount(
fn):void
Defined in: ui/src/view/view.ts:283
Register a callback to run once when the view becomes live (after its first layout gives it bounds). This is where to call bind, since the view's reactive scope exists by then. Registering after the view is already live runs the callback immediately.
Parameters
fn
() => void
Post-mount setup.
Returns
void
Inherited from
select()
select(
color):void
Defined in: ui/src/color/color-swatch.ts:138
Programmatically select a color: set value and fire both the live onInput and commit onChange.
Parameters
color
Color
Returns
void
selectByClick()?
optionalselectByClick():void
Defined in: ui/src/view/view.ts:182
Optional "select + raise on click" hook. Left undefined on the base, so a plain view is not a select/raise target. A container that owns z-order (a Window) overrides it to select and raise itself. The hit-test invokes the first ancestor that defines this — before delivering the mouse-down — so a click always raises the window even if the interior also consumes the click.
Returns
void
Inherited from
setLive()
protectedsetLive(idx):void
Defined in: ui/src/color/color-swatch.ts:148
Select cell idx and update value immediately so the ◘ marker tracks it. A no-op for an out-of-range index. This does NOT close a hosting ColorPicker — that is the close hook.
Parameters
idx
number
Returns
void