Connect browser text editing and preserve IME ownership across redraws

This commit is contained in:
waozi committed 2026-09-15 11:57:58 -03:00
1 parent 6ee1f4baeb
commit 4d60fab509
14 files changed
+567 -30

No files matched your search

+8 -1
View File
@@ -571,7 +571,14 @@ generated-runtime-parity-test: $(K2C) $(K2GO) $(K2JS) $(LIB) $(KRYON_BACKEND_LIB
keyboard-policy-test: $(K2JS) menu-policy-test collapsible-policy-test text-input-policy-test
sh tests/keyboard_policy_test.sh $(BUILD_DIR)
fast-test: keyboard-policy-test
fast-test: keyboard-policy-test web-text-capacity-test
.PHONY: web-text-capacity-test web-text-input-browser-test
web-text-capacity-test: $(K2JS)
sh tests/web_text_capacity_test.sh $(K2JS)
web-text-input-browser-test:
sh tests/web_text_input_browser_test.sh .
.PHONY: widget-instance-test
preflight test: widget-instance-test
+2 -2
View File
@@ -836,9 +836,9 @@ tx_index_base_start(const char *dst, size_t end)
return i;
continue;
}
if(isalnum((unsigned char)dst[i - 1]) || dst[i - 1] == '_') {
if(isalnum((unsigned char)dst[i - 1]) || dst[i - 1] == '_' || dst[i - 1] == '$') {
while(i > 0 && (isalnum((unsigned char)dst[i - 1]) ||
dst[i - 1] == '_'))
dst[i - 1] == '_' || dst[i - 1] == '$'))
i--;
while(i > 0 && (dst[i - 1] == ' ' || dst[i - 1] == '\t'))
i--;
+7
View File
@@ -1371,6 +1371,13 @@ typedef struct {
} TextInputProps;
```
Web `TextField`/`TextArea` bindings update their `.kry` state through the same
editing decisions as queued input. Cursor positions use UTF-8 byte offsets;
the DOM adapter translates browser UTF-16 selections. Preedit remains provisional
until composition commits, and blur cancels it. Redraw preserves the active DOM
editor. Declared fixed char state-buffer sizes in `sizeof(buffer)` are emitted
as numeric web capacities.
#### `TextField`
```c
+9 -2
View File
@@ -166,12 +166,19 @@ word-boundary rule; Go applies generated navigation, deletion and composition
decisions. Hosts traverse UTF-8 bytes to resolve the requested cursor movement.
Native and Go event loops sample keys and apply those decisions; clipboard IO, buffer
storage, focus registration and pointer-event queues remain host services.
The web queued editor uses generated text-input policy, with JavaScript limited
The web queued editor and live DOM text fields use generated text-input policy,
with JavaScript limited
to string storage, UTF-8 offset traversal, event routing and clipboard transport.
Go and web defer input after backward Tab until the destination's next frame,
discarding it if focus changes in between. Composition events do not transfer
to the next field during Tab navigation.
Generated JavaScript keyboard policy and queued editing behavior are checked
by `make keyboard-policy-test`.
This focused policy proof does not imply complete web block or IME parity; see
`make web-text-input-browser-test` exercises live DOM typing, clipboard,
composition and redraw, then Chromium keyboard/pointer events, wrapped visual
lines and native preedit presentation. The browser owns UTF-16 DOM selection,
visual-row geometry, caret scrolling and platform IME presentation; the adapter
translates offsets to the UTF-8 byte positions used by application state.
Stable DOM nodes stay attached during redraw so focus and composition survive.
This coverage does not imply complete web block or every platform's IME parity; see
`plan/canonical/README.md` for the remaining execution audit.
+47
View File
@@ -0,0 +1,47 @@
# Text input ownership and verification
Editing decisions live in `runtime/text_input.kry`. The C, Go, and JavaScript
hosts apply generated decisions and store the resulting text and selection.
| Path | Selection and focus ownership | Platform services |
| --- | --- | --- |
| Immediate C (`src/ui/ui.c`) | `TextSelectionOwnerMatches`, `TextFocusOwnerDecisionFor`, generated selection ranges and navigation | Caller-buffer/pointer identity, input collection, font measurement, clipboard |
| Retained C (`src/ui/ui_tree.c`) | Node-owned state; generated collapse/select-all/navigation, composition input gates and edit-command decisions | Node lifetime, focus registration, buffer movement, paint invalidation |
| Go (`go/kryon/runtime.go`, `composition.go`) | Focus-ID keyed state; generated selection, navigation, deletion and composition decisions | UTF-8 traversal, field registration, event queues, font measurement |
| Web (`web/text_edit.js`, `text_dom.js`) | Runtime focus ID and DOM-node binding; generated editing/navigation/composition decisions | UTF-16/UTF-8 conversion, native visual-row geometry, pointer hit testing, clipboard transport and IME presentation |
The retained C composition cancellation gate now uses the same generated
`TextCompositionInputDecisionFor` as Go and web. Numeric editors in `ui_tk.c`
retain numeric-control activation and storage; they are not an alternate
TextField implementation. Their separate numeric policy remains in `input.kry`.
DOM events do not enqueue a second synthetic tap. Browser selection is
translated back to byte offsets before editing and after native pointer or
visual-row movement. Stable DOM nodes are not detached or emptied during
redraw. Read-only/disabled transitions, blur, and replacing an editor binding
cancel provisional composition. Native IME presentation is not copied into
the committed application buffer until commit.
The compiler resolves `sizeof(name)` for fixed char arrays declared in module
state into numeric TextField/TextArea capacities. The capacity regression uses
an eight-byte buffer, an emoji replacement, and a preserved Unicode suffix.
## Verified behavior
- `make keyboard-policy-test`: generated policy and queued web editing, Unicode
offsets, clipboard restrictions, insertion limits, multiline navigation,
read-only fields, focus handoff, and composition ownership.
- `make web-text-capacity-test`: compiled `.kry` state-buffer capacity enforcement.
- `make web-text-input-browser-test`: live DOM events plus real Chromium keyboard
and pointer input, wrapped rows, Home/End, Page Up/Down scrolling, backward Tab,
native browser preedit, redraw, single commit, and screenshots.
- `make generated-runtime-parity-test`: matched C/Go/JS fixtures; the composition
fixture additionally exercises web preedit, commit/cancel and read-only input.
- `make go-runtime-test` and the retained `ui_tk_test`: native ownership,
navigation, focus, composition and retained-control regressions.
The browser tests use Chromium's native composition API. They do not automate
an operating-system IME candidate window or establish coverage for every
browser/OS pairing. Logical-line queued tests and browser visual-row tests are
reported separately; the full native composition fixture still includes native
layout and pointer scenarios beyond the shared event sequence.
+12 -16
View File
@@ -1,19 +1,15 @@
# Remaining text editing work
- Audit retained/immediate selection ownership and focus transitions for
decisions still implemented independently of `runtime/text_input.kry`.
- Connect browser DOM input/composition events and selection presentation to
the shared editor path. Queued web input is covered; browser-native IME
candidate windows and actual DOM selection still need integration tests.
- Finish web parity for composition presentation, wrapped-line geometry,
pointer selection and scrolling. The composition fixture now executes web
preedit, commit/cancel and read-only behavior; its full native scenario
also tests layout-dependent movement and selection.
- Carry declared `.kry` buffer capacities into web props. The queued web host
enforces explicit numeric text sizes and codepoint limits, but `sizeof(buffer)`
is not yet evaluated in serialized widget props.
- Extend matched composition-fixture execution to the remaining native
layout/pointer scenarios. Web logical editing and live Chromium visual-row,
pointer and composition tests now run, but are separate tests.
- Verify native OS IME candidate windows and browser/platform combinations
beyond Chromium. The automated browser test exercises native composition
events and visible preedit, not the OS candidate window.
- Extend web capacity lowering beyond fixed char arrays in module state where
maintained callers need local buffers or computed capacity expressions.
Raw buffers, memory movement, clipboard IO, font measurement, UTF-8 traversal,
and platform IME remain host services. `EditText` is the active native
buffer-edit service. Do not create a new text widget or forwarding layer.
See `docs/BOUNDARIES.md` for the shared policy/host split.
Completed behavior, source ownership and verification commands live in
`docs/TEXT_INPUT_BEHAVIOR.md`. Buffers, OS input, font measurement, UTF-8
traversal and browser geometry remain host services. Keep editing decisions in
`runtime/text_input.kry`; do not add a second editor or compatibility layer.
+4 -2
View File
@@ -1451,8 +1451,10 @@ RouteInput(void)
if(field->focused != NULL)
*field->focused = state->focused;
int keyboard_captured = ui_popup_input_snapshot_keyboard_captures(ui_tree_input_snapshot(node));
if((!state->focused || field->read_only || keyboard_captured) &&
ui_text_composition_cancel(state)) {
TextCompositionInputDecision composition_input =
TextCompositionInputDecisionFor(state->focused && !keyboard_captured,
field->read_only);
if(composition_input.cancel && ui_text_composition_cancel(state)) {
ui_text_field_event(node,EVENT_COMPOSITION_CHANGED,GetTime());
ui_tree_invalid |= INVALIDATE_PAINT;
}
+4 -2
View File
@@ -4,8 +4,10 @@ build=${1:-build/linux-x86_64}
work=$(mktemp -d "${TMPDIR:-/tmp}/kryon-keyboard-policy.XXXXXX")
trap 'rm -rf "$work"' EXIT INT TERM
"$build/bin/k2js" --strict --no-main --root runtime \
--runtime ./kryon-runtime.js -o "$work" runtime/*.kry
cp web/kryon-runtime.js web/text_edit.js "$work/"
--runtime ./kryon-runtime.js -o "$work" runtime/menu.kry runtime/collapsible.kry runtime/text_input.kry \
runtime/control_props.kry runtime/drawing_props.kry runtime/style.kry \
runtime/style_sheet.kry runtime/surface.kry runtime/instance.kry
cp web/kryon-runtime.js web/text_edit.js web/text_dom.js "$work/"
cp tests/keyboard_policy_test.mjs tests/web_text_edit_test.mjs "$work/"
printf '%s\n' '{"type":"module"}' > "$work/package.json"
node "$work/keyboard_policy_test.mjs"
+13
View File
@@ -0,0 +1,13 @@
#import "kryon.h"
app "Text buffer capacity" {
size 240 100
}
state {
value: [8] char = "aβ"
cursor: int = 1
byte: int = 0
}
capacity_frame :: () #ui {
byte = value[1]
TextField((TextFieldProps){.text = value, .text_size = sizeof(value), .cursor_position = &cursor, .focus_id = 35101})
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
set -eu
compiler=${1:-build/linux-x86_64/bin/k2js}
work=$(mktemp -d /tmp/kryon-text-capacity.XXXXXX)
trap 'rm -rf "$work"' EXIT INT TERM
"$compiler" --root . -o "$work" tests/parity/text_capacity.kry
cp web/*.js "$work/"
printf '%s\n' '{"type":"module"}' > "$work/package.json"
cat > "$work/check.mjs" <<'JS'
import assert from "node:assert/strict";
import * as fixture from "./tests/parity/text_capacity.js";
import {createRuntime} from "./kryon-runtime.js";
const rt=createRuntime(), state=fixture.createState();
rt.SetFocus(35101);
rt.SetSelection(35101,0,1);
rt.QueueText("😀");
fixture.frame(rt,state);
assert.equal(state.byte,206);
assert.equal(state.value,"😀β");
assert.equal(state.cursor,4);
rt.QueueText("日");
fixture.frame(rt,state);
assert.equal(state.value,"😀β");
assert.equal(state.cursor,4);
console.log("compiled web buffer capacity passed");
JS
node "$work/check.mjs"
+74
View File
@@ -0,0 +1,74 @@
#!/bin/sh
set -eu
root=$(cd "${1:-.}" && pwd)
work=${2:-$(mktemp -d /tmp/kryon-text-browser.XXXXXX)}
mkdir -p "$work/profile"
cat > "$work/index.html" <<HTML
<!doctype html><meta charset="utf-8"><title>Kryon text input verification</title>
<style>body{font:18px sans-serif;background:#f5f7fa;padding:32px}input,textarea{display:block;margin:16px;padding:12px;width:300px;font:20px monospace}#result{white-space:pre-wrap}</style>
<h1>Kryon text input verification</h1><div id="app"></div><pre id="result">Running</pre>
<script type="module">
import * as k from 'file://$root/web/kryon-runtime.js';
const rt=k.createRuntime();
const state={first:'a界β',cursor:6,second:'second',secondCursor:6,notes:'line one\nline two\nline three\nline four\nline five\nline six',notesCursor:0,readonly:false};
function draw(){
k.beginFrame(rt);
k.widget(rt,'Screen',{},state,{path:'root'});
for(const [name,text,cursor,id] of [['TextField','first','cursor',1],['TextField','second','secondCursor',2],['TextArea','notes','notesCursor',3]])
k.widget(rt,name,'(TextFieldProps){.text = '+text+', .cursor_position = &'+cursor+', .focus_id = '+id+', .text_size = 64, .read_only = readonly}',state,{path:'root/'+id,parentPath:'root'});
k.endFrame(rt);k.mount(rt,document.querySelector('#app'));
}
function check(value,message){if(!value)throw Error(message)}
function input(el,text){el.dispatchEvent(new InputEvent('beforeinput',{bubbles:true,cancelable:true,inputType:'insertText',data:text}));}
function key(el,name,options={}){el.dispatchEvent(new KeyboardEvent('keydown',{bubbles:true,cancelable:true,key:name,...options}));}
try{
draw();
const first=document.querySelector('input'),second=document.querySelectorAll('input')[1];
first.focus();first.setSelectionRange(1,2);input(first,'日');
check(state.first==='a日β' && state.cursor===4,'Unicode replacement/byte cursor');
const clipboard=new DataTransfer();clipboard.setData('text/plain','界');
first.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,cancelable:true,clipboardData:clipboard}));
check(state.first==='a日界β','paste');
first.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
first.value='a日界にβ';
first.dispatchEvent(new CompositionEvent('compositionupdate',{bubbles:true,data:'に'}));
check(state.first==='a日界β','preedit mutated committed text');
draw();
check(first.value==='a日界にβ','rerender destroyed preedit');
first.dispatchEvent(new CompositionEvent('compositionend',{bubbles:true,data:'日本'}));
check(state.first==='a日界日本β','composition commit');
first.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'insertCompositionText',data:'日本'}));
check(state.first==='a日界日本β','composition inserted twice');
first.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
first.value='provisional';
first.dispatchEvent(new CompositionEvent('compositionupdate',{bubbles:true,data:'wrong'}));
second.focus();
first.dispatchEvent(new CompositionEvent('compositionend',{bubbles:true,data:'wrong'}));
check(state.first==='a日界日本β' && state.second==='second','composition leaked after blur');
first.focus();first.dispatchEvent(new CompositionEvent('compositionstart',{bubbles:true}));
first.value='provisional';
first.dispatchEvent(new CompositionEvent('compositionupdate',{bubbles:true,data:'wrong'}));
state.readonly=true;draw();
first.dispatchEvent(new CompositionEvent('compositionend',{bubbles:true,data:'wrong'}));
check(state.first==='a日界日本β' && !first.__kryTextComposing,'readonly transition did not cancel composition');
second.focus();input(second,'blocked');key(second,'Backspace');
check(state.second==='second','readonly mutated text');
state.readonly=false;draw();
first.focus();first.setSelectionRange(0,first.value.length);input(first,'verified 日本');
check(state.first==='verified 日本','editing after readonly');
key(first,'Escape');check(rt.Focus()===0,'Escape did not blur');
document.querySelector('#result').textContent='PASS: Unicode selection, paste, preedit, rerender, IME commit, blur cancellation, read-only, Escape';
document.body.dataset.result='ok';
window.textTest={rt,state,draw};
}catch(error){document.body.dataset.result='fail';document.querySelector('#result').textContent=error.stack;}
</script>
HTML
chromium --headless=new --disable-gpu --no-sandbox --allow-file-access-from-files \
--virtual-time-budget=3000 --user-data-dir="$work/profile" --window-size=900,900 \
--screenshot="$work/text-input.png" --dump-dom "file://$work/index.html" > "$work/dom.html" 2> "$work/browser.log"
if ! rg -q 'data-result="ok"' "$work/dom.html"; then
cat "$work/dom.html"
exit 1
fi
printf 'Browser text input passed. Screenshot: %s/text-input.png\n' "$work"
node "$root/tests/web_text_input_events_test.mjs" "$work"
+91
View File
@@ -0,0 +1,91 @@
import {spawn} from "node:child_process";
import {writeFileSync} from "node:fs";
import assert from "node:assert/strict";
const work = process.argv[2];
const browser = spawn("chromium", ["--headless=new", "--no-sandbox", "--disable-gpu",
"--allow-file-access-from-files", "--remote-debugging-port=0",
`--user-data-dir=${work}/events-profile`, "about:blank"]);
let socket;
try {
const endpoint = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(Error("Chromium startup timed out")), 15000);
browser.stderr.on("data", chunk => {
const match = String(chunk).match(/DevTools listening on (ws:\/\/\S+)/);
if (match) { clearTimeout(timeout); resolve(match[1]); }
});
browser.on("error", reject);
});
socket = new WebSocket(endpoint);
await new Promise(resolve => socket.addEventListener("open", resolve, {once: true}));
let id = 0;
const pending = new Map();
socket.addEventListener("message", event => {
const response = JSON.parse(event.data);
const callback = pending.get(response.id);
if (callback) { pending.delete(response.id); callback(response); }
});
function send(method, params = {}, sessionId) {
return new Promise((resolve, reject) => {
const request = ++id;
pending.set(request, response => response.error ? reject(Error(JSON.stringify(response.error))) : resolve(response.result));
socket.send(JSON.stringify({id: request, method, params, sessionId}));
});
}
const {targetId} = await send("Target.createTarget", {url: `file://${work}/index.html`});
const {sessionId} = await send("Target.attachToTarget", {targetId, flatten: true});
const call = (method, params) => send(method, params, sessionId);
async function evaluate(expression) {
const response = await call("Runtime.evaluate", {expression, returnByValue: true, awaitPromise: true});
if (response.exceptionDetails) throw Error(JSON.stringify(response.exceptionDetails));
return response.result.value;
}
await evaluate(`new Promise((resolve,reject)=>{
const deadline=Date.now()+5000;
const poll=()=>window.textTest?resolve(true):Date.now()>deadline?reject(Error(document.querySelector('#result').textContent)):setTimeout(poll,20);
poll();
})`);
await evaluate(`textTest.state.notes='alpha beta gamma delta epsilon zeta eta theta iota';textTest.draw();
window.area=document.querySelector('textarea');area.style.width='130px';area.style.height='55px';
area.focus();area.setSelectionRange(0,0);`);
async function key(name, code, modifiers = 0) {
await call("Input.dispatchKeyEvent", {type: "keyDown", key: name, code: name, windowsVirtualKeyCode: code, modifiers});
await call("Input.dispatchKeyEvent", {type: "keyUp", key: name, code: name, windowsVirtualKeyCode: code, modifiers});
}
await key("ArrowDown", 40);
assert.ok(await evaluate("area.selectionStart>0 && textTest.state.notesCursor===area.selectionStart"), "wrapped Down and cursor ownership");
await key("End", 35);
const lineEnd = await evaluate("area.selectionStart");
await key("Home", 36);
assert.ok(await evaluate(`area.selectionStart<${lineEnd}`), "visual Home/End");
await key("PageDown", 34);
assert.ok(await evaluate("area.scrollTop>0"), "PageDown scrolls the caret into view");
await key("PageUp", 33);
await evaluate("area.scrollTop=0");
const rect = await evaluate("(()=>{const r=area.getBoundingClientRect();return {x:r.x+16,y:r.y+18}})()");
await call("Input.dispatchMouseEvent", {type:"mousePressed",x:rect.x,y:rect.y,button:"left",buttons:1,clickCount:1});
await call("Input.dispatchMouseEvent", {type:"mouseMoved",x:rect.x+75,y:rect.y+25,button:"left",buttons:1});
await call("Input.dispatchMouseEvent", {type:"mouseReleased",x:rect.x+75,y:rect.y+25,button:"left",clickCount:1});
await evaluate("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
const pointer = await evaluate("({start:area.selectionStart,end:area.selectionEnd,cursor:textTest.state.notesCursor,direction:area.selectionDirection})");
assert.ok(pointer.end > pointer.start && pointer.cursor === pointer.end, "pointer selection across wrapped lines: " + JSON.stringify(pointer));
assert.ok(await evaluate("!textTest.rt.input.events.some(event=>event.type==='tap')"), "DOM selection queued a duplicate synthetic tap");
await key("Tab", 9, 8);
assert.ok(await evaluate("document.activeElement===document.querySelectorAll('input')[1] && textTest.rt.Focus()===2"), "backward Tab follows browser focus order");
await evaluate("document.querySelector('#result').textContent+='\\nPASS: real key events, wrapped lines, Home/End, Page Up/Down, pointer selection, backward Tab';");
await evaluate("window.first=document.querySelector('input');first.focus();first.setSelectionRange(first.value.length,first.value.length);window.beforeIME=textTest.state.first;");
await call("Input.imeSetComposition", {text:"に",selectionStart:1,selectionEnd:1});
assert.ok(await evaluate("first.value.endsWith('に') && textTest.state.first===beforeIME"), "native browser preedit presentation");
await evaluate("textTest.draw()");
assert.ok(await evaluate("first.value.endsWith('に') && document.activeElement===first"), "native preedit survives redraw");
const preedit = await call("Page.captureScreenshot", {format:"png"});
writeFileSync(`${work}/text-input-preedit.png`, Buffer.from(preedit.data,"base64"));
await call("Input.insertText", {text:"日"});
assert.ok(await evaluate("textTest.state.first===beforeIME+'日' && first.value===textTest.state.first"), "native browser composition commits once");
const capture = await call("Page.captureScreenshot", {format:"png"});
writeFileSync(`${work}/text-input-events.png`, Buffer.from(capture.data,"base64"));
console.log("Real browser text input events passed");
} finally {
socket?.close();
browser.kill();
}
+24 -5
View File
@@ -1,4 +1,4 @@
import {registerTextEditor, connectTextEditor, bindTextEditorEvents} from "./text_dom.js";
import {registerTextEditor, connectTextEditor, hasTextEditor, bindTextEditorEvents, refreshTextEditor, presentTextEditor} from "./text_dom.js";
import { editTextEvent } from "./text_edit.js";
// Kryon web runtime for k2js-generated ESM.
import { Instance_InstanceExpired } from "./instance.js";
@@ -412,6 +412,7 @@ export function widget(rt, name, args, state = null, meta = null) {
const result = handleWidget(rt, name, args, state);
if ((name === "TextField" || name === "TextArea") && state) {
const props = parseTextInputProps(args, state, name === "TextArea");
props.disabled = isTruthyProp(args, "disabled") || !!state[propIdent(args, "disabled")] || rt.disabledStack.some(Boolean);
if (props.textKey && props.cursorKey)
registerTextEditor(item, {rt, state, props});
}
@@ -488,10 +489,24 @@ export function expr(text) {
/* Byte-aware value index shared with generated KSS/strict code: string bases
* yield byte numbers, array bases index normally. */
export function index(base, index) {
return typeof base === "string" ? base.charCodeAt(index) : base[index];
const stringEncoder = new TextEncoder();
const stringDecoder = new TextDecoder();
let indexedString = null;
let indexedBytes = null;
function utf8StringBytes(value) {
if (value !== indexedString) {
indexedString = value;
indexedBytes = stringEncoder.encode(value);
}
return indexedBytes;
}
export function index(base, index) {
return typeof base === "string" ? utf8StringBytes(base)[index] : base[index];
}
export function struct(type, value) {
return { type, value };
}
@@ -1132,7 +1147,7 @@ function parseTextInputProps(args, state, multiline) {
cursorKey: propRef(args, "cursor_position"),
focusID: propNumber(args, "focus_id", 0),
maxCodepoints: propNumber(args, "max_codepoints", 4095),
secure: isTruthyProp(args, "secure"),
secure: isTruthyProp(args, "secure") || !!state?.[propIdent(args, "secure")],
readOnly: isTruthyProp(args, "read_only") || !!state?.[propIdent(args, "read_only")],
multiline,
textSize: propNumber(args, "text_size", 2147483647) || 2147483647,
@@ -5971,7 +5986,7 @@ function bindNodeEvents(el) {
const rt = el.__kryRuntime;
if (!docNode)
return;
if (rt?.QueueTap) {
if (rt?.QueueTap && !hasTextEditor(docNode)) {
const x = docNode.bounds.x + Math.max(1, docNode.bounds.width) * 0.5;
const y = docNode.bounds.y + Math.max(1, docNode.bounds.height) * 0.5;
rt.QueueTap(x, y);
@@ -8372,6 +8387,7 @@ function syncWebFieldsetLegend(el, docNode) {
function applyWebNode(el, docNode, rt) {
el.__kryDocNode = docNode;
refreshTextEditor(el);
el.__kryRuntime = rt;
bindWebDOMObjectProperties(el);
bindNodeEvents(el);
@@ -9381,6 +9397,9 @@ export function renderWebDocument(rt, target) {
dispatchWebDOMLifecycle(root, existed ? "kry-update" : "kry-mount", frame,
makeWebDOMObject(root, docNode, el, ref));
}
for (const [identity, element] of children) {
if (live.has(identity)) presentTextEditor(element);
}
const stale = Array.from(children.entries()).filter(([identity]) => !live.has(identity));
for (const [, el] of stale) {
dispatchWebDOMLifecycle(root, "kry-unmount", frame,
+245
View File
@@ -0,0 +1,245 @@
// Browser transport for the shared editor. DOM selection offsets are UTF-16;
// application cursor and selection offsets are UTF-8 bytes.
import {editTextEvent, textBytes} from "./text_edit.js";
import * as policy from "./text_input.js";
const editors = new WeakMap();
export function registerTextEditor(item, editor) {
editors.set(item, editor);
}
export function hasTextEditor(node) {
return editors.has(node);
}
export function connectTextEditor(item, node) {
const editor = editors.get(item);
if (editor) {
editors.set(node, editor);
node.value = String(editor.state[editor.props.textKey] || "");
node.text = node.value;
node.readOnly = editor.props.readOnly;
node.state.disabled ||= editor.props.disabled;
}
}
export function presentTextEditor(el) {
const editor = editorFor(el);
if (!editor || !editor.props.focusID || el.__kryTextComposing) {
return;
}
if (editor.rt.Focus() === editor.props.focusID && !editor.props.disabled) {
if (document.activeElement !== el) {
el.focus();
}
showText(el, editor);
} else if (document.activeElement === el) {
el.blur();
}
}
export function refreshTextEditor(el) {
el.__kryRefreshTextEditor?.();
}
function utf16At(text, bytes) {
let used = 0;
let index = 0;
for (const character of text) {
if (used + textBytes(character) > bytes) {
break;
}
used += textBytes(character);
index += character.length;
}
return index;
}
function editorFor(el) {
return editors.get(el.__kryDocNode);
}
function syncSelection(el, editor) {
const text = String(editor.state[editor.props.textKey] || "");
const start = textBytes(text.slice(0, el.selectionStart));
const end = textBytes(text.slice(0, el.selectionEnd));
const backward = el.selectionDirection === "backward";
editor.rt.input.selections.set(editor.props.focusID,
{anchor: backward ? end : start, cursor: backward ? start : end});
editor.state[editor.props.cursorKey] = backward ? start : end;
}
function showText(el, editor) {
const text = String(editor.state[editor.props.textKey] || "");
el.value = text;
const selection = editor.rt.input.selections.get(editor.props.focusID);
const cursor = Number(editor.state[editor.props.cursorKey] || 0);
const anchor = selection?.anchor ?? cursor;
const end = selection?.cursor ?? cursor;
el.setSelectionRange(utf16At(text, Math.min(anchor, end)),
utf16At(text, Math.max(anchor, end)), anchor > end ? "backward" : "forward");
}
function apply(el, editor, event) {
editTextEvent(editor.rt.input, editor.state, editor.props, event);
showText(el, editor);
if (editor.rt.Focus() === 0) {
el.blur();
}
}
export function bindTextEditorEvents(el) {
if (el.__kryTextEvents) {
return;
}
el.__kryTextEvents = true;
let composing = false;
el.__kryTextComposing = false;
let compositionOwner = null;
el.__kryRefreshTextEditor = () => {
const editor = editorFor(el);
if (composing && (!editor || editor.props.readOnly || editor.props.disabled ||
editor.state !== compositionOwner?.state || editor.props.focusID !== compositionOwner?.props.focusID)) {
compositionOwner?.rt.input.preedit.delete(compositionOwner.props.focusID);
composing = false;
el.__kryTextComposing = false;
compositionOwner = null;
if (editor) {
showText(el, editor);
}
}
};
const listen = (name, callback) => el.addEventListener(name, event => {
const editor = editorFor(el);
if (!editor || (editor.props.disabled && name !== "blur")) {
return;
}
callback(event, editor);
}, true);
listen("click", event => event.stopPropagation());
listen("focus", (_event, editor) => {
editor.rt.SetFocus(editor.props.focusID);
});
listen("blur", (_event, editor) => {
if (composing) {
apply(el, editor, {type: "composition", phase: 4, text: "", owner: editor.props.focusID});
}
composing = false;
el.__kryTextComposing = false;
compositionOwner = null;
editor.rt.input.preedit.delete(editor.props.focusID);
if (editor.rt.Focus() === editor.props.focusID) {
editor.rt.SetFocus(0);
}
});
for (const name of ["select", "pointerup", "keyup"]) {
listen(name, (_event, editor) => {
if (!composing) {
syncSelection(el, editor);
}
});
}
listen("compositionstart", (_event, editor) => {
if (editor.props.readOnly) {
return;
}
syncSelection(el, editor);
composing = true;
el.__kryTextComposing = true;
compositionOwner = editor;
});
listen("compositionupdate", (event, editor) => {
if (!composing || (compositionOwner?.state !== editor.state || compositionOwner?.props.focusID !== editor.props.focusID)) {
return;
}
editTextEvent(editor.rt.input, editor.state, editor.props,
{type: "composition", phase: 2, text: event.data || "", owner: editor.props.focusID});
});
listen("compositionend", (event, editor) => {
if (!composing || (compositionOwner?.state !== editor.state || compositionOwner?.props.focusID !== editor.props.focusID)) {
return;
}
composing = false;
el.__kryTextComposing = false;
compositionOwner = null;
apply(el, editor, {type: "composition", phase: event.data ? 3 : 4,
text: event.data || "", owner: editor.props.focusID});
event.stopImmediatePropagation();
});
listen("beforeinput", (event, editor) => {
if (composing || event.isComposing) {
return;
}
// Committed composition is applied by compositionend, once.
if (event.inputType === "insertFromComposition") {
event.preventDefault();
return;
}
syncSelection(el, editor);
let action = null;
if (event.inputType.startsWith("insert")) {
action = {type: "text", text: event.inputType === "insertLineBreak" ||
event.inputType === "insertParagraph" ? "\n" : event.data || ""};
} else if (event.inputType.startsWith("delete")) {
action = {type: event.inputType.includes("Word") ? "shortcut" : "key",
key: event.inputType.endsWith("Backward") ? 259 : 261};
}
if (action) {
event.preventDefault();
event.stopImmediatePropagation();
apply(el, editor, action);
}
});
listen("input", (event, editor) => {
// Native composition owns the provisional DOM value, never committed state.
if (!composing) {
showText(el, editor);
}
event.stopImmediatePropagation();
});
const keys = {ArrowLeft: 263, ArrowRight: 262, ArrowUp: 265, ArrowDown: 264,
PageUp: 266, PageDown: 267, Home: 268, End: 269,
Backspace: 259, Delete: 261, Enter: 257, Escape: 256, a: 65};
listen("keydown", (event, editor) => {
if (composing && event.key !== "Escape") {
return;
}
// The browser resolves visual rows, pointer hit testing and caret scrolling.
// Tab follows the live DOM focus order, including controls outside the editor.
const key = keys[event.key];
if (!key || (event.key === "a" && !event.ctrlKey && !event.metaKey)) {
return;
}
if (!composing) {
syncSelection(el, editor);
}
const navigationKey = policy.TextInput_TextNavigationKeyFor(null, undefined, undefined,
editor.props.multiline, key === 263, key === 262, key === 268, key === 269,
key === 265, key === 264, key === 266, key === 267);
const navigation = policy.TextInput_TextNavigationDecisionFor(null, undefined, undefined,
navigationKey, editor.props.multiline, event.shiftKey, event.ctrlKey || event.metaKey,
editor.props.secure, el.selectionStart !== el.selectionEnd);
if (navigation.vertical_direction || navigation.page_direction || navigation.line_edge) {
return;
}
if (composing && event.key === "Escape") {
composing = false;
el.__kryTextComposing = false;
compositionOwner = null;
}
event.preventDefault();
event.stopImmediatePropagation();
apply(el, editor, {type: event.ctrlKey || event.metaKey ? "shortcut" : "key", key, shift: event.shiftKey});
});
for (const [name, key] of [["copy", 67], ["cut", 88], ["paste", 86]]) {
listen(name, (event, editor) => {
if (composing) {
return;
}
syncSelection(el, editor);
event.preventDefault();
event.stopImmediatePropagation();
if (name === "paste") {
editor.rt.SetClipboardText(event.clipboardData?.getData("text/plain") || "");
}
if (name !== "paste") {
editor.rt.SetClipboardText("");
}
apply(el, editor, {type: "shortcut", key});
if (name !== "paste") {
event.clipboardData?.setData("text/plain", editor.rt.ClipboardText());
}
});
}
}