@jsvision/code-editor / CodeEditor
Class: CodeEditor
Documented in: Code Editor
Defined in: code-editor/src/ui/code-editor.ts:67
Focusable terminal-native source editor backed by a document controller.
Example
const editor = new CodeEditor({ controller });Extends
Group
Constructors
Constructor
new CodeEditor(
options):CodeEditor
Defined in: code-editor/src/ui/code-editor.ts:109
Parameters
options
Returns
CodeEditor
Overrides
Group.constructor
Properties
assistanceView
readonlyassistanceView:CodeEditorAssistanceView
Defined in: code-editor/src/ui/code-editor.ts:86
background?
optionalbackground?: keyof Theme
Defined in: ui/dist/view/group.d.ts:55
Optional background theme role filled before children compose, so overlap never leaks cells.
Inherited from
Group.background
behavior
readonlybehavior:Readonly<{documentTransactions:true;keyboardOnly:false; }>
Defined in: code-editor/src/ui/code-editor.ts:74
bounds
bounds:
Rect
Defined in: ui/dist/view/view.d.ts:61
Parent-relative integer rect; written by the layout pass — read it in draw/hit-testing.
Inherited from
Group.bounds
castsShadow
castsShadow:
boolean
Defined in: ui/dist/view/view.d.ts:91
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
Group.castsShadow
centered
centered:
boolean
Defined in: ui/dist/view/view.d.ts:98
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
Group.centered
children
readonlychildren:View[]
Defined in: ui/dist/view/group.d.ts:53
Ordered children; array order is paint order (back-to-front).
Inherited from
Group.children
chrome
readonlychrome:Readonly<{horizontalScrollBar:false;statusLine:false;verticalScrollBar:false; }>
Defined in: code-editor/src/ui/code-editor.ts:84
controller
readonlycontroller:CodeEditorController
Defined in: code-editor/src/ui/code-editor.ts:69
focusable
focusable:
boolean=true
Defined in: code-editor/src/ui/code-editor.ts:68
Whether this view can receive keyboard focus. Effective focusability also requires the view to be visible and enabled with no hidden/disabled ancestor. Default false; the focus manager drives the state.focused flag.
Overrides
Group.focusable
focusState
focusState:
"idle"|"focused"|"released"='idle'
Defined in: code-editor/src/ui/code-editor.ts:88
grabsFocus
grabsFocus:
boolean
Defined in: ui/dist/view/view.d.ts:113
Whether a mouse-down that hits this view moves keyboard focus to it. Default true — the usual click-to-focus. Set false for a control that should act on a click without stealing focus from whatever is focused (e.g. a dialog Cancel button, or a toolbar/stepper button): the click still dispatches, but the previously-focused view keeps focus, so it never fires a focus-leave side effect such as a field's blur-validation. Independent of focusable — a grabsFocus: false view can still be reached by Tab and activated by Space.
Inherited from
Group.grabsFocus
i18n
readonlyi18n:I18n
Defined in: code-editor/src/ui/code-editor.ts:71
Exact locale-bound service used by this editor instance.
journey
readonlyjourney:string[] =[]
Defined in: code-editor/src/ui/code-editor.ts:85
layout
readonlylayout:Readonly<LayoutProps>
Defined in: ui/dist/view/view.d.ts:83
Layout props for this view (direction, size, padding, absolute placement, …) — read-only.
Change them with setLayout, which is the only writer. The field and every prop on it are closed, so neither view.layout = {…} nor view.layout.rect = {…} compiles, and neither does editing a solved rect a field at a time (view.layout.rect.x = 5). That is deliberate: a wholesale assignment silently drops every prop it omits and never reflows, and an in-place prop write reflows only if you remember to ask.
Read it freely — this is where a view's solved intent lives, and layout.rect is how an absolutely-placed view reports where it was put.
Inherited from
Group.layout
lineNumbers
readonlylineNumbers:boolean
Defined in: code-editor/src/ui/code-editor.ts:73
Whether this editor projects the optional line-number gutter.
nonColorIndicators
readonlynonColorIndicators: readonlystring[]
Defined in: code-editor/src/ui/code-editor.ts:75
postProcess
postProcess:
boolean
Defined in: ui/dist/view/view.d.ts:117
Take part in the post-process sweep (after the focused view sees the event).
Inherited from
Group.postProcess
preProcess
preProcess:
boolean
Defined in: ui/dist/view/view.d.ts:115
Take part in the pre-process sweep (root→down, before the focused view sees the event).
Inherited from
Group.preProcess
scroll
readonlyscroll:object
Defined in: code-editor/src/ui/code-editor.ts:87
x
readonlyx:Signal<number>
y
readonlyy:Signal<number>
state
readonlystate:ViewState
Defined in: ui/dist/view/view.d.ts:70
Draw-against flags. The object reference is fixed; individual fields mutate (e.g. focused).
Writing visible or disabled changes only what the next paint would draw — it does not ask for that paint. Follow such a write with invalidate (or invalidateLayout, which a visibility flip needs, since layout omits hidden views). A development build warns when a write goes unaccounted for.
Inherited from
Group.state
Accessors
interactionRevision
Get Signature
get interactionRevision():
number
Defined in: code-editor/src/ui/code-editor.ts:252
Returns a reactive counter that changes after each caret, selection, or document update.
Returns
number
retainedState
Get Signature
get retainedState():
object
Defined in: code-editor/src/ui/code-editor.ts:473
Returns content-free retained UI counters for lifecycle inspection.
Returns
object
completionItems
readonlycompletionItems:number
pendingHostEffects
readonlypendingHostEffects:number
popupRows
readonlypopupRows:number
snippetPlaceholders
readonlysnippetPlaceholders:number
searchState
Get Signature
get searchState():
CodeEditorSearchState
Defined in: code-editor/src/ui/code-editor.ts:257
Returns immutable keyboard find/replace state for host status and accessibility surfaces.
Returns
themeInspection
Get Signature
get themeInspection():
CodeEditorThemeResolutionReport
Defined in: code-editor/src/ui/code-editor.ts:409
Returns immutable content-free evidence for the active or retained palette.
Returns
CodeEditorThemeResolutionReport
viewportMetrics
Get Signature
get viewportMetrics():
CodeEditorViewportMetrics
Defined in: code-editor/src/ui/code-editor.ts:247
Returns reactive viewport geometry and clamped scroll limits for passive host chrome.
Returns
Methods
accelerators()
accelerators(): readonly
string[]
Defined in: ui/dist/view/view.d.ts:131
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
Group.accelerators
add()
add(
child):void
Defined in: ui/dist/view/group.d.ts:72
Add a child, appending it on top (later in the array draws in front). If this group is already mounted, the child mounts immediately — its scope nested under this group's — and a reflow is scheduled for the new layout; otherwise the child mounts when this group itself mounts.
Parameters
child
View
The view to append.
Returns
void
Inherited from
Group.add
addDynamic()
addDynamic(
build):void
Defined in: ui/dist/view/group.d.ts:104
Add children reactively from a Show/For accessor, so the set of children updates itself as signals change. When the group is mounted, an effect reads the accessor, mounts any newly produced views, unmounts any that disappeared (firing their onCleanup), and schedules a reflow on change. Pass a factory that builds the combinator inside itself, not an already-built accessor — this lets the group own and dispose the combinator's reactive nodes on unmount.
Parameters
build
DynamicBuilder
A factory that constructs the combinator, e.g. () => Show(cond, then) or () => For(each, key, render).
Returns
void
Example
import { Group, View, signal, Show, type DrawContext } from '@jsvision/ui';
class Panel extends View {
draw(ctx: DrawContext) {
ctx.fill(' ', ctx.color('window'));
}
}
const open = signal(false);
const group = new Group();
group.addDynamic(() => Show(() => open(), () => new Panel())); // Panel appears when `open` is trueInherited from
Group.addDynamic
bind()
bind<
T>(reader,apply?,opts?):void
Defined in: ui/dist/view/view.d.ts:277
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 { View, signal, type DrawContext } from '@jsvision/ui';
const count = signal(0);
class StatusLine extends View {
draw(ctx: DrawContext): void {
ctx.text(0, 0, `${count()} pending`, ctx.color('statusBar'));
}
}
const status = new StatusLine();
// In onMount, not the constructor: bind() needs the view's scope, which only exists once mounted.
status.onMount(() => {
status.bind(() => count()); // repaint the status line whenever `count` changes
});Inherited from
Group.bind
derived()
protectedderived<T>(fn): () =>T
Defined in: ui/dist/view/view.d.ts:299
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
Group.derived
desiredCaret()
desiredCaret():
Point|null
Defined in: code-editor/src/ui/code-editor.ts:527
Exposes the projected caret to the terminal event loop.
Returns
Point | null
Overrides
Group.desiredCaret
dispose()
dispose():
void
Defined in: code-editor/src/ui/code-editor.ts:459
Releases view-owned assistance, host-effect, and controller resources.
Returns
void
draw()
draw(
context):void
Defined in: code-editor/src/ui/code-editor.ts:488
Paints sanitized, semantically styled cells through JSVision.
Parameters
context
DrawContext
Returns
void
Overrides
Group.draw
execute()
execute(
command):void
Defined in: code-editor/src/ui/code-editor.ts:171
Executes one stable public editor command.
Parameters
command
CodeEditorCommand
Returns
void
focus()
focus():
boolean
Defined in: code-editor/src/ui/code-editor.ts:164
Gives the editor logical focus for standalone and test-driven operation.
Returns
boolean
focusSignal()
focusSignal():
Signal<void>
Defined in: ui/dist/view/view.d.ts:168
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
import { View, Button, type DrawContext } from '@jsvision/ui';
// A caption that highlights while the control it labels holds focus.
class Caption extends View {
constructor(
private readonly text: string,
private readonly target: View,
) {
super();
// Reading the target's focus signal inside bind() ties this view's repaint to the target's
// focus flips — a view can observe focus it does not own.
this.onMount(() => this.bind(() => this.target.focusSignal()()));
}
draw(ctx: DrawContext): void {
ctx.text(0, 0, this.text, ctx.color(this.target.state.focused ? 'labelSelected' : 'label'));
}
}
const ok = new Button('~O~K');
const caption = new Caption('Confirm:', ok);Inherited from
Group.focusSignal
insertText()
insertText(
text):boolean
Defined in: code-editor/src/ui/code-editor.ts:236
Inserts text through one validated document transaction.
Parameters
text
string
Returns
boolean
invalidate()
invalidate():
void
Defined in: ui/dist/view/view.d.ts:213
Request a repaint of this view. A no-op before the view is mounted (the first frame paints everything).
Returns
void
Inherited from
Group.invalidate
invalidateLayout()
invalidateLayout():
void
Defined in: ui/dist/view/view.d.ts:215
Request a reflow (re-run layout, then repaint). Use this when a change affects size/position, not just pixels.
Returns
void
Inherited from
Group.invalidateLayout
measure()?
optionalmeasure(available):Size2D
Defined in: ui/dist/view/view.d.ts:85
Optional intrinsic-size hook for auto sizing — return the size this view wants for available.
Parameters
available
Size2D
Returns
Size2D
Inherited from
Group.measure
onCleanup()
onCleanup(
fn):void
Defined in: ui/dist/view/view.d.ts:315
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
Group.onCleanup
onEvent()
onEvent(
event):void
Defined in: code-editor/src/ui/code-editor.ts:534
Bridges decoded terminal keys into the deterministic router.
Parameters
event
DispatchEvent
Returns
void
Overrides
Group.onEvent
onMount()
onMount(
fn):void
Defined in: ui/dist/view/view.d.ts:307
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
Group.onMount
openCompletion()
openCompletion(
items):void
Defined in: code-editor/src/ui/code-editor.ts:289
Opens a validated completion list without changing the document selection.
Parameters
items
readonly CodeEditorCompletionItem[]
Returns
void
openModal()
openModal(
modal):void
Defined in: code-editor/src/ui/code-editor.ts:294
Opens one modal surface; Escape always dismisses it first.
Parameters
modal
CodeEditorModalState
Returns
void
project()
project(
options):CodeEditorFrame
Defined in: code-editor/src/ui/code-editor.ts:414
Projects the current state for a concrete terminal viewport.
Parameters
options
caps
CapabilityProfile
height
number
width
number
Returns
remove()
remove(
child):void
Defined in: ui/dist/view/group.d.ts:80
Remove a child: dispose its scope (recursively disposing its descendants and running their onCleanup), detach it, and schedule a reflow. Removing a non-child (or removing twice) is a safe no-op.
Parameters
child
View
The view to remove.
Returns
void
Inherited from
Group.remove
resizeViewport()
resizeViewport(
width,height):void
Defined in: code-editor/src/ui/code-editor.ts:269
Re-fits a standalone or window-hosted editor before the next layout pass applies real bounds.
Normal drawing discovers its own dimensions automatically. Window composition calls this method during resize so caret tracking and scrollbar ranges update in the same event tick.
Parameters
width
number
height
number
Returns
void
Throws
When either dimension is not a supported non-negative integer.
routeKey()
routeKey(
key):CodeEditorKeyRoute
Defined in: code-editor/src/ui/code-editor.ts:328
Routes one key according to assistance/editor/text precedence.
Parameters
key
CodeEditorKey
Returns
selectByClick()?
optionalselectByClick():void
Defined in: ui/dist/view/view.d.ts:202
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
Group.selectByClick
setLayout()
setLayout(
patch):void
Defined in: ui/dist/view/view.d.ts:246
Change some of this view's layout props and request a reflow — the only way to write layout. Props the patch does not name are kept, and the reflow happens for you.
The merge is shallow, deliberately: size and rect are replaced whole rather than merged field-by-field. That is what makes a variant swap correct — going from {kind:'fixed',cells:1} to {kind:'fr',weight:1} must not leave a stale cells behind. The cost is that per-side padding cannot be patched one side at a time; pass the whole padding value.
Two behaviours worth knowing:
- An explicit
undefinedresets that prop to its layout default.setLayout({ size: undefined })makes the view auto-sized again, andsetLayout({ position: 'flow' })puts an absolutely-placed view back in the flow (its now-unusedrectis simply ignored). - Do not call it in a constructor of a class that subclasses may extend. A base constructor body runs before a subclass's
override readonly layout = {…}field initializer, and that initializer installs a fresh object, so the call would be erased. Call it after construction, or fromonMount.
Reflowing an unmounted view is a no-op, so calling it before mount is safe.
Parameters
patch
Partial<LayoutProps>
The layout props to change; anything omitted is preserved.
Returns
void
Example
import { Group } from '@jsvision/ui';
const panel = new Group();
panel.setLayout({ direction: 'col', padding: 1 });
// Later — `direction` and `padding` survive; once `panel` is mounted this also reflows:
panel.setLayout({ size: { kind: 'fr', weight: 1 } });Inherited from
Group.setLayout
setReplacementText()
setReplacementText(
replacement):void
Defined in: code-editor/src/ui/code-editor.ts:318
Updates bounded replacement text without mutating the source document.
Parameters
replacement
string
Returns
void
setSearchCaseSensitive()
setSearchCaseSensitive(
caseSensitive):void
Defined in: code-editor/src/ui/code-editor.ts:323
Selects case-sensitive or case-insensitive literal matching.
Parameters
caseSensitive
boolean
Returns
void
setSearchQuery()
setSearchQuery(
query):void
Defined in: code-editor/src/ui/code-editor.ts:313
Updates the keyboard-driven search query without changing source text.
Parameters
query
string
Returns
void
setTheme()
setTheme(
theme):void
Defined in: code-editor/src/ui/code-editor.ts:397
Snapshots a preset or resolver result for presentation-only changes.
Parameters
theme
CodeEditorTheme | ResolvedCodeEditorTheme
Returns
void
setThemeSource()
setThemeSource(
source):void
Defined in: code-editor/src/ui/code-editor.ts:403
Selects a live source resolved from the active application theme on every coalesced repaint.
Parameters
source
Returns
void
startSnippet()
startSnippet(
placeholders):void
Defined in: code-editor/src/ui/code-editor.ts:301
Starts validated, bounded snippet placeholder traversal.
Parameters
placeholders
readonly object[]
Returns
void
whenIdle()
whenIdle():
Promise<void>
Defined in: code-editor/src/ui/code-editor.ts:453
Resolves after all currently accepted host effects settle.
Returns
Promise<void>