Events and focus
Input travels through the logical DOM tree in three phases: capture walks ancestors from the dom.Document down to the target’s parent, target runs capture and then bubble listeners on the target itself, and bubble walks back up to the document for bubbling events.
Capture, target, and bubble
Section titled “Capture, target, and bubble”Pass event.Capture() to AddEventListener to intercept events before a focused descendant handles them. Register event.Once() for one-shot listeners or event.Passive() as a hint that the listener will not call PreventDefault(), and call sub.Cancel() to unsubscribe.
doc := eng.Document()
// Intercept Ctrl+K globally during capture before an input consumes it.shortcutSub := doc.AddEventListener(event.EventKeyDown, func(e event.Event) { ke, ok := e.(*event.KeyEvent) if !ok || !ke.MatchString("ctrl+k") { return } openCommandPalette() e.PreventDefault() e.StopPropagation()}, event.Capture())defer shortcutSub.Cancel()
// Stop Escape inside a modal panel from bubbling to outer document handlers.modal := element.Box().OnKey("esc", func(ke *event.KeyEvent) { closeModal() ke.StopPropagation()})To see all three phases in order, click the button inside this panel:
trace := element.Text("Click Trace click to watch each phase.")button := element.Button("Trace click").Style(demo.Default.PrimaryButton)panel := element.Box(button).Style( style.S(). Display(style.DisplayFlex). FlexDirection(style.FlexColumn). AlignItems(style.AlignStart),)
var phases []stringpanel.AddEventListener(event.EventClick, func(event.Event) { stopTimers() phases = []string{"1. Capture"} trace.SetData("1. Capture")}, event.Capture())
button.OnClick(func(*event.MouseEvent) { phases = append(phases, "2. Target") snapshot := strings.Join(phases, " → ") after(450*time.Millisecond, func() { trace.SetData(snapshot) })})
panel.OnClick(func(*event.MouseEvent) { phases = append(phases, "3. Bubble") snapshot := strings.Join(phases, " → ") after(900*time.Millisecond, func() { trace.SetData(snapshot) })})
root := element.Box( panel, element.Box(trace).Style( style.S().Foreground(demo.Default.Colors.Accent), ),).Style(demo.Default.Column())Built-in default behavior runs through three distinct mechanisms:
event.DefaultActionHandler: runs post-dispatch when!e.DefaultPrevented()(used by text controls forEventPaste).- Engine-level post-dispatch key actions:
Tab/Shift+Tabfocus traversal and arrow-key caret/spatial navigation also run after dispatch unlessPreventDefault()was called. - Built-in control listeners: behaviors such as text-control keydown editing and checkbox click/
Spacetoggling are registered on the control at construction. Intercept them in the capture phase (event.Capture()) withPreventDefault()(for text-control keydown) and/orStopPropagation()(required for checkboxes).
| Method | Stops current target listeners? | Stops ancestor phases? | Suppresses built-in default action? |
|---|---|---|---|
e.PreventDefault() |
No | No | Yes (e.DefaultPrevented() becomes true) |
e.StopPropagation() |
Yes (skips remaining listeners on current target) | Yes (skips remaining capture/bubble steps) | No for post-dispatch actions (call PreventDefault() too; capture-phase StopPropagation() skips target listeners) |
Some events do not bubble (e.Bubbles() is false): for example, EventFocus, EventBlur, EventMouseEnter, EventMouseLeave, EventPaste, and EventSelectionChange. Listen for EventFocusIn and EventFocusOut when a parent needs to observe descendant focus changes.
Typed listeners and mouse reporting
Section titled “Typed listeners and mouse reporting”Use typed element builders rather than type-asserting raw event.Event values on common controls:
OnPress(func()): activates on primary click or keyboardEnter/Spaceon buttons.OnClick(func(*event.MouseEvent)): receives screen/local coordinates,Button, andMods.OnChange(...): deliversstringonInputElement,TextAreaElement,SelectElement, andRadioGroupElement, orboolonCheckboxElement.OnKeyDown(func(*event.KeyEvent)): receives every keydown event;OnKey(combo, fn)filters byMatchString(combo).key.Key.MatchString(s ...string): matches one or more key combinations such aske.MatchString("esc", "ctrl+c").
status := element.Text("Press Enter or Esc")search := element.Input(""). WithPlaceholder("Search"). Style(demo.Default.Input)
search.OnKey("esc", func(e *event.KeyEvent) { status.SetData("Matched Esc") e.StopPropagation()})search.OnKey("enter", func(e *event.KeyEvent) { status.SetData("Matched Enter") e.PreventDefault()})
clear := element.Button("Clear"). Style(demo.Default.Button). OnPress(func() { search.SetValue("") status.SetData("Cleared") })Select the minimum terminal mouse reporting your UI needs with kite.WithMouseMode (constants live in package kite):
| Option | Reported mouse events |
|---|---|
kite.MouseModeOff |
Disables mouse reporting |
kite.MouseModeClick |
Button press and release events only |
kite.MouseModeDrag |
Clicks plus motion while a button is held (default) |
kite.MouseModeTrack |
All mouse motion, including unpressed hover movement |
Focus and FocusScope
Section titled “Focus and FocusScope”Controls can be focused or blurred programmatically (el.Focus(), el.Blur()), or queried on the document (doc.CurrentFocus(), doc.IsFocused(el)). Sequential Tab and Shift+Tab navigation visits eligible controls with TabIndex() >= 0 in DOM tree order; set WithTabIndex(-1) to keep a control programmatically focusable while excluding it from Tab, and call Disabled(true) rather than styling a control gray so focus and interaction skip it.
Arrow keys trigger spatial navigation (doc.NavigateFocus(dir) with dom.DirectionUp, dom.DirectionDown, dom.DirectionLeft, dom.DirectionRight). Text controls implement dom.SpatialCaret, so doc.MoveCaret(dir) moves the caret inside the control first and only shifts focus spatially once the caret hits an edge.
Use dom.FocusScope to trap focus within a modal or drawer subtree (focus.Scope is an internal alias, not an application import):
open := element.Button("Open drawer").Style(demo.Default.PrimaryButton)status := element.Text("Drawer closed")root := element.Box(open, status).Style(demo.Default.Column())
confirm := element.Button("Confirm"). Style(demo.Default.Button). OnPress(func() { status.SetData("Confirmed") })
cancel := element.Button("Cancel").Style(demo.Default.Button)drawer := element.Box(confirm, cancel).Style(demo.Default.ButtonRow)
open.OnPress(func() { if drawer.IsConnected() { return } root.AddChild(drawer) root.OwnerDocument().PushScope(&dom.FocusScope{ Root: drawer, Autofocus: confirm, }) status.SetData("Drawer open")})
cancel.OnPress(func() { root.OwnerDocument().PopScope() root.RemoveChild(drawer) status.SetData("Drawer closed")})scope.Root must be connected to doc before calling doc.PushScope(scope) (otherwise the focus manager discards the detached scope). element.Dialog automatically registers an overlay and pushes/pops a dom.FocusScope on connect and disconnect. For custom overlays or sub-panes, call doc.PushScope when opening and doc.PopScope when closing.
Selection and clipboard
Section titled “Selection and clipboard”Focus identifies a control; selection identifies a range of text. Read doc.Selection() or subscribe to event.EventSelectionChange rather than inferring selected text from the focused control. Note that EventSelectionChange does not bubble: attach input.OnSelectionChange(...) for caret/selection byte offsets inside a text control, or listen on doc for document selection range updates.
editor := element.Input("hello world").OnSelectionChange(func(e *event.SelectionChangeEvent) { updateStatusBar(e.Start, e.End)})
doc.AddEventListener(event.EventSelectionChange, func(event.Event) { selected := doc.Selection().String() _ = selected})To use the host OS clipboard instead of the default OSC 52 terminal clipboard, configure the engine with kite.WithClipboard(clipboard.New()) from extras/clipboard. Access the provider via doc.Terminal().Clipboard(), whose methods return *promise.Promise[T]:
cb := doc.Terminal().Clipboard()
// Copy plain text asynchronously, or store a custom MIME payload.cb.WriteText(doc.Selection().String()).Catch(logClipboardError)cb.Write("text/markdown", []byte("**selected**")).Catch(logClipboardError)
// Inspect available MIME formats before reading rich or plain content.cb.ListFormats().Then(func(formats []string) { if slices.Contains(formats, "image/png") { cb.Read("image/png").Then(func(data []byte) { attachImage(data) }, logClipboardError) return } cb.ReadText().Then(insertText, logClipboardError)}, logClipboardError)Handle errors explicitly rather than assuming every platform or terminal supports every MIME format. For Write(mime, data) and custom paste handling, see Clipboard.