oficina / sheets Public

Web: an editor opened by typing after Bold, a menu or the formula bar obeys Enter and Escape

#72 web canary, blocking. A pointer click outside the table (a toolbar
button, a menu item, the formula bar) makes Jspreadsheet set its current
sheet to none, and it drives an open editor only for its current sheet.
typestart.js opened the editor itself, so after such a click Enter saved
nothing, Escape cancelled nothing, the arrows did nothing, and the next
click saved what Escape should have discarded. Now whenever the holder has
the keyboard (on focus, on a key, and before opening an editor) the grid's
worksheet is made current again.

Also (WebKit): the library removing the editor on Escape or Enter fires no
focusout there, so the keyboard fell to <body> and a dead key or input
method after Escape did not compose from the first key. Enter, Tab and
Escape on an open editor now hand the keyboard back to the holder.

TestFirstKeystrokeAfterLeavingTheGrid (in make test-browser): after Bold,
after Bold typed at once, after Format > Bold, and after leaving the formula
bar, type and Enter saves the value; type and Escape closes the editor,
puts the keyboard on the holder, and a click away keeps the old value.
Fails without this ("Enter left the editor open", "holds old0").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 4ee9599a50c941fd95794f11ff1967c9fd0762f2 parent 41ebeea
2 files changed, +156 −2
  • internal/sheets/static/typestart.js +19 −2
  • internal/sheets/typestart_leave_browser_test.go +137 −0
diff --git a/internal/sheets/static/typestart.js b/internal/sheets/static/typestart.js
index 5080e2b..00b5dec 100644
--- a/internal/sheets/static/typestart.js
+++ b/internal/sheets/static/typestart.js
@@ -67,10 +67,21 @@
return !e.ctrlKey || e.altKey; /* Ctrl+Alt is AltGr on Windows */
}
+ /* The library drives an open editor (Enter, Escape, the arrows) only for
+ * its "current" sheet, and a click anywhere outside the table (Bold, a
+ * menu, the formula bar) sets that to none. Whenever the holder has the
+ * keyboard, the grid is current again; without this an editor opened by
+ * typing ignored Enter and Escape and was saved by the next click. */
+ function own() {
+ var ws = grid() && grid().worksheet();
+ if (ws && window.jspreadsheet) window.jspreadsheet.current = ws;
+ }
+
function open(sel) {
var td = cellAt(sel);
var ws = grid().worksheet();
if (!td || !ws.openEditor) return null;
+ own();
state.replacing = true;
try { ws.openEditor(td, true); } finally { state.replacing = false; }
return td.querySelector('input, textarea');
@@ -80,8 +91,13 @@
* 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());
+ var ws = g && g.worksheet();
+ /* Enter, Tab or Escape closing an edit: WebKit sends no focusout when
+ * the library removes the editor, so take the keyboard back here too. */
+ if (ws && ws.edition && (e.key === 'Enter' || e.key === 'Tab' || e.key === 'Escape')) claim();
+ if (!g || !idle() || !unclaimed(document.activeElement)) return;
+ if (document.activeElement === holder) own();
+ if (startsText(e)) open(g.selection());
}, true);
/* A composition that landed in the holder after all moves to the cell. */
@@ -128,6 +144,7 @@
var g = grid();
if (!g || !g.mayWrite) return;
surface.appendChild(holder);
+ holder.addEventListener('focus', own);
g.onSelection(claim);
/* Every "back to the grid" (after a menu item, a paste, the formula
* bar) lands on the holder, so the next key composes from the first. */
diff --git a/internal/sheets/typestart_leave_browser_test.go b/internal/sheets/typestart_leave_browser_test.go
new file mode 100644
index 0000000..9463cb0
--- /dev/null
+++ b/internal/sheets/typestart_leave_browser_test.go
@@ -0,0 +1,137 @@
+//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"
+)
+
+// TestFirstKeystrokeAfterLeavingTheGrid: #72's web canary. A pointer click
+// outside the table (Bold, a menu item, the formula bar) makes Jspreadsheet
+// drop the sheet as "current", and an editor opened by typing after it
+// ignored Enter and Escape: Enter saved nothing, Escape cancelled nothing
+// (the next click saved the discarded text), and Bold-then-type at once
+// saved an empty cell when the format's repaint wiped the open editor. For
+// each way of leaving the grid, type and press Enter (the value is saved),
+// and type and press Escape (the cell keeps its old value, and the keyboard
+// is back on the cell's text holder).
+func TestFirstKeystrokeAfterLeavingTheGrid(t *testing.T) {
+ app, cookies := signIn(t)
+ sheet, cells := newSheet(t, app, cookies, "Leaving")
+ for r := 0; r < 14; r++ {
+ postCell(t, app, cookies, cells, fmt.Sprintf(`{"r":%d,"c":0,"raw":"old%d"}`, r, r))
+ }
+ 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, c int) string { return fmt.Sprintf(`td[data-x="%d"][data-y="%d"]`, c, r) }
+ 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]{
+ command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: kind, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk, Text: text, UnmodifiedText: text}),
+ command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyUp, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk}),
+ }
+ }
+ 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)
+ }
+ }
+ raw := func(r int) string {
+ read := decodeGrid(t, do(t, app, as(httptest.NewRequest(http.MethodGet, cells+"?rows=16&cols=2", nil), cookies)))
+ for _, c := range read.Cells {
+ if c.R == r && c.C == 0 {
+ return c.Raw
+ }
+ }
+ return ""
+ }
+ saved := func(what string, r int, want string) {
+ t.Helper()
+ deadline := time.Now().Add(4 * time.Second)
+ for raw(r) != want {
+ if time.Now().After(deadline) {
+ t.Fatalf("%s: row %d holds %q, want %q", what, r+1, raw(r), want)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ }
+ state := func() (editorOpen bool, holder bool) {
+ var got struct{ Editor, Holder bool }
+ run("read state", evalInto(&got, `({Editor: !!document.querySelector('td.editor'), Holder: !!(document.activeElement && document.activeElement.hasAttribute('data-type-holder'))})`))
+ return got.Editor, got.Holder
+ }
+ menu := func(cmd string) chromedp.Action[chromedp.Void] {
+ return evalInto((*any)(nil), fmt.Sprintf(`(() => {
+ const s = document.querySelector('details[estilo-menubar-menu]:has(button[estilo-menu-item][data-cmd=%q]) > summary');
+ s.click();
+ return null;
+ })()`, cmd))
+ }
+ pointerClick := func(sel string) chromedp.Action[chromedp.Void] { return chromedp.Click(chromedp.CSS(sel)) }
+
+ ways := []struct {
+ name string
+ leave []chromedp.Action[chromedp.Void]
+ pause time.Duration
+ }{
+ {"Bold on the toolbar", []chromedp.Action[chromedp.Void]{pointerClick(`button[data-tool][data-cmd="bold"]`)}, 250 * time.Millisecond},
+ // Typing at once, inside the format's round trip: its repaint must
+ // not wipe the editor the key opened.
+ {"Bold on the toolbar, then typing at once", []chromedp.Action[chromedp.Void]{pointerClick(`button[data-tool][data-cmd="italic"]`)}, 0},
+ {"Format › Bold", []chromedp.Action[chromedp.Void]{menu("bold"), chromedp.Sleep(150 * time.Millisecond),
+ pointerClick(`details[estilo-menubar-menu][open] button[estilo-menu-item][data-cmd="bold"]`)}, 250 * time.Millisecond},
+ {"leaving the formula bar with Escape", append([]chromedp.Action[chromedp.Void]{pointerClick(`[data-formula-input]`)},
+ press("Escape", "Escape", 27, "")...), 250 * time.Millisecond},
+ }
+ run("open the sheet", chromedp.Navigate(fmt.Sprintf("%s/sheets/%d", rig.Origin, sheet.ID)),
+ chromedp.WaitVisible(chromedp.CSS(cell(13, 0))), chromedp.Sleep(200*time.Millisecond))
+ for i, way := range ways {
+ enter, escape := 2*i, 2*i+1
+ // Enter saves what was typed.
+ run(way.name+": select", pointerClick(cell(enter, 0)), chromedp.Sleep(150*time.Millisecond))
+ run(way.name+": leave", append(way.leave, chromedp.Sleep(way.pause))...)
+ run(way.name+": type, Enter", append(append(press("q", "KeyQ", 81, "q"), chromedp.Sleep(100*time.Millisecond)),
+ append(press("Enter", "Enter", 13, "\r"), chromedp.Sleep(300*time.Millisecond))...)...)
+ if open, _ := state(); open {
+ t.Errorf("%s: Enter left the editor open", way.name)
+ }
+ saved(way.name+", Enter", enter, "q")
+
+ // Escape cancels, and a click away saves nothing.
+ run(way.name+": select", pointerClick(cell(escape, 0)), chromedp.Sleep(150*time.Millisecond))
+ run(way.name+": leave", append(way.leave, chromedp.Sleep(way.pause))...)
+ run(way.name+": type, Escape", append(append(press("q", "KeyQ", 81, "q"), chromedp.Sleep(100*time.Millisecond)),
+ append(press("Escape", "Escape", 27, ""), chromedp.Sleep(200*time.Millisecond))...)...)
+ open, holder := state()
+ if open {
+ t.Errorf("%s: Escape left the editor open", way.name)
+ }
+ if !holder {
+ t.Errorf("%s: after Escape the keyboard is not back on the cell's holder", way.name)
+ }
+ run(way.name+": click away", pointerClick(cell(15, 1)), chromedp.Sleep(300*time.Millisecond))
+ if got := raw(escape); got != fmt.Sprintf("old%d", escape) {
+ t.Errorf("%s: Escape then a click away saved %q over old%d", way.name, got, escape)
+ }
+ }
+}