From 36efd836baca28be6f2e003d30e8f0224a4482b5 Mon Sep 17 00:00:00 2001 From: webdevbyjasmine Date: Tue, 17 Nov 2026 14:14:08 +0800 Subject: [PATCH] Add a Format JS button to the interview editor Candidates who move code around while thinking out loud end up with indentation that no longer shows the structure, and the editor had no way to tidy it. Format JS, and Shift+Alt+F in the editor, reformat the whole JavaScript buffer with Prettier 3.10.1, vendored and pinned like pdf.js and imported on the first press, so the code never leaves the browser and a candidate who never formats downloads nothing. The issue asked for a shortcut alone, off by default; a chord can be taken by the system or an input method before the page sees it, so the button leads, and since each press is one explicit format, never on save or before a run, there is no setting to opt into. Nothing changes until a candidate presses it, and Python, C, C++ and Java are untouched: the button is disabled there and the chord passes through, though on a Mac's JavaScript tab Option+Shift+F now formats instead of typing a letter. A format is one edit in the page history and takes the same input path as typing, so one undo takes it back and highlighting, line numbers, code_update and the test runner all see it; code that does not parse is left as it was, with the reason and position shown above the editor. Close #485 Change-Id: I220d38de889beb6d8a6bcb0c06018e6627522248 --- .gitignore | 4 + THIRD-PARTY-NOTICES.md | 6 +- tests/browser/editor-format.test.js | 249 ++++++++ tests/browser/format-shortcut.test.js | 769 +++++++++++++++++++++++++ web/editor.js | 26 + web/format.js | 66 +++ web/interview.html | 20 + web/interview.js | 105 +++- web/styles.css | 27 + web/vendor/prettier-plugins/FETCH | 4 + web/vendor/prettier-plugins/SHA256SUMS | 2 + web/vendor/prettier/FETCH | 5 + web/vendor/prettier/LICENSE | 7 + web/vendor/prettier/README.md | 27 + web/vendor/prettier/SHA256SUMS | 2 + web/workspace.js | 15 +- 16 files changed, 1327 insertions(+), 7 deletions(-) create mode 100644 tests/browser/editor-format.test.js create mode 100644 tests/browser/format-shortcut.test.js create mode 100644 web/format.js create mode 100644 web/vendor/prettier-plugins/FETCH create mode 100644 web/vendor/prettier-plugins/SHA256SUMS create mode 100644 web/vendor/prettier/FETCH create mode 100644 web/vendor/prettier/LICENSE create mode 100644 web/vendor/prettier/README.md create mode 100644 web/vendor/prettier/SHA256SUMS diff --git a/.gitignore b/.gitignore index 9b388af1d..e13788056 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,10 @@ web/vendor/tree-sitter-*/*.wasm # And pdf.js, pinned in web/vendor/pdfjs/SHA256SUMS: 1.7 MB of minified API # and worker, the same argument at a smaller size. web/vendor/pdfjs/*.mjs +# And Prettier, which formats JavaScript in the editor on request. +web/vendor/prettier/*.mjs +web/vendor/prettier/THIRD-PARTY-NOTICES.md +web/vendor/prettier-plugins/*.mjs # And the temp file a download in progress writes, which carries none of those # suffixes: a run killed outright leaves one, and it is the same megabytes. web/vendor/*/.*.part diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index c402ed862..f09877d3f 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -18,8 +18,9 @@ pinned files with `make verify-vendor`. | [Tree-sitter Python](https://github.com/tree-sitter/tree-sitter-python) | 0.25.0 | MIT | Python grammar | | [Three.js](https://threejs.org/) | 0.185.1 | MIT | Avatar renderer | | [@pixiv/three-vrm](https://github.com/pixiv/three-vrm) | 3.5.5 | MIT | VRM support | +| [Prettier](https://github.com/prettier/prettier) | 3.10.1 | MIT | Editor's Format JS, `standalone.mjs` with the estree and acorn plugins | -The MediaPipe binaries, the Pyodide binaries, pdf.js and Tree-sitter are fetched at build time from +The MediaPipe binaries, the Pyodide binaries, pdf.js, Tree-sitter and Prettier are fetched at build time from the version or commit named in their `FETCH` manifests, and accepted only when they match the adjacent `SHA256SUMS`. The LiveKit client and the three-vrm bundle are committed and pinned in place. @@ -34,6 +35,9 @@ License texts and source details are shipped with the relevant assets: - `web/vendor/avatar/README.md` - `web/vendor/pyodide/README.md` - `web/vendor/pdfjs/README.md` +- `web/vendor/prettier/LICENSE`, `web/vendor/prettier/THIRD-PARTY-NOTICES.md` + (Prettier and what its bundles include, such as acorn and acorn-jsx) and + `web/vendor/prettier/README.md` The build also patches two Rust crates, kept in source form with their licenses: diff --git a/tests/browser/editor-format.test.js b/tests/browser/editor-format.test.js new file mode 100644 index 000000000..9c1a2176e --- /dev/null +++ b/tests/browser/editor-format.test.js @@ -0,0 +1,249 @@ +// Run with: node --test tests/browser/editor-format.test.js +// +// The parts of Shift+Alt+F formatting that need no page: what the formatter +// answers for a buffer and which keystrokes are the chord. +// format-shortcut.test.js drives the same code, through the Format JS button +// and the chord, in a browser. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import vm from "node:vm"; + +import { createJavaScriptFormatter } from "../../web/format.js"; +import { isFormatKeystroke, shortcutKey } from "../../web/editor.js"; + +const FOUR = " "; +const format = createJavaScriptFormatter(); + +async function formatted(code, caret = 0, indent = FOUR) { + const result = await format(code, caret, indent); + assert.equal(result.ok, true, result.message); + return result; +} + +// Before and after, byte for byte, under the default four-space indentation. +// Each "after" is Prettier 3.10.1's answer; a version bump that moves one is +// a change the pull request has to show. +const FIXTURES = [ + { + name: "a one-line function", + before: "function add(a,b){return a+b}", + after: "function add(a, b) {\n return a + b;\n}\n", + }, + { + name: "comments, line and block, kept where they were", + before: + "// head\nfunction f(x){ /* inner */ return x // tail\n}\n/* end */\n", + after: + "// head\nfunction f(x) {\n /* inner */ return x; // tail\n}\n/* end */\n", + }, + { + name: "a template literal's text untouched, its expressions spaced", + before: "const s=`a b\n c ${ 1+2 }`\n", + after: "const s = `a b\n c ${1 + 2}`;\n", + }, + { + name: "a directive stays first and keeps its quotes", + before: "'use strict'\nlet x=1\n", + after: '"use strict";\nlet x = 1;\n', + }, + { + name: "a long line broken at eighty columns", + before: + "const total = values.map((value) => value * factor).filter((value) => value > threshold).reduce((a, b) => a + b, 0);\n", + after: + "const total = values\n .map((value) => value * factor)\n .filter((value) => value > threshold)\n .reduce((a, b) => a + b, 0);\n", + }, + // Automatic semicolon insertion does not apply before a line that opens + // with "[", so these two lines are one expression. Prettier prints the + // expression the parser saw, which shows the hazard rather than hiding it. + { + name: "a missing semicolon before '[' printed as the one expression it is", + before: "let a = 1\n[1,2].forEach(x=>x)\n", + after: "let a = (1)[(1, 2)].forEach((x) => x);\n", + }, +]; + +for (const { name, before, after } of FIXTURES) { + test(`formats ${name}`, async () => { + assert.equal((await formatted(before)).value, after); + }); + + test(`formatting ${name} a second time changes nothing`, async () => { + assert.equal((await formatted(after)).value, after); + }); +} + +test("an empty or blank buffer formats to empty, with the caret kept in range", async () => { + assert.deepEqual(await format("", 0, FOUR), { + ok: true, + value: "", + cursor: 0, + }); + assert.deepEqual(await format(" \n\n ", 4, FOUR), { + ok: true, + value: "", + cursor: 0, + }); +}); + +test("the caret stays on the token it was on", async () => { + const code = "function f(a,b){return a+b}"; + const caret = code.indexOf("return") + 2; + const { value, cursor } = await formatted(code, caret); + assert.equal(value.slice(cursor - 2, cursor + 4), "return"); +}); + +test("the lobby's indentation is the formatter's", async () => { + const code = "if(a){b()}"; + assert.equal((await formatted(code, 0, " ")).value, "if (a) {\n b();\n}\n"); + assert.equal( + (await formatted(code, 0, FOUR)).value, + "if (a) {\n b();\n}\n", + ); + assert.equal((await formatted(code, 0, "\t")).value, "if (a) {\n\tb();\n}\n"); +}); + +// A formatter that guessed at incomplete code would hand the candidate a +// program they did not write. Acorn refuses it, and the refusal names where. +for (const [code, message] of [ + ["function f(", "Unexpected token at line 1, column 12"], + ["let x = ;", "Unexpected token at line 1, column 9"], + ["if (a) {\n b()\n", "Unexpected token at line 3, column 1"], + ["const s = `open", "Unterminated template at line 1, column 12"], + ["a + b = 1", "Assigning to rvalue at line 1, column 1"], +]) { + test(`incomplete code is refused, not repaired: ${JSON.stringify(code)}`, async () => { + assert.deepEqual(await format(code, 0, FOUR), { ok: false, message }); + }); +} + +// The known exceptions to "only what the runner runs": Prettier's acorn +// parser carries JSX and allows a top-level return. Each is formatted, and +// stays as unrunnable after as it was before, so nothing invalid becomes valid. +test("JSX and a top-level return are formatted rather than refused", async () => { + assert.equal( + (await formatted("const a=
")).value, + "const a =
;\n", + ); + assert.equal((await formatted("return 1")).value, "return 1;\n"); +}); + +// Parsing is not proof: each program prints the same thing before and after, +// run in a fresh context each time. +for (const program of [ + "let a = [3,1,2]\nlet b = a.sort((x,y)=>x-y)\n;[a.length].forEach(n=>out.push(n))\nout.push(b.join(','))", + "function f(){return (\n1+1)}\nout.push(f())", + "const o={a:1,'b-c':2}; out.push(JSON.stringify(o))", + "let i=0\ni++\n++i\nout.push(i)", + "const t=`x${ [1,2].map(n=>n*2) }y`;out.push(t)", + "label: for(const x of [1,2,3]){ if(x===2) continue label; out.push(x) }", +]) { + test(`formatting keeps what a program does: ${JSON.stringify(program.slice(0, 30))}`, async () => { + const run = (code) => { + const out = []; + vm.runInNewContext(code, { out }); + return out; + }; + const after = (await formatted(program)).value; + assert.notEqual(after, program); + assert.deepEqual(run(after), run(program)); + }); +} + +test("a large buffer formats within the budget", async (t) => { + const body = Array.from( + { length: 400 }, + (_, i) => + `function f${i}(a,b){const c=[a,b,${i}].map(x=>x*2).filter(x=>x>1);return c.reduce((s,x)=>s+x,0)}`, + ).join("\n"); + await formatted("let warm=1"); // the import is the first call's cost, not this one's + const started = performance.now(); + const { value } = await formatted(body); + const elapsed = performance.now() - started; + t.diagnostic( + `${body.length} characters, ${value.split("\n").length} lines formatted in ${Math.round(elapsed)} ms`, + ); + // Measured at 245 ms on one machine. The ceiling is twenty times that, so a + // loaded CI shard does not fail it; it catches a formatter that went + // quadratic, not a slow runner. + assert.ok(elapsed < 5000, `${Math.round(elapsed)} ms`); +}); + +test("a formatter that cannot load says so, and the next call loads again", async () => { + let calls = 0; + let online = false; + const flaky = createJavaScriptFormatter((url) => { + calls += 1; + return online + ? import(url.href) + : Promise.reject(new TypeError("Failed to fetch")); + }); + assert.deepEqual(await flaky("let a=1", 0, FOUR), { + ok: false, + message: "The formatter could not be loaded", + }); + online = true; + assert.deepEqual(await flaky("let a=1", 0, FOUR), { + ok: true, + value: "let a = 1;\n", + cursor: 0, + }); + // Three modules each time: the failure was not cached. + assert.equal(calls, 6); +}); + +// A Prettier error with no parser position still says what went wrong. +test("a formatter error without a position is reported as it is", async () => { + const broken = createJavaScriptFormatter(async (url) => + url.pathname.endsWith("standalone.mjs") + ? { + formatWithCursor() { + throw new Error("Comment was not printed\nmore detail"); + }, + } + : {}, + ); + assert.deepEqual(await broken("let a=1", 0, FOUR), { + ok: false, + message: "Comment was not printed", + }); +}); + +const key = (init) => ({ + key: "F", + code: "KeyF", + shiftKey: true, + altKey: true, + ctrlKey: false, + metaKey: false, + isComposing: false, + keyCode: 70, + ...init, +}); + +test("Shift+Alt+F is the chord, on every platform's spelling of it", () => { + assert.equal(isFormatKeystroke(key()), true); + assert.equal(isFormatKeystroke(key({ key: "f" })), true); + // Option+Shift+F on a Mac composes a character; the key's position says F. + assert.equal(isFormatKeystroke(key({ key: "Ï" })), true); +}); + +test("nothing else is the chord", () => { + for (const [why, init] of [ + ["no Shift", { shiftKey: false, key: "f" }], + ["no Alt", { altKey: false }], + ["AltGr, which is Ctrl+Alt on Windows", { ctrlKey: true }], + ["Cmd", { metaKey: true }], + ["another letter", { key: "G", code: "KeyG" }], + ["a composition", { isComposing: true }], + ["an engine that cleared isComposing early", { keyCode: 229 }], + ]) + assert.equal(isFormatKeystroke(key(init)), false, why); +}); + +test("shortcutKey lowercases ASCII, reads a composed character by key position, and keeps named keys", () => { + assert.equal(shortcutKey({ key: "Z", code: "KeyZ" }), "z"); + assert.equal(shortcutKey({ key: "Ω", code: "KeyZ" }), "z"); + assert.equal(shortcutKey({ key: "Enter", code: "Enter" }), "Enter"); +}); diff --git a/tests/browser/format-shortcut.test.js b/tests/browser/format-shortcut.test.js new file mode 100644 index 000000000..a5b215868 --- /dev/null +++ b/tests/browser/format-shortcut.test.js @@ -0,0 +1,769 @@ +// Run with: node --test tests/browser/format-shortcut.test.js +// +// The Format JS button and Shift+Alt+F in a real interview page. What the +// formatter writes is pinned in editor-format.test.js; what can break here is +// the wiring: the button and the chord reaching the formatter in JavaScript +// and no other language, the result landing as one edit that undo takes back +// with the overlay and the gutter in step, and a refusal leaving everything as +// it was. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; + +import { createJavaScriptFormatter } from "../../web/format.js"; +import { + DEFAULT_RUNTIME_CONFIG, + FAKE_SPEECH_CAPTURE, + fakeLiveKit, + launchChromium, + startStaticServer, +} from "./source.js"; + +const PROBLEM = "chargeback-pair-match"; +// A working answer to the problem, written with no formatting at all. +const MESSY = + "function matchDisputedCharge(nums,target){const seen=new Map();for(let i=0;i { + tidy = (await createJavaScriptFormatter()(MESSY, 0, " ")).value; + browser = await launchChromium(); + if (!browser) return; + // Compiled runs on, at an origin nothing answers, so the C, C++ and Java + // tabs are offered without anything leaving the machine. + ({ server, base } = await startStaticServer({ + runtimeConfig: DEFAULT_RUNTIME_CONFIG.replace( + "COMPILER_EXPLORER_ENABLED = false", + "COMPILER_EXPLORER_ENABLED = true", + ).replace( + 'COMPILER_EXPLORER_BASE_URL = ""', + 'COMPILER_EXPLORER_BASE_URL = "https://compiler.invalid"', + ), + })); +}); + +after(async () => { + await browser?.close(); + await new Promise((closed) => (server ? server.close(closed) : closed())); +}); + +/// The interview page with the editor reachable, on the JavaScript tab unless +/// told otherwise. Waits on the placeholder bindEvents sets, because the +/// textarea looks ready before any listener exists. +/// +/// A window listener records whether the last F keydown had its default +/// taken; it runs after the editor's own, so it sees the answer. Requests for +/// the vendored formatter are counted, to show it loads only when asked for. +async function interviewPage(t, { prepare } = {}) { + if (!browser) { + t.skip("playwright chromium unavailable"); + return null; + } + const page = await browser.newPage(); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + const formatterRequests = []; + page.on("request", (request) => { + if (request.url().includes("/vendor/prettier")) + formatterRequests.push(request.url()); + }); + await prepare?.(page); + await openEditor(page); + await page.locator("#language-select").selectOption("javascript"); + return { page, errors, formatterRequests }; +} + +/// Loads the interview page and clears the way to its editor. +async function openEditor(page) { + await page.goto(`${base}/interview.html?problem=${PROBLEM}`, { + waitUntil: "domcontentloaded", + }); + await page.waitForFunction( + () => document.querySelector("#candidate-case-input").placeholder !== "", + ); + await page.evaluate(() => { + document.querySelector("#audio-check").hidden = true; + window.addEventListener("keydown", (event) => { + if (event.code === "KeyF") + globalThis.fDefaultPrevented = event.defaultPrevented; + }); + }); +} + +const formatButton = (page) => + page.getByRole("button", { name: "Format JS", exact: true }); + +/// Replaces the buffer and places the caret. One input event rather than +/// typing, so auto-indent and bracket pairing have no say in the fixture. +const setBuffer = (page, value, start = 0, end = start) => + page.evaluate( + ([value, start, end]) => { + const editor = document.querySelector("#editor"); + editor.value = value; + editor.dispatchEvent(new Event("input", { bubbles: true })); + editor.focus(); + editor.setSelectionRange(start, end); + }, + [value, start, end], + ); + +const buffer = (page) => page.locator("#editor").inputValue(); +const selection = (page) => + page.evaluate(() => { + const editor = document.querySelector("#editor"); + return [editor.selectionStart, editor.selectionEnd]; + }); +const status = (page) => page.locator("#editor-format-status"); +const fDefaultPrevented = (page) => + page.evaluate(() => globalThis.fDefaultPrevented); + +/// Waits until the newest format has answered, then one frame more for the +/// status line, so an absence can be asserted without a fixed sleep. +async function formatSettled(page) { + await page.waitForFunction( + () => !document.querySelector("#editor-format").classList.contains("busy"), + ); + await page.evaluate(() => new Promise(requestAnimationFrame)); +} + +/// Presses the chord and waits for the formatter's answer, which arrives +/// asynchronously and is always announced in the status line. +async function formatNow(page) { + await page.keyboard.press(CHORD); + await page.waitForFunction( + () => document.querySelector("#editor-format-status").textContent !== "", + ); +} + +/// The overlay and the gutter, once the next frame has painted them. The +/// overlay carries one more newline after a trailing one, which highlight.js +/// adds so the last row does not collapse. +async function assertPainted(page, code, message) { + await page.waitForFunction( + (overlay) => + document.querySelector("#editor-highlight code").textContent === overlay, + code.endsWith("\n") ? `${code}\n` : code, + ); + assert.equal( + await page.locator("#editor-lines").textContent(), + code + .split("\n") + .map((_, index) => index + 1) + .join("\n"), + `${message}: line numbers`, + ); +} + +test("the Format JS button formats JavaScript and is off on every other tab", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors, formatterRequests } = ctx; + try { + // The chord is named where it works: on the editor, on this tab only. + assert.equal( + await page.locator("#editor").getAttribute("aria-keyshortcuts"), + "Shift+Alt+F", + ); + assert.match( + await formatButton(page).getAttribute("title"), + /in the editor/, + ); + for (const language of ["python", "c", "cpp", "java"]) { + await page.locator("#language-select").selectOption(language); + assert.equal(await formatButton(page).isDisabled(), true, language); + } + await page.locator("#language-select").selectOption("javascript"); + assert.equal(await formatButton(page).isDisabled(), false); + // Nothing is downloaded until a candidate formats. + assert.deepEqual(formatterRequests, []); + const caret = MESSY.indexOf("new Map") + 2; + await setBuffer(page, MESSY, caret); + await formatButton(page).click(); + await page.waitForFunction( + () => document.querySelector("#editor-format-status").textContent !== "", + ); + assert.equal(await buffer(page), tidy); + await assertPainted(page, tidy, "formatted"); + assert.match(await status(page).textContent(), /^Formatted the code\./); + // The editor has the focus back, with the caret where the formatter put + // it, so typing goes on in the code. + assert.equal( + await page.evaluate(() => document.activeElement?.id), + "editor", + ); + const [start] = await selection(page); + assert.equal(tidy.slice(start - 2, start + 5), "new Map"); + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), MESSY); + await page.keyboard.press("ControlOrMeta+Shift+Z"); + assert.equal(await buffer(page), tidy); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("Shift+Alt+F formats JavaScript as one edit undo takes back, with the overlay and gutter in step", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors } = ctx; + try { + // Inside a token, where the caret has one place to go; at a boundary + // between two, Prettier may keep it with either. + const caret = MESSY.indexOf("new Map") + 2; + await setBuffer(page, MESSY, caret); + await formatNow(page); + assert.equal(await fDefaultPrevented(page), true); + assert.equal(await buffer(page), tidy); + const [start, end] = await selection(page); + assert.equal(start, end); + assert.equal(tidy.slice(start - 2, start + 5), "new Map"); + assert.match(await status(page).textContent(), /^Formatted the code\./); + assert.equal(await status(page).isVisible(), true); + await assertPainted(page, tidy, "formatted"); + // Repeated, so a second round trip is not a different path from the first. + for (let round = 0; round < 3; round += 1) { + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), MESSY, `undo ${round}`); + await assertPainted(page, MESSY, `undo ${round}`); + await page.keyboard.press("ControlOrMeta+Shift+Z"); + assert.equal(await buffer(page), tidy, `redo ${round}`); + await assertPainted(page, tidy, `redo ${round}`); + } + // Formatting what is already formatted is no edit at all. + await page.keyboard.press("ControlOrMeta+Z"); + await page.keyboard.press("ControlOrMeta+Shift+Z"); + await formatNow(page); + assert.equal( + await status(page).textContent(), + "The code is already formatted.", + ); + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("Python, C, C++ and Java keep the chord", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors, formatterRequests } = ctx; + try { + for (const language of ["python", "c", "cpp", "java"]) { + await page.locator("#language-select").selectOption(language); + await setBuffer(page, "x = 1\n"); + await page.keyboard.press(CHORD); + assert.equal(await fDefaultPrevented(page), false, language); + assert.equal(await buffer(page), "x = 1\n", language); + assert.equal( + await page.locator("#editor").getAttribute("aria-keyshortcuts"), + null, + language, + ); + } + assert.deepEqual(formatterRequests, []); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("code that does not parse is left as it was, selection and history included", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors } = ctx; + try { + const earlier = await buffer(page); + const broken = "function f(a,b){return a+\n"; + await setBuffer(page, broken, 3, 9); + await formatNow(page); + assert.equal( + await status(page).textContent(), + "Formatting failed: Unexpected token at line 2, column 1. The code was not changed.", + ); + assert.equal(await status(page).isVisible(), true); + // Between the button and the code, where it is seen without scrolling. + const [note, code] = await Promise.all([ + status(page).boundingBox(), + page.locator(".editor-stack").boundingBox(), + ]); + assert.ok( + note.y + note.height <= code.y + 1, + JSON.stringify({ note, code }), + ); + assert.equal(await buffer(page), broken); + assert.deepEqual(await selection(page), [3, 9]); + // The editor is still the candidate's: typing goes on, and the note stays + // so the editor does not move under the caret. + const message = await status(page).textContent(); + await page.keyboard.press("End"); + await page.keyboard.type("b"); + assert.equal(await status(page).textContent(), message); + // No history entry was added: two undos reach the buffer before the fixture. + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), broken); + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), earlier); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a formatter that cannot load changes nothing, and the next press loads it", async (t) => { + let online = false; + const ctx = await interviewPage(t, { + prepare: (page) => + page.route("**/vendor/prettier/standalone.mjs", (route) => + online ? route.continue() : route.abort(), + ), + }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + await formatNow(page); + assert.equal( + await status(page).textContent(), + "Formatting failed: The formatter could not be loaded. The code was not changed.", + ); + assert.equal(await buffer(page), MESSY); + online = true; + await formatNow(page); + assert.equal(await buffer(page), tidy); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +/// Holds the first formatter module until `release` is called, so a test can +/// act while the formatter is still loading. +function holdFormatter() { + let release; + const held = new Promise((resolve) => (release = resolve)); + return { + release, + prepare: (page) => + page.route("**/vendor/prettier/standalone.mjs", async (route) => { + await held; + await route.continue(); + }), + }; +} + +test("the button shows its press, and keeps that look until the formatter answers", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + // Read where the toolbar's eased colors settle. + const border = () => + formatButton(page).evaluate(async (node) => { + await Promise.all(node.getAnimations().map((a) => a.finished)); + return getComputedStyle(node).borderColor; + }); + await setBuffer(page, MESSY); + const idle = await border(); + const box = await formatButton(page).boundingBox(); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + const pressed = await border(); + assert.notEqual(pressed, idle, "pressed"); + await page.mouse.up(); + // Prettier is still loading, and the button keeps the pressed look. + await page.mouse.move(0, 0); + assert.equal(await border(), pressed, "working"); + hold.release(); + await page.waitForFunction( + () => document.querySelector("#editor-format-status").textContent !== "", + ); + await page.mouse.move(0, 0); + await page.evaluate(() => document.activeElement?.blur()); + assert.equal(await border(), idle, "answered"); + assert.equal(await buffer(page), tidy); + await page.locator("#editor").focus(); + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("an edit made while the formatter loads is kept, and the result dropped", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY, MESSY.length); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await page.keyboard.press(CHORD); + await requested; + await page.keyboard.type("//x"); + hold.release(); + await formatSettled(page); + assert.equal(await buffer(page), `${MESSY}//x`); + assert.equal(await status(page).textContent(), ""); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a tab switch while the formatter loads drops the result", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await page.keyboard.press(CHORD); + await requested; + await page.locator("#language-select").selectOption("python"); + const python = await buffer(page); + hold.release(); + await formatSettled(page); + assert.equal(await buffer(page), python); + await page.locator("#language-select").selectOption("javascript"); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a second press while the formatter loads formats the newer buffer", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY, MESSY.length); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await formatButton(page).click(); + await requested; + // The candidate edits and asks again before the first answer is in. The + // first result no longer fits the buffer; the second press is the one + // that counts. + await page.keyboard.type("let after=1"); + await formatButton(page).click(); + hold.release(); + await formatSettled(page); + const newer = ( + await createJavaScriptFormatter()(`${MESSY}let after=1`, 0, " ") + ).value; + assert.equal(await buffer(page), newer); + assert.match(await status(page).textContent(), /^Formatted the code\./); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a caret moved while the formatter loads is where the caret lands", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY, 0); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await page.keyboard.press(CHORD); + await requested; + // Moved without typing: the buffer is the same, the caret is not. + const moved = MESSY.indexOf("seen.set") + 2; + await page.evaluate( + (at) => document.querySelector("#editor").setSelectionRange(at, at), + moved, + ); + hold.release(); + await formatSettled(page); + assert.equal(await buffer(page), tidy); + const [start, end] = await selection(page); + assert.equal(start, end); + assert.equal(tidy.slice(start - 2, start + 6), "seen.set"); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("an editor locked while the formatter loads keeps its code", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await page.keyboard.press(CHORD); + await requested; + await page.evaluate(() => { + document.querySelector("#editor").readOnly = true; + }); + hold.release(); + await formatSettled(page); + assert.equal(await buffer(page), MESSY); + assert.equal(await status(page).textContent(), ""); + // A locked editor does not take the chord at all. + await page.keyboard.press(CHORD); + assert.equal(await fDefaultPrevented(page), false); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a composition begun while the formatter loads keeps its code", async (t) => { + const hold = holdFormatter(); + const ctx = await interviewPage(t, { prepare: hold.prepare }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY, MESSY.length); + const requested = page.waitForRequest("**/vendor/prettier/standalone.mjs"); + await page.keyboard.press(CHORD); + await requested; + // An input method has opened its candidate window but changed nothing yet. + await page.evaluate(() => + document + .querySelector("#editor") + .dispatchEvent(new CompositionEvent("compositionstart")), + ); + hold.release(); + await formatSettled(page); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a repeated keydown after the formatter answered does not format again", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + await formatNow(page); + const formatted = await status(page).textContent(); + assert.match(formatted, /^Formatted the code\./); + // The key still held: another format would announce that the code is + // already formatted, replacing the message. + const prevented = await page.evaluate(() => { + const event = new KeyboardEvent("keydown", { + key: "F", + code: "KeyF", + shiftKey: true, + altKey: true, + repeat: true, + bubbles: true, + cancelable: true, + }); + document.querySelector("#editor").dispatchEvent(event); + return event.defaultPrevented; + }); + assert.equal(prevented, true); + await formatSettled(page); + assert.equal(await status(page).textContent(), formatted); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("a held chord formats once", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + await page.keyboard.down("Shift"); + await page.keyboard.down("Alt"); + await page.keyboard.down("F"); + // A second down with no up between is how Playwright sends a repeat. + await page.keyboard.down("F"); + assert.equal(await fDefaultPrevented(page), true); + await page.keyboard.up("F"); + await page.keyboard.up("Alt"); + await page.keyboard.up("Shift"); + await page.waitForFunction( + () => document.querySelector("#editor-format-status").textContent !== "", + ); + assert.equal(await buffer(page), tidy); + await page.keyboard.press("ControlOrMeta+Z"); + assert.equal(await buffer(page), MESSY); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +// Option+Shift+F on a Mac arrives as a composed letter, U+00CF. Taken in +// JavaScript, typed as ever anywhere else. +test("the Mac spelling of the chord is the chord", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors } = ctx; + try { + for (const [language, taken] of [ + ["javascript", true], + ["python", false], + ]) { + await page.locator("#language-select").selectOption(language); + await setBuffer(page, "x"); + const prevented = await page.evaluate(() => { + const event = new KeyboardEvent("keydown", { + key: "Ï", + code: "KeyF", + shiftKey: true, + altKey: true, + bubbles: true, + cancelable: true, + }); + document.querySelector("#editor").dispatchEvent(event); + return event.defaultPrevented; + }); + assert.equal(prevented, taken, language); + } + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("typing, Ctrl+/ and the other Alt chords are untouched", async (t) => { + const ctx = await interviewPage(t); + if (!ctx) return; + const { page, errors, formatterRequests } = ctx; + try { + await setBuffer(page, "x", 1); + await page.keyboard.type("fF"); + assert.equal(await buffer(page), "xfF"); + await page.keyboard.press("Alt+F"); + assert.equal(await fDefaultPrevented(page), false); + await page.keyboard.press("Control+Shift+F"); + assert.equal(await fDefaultPrevented(page), false); + assert.equal(await buffer(page), "xfF"); + await page.keyboard.press("Control+/"); + assert.equal(await buffer(page), "// xfF"); + assert.deepEqual(formatterRequests, []); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +test("Run tests runs the formatted buffer", async (t) => { + const ctx = await interviewPage(t, { + // The runner builds its Worker from a Blob whose first part is the code. + prepare: (page) => + page.addInitScript(() => { + const NativeBlob = Blob; + globalThis.__workerSources = []; + globalThis.Blob = class extends NativeBlob { + constructor(parts, options) { + super(parts, options); + if (typeof parts?.[0] === "string") + globalThis.__workerSources.push(parts[0]); + } + }; + }), + }); + if (!ctx) return; + const { page, errors } = ctx; + try { + await setBuffer(page, MESSY); + await formatNow(page); + assert.equal(await buffer(page), tidy); + await page.click("#run-tests"); + await page.waitForFunction( + (tidy) => globalThis.__workerSources.includes(tidy), + tidy, + ); + assert.equal( + await page.evaluate( + (messy) => globalThis.__workerSources.includes(messy), + MESSY, + ), + false, + ); + assert.deepEqual(errors, []); + } finally { + await page.close(); + } +}); + +// The interviewer reads the editor through code_update, so the formatted +// buffer has to reach it the way a typed one does. +test("the formatted buffer reaches the interviewer like any edit", async (t) => { + if (!browser) return t.skip("playwright chromium unavailable"); + const { chromium } = await import("playwright"); + const media = await chromium.launch({ + args: [ + "--use-fake-device-for-media-stream", + "--use-fake-ui-for-media-stream", + FAKE_SPEECH_CAPTURE, + ], + }); + t.after(() => media.close()); + const page = await media.newPage(); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.addInitScript(fakeLiveKit({ startupReady: true })); + await page.route("**/vendor/livekit-client.js", (route) => + route.fulfill({ contentType: "text/javascript", body: "" }), + ); + await page.route("**/api/token", (route) => + route.fulfill({ + contentType: "application/json", + body: JSON.stringify({ + serverUrl: "wss://fake.invalid", + token: "token", + durationMin: 10, + }), + }), + ); + await page.goto(`${base}/interview.html?problem=${PROBLEM}`, { + waitUntil: "domcontentloaded", + }); + await page.waitForFunction( + () => document.querySelector("#candidate-case-input").placeholder !== "", + ); + await page.getByRole("button", { name: "Play test tone" }).click(); + await page.getByRole("button", { name: "I heard it" }).click(); + await page.waitForFunction( + () => !document.querySelector("#audio-check-join").disabled, + ); + await page.click("#audio-check-join"); + await page.waitForFunction(() => + (window.__published || []).some((p) => p.topic === "code_update"), + ); + await page.locator("#language-select").selectOption("javascript"); + await setBuffer(page, MESSY); + await formatNow(page); + await page.waitForFunction( + (tidy) => + (window.__published || []).some( + (p) => + p.topic === "code_update" && + p.payload.language === "javascript" && + p.payload.code === tidy, + ), + tidy, + { timeout: 5000 }, + ); + assert.deepEqual(errors, []); +}); diff --git a/web/editor.js b/web/editor.js index 68c6f2ff3..2e1450473 100644 --- a/web/editor.js +++ b/web/editor.js @@ -382,6 +382,32 @@ export function isToggleCommentKeystroke(event) { ); } +/// The key a shortcut means, lowercased: the character when it is printable +/// ASCII, else the letter of the key's position for a single character an +/// Option or Alt chord composed (Option+Shift+F types U+00CF on a Mac), else the +/// key's name ("Enter", "Tab"). +export function shortcutKey(event) { + if (/^[\x20-\x7e]$/.test(event.key)) return event.key.toLowerCase(); + if (event.key.length === 1) + return event.code?.replace(/^Key/, "").toLowerCase(); + return event.key; +} + +// Shift+Alt+F, the chord VS Code formats with. Ctrl and Meta are refused +// because AltGr reports as Ctrl+Alt on Windows and types a character of its +// own; a composition is the input method's. +export function isFormatKeystroke(event) { + return ( + shortcutKey(event) === "f" && + event.shiftKey && + event.altKey && + !event.ctrlKey && + !event.metaKey && + !event.isComposing && + event.keyCode !== 229 + ); +} + // Comments the lines the selection touches, or uncomments them when every one // that has text already is a comment, so a second press undoes the first and // a block with one commented line in it gains a level rather than losing that diff --git a/web/format.js b/web/format.js new file mode 100644 index 000000000..546b66e1b --- /dev/null +++ b/web/format.js @@ -0,0 +1,66 @@ +// JavaScript formatting for the interview editor's Format JS button. +// Prettier is imported on first use rather than with the page, so a candidate +// who never formats never downloads it. +const MODULES = [ + "./vendor/prettier/standalone.mjs", + "./vendor/prettier-plugins/estree.mjs", + "./vendor/prettier-plugins/acorn.mjs", +].map((path) => new URL(path, import.meta.url)); + +/// A formatter with its own copy of Prettier, loaded on its first call. +/// +/// The returned function formats `code` as one whole buffer and answers rather +/// than throws, so the caller has one shape to handle. `cursor` is where +/// `caret` lands in the formatted text; Prettier maps one offset, so a +/// selection collapses to where its start went. Prettier's other options stay +/// at their defaults, so the output depends only on the code, the indentation +/// the lobby chose and the pinned version. +export function createJavaScriptFormatter(load = (url) => import(url.href)) { + let loading = null; + function loaded() { + loading ??= Promise.all(MODULES.map(load)).then( + ([prettier, estree, acorn]) => ({ prettier, plugins: [estree, acorn] }), + (error) => { + // A dropped connection is not the formatter's last word: the next + // press tries again rather than replaying a cached rejection. + loading = null; + throw error; + }, + ); + return loading; + } + + return async function formatJavaScript(code, caret, indent) { + let formatter; + try { + formatter = await loaded(); + } catch { + return { ok: false, message: "The formatter could not be loaded" }; + } + try { + const { formatted, cursorOffset } = + await formatter.prettier.formatWithCursor(code, { + parser: "acorn", + plugins: formatter.plugins, + cursorOffset: caret, + useTabs: indent === "\t", + tabWidth: indent === "\t" ? 4 : indent.length, + }); + // Prettier answers -1 when there was nothing to map the caret through, + // as for a buffer of only whitespace. + const cursor = + cursorOffset < 0 ? Math.min(caret, formatted.length) : cursorOffset; + return { ok: true, value: formatted, cursor }; + } catch (error) { + // The parser's first line ends in a terse "(8:1)"; the place is said in + // words instead. The code frame after that line repeats the candidate's + // code back to them, so it is left out. + const reason = String(error?.message) + .split("\n")[0] + .replace(/ \(\d+:\d+\)$/, ""); + const start = error?.loc?.start; + const at = start ? ` at line ${start.line}, column ${start.column}` : ""; + return { ok: false, message: `${reason}${at}` }; + } + }; +} diff --git a/web/interview.html b/web/interview.html index 75ec4feb8..38755edcf 100644 --- a/web/interview.html +++ b/web/interview.html @@ -292,6 +292,18 @@

Loading interview...

> + + Loading interview...
+ +

diff --git a/web/interview.js b/web/interview.js index 1b4a8f6f8..40f617a86 100644 --- a/web/interview.js +++ b/web/interview.js @@ -59,6 +59,7 @@ import { INDENT_UNITS, indentFromParams, } from "./editor-options.js"; +import { createJavaScriptFormatter } from "./format.js"; import { attachSplitter } from "./splitter.js"; import { BOARD_WIDTH, @@ -338,6 +339,7 @@ const replayVersion = globalThis.CODETRIAL_REPLAY_VERSION || 1; const params = new URLSearchParams(window.location.search); const editorOptions = editorOptionsFromParams(params); const indentUnit = INDENT_UNITS[indentFromParams(params)]; +const formatJavaScript = createJavaScriptFormatter(); const strict = params.get("selection") === "strict"; // Start this independent request while the problem data is loading. It has to // settle rather than reject: nothing awaits it until init() reaches the sign-in @@ -668,8 +670,10 @@ const nodes = { editorFontLarger: document.querySelector("#editor-font-larger"), editorThemeToggle: document.querySelector("#editor-theme-toggle"), editorWrapToggle: document.querySelector("#editor-wrap-toggle"), + formatButton: document.querySelector("#editor-format"), restoreStarter: document.querySelector("#editor-restore-starter"), restoreStatus: document.querySelector("#editor-restore-status"), + formatStatus: document.querySelector("#editor-format-status"), compileDisclosure: document.querySelector(".compile-disclosure"), run: document.querySelector("#run-tests"), testDrawer: document.querySelector(".test-drawer"), @@ -1071,8 +1075,8 @@ async function init() { // Strict editing waits for readiness: work done while Gemini stays silent // would be untimed. The deadline arms the leave warning. if (strict) { - updateRunAvailability(); if (!whiteboard) nodes.editor.disabled = false; + updateRunAvailability(); } updateBeforeUnloadGuard(); tickTimer(); @@ -1191,6 +1195,7 @@ function announceRestore(message, stillTrue) { // Restoring is one ordinary, undoable edit in the current language. function restoreStarter() { clearRestoreStatus(); + clearFormatStatus(); const starter = problem?.starterCode[state.language]; if ( codingClosed() || @@ -1214,6 +1219,87 @@ function restoreStarter() { "Restored the starter code. Ctrl+Z (Cmd+Z on a Mac) undoes this, including after switching languages."; } +function clearFormatStatus() { + nodes.formatStatus.textContent = ""; +} + +// Written a frame after the clear, as announceRestore is, so the same message +// twice is still announced twice, and only while the buffer is still the one +// the message is about. +function announceFormat(message, code) { + requestAnimationFrame(() => { + if (nodes.editor.value === code) nodes.formatStatus.textContent = message; + }); +} + +function formatAvailable() { + return ( + state.language === "javascript" && + !codingClosed() && + !nodes.editor.disabled && + !nodes.editor.readOnly + ); +} + +/// The Format JS button, and Shift+Alt+F where the keystroke reaches the +/// page. Answers whether formatting applies, so the editor takes the chord +/// only then. +/// +/// Formatting is asynchronous, the first one loading Prettier, and a result is +/// written only over the buffer it was made from: an edit, a tab switch, a +/// composition or the end of coding in the meantime drops it, and a caret +/// moved in the meantime formats again from where the caret is now. So a +/// second press needs no queue: whichever result still fits the buffer lands, +/// and the other is dropped. A failure leaves the buffer, the selection and +/// the history as they were. +function formatCode(repeat = false) { + if (!formatAvailable()) return false; + // A held chord formats once. + if (repeat) return true; + clearFormatStatus(); + nodes.formatButton.classList.add("busy"); + const before = editorSnapshot(nodes.editor); + void formatJavaScript(before.value, before.start, indentUnit).then( + (result) => { + nodes.formatButton.classList.remove("busy"); + const now = editorSnapshot(nodes.editor); + if (!formatAvailable() || editorComposition || now.value !== before.value) + return; + if (now.start !== before.start || now.end !== before.end) { + formatCode(); + return; + } + if (!result.ok) + announceFormat( + `Formatting failed: ${result.message}. The code was not changed.`, + before.value, + ); + else if (result.value === before.value) + announceFormat("The code is already formatted.", before.value); + else { + applyEditorEdit({ + value: result.value, + start: result.cursor, + end: result.cursor, + }); + announceFormat( + `Formatted the code. ${mac ? "Cmd+Z" : "Ctrl+Z"} undoes this.`, + result.value, + ); + } + }, + ); + return true; +} + +// The chord works in the editor, not on the button, so the editor names it, +// and only on the tab where it formats. +function renderFormatShortcut() { + if (state.language === "javascript") + nodes.editor.setAttribute("aria-keyshortcuts", "Shift+Alt+F"); + else nodes.editor.removeAttribute("aria-keyshortcuts"); +} + function bindEvents() { nodes.jimVolumeRange.addEventListener("input", () => jimVolume.setVolume(Number(nodes.jimVolumeRange.value)), @@ -1376,6 +1462,12 @@ function bindEvents() { syncEditorScroll(); writeStored(EDITOR_WRAP_KEY, on ? "1" : "0"); }); + // Back to the editor first, as Restore does: the caret the formatter maps + // is the editor's, and the candidate goes on typing there. + nodes.formatButton.addEventListener("click", () => { + nodes.editor.focus(); + formatCode(); + }); // The CSS media query repaints the editor itself on a system theme change // with no reload, but aria-pressed is JS state and would otherwise go // stale until the next click. Re-applying with the current attribute is a @@ -1453,6 +1545,7 @@ function bindEvents() { }, onEdit: workspaceEdited, indentFor, + formatCode, }, }); nodes.report.addEventListener("click", (event) => { @@ -1464,6 +1557,8 @@ function bindEvents() { if (event.target.closest("#done")) leaveRoom(); if (event.target.closest("#download-report")) void downloadReport(); }); + // The format result stays while the candidate types, so the editor does not + // move under the caret; the next format, tab switch or Restore replaces it. nodes.editor.addEventListener("input", () => { clearRestoreStatus(); }); @@ -3359,6 +3454,7 @@ function setLanguage(language) { flushPendingEditorPublish(); state.codeByLanguage[state.language] = nodes.editor.value; clearRestoreStatus(); + clearFormatStatus(); } const next = editorHistory.select( language, @@ -3371,6 +3467,7 @@ function setLanguage(language) { editorInitialized ? editorSnapshot(nodes.editor) : null, ); state.language = language; + renderFormatShortcut(); nodes.editor.value = next.value; nodes.editor.setSelectionRange(next.start, next.end, next.direction); observedEditor = editorSnapshot(nodes.editor); @@ -4397,6 +4494,12 @@ function updateRunAvailability() { nodes.languageSelect.focus({ preventScroll: true }); nodes.restoreStarter.disabled = restoreOff; if (restoreOff) clearRestoreStatus(); + // Off wherever a press would do nothing: another tab, a locked editor. + const formatOff = !formatAvailable(); + if (formatOff && document.activeElement === nodes.formatButton) + nodes.languageSelect.focus({ preventScroll: true }); + nodes.formatButton.disabled = formatOff; + if (formatOff) clearFormatStatus(); nodes.run.disabled = state.candidateCaseEdit !== null || !editorOptions.execution || diff --git a/web/styles.css b/web/styles.css index efb3c1f68..ed2d1b527 100644 --- a/web/styles.css +++ b/web/styles.css @@ -588,6 +588,15 @@ p { border-color: var(--accent); color: var(--ink); } + +/* Format JS acts rather than toggles, so it shows the press itself, and keeps + that look while the formatter works (.busy); the first time, Prettier is + still loading. A disabled button shows neither. */ +#editor-format:not(:disabled):active, +#editor-format.busy:not(:disabled) { + border-color: var(--accent); + color: var(--ink); +} .history { margin-top: 1rem; padding: 1rem; @@ -1565,6 +1574,24 @@ p { font-size: var(--text-xs); } +/* What Format JS did, between the toolbar and the code. Collapsed rather + than hidden while empty: a live region has to be in the accessibility tree + before its message arrives to announce it. */ +.editor-format-status { + flex: none; + margin: 0; + padding: 0.375rem 0.75rem; + border-bottom: 1px solid var(--hairline); + background: var(--surface); + color: var(--sub); + font-size: var(--text-xs); +} + +.editor-format-status:empty { + padding-block: 0; + border-bottom: 0; +} + .sync-state span { display: inline-block; width: 0.4rem; diff --git a/web/vendor/prettier-plugins/FETCH b/web/vendor/prettier-plugins/FETCH new file mode 100644 index 000000000..5c60e79bc --- /dev/null +++ b/web/vendor/prettier-plugins/FETCH @@ -0,0 +1,4 @@ +# Downloaded by scripts/fetch-vendor.sh; bump this URL with ../prettier/FETCH. +https://cdn.jsdelivr.net/npm/prettier@3.10.1/plugins/ +estree.mjs +acorn.mjs diff --git a/web/vendor/prettier-plugins/SHA256SUMS b/web/vendor/prettier-plugins/SHA256SUMS new file mode 100644 index 000000000..be6bc5d47 --- /dev/null +++ b/web/vendor/prettier-plugins/SHA256SUMS @@ -0,0 +1,2 @@ +312e5ed5503dfa31efd644a00d053acd97dae1305a94c9a443ba98023775af56 estree.mjs +445f9f7de5747a1e8b156aaf2a78a6d25acf9c2613a2a228f20216f4f160341e acorn.mjs diff --git a/web/vendor/prettier/FETCH b/web/vendor/prettier/FETCH new file mode 100644 index 000000000..b6a353a64 --- /dev/null +++ b/web/vendor/prettier/FETCH @@ -0,0 +1,5 @@ +# Downloaded by scripts/fetch-vendor.sh; bump this URL, the plugins' URL in +# ../prettier-plugins/FETCH and both SHA256SUMS together. +https://cdn.jsdelivr.net/npm/prettier@3.10.1/ +standalone.mjs +THIRD-PARTY-NOTICES.md diff --git a/web/vendor/prettier/LICENSE b/web/vendor/prettier/LICENSE new file mode 100644 index 000000000..5767e34d3 --- /dev/null +++ b/web/vendor/prettier/LICENSE @@ -0,0 +1,7 @@ +Copyright © James Long and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/web/vendor/prettier/README.md b/web/vendor/prettier/README.md new file mode 100644 index 000000000..69166e300 --- /dev/null +++ b/web/vendor/prettier/README.md @@ -0,0 +1,27 @@ +# Prettier browser assets + +The interview editor formats JavaScript with Prettier 3.10.1 when the candidate +presses the toolbar's "Format JS" button or Shift+Alt+F. The version is pinned +here on its own: package.json's Prettier formats the repository and moves with +its dependency updates, and this copy changes only when someone bumps it here. + +The standalone formatter is fetched here; the estree printer and the acorn +parser are fetched into the sibling prettier-plugins directory, because each +FETCH names one base URL. Acorn rather than Babel: it parses standard +ECMAScript only, which is what the JavaScript runner executes, it rejects +incomplete code instead of recovering from it, and it is half the size. + +web/format.js imports the three files the first time a candidate formats, so +a candidate who never formats never downloads them. None of them evaluates a +string, so they run under the interview page's Content-Security-Policy as it +is. + +THIRD-PARTY-NOTICES.md is Prettier's own list of what its bundles include, +acorn and acorn-jsx among them; it is fetched and pinned with the modules. + +Run scripts/fetch-vendor.sh to download and scripts/verify-vendor.sh to verify. +The fetched files are ignored by Git. Updating Prettier requires updating both +FETCH URLs, both SHA256SUMS and the LICENSE together, and the version in the +repository's THIRD-PARTY-NOTICES.md. + +Upstream: https://github.com/prettier/prettier diff --git a/web/vendor/prettier/SHA256SUMS b/web/vendor/prettier/SHA256SUMS new file mode 100644 index 000000000..b5def4554 --- /dev/null +++ b/web/vendor/prettier/SHA256SUMS @@ -0,0 +1,2 @@ +6dec74d81fa80479a63d7a171df54fedcb59aaba6821aa516529d4a35f5a6c25 standalone.mjs +1adf328f64b26383979c603da48518620b766bd0c2044b7628640eb7d6b96bdc THIRD-PARTY-NOTICES.md diff --git a/web/workspace.js b/web/workspace.js index 2413c62c5..78427c7cd 100644 --- a/web/workspace.js +++ b/web/workspace.js @@ -10,6 +10,8 @@ import { indentSelection, toggleLineComment, isToggleCommentKeystroke, + isFormatKeystroke, + shortcutKey, insertBracketPair, isBracketOpenerKeystroke, isBracketCloserKeystroke, @@ -268,11 +270,7 @@ function mountControlledWorkspace(nodes, c) { }); } nodes.editor.addEventListener("keydown", (event) => { - const key = /^[\x20-\x7e]$/.test(event.key) - ? event.key.toLowerCase() - : event.key.length === 1 - ? event.code?.replace(/^Key/, "").toLowerCase() - : event.key; + const key = shortcutKey(event); const historyKey = (c.mac ? event.metaKey && !event.ctrlKey @@ -324,6 +322,13 @@ function mountControlledWorkspace(nodes, c) { if (!event.repeat) c.applyEditorEdit(toggled); return; } + if (isFormatKeystroke(event)) { + // Taken only where the formatter answers to it. Anywhere else, in + // another language or a locked editor, a Mac still types the character + // Option+Shift+F makes. + if (c.formatCode?.(event.repeat)) event.preventDefault(); + return; + } if (!indents) return; event.preventDefault(); c.applyEditorEdit(