oficina / docs Public

web: a sheet opened from a keyboard takes focus, and Escape closes it

Review 1 on #181. setSheet read from.detail, but from is the Aa button,
which has no detail, so a sheet opened with Enter or Space never took
focus and Escape (which only closed it from the body) did nothing. Now
the opener alone decides: opened from a keyboard, focus goes to the
sheet's title (tabindex -1), and Escape anywhere closes it unless
something nearer used the key. Focus goes back to Aa.

TestTheSheetFromAKeyboard failed before this (focus stayed on Aa, and
Escape left the sheet open).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 5c72cd7f85974775ad17540a86777790342c487f parent 218c148
3 files changed, +167 −8
  • internal/docs/brand/phone.js +9 −7
  • internal/docs/phone_sheet_browser_test.go +157 −0
  • internal/docs/views/show.html +1 −1
diff --git a/internal/docs/brand/phone.js b/internal/docs/brand/phone.js
index b7ef5ed..0721de4 100644
--- a/internal/docs/brand/phone.js
+++ b/internal/docs/brand/phone.js
@@ -227,12 +227,12 @@
place();
if (open) {
openedFrom = from || null;
- // Opened from a keyboard (Enter or Space on Aa), focus goes into
- // the sheet; a tap leaves it where the tap was.
- if (from && from.detail === 0) {
- var first = sheet && sheet.querySelector("[docs-toolbar] [tabindex='0'], [docs-sheet-close]");
- if (first) first.focus();
- }
+ // from is the Aa a keyboard opened it from (Enter or Space: a
+ // click with no detail): focus goes to the sheet's title, which
+ // names it, and Tab goes on to its controls. A tap leaves focus
+ // where it was.
+ var title = from && sheet && sheet.querySelector("[docs-sheet-title]");
+ if (title) title.focus();
} else if (openedFrom && sheet && sheet.contains(document.activeElement)) {
openedFrom.focus();
}
@@ -248,8 +248,10 @@
sheet.addEventListener("keydown", function (e) {
if (e.key === "Escape" && sheetOpen() && !e.defaultPrevented) { e.preventDefault(); setSheet(false); }
});
+ // Escape anywhere closes it, unless something nearer (a picker's
+ // list, a dialog) has used the key already.
document.addEventListener("keydown", function (e) {
- if (e.key === "Escape" && sheetOpen() && (document.activeElement === document.body || !document.activeElement)) setSheet(false);
+ if (e.key === "Escape" && sheetOpen() && !e.defaultPrevented) setSheet(false);
});
// A swipe down on the grabber or the title closes it.
var head = sheet.querySelector("[docs-sheet-head]");
diff --git a/internal/docs/phone_sheet_browser_test.go b/internal/docs/phone_sheet_browser_test.go
new file mode 100644
index 0000000..fb58bdb
--- /dev/null
+++ b/internal/docs/phone_sheet_browser_test.go
@@ -0,0 +1,157 @@
+//go:build browser
+
+// The phone's Format sheet in the corners Fable's review of P2 found
+// (#181): how it opens and closes from a keyboard and from the document,
+// what it does to the caret and the selection, and the visual viewport's
+// odd shapes. Chromium with a touch screen, 390×844, and the scripted
+// visualViewport of phone_format_browser_test.go.
+//
+// CGO_ENABLED=0 go test -tags browser -run Sheet ./internal/docs/
+package docs_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+
+ "github.com/carlosframework/docs/internal/docs"
+)
+
+// sheetRig is one signed-in phone on one document.
+type sheetRig struct {
+ t *testing.T
+ rig *harness.Rig
+ app *docs.App
+ cookies []*http.Cookie
+ sqid string
+}
+
+const sheetPerson = "sheet@example.com"
+
+// newSheetRig opens a document holding the fragment vector (simple.bin:
+// "First paragraph." and "Second paragraph.") on a phone, at path's
+// query (?novv drops visualViewport).
+func newSheetRig(t *testing.T, vector, query string) *sheetRig {
+ t.Helper()
+ s := &sheetRig{t: t}
+ s.rig = harness.New(t, func(origin string) http.Handler {
+ var err error
+ s.app, err = docs.NewForTestWith(t, docs.Config{Origin: origin})
+ if err != nil {
+ t.Fatalf("NewForTestWith: %v", err)
+ }
+ return s.app.Handler()
+ })
+ s.cookies = signInCookies(t, s.app, sheetPerson)
+ ctx := context.Background()
+ doc, err := s.app.Store().Create(ctx, s.app.TestPerson(t, sheetPerson), "Minutes")
+ if err != nil {
+ t.Fatal(err)
+ }
+ update, err := os.ReadFile("../../fixtures/vectors/fragment/" + vector)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.app.Store().ApplyUpdate(ctx, doc, s.app.TestActorFor(t, doc), update); err != nil {
+ t.Fatal(err)
+ }
+ s.sqid = doc.Sqid
+ var set []chromedp.Action[chromedp.Void]
+ for _, c := range s.cookies {
+ set = append(set, setCookie(s.rig.Origin, c))
+ }
+ s.run("a phone", append(set,
+ command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: fakeViewport}),
+ command(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}),
+ command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 390, Height: 844, DeviceScaleFactor: 2, Mobile: true}),
+ chromedp.Navigate(s.rig.Origin+"/d/"+s.sqid+query), chromedp.WaitVisible(chromedp.CSS(`[contenteditable="true"]`)),
+ chromedp.WaitNotPresent(chromedp.CSS(`[docs-quickbar] [data-docs-command="strong"][disabled]`)),
+ chromedp.Sleep(400*time.Millisecond))...)
+ return s
+}
+
+func (s *sheetRig) run(what string, actions ...chromedp.Action[chromedp.Void]) {
+ s.t.Helper()
+ ctx, cancel := context.WithTimeout(s.rig.Context(), 25*time.Second)
+ defer cancel()
+ if err := chromedp.Do(ctx, actions...); err != nil {
+ s.t.Fatalf("%s: %v", what, err)
+ }
+}
+
+func (s *sheetRig) eval(what, js string, out any) {
+ s.t.Helper()
+ var raw json.RawMessage
+ s.run(what, evalInto(&raw, js))
+ if err := json.Unmarshal(raw, out); err != nil {
+ s.t.Fatalf("%s: %v (%s)", what, err, raw)
+ }
+}
+
+func (s *sheetRig) probe(what string) formatProbe {
+ s.t.Helper()
+ var p formatProbe
+ s.eval(what, formatProbeJS, &p)
+ return p
+}
+
+// settle is long enough for phone.js and the editor to answer a step.
+var settle = chromedp.Sleep(400 * time.Millisecond)
+
+// do runs a script for its effect.
+func do(js string) chromedp.Action[chromedp.Void] {
+ return chromedp.Evaluate[chromedp.Void]("(() => {" + js + "; return true })()")
+}
+
+// post is a collaborator's change: a fragment vector posted to the
+// document's update log, as another tab posts one.
+func (s *sheetRig) post(vector string) {
+ s.t.Helper()
+ update := mustRead(s.t, "../../fixtures/vectors/fragment/"+vector)
+ req := httptest.NewRequest(http.MethodPost, "/d/"+s.sqid+"/updates", bytes.NewReader(update))
+ req.Header.Set("Content-Type", "application/octet-stream")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, c := range s.cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ s.app.Handler().ServeHTTP(rec, req)
+ if rec.Code/100 != 2 {
+ s.t.Fatalf("POST %s: %d %s", vector, rec.Code, rec.Body.String())
+ }
+}
+
+// Review 1: Enter on Aa opens the sheet with focus in it, on its title;
+// Escape closes it, and focus is back on Aa.
+func TestTheSheetFromAKeyboard(t *testing.T) {
+ s := newSheetRig(t, "simple.bin", "")
+ s.run("Enter on Aa", chromedp.Focus(chromedp.CSS(`[docs-aa]`)), chromedp.KeyEvent("\r"), settle)
+ var at struct {
+ Open bool
+ Active string
+ InSheet bool
+ }
+ where := `(() => { const a = document.activeElement; return { Open: document.documentElement.getAttribute('data-docs-sheet') === 'open',
+ Active: a ? a.outerHTML.slice(0, 40) : '', InSheet: !!a && !!a.closest('[docs-inspector]') } })()`
+ s.eval("opened", where, &at)
+ if !at.Open || !at.InSheet {
+ t.Errorf("Enter on Aa: sheet open %v, focus on %q, want it in the sheet", at.Open, at.Active)
+ }
+ s.run("Escape", chromedp.KeyEvent("\u001b"), settle)
+ var back bool
+ s.eval("closed", where, &at)
+ s.eval("on Aa", `document.activeElement === document.querySelector('[docs-aa]')`, &back)
+ if at.Open || !back {
+ t.Errorf("Escape: sheet open %v, focus on %q, want it closed and focus back on Aa", at.Open, at.Active)
+ }
+}
diff --git a/internal/docs/views/show.html b/internal/docs/views/show.html
index 8187321..4794185 100644
--- a/internal/docs/views/show.html
+++ b/internal/docs/views/show.html
@@ -2118,7 +2118,7 @@
at any other width, where the aside is the strip or the inspector. */}}
<div docs-sheet-head>
<span docs-sheet-grab aria-hidden="true"></span>
- <h2 docs-sheet-title>{{.Toolbar.Format}}</h2>
+ <h2 docs-sheet-title tabindex="-1">{{.Toolbar.Format}}</h2>
<button docs-sheet-close type="button" aria-label="{{.Toolbar.Close}}"><svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true" focusable="false"><path d="M5 5l10 10M15 5 5 15" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" fill="none"/></svg></button>
</div>
<div docs-toolbar role="toolbar" aria-orientation="horizontal" aria-label="{{.Toolbar.Label}}">