oficina / sheets Public

Sheets web: typing on a selected cell types its first key, composed or not

Two causes. grid.js filled the in-cell editor with the cell's formula a
frame after it opened; opened by typing, that overwrote the typed key with
the old contents and selected them, so the next key replaced everything.
And with no focused text control a dead key was ignored and an input
method never engaged, so the first key of "ka" arrived as a bare k.

typestart.js keeps a text field with no on-screen keyboard
(inputmode=none) focused on the selected cell, and on the keydown that
starts text (a printable key, Option/AltGr characters, Dead, Process) opens
the cell's editor in replace mode before the browser places the text or
composition, which the editor then receives. grid.js skips its formula fill
for that edit; F2 and double-click still show the formula. The clipboard
and shortcut handlers treat the holder as the grid, not a text field.

TestFirstKeystrokeTypesInABrowser (in make test-browser) types a plain key,
a dead key and an input-method composition as Chromium receives them from
the OS; without the grid.js change it reads "old A1" where x was typed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 89bd9c4900313d427f9c549a1537e2dfbd3fa7a5 parent d3cc31a
8 files changed, +324 −10
  • Makefile +5 −2
  • internal/sheets/static/clipboard.js +3 −2
  • internal/sheets/static/commands.js +1 −1
  • internal/sheets/static/grid.js +5 −5
  • internal/sheets/static/sheets.css +18 −0
  • internal/sheets/static/typestart.js +132 −0
  • internal/sheets/templates/sheet.html +1 −0
  • internal/sheets/typestart_browser_test.go +159 −0
diff --git a/Makefile b/Makefile
index bfb122e..f0b5579 100644
--- a/Makefile
+++ b/Makefile
@@ -141,7 +141,7 @@ test-race:
# only; on a Mac set RASTRILLO_CHROME to Playwright's or Chrome's binary).
# Deliberately NOT part of `test`: the gate CI runs on every push must
# not need a browser. Run it before shipping a change to the CSS or to
-# rastrillo's pin. The filter runs five tests: OnTap matches both
+# rastrillo's pin. The filter runs six tests: OnTap matches both
# TestNoZoomOnTap (the iOS zoom-on-tap check) and TestFormatMenuFitsOnTap;
# TestDocumentStylesSurviveTheProductionCSP and TestSmartDoorInABrowser
# are served through rastrillo's production stack, so they see the real
@@ -149,5 +149,8 @@ test-race:
# measure whichever scheme the browser starts in.
# TestEveryScreenKeepsTheRhythm is Fiesta's rhythm audit over every
# screen but the grid's own surface, at 1280 and 390px.
+# TestFirstKeystrokeTypesInABrowser types into the grid as the OS
+# delivers keys: a plain key, a dead key and an input method's
+# composition each start a cell edit from the first key.
test-browser:
- CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|DocumentStyles|SmartDoorInABrowser|KeepsTheRhythm' ./internal/sheets/
+ CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|DocumentStyles|SmartDoorInABrowser|KeepsTheRhythm|FirstKeystroke' ./internal/sheets/
diff --git a/internal/sheets/static/clipboard.js b/internal/sheets/static/clipboard.js
index c680b10..e670006 100644
--- a/internal/sheets/static/clipboard.js
+++ b/internal/sheets/static/clipboard.js
@@ -121,9 +121,10 @@
}).then(function () { if (move) move.busy = false; });
}
+ // typestart.js's holder is the grid's keyboard, not a text field.
function inTextField(el) {
- return !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' ||
- el.isContentEditable);
+ return !!el && !el.hasAttribute('data-type-holder') &&
+ (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);
}
function own(e) {
diff --git a/internal/sheets/static/commands.js b/internal/sheets/static/commands.js
index 1177c5b..d6ad716 100644
--- a/internal/sheets/static/commands.js
+++ b/internal/sheets/static/commands.js
@@ -215,7 +215,7 @@
document.addEventListener('keydown', function (e) {
var t = e.target;
- if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (t && !t.hasAttribute('data-type-holder') && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
/* Delete is deliberately NOT handled here. The vendored grid
* already clears the selection through its own setValue, which
diff --git a/internal/sheets/static/grid.js b/internal/sheets/static/grid.js
index fda8e51..7769f65 100644
--- a/internal/sheets/static/grid.js
+++ b/internal/sheets/static/grid.js
@@ -193,13 +193,13 @@
r2: parseInt(y2, 10), c2: parseInt(x2, 10) };
announce();
},
- /* The in-cell editor should show the formula, not its result.
- * The input does not exist yet when this fires, so it is filled
- * on the next frame — best effort, because the formula bar is
- * the reliable path and this is the convenience. */
+ /* An edit that keeps the cell (Enter, F2, double-click) shows its
+ * formula, not its result, filled on the next frame because the
+ * input does not exist yet. One opened by typing replaces the cell
+ * (typestart.js): filling it would overwrite the typed key. */
oneditionstart: function (instance, td, c, r) {
var text = at(parseInt(r, 10), parseInt(c, 10)).raw;
- if (!text) return;
+ if (!text || (window.SheetsTypeStart && window.SheetsTypeStart.replacing)) return;
requestAnimationFrame(function () {
var input = td.querySelector('input, textarea');
if (input) { input.value = text; input.select(); }
diff --git a/internal/sheets/static/sheets.css b/internal/sheets/static/sheets.css
index 85704b1..e1bb01a 100644
--- a/internal/sheets/static/sheets.css
+++ b/internal/sheets/static/sheets.css
@@ -1340,3 +1340,21 @@
[estilo-google-import] p {
margin: 0;
}
+
+/* typestart.js: the keyboard's place on the selected cell, so a dead key
+ * or an input method composes from the first key. Never seen: the key
+ * that starts typing opens the cell's own editor, which shows the text.
+ * 16px type so a touch screen never zooms for it. */
+[data-type-holder] {
+ position: fixed;
+ inline-size: 1px;
+ block-size: 1px;
+ padding: 0;
+ border: 0;
+ margin: 0;
+ opacity: 0;
+ resize: none;
+ overflow: hidden;
+ pointer-events: none;
+ font-size: 16px;
+}
diff --git a/internal/sheets/static/typestart.js b/internal/sheets/static/typestart.js
new file mode 100644
index 0000000..48fc8e2
--- /dev/null
+++ b/internal/sheets/static/typestart.js
@@ -0,0 +1,132 @@
+/* Typing on a selected cell replaces it, from the first key.
+ *
+ * Paul, 2026-11-26: "the first character typed focusses the cell and
+ * doesn't actually type into it." Two causes, both fixed here:
+ *
+ * - grid.js filled the in-cell editor with the cell's formula a frame
+ * after it opened. Opened by typing, that overwrote the typed key
+ * with the old contents and selected them, so the next key replaced
+ * everything. The fill now happens only for an edit that keeps the
+ * contents (Enter, F2, double-click): `replacing` says which.
+ *
+ * - A browser composes text (´ then e makes é; an input method's かな)
+ * only inside a focused text control, and the grid is not one. The
+ * library ignores a dead key ("Dead"), and with nothing editable
+ * focused an input method never engages, so the first key arrives as a
+ * bare letter and "ka" becomes "kあ". So while a cell is selected a
+ * text field with no on-screen keyboard (inputmode=none) holds focus on
+ * it; the key that starts typing opens the cell's editor in the same
+ * keydown, before the browser places the text or composition, and the
+ * editor receives it. If a browser composes into the holder anyway,
+ * what it composed moves into the editor when the composition ends.
+ */
+(function () {
+ 'use strict';
+
+ var surface = document.querySelector('[data-sheet-surface]');
+ if (!surface || surface.dataset.mayWrite !== '1') return;
+
+ var state = { replacing: false };
+ window.SheetsTypeStart = state;
+
+ var holder = document.createElement('textarea');
+ holder.setAttribute('data-type-holder', '');
+ holder.setAttribute('inputmode', 'none');
+ holder.setAttribute('autocomplete', 'off');
+ holder.setAttribute('autocapitalize', 'off');
+ holder.setAttribute('spellcheck', 'false');
+ holder.setAttribute('aria-label', 'Selected cell');
+ holder.tabIndex = -1;
+
+ function grid() { return window.SheetsGrid; }
+ function idle() {
+ var g = grid();
+ var ws = g && g.worksheet();
+ return !!(ws && !ws.edition && g.selection());
+ }
+ function cellAt(sel) {
+ var ws = grid().worksheet();
+ var row = ws && ws.records && ws.records[sel.r];
+ return row && row[sel.c] ? row[sel.c].element : null;
+ }
+
+ /* Where the keyboard is when nobody else has it: the page itself, the
+ * grid, or the holder. Never the formula bar, a menu or a dialog. */
+ function unclaimed(el) {
+ return !el || el === document.body || el === holder ||
+ (el.closest && el.closest('[data-sheet-grid]') && !el.closest('td.editor'));
+ }
+
+ /* A key that is text, or the start of some: a printable key (Option and
+ * AltGr characters included), a dead key, or an input method's key. */
+ function startsText(e) {
+ if (e.isComposing) return false;
+ if (e.key === 'Dead' || e.key === 'Process' || e.keyCode === 229) return true;
+ if (!e.key || e.key.length !== 1) return false;
+ if (e.metaKey) return false;
+ return !e.ctrlKey || e.altKey; /* Ctrl+Alt is AltGr on Windows */
+ }
+
+ function open(sel) {
+ var td = cellAt(sel);
+ var ws = grid().worksheet();
+ if (!td || !ws.openEditor) return null;
+ state.replacing = true;
+ try { ws.openEditor(td, true); } finally { state.replacing = false; }
+ return td.querySelector('input, textarea');
+ }
+
+ /* Capture phase: ahead of the library's own document handler, which
+ * then finds an edit already open and leaves the key to the editor. */
+ document.addEventListener('keydown', function (e) {
+ var g = grid();
+ if (!g || !idle() || !unclaimed(document.activeElement) || !startsText(e)) return;
+ open(g.selection());
+ }, true);
+
+ /* A composition that landed in the holder after all moves to the cell. */
+ function rescue() {
+ var text = holder.value;
+ holder.value = '';
+ if (!text || !idle()) return;
+ var input = open(grid().selection());
+ if (!input) return;
+ input.value = text;
+ input.setSelectionRange(text.length, text.length);
+ }
+ holder.addEventListener('input', function (e) { if (!e.isComposing) rescue(); });
+ holder.addEventListener('compositionend', function () { setTimeout(rescue, 0); });
+
+ function place(sel) {
+ var td = sel && cellAt(sel);
+ if (!td) return;
+ var box = td.getBoundingClientRect();
+ holder.style.left = Math.round(box.left) + 'px';
+ holder.style.top = Math.round(box.top) + 'px';
+ holder.setAttribute('aria-label', td.textContent ? td.textContent : 'Empty cell');
+ }
+
+ /* After the browser's own focus move for the click that selected. */
+ function claim() {
+ setTimeout(function () {
+ if (!idle() || !unclaimed(document.activeElement)) return;
+ place(grid().selection());
+ holder.focus({ preventScroll: true });
+ }, 0);
+ }
+
+ function ready() {
+ var g = grid();
+ if (!g || !g.mayWrite) return;
+ surface.appendChild(holder);
+ g.onSelection(claim);
+ /* An edit closed (Enter, Tab, Escape, a click away): the page has the
+ * keyboard again, so the holder takes it back. */
+ document.addEventListener('focusout', function (e) {
+ if (e.target && e.target.closest && e.target.closest('td.editor')) claim();
+ });
+ }
+
+ if (window.SheetsGrid) ready();
+ else document.addEventListener('sheets:ready', ready, { once: true });
+}());
diff --git a/internal/sheets/templates/sheet.html b/internal/sheets/templates/sheet.html
index fed9d8d..a84a4a2 100644
--- a/internal/sheets/templates/sheet.html
+++ b/internal/sheets/templates/sheet.html
@@ -14,6 +14,7 @@
<script defer src="{{asset "static/sizes.js"}}"></script>
<script defer src="{{asset "static/autofit.js"}}"></script>
<script defer src="{{asset "static/grid.js"}}"></script>
+<script defer src="{{asset "static/typestart.js"}}"></script>
<script defer src="{{asset "static/menubar.js"}}"></script>
<script defer src="{{asset "static/formulabar.js"}}"></script>
<script defer src="{{asset "static/formulapick.js"}}"></script>
diff --git a/internal/sheets/typestart_browser_test.go b/internal/sheets/typestart_browser_test.go
new file mode 100644
index 0000000..2ef6e1b
--- /dev/null
+++ b/internal/sheets/typestart_browser_test.go
@@ -0,0 +1,159 @@
+//go:build browser
+
+package sheets
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/input"
+ "github.com/chromedp/chromedp"
+)
+
+// TestFirstKeystrokeTypesInABrowser: Paul, 2026-11-26, "the first
+// character typed focusses the cell and doesn't actually type into it."
+// Typing on a selected cell replaces it from the first key (typestart.js),
+// including a dead key (´ then e) and an input method's composition, and
+// F2 or a double-click edits the cell keeping what it holds. Served through the
+// production stack, so the page runs under the real CSP.
+//
+// Keys go in as the browser receives them from the operating system:
+// Input.dispatchKeyEvent for the key, then Input.imeSetComposition and
+// Input.insertText for what the keyboard layout or input method makes of
+// it, in that order, to whatever has focus by then.
+func TestFirstKeystrokeTypesInABrowser(t *testing.T) {
+ app, cookies := signIn(t)
+ sheet, cells := newSheet(t, app, cookies, "Typing")
+ for r, raw := range []string{"old A1", "old A2", "old A3", "old A4", "old A5"} {
+ postCell(t, app, cookies, cells, fmt.Sprintf(`{"r":%d,"c":0,"raw":%q}`, r, raw))
+ }
+ rig := harness.New(t, func(string) http.Handler { return productionHandler(t, app) })
+ var set []chromedp.Action[chromedp.Void]
+ for _, c := range cookies {
+ set = append(set, setCookie(rig.Origin, c))
+ }
+ rig.Run(set...)
+
+ cell := func(r int) string { return fmt.Sprintf(`td[data-x="0"][data-y="%d"]`, r) }
+ editor := func(r int) string { return cell(r) + ` input, ` + cell(r) + ` textarea` }
+ key := func(kind input.DispatchKeyEventType, key, code string, vk int64, text string, mods int64) chromedp.Action[chromedp.Void] {
+ return command(input.DispatchKeyEvent, input.DispatchKeyEventParams{
+ Type: kind, Key: key, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk,
+ Text: text, UnmodifiedText: text, Modifiers: mods,
+ })
+ }
+ press := func(k, code string, vk int64, text string) []chromedp.Action[chromedp.Void] {
+ kind := input.DispatchKeyEventTypeKeyDown
+ if text == "" {
+ kind = input.DispatchKeyEventTypeRawKeyDown
+ }
+ return []chromedp.Action[chromedp.Void]{key(kind, k, code, vk, text, 0), key(input.DispatchKeyEventTypeKeyUp, k, code, vk, "", 0)}
+ }
+ compose := func(text string) chromedp.Action[chromedp.Void] {
+ n := int64(len([]rune(text)))
+ return command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: text, SelectionStart: n, SelectionEnd: n})
+ }
+ commit := func(text string) chromedp.Action[chromedp.Void] {
+ return command(input.InsertText, input.InsertTextParams{Text: text})
+ }
+ // Two frames: grid.js's fill of the editor ran on the next one.
+ settle := chromedp.Sleep(80 * time.Millisecond)
+ run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
+ defer cancel()
+ if err := chromedp.Do(ctx, actions...); err != nil {
+ t.Fatalf("%s: %v", what, err)
+ }
+ }
+ value := func(r int) string {
+ t.Helper()
+ var v string
+ run("read the editor", evalInto(&v, fmt.Sprintf(`(document.querySelector(%q) || {}).value || ''`, editor(r))))
+ return v
+ }
+ saved := func(r int, want string) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ read := decodeGrid(t, do(t, app, as(httptest.NewRequest(http.MethodGet, cells+"?rows=6&cols=2", nil), cookies)))
+ for _, c := range read.Cells {
+ if c.R == r && c.C == 0 && c.Raw == want {
+ return
+ }
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("row %d never saved %q: %+v", r+1, want, read.Cells)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ }
+ selectCell := func(r int) {
+ t.Helper()
+ var holder bool
+ run(fmt.Sprintf("select row %d", r+1),
+ chromedp.Click(chromedp.CSS(cell(r))),
+ chromedp.Sleep(50*time.Millisecond),
+ evalInto(&holder, `document.activeElement && document.activeElement.hasAttribute('data-type-holder')`),
+ )
+ if !holder {
+ t.Fatalf("row %d: a selected cell must hold the keyboard in a text field, or an input method never engages", r+1)
+ }
+ }
+
+ run("open the sheet",
+ chromedp.Navigate(fmt.Sprintf("%s/sheets/%d", rig.Origin, sheet.ID)),
+ chromedp.WaitVisible(chromedp.CSS(cell(4))),
+ chromedp.Sleep(200*time.Millisecond),
+ )
+
+ // A plain key replaces the cell, and stays typed.
+ selectCell(0)
+ run("type x", append(press("x", "KeyX", 88, "x"), settle)...)
+ if got := value(0); got != "x" {
+ t.Fatalf("typing x on a selected cell: the editor holds %q, want %q", got, "x")
+ }
+ run("type y, Enter", append(append(press("y", "KeyY", 89, "y"), press("Enter", "Enter", 13, "\r")...), settle)...)
+ saved(0, "xy")
+
+ // A dead key: ´ (Option-E on a Mac) composes with the next key.
+ selectCell(1)
+ run("dead key", key(input.DispatchKeyEventTypeRawKeyDown, "Dead", "KeyE", 69, "", 1), compose("´"),
+ key(input.DispatchKeyEventTypeKeyUp, "Dead", "KeyE", 69, "", 1), settle)
+ run("e", key(input.DispatchKeyEventTypeRawKeyDown, "e", "KeyE", 69, "", 0), commit("é"),
+ key(input.DispatchKeyEventTypeKeyUp, "e", "KeyE", 69, "", 0), settle)
+ if got := value(1); got != "é" {
+ t.Fatalf("´ then e on a selected cell: the editor holds %q, want é", got)
+ }
+ run("Enter", append(press("Enter", "Enter", 13, "\r"), settle)...)
+ saved(1, "é")
+
+ // An input method: its keys arrive as "Process", and it composes.
+ selectCell(2)
+ run("k", key(input.DispatchKeyEventTypeRawKeyDown, "Process", "KeyK", 229, "", 0), compose("k"), settle)
+ run("a", key(input.DispatchKeyEventTypeRawKeyDown, "Process", "KeyA", 229, "", 0), compose("か"), settle)
+ if got := value(2); got != "か" {
+ t.Fatalf("an input method's composition: the editor holds %q, want か", got)
+ }
+ run("confirm, Enter", commit("か"), settle)
+ run("Enter", append(press("Enter", "Enter", 13, "\r"), settle)...)
+ saved(2, "か")
+
+ // Double-click and F2 keep the cell. (Enter on a selected cell moves
+ // down, as in Excel; that is unchanged.)
+ run("double-click", chromedp.DoubleClick(chromedp.CSS(cell(3))), settle)
+ if got := value(3); got != "old A4" {
+ t.Fatalf("double-click on a cell: the editor holds %q, want its contents", got)
+ }
+ run("Escape", append(press("Escape", "Escape", 27, ""), settle)...)
+ selectCell(4)
+ run("F2", append(press("F2", "F2", 113, ""), settle)...)
+ if got := value(4); got != "old A5" {
+ t.Fatalf("F2 on a selected cell: the editor holds %q, want its contents", got)
+ }
+}