diff --git a/src/lib/editor/readingSearch.ts b/src/lib/editor/readingSearch.ts index 986233c..f1423df 100644 --- a/src/lib/editor/readingSearch.ts +++ b/src/lib/editor/readingSearch.ts @@ -1,10 +1,18 @@ import { SearchQuery } from "@codemirror/search"; import { documentMatches, type FindTarget } from "./findTarget"; +/** Keys that do not change the text of the find field. These keys keep the selected match. */ +const keepsMatch = /^(?:Enter|Escape|Tab|Shift|Control|Alt|Meta|CapsLock|ContextMenu|F\d+)$/; + /** Search the visible reading text without changing its Markdown or rendered nodes. */ export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget { let query = new SearchQuery({ search: "" }); let current = -1; + // The window selection also holds the caret of a focused find field. There it reads as collapsed and outside the text. + function matchSelected() { + const selection = window.getSelection(); + return !!selection && !selection.isCollapsed && root.contains(selection.anchorNode); + } function ranges() { const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const nodes: { node: Text; from: number; to: number }[] = []; @@ -40,7 +48,15 @@ export function readingSearch(root: HTMLElement, close: () => void, options: { i } return { get query() { return query; }, readOnly: true, canSelectAll: false, - setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); }, + setQuery(value) { if (query.eq(value)) return; query = value; current = -1; if (matchSelected()) window.getSelection()?.removeAllRanges(); }, + // A selected match takes the caret from the find field, and the browser then drops typed keys. Put the caret back first. + // The field cannot report its old caret at this time, so the caret goes to the end of the text. + keydown(event) { + const field = event.target; + const copy = (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c"; + if (field instanceof HTMLInputElement && field.type === "text" && !copy && !keepsMatch.test(event.key) && matchSelected()) field.setSelectionRange(field.value.length, field.value.length); + return false; + }, next, selectAll() {}, replace() {}, close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); }, }; diff --git a/tests/smoke/find/typing.smoke.mjs b/tests/smoke/find/typing.smoke.mjs new file mode 100644 index 0000000..3c80e82 --- /dev/null +++ b/tests/smoke/find/typing.smoke.mjs @@ -0,0 +1,81 @@ +// Find takes typed text key by key in Write, Source, Read, and both sides of Split, also after Enter finds a match. +import assert from "node:assert/strict"; +import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs"; + +await runSmoke("find/typing", async ({ page }) => { + const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n"; + await mockTauri(page, { + state: { sample }, + commands: test => { + const workspace = test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": test.state.sample } }); + return { ...workspace, workspace_search: () => [], "plugin:dialog|message": () => "Cancel" }; + }, + }); + const find = page.getByRole("textbox", { name: "Find in document", exact: true }); + const type = text => page.keyboard.type(text, { delay: 15 }); + const focused = () => find.evaluate(node => node === document.activeElement); + const reading = { typed: "Alpha alp", removed: "Alpha aha" }; + + /** + * Open Find, then type, delete, and type again without another click in the field. + * After Enter, CodeMirror selects the text of the field in Write and Source, so the next key replaces it. + * In Read, the caret stays at the end of the text, so the next key adds to it. + */ + async function typing(label, open, afterEnter = { typed: "p", removed: "ha" }) { + await open(); + await page.keyboard.press("Control+f"); + await find.waitFor(); + assert.equal(await focused(), true, `${label}: Find has focus`); + await type("Alpha"); + assert.equal(await find.inputValue(), "Alpha", `${label}: each key reaches the field`); + await page.keyboard.press("Backspace"); + await type("a al"); + assert.equal(await find.inputValue(), "Alpha al", `${label}: Backspace and more keys reach the field`); + assert.equal(await focused(), true, `${label}: Find keeps focus`); + await page.keyboard.press("Enter"); + assert.equal(await focused(), true, `${label}: Enter keeps focus in Find`); + await type("p"); + assert.equal(await find.inputValue(), afterEnter.typed, `${label}: keys after Enter reach the field`); + await page.keyboard.press("Enter"); + await page.keyboard.press("Backspace"); + await page.keyboard.press("Backspace"); + await type("ha"); + assert.equal(await find.inputValue(), afterEnter.removed, `${label}: Backspace after Enter acts on the field`); + await page.keyboard.press("Escape"); + await find.waitFor({ state: "detached" }); + } + + await page.goto(smokeUrl); + await page.getByText("smoke-workspace", { exact: true }).waitFor(); + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md"); + await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click(); + await page.locator(".cm-content").waitFor(); + + await typing("Write", async () => { await page.locator(".cm-content").click(); }); + await typing("Source", async () => { + await chooseView(page, "Source"); + await page.locator(".source-editor .cm-content").click(); + }); + await typing("Read", async () => { + await chooseView(page, "Read"); + await page.locator(".md-page > .reading").focus(); + }, reading); + await chooseView(page, "Source"); + await chooseView(page, "Split"); + await typing("Split, the text side", async () => { await page.locator(".source-editor .cm-content").click(); }); + await typing("Split, the reading side", async () => { await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } }); }, reading); + + // A match stays selected until the search text changes, and the next search finds a match again. + await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } }); + await page.keyboard.press("Control+f"); + await type("Alpha"); + await page.keyboard.press("Enter"); + assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha", "Enter selects the match"); + await type(" a"); + assert.equal(await find.inputValue(), "Alpha a", "A key after Enter adds to the text"); + assert.equal(await page.evaluate(() => window.getSelection().toString()), "", "A new key removes the selected match"); + await page.keyboard.press("Enter"); + assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha a", "Enter selects the match of the longer text"); + await page.keyboard.press("Escape"); +});