@jsvision/ui / Editor
Class: Editor
Documented in: Editor
Defined in: ui/src/editor/editor.ts:74
A focusable, scrollable multiline text editor. Add it to a Group, give it a size, and drive it via the event loop or programmatically (setText/getText/insertText/ execute). The reactive signals (curPos, modified, canUndo, …) drive a status line/indicator. The loop shares Cut/Copy/Paste; use an optional clipboard projection for visibility and EditWindow for scroll bars (see EditorOptions).
Example
import { Group, Editor, createEventLoop, effect } from '@jsvision/ui';
import { resolveCapabilities } from '@jsvision/core';
const caps = resolveCapabilities().profile;
const editor = new Editor({ clipboard: new Editor() });
const root = new Group();
root.add(editor);
const loop = createEventLoop({ width: 60, height: 20 }, { caps });
loop.mount(root);
loop.focusView(editor);
editor.setText('The quick brown fox\nSecond line.');
effect(() => {
const { line, col } = editor.curPos();
console.log(`caret at ${line}:${col}`);
});Extends
Extended by
Constructors
Constructor
new Editor(
options?):Editor
Defined in: ui/src/editor/editor.ts:140
Parameters
options?
EditorOptions = {}
Returns
Editor
Overrides
Properties
autoIndentOn
autoIndentOn:
boolean
Defined in: ui/src/editor/editor.ts:106
bounds
bounds:
Rect
Defined in: ui/src/view/view.ts:66
Parent-relative integer rect; written by the layout pass — read it in draw/hit-testing.
Inherited from
canRedo
readonlycanRedo:Signal<boolean>
Defined in: ui/src/editor/editor.ts:92
canUndo
readonlycanUndo:Signal<boolean>
Defined in: ui/src/editor/editor.ts:91
Whether an undo / redo step is available.
castsShadow
castsShadow:
boolean=false
Defined in: ui/src/view/view.ts:97
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:105
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
curPos
readonlycurPos:Signal<{col:number;line:number; }>
Defined in: ui/src/editor/editor.ts:83
The caret as 1-based {line, col} (col is the visual column).
curPtr
curPtr:
number=0
Defined in: ui/src/editor/editor.ts:100
curY
curY:
number=0
Defined in: ui/src/editor/editor.ts:109
delta
readonlydelta:object
Defined in: ui/src/editor/editor.ts:94
The scroll offset, as a pair of signals — also the value channel for scroll bars: a bar bound to delta.x/delta.y scrolls the editor on any write (clamped to the content).
x
readonlyx:Signal<number>
y
readonlyy:Signal<number>
doReplace
doReplace:
boolean=false
Defined in: ui/src/editor/editor.ts:257
drawLine
drawLine:
number=0
Defined in: ui/src/editor/editor.ts:110
drawPtrP
drawPtrP:
number=0
Defined in: ui/src/editor/editor.ts:111
eolKind
eolKind:
LineEnding='lf'
Defined in: ui/src/editor/editor.ts:99
focusable
focusable:
boolean=true
Defined in: ui/src/editor/editor.ts:75
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
grabsFocus
grabsFocus:
boolean=true
Defined in: ui/src/view/view.ts:122
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
hasSelection
readonlyhasSelection:Signal<boolean>
Defined in: ui/src/editor/editor.ts:85
Whether any text is currently selected.
indicator
indicator:
IndicatorTarget|null=null
Defined in: ui/src/editor/editor.ts:134
insertMode
readonlyinsertMode:Signal<boolean>
Defined in: ui/src/editor/editor.ts:87
true = insert mode, false = overwrite mode; the Insert key toggles it.
keyBindings
readonlykeyBindings:EditorKeyBindings
Defined in: ui/src/editor/editor.ts:115
layout
readonlylayout:Readonly<LayoutProps> ={}
Defined in: ui/src/view/view.ts:88
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
limitY
limitY:
number=1
Defined in: ui/src/editor/editor.ts:112
lineCount
readonlylineCount:Signal<number>
Defined in: ui/src/editor/editor.ts:89
The number of lines in the buffer.
modified
readonlymodified:Signal<boolean>
Defined in: ui/src/editor/editor.ts:81
Whether the buffer has unsaved changes since it was last loaded or saved.
normalRole
protectednormalRole: keyofTheme='editorNormal'
Defined in: ui/src/editor/editor.ts:137
The normal/selected theme roles; Memo overrides them to the gray-dialog palette.
options
readonlyoptions:EditorOptions
Defined in: ui/src/editor/editor.ts:120
overwrite
overwrite:
boolean
Defined in: ui/src/editor/editor.ts:105
postProcess
postProcess:
boolean=false
Defined in: ui/src/view/view.ts:126
Take part in the post-process sweep (after the focused view sees the event).
Inherited from
preProcess
preProcess:
boolean=true
Defined in: ui/src/editor/editor.ts:77
Sees keys before app chrome so the focused editor can claim the WordStar Ctrl-Q/Ctrl-K prefixes.
Overrides
promptOnReplace
promptOnReplace:
boolean=true
Defined in: ui/src/editor/editor.ts:255
replaceAllFlag
replaceAllFlag:
boolean=false
Defined in: ui/src/editor/editor.ts:256
replaceStr
replaceStr:
string=''
Defined in: ui/src/editor/editor.ts:253
searchOpts
searchOpts:
SearchOptions
Defined in: ui/src/editor/editor.ts:254
selectedRole
protectedselectedRole: keyofTheme='editorSelected'
Defined in: ui/src/editor/editor.ts:138
selecting
selecting:
boolean=false
Defined in: ui/src/editor/editor.ts:104
selEndP
selEndP:
number=0
Defined in: ui/src/editor/editor.ts:103
state
readonlystate:ViewState
Defined in: ui/src/view/view.ts:75
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
undoStack
readonlyundoStack:UndoStack
Defined in: ui/src/editor/editor.ts:123
vBar
vBar:
GadgetBar|null=null
Defined in: ui/src/editor/editor.ts:133
Methods
accelerators()
accelerators(): readonly
string[]
Defined in: ui/src/view/view.ts:142
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
attachGadgets()
attachGadgets(
h?,v?,ind?):void
Defined in: ui/src/editor/editor.ts:233
Wire up the scroll bars and line/column indicator that display and drive this editor.
Parameters
h?
GadgetBar
v?
GadgetBar
ind?
Returns
void
bind()
bind<
T>(reader,apply?,opts?):void
Defined in: ui/src/view/view.ts:326
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
copy()
copy():
void
Defined in: ui/src/editor/editor.ts:283
Copy the selection to the canonical clipboard and refresh any visible clipboard projection.
Returns
void
cut()
cut():
void
Defined in: ui/src/editor/editor.ts:288
Cut the selection to the canonical clipboard as one undo step.
Returns
void
deleteSelect()
deleteSelect():
void
Defined in: ui/src/editor/editor.ts:421
Returns
void
derived()
protectedderived<T>(fn): () =>T
Defined in: ui/src/view/view.ts:359
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/editor/editor.ts:241
The hardware-caret cell (view-local) while focused and in view, else null.
Returns
Point | null
Overrides
doSearchReplace()
doSearchReplace():
Promise<number>
Defined in: ui/src/editor/editor.ts:278
Returns
Promise<number>
draw()
draw(
ctx):void
Defined in: ui/src/editor/editor.ts:491
Paint the visible rows.
Parameters
ctx
Returns
void
Overrides
execute()
execute(
action):void
Defined in: ui/src/editor/editor.ts:228
Run one editor action programmatically — the same operations the keymap triggers.
Parameters
action
The action to run (e.g. 'lineDown', 'undo', 'textEnd', 'selectAll').
Returns
void
Example
import { Editor } from '@jsvision/ui';
const editor = new Editor();
editor.setText('hello world');
editor.execute('textEnd'); // caret to end of bufferfind()
find():
Promise<void>
Defined in: ui/src/editor/editor.ts:260
Open the Find dialog and search for the first match. Resolves when the interaction is done.
Returns
Promise<void>
focusSignal()
focusSignal():
Signal<void>
Defined in: ui/src/view/view.ts:183
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
getMousePtr()
getMousePtr(
local):number
Defined in: ui/src/editor/editor.ts:474
Parameters
local
Returns
number
getText()
getText(
range?):string
Defined in: ui/src/editor/editor.ts:199
The full buffer content, or the text in a [from, to) range — returned verbatim.
Parameters
range?
Optional half-open buffer-offset range; omit for the whole buffer.
from
number
to
number
Returns
string
The requested text.
insertText()
insertText(
text):void
Defined in: ui/src/editor/editor.ts:208
Insert text at the caret, replacing any selection; line endings are normalized to the buffer's kind, as if typed.
Parameters
text
string
The text to insert.
Returns
void
invalidate()
invalidate():
void
Defined in: ui/src/view/view.ts:244
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:250
Request a reflow (re-run layout, then repaint). Use this when a change affects size/position, not just pixels.
Returns
void
Inherited from
measure()?
optionalmeasure(available):Size2D
Defined in: ui/src/view/view.ts:90
Optional intrinsic-size hook for auto sizing — return the size this view wants for available.
Parameters
available
Returns
Inherited from
onCleanup()
onCleanup(
fn):void
Defined in: ui/src/view/view.ts:396
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/editor/editor.ts:496
Handle a dispatched event (keys, mouse/wheel, paste, and editing commands).
Parameters
ev
Returns
void
Overrides
onMount()
onMount(
fn):void
Defined in: ui/src/view/view.ts:381
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
paste()
paste():
void
Defined in: ui/src/editor/editor.ts:293
Paste the canonical clipboard at the caret as one undo step.
Returns
void
redo()
redo():
void
Defined in: ui/src/editor/editor.ts:303
Redo the most recently undone edit.
Returns
void
replace()
replace():
Promise<number>
Defined in: ui/src/editor/editor.ts:265
Open the Replace dialog and run the replace loop; resolves with the number of replacements made.
Returns
Promise<number>
scrollTo()
scrollTo(
x,y):void
Defined in: ui/src/editor/editor.ts:465
Parameters
x
number
y
number
Returns
void
searchAgain()
searchAgain():
Promise<number>
Defined in: ui/src/editor/editor.ts:270
Repeat the last search/replace with the stored parameters; resolves with the replacement count.
Returns
Promise<number>
searchOnce()
searchOnce():
boolean
Defined in: ui/src/editor/editor.ts:274
Returns
boolean
selectByClick()?
optionalselectByClick():void
Defined in: ui/src/view/view.ts:229
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
selectionText()
selectionText():
string
Defined in: ui/src/editor/editor.ts:214
The currently selected text, or '' when there is no selection.
Returns
string
setLayout()
setLayout(
patch):void
Defined in: ui/src/view/view.ts:285
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
setText()
setText(
text):void
Defined in: ui/src/editor/editor.ts:173
Replace the entire content (verbatim, mixed line endings preserved); the line-ending kind is re-detected and cursor/selection/scroll/undo history are reset.
Parameters
text
string
The new buffer content.
Returns
void
toggleInsMode()
toggleInsMode():
void
Defined in: ui/src/editor/editor.ts:459
Returns
void
undo()
undo():
void
Defined in: ui/src/editor/editor.ts:298
Undo the most recent edit.
Returns
void
viewH()
viewH():
number
Defined in: ui/src/editor/editor.ts:313
Returns
number